From 6ff413078b74f7d6c133cac6bd0c8344c252ec6e Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 13 Sep 2026 19:20:23 +0800 Subject: [PATCH] feat(web): drag-and-drop reorder kanban task cards within a column (#3623) Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com> Co-authored-by: Carlos Florencio --- .../internal/backendapp/boot_state_routes.go | 1 + .../backendapp/boot_state_routes_test.go | 15 + apps/backend/internal/backendapp/helpers.go | 11 +- .../backend/internal/backendapp/httpserver.go | 4 +- apps/backend/internal/backendapp/main.go | 2 +- .../backendapp/persistence_middleware.go | 4 +- apps/backend/internal/events/types.go | 18 +- .../gateway/websocket/task_notifications.go | 1 + .../websocket/task_notifications_test.go | 2 +- .../budget_admission_lost_race_test.go | 6 +- ...subscribers_lost_race_side_effects_test.go | 2 +- .../service/finish_run_error_logging_test.go | 2 +- .../service/retry_cancel_lost_race_test.go | 4 +- .../office/service/retry_cancel_test.go | 2 +- .../retry_stale_terminal_shape_test.go | 2 +- .../service/run_claimed_counter_test.go | 2 +- .../service/scheduler_integration_test.go | 2 +- .../scheduler_lost_race_activity_test.go | 4 +- .../service/scheduler_taskless_launch_test.go | 4 +- .../office/service/session_hop_direct_test.go | 4 +- .../service/session_persist_failure_test.go | 4 +- .../service/terminal_shape_wiring_test.go | 4 +- .../office/service/tree_controls_test.go | 4 +- ...handlers_agent_error_evaluate_only_test.go | 6 +- .../orchestrator/event_handlers_workflow.go | 9 +- .../event_handlers_workflow_test.go | 2 +- .../executor/executor_mocks_test.go | 5 +- .../internal/orchestrator/workflow_store.go | 45 +- .../orchestrator/workflow_store_test.go | 52 +- apps/backend/internal/task/dto/converters.go | 1 + apps/backend/internal/task/dto/dto.go | 18 +- .../task/handlers/process_handlers_test.go | 3 + .../task/handlers/task_detachment_test.go | 4 + .../internal/task/handlers/task_handlers.go | 5 + .../task/handlers/task_http_handlers.go | 60 ++ .../task_http_handlers_external_id_test.go | 4 + .../task/handlers/task_http_handlers_test.go | 4 + .../handlers/task_port_forwarding_test.go | 4 + .../handlers/task_reorder_handlers_test.go | 166 ++++ .../task/handlers/task_ws_authz_test.go | 4 + .../task/handlers/task_ws_handlers_test.go | 4 + .../task/handlers/workflow_handlers_test.go | 22 + .../internal/task/models/step_order.go | 57 ++ .../internal/task/models/step_order_test.go | 89 +++ .../internal/task/repository/interface.go | 12 + .../task/repository/repoerrors/errors.go | 13 + .../internal/task/repository/sqlite/base.go | 40 + .../task/repository/sqlite/base_migrations.go | 4 + .../task/repository/sqlite/base_schema.go | 1 + .../next_queued_task_ordering_pin_test.go | 8 + .../internal/task/repository/sqlite/task.go | 710 +++++++++++++++++- .../task_arrival_position_postgres_test.go | 119 +++ .../task_move_source_lock_postgres_test.go | 205 +++++ .../task_promotion_lock_postgres_test.go | 160 ++++ .../task/repository/sqlite/task_reorder.go | 307 ++++++++ .../sqlite/task_reorder_rigor_test.go | 370 +++++++++ .../repository/sqlite/task_reorder_test.go | 287 +++++++ .../sqlite/task_selection_coverage_test.go | 10 + ...k_step_lock_reattach_race_postgres_test.go | 262 +++++++ ...k_step_lock_retry_release_postgres_test.go | 347 +++++++++ .../task_step_lock_toctou_postgres_test.go | 119 +++ .../task_update_preserves_position_test.go | 121 +++ .../task_visibility_lock_postgres_test.go | 403 ++++++++++ .../sqlite/task_wip_postgres_test.go | 2 +- .../task/repository/sqlite/workspace.go | 46 ++ .../workspace_cascade_lock_postgres_test.go | 123 +++ .../internal/task/repository/task_wip_test.go | 14 +- .../task/service/handoff_workspace_test.go | 4 + apps/backend/internal/task/service/service.go | 33 +- .../internal/task/service/service_access.go | 17 + .../service_bulk_move_concurrency_test.go | 101 +++ .../service_bulk_move_dangling_step_test.go | 34 + .../service_bulk_move_lock_drift_test.go | 205 +++++ .../service_bulk_move_lock_order_test.go | 184 +++++ .../internal/task/service/service_reorder.go | 105 +++ .../task/service/service_reorder_test.go | 335 +++++++++ .../internal/task/service/service_tasks.go | 12 +- .../internal/task/service/service_workflow.go | 333 +++++++- .../service_workflow_feeder_move_test.go | 6 +- .../service/service_workflow_race_test.go | 3 +- .../service/service_workflow_state_test.go | 26 + .../task/service/service_workflow_test.go | 183 ++++- .../internal/workflow/models/models.go | 11 +- .../internal/workflow/repository/sqlite.go | 12 +- .../workflow/repository/sqlite_test.go | 61 ++ .../workflow/stepevents/stepevents.go | 1 + .../workflow/stepevents/stepevents_test.go | 2 + apps/backend/pkg/pluginsdk/data_types.go | 9 +- apps/backend/pkg/websocket/actions.go | 1 + .../proto/kandev/plugin/v1/plugin.pb.go | 7 +- .../proto/kandev/plugin/v1/plugin.proto | 7 +- apps/web/components/kanban-card-actions.tsx | 185 +++++ apps/web/components/kanban-card-content.tsx | 347 ++------- .../components/kanban-card-status-icon.tsx | 122 +++ .../kanban-card.render-stability.test.tsx | 3 + apps/web/components/kanban-card.tsx | 14 + .../kanban-column.render-stability.test.tsx | 102 +++ apps/web/components/kanban-column.tsx | 26 +- .../kanban/graph2-task-pipeline.test.tsx | 46 ++ ...imlane-container.render-stability.test.tsx | 3 + .../kanban/swimlane-graph2-content.tsx | 50 +- .../swimlane-graph2-orphan-display.test.ts | 23 + .../kanban/swimlane-kanban-content.tsx | 248 ++---- .../components/kanban/swipeable-columns.tsx | 14 +- .../virtualized-column-task-list.test.tsx | 238 ++++++ .../kanban/virtualized-column-task-list.tsx | 464 +++++++++--- .../task/task-move-error-message.ts | 21 + .../task/task-title-hover-card.test.tsx | 3 + .../threads/thread-task-actions.test.tsx | 3 + apps/web/e2e/helpers/api-client.ts | 1 + .../e2e/tests/kanban/kanban-reorder.spec.ts | 159 ++++ .../kanban/mobile-kanban-reorder.spec.ts | 111 +++ .../e2e/tests/kanban/swimlane-height.spec.ts | 14 +- .../tests/kanban/task-multi-select.spec.ts | 77 ++ .../kanban/use-all-workflow-snapshots.ts | 1 + .../kanban/use-cross-step-move.test.ts | 78 ++ .../kanban/use-keyboard-reorder.test.ts | 193 +++++ .../domains/kanban/use-keyboard-reorder.ts | 163 ++++ .../kanban/use-shared-kanban-layout-props.ts | 11 +- .../use-step-reorder-reconciliation.test.ts | 461 ++++++++++++ .../domains/kanban/use-step-reorder.test.ts | 390 ++++++++++ .../hooks/domains/kanban/use-step-reorder.ts | 299 ++++++++ .../kanban/use-swimlane-kanban-dnd.test.ts | 132 ++++ .../domains/kanban/use-swimlane-kanban-dnd.ts | 201 +++++ .../hooks/domains/kanban/use-swimlane-move.ts | 1 - .../domains/kanban/use-task-subtasks.test.tsx | 3 + ...se-change-request-provider-target.test.tsx | 3 + apps/web/hooks/use-task-actions.ts | 2 +- apps/web/hooks/use-task-in-flight.test.tsx | 3 + .../use-task-multi-select-bulk-move.test.ts | 106 +++ apps/web/hooks/use-task-multi-select.ts | 93 +-- apps/web/lib/api/domains/kanban-api.test.ts | 87 +++ apps/web/lib/api/domains/kanban-api.ts | 27 +- .../lib/kanban/drop-classification.test.ts | 188 +++++ apps/web/lib/kanban/drop-classification.ts | 94 +++ apps/web/lib/kanban/keyboard-reorder.test.ts | 26 + apps/web/lib/kanban/keyboard-reorder.ts | 27 + apps/web/lib/kanban/reorder-merge.test.ts | 105 +++ apps/web/lib/kanban/reorder-merge.ts | 64 ++ apps/web/lib/kanban/task-order.test.ts | 90 ++- apps/web/lib/kanban/task-order.ts | 72 ++ apps/web/lib/kanban/wip-queue.test.ts | 42 ++ apps/web/lib/kanban/wip-queue.ts | 57 +- .../lib/kanban/workflow-step-order.test.ts | 37 +- apps/web/lib/kanban/workflow-step-order.ts | 28 + .../routing/kanban-route-hydration.test.ts | 11 +- apps/web/lib/ssr/mapper.ts | 1 + .../hydration/hydrator-order-revision.test.ts | 108 +++ apps/web/lib/state/hydration/hydrator.ts | 27 +- .../state/slices/kanban/kanban-slice.test.ts | 24 + .../lib/state/slices/kanban/kanban-slice.ts | 40 +- apps/web/lib/state/slices/kanban/types.ts | 45 ++ apps/web/lib/types/backend.ts | 10 + apps/web/lib/types/http.ts | 35 + .../ws/handlers/agent-session-kanban.test.ts | 9 + .../handlers/kanban-auto-start-failed.test.ts | 132 ++-- .../lib/ws/handlers/kanban-priority.test.ts | 3 + .../kanban-workspace-orphaned.test.ts | 118 ++- apps/web/lib/ws/handlers/kanban.test.ts | 21 + apps/web/lib/ws/handlers/kanban.ts | 178 +++++ .../lib/ws/handlers/task-reordered.test.ts | 227 ++++++ .../ws/handlers/tasks-pending-action.test.ts | 3 + apps/web/lib/ws/handlers/workflows.test.ts | 3 + apps/web/src/locales/en/kanban.json | 1 + apps/web/src/locales/en/task.json | 2 + apps/web/src/locales/pseudo/kanban.json | 1 + apps/web/src/locales/pseudo/task.json | 2 + apps/web/src/locales/pt-pt/kanban.json | 1 + apps/web/src/locales/pt-pt/task.json | 2 + apps/web/src/locales/zh-cn/kanban.json | 1 + apps/web/src/locales/zh-cn/task.json | 2 + apps/web/src/locales/zh-hk/kanban.json | 1 + apps/web/src/locales/zh-hk/task.json | 2 + apps/web/src/locales/zh-tw/kanban.json | 1 + apps/web/src/locales/zh-tw/task.json | 2 + docs/plans/kanban-task-reordering/plan.md | 25 + ...ask-01-implement-kanban-task-reordering.md | 60 ++ docs/public/tasks-and-workflows.md | 2 + .../requirements/kanban-task-reordering.md | 343 +++++++++ .../system-design/kanban-task-reordering.md | 506 +++++++++++++ 180 files changed, 12251 insertions(+), 1099 deletions(-) create mode 100644 apps/backend/internal/task/handlers/task_reorder_handlers_test.go create mode 100644 apps/backend/internal/task/models/step_order.go create mode 100644 apps/backend/internal/task/models/step_order_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_arrival_position_postgres_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_move_source_lock_postgres_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_promotion_lock_postgres_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_reorder.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_reorder_rigor_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_reorder_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_step_lock_reattach_race_postgres_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_step_lock_retry_release_postgres_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_step_lock_toctou_postgres_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_update_preserves_position_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/task_visibility_lock_postgres_test.go create mode 100644 apps/backend/internal/task/repository/sqlite/workspace_cascade_lock_postgres_test.go create mode 100644 apps/backend/internal/task/service/service_bulk_move_concurrency_test.go create mode 100644 apps/backend/internal/task/service/service_bulk_move_dangling_step_test.go create mode 100644 apps/backend/internal/task/service/service_bulk_move_lock_drift_test.go create mode 100644 apps/backend/internal/task/service/service_bulk_move_lock_order_test.go create mode 100644 apps/backend/internal/task/service/service_reorder.go create mode 100644 apps/backend/internal/task/service/service_reorder_test.go create mode 100644 apps/web/components/kanban-card-actions.tsx create mode 100644 apps/web/components/kanban-card-status-icon.tsx create mode 100644 apps/web/components/kanban-column.render-stability.test.tsx create mode 100644 apps/web/components/kanban/virtualized-column-task-list.test.tsx create mode 100644 apps/web/e2e/tests/kanban/kanban-reorder.spec.ts create mode 100644 apps/web/e2e/tests/kanban/mobile-kanban-reorder.spec.ts create mode 100644 apps/web/hooks/domains/kanban/use-cross-step-move.test.ts create mode 100644 apps/web/hooks/domains/kanban/use-keyboard-reorder.test.ts create mode 100644 apps/web/hooks/domains/kanban/use-keyboard-reorder.ts create mode 100644 apps/web/hooks/domains/kanban/use-step-reorder-reconciliation.test.ts create mode 100644 apps/web/hooks/domains/kanban/use-step-reorder.test.ts create mode 100644 apps/web/hooks/domains/kanban/use-step-reorder.ts create mode 100644 apps/web/hooks/domains/kanban/use-swimlane-kanban-dnd.test.ts create mode 100644 apps/web/hooks/domains/kanban/use-swimlane-kanban-dnd.ts create mode 100644 apps/web/hooks/use-task-multi-select-bulk-move.test.ts create mode 100644 apps/web/lib/kanban/drop-classification.test.ts create mode 100644 apps/web/lib/kanban/drop-classification.ts create mode 100644 apps/web/lib/kanban/keyboard-reorder.test.ts create mode 100644 apps/web/lib/kanban/keyboard-reorder.ts create mode 100644 apps/web/lib/kanban/reorder-merge.test.ts create mode 100644 apps/web/lib/kanban/reorder-merge.ts create mode 100644 apps/web/lib/state/hydration/hydrator-order-revision.test.ts create mode 100644 apps/web/lib/ws/handlers/task-reordered.test.ts create mode 100644 docs/plans/kanban-task-reordering/plan.md create mode 100644 docs/plans/kanban-task-reordering/task-01-implement-kanban-task-reordering.md create mode 100644 docs/specs/tasks/requirements/kanban-task-reordering.md create mode 100644 docs/specs/tasks/system-design/kanban-task-reordering.md diff --git a/apps/backend/internal/backendapp/boot_state_routes.go b/apps/backend/internal/backendapp/boot_state_routes.go index 1c9d8ebf84..c089183339 100644 --- a/apps/backend/internal/backendapp/boot_state_routes.go +++ b/apps/backend/internal/backendapp/boot_state_routes.go @@ -754,6 +754,7 @@ func mapKanbanStepState(step taskdto.WorkflowStepDTO) map[string]any { "stage_type": nullString(step.StageType), "wip_limit": step.WIPLimit, "pull_from_step_id": nullString(step.PullFromStepID), + "order_revision": step.OrderRevision, } } diff --git a/apps/backend/internal/backendapp/boot_state_routes_test.go b/apps/backend/internal/backendapp/boot_state_routes_test.go index 41338e3f62..338767a227 100644 --- a/apps/backend/internal/backendapp/boot_state_routes_test.go +++ b/apps/backend/internal/backendapp/boot_state_routes_test.go @@ -52,6 +52,21 @@ func TestMapKanbanStepStateIncludesAutoAdvanceRequiresSignal(t *testing.T) { } } +// TestMapKanbanStepStateIncludesOrderRevision covers the Build-phase fix for +// missing order_revision on HTTP hydration: without this field in the boot +// payload, the frontend has no way to seed kanbanMulti.orderRevisionByStepId +// before the first task.reordered WS event arrives, so that event's revision +// gate accepts whatever arrives first — even a stale reorder. +func TestMapKanbanStepStateIncludesOrderRevision(t *testing.T) { + step := mapKanbanStepState(taskdto.WorkflowStepDTO{ + ID: "step-revisioned", + OrderRevision: 7, + }) + if step["order_revision"] != int64(7) { + t.Fatalf("order_revision = %#v, want 7", step["order_revision"]) + } +} + // TestMapKanbanTaskStateIncludesAutoStartFailed regression-tests Review round // 2's MAJOR finding: mapKanbanTaskState is a camelCase whitelist that omitted // auto_start_failed, so a task whose auto-start already failed rendered with diff --git a/apps/backend/internal/backendapp/helpers.go b/apps/backend/internal/backendapp/helpers.go index 1055d398a6..8c464337ad 100644 --- a/apps/backend/internal/backendapp/helpers.go +++ b/apps/backend/internal/backendapp/helpers.go @@ -119,6 +119,9 @@ const ( serviceFieldKey = "service" kandevName = "kandev" startingStatus = "starting" + healthRoutePath = "/health" + readyRoutePath = "/ready" + websocketRoutePath = "/ws" ) // buildSessionDataProvider constructs the session data provider function used by the WebSocket hub @@ -890,7 +893,7 @@ func registerRoutes(p routeParams) { // but it does not gate on that flag — liveness must not depend on // readiness, or the crash loop docs/specs/startup-listener-before- // recovery/spec.md exists to fix comes back. - p.router.GET("/health", healthHandler(p)) + p.router.GET(healthRoutePath, healthHandler(p)) // /ready is a readiness probe. It returns 200 only after main has // flipped the package-level `ready` flag — which happens after route @@ -901,7 +904,7 @@ func registerRoutes(p routeParams) { // instead of racing ahead and hitting 404s on routes that aren't wired // yet. See docs/specs/health-endpoint-version/spec.md for the exact // contract this endpoint now owns. - p.router.GET("/ready", readyHandler(p)) + p.router.GET(readyRoutePath, readyHandler(p)) // /api/v1/features is a public, unauthenticated read of the runtime // feature-flag map. The frontend SSR-fetches it once per page render to @@ -938,7 +941,7 @@ func registerRoutes(p routeParams) { } else { p.router.NoRoute(func(c *gin.Context) { path := c.Request.URL.Path - if strings.HasPrefix(path, "/api/") || path == "/ws" || path == "/health" || path == "/ready" { + if strings.HasPrefix(path, "/api/") || path == websocketRoutePath || path == healthRoutePath || path == readyRoutePath { c.AbortWithStatus(http.StatusNotFound) return } @@ -1059,7 +1062,7 @@ func webAppHandlerOptions(p routeParams) []webapp.HandlerOption { func webRuntimeConfig(debug bool, titlePrefix string, req *http.Request) webapp.RuntimeConfig { return webapp.RuntimeConfig{ APIPrefix: "/api/v1", - WebSocketPath: "/ws", + WebSocketPath: websocketRoutePath, LSPAutoInstallPreferenceLanguages: lspinstaller.AutoInstallPreferenceLanguages(), Debug: debug, // Gates QA-only UI (the pseudo-locale option). Separate from Debug: the diff --git a/apps/backend/internal/backendapp/httpserver.go b/apps/backend/internal/backendapp/httpserver.go index db1b328935..decdd8ee9d 100644 --- a/apps/backend/internal/backendapp/httpserver.go +++ b/apps/backend/internal/backendapp/httpserver.go @@ -64,13 +64,13 @@ func newBootstrapHandler(version string, reporters ...*startup.Reporter) http.Ha progress = reporters[0] } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet || r.URL.Path != "/health" { + if r.Method != http.MethodGet || r.URL.Path != healthRoutePath { body := map[string]any{ statusKey: startingStatus, serviceFieldKey: kandevName, versionFieldKey: version, } - if r.Method == http.MethodGet && r.URL.Path == "/ready" { + if r.Method == http.MethodGet && r.URL.Path == readyRoutePath { body["startup"] = progress.Snapshot() } writeBootstrapJSON(w, http.StatusServiceUnavailable, body) diff --git a/apps/backend/internal/backendapp/main.go b/apps/backend/internal/backendapp/main.go index fad60487bd..bdc657a52d 100644 --- a/apps/backend/internal/backendapp/main.go +++ b/apps/backend/internal/backendapp/main.go @@ -1230,7 +1230,7 @@ func startGatewayAndServe( } log.Info("API configured", - zap.String("websocket", "/ws"), + zap.String("websocket", websocketRoutePath), zap.String("health", "/health"), zap.String("http", "/api/v1"), ) diff --git a/apps/backend/internal/backendapp/persistence_middleware.go b/apps/backend/internal/backendapp/persistence_middleware.go index 77a79f05a4..95262404c7 100644 --- a/apps/backend/internal/backendapp/persistence_middleware.go +++ b/apps/backend/internal/backendapp/persistence_middleware.go @@ -32,8 +32,8 @@ func requiredPersistenceMiddleware(health *requiredstores.Health) gin.HandlerFun } func persistencePathExcluded(path string) bool { - if path == "/health" || path == "/ready" || path == persistenceDiagnosticsPath { + if path == healthRoutePath || path == readyRoutePath || path == persistenceDiagnosticsPath { return true } - return !strings.HasPrefix(path, "/api/") && !strings.HasPrefix(path, "/mcp") && path != "/ws" + return !strings.HasPrefix(path, "/api/") && !strings.HasPrefix(path, "/mcp") && path != websocketRoutePath } diff --git a/apps/backend/internal/events/types.go b/apps/backend/internal/events/types.go index 78e49d655e..1684c26cb9 100644 --- a/apps/backend/internal/events/types.go +++ b/apps/backend/internal/events/types.go @@ -3,12 +3,18 @@ package events // Event types for tasks const ( - TaskCreated = "task.created" - TaskUpdated = "task.updated" - TaskStateChanged = "task.state_changed" - TaskDeleted = "task.deleted" - TaskMoved = "task.moved" // Manual step change via MoveTask - TaskQueuePromoted = "task.queue_promoted" + TaskCreated = "task.created" + TaskUpdated = "task.updated" + TaskStateChanged = "task.state_changed" + TaskDeleted = "task.deleted" + TaskMoved = "task.moved" // Manual step change via MoveTask + TaskQueuePromoted = "task.queue_promoted" + // TaskReordered fires when a within-step band reorder commits + // (REQ-TASKS-KANBAN-TASK-REORDERING-001.16). Payload: + // {workflow_step_id, band, revision, tasks: [{id, position}]}, the whole + // step's non-hidden tasks in both bands. Deliberately not task.moved + // (.21) and not one task.updated per task. + TaskReordered = "task.reordered" SessionWorkspaceSourcesUpdated = "session.workspace_sources.updated" // TaskDependenciesResolved fires when a task's last unresolved dependency // completes successfully. Payload: {task_id, resolved_by_task_id}. diff --git a/apps/backend/internal/gateway/websocket/task_notifications.go b/apps/backend/internal/gateway/websocket/task_notifications.go index 44967b97e7..b098fa0835 100644 --- a/apps/backend/internal/gateway/websocket/task_notifications.go +++ b/apps/backend/internal/gateway/websocket/task_notifications.go @@ -43,6 +43,7 @@ func RegisterTaskNotifications(ctx context.Context, eventBus bus.EventBus, hub * b.subscribe(eventBus, events.AgentProfileDeleted, ws.ActionAgentProfileDeleted) b.subscribe(eventBus, events.TaskCreated, ws.ActionTaskCreated) b.subscribe(eventBus, events.TaskUpdated, ws.ActionTaskUpdated) + b.subscribe(eventBus, events.TaskReordered, ws.ActionTaskReordered) b.subscribe(eventBus, events.SessionWorkspaceSourcesUpdated, ws.ActionSessionWorkspaceSourcesUpdated) b.subscribe(eventBus, events.TaskDeleted, ws.ActionTaskDeleted) b.subscribeLifecycleStateEvents(eventBus) diff --git a/apps/backend/internal/gateway/websocket/task_notifications_test.go b/apps/backend/internal/gateway/websocket/task_notifications_test.go index b0a5f41645..0d05ca76ce 100644 --- a/apps/backend/internal/gateway/websocket/task_notifications_test.go +++ b/apps/backend/internal/gateway/websocket/task_notifications_test.go @@ -112,7 +112,7 @@ func TestTaskEventBroadcaster_NoDuplicateSubscriptions(t *testing.T) { // // Update this number when adding or removing event subscriptions in // RegisterTaskNotifications — it is intentionally exact. - const wantSubscriptions = 73 + const wantSubscriptions = 74 if got := len(b.subscriptions); got != wantSubscriptions { t.Errorf("RegisterTaskNotifications created %d subscriptions, want %d — "+ "did an event get subscribed twice?", got, wantSubscriptions) diff --git a/apps/backend/internal/office/service/budget_admission_lost_race_test.go b/apps/backend/internal/office/service/budget_admission_lost_race_test.go index 8d8039e104..4e98540517 100644 --- a/apps/backend/internal/office/service/budget_admission_lost_race_test.go +++ b/apps/backend/internal/office/service/budget_admission_lost_race_test.go @@ -23,7 +23,7 @@ func TestCancelBudgetRun_LostRaceDoesNotClassifyPublishOrLog(t *testing.T) { if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { t.Fatalf("queue: %v", err) } run, err := svc.ClaimNextRun(ctx) @@ -88,7 +88,7 @@ func TestDeferWorkspaceLookupFailure_LostRaceDoesNotLog(t *testing.T) { if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { t.Fatalf("queue: %v", err) } run, err := svc.ClaimNextRun(ctx) @@ -148,7 +148,7 @@ func TestCancelUnresolvableAgentRun_LostRaceDoesNotClassifyPublishOrLog(t *testi if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { t.Fatalf("queue: %v", err) } run, err := svc.ClaimNextRun(ctx) diff --git a/apps/backend/internal/office/service/event_subscribers_lost_race_side_effects_test.go b/apps/backend/internal/office/service/event_subscribers_lost_race_side_effects_test.go index 96ef4c03a7..a77e43d3c1 100644 --- a/apps/backend/internal/office/service/event_subscribers_lost_race_side_effects_test.go +++ b/apps/backend/internal/office/service/event_subscribers_lost_race_side_effects_test.go @@ -28,7 +28,7 @@ func TestHandleAgentCompleted_FinishRunFailureSkipsCompletionSideEffects(t *test createTestAgent(t, svc, "ws-1", "worker-race") taskID := createOfficeTask(t, svc, "ws-1", "worker-race") - if err := svc.QueueRun( + if _, err := svc.QueueRun( ctx, "worker-race", service.RunReasonTaskAssigned, `{"task_id":"`+taskID+`"}`, "run-output-race", ); err != nil { diff --git a/apps/backend/internal/office/service/finish_run_error_logging_test.go b/apps/backend/internal/office/service/finish_run_error_logging_test.go index 0f3f081737..797ef1c766 100644 --- a/apps/backend/internal/office/service/finish_run_error_logging_test.go +++ b/apps/backend/internal/office/service/finish_run_error_logging_test.go @@ -53,7 +53,7 @@ func TestSchedulerOutcome_IdleSkipped_FinishRunErrorIsLogged(t *testing.T) { if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonHeartbeat, `{}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonHeartbeat, `{}`, ""); err != nil { t.Fatalf("queue: %v", err) } diff --git a/apps/backend/internal/office/service/retry_cancel_lost_race_test.go b/apps/backend/internal/office/service/retry_cancel_lost_race_test.go index 4b1132bca4..b8a3fd3f88 100644 --- a/apps/backend/internal/office/service/retry_cancel_lost_race_test.go +++ b/apps/backend/internal/office/service/retry_cancel_lost_race_test.go @@ -27,7 +27,7 @@ func TestHandleRunFailure_LostCancelRaceDoesNotPublishFalseCancelled(t *testing. if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", "k-stale-retry-race"); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", "k-stale-retry-race"); err != nil { t.Fatalf("queue: %v", err) } run, err := svc.ClaimNextRun(ctx) @@ -98,7 +98,7 @@ func TestSchedulerIntegration_CancelStaleRunLostRaceDoesNotPublishOrLog(t *testi (id, workspace_id, workflow_step_id, title, created_at, updated_at) VALUES ('task-moved-step-race', 'ws-1', 'step-current', 'Moved task', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`) - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-moved-step-race","workflow_step_id":"step-old"}`, ""); err != nil { t.Fatalf("queue run: %v", err) } diff --git a/apps/backend/internal/office/service/retry_cancel_test.go b/apps/backend/internal/office/service/retry_cancel_test.go index 9aa860d58a..a9c40a201d 100644 --- a/apps/backend/internal/office/service/retry_cancel_test.go +++ b/apps/backend/internal/office/service/retry_cancel_test.go @@ -29,7 +29,7 @@ func TestCancelPendingRetriesForTask_RecordsTerminalShape(t *testing.T) { VALUES (?, ?, 'Build API', 'Implement endpoint', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`, taskID, agent.WorkspaceID) - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"`+taskID+`"}`, ""); err != nil { t.Fatalf("queue: %v", err) } diff --git a/apps/backend/internal/office/service/retry_stale_terminal_shape_test.go b/apps/backend/internal/office/service/retry_stale_terminal_shape_test.go index eea40aeaf2..02d5690bca 100644 --- a/apps/backend/internal/office/service/retry_stale_terminal_shape_test.go +++ b/apps/backend/internal/office/service/retry_stale_terminal_shape_test.go @@ -25,7 +25,7 @@ func TestHandleRunFailure_CancelsStaleRetryAndRecordsTerminalShape(t *testing.T) if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", "k-stale-retry"); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", "k-stale-retry"); err != nil { t.Fatalf("queue: %v", err) } run, err := svc.ClaimNextRun(ctx) diff --git a/apps/backend/internal/office/service/run_claimed_counter_test.go b/apps/backend/internal/office/service/run_claimed_counter_test.go index 0dd09fad25..bbb4e4f8e8 100644 --- a/apps/backend/internal/office/service/run_claimed_counter_test.go +++ b/apps/backend/internal/office/service/run_claimed_counter_test.go @@ -40,7 +40,7 @@ func TestClaimNextRun_IncrementsRunClaimedCounter(t *testing.T) { if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", ""); err != nil { t.Fatalf("queue: %v", err) } diff --git a/apps/backend/internal/office/service/scheduler_integration_test.go b/apps/backend/internal/office/service/scheduler_integration_test.go index 8f27d41af6..d5858a35ae 100644 --- a/apps/backend/internal/office/service/scheduler_integration_test.go +++ b/apps/backend/internal/office/service/scheduler_integration_test.go @@ -112,7 +112,7 @@ func TestSchedulerIntegration_CancelStaleRunRecordsTerminalShape(t *testing.T) { (id, workspace_id, workflow_step_id, title, created_at, updated_at) VALUES ('task-moved-step-shape', 'ws-1', 'step-current', 'Moved task', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`) - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-moved-step-shape","workflow_step_id":"step-old"}`, ""); err != nil { t.Fatalf("queue run: %v", err) } diff --git a/apps/backend/internal/office/service/scheduler_lost_race_activity_test.go b/apps/backend/internal/office/service/scheduler_lost_race_activity_test.go index b58e1413b7..3b60ebcf7b 100644 --- a/apps/backend/internal/office/service/scheduler_lost_race_activity_test.go +++ b/apps/backend/internal/office/service/scheduler_lost_race_activity_test.go @@ -46,7 +46,7 @@ func TestSchedulerIntegration_IdleSkipLostRaceDoesNotLogFalseActivity(t *testing } // Worker defaults to skip_idle_runs=true, no tasks assigned. - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonHeartbeat, `{}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonHeartbeat, `{}`, ""); err != nil { t.Fatalf("queue: %v", err) } @@ -103,7 +103,7 @@ func TestSchedulerIntegration_BudgetBlockedLostRaceDoesNotLogFalseActivity(t *te insertTestTask(t, svc, "task-budget-race", "ws-1") insertTestCostEvent(t, svc, agent.ID, "task-budget-race", int64(600)) - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-budget-race"}`, ""); err != nil { t.Fatalf("queue: %v", err) } diff --git a/apps/backend/internal/office/service/scheduler_taskless_launch_test.go b/apps/backend/internal/office/service/scheduler_taskless_launch_test.go index 49b54f6c3d..d63c7178d3 100644 --- a/apps/backend/internal/office/service/scheduler_taskless_launch_test.go +++ b/apps/backend/internal/office/service/scheduler_taskless_launch_test.go @@ -100,7 +100,7 @@ func TestSchedulerTick_TasklessRunRecordsTerminalShape(t *testing.T) { key := service.LoopMetricLabel("workspace", "ws-1", "shape", string(service.ShapeUnlaunchedFailed)) before := terminalShapeExpvarInt(t, key) - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { t.Fatalf("queue: %v", err) } service.RunSchedulerTick(svc, ctx) @@ -135,7 +135,7 @@ func TestFailTasklessRun_LostRaceDoesNotAppendSpuriousErrorEvent(t *testing.T) { if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{}`, ""); err != nil { t.Fatalf("queue: %v", err) } run, err := svc.ClaimNextRun(ctx) diff --git a/apps/backend/internal/office/service/session_hop_direct_test.go b/apps/backend/internal/office/service/session_hop_direct_test.go index 79fe6ae823..0791091871 100644 --- a/apps/backend/internal/office/service/session_hop_direct_test.go +++ b/apps/backend/internal/office/service/session_hop_direct_test.go @@ -72,7 +72,7 @@ func TestSchedulerTick_DirectLaunchPersistsSessionID(t *testing.T) { } svc.ExecSQL(t, `INSERT INTO tasks (id, workspace_id, title, description, created_at, updated_at) VALUES ('task-direct-session-1', 'ws-1', 'Build API', 'Implement endpoint', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`) - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-direct-session-1"}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-direct-session-1"}`, ""); err != nil { t.Fatalf("queue: %v", err) } @@ -117,7 +117,7 @@ func TestSchedulerTick_DirectLaunchWithoutSessionSeamCountsWithoutSession(t *tes } svc.ExecSQL(t, `INSERT INTO tasks (id, workspace_id, title, description, created_at, updated_at) VALUES ('task-direct-nosession-1', 'ws-1', 'Build API', 'Implement endpoint', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`) - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-direct-nosession-1"}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-direct-nosession-1"}`, ""); err != nil { t.Fatalf("queue: %v", err) } diff --git a/apps/backend/internal/office/service/session_persist_failure_test.go b/apps/backend/internal/office/service/session_persist_failure_test.go index 46759a626c..411b0d74ae 100644 --- a/apps/backend/internal/office/service/session_persist_failure_test.go +++ b/apps/backend/internal/office/service/session_persist_failure_test.go @@ -49,7 +49,7 @@ func TestSchedulerTick_DirectLaunchSessionPersistFailureCountsSeparately(t *test } svc.ExecSQL(t, `INSERT INTO tasks (id, workspace_id, title, description, created_at, updated_at) VALUES ('task-direct-persist-fail-1', 'ws-1', 'Build API', 'Implement endpoint', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`) - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-direct-persist-fail-1"}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-direct-persist-fail-1"}`, ""); err != nil { t.Fatalf("queue: %v", err) } @@ -128,7 +128,7 @@ func TestSchedulerTick_DirectLaunchZeroRowSessionWriteCountsAsPersistFailure(t * } svc.ExecSQL(t, `INSERT INTO tasks (id, workspace_id, title, description, created_at, updated_at) VALUES ('task-direct-vanished-1', 'ws-1', 'Build API', 'Implement endpoint', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`) - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-direct-vanished-1"}`, ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"task-direct-vanished-1"}`, ""); err != nil { t.Fatalf("queue: %v", err) } diff --git a/apps/backend/internal/office/service/terminal_shape_wiring_test.go b/apps/backend/internal/office/service/terminal_shape_wiring_test.go index 2c18c5b5ca..e8b46959bc 100644 --- a/apps/backend/internal/office/service/terminal_shape_wiring_test.go +++ b/apps/backend/internal/office/service/terminal_shape_wiring_test.go @@ -43,7 +43,7 @@ func TestFinishRun_RecordsSilentSuccessTerminalShape(t *testing.T) { if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", ""); err != nil { t.Fatalf("queue: %v", err) } run, err := svc.ClaimNextRun(ctx) @@ -73,7 +73,7 @@ func TestFailRun_RecordsUnlaunchedFailedTerminalShape(t *testing.T) { if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", ""); err != nil { + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, "{}", ""); err != nil { t.Fatalf("queue: %v", err) } run, err := svc.ClaimNextRun(ctx) diff --git a/apps/backend/internal/office/service/tree_controls_test.go b/apps/backend/internal/office/service/tree_controls_test.go index 5707f6b44e..d51a8af3df 100644 --- a/apps/backend/internal/office/service/tree_controls_test.go +++ b/apps/backend/internal/office/service/tree_controls_test.go @@ -77,7 +77,7 @@ func TestPauseTaskTree_RecordsTerminalShapeForCancelledRuns(t *testing.T) { if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"root"}`, ""); err != nil { t.Fatalf("queue: %v", err) } @@ -153,7 +153,7 @@ func TestCancelTaskTree_RecordsTerminalShapeForCancelledRuns(t *testing.T) { if err := svc.CreateAgentInstance(ctx, agent); err != nil { t.Fatalf("create agent: %v", err) } - if err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonTaskAssigned, `{"task_id":"root"}`, ""); err != nil { t.Fatalf("queue: %v", err) } diff --git a/apps/backend/internal/orchestrator/event_handlers_agent_error_evaluate_only_test.go b/apps/backend/internal/orchestrator/event_handlers_agent_error_evaluate_only_test.go index 774496f552..2d0d367259 100644 --- a/apps/backend/internal/orchestrator/event_handlers_agent_error_evaluate_only_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_agent_error_evaluate_only_test.go @@ -242,7 +242,7 @@ type agentErrorCommitErrorRepo struct { } func (r *agentErrorCommitErrorRepo) UpdateTaskWithWorkflowStepAdmission( - _ context.Context, _ *models.Task, _ string, _ int, + _ context.Context, _ *models.Task, _, _ string, _ int, ) (bool, error) { return false, r.err } @@ -612,7 +612,7 @@ func (r *agentErrorBlockingCommitRepo) sessionCallCount() int { } func (r *agentErrorBlockingCommitRepo) UpdateTaskWithWorkflowStepAdmission( - ctx context.Context, task *models.Task, targetStepID string, limit int, + ctx context.Context, task *models.Task, sourceStepID, targetStepID string, limit int, ) (bool, error) { r.commitMu.Lock() r.commitCalls++ @@ -622,7 +622,7 @@ func (r *agentErrorBlockingCommitRepo) UpdateTaskWithWorkflowStepAdmission( close(r.entered) <-r.release } - return r.Repository.UpdateTaskWithWorkflowStepAdmission(ctx, task, targetStepID, limit) + return r.Repository.UpdateTaskWithWorkflowStepAdmission(ctx, task, sourceStepID, targetStepID, limit) } // TestDispatchKanbanAgentErrorTrigger_ConcurrentSameOperationLockSpansThroughCommit diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow.go b/apps/backend/internal/orchestrator/event_handlers_workflow.go index f01da7f1a4..a1c0085420 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow.go @@ -468,7 +468,11 @@ func (s *Service) executeStepTransition(ctx context.Context, taskID, sessionID s legacyTrigger = engine.TriggerOnTurnComplete } transitionCtx := engineTransitionAttribution(ctx, sessionID, legacyTrigger) - if err := s.updateTransitionTaskWithCapacity(transitionCtx, task, targetStep); err != nil { + fromStepID := "" + if fromStep != nil { + fromStepID = fromStep.ID + } + if err := s.updateTransitionTaskWithCapacity(transitionCtx, task, fromStepID, targetStep); err != nil { s.logger.Warn("workflow transition rejected or failed", zap.String("task_id", taskID), zap.String("from_step", fromStep.Name), @@ -579,6 +583,7 @@ func (s *Service) executeStepTransition(ctx context.Context, taskID, sessionID s func (s *Service) updateTransitionTaskWithCapacity( ctx context.Context, task *models.Task, + fromStepID string, targetStep *wfmodels.WorkflowStep, ) error { if targetStep == nil { @@ -588,7 +593,7 @@ func (s *Service) updateTransitionTaskWithCapacity( if !ok { return fmt.Errorf("workflow step admission repository unavailable for step %s", targetStep.ID) } - _, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, task, targetStep.ID, targetStep.WIPLimit) + _, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, task, fromStepID, targetStep.ID, targetStep.WIPLimit) return err } diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow_test.go b/apps/backend/internal/orchestrator/event_handlers_workflow_test.go index 36b678ef3c..69c72401b6 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow_test.go @@ -46,7 +46,7 @@ func TestUpdateTransitionTaskWithCapacity_QueuesFullLimitedStep(t *testing.T) { task.WorkflowStepID = "step2" target := &wfmodels.WorkflowStep{ID: "step2", WorkflowID: "wf1", WIPLimit: 1} - err = svc.updateTransitionTaskWithCapacity(ctx, task, target) + err = svc.updateTransitionTaskWithCapacity(ctx, task, "step1", target) if err != nil { t.Fatalf("updateTransitionTaskWithCapacity: %v", err) } diff --git a/apps/backend/internal/orchestrator/executor/executor_mocks_test.go b/apps/backend/internal/orchestrator/executor/executor_mocks_test.go index 23bc616775..c84d5b5ac4 100644 --- a/apps/backend/internal/orchestrator/executor/executor_mocks_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_mocks_test.go @@ -809,7 +809,10 @@ func (m *mockRepository) GetTasksByIDs(ctx context.Context, ids []string) ([]*mo return out, nil } func (m *mockRepository) UpdateTask(ctx context.Context, task *models.Task) error { return nil } -func (m *mockRepository) DeleteTask(ctx context.Context, id string) error { return nil } +func (m *mockRepository) UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error { + return nil +} +func (m *mockRepository) DeleteTask(ctx context.Context, id string) error { return nil } func (m *mockRepository) ListTasks(ctx context.Context, workflowID string) ([]*models.Task, error) { return nil, nil } diff --git a/apps/backend/internal/orchestrator/workflow_store.go b/apps/backend/internal/orchestrator/workflow_store.go index 8c9d9de6a0..8839fea9e2 100644 --- a/apps/backend/internal/orchestrator/workflow_store.go +++ b/apps/backend/internal/orchestrator/workflow_store.go @@ -44,7 +44,7 @@ type workflowLimitedMoveRepository interface { } type workflowMoveAdmissionRepository interface { - UpdateTaskWithWorkflowStepAdmission(ctx context.Context, task *models.Task, targetStepID string, limit int) (bool, error) + UpdateTaskWithWorkflowStepAdmission(ctx context.Context, task *models.Task, sourceStepID, targetStepID string, limit int) (bool, error) } // workflowMoveAdmissionCASRepository is the AC-46/48 compare-and-swap @@ -392,7 +392,7 @@ func (s *workflowStore) applyTransition( ); err != nil { return fmt.Errorf("update task workflow step: %w", err) } - } else if err := s.updateTransitionTask(transitionCtx, task, targetStep); err != nil { + } else if err := s.updateTransitionTask(transitionCtx, task, fromStepID, targetStep); err != nil { return fmt.Errorf("update task workflow step: %w", err) } @@ -609,7 +609,7 @@ func markDeferredMoveApplied(task *models.Task, moveID string) error { return nil } -func (s *workflowStore) updateTransitionTask(ctx context.Context, task *models.Task, targetStep *wfmodels.WorkflowStep) error { +func (s *workflowStore) updateTransitionTask(ctx context.Context, task *models.Task, fromStepID string, targetStep *wfmodels.WorkflowStep) error { if targetStep == nil { return s.repo.UpdateTask(ctx, task) } @@ -617,7 +617,7 @@ func (s *workflowStore) updateTransitionTask(ctx context.Context, task *models.T if !ok { return fmt.Errorf("workflow step admission repository unavailable for step %s", targetStep.ID) } - _, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, task, targetStep.ID, targetStep.WIPLimit) + _, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, task, fromStepID, targetStep.ID, targetStep.WIPLimit) return err } @@ -803,7 +803,7 @@ func (s *workflowStore) pullOneFeederTask( continue } } else if admissionRepo, ok := s.repo.(workflowMoveAdmissionRepository); ok { - claimed, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, vacatedStep.ID, vacatedStep.WIPLimit) + claimed, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, fromStepID, vacatedStep.ID, vacatedStep.WIPLimit) if err != nil { s.logger.Warn("failed to promote feeder task", zap.String("task_id", candidate.ID), zap.Error(err)) skipped[candidate.ID] = struct{}{} @@ -868,7 +868,7 @@ func (s *workflowStore) promoteSameStepTask(ctx context.Context, candidate *mode return s.pullOneFeederTask(ctx, pullRepo, limitedRepo, step, position, skipped) } } else if admissionRepo, ok := s.repo.(workflowMoveAdmissionRepository); ok { - claimed, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, step.ID, step.WIPLimit) + claimed, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, fromStepID, step.ID, step.WIPLimit) if err != nil { s.logger.Warn("failed to promote same-step queued task", zap.String("task_id", candidate.ID), zap.Error(err)) skipped[candidate.ID] = struct{}{} @@ -941,34 +941,13 @@ func (s *workflowStore) nextQueuedSameStepTask(ctx context.Context, stepID strin return best } +// queuedTaskBefore is the WIP promotion comparator +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.1, .36): position, priority rank, +// queued_at (coalesced to created_at when absent), created_at, id. Delegates +// to models.StepOrderLess, the single source of truth this comparator's +// byte-identical task/service copy and the reorder repository also use. func queuedTaskBefore(left, right *models.Task) bool { - if left.Position != right.Position { - return left.Position < right.Position - } - priority := func(value string) int { - switch value { - case "critical": - return 0 - case "high": - return 1 - case "medium": - return 2 - case "low": - return 3 - default: - return 4 - } - } - if priority(left.Priority) != priority(right.Priority) { - return priority(left.Priority) < priority(right.Priority) - } - if left.QueuedAt != nil && right.QueuedAt != nil && !left.QueuedAt.Equal(*right.QueuedAt) { - return left.QueuedAt.Before(*right.QueuedAt) - } - if !left.CreatedAt.Equal(right.CreatedAt) { - return left.CreatedAt.Before(right.CreatedAt) - } - return left.ID < right.ID + return models.StepOrderLess(left, right) } func (s *workflowStore) feederCandidateBlocked(ctx context.Context, taskID string) bool { diff --git a/apps/backend/internal/orchestrator/workflow_store_test.go b/apps/backend/internal/orchestrator/workflow_store_test.go index 87e1482529..e13f00f66f 100644 --- a/apps/backend/internal/orchestrator/workflow_store_test.go +++ b/apps/backend/internal/orchestrator/workflow_store_test.go @@ -3,6 +3,7 @@ package orchestrator import ( "context" "testing" + "time" "github.com/kandev/kandev/internal/task/models" wfmodels "github.com/kandev/kandev/internal/workflow/models" @@ -309,18 +310,11 @@ func TestWorkflowStore_ApplyTransitionPullsNextFeederTaskOnVacate(t *testing.T) ctx := context.Background() repo := setupTestRepo(t) seedSession(t, repo, "t1", "s1", "step-limited") - if err := repo.CreateTask(ctx, &models.Task{ - ID: "task-low", - WorkspaceID: "ws1", - WorkflowID: "wf1", - WorkflowStepID: "step-feeder", - Title: "Low", - State: "TODO", - Priority: "low", - Position: 0, - }); err != nil { - t.Fatalf("CreateTask low: %v", err) - } + // Creation now assigns each task the next arrival position in its step + // regardless of any caller-supplied Position, and step order ranks + // position ahead of priority. So the critical task must arrive first to + // be the one pulled here; a same-position tiebreak on priority is + // covered directly in models.TestStepOrderLess. if err := repo.CreateTask(ctx, &models.Task{ ID: "task-critical", WorkspaceID: "ws1", @@ -329,10 +323,20 @@ func TestWorkflowStore_ApplyTransitionPullsNextFeederTaskOnVacate(t *testing.T) Title: "Critical", State: "TODO", Priority: "critical", - Position: 0, }); err != nil { t.Fatalf("CreateTask critical: %v", err) } + if err := repo.CreateTask(ctx, &models.Task{ + ID: "task-low", + WorkspaceID: "ws1", + WorkflowID: "wf1", + WorkflowStepID: "step-feeder", + Title: "Low", + State: "TODO", + Priority: "low", + }); err != nil { + t.Fatalf("CreateTask low: %v", err) + } stepGetter := newMockStepGetter() stepGetter.steps["step-limited"] = &wfmodels.WorkflowStep{ @@ -564,3 +568,25 @@ func TestWorkflowStore_OperationIdempotency(t *testing.T) { } }) } + +// TestQueuedTaskBeforeAlignsQueuedAtWithCreatedAtFallback covers +// AC-TASKS-KANBAN-TASK-REORDERING-001.36: this comparator is byte-identical +// to service_workflow.go's queuedTaskBefore and must apply the same +// COALESCE(queued_at, created_at) fallback rather than skipping the key +// whenever either side's queued_at is nil. +func TestQueuedTaskBeforeAlignsQueuedAtWithCreatedAtFallback(t *testing.T) { + earlier := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + later := earlier.Add(time.Hour) + + left := &models.Task{ID: "a", Position: 1, Priority: "medium", QueuedAt: nil, CreatedAt: earlier} + right := &models.Task{ID: "b", Position: 1, Priority: "medium", QueuedAt: &earlier, CreatedAt: later} + if !queuedTaskBefore(left, right) { + t.Fatalf("queuedTaskBefore(nil queued_at falling back to earlier created_at) = false, want true") + } + + leftLate := &models.Task{ID: "a", Position: 1, Priority: "medium", QueuedAt: &later, CreatedAt: earlier} + rightNil := &models.Task{ID: "b", Position: 1, Priority: "medium", QueuedAt: nil, CreatedAt: earlier} + if queuedTaskBefore(leftLate, rightNil) { + t.Fatalf("queuedTaskBefore(later effective queued_at) = true, want false") + } +} diff --git a/apps/backend/internal/task/dto/converters.go b/apps/backend/internal/task/dto/converters.go index 8fc90c63c9..b2f6643302 100644 --- a/apps/backend/internal/task/dto/converters.go +++ b/apps/backend/internal/task/dto/converters.go @@ -30,6 +30,7 @@ func FromWorkflowStep(step *wfmodels.WorkflowStep) WorkflowStepDTO { AutoAdvanceRequiresSignal: step.AutoAdvanceRequiresSignal, CancelTriggersTurnComplete: step.CancelTriggersTurnComplete, CompleteTaskOnEnter: step.CompleteTaskOnEnter, + OrderRevision: step.OrderRevision, } if hasStepEvents(step.Events) { events := &StepEventsDTO{} diff --git a/apps/backend/internal/task/dto/dto.go b/apps/backend/internal/task/dto/dto.go index a2b7b13f3d..07a1de9278 100644 --- a/apps/backend/internal/task/dto/dto.go +++ b/apps/backend/internal/task/dto/dto.go @@ -1188,12 +1188,18 @@ type WorkflowStepDTO struct { PullFromStepID string `json:"pull_from_step_id,omitempty"` // StageType is a Phase 2 (ADR-0004) semantic hint for the frontend. // Allowed values: "work" | "review" | "approval" | "custom". - StageType string `json:"stage_type,omitempty"` - AutoAdvanceRequiresSignal bool `json:"auto_advance_requires_signal"` - CancelTriggersTurnComplete bool `json:"cancel_triggers_turn_complete"` - CompleteTaskOnEnter bool `json:"complete_task_on_enter"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + StageType string `json:"stage_type,omitempty"` + AutoAdvanceRequiresSignal bool `json:"auto_advance_requires_signal"` + CancelTriggersTurnComplete bool `json:"cancel_triggers_turn_complete"` + CompleteTaskOnEnter bool `json:"complete_task_on_enter"` + // OrderRevision lets a client seed its last-known revision for this step + // before accepting any task.reordered WS event, so a stale event received + // right after hydration cannot be mistaken for the first order this + // client has ever seen (see kanban-task-reordering system design, + // "Reorder contract"). + OrderRevision int64 `json:"order_revision"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } // StepEventsDTO represents step events for API responses diff --git a/apps/backend/internal/task/handlers/process_handlers_test.go b/apps/backend/internal/task/handlers/process_handlers_test.go index cddf23e132..0783bbf126 100644 --- a/apps/backend/internal/task/handlers/process_handlers_test.go +++ b/apps/backend/internal/task/handlers/process_handlers_test.go @@ -89,6 +89,9 @@ func (m *mockRepository) GetTasksByIDs(ctx context.Context, ids []string) ([]*mo func (m *mockRepository) UpdateTask(ctx context.Context, task *models.Task) error { return nil } +func (m *mockRepository) UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error { + return nil +} func (m *mockRepository) DeleteTask(ctx context.Context, id string) error { return nil } diff --git a/apps/backend/internal/task/handlers/task_detachment_test.go b/apps/backend/internal/task/handlers/task_detachment_test.go index f0491be0c9..be17ba1f32 100644 --- a/apps/backend/internal/task/handlers/task_detachment_test.go +++ b/apps/backend/internal/task/handlers/task_detachment_test.go @@ -39,6 +39,10 @@ func (r *detachHandlerRepo) UpdateTask(_ context.Context, task *models.Task) err return nil } +func (r *detachHandlerRepo) UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error { + return r.UpdateTask(ctx, task) +} + func (r *detachHandlerRepo) DetachTask(_ context.Context, _ string) (bool, error) { if r.getErr != nil { return false, r.getErr diff --git a/apps/backend/internal/task/handlers/task_handlers.go b/apps/backend/internal/task/handlers/task_handlers.go index 87799a7ee4..affc3f418d 100644 --- a/apps/backend/internal/task/handlers/task_handlers.go +++ b/apps/backend/internal/task/handlers/task_handlers.go @@ -224,6 +224,11 @@ func (h *TaskHandlers) registerHTTP(router *gin.Engine) { api.GET("/workflows/:id/task-count", h.httpGetWorkflowTaskCount) api.GET("/workflow/steps/:id/task-count", h.httpGetStepTaskCount) + // Kanban task reordering (REQ-TASKS-KANBAN-TASK-REORDERING-001.17): the + // only request surface for a reorder, mirroring the hyphenated + // collection-reorder precedent PUT /api/v1/workspaces/:id/workflows/reorder. + api.PUT("/workflow-steps/:id/tasks/reorder", h.httpReorderStepTasks) + // Session workflow review endpoints api.POST("/sessions/:id/approve", h.httpApproveSession) diff --git a/apps/backend/internal/task/handlers/task_http_handlers.go b/apps/backend/internal/task/handlers/task_http_handlers.go index 9572b79968..657541189f 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers.go +++ b/apps/backend/internal/task/handlers/task_http_handlers.go @@ -1734,6 +1734,66 @@ type httpMoveTaskRequest struct { EntryOptions *workflowmove.EntryOptions `json:"entry_options,omitempty"` } +// httpReorderStepTasksRequest is the frozen reorder request contract +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.17): the step is the path parameter, +// so the body never repeats it, and the band is an explicit discriminator +// rather than inferred from the submitted ids. +type httpReorderStepTasksRequest struct { + Band string `json:"band"` + OrderedTaskIDs []string `json:"ordered_task_ids"` +} + +func (h *TaskHandlers) httpReorderStepTasks(c *gin.Context) { + var body httpReorderStepTasksRequest + if err := c.ShouldBindJSON(&body); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"code": "invalid_reorder"}) + return + } + result, err := h.service.ReorderStepTasks(c.Request.Context(), c.Param("id"), body.Band, body.OrderedTaskIDs) + if err != nil { + h.handleReorderStepTasksError(c, err, result) + return + } + c.JSON(http.StatusOK, reorderStepTasksResponseBody(result)) +} + +// handleReorderStepTasksError maps a reorder failure to the frozen response +// shapes: step_changed carries the authoritative whole-step order the board +// reconciles to silently (REQ-TASKS-KANBAN-TASK-REORDERING-001.19); +// invalid_reorder carries no task list, since a malformed request implies +// nothing about the persisted order (REQ-TASKS-KANBAN-TASK-REORDERING-001.18). +func (h *TaskHandlers) handleReorderStepTasksError(c *gin.Context, err error, result *service.ReorderStepTasksResult) { + switch { + case isClientDisconnect(err): + abortClientDisconnect(c) + case errors.Is(err, taskrepository.ErrStepChanged): + body := reorderStepTasksResponseBody(result) + body["code"] = "step_changed" + c.JSON(http.StatusConflict, body) + case errors.Is(err, taskrepository.ErrInvalidReorder): + c.JSON(http.StatusBadRequest, gin.H{"code": "invalid_reorder"}) + case isNotFound(err): + c.JSON(http.StatusNotFound, gin.H{"error": "workflow step not found"}) + case service.IsForbidden(err): + c.JSON(http.StatusForbidden, gin.H{"error": err.Error()}) + default: + h.logger.Error("reorder step tasks failed", zap.Error(err)) + c.JSON(http.StatusInternalServerError, gin.H{"error": "reorder failed"}) + } +} + +func reorderStepTasksResponseBody(result *service.ReorderStepTasksResult) gin.H { + entries := make([]gin.H, len(result.Tasks)) + for i, task := range result.Tasks { + entries[i] = gin.H{"id": task.ID, "position": task.Position} + } + return gin.H{ + "workflow_step_id": result.WorkflowStepID, + "revision": result.Revision, + "tasks": entries, + } +} + func (h *TaskHandlers) httpMoveTask(c *gin.Context) { var body httpMoveTaskRequest if err := c.ShouldBindJSON(&body); err != nil { diff --git a/apps/backend/internal/task/handlers/task_http_handlers_external_id_test.go b/apps/backend/internal/task/handlers/task_http_handlers_external_id_test.go index 86483ec2b4..8164787a1f 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers_external_id_test.go +++ b/apps/backend/internal/task/handlers/task_http_handlers_external_id_test.go @@ -134,6 +134,10 @@ func (r *idempotentCreateTaskRepo) UpdateTask(_ context.Context, task *models.Ta return nil } +func (r *idempotentCreateTaskRepo) UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error { + return r.UpdateTask(ctx, task) +} + func (r *idempotentCreateTaskRepo) GetTaskByExternalID(_ context.Context, workspaceID, externalID string) (*models.Task, error) { r.mu.Lock() defer r.mu.Unlock() diff --git a/apps/backend/internal/task/handlers/task_http_handlers_test.go b/apps/backend/internal/task/handlers/task_http_handlers_test.go index fdf79d9cfc..eb5b2ac2fe 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers_test.go +++ b/apps/backend/internal/task/handlers/task_http_handlers_test.go @@ -1401,6 +1401,10 @@ func (m *moveTaskConflictRepo) UpdateTask(ctx context.Context, task *models.Task return nil } +func (m *moveTaskConflictRepo) UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error { + return m.UpdateTask(ctx, task) +} + func (m *moveTaskConflictRepo) GetWorkflow(ctx context.Context, id string) (*models.Workflow, error) { if m.workflows != nil { if workflow, ok := m.workflows[id]; ok { diff --git a/apps/backend/internal/task/handlers/task_port_forwarding_test.go b/apps/backend/internal/task/handlers/task_port_forwarding_test.go index 2629fdcb5e..0e639d2d4a 100644 --- a/apps/backend/internal/task/handlers/task_port_forwarding_test.go +++ b/apps/backend/internal/task/handlers/task_port_forwarding_test.go @@ -38,6 +38,10 @@ func (r *portForwardingHandlerRepo) UpdateTask(_ context.Context, task *models.T return nil } +func (r *portForwardingHandlerRepo) UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error { + return r.UpdateTask(ctx, task) +} + func newPortForwardingHandler(t *testing.T, repo *portForwardingHandlerRepo) *TaskHandlers { t.Helper() taskService := service.NewService(service.Repos{ diff --git a/apps/backend/internal/task/handlers/task_reorder_handlers_test.go b/apps/backend/internal/task/handlers/task_reorder_handlers_test.go new file mode 100644 index 0000000000..f99e6e38e3 --- /dev/null +++ b/apps/backend/internal/task/handlers/task_reorder_handlers_test.go @@ -0,0 +1,166 @@ +package handlers + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/jmoiron/sqlx" + "github.com/stretchr/testify/require" + + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/events/bus" + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository" + taskrepo "github.com/kandev/kandev/internal/task/repository/sqlite" + "github.com/kandev/kandev/internal/task/service" + wfmodels "github.com/kandev/kandev/internal/workflow/models" +) + +type reorderHandlerStepGetter struct { + steps map[string]*wfmodels.WorkflowStep +} + +func (f *reorderHandlerStepGetter) GetStep(_ context.Context, stepID string) (*wfmodels.WorkflowStep, error) { + if step, ok := f.steps[stepID]; ok { + return step, nil + } + return nil, taskrepo.ErrTaskNotFound +} + +func (f *reorderHandlerStepGetter) GetNextStepByPosition(context.Context, string, int) (*wfmodels.WorkflowStep, error) { + return nil, nil +} + +// newReorderHandlerTest builds a real sqlite-backed service (the reorder +// repository method needs actual workflow_steps/tasks rows, not a mock) and +// seeds one step with the given tasks, each getting its own arrival +// position in creation order. +func newReorderHandlerTest(t *testing.T, stepID string, taskIDs ...string) (*TaskHandlers, *taskrepo.Repository) { + t.Helper() + dbConn, err := db.OpenSQLite(filepath.Join(t.TempDir(), "test.db")) + require.NoError(t, err) + sqlxDB := sqlx.NewDb(dbConn, "sqlite3") + t.Cleanup(func() { _ = sqlxDB.Close() }) + repo, cleanup, err := repository.Provide(sqlxDB, sqlxDB, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = cleanup() }) + + ctx := context.Background() + require.NoError(t, repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-reorder-http", Name: "Workspace"})) + require.NoError(t, repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-reorder-http", WorkspaceID: "ws-reorder-http", Name: "Workflow"})) + + now := time.Now().UTC() + _, err = repo.DB().Exec(`INSERT INTO workflow_steps + (id, workflow_id, name, position, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)`, + stepID, "wf-reorder-http", stepID, 0, now, now) + require.NoError(t, err) + + for _, id := range taskIDs { + require.NoError(t, repo.CreateTask(ctx, &models.Task{ + ID: id, WorkspaceID: "ws-reorder-http", WorkflowID: "wf-reorder-http", WorkflowStepID: stepID, Title: id, + })) + } + + log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json", OutputPath: "stdout"}) + require.NoError(t, err) + svc := service.NewService(service.Repos{ + Workspaces: repo, Tasks: repo, TaskRepos: repo, + Workflows: repo, Messages: repo, Turns: repo, + Sessions: repo, GitSnapshots: repo, RepoEntities: repo, + Executors: repo, Environments: repo, TaskEnvironments: repo, + Reviews: repo, + }, bus.NewMemoryEventBus(log), log, service.RepositoryDiscoveryConfig{}) + svc.SetWorkflowStepGetter(&reorderHandlerStepGetter{steps: map[string]*wfmodels.WorkflowStep{ + stepID: {ID: stepID, WorkflowID: "wf-reorder-http", Name: stepID, Position: 0}, + }}) + return &TaskHandlers{service: svc, logger: log}, repo +} + +func reorderRequestContext(stepID, body string) (*gin.Context, *httptest.ResponseRecorder) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Params = gin.Params{{Key: "id", Value: stepID}} + c.Request = httptest.NewRequest(http.MethodPut, "/api/v1/workflow-steps/"+stepID+"/tasks/reorder", strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + return c, rec +} + +func TestHTTPReorderStepTasksSuccess(t *testing.T) { + h, _ := newReorderHandlerTest(t, "step-http-ok", "task-1", "task-2") + c, rec := reorderRequestContext("step-http-ok", `{"band":"admitted","ordered_task_ids":["task-2","task-1"]}`) + + h.httpReorderStepTasks(c) + + require.Equal(t, http.StatusOK, rec.Code) + var body map[string]interface{} + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + if body["workflow_step_id"] != "step-http-ok" { + t.Fatalf("workflow_step_id = %v, want step-http-ok", body["workflow_step_id"]) + } + if body["revision"].(float64) != 1 { + t.Fatalf("revision = %v, want 1", body["revision"]) + } + tasks, ok := body["tasks"].([]interface{}) + if !ok || len(tasks) != 2 { + t.Fatalf("tasks = %v, want 2 entries", body["tasks"]) + } + first := tasks[0].(map[string]interface{}) + if first["id"] != "task-2" || first["position"].(float64) != 0 { + t.Fatalf("tasks[0] = %v, want {id: task-2, position: 0}", first) + } +} + +func TestHTTPReorderStepTasksStepChangedConflict(t *testing.T) { + h, _ := newReorderHandlerTest(t, "step-http-conflict", "task-1", "task-2") + // Submission omits task-2: the band gained a member the caller doesn't + // know about (REQ-TASKS-KANBAN-TASK-REORDERING-001.19/.26). + c, rec := reorderRequestContext("step-http-conflict", `{"band":"admitted","ordered_task_ids":["task-1"]}`) + + h.httpReorderStepTasks(c) + + require.Equal(t, http.StatusConflict, rec.Code) + var body map[string]interface{} + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + if body["code"] != "step_changed" { + t.Fatalf("code = %v, want step_changed", body["code"]) + } + tasks, ok := body["tasks"].([]interface{}) + if !ok || len(tasks) != 2 { + t.Fatalf("tasks = %v, want the authoritative 2-task order", body["tasks"]) + } +} + +func TestHTTPReorderStepTasksInvalidRequest(t *testing.T) { + h, _ := newReorderHandlerTest(t, "step-http-invalid", "task-1") + c, rec := reorderRequestContext("step-http-invalid", `{"band":"admitted","ordered_task_ids":[]}`) + + h.httpReorderStepTasks(c) + + require.Equal(t, http.StatusBadRequest, rec.Code) + var body map[string]interface{} + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + if body["code"] != "invalid_reorder" { + t.Fatalf("code = %v, want invalid_reorder", body["code"]) + } + if _, hasTasks := body["tasks"]; hasTasks { + t.Fatalf("invalid_reorder body must carry no task list, got %v", body) + } +} + +func TestHTTPReorderStepTasksForbidden(t *testing.T) { + h, _ := newReorderHandlerTest(t, "step-http-forbidden", "task-1") + c, rec := reorderRequestContext("step-http-forbidden", `{"band":"admitted","ordered_task_ids":["task-1"]}`) + + h.handleReorderStepTasksError(c, service.ErrForbidden, nil) + + require.Equal(t, http.StatusForbidden, rec.Code) +} diff --git a/apps/backend/internal/task/handlers/task_ws_authz_test.go b/apps/backend/internal/task/handlers/task_ws_authz_test.go index 26b5532306..b7f9a22311 100644 --- a/apps/backend/internal/task/handlers/task_ws_authz_test.go +++ b/apps/backend/internal/task/handlers/task_ws_authz_test.go @@ -64,6 +64,10 @@ func (r *authzWSRepo) UpdateTask(_ context.Context, task *models.Task) error { return nil } +func (r *authzWSRepo) UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error { + return r.UpdateTask(ctx, task) +} + func (r *authzWSRepo) writes() int { r.mu.Lock() defer r.mu.Unlock() diff --git a/apps/backend/internal/task/handlers/task_ws_handlers_test.go b/apps/backend/internal/task/handlers/task_ws_handlers_test.go index e28d91a2d7..cb6fc025bc 100644 --- a/apps/backend/internal/task/handlers/task_ws_handlers_test.go +++ b/apps/backend/internal/task/handlers/task_ws_handlers_test.go @@ -80,6 +80,10 @@ func (r *wsTaskRepo) UpdateTask(_ context.Context, task *models.Task) error { return nil } +func (r *wsTaskRepo) UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error { + return r.UpdateTask(ctx, task) +} + func (r *wsTaskRepo) DeleteTask(_ context.Context, id string) error { r.deleted = append(r.deleted, id) return nil diff --git a/apps/backend/internal/task/handlers/workflow_handlers_test.go b/apps/backend/internal/task/handlers/workflow_handlers_test.go index 43a8c116f1..999e7cd027 100644 --- a/apps/backend/internal/task/handlers/workflow_handlers_test.go +++ b/apps/backend/internal/task/handlers/workflow_handlers_test.go @@ -565,6 +565,28 @@ func TestHTTPGetWorkflowSnapshotReturnsWorkflowStepsAndTasks(t *testing.T) { require.Empty(t, snapshot.Tasks) } +// TestHTTPGetWorkflowSnapshotIncludesStepOrderRevision covers the Build-phase +// fix for missing order_revision on HTTP hydration: the frontend seeds +// kanbanMulti.orderRevisionByStepId from this endpoint's response before +// accepting any task.reordered WS event, so a step's current revision must +// round-trip through the snapshot response. +func TestHTTPGetWorkflowSnapshotIncludesStepOrderRevision(t *testing.T) { + repo := workflowFixture() + steps := &stubStepLister{steps: []*workflowmodels.WorkflowStep{ + {ID: "step-1", WorkflowID: "wf-1", Name: "Todo", OrderRevision: 5}, + }} + h := newWorkflowHandlers(t, repo, steps) + c, rec := newWorkflowRequest(t, http.MethodGet, "/api/v1/workflows/wf-1/snapshot", "") + c.Params = gin.Params{{Key: "id", Value: "wf-1"}} + + h.httpGetWorkflowSnapshot(c) + + require.Equal(t, http.StatusOK, rec.Code) + snapshot := decodeWorkflowSnapshot(t, rec.Body.Bytes()) + require.Len(t, snapshot.Steps, 1) + require.Equal(t, int64(5), snapshot.Steps[0].OrderRevision) +} + func TestHTTPGetWorkflowSnapshotReturnsNotFoundForUnknownWorkflow(t *testing.T) { repo := workflowFixture() h := newWorkflowHandlers(t, repo, &stubStepLister{}) diff --git a/apps/backend/internal/task/models/step_order.go b/apps/backend/internal/task/models/step_order.go new file mode 100644 index 0000000000..db53cf6c77 --- /dev/null +++ b/apps/backend/internal/task/models/step_order.go @@ -0,0 +1,57 @@ +package models + +import "time" + +// StepOrderLess reports whether left sorts before right under +// REQ-TASKS-KANBAN-TASK-REORDERING-001.1: position ascending, then priority +// rank (critical, high, medium, low, then any other or absent value), then +// queued_at ascending — an absent queued_at reads as the task's created_at +// (.36's alignment with the SQL promotion query's +// COALESCE(queued_at, created_at), rather than skipping the key) — then +// created_at ascending, then id ascending. Every key is a named column and id +// is unique, so this is a total order for any two distinct tasks. +// +// The single source of truth for this ordering: the WIP promotion +// comparators (task/service, orchestrator) and the reorder repository both +// delegate here so the three cannot drift apart again. +func StepOrderLess(left, right *Task) bool { + if left.Position != right.Position { + return left.Position < right.Position + } + if lp, rp := stepOrderPriorityRank(left.Priority), stepOrderPriorityRank(right.Priority); lp != rp { + return lp < rp + } + leftQueuedAt, rightQueuedAt := stepOrderEffectiveQueuedAt(left), stepOrderEffectiveQueuedAt(right) + if !leftQueuedAt.Equal(rightQueuedAt) { + return leftQueuedAt.Before(rightQueuedAt) + } + if !left.CreatedAt.Equal(right.CreatedAt) { + return left.CreatedAt.Before(right.CreatedAt) + } + return left.ID < right.ID +} + +func stepOrderPriorityRank(priority string) int { + switch priority { + case TaskPriorityCritical: + return 0 + case TaskPriorityHigh: + return 1 + case TaskPriorityMedium: + return 2 + case TaskPriorityLow: + return 3 + default: + return 4 + } +} + +// stepOrderEffectiveQueuedAt is the queued_at key StepOrderLess and +// REQ-TASKS-KANBAN-TASK-REORDERING-001.36 name: a task's own queued_at, or +// its created_at when it was never queued. +func stepOrderEffectiveQueuedAt(task *Task) time.Time { + if task.QueuedAt != nil { + return *task.QueuedAt + } + return task.CreatedAt +} diff --git a/apps/backend/internal/task/models/step_order_test.go b/apps/backend/internal/task/models/step_order_test.go new file mode 100644 index 0000000000..03eaaeabaa --- /dev/null +++ b/apps/backend/internal/task/models/step_order_test.go @@ -0,0 +1,89 @@ +package models + +import ( + "testing" + "time" +) + +func TestStepOrderLess(t *testing.T) { + earlier := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + later := earlier.Add(time.Hour) + + cases := []struct { + name string + left, right *Task + want bool + }{ + { + name: "lower position wins", + left: &Task{ID: "a", Position: 1, Priority: "low"}, + right: &Task{ID: "b", Position: 2, Priority: "critical"}, + want: true, + }, + { + name: "critical beats high at equal position", + left: &Task{ID: "a", Position: 1, Priority: "critical"}, + right: &Task{ID: "b", Position: 1, Priority: "high"}, + want: true, + }, + { + name: "known priority beats an unrecognized one", + left: &Task{ID: "a", Position: 1, Priority: "low"}, + right: &Task{ID: "b", Position: 1, Priority: "whenever"}, + want: true, + }, + { + name: "a nil queued_at falls back to created_at instead of skipping the key", + left: &Task{ID: "a", Position: 1, Priority: "medium", QueuedAt: nil, CreatedAt: earlier}, + right: &Task{ID: "b", Position: 1, Priority: "medium", QueuedAt: &earlier, CreatedAt: later}, + want: true, + }, + { + // left's fallback (its own created_at, later) loses to right's + // earlier explicit queued_at, even though right's created_at is + // later still - discriminates the fallback from two wrong + // implementations that would both also report true here: (a) + // treating a nil queued_at as an always-smallest sentinel, and + // (b) comparing created_at directly instead of queued_at. + name: "a nil queued_at's created_at fallback loses to an earlier explicit queued_at", + left: &Task{ID: "a", Position: 1, Priority: "medium", QueuedAt: nil, CreatedAt: later}, + right: &Task{ID: "b", Position: 1, Priority: "medium", QueuedAt: &earlier, CreatedAt: later.Add(time.Hour)}, + want: false, + }, + { + // The mirror case: left's fallback (its own created_at, earlier) + // beats right's later explicit queued_at, even though right's + // created_at is earlier still - discriminates the fallback from + // comparing created_at directly instead of queued_at. + name: "a nil queued_at's created_at fallback beats a later explicit queued_at", + left: &Task{ID: "a", Position: 1, Priority: "medium", QueuedAt: nil, CreatedAt: earlier}, + right: &Task{ID: "b", Position: 1, Priority: "medium", QueuedAt: &later, CreatedAt: earlier.Add(-time.Hour)}, + want: true, + }, + { + name: "created_at breaks a queued_at tie", + left: &Task{ID: "a", Position: 1, Priority: "medium", QueuedAt: &earlier, CreatedAt: earlier}, + right: &Task{ID: "b", Position: 1, Priority: "medium", QueuedAt: &earlier, CreatedAt: later}, + want: true, + }, + { + name: "id breaks a full tie", + left: &Task{ID: "a", Position: 1, Priority: "medium", QueuedAt: &earlier, CreatedAt: earlier}, + right: &Task{ID: "b", Position: 1, Priority: "medium", QueuedAt: &earlier, CreatedAt: earlier}, + want: true, + }, + { + name: "identical tasks are not before each other", + left: &Task{ID: "same", Position: 1, Priority: "medium", QueuedAt: &earlier, CreatedAt: earlier}, + right: &Task{ID: "same", Position: 1, Priority: "medium", QueuedAt: &earlier, CreatedAt: earlier}, + want: false, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := StepOrderLess(tc.left, tc.right); got != tc.want { + t.Fatalf("StepOrderLess = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/apps/backend/internal/task/repository/interface.go b/apps/backend/internal/task/repository/interface.go index 2c3f8d75cb..91df26fef4 100644 --- a/apps/backend/internal/task/repository/interface.go +++ b/apps/backend/internal/task/repository/interface.go @@ -23,6 +23,8 @@ var ErrTaskEnvironmentNotFound = repoerrors.ErrTaskEnvironmentNotFound var ErrTaskEnvironmentOwnershipChanged = repoerrors.ErrTaskEnvironmentOwnershipChanged var ErrWIPLimitExceeded = wfmodels.ErrWIPLimitExceeded var ErrExternalIDConflict = repoerrors.ErrExternalIDConflict +var ErrStepChanged = repoerrors.ErrStepChanged +var ErrInvalidReorder = repoerrors.ErrInvalidReorder // WorkspaceRepository handles workspace CRUD. type WorkspaceRepository interface { @@ -55,7 +57,17 @@ type TaskRepository interface { CreateTask(ctx context.Context, task *models.Task) error GetTask(ctx context.Context, id string) (*models.Task, error) GetTasksByIDs(ctx context.Context, ids []string) ([]*models.Task, error) + // UpdateTask writes the full task row, preserving whatever position is + // currently persisted regardless of what task.Position holds — a + // pre-transaction read is not authoritative once a concurrent reorder or + // arrival may have moved the row (REQ-TASKS-KANBAN-TASK-REORDERING-001.28/ + // .31). Use UpdateTaskWithExplicitPosition for the one caller that must + // write a literal position. UpdateTask(ctx context.Context, task *models.Task) error + // UpdateTaskWithExplicitPosition is UpdateTask's counterpart that writes + // task.Position as given, for the generic task-update API's explicit + // position field (predates REQ-TASKS-KANBAN-TASK-REORDERING-001). + UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error DeleteTask(ctx context.Context, id string) error ListTasks(ctx context.Context, workflowID string) ([]*models.Task, error) ListTasksByWorkspace(ctx context.Context, workspaceID, workflowID, repositoryID, query string, page, pageSize int, sort string, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) diff --git a/apps/backend/internal/task/repository/repoerrors/errors.go b/apps/backend/internal/task/repository/repoerrors/errors.go index 4be41666f0..0b6d4e6e4f 100644 --- a/apps/backend/internal/task/repository/repoerrors/errors.go +++ b/apps/backend/internal/task/repository/repoerrors/errors.go @@ -82,3 +82,16 @@ var ErrTaskCleanupInProgress = errors.New("task cleanup in progress") // did. See task/service.MoveTaskOptions.ExpectedWorkflowID for the caller // contract. var ErrWorkflowResolutionConflict = errors.New("task workflow changed since resolution") + +// ErrStepChanged reports that a reorder's submitted band membership no +// longer exactly matches the band's persisted membership +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.19). The whole request is rejected +// atomically and the caller reconciles to the authoritative order the error +// carries, silently rather than showing the user a message. +var ErrStepChanged = errors.New("step_changed") + +// ErrInvalidReorder reports a malformed reorder request +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.18): no valid band named, an empty or +// duplicate id list, or an id that names a task outside the named step/band. +// Unlike ErrStepChanged this implies nothing about the persisted order. +var ErrInvalidReorder = errors.New("invalid_reorder") diff --git a/apps/backend/internal/task/repository/sqlite/base.go b/apps/backend/internal/task/repository/sqlite/base.go index 625cc517c0..3f2b61e1be 100644 --- a/apps/backend/internal/task/repository/sqlite/base.go +++ b/apps/backend/internal/task/repository/sqlite/base.go @@ -26,6 +26,14 @@ type Repository struct { queuePurgePrepare func(context.Context, string) queuePurgeNotify func(context.Context, string) queueSessionPurgeNotify func(context.Context, string, string) + // stepArrivalLocks holds one *sync.Mutex per workflow step, serializing + // this process's own arrival-position writes (assignArrivalPosition) + // against each other for the same step. lockWorkflowStepForWrite alone + // only serializes within a single transaction; a caller assigning + // positions to several tasks across several sequential transactions (a + // bulk move) needs this held across the whole sequence — see + // LockStepArrivalsForBatch. + stepArrivalLocks sync.Map // clockNow is a test-only clock seam. Set it before any concurrent // repository call; it carries no synchronization. clockNow func() time.Time @@ -93,6 +101,38 @@ type Repository struct { // than only the injected failpoint errors). Nil in production and in // every test but the one that sets it. usageEventPreRollupHook func() + // reorderPreWriteHook is a test-only synchronization seam, called (if + // set) inside ReorderStepTasks after stepID's current membership has + // been read and resolved against the caller's ordered id list, but + // before the renumbering write loop begins. Like usageEventPreRollupHook + // above, it does not alter control flow; it exists so a Postgres test + // can pause a real production reorder transaction at this exact + // boundary - after it has locked stepID and observed a task's + // still-current membership, but before it writes - to construct a real + // interleaving against a concurrent writer that changes that task's step + // membership in between. Nil in production and in every test but the + // one that sets it. + reorderPreWriteHook func() + // taskStepLockBeforeAcquireHook is a test-only synchronization seam, + // called (if set) inside lockTaskStepForWrite's retry loop after it has + // read a task's candidate step but before it locks that step - the exact + // gap a concurrent move of the same task can land in. It exists so a + // Postgres test can pause there and commit a real concurrent move, + // proving the confirm-and-retry loop settles on the task's post-move + // step rather than the stale one it read. Nil in production and in + // every test but the one that sets it. + taskStepLockBeforeAcquireHook func(candidateStepID string) + // taskRowReconfirmHook is a test-only synchronization seam, called (if + // set) inside lockTaskRowIfStepless right before it re-locks a task's + // own row to confirm the task still has no step - the exact gap a + // concurrent reattachment of that task can land in, between + // lockTaskStepForWrite releasing a stale step's lock (or finding none on + // its first read) and re-verifying there is truly nothing left to + // protect. It exists so a Postgres test can pause there and commit a + // real concurrent reattachment, proving the retry locks the task's new + // step instead of returning as if there were none. Nil in production + // and in every test but the one that sets it. + taskRowReconfirmHook func() // stepEntryDispatcher fires a step's session-independent on_enter // sequence after a registered step-transition writer commits. Nil-safe // (see dispatchStepEntry in step_entry_dispatch.go): unset in every diff --git a/apps/backend/internal/task/repository/sqlite/base_migrations.go b/apps/backend/internal/task/repository/sqlite/base_migrations.go index 4f942f4240..aeba76d806 100644 --- a/apps/backend/internal/task/repository/sqlite/base_migrations.go +++ b/apps/backend/internal/task/repository/sqlite/base_migrations.go @@ -323,6 +323,10 @@ func (r *Repository) runMigrations() error { r.migrate.Apply("workflow_steps.profile_session_start_policy", `ALTER TABLE workflow_steps ADD COLUMN profile_session_start_policy TEXT NOT NULL DEFAULT 'reuse'`) _ = r.migrate.Apply("workflow_steps.profile_session_end_policy", `ALTER TABLE workflow_steps ADD COLUMN profile_session_end_policy TEXT NOT NULL DEFAULT 'park'`) _ = r.migrate.Apply("workflow_steps.session_target", `ALTER TABLE workflow_steps ADD COLUMN session_target TEXT`) + // Kanban task reordering (REQ-TASKS-KANBAN-TASK-REORDERING-001.25). Kept + // compatible with databases whose workflow repository has not replayed its + // own migrations yet, same as the columns above. + _ = r.migrate.Apply("workflow_steps.order_revision", `ALTER TABLE workflow_steps ADD COLUMN order_revision INTEGER NOT NULL DEFAULT 0`) // Slack-style unread divider: the read cursor a session advances to the // latest message id whenever it becomes the visible chat panel. The diff --git a/apps/backend/internal/task/repository/sqlite/base_schema.go b/apps/backend/internal/task/repository/sqlite/base_schema.go index 1442fc772c..3e71285f54 100644 --- a/apps/backend/internal/task/repository/sqlite/base_schema.go +++ b/apps/backend/internal/task/repository/sqlite/base_schema.go @@ -290,6 +290,7 @@ func (r *Repository) ensureRunnerProjectionTables() error { auto_advance_requires_signal INTEGER NOT NULL DEFAULT 0, cancel_triggers_turn_complete INTEGER NOT NULL DEFAULT 0, complete_task_on_enter INTEGER NOT NULL DEFAULT 0, + order_revision INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP )`); err != nil { diff --git a/apps/backend/internal/task/repository/sqlite/next_queued_task_ordering_pin_test.go b/apps/backend/internal/task/repository/sqlite/next_queued_task_ordering_pin_test.go index 386978b622..2e90e86525 100644 --- a/apps/backend/internal/task/repository/sqlite/next_queued_task_ordering_pin_test.go +++ b/apps/backend/internal/task/repository/sqlite/next_queued_task_ordering_pin_test.go @@ -117,6 +117,14 @@ func mustCreateOrderedTaskWithCreatedAt(t *testing.T, ctx context.Context, repo if _, err := repo.db.Exec(repo.db.Rebind(`UPDATE tasks SET created_at = ? WHERE id = ?`), createdAt, id); err != nil { t.Fatalf("backdate created_at(%s): %v", id, err) } + // CreateTask now assigns its own arrival position + // (REQ-TASKS-KANBAN-TASK-REORDERING-001.28), overwriting the caller's + // literal. This ladder test deliberately puts several tasks at the same + // position to exercise the tiebreakers below it, so restore the fixture's + // intended value the same way created_at is backdated above. + if _, err := repo.db.Exec(repo.db.Rebind(`UPDATE tasks SET position = ? WHERE id = ?`), position, id); err != nil { + t.Fatalf("restore position(%s): %v", id, err) + } } // setQueuedAt marks a task as queued for destinationStepID with an explicit diff --git a/apps/backend/internal/task/repository/sqlite/task.go b/apps/backend/internal/task/repository/sqlite/task.go index ddca362aa8..c2293677c3 100644 --- a/apps/backend/internal/task/repository/sqlite/task.go +++ b/apps/backend/internal/task/repository/sqlite/task.go @@ -8,6 +8,7 @@ import ( "fmt" "sort" "strings" + "sync" "time" "github.com/google/uuid" @@ -27,6 +28,10 @@ import ( v1 "github.com/kandev/kandev/pkg/api/v1" ) +// forUpdateClause is the Postgres row-lock suffix appended to a conditionally +// built SELECT. Not used on SQLite (dialect.IsPostgres gates every call site). +const forUpdateClause = " FOR UPDATE" + // defaultTaskAlias is the fallback alias the projection helpers use when // the caller passes an empty string — i.e., when the SELECT references // the `tasks` table directly rather than through a join alias. @@ -216,6 +221,14 @@ func (r *Repository) CreateTaskWithWorkflowStepAdmission( if err := r.prepareTaskForCreate(task); err != nil { return err } + + // The actual placement (target or feeder) is decided inside tx by + // applyAdmissionPlacement below, so both candidates' arrival locks must + // be held before tx opens — see withStepArrivalLocks. + var unlock func() + ctx, unlock = r.withStepArrivalLocks(ctx, targetStepID, feederStepID) + defer unlock() + tx, err := r.db.BeginTx(ctx, nil) if err != nil { return err @@ -240,6 +253,14 @@ func (r *Repository) CreateTaskWithWorkflowStepAdmission( return err } + // task.WorkflowStepID is now the actual placement (target or feeder) — + // REQ-TASKS-KANBAN-TASK-REORDERING-001.28 applies to creation too. Both + // candidate steps are already locked above (lockWorkflowStepsForAdmission), + // so this only needs the read. + if err := r.assignArrivalPosition(ctx, tx, task, task.WorkflowStepID); err != nil { + return err + } + entryID, err := r.insertTaskTx(ctx, tx, task) if err != nil { return err @@ -296,6 +317,16 @@ func (r *Repository) createTask(ctx context.Context, task *models.Task, targetSt return err } + // task.WorkflowStepID (not targetStepID) is the row's actual destination + // — see the assignArrivalPosition call below — and is already final at + // this point, so the arrival lock can be taken before tx opens. + isArrival := task.WorkflowStepID != "" && !isHiddenArrival(task) + if isArrival { + var unlock func() + ctx, unlock = r.withStepArrivalLocks(ctx, task.WorkflowStepID) + defer unlock() + } + tx, err := r.db.BeginTx(ctx, nil) if err != nil { return err @@ -317,6 +348,17 @@ func (r *Repository) createTask(ctx context.Context, task *models.Task, targetSt return err } + // Creation is an arrival too (REQ-TASKS-KANBAN-TASK-REORDERING-001.28): + // task.WorkflowStepID, not targetStepID, is the row's actual destination + // — targetStepID is "" whenever this runs through the bare CreateTask + // path (no WIP check requested), which is the common case since most + // steps carry no WIP limit. + if isArrival { + if err := r.assignArrivalPosition(ctx, tx, task, task.WorkflowStepID); err != nil { + return err + } + } + entryID, err := r.insertTaskTx(ctx, tx, task) if err != nil { if rollbackErr := tx.Rollback(); rollbackErr != nil { @@ -411,7 +453,7 @@ func (r *Repository) lockWorkflowStepsForAdmission(ctx context.Context, tx *sql. ids[0], ids[1] = ids[1], ids[0] } for _, id := range ids { - if err := lockWorkflowStepForCapacity(ctx, tx, r.db.DriverName(), r.db.Rebind, id); err != nil { + if err := lockWorkflowStepForWrite(ctx, tx, r.db.DriverName(), r.db.Rebind, id); err != nil { return err } } @@ -434,7 +476,7 @@ func (r *Repository) ensureWorkflowStepCapacity(ctx context.Context, tx *sql.Tx, if limit <= 0 { return nil } - if err := lockWorkflowStepForCapacity(ctx, tx, r.db.DriverName(), r.db.Rebind, targetStepID); err != nil { + if err := lockWorkflowStepForWrite(ctx, tx, r.db.DriverName(), r.db.Rebind, targetStepID); err != nil { return err } var occupants int @@ -453,12 +495,416 @@ func (r *Repository) ensureWorkflowStepCapacity(ctx context.Context, tx *sql.Tx, return nil } -func lockWorkflowStepForCapacity(ctx context.Context, tx *sql.Tx, driver string, rebind func(string) string, stepID string) error { +// lockWorkflowStepForWrite serializes callers writing tasks.position for the +// same step: a reorder's renumbering, and an arrival's max(position)+1 +// read-then-write, must not straddle each other. On SQLite the writer pool +// is a single connection (db.SetMaxOpenConns(1)), so any caller running this +// inside its own write transaction already gets that serialization for free +// and this is a no-op. On Postgres it takes the step row's FOR UPDATE lock +// for the rest of the transaction. A stepID with no matching row has no +// concurrent writer to serialize against either (nothing else can look it +// up), so a missing row is not an error here — callers that need the step +// to exist verify that separately. +func lockWorkflowStepForWrite(ctx context.Context, tx interface { + QueryRowContext(context.Context, string, ...any) *sql.Row +}, driver string, rebind func(string) string, stepID string) error { if !dialect.IsPostgres(driver) { return nil } var lockedID string - return tx.QueryRowContext(ctx, rebind(`SELECT id FROM workflow_steps WHERE id = ? FOR UPDATE`), stepID).Scan(&lockedID) + err := tx.QueryRowContext(ctx, rebind(`SELECT id FROM workflow_steps WHERE id = ? FOR UPDATE`), stepID).Scan(&lockedID) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + return err +} + +// lockTaskStepForWriteSavepoint is the name of the per-attempt Postgres +// savepoint lockTaskStepForWrite wraps each lock attempt in, so a retry can +// release a stale step's lock (see the function doc) via ROLLBACK TO +// SAVEPOINT. Reused across attempts: ROLLBACK TO SAVEPOINT does not destroy +// the named savepoint, so a later SAVEPOINT with the same name nests rather +// than replaces it. Each attempt still releases its own lock (via RELEASE or +// ROLLBACK TO) before the next attempt locks a different step, bounded by +// maxAttempts; every savepoint, nested or not, is discarded when the +// surrounding transaction ends. +const lockTaskStepForWriteSavepoint = "lock_task_step_for_write" + +// taskStepLockSavepointTx is the minimal transaction surface the three +// lockTaskStepForWrite savepoint helpers below need. +type taskStepLockSavepointTx interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) +} + +// beginTaskStepLockSavepoint opens the per-attempt savepoint a Postgres +// caller can later release or roll back to; a no-op on every other dialect. +func beginTaskStepLockSavepoint(ctx context.Context, tx taskStepLockSavepointTx, usePostgres bool) error { + if !usePostgres { + return nil + } + if _, err := tx.ExecContext(ctx, "SAVEPOINT "+lockTaskStepForWriteSavepoint); err != nil { + return fmt.Errorf("lockTaskStepForWrite: savepoint: %w", err) + } + return nil +} + +// releaseTaskStepLockSavepoint keeps the attempt's step lock for the rest of +// the transaction. +func releaseTaskStepLockSavepoint(ctx context.Context, tx taskStepLockSavepointTx, usePostgres bool) error { + if !usePostgres { + return nil + } + if _, err := tx.ExecContext(ctx, "RELEASE SAVEPOINT "+lockTaskStepForWriteSavepoint); err != nil { + return fmt.Errorf("lockTaskStepForWrite: release savepoint: %w", err) + } + return nil +} + +// rollbackTaskStepLockSavepoint releases the attempt's step lock: the task +// moved to a different step, or left its step entirely, while the lock was +// held, so this attempt's step is no longer the one to protect. +func rollbackTaskStepLockSavepoint(ctx context.Context, tx taskStepLockSavepointTx, usePostgres bool) error { + if !usePostgres { + return nil + } + if _, err := tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT "+lockTaskStepForWriteSavepoint); err != nil { + return fmt.Errorf("lockTaskStepForWrite: rollback to savepoint: %w", err) + } + return nil +} + +// resolveTaskStepIDForLock resolves the step lockTaskStepForWrite's current +// attempt should lock: a plain read of taskID's workflow_step_id, falling +// back to lockTaskRowIfStepless when that read finds none. found reports +// whether there is a step to lock at all; when it does not, +// lockTaskRowIfStepless has already secured the task's own row instead, and +// the caller should return success rather than treat the missing step as an +// error. +func (r *Repository) resolveTaskStepIDForLock(ctx context.Context, tx interface { + QueryRowContext(context.Context, string, ...any) *sql.Row + ExecContext(context.Context, string, ...any) (sql.Result, error) +}, usePostgres bool, taskID string) (stepID string, found bool, err error) { + stepID, found, err = r.readTaskWorkflowStepID(ctx, tx, taskID, false) + if err != nil || found { + return stepID, found, err + } + return r.lockTaskRowIfStepless(ctx, tx, usePostgres, taskID) +} + +// lockTaskStepForWrite locks the workflow step taskID currently belongs to +// (see lockWorkflowStepForWrite), so a caller hiding or removing the task +// (archive, delete, unarchive) cannot straddle a concurrent ReorderStepTasks +// of that same step: whichever acquires the step's row lock first runs to +// completion before the other proceeds. A task with no step has no step to +// lock against, but lockTaskRowIfStepless still locks the task's own row in +// that case (unless the row itself no longer exists), so a concurrent +// reattachment cannot slip the task into a step behind the caller's back. +// +// The step to lock is resolved with a plain read and re-confirmed with a +// second, locked read taken only after that step's lock is held - not with +// a single locked read up front. Locking the task row before the step would +// invert this package's established order (step lock(s) acquired before any +// task-row lock — see rebaseTaskForStepAdmissionCAS's call to +// readTaskStepInTx, which runs after updateTaskWithWorkflowStepAdmission has +// already taken its step locks) and could deadlock against a concurrent +// CAS-guarded move doing the reverse. If a move changes the task's step in +// the gap between the plain read and the step lock, the confirming re-read +// (safe to take FOR UPDATE here, since the step lock already held orders it +// correctly) detects the mismatch and this retries against the task's real +// current step. +// +// A retry must not simply move on to the new step while still holding the +// stale one: this package's other multi-step lockers (lockWorkflowStepsForAdmission) +// always acquire two step locks in ascending sorted order specifically to +// avoid an AB-BA deadlock against each other, and on Postgres a row lock is +// held until end of transaction with no in-place unlock — so accumulating +// stale-then-new locks here would deadlock against a concurrent sorted-order +// locker taking the same two steps in the opposite order. Each attempt +// therefore runs inside its own savepoint: a mismatch rolls back to it +// (releasing that attempt's step lock, per Postgres subtransaction +// semantics) before the next attempt locks a different step, so this +// function never holds more than one step lock at a time. +func (r *Repository) lockTaskStepForWrite(ctx context.Context, tx interface { + QueryRowContext(context.Context, string, ...any) *sql.Row + ExecContext(context.Context, string, ...any) (sql.Result, error) +}, taskID string) error { + const maxAttempts = 10 + usePostgres := dialect.IsPostgres(r.db.DriverName()) + for attempt := 0; attempt < maxAttempts; attempt++ { + stepID, found, err := r.resolveTaskStepIDForLock(ctx, tx, usePostgres, taskID) + if err != nil { + return err + } + if !found { + return nil + } + if r.taskStepLockBeforeAcquireHook != nil { + r.taskStepLockBeforeAcquireHook(stepID) + } + if err := beginTaskStepLockSavepoint(ctx, tx, usePostgres); err != nil { + return err + } + if err := lockWorkflowStepForWrite(ctx, tx, r.db.DriverName(), r.db.Rebind, stepID); err != nil { + return err + } + confirmedStepID, found, err := r.readTaskWorkflowStepID(ctx, tx, taskID, true) + if err != nil { + return err + } + if !found { + // The task left its step entirely (workflow_step_id cleared, or + // the row is gone) while we waited for stepID's lock. + hasNewStep, err := r.releaseStaleStepAndRecheckStepless(ctx, tx, usePostgres, taskID) + if err != nil { + return err + } + if !hasNewStep { + return nil + } + continue + } + if confirmedStepID == stepID { + return releaseTaskStepLockSavepoint(ctx, tx, usePostgres) + } + // The task moved to a different step while we waited for stepID's + // lock. Release that now-stale step's lock before retrying against + // the task's real current step. + if err := rollbackTaskStepLockSavepoint(ctx, tx, usePostgres); err != nil { + return err + } + } + return fmt.Errorf("lockTaskStepForWrite: task %s kept changing steps", taskID) +} + +// releaseStaleStepAndRecheckStepless handles lockTaskStepForWrite's +// confirming read finding the task no longer in the step it just locked. It +// releases that now-stale step's lock, then re-verifies under +// lockTaskRowIfStepless rather than trusting the confirming read's snapshot: +// see that function's doc for why a naked rollback here would leave the +// caller's subsequent mutation unprotected against a concurrent +// reattachment. hasNewStep reports whether the task has since gained a +// different step to retry the loop against, as opposed to having none at +// all (in which case lockTaskRowIfStepless has already secured the task's +// own row, and the caller should return success). +func (r *Repository) releaseStaleStepAndRecheckStepless(ctx context.Context, tx interface { + QueryRowContext(context.Context, string, ...any) *sql.Row + ExecContext(context.Context, string, ...any) (sql.Result, error) +}, usePostgres bool, taskID string) (hasNewStep bool, err error) { + if err := rollbackTaskStepLockSavepoint(ctx, tx, usePostgres); err != nil { + return false, err + } + _, found, err := r.lockTaskRowIfStepless(ctx, tx, usePostgres, taskID) + if err != nil { + return false, err + } + return found, nil +} + +// lockTaskRowIfStepless is called whenever lockTaskStepForWrite's read of +// taskID - the unlocked first read of an attempt, or the confirming read +// after a step lock turned out stale - finds no current step. Releasing a +// stale step's savepoint (ROLLBACK TO SAVEPOINT) frees every lock taken +// since that savepoint, not only the step: the confirming read's own FOR +// UPDATE on the task's row goes with it, so returning success right after +// that rollback would leave the caller's subsequent mutation (archive, +// delete, unarchive) racing a concurrent reattachment with nothing locked +// at all. +// +// This re-verifies under its own savepoint, locking ONLY the task's own +// row - never a step, so this cannot invert lockTaskStepForWrite's +// documented step-lock-before-task-row-lock order. If the task still has +// no step, the savepoint is released and that row lock kept for the rest +// of the transaction: nothing can reattach the task without first taking +// it, so the caller's mutation is protected even though there is no step +// left to lock. If the task has gained a step since the read that led +// here - a reattachment landing in this exact gap - the savepoint is +// rolled back (releasing this function's own row lock, so the retry it +// triggers never stacks a task-row lock underneath the step lock it is +// about to request) and the new step id is returned so +// lockTaskStepForWrite's loop can lock it the normal way instead. +func (r *Repository) lockTaskRowIfStepless(ctx context.Context, tx interface { + QueryRowContext(context.Context, string, ...any) *sql.Row + ExecContext(context.Context, string, ...any) (sql.Result, error) +}, usePostgres bool, taskID string) (string, bool, error) { + if r.taskRowReconfirmHook != nil { + r.taskRowReconfirmHook() + } + if err := beginTaskStepLockSavepoint(ctx, tx, usePostgres); err != nil { + return "", false, err + } + stepID, found, err := r.readTaskWorkflowStepID(ctx, tx, taskID, true) + if err != nil { + return "", false, err + } + if found { + if err := rollbackTaskStepLockSavepoint(ctx, tx, usePostgres); err != nil { + return "", false, err + } + return stepID, true, nil + } + if err := releaseTaskStepLockSavepoint(ctx, tx, usePostgres); err != nil { + return "", false, err + } + return "", false, nil +} + +// readTaskWorkflowStepID reads taskID's current workflow_step_id. forUpdate +// requests Postgres' FOR UPDATE, which is only safe to set once any step +// lock this read must be ordered after is already held (see +// lockTaskStepForWrite's confirming re-read). +func (r *Repository) readTaskWorkflowStepID(ctx context.Context, tx interface { + QueryRowContext(context.Context, string, ...any) *sql.Row +}, taskID string, forUpdate bool) (stepID string, found bool, err error) { + query := `SELECT workflow_step_id FROM tasks WHERE id = ?` + if forUpdate && dialect.IsPostgres(r.db.DriverName()) { + query += forUpdateClause + } + err = tx.QueryRowContext(ctx, r.db.Rebind(query), taskID).Scan(&stepID) + if errors.Is(err, sql.ErrNoRows) { + return "", false, nil + } + if err != nil { + return "", false, err + } + if stepID == "" { + return "", false, nil + } + return stepID, true, nil +} + +// stepArrivalLockHeldKey marks, in a context, that the caller already holds +// stepArrivalMutex(stepID) for the rest of this call chain — see +// withStepArrivalLocks. +type stepArrivalLockHeldKey struct{ stepID string } + +func contextWithStepArrivalLockHeld(ctx context.Context, stepID string) context.Context { + return context.WithValue(ctx, stepArrivalLockHeldKey{stepID}, true) +} + +func stepArrivalLockAlreadyHeld(ctx context.Context, stepID string) bool { + held, _ := ctx.Value(stepArrivalLockHeldKey{stepID}).(bool) + return held +} + +// stepArrivalMutex returns the process-wide mutex serializing +// assignArrivalPosition calls for stepID, creating one on first use. +func (r *Repository) stepArrivalMutex(stepID string) *sync.Mutex { + mu, _ := r.stepArrivalLocks.LoadOrStore(stepID, &sync.Mutex{}) + return mu.(*sync.Mutex) +} + +// withStepArrivalLocks acquires stepArrivalMutex for every distinct, +// non-empty step in stepIDs (sorted first, so any two callers locking the +// same set always agree on acquisition order) and returns a context carrying +// that fact plus an unlock func releasing them in reverse. A step already +// marked held by an ancestor call (see the returned context of a previous +// call) is skipped, since Go's sync.Mutex is not reentrant. +// +// Every caller MUST acquire this lock before opening the database +// transaction that will call assignArrivalPosition for the same step(s) — +// never after. assignArrivalPosition itself no longer locks: it runs inside +// an already-open tx, and this process's SQLite pool holds only one +// connection, so a mutex taken there would already be holding that +// connection while it waits — a caller that (like a bulk move) takes the +// mutex first and only then opens its transaction can never get the +// connection back to finish, deadlocking against the one holding it. +// Locking before BeginTx keeps acquisition order identical (mutex, then +// connection) for every path. +// +// This also lets a caller that assigns several tasks' arrival positions +// across several sequential transactions — a bulk move — hold a step's +// arrival serialization across the whole sequence instead of only within +// each individual call's own transaction. A per-call-only lock leaves a +// window between transactions where an unrelated arrival (another create, +// move, WIP promotion, or automatic transition) into the same step can land +// in the middle of the batch's own sequence, breaking the batch-scoped +// consecutiveness REQ-TASKS-KANBAN-TASK-REORDERING-001.29 requires (see +// AC .29). The caller must call the returned unlock func exactly once, after +// its whole sequence completes. +func (r *Repository) withStepArrivalLocks(ctx context.Context, stepIDs ...string) (context.Context, func()) { + ids := dedupeSortedStepIDs(stepIDs) + unlocks := make([]func(), 0, len(ids)) + for _, id := range ids { + if stepArrivalLockAlreadyHeld(ctx, id) { + continue + } + mu := r.stepArrivalMutex(id) + mu.Lock() + ctx = contextWithStepArrivalLockHeld(ctx, id) + unlocks = append(unlocks, mu.Unlock) + } + return ctx, func() { + for i := len(unlocks) - 1; i >= 0; i-- { + unlocks[i]() + } + } +} + +func dedupeSortedStepIDs(stepIDs []string) []string { + seen := make(map[string]bool, len(stepIDs)) + ids := make([]string, 0, len(stepIDs)) + for _, id := range stepIDs { + if id == "" || seen[id] { + continue + } + seen[id] = true + ids = append(ids, id) + } + sort.Strings(ids) + return ids +} + +// LockStepArrivalsForBatch acquires every step in stepIDs as one +// ascending-ordered lock set for a caller outside this package +// (BulkMoveSelectedTasks, BulkMoveTasks) — see withStepArrivalLocks. The +// caller must pass the target step plus every distinct source step its +// batch will touch, known before the dispatch loop starts: locking only the +// target up front and letting each per-task MoveTask pick up its own source +// step mid-loop fixes the acquisition order at target-then-source, which +// deadlocks against an ordinary single move running the opposite direction +// between the same two steps. +func (r *Repository) LockStepArrivalsForBatch(ctx context.Context, stepIDs ...string) (context.Context, func()) { + return r.withStepArrivalLocks(ctx, stepIDs...) +} + +// assignArrivalPosition locks stepID for the rest of tx (see +// lockWorkflowStepForWrite) and sets task.Position to one greater than the +// highest position held by any non-hidden task already in stepID, or 0 when +// the step holds none (REQ-TASKS-KANBAN-TASK-REORDERING-001.28). Callers +// must run this inside the same transaction that performs the arriving +// insert/update, so the read cannot straddle a concurrent reorder's +// renumbering — see the design's worked displacement example. Ignores +// whatever position the caller had already set: every arrival path +// (creation, manual move, bulk move, WIP promotion, automatic workflow +// transition) computes it here instead. Callers must already hold stepID's +// arrival lock (withStepArrivalLocks) before opening tx. +func (r *Repository) assignArrivalPosition(ctx context.Context, tx *sql.Tx, task *models.Task, stepID string) error { + if err := lockWorkflowStepForWrite(ctx, tx, r.db.DriverName(), r.db.Rebind, stepID); err != nil { + return err + } + var maxPosition sql.NullInt64 + if err := tx.QueryRowContext(ctx, r.db.Rebind(` + SELECT MAX(position) FROM tasks + WHERE workflow_step_id = ? AND archived_at IS NULL AND is_ephemeral = 0`+andNotAutomationOrigin+` + `), stepID).Scan(&maxPosition); err != nil { + return err + } + if maxPosition.Valid { + task.Position = int(maxPosition.Int64) + 1 + } else { + task.Position = 0 + } + return nil +} + +// isHiddenArrival reports whether task is excluded from the arrival-position +// guarantee (REQ-TASKS-KANBAN-TASK-REORDERING-001.28's "non-hidden" +// qualifier): ephemeral (quick chat) or automation-run tasks are never shown +// in a step list, so locking a step to compute their position would be +// unobservable overhead. Archived is not checked here — nothing arrives +// pre-archived. +func isHiddenArrival(task *models.Task) bool { + return task.IsEphemeral || task.Origin == models.TaskOriginAutomationRun } // upsertRunnerInTx writes (or replaces) a 'runner' participant row for @@ -467,7 +913,7 @@ func lockWorkflowStepForCapacity(ctx context.Context, tx *sql.Tx, driver string, // // rebind is the caller's r.db.Rebind — required on Postgres, where the raw // "?" placeholders below are not valid bind syntax (unlike SQLite, which -// accepts them natively). Mirrors lockWorkflowStepForCapacity's pattern for +// accepts them natively). Mirrors lockWorkflowStepForWrite's pattern for // a free function that isn't a *Repository method. func upsertRunnerInTx(ctx context.Context, tx *sql.Tx, rebind func(string) string, stepID, taskID, agentProfileID string) error { if stepID == "" || taskID == "" || agentProfileID == "" { @@ -564,7 +1010,7 @@ func (r *Repository) UpdateTask(ctx context.Context, task *models.Task) error { } defer func() { _ = tx.Rollback() }() - entryID, markerEntryID, err := r.updateTaskTx(ctx, tx, task, metadata, "") + entryID, markerEntryID, err := r.updateTaskTx(ctx, tx, task, metadata, "", true) if err != nil { return err } @@ -599,7 +1045,7 @@ func (r *Repository) UpdateTaskIfWorkflowMatches(ctx context.Context, task *mode } defer func() { _ = tx.Rollback() }() - entryID, markerEntryID, err := r.updateTaskTx(ctx, tx, task, metadata, expectedWorkflowID) + entryID, markerEntryID, err := r.updateTaskTx(ctx, tx, task, metadata, expectedWorkflowID, true) if err != nil { return err } @@ -611,7 +1057,67 @@ func (r *Repository) UpdateTaskIfWorkflowMatches(ctx context.Context, task *mode return nil } -func (r *Repository) updateTaskTx(ctx context.Context, tx *sql.Tx, task *models.Task, metadata []byte, expectedWorkflowID string) (entryID string, markerEntryID int64, err error) { +// UpdateTaskWithExplicitPosition performs the same write as UpdateTask +// except it writes task.Position as given rather than preserving whatever +// is currently persisted. It is the one path allowed to write a +// caller-supplied position outside the reorder and arrival contract +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.28/.31): the generic task-update +// API's explicit position field, which predates that contract. +func (r *Repository) UpdateTaskWithExplicitPosition(ctx context.Context, task *models.Task) error { + metadata, err := json.Marshal(task.Metadata) + if err != nil { + metadata = []byte("{}") + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + + entryID, markerEntryID, err := r.updateTaskTx(ctx, tx, task, metadata, "", false) + if err != nil { + return err + } + + if err := tx.Commit(); err != nil { + return err + } + r.dispatchStepEntry(ctx, task.ID, task.WorkflowID, task.WorkflowStepID, entryID, markerEntryID) + return nil +} + +// readTaskPositionInTx reads a task's currently-persisted position inside +// the write transaction, taking the same Postgres row lock as +// readTaskStepInTx. A writer that must not disturb position (AC-TASKS- +// KANBAN-TASK-REORDERING-001.28/.31: only a renumbering or an arrival may +// rewrite it) uses this to observe the value after any concurrent reorder or +// arrival of the same row rather than before, instead of writing back +// whatever a pre-transaction read left in memory. +func (r *Repository) readTaskPositionInTx(ctx context.Context, tx *sql.Tx, taskID string) (position int, found bool, err error) { + query := `SELECT position FROM tasks WHERE id = ?` + if dialect.IsPostgres(r.db.DriverName()) { + query += forUpdateClause + } + err = tx.QueryRowContext(ctx, r.db.Rebind(query), taskID).Scan(&position) + if errors.Is(err, sql.ErrNoRows) { + return 0, false, nil + } + if err != nil { + return 0, false, err + } + return position, true, nil +} + +// updateTaskTx writes the full task row. preservePosition, true for every +// caller except the one path that honors an explicit caller-supplied +// position (UpdateTaskWithExplicitPosition), overwrites task.Position with +// the value read fresh inside this transaction rather than the one already +// in the struct: a caller's task object was read before this transaction +// began, and by the time this write commits a concurrent reorder or arrival +// (AC-TASKS-KANBAN-TASK-REORDERING-001.28) may have moved the row to a +// different position that this write must not clobber. +func (r *Repository) updateTaskTx(ctx context.Context, tx *sql.Tx, task *models.Task, metadata []byte, expectedWorkflowID string, preservePosition bool) (entryID string, markerEntryID int64, err error) { fromWorkflowID, fromStepID, found, err := r.readTaskStepInTx(ctx, tx, task.ID) if err != nil { return "", 0, err @@ -625,6 +1131,15 @@ func (r *Repository) updateTaskTx(ctx context.Context, tx *sql.Tx, task *models. // ladder over every other case (design's error-mapping table). return "", 0, fmt.Errorf("%w: %s", ErrTaskNotFound, task.ID) } + if preservePosition { + currentPosition, positionFound, posErr := r.readTaskPositionInTx(ctx, tx, task.ID) + if posErr != nil { + return "", 0, posErr + } + if positionFound { + task.Position = currentPosition + } + } if expectedWorkflowID != "" && fromWorkflowID != expectedWorkflowID { // Checked here, immediately before the UPDATE below and using the // same in-transaction, lock-protected read the ledger's "from" value @@ -707,14 +1222,17 @@ func (r *Repository) updateTaskTx(ctx context.Context, tx *sql.Tx, task *models. // UpdateTaskWithWorkflowStepAdmission atomically moves a task into a workflow // step. A limited full target stores the task in that destination as queued; -// it never rejects the move for WIP capacity. +// it never rejects the move for WIP capacity. sourceStepID is the step the +// task is leaving ("" when there is none, e.g. this task's first placement); +// see updateTaskWithWorkflowStepAdmission for why it must be locked too. func (r *Repository) UpdateTaskWithWorkflowStepAdmission( ctx context.Context, task *models.Task, + sourceStepID string, targetStepID string, limit int, ) (bool, error) { - admitted, _, err := r.updateTaskWithWorkflowStepAdmission(ctx, task, targetStepID, limit, nil, false, "", "", nil) + admitted, _, err := r.updateTaskWithWorkflowStepAdmission(ctx, task, sourceStepID, targetStepID, limit, nil, false, "", "", nil) return admitted, err } @@ -731,6 +1249,7 @@ func (r *Repository) UpdateTaskWithWorkflowStepAdmission( func (r *Repository) UpdateTaskWithWorkflowStepAdmissionAndState( ctx context.Context, task *models.Task, + sourceStepID string, targetStepID string, limit int, admittedState *v1.TaskState, @@ -738,7 +1257,7 @@ func (r *Repository) UpdateTaskWithWorkflowStepAdmissionAndState( expectedWorkflowID string, ) (bool, error) { admitted, _, err := r.updateTaskWithWorkflowStepAdmission( - ctx, task, targetStepID, limit, admittedState, queueExitPending, "", expectedWorkflowID, nil, + ctx, task, sourceStepID, targetStepID, limit, admittedState, queueExitPending, "", expectedWorkflowID, nil, ) return admitted, err } @@ -759,7 +1278,9 @@ func (r *Repository) UpdateTaskWithWorkflowStepAdmissionIfAtStep( targetStepID string, limit int, ) (applied bool, err error) { - _, applied, err = r.updateTaskWithWorkflowStepAdmission(ctx, task, targetStepID, limit, nil, false, expectedStepID, "", nil) + // expectedStepID doubles as the source step to lock: it is, by + // construction, the step this task is expected to currently occupy. + _, applied, err = r.updateTaskWithWorkflowStepAdmission(ctx, task, expectedStepID, targetStepID, limit, nil, false, expectedStepID, "", nil) return applied, err } @@ -770,8 +1291,10 @@ func (r *Repository) UpdateTaskWithWorkflowStepAdmissionForDeferredMove( limit int, record messagequeue.PendingMoveRecord, ) (admitted, applied bool, err error) { + // expectedStepID doubles as the source step to lock: it is, by + // construction, the step this task is expected to currently occupy. return r.updateTaskWithWorkflowStepAdmission( - ctx, task, targetStepID, limit, nil, false, expectedStepID, "", &record, + ctx, task, expectedStepID, targetStepID, limit, nil, false, expectedStepID, "", &record, ) } @@ -815,7 +1338,7 @@ func (r *Repository) MarkDeferredMoveAppliedForSession( if err != nil { return false, err } - if _, _, err := r.updateTaskTx(ctx, tx, task, metadata, ""); err != nil { + if _, _, err := r.updateTaskTx(ctx, tx, task, metadata, "", true); err != nil { return false, err } if err := r.deleteDeferredMoveGuardTx(ctx, tx, record); err != nil { @@ -987,9 +1510,68 @@ const ( pendingMoveOptionsKey = "options" ) +const admissionSourceRetryLimit = 8 + +type admissionSourceChangedError struct { + stepID string +} + +func (e *admissionSourceChangedError) Error() string { + if e.stepID == "" { + return "task source step changed" + } + return fmt.Sprintf("task source step changed to %s", e.stepID) +} + func (r *Repository) updateTaskWithWorkflowStepAdmission( ctx context.Context, task *models.Task, + sourceStepID string, + targetStepID string, + limit int, + admittedState *v1.TaskState, + queueExitPending bool, + expectedStepID string, + expectedWorkflowID string, + deferredMove *messagequeue.PendingMoveRecord, +) (admitted bool, applied bool, err error) { + currentSourceStepID := sourceStepID + for attempt := 0; attempt < admissionSourceRetryLimit; attempt++ { + attemptCtx, unlock := r.withStepArrivalLocks(ctx, targetStepID, currentSourceStepID) + admitted, applied, err = r.updateTaskWithWorkflowStepAdmissionAttempt( + attemptCtx, + task, + currentSourceStepID, + targetStepID, + limit, + admittedState, + queueExitPending, + expectedStepID, + expectedWorkflowID, + deferredMove, + ) + unlock() + + var changed *admissionSourceChangedError + if !errors.As(err, &changed) { + return admitted, applied, err + } + if expectedStepID != "" { + // CAS callers preserve their existing applied=false contract when + // the task has left the expected step. They must not retry against + // the new step and turn a stale transition into a new one. + return false, false, nil + } + currentSourceStepID = changed.stepID + } + return false, false, fmt.Errorf("task source step kept changing after %d attempts", admissionSourceRetryLimit) +} + +//nolint:cyclop,gocognit,funlen // Admission owns one transaction for locks, WIP state, and deferred moves. +func (r *Repository) updateTaskWithWorkflowStepAdmissionAttempt( + ctx context.Context, + task *models.Task, + sourceStepID string, targetStepID string, limit int, admittedState *v1.TaskState, @@ -1033,6 +1615,26 @@ func (r *Repository) updateTaskWithWorkflowStepAdmission( return false, false, err } } + if err := r.lockWorkflowStepsForAdmission(ctx, tx, targetStepID, sourceStepID); err != nil { + return false, false, err + } + + // The caller's sourceStepID came from an earlier task snapshot. Confirm it + // after the target and supplied source locks are held. A mismatch releases + // the whole transaction, and the outer loop retries with the task's real + // source so it acquires the complete sorted lock set before assigning an + // arrival position. This closes the single-move TOCTOU window without + // acquiring a newly discovered source beneath an already-held lock. + _, actualSourceStepID, found, err := r.readTaskStepInTx(ctx, tx, task.ID) + if err != nil { + return false, false, err + } + if !found { + return false, false, fmt.Errorf("%w: %s", ErrTaskNotFound, task.ID) + } + if actualSourceStepID != sourceStepID { + return false, false, &admissionSourceChangedError{stepID: actualSourceStepID} + } // AC-46/48 compare-and-swap precondition, only for CAS callers (see // rebaseTaskForStepAdmissionCAS for the full rationale). A mismatch means @@ -1049,7 +1651,14 @@ func (r *Repository) updateTaskWithWorkflowStepAdmission( } } - if err := lockWorkflowStepForCapacity(ctx, tx, r.db.DriverName(), r.db.Rebind, targetStepID); err != nil { + // updateTaskWithWorkflowStepAdmission is always an arrival: every caller + // (manual cross-step move, CAS-guarded plugin/engine transitions, and + // feeder/same-step promotion's UpdateTaskWithWorkflowStepAdmission + // fallback) admits into targetStepID from a different step, never a + // same-step reorder — see updateMovedTaskSameStep, which writes through + // plain UpdateTask instead. So the caller-supplied task.Position is + // always overwritten here (REQ-TASKS-KANBAN-TASK-REORDERING-001.28). + if err := r.assignArrivalPosition(ctx, tx, task, targetStepID); err != nil { return false, false, err } occupants, err := r.countAdmittedInTx(ctx, tx, targetStepID, task.ID) @@ -1098,7 +1707,7 @@ func (r *Repository) updateTaskWithWorkflowStepAdmission( if err != nil { metadata = []byte("{}") } - entryID, markerEntryID, err := r.updateTaskTx(ctx, tx, task, metadata, expectedWorkflowID) + entryID, markerEntryID, err := r.updateTaskTx(ctx, tx, task, metadata, expectedWorkflowID, false) if err != nil { return false, false, err } @@ -1911,13 +2520,20 @@ func (r *Repository) UpdateTaskIfWorkflowStepHasCapacity(ctx context.Context, ta metadata = []byte("{}") } + var unlock func() + ctx, unlock = r.withStepArrivalLocks(ctx, targetStepID) + defer unlock() + tx, err := r.db.BeginTx(ctx, nil) if err != nil { return err } defer func() { _ = tx.Rollback() }() - if err := lockWorkflowStepForCapacity(ctx, tx, r.db.DriverName(), r.db.Rebind, targetStepID); err != nil { + // Always an arrival into targetStepID (the fallback promotion path used + // when the atomic PromoteQueuedTaskIfWorkflowStepHasCapacity is + // unavailable) — REQ-TASKS-KANBAN-TASK-REORDERING-001.28. + if err := r.assignArrivalPosition(ctx, tx, task, targetStepID); err != nil { return err } @@ -2001,13 +2617,29 @@ func (r *Repository) PromoteQueuedTaskIfWorkflowStepHasCapacity( metadata = []byte("{}") } + var unlock func() + ctx, unlock = r.withStepArrivalLocks(ctx, destinationStepID, fromStepID) + defer unlock() + tx, err := r.db.BeginTx(ctx, nil) if err != nil { return false, err } defer func() { _ = tx.Rollback() }() - if err := lockWorkflowStepForCapacity(ctx, tx, r.db.DriverName(), r.db.Rebind, destinationStepID); err != nil { + // A promotion also leaves fromStepID's queued/admitted band, not only + // destinationStepID's, so a concurrent reorder of fromStepID must see + // the departure rather than commit a write against stale membership. + // Both locks are acquired here, sorted, mirroring + // updateTaskWithWorkflowStepAdmission's target+source pair. + if err := r.lockWorkflowStepsForAdmission(ctx, tx, destinationStepID, fromStepID); err != nil { + return false, err + } + + // This is always an arrival — a promotion enters destinationStepID from a + // queued band, never a reorder — so the caller-supplied task.Position is + // overwritten (REQ-TASKS-KANBAN-TASK-REORDERING-001.28). + if err := r.assignArrivalPosition(ctx, tx, task, destinationStepID); err != nil { return false, err } if limit > 0 { @@ -2110,7 +2742,15 @@ func (r *Repository) DeleteTaskWithVacatedStep(ctx context.Context, id string) ( return "", err } defer func() { _ = tx.Rollback() }() - // Serialize with session/worktree creation FIRST (task-row lock), then + // Lock the task's step first, so a concurrent ReorderStepTasks of that + // step cannot straddle this delete (see lockTaskStepForWrite): either the + // reorder's whole read-then-write runs first and sees this task still + // live, or it waits behind this transaction and then correctly excludes + // the now-deleted task instead of blindly renumbering a row that is gone. + if err := r.lockTaskStepForWrite(ctx, tx, id); err != nil { + return "", err + } + // Serialize with session/worktree creation next (task-row lock), then // capture the authoritative session set: a concurrent CreateTaskSession // holds the same task-row barrier, so every session committed before this // lock is visible to the capture and anything after blocks until the task @@ -2861,6 +3501,9 @@ func (r *Repository) ArchiveTask(ctx context.Context, id string) error { return err } defer func() { _ = tx.Rollback() }() + if err := r.lockTaskStepForWrite(ctx, tx, id); err != nil { + return err + } result, err := tx.ExecContext(ctx, r.db.Rebind(`UPDATE tasks SET archived_at = ?, updated_at = ? WHERE id = ?`), now, now, id) if err != nil { return err @@ -2911,6 +3554,9 @@ func (r *Repository) ArchiveTaskIfActiveWithVacatedStep( return "", false, err } defer func() { _ = tx.Rollback() }() + if err := r.lockTaskStepForWrite(ctx, tx, id); err != nil { + return "", false, err + } _, vacatedStepID, found, err := r.readTaskStepInTx(ctx, tx, id) if err != nil { return "", false, err @@ -3098,7 +3744,15 @@ func (r *Repository) UnarchiveTaskByCascade(ctx context.Context, id, cascadeID s if cascadeID == "" { return false, fmt.Errorf("cascadeID is required") } - result, err := r.db.ExecContext(ctx, r.db.Rebind(` + tx, err := r.db.BeginTxx(ctx, nil) + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback() }() + if err := r.lockTaskStepForWrite(ctx, tx, id); err != nil { + return false, err + } + result, err := tx.ExecContext(ctx, r.db.Rebind(` UPDATE tasks SET archived_at = NULL, archived_by_cascade_id = '', updated_at = ? WHERE id = ? AND archived_by_cascade_id = ? `), time.Now().UTC(), id, cascadeID) @@ -3106,6 +3760,9 @@ func (r *Repository) UnarchiveTaskByCascade(ctx context.Context, id, cascadeID s return false, err } rows, _ := result.RowsAffected() + if err := tx.Commit(); err != nil { + return false, err + } return rows > 0, nil } @@ -3116,7 +3773,15 @@ func (r *Repository) UnarchiveTaskByCascade(ctx context.Context, id, cascadeID s // rows are only restored via UnarchiveTaskByCascade. Returns whether a // row was actually updated. func (r *Repository) UnarchiveTask(ctx context.Context, id string) (bool, error) { - result, err := r.db.ExecContext(ctx, r.db.Rebind(` + tx, err := r.db.BeginTxx(ctx, nil) + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback() }() + if err := r.lockTaskStepForWrite(ctx, tx, id); err != nil { + return false, err + } + result, err := tx.ExecContext(ctx, r.db.Rebind(` UPDATE tasks SET archived_at = NULL, archived_by_cascade_id = '', updated_at = ? WHERE id = ? AND archived_at IS NOT NULL AND (archived_by_cascade_id = '' OR archived_by_cascade_id IS NULL) @@ -3125,6 +3790,9 @@ func (r *Repository) UnarchiveTask(ctx context.Context, id string) (bool, error) return false, err } rows, _ := result.RowsAffected() + if err := tx.Commit(); err != nil { + return false, err + } return rows > 0, nil } diff --git a/apps/backend/internal/task/repository/sqlite/task_arrival_position_postgres_test.go b/apps/backend/internal/task/repository/sqlite/task_arrival_position_postgres_test.go new file mode 100644 index 0000000000..31f5089463 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_arrival_position_postgres_test.go @@ -0,0 +1,119 @@ +package sqlite + +import ( + "context" + "fmt" + "sort" + "sync" + "testing" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/testutil" +) + +// TestPostgresAssignArrivalPositionToleratesMissingWorkflowStepRow proves +// task creation does not require a workflow_steps row to already exist on +// Postgres: lockWorkflowStepForWrite's FOR UPDATE select has nothing to lock +// when the step is not a real row, and that must not fail the arrival. +// Skips unless KANDEV_TEST_POSTGRES_DSN is set. +func TestPostgresAssignArrivalPositionToleratesMissingWorkflowStepRow(t *testing.T) { + db := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + repo, err := NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("init postgres schema: %v", err) + } + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "arrival-no-step-ws", Name: "Arrival no-step workspace"}); err != nil { + t.Fatalf("seed workspace: %v", err) + } + + const missingStep = "step-that-does-not-exist" + first := &models.Task{ID: "arrival-no-step-1", WorkspaceID: "arrival-no-step-ws", WorkflowID: "wf", WorkflowStepID: missingStep, Title: "first"} + if err := repo.CreateTask(ctx, first); err != nil { + t.Fatalf("CreateTask into a step with no workflow_steps row: %v", err) + } + if first.Position != 0 { + t.Fatalf("first arrival Position = %d, want 0", first.Position) + } + + second := &models.Task{ID: "arrival-no-step-2", WorkspaceID: "arrival-no-step-ws", WorkflowID: "wf", WorkflowStepID: missingStep, Title: "second"} + if err := repo.CreateTask(ctx, second); err != nil { + t.Fatalf("CreateTask (second arrival) into a step with no workflow_steps row: %v", err) + } + if second.Position != 1 { + t.Fatalf("second arrival Position = %d, want 1", second.Position) + } +} + +// TestPostgresAssignArrivalPositionSerializesConcurrentArrivals proves the +// FOR UPDATE lock actually does its job when the step row does exist: +// concurrent CreateTask calls into the same step must not race the +// max(position)+1 read against each other and produce duplicate positions. +// Skips unless KANDEV_TEST_POSTGRES_DSN is set. +func TestPostgresAssignArrivalPositionSerializesConcurrentArrivals(t *testing.T) { + const ( + concurrency = 8 + stepID = "arrival-concurrent-step" + ) + db := openIsolatedPostgresMultiConn(t, testutil.PostgresDSNFromEnv(t), concurrency) + repo, err := NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("init postgres schema: %v", err) + } + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "arrival-concurrent-ws", Name: "Arrival concurrent workspace"}); err != nil { + t.Fatalf("seed workspace: %v", err) + } + if _, err := db.Exec(db.Rebind(` + INSERT INTO workflow_steps (id, workflow_id, name, position) + VALUES (?, ?, ?, ?) + `), stepID, "arrival-concurrent-workflow", "Arrival concurrent step", 0); err != nil { + t.Fatalf("seed workflow step: %v", err) + } + + start := make(chan struct{}) + positions := make(chan int, concurrency) + errs := make(chan error, concurrency) + var wg sync.WaitGroup + for i := 0; i < concurrency; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-start + task := &models.Task{ + ID: fmt.Sprintf("arrival-concurrent-task-%d", i), WorkspaceID: "arrival-concurrent-ws", + WorkflowID: "arrival-concurrent-workflow", WorkflowStepID: stepID, Title: fmt.Sprintf("task %d", i), + } + if err := repo.CreateTask(ctx, task); err != nil { + errs <- err + return + } + positions <- task.Position + }(i) + } + close(start) + wg.Wait() + close(positions) + close(errs) + + for err := range errs { + t.Fatalf("concurrent CreateTask: %v", err) + } + got := make([]int, 0, concurrency) + for p := range positions { + got = append(got, p) + } + sort.Ints(got) + want := make([]int, concurrency) + for i := range want { + want[i] = i + } + if len(got) != len(want) { + t.Fatalf("got %d positions, want %d", len(got), len(want)) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("positions = %v, want a permutation of %v (duplicate or gap: lock did not serialize)", got, want) + } + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_move_source_lock_postgres_test.go b/apps/backend/internal/task/repository/sqlite/task_move_source_lock_postgres_test.go new file mode 100644 index 0000000000..14f8cd2ee3 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_move_source_lock_postgres_test.go @@ -0,0 +1,205 @@ +package sqlite + +import ( + "context" + "errors" + "sync" + "testing" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" + "github.com/kandev/kandev/internal/testutil" +) + +// TestPostgresCrossStepMoveLocksSourceStepAgainstConcurrentReorder proves +// updateTaskWithWorkflowStepAdmission locks the step a task is LEAVING, not +// only the one it is entering (REQ-TASKS-KANBAN-TASK-REORDERING-001.26): a +// ReorderStepTasks call racing a cross-step move of the source step must +// either serialize behind the move and see the departure (step_changed) or +// commit first and hand the move a still-consistent step. Before this lock +// existed, the two transactions could interleave on Postgres with the +// reorder's read of source-step membership straddling the move's write, +// letting the reorder commit against membership that had already changed +// underneath it with no conflict signal at all. +// Skips unless KANDEV_TEST_POSTGRES_DSN is set. +func TestPostgresCrossStepMoveLocksSourceStepAgainstConcurrentReorder(t *testing.T) { + const ( + sourceStep = "move-lock-source" + targetStep = "move-lock-target" + ) + db := openIsolatedPostgresMultiConn(t, testutil.PostgresDSNFromEnv(t), 2) + repo, err := NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("init postgres schema: %v", err) + } + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "move-lock-ws", Name: "Move lock workspace"}); err != nil { + t.Fatalf("seed workspace: %v", err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "move-lock-workflow", WorkspaceID: "move-lock-ws", Name: "Move lock workflow"}); err != nil { + t.Fatalf("seed workflow: %v", err) + } + for _, step := range []string{sourceStep, targetStep} { + if _, err := db.Exec(db.Rebind(` + INSERT INTO workflow_steps (id, workflow_id, name, position) + VALUES (?, ?, ?, ?) + `), step, "move-lock-workflow", step, 0); err != nil { + t.Fatalf("seed workflow step %s: %v", step, err) + } + } + + moving := &models.Task{ + ID: "move-lock-moving", WorkspaceID: "move-lock-ws", WorkflowID: "move-lock-workflow", + WorkflowStepID: sourceStep, Title: "Moving", WIPAdmitted: true, + } + stays := &models.Task{ + ID: "move-lock-stays", WorkspaceID: "move-lock-ws", WorkflowID: "move-lock-workflow", + WorkflowStepID: sourceStep, Title: "Stays", WIPAdmitted: true, + } + for _, task := range []*models.Task{moving, stays} { + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task %s: %v", task.ID, err) + } + } + + start := make(chan struct{}) + var wg sync.WaitGroup + var moveErr error + var reorderErr error + + wg.Add(2) + go func() { + defer wg.Done() + <-start + _, moveErr = repo.UpdateTaskWithWorkflowStepAdmission(ctx, moving, sourceStep, targetStep, 0) + }() + go func() { + defer wg.Done() + <-start + _, _, reorderErr = repo.ReorderStepTasks(ctx, sourceStep, ReorderBandAdmitted, []string{moving.ID, stays.ID}) + }() + close(start) + wg.Wait() + + if moveErr != nil { + t.Fatalf("cross-step move must always succeed (unlimited target): %v", moveErr) + } + if reorderErr != nil && !errors.Is(reorderErr, repoerrors.ErrStepChanged) { + t.Fatalf("reorder error = %v, want nil or ErrStepChanged", reorderErr) + } + + stored, err := repo.GetTask(ctx, moving.ID) + if err != nil { + t.Fatalf("reload moved task: %v", err) + } + if stored.WorkflowStepID != targetStep { + t.Fatalf("moved task ended up in step %q, want %q", stored.WorkflowStepID, targetStep) + } +} + +// TestPostgresAdmissionRechecksStaleSourceBeforeMoving proves a manual move +// cannot miss the task's real source step when its caller snapshot is stale. +// The reorder pauses after reading step B. The move is given a stale source A +// and must wait for B, then arrive in C after the reorder commits. Before the +// source recheck, it locked A and C, moved the task to C, and the paused +// reorder wrote B's position into the task after that move. +func TestPostgresAdmissionRechecksStaleSourceBeforeMoving(t *testing.T) { + const ( + stepA = "stale-source-a" + stepB = "stale-source-b" + stepC = "stale-source-c" + ) + db := openIsolatedPostgresMultiConn(t, testutil.PostgresDSNFromEnv(t), 3) + repo, err := NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("init postgres schema: %v", err) + } + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "stale-source-ws", Name: "Stale source"}); err != nil { + t.Fatalf("seed workspace: %v", err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "stale-source-workflow", WorkspaceID: "stale-source-ws", Name: "Stale source"}); err != nil { + t.Fatalf("seed workflow: %v", err) + } + for i, stepID := range []string{stepA, stepB, stepC} { + if _, err := db.Exec(db.Rebind(` + INSERT INTO workflow_steps (id, workflow_id, name, position) + VALUES (?, ?, ?, ?) + `), stepID, "stale-source-workflow", stepID, i); err != nil { + t.Fatalf("seed workflow step %s: %v", stepID, err) + } + } + + moving := &models.Task{ + ID: "stale-source-moving", WorkspaceID: "stale-source-ws", WorkflowID: "stale-source-workflow", + WorkflowStepID: stepB, Title: "Moving", WIPAdmitted: true, + } + stays := &models.Task{ + ID: "stale-source-stays", WorkspaceID: "stale-source-ws", WorkflowID: "stale-source-workflow", + WorkflowStepID: stepB, Title: "Stays", WIPAdmitted: true, + } + target := &models.Task{ + ID: "stale-source-target", WorkspaceID: "stale-source-ws", WorkflowID: "stale-source-workflow", + WorkflowStepID: stepC, Title: "Target", WIPAdmitted: true, + } + for _, task := range []*models.Task{moving, stays, target} { + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task %s: %v", task.ID, err) + } + } + + reorderPaused := make(chan struct{}) + releaseReorder := make(chan struct{}) + var pauseOnce sync.Once + repo.reorderPreWriteHook = func() { + pauseOnce.Do(func() { + close(reorderPaused) + <-releaseReorder + }) + } + t.Cleanup(func() { + repo.reorderPreWriteHook = nil + select { + case <-releaseReorder: + default: + close(releaseReorder) + } + }) + + var reorderErr error + reorderDone := make(chan struct{}) + go func() { + _, _, reorderErr = repo.ReorderStepTasks(ctx, stepB, ReorderBandAdmitted, []string{moving.ID, stays.ID}) + close(reorderDone) + }() + <-reorderPaused + + // The caller's model still says A, while the persisted task is in B. + staleSnapshot := *moving + staleSnapshot.WorkflowStepID = stepA + moveDone := make(chan error, 1) + go func() { + _, err := repo.UpdateTaskWithWorkflowStepAdmission(ctx, &staleSnapshot, stepA, stepC, 0) + moveDone <- err + }() + + close(releaseReorder) + <-reorderDone + if reorderErr != nil { + t.Fatalf("reorder: %v", reorderErr) + } + if err := <-moveDone; err != nil { + t.Fatalf("move with stale source: %v", err) + } + + stored, err := repo.GetTask(ctx, moving.ID) + if err != nil { + t.Fatalf("reload moved task: %v", err) + } + if stored.WorkflowStepID != stepC { + t.Fatalf("moved task ended in step %q, want %q", stored.WorkflowStepID, stepC) + } + if stored.Position != target.Position+1 { + t.Fatalf("moved task position = %d, want %d after target arrival", stored.Position, target.Position+1) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_promotion_lock_postgres_test.go b/apps/backend/internal/task/repository/sqlite/task_promotion_lock_postgres_test.go new file mode 100644 index 0000000000..1a3c086cb2 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_promotion_lock_postgres_test.go @@ -0,0 +1,160 @@ +package sqlite + +// TestPostgresPromotionLocksSourceStepAgainstConcurrentReorder proves +// PromoteQueuedTaskIfWorkflowStepHasCapacity locks the step a task is +// LEAVING, not only the one it is entering. Before this lock existed, the +// promotion's claim held no lock a concurrent ReorderStepTasks of the source +// step would wait on, so the two transactions could interleave on Postgres: +// the reorder could read the source step's membership before the promotion +// committed (a legitimate read - the task had not left yet), then, paused +// until the promotion committed, write the promoted task's position (a bare +// UPDATE keyed only on task id, with no step predicate) after the promotion +// had already moved that task into the destination step and assigned it a +// destination-scoped position - silently clobbering that position with a +// stale source-step-scoped one. +// +// Natural goroutine scheduling almost never reproduces this: reorder +// reaches its write with fewer preliminary round trips than the promotion +// reaches its own, so it usually writes first and the promotion's later, +// predicate-guarded write simply overwrites it correctly. Constructing the +// adversarial ordering deterministically needs reorderPreWriteHook (mirrors +// usageEventPreRollupHook's role in the usage-event deadlock test) to pause +// a real reorder transaction after its membership read but before its +// write, so the promotion can run to completion in between. +// +// Skips unless KANDEV_TEST_POSTGRES_DSN is set. + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresPromotionLocksSourceStepAgainstConcurrentReorder(t *testing.T) { + const ( + feeder = "promo-lock-feeder" + target = "promo-lock-target" + ) + db := openIsolatedPostgresMultiConn(t, testutil.PostgresDSNFromEnv(t), 2) + repo, err := NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("init postgres schema: %v", err) + } + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "promo-lock-ws", Name: "Promotion lock workspace"}); err != nil { + t.Fatalf("seed workspace: %v", err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "promo-lock-workflow", WorkspaceID: "promo-lock-ws", Name: "Promotion lock workflow"}); err != nil { + t.Fatalf("seed workflow: %v", err) + } + for _, step := range []string{feeder, target} { + if _, err := db.Exec(db.Rebind(` + INSERT INTO workflow_steps (id, workflow_id, name, position) + VALUES (?, ?, ?, ?) + `), step, "promo-lock-workflow", step, 0); err != nil { + t.Fatalf("seed workflow step %s: %v", step, err) + } + } + + prior := &models.Task{ + ID: "promo-lock-prior", WorkspaceID: "promo-lock-ws", WorkflowID: "promo-lock-workflow", + WorkflowStepID: target, Title: "Prior", WIPAdmitted: true, + } + if err := repo.CreateTask(ctx, prior); err != nil { + t.Fatalf("seed prior target task: %v", err) + } + + promoted := &models.Task{ + ID: "promo-lock-promoted", WorkspaceID: "promo-lock-ws", WorkflowID: "promo-lock-workflow", + WorkflowStepID: feeder, Title: "Promoted", WIPAdmitted: true, QueuedForStepID: target, + } + stays := &models.Task{ + ID: "promo-lock-stays", WorkspaceID: "promo-lock-ws", WorkflowID: "promo-lock-workflow", + WorkflowStepID: feeder, Title: "Stays", WIPAdmitted: true, + } + for _, task := range []*models.Task{promoted, stays} { + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed feeder task %s: %v", task.ID, err) + } + } + + // Mirrors service.promoteFeederQueuedTask: the caller stamps the + // candidate's destination membership onto the struct before invoking the + // repository claim, since the repository only assigns the arrival + // position, not the step itself. + promoted.WorkflowStepID = target + promoted.WIPAdmitted = true + promoted.QueuedForStepID = "" + + reorderPaused := make(chan struct{}) + releaseReorder := make(chan struct{}) + var hookFired bool + repo.reorderPreWriteHook = func() { + if hookFired { + return + } + hookFired = true + close(reorderPaused) + <-releaseReorder + } + t.Cleanup(func() { repo.reorderPreWriteHook = nil }) + + var wg sync.WaitGroup + var reorderErr error + wg.Add(1) + go func() { + defer wg.Done() + _, _, reorderErr = repo.ReorderStepTasks(ctx, feeder, ReorderBandAdmitted, []string{promoted.ID, stays.ID}) + }() + + <-reorderPaused // reorder holds feeder's row lock and has already read promoted as still resident there + + var claimed bool + var promoteErr error + wg.Add(1) + go func() { + defer wg.Done() + claimed, promoteErr = repo.PromoteQueuedTaskIfWorkflowStepHasCapacity(ctx, promoted, feeder, target, 0) + }() + + // Give the promotion goroutine time to run to completion (unfixed code) + // or register its lock wait against reorder's held feeder lock (fixed + // code) before releasing reorder - mirrors the usage-event deadlock + // test's registration-order wait. + time.Sleep(200 * time.Millisecond) + close(releaseReorder) + + wg.Wait() + + if promoteErr != nil { + t.Fatalf("promotion must always succeed (unlimited target): %v", promoteErr) + } + if !claimed { + t.Fatalf("promotion did not claim the feeder task") + } + if reorderErr != nil && !errors.Is(reorderErr, repoerrors.ErrStepChanged) { + t.Fatalf("reorder error = %v, want nil or ErrStepChanged", reorderErr) + } + + storedPromoted, err := repo.GetTask(ctx, promoted.ID) + if err != nil { + t.Fatalf("reload promoted task: %v", err) + } + if storedPromoted.WorkflowStepID != target { + t.Fatalf("promoted task ended up in step %q, want %q", storedPromoted.WorkflowStepID, target) + } + storedPrior, err := repo.GetTask(ctx, prior.ID) + if err != nil { + t.Fatalf("reload prior target task: %v", err) + } + if storedPromoted.Position == storedPrior.Position { + t.Fatalf("promoted task position %d collides with prior target task position %d: a concurrent reorder of the "+ + "feeder step overwrote the arrival position the promotion assigned", storedPromoted.Position, storedPrior.Position) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_reorder.go b/apps/backend/internal/task/repository/sqlite/task_reorder.go new file mode 100644 index 0000000000..a2366c4544 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_reorder.go @@ -0,0 +1,307 @@ +package sqlite + +import ( + "context" + "database/sql" + "sort" + "strings" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" +) + +// Reorder band discriminators (REQ-TASKS-KANBAN-TASK-REORDERING-001.17): the +// wire contract's explicit "admitted" | "queued" values. +const ( + ReorderBandAdmitted = "admitted" + ReorderBandQueued = "queued" +) + +// ReorderStepTasks rewrites stepID's named band to orderedTaskIDs and +// densely renumbers the whole step from 0, admitted band first +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.15). It returns the step's full +// non-hidden task list in its new order plus the step's order_revision as of +// commit. +// +// Validation is two-tiered. A submitted id matching no task row in stepID's +// own workspace is a structurally malformed request: ErrInvalidReorder, +// alongside an invalid band value, an empty list, or a duplicate id +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.18) — a task in a different +// workspace was never a candidate for this band under any race, and this +// also keeps the check from leaking whether an id the caller cannot +// authorize against exists at all. A submitted id naming a real task, in the +// same workspace, that the named step's current non-hidden membership does +// not include — because it became hidden, or because it moved to another +// step, since the client read the band — is not malformed: REQ-TASKS-KANBAN- +// TASK-REORDERING-001.26 and .33 route every such case to the +// REQ-TASKS-KANBAN-TASK-REORDERING-001.19 conflict, ErrStepChanged, because +// the server has no signal to tell "moved away during this exact window" +// apart from "was already elsewhere" — only nonexistence-in-workspace is +// unambiguous. Once every id resolves to a current, non-hidden member of +// stepID, whether that member set exactly equals the named band's current +// membership is the same conflict, checked by set comparison instead of +// existence. +func (r *Repository) ReorderStepTasks( + ctx context.Context, stepID, band string, orderedTaskIDs []string, +) ([]*models.Task, int64, error) { + if band != ReorderBandAdmitted && band != ReorderBandQueued { + return nil, 0, repoerrors.ErrInvalidReorder + } + if err := validateReorderIDList(orderedTaskIDs); err != nil { + return nil, 0, err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, 0, err + } + defer func() { _ = tx.Rollback() }() + + if err := lockWorkflowStepForWrite(ctx, tx, r.db.DriverName(), r.db.Rebind, stepID); err != nil { + return nil, 0, err + } + tasks, err := r.listStepTasksInTx(ctx, tx, stepID) + if err != nil { + return nil, 0, err + } + admitted, queued := partitionReorderBands(tasks, stepID) + named := admitted + other := queued + if band == ReorderBandQueued { + named, other = queued, admitted + } + + orderedNamed, unresolvedIDs := resolveReorderStepMembership(tasks, orderedTaskIDs) + if len(unresolvedIDs) > 0 { + return r.reorderUnresolvedIDsResult(ctx, tx, stepID, tasks, unresolvedIDs) + } + if !sameTaskSet(orderedNamed, named) { + revision, revErr := r.stepOrderRevisionInTx(ctx, tx, stepID) + if revErr != nil { + return nil, 0, revErr + } + return sortStepOrder(tasks), revision, repoerrors.ErrStepChanged + } + + renumbered := renumberReorderedStep(band, orderedNamed, other) + r.fireReorderPreWriteHook() + for _, task := range renumbered { + if _, err := tx.ExecContext(ctx, r.db.Rebind(`UPDATE tasks SET position = ?, updated_at = ? WHERE id = ?`), + task.Position, r.nowUTC(), task.ID); err != nil { + return nil, 0, err + } + } + revision, err := r.bumpStepOrderRevisionInTx(ctx, tx, stepID) + if err != nil { + return nil, 0, err + } + if err := tx.Commit(); err != nil { + return nil, 0, err + } + return renumbered, revision, nil +} + +func (r *Repository) fireReorderPreWriteHook() { + if r.reorderPreWriteHook != nil { + r.reorderPreWriteHook() + } +} + +func validateReorderIDList(orderedTaskIDs []string) error { + if len(orderedTaskIDs) == 0 { + return repoerrors.ErrInvalidReorder + } + seen := make(map[string]struct{}, len(orderedTaskIDs)) + for _, id := range orderedTaskIDs { + if _, dup := seen[id]; dup { + return repoerrors.ErrInvalidReorder + } + seen[id] = struct{}{} + } + return nil +} + +// listStepTasksInTx reads stepID's non-hidden tasks inside tx, so the read +// cannot straddle a concurrent writer's renumbering. +func (r *Repository) listStepTasksInTx(ctx context.Context, tx *sql.Tx, stepID string) ([]*models.Task, error) { + rows, err := tx.QueryContext(ctx, r.db.Rebind(` + SELECT `+taskSelectColumns("t")+` + FROM tasks t + WHERE t.workflow_step_id = ? AND t.archived_at IS NULL AND t.is_ephemeral = 0`+andNotAutomationOriginT+` + `), stepID) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + return r.scanTasks(rows) +} + +// partitionReorderBands splits stepID's non-hidden tasks into its admitted +// and queued bands (Terminology: the queued band is +// !wip_admitted && queued_for_step_id == stepID; everything else in the step +// is the admitted band). +func partitionReorderBands(tasks []*models.Task, stepID string) (admitted, queued []*models.Task) { + for _, task := range tasks { + if !task.WIPAdmitted && task.QueuedForStepID == stepID { + queued = append(queued, task) + } else { + admitted = append(admitted, task) + } + } + return admitted, queued +} + +// resolveReorderStepMembership resolves each of orderedIDs against +// stepTasks, the step's current non-hidden members (both bands). An id with +// no match is returned in unresolved rather than rejected immediately: the +// caller still has to tell an id matching no task row at all apart from one +// naming a real task that has simply left stepID's current membership since +// the client read the band, which is a membership-change conflict rather +// than a malformed request (REQ-TASKS-KANBAN-TASK-REORDERING-001.26/.33). +func resolveReorderStepMembership(stepTasks []*models.Task, orderedIDs []string) (resolved []*models.Task, unresolved []string) { + byID := make(map[string]*models.Task, len(stepTasks)) + for _, task := range stepTasks { + byID[task.ID] = task + } + resolved = make([]*models.Task, 0, len(orderedIDs)) + for _, id := range orderedIDs { + task, ok := byID[id] + if !ok { + unresolved = append(unresolved, id) + continue + } + resolved = append(resolved, task) + } + return resolved, unresolved +} + +// reorderUnresolvedIDsResult resolves the two-way branch for ids that don't +// currently match any of stepID's non-hidden tasks: an id resolving to no +// task row in stepID's own workspace is a structurally malformed request, +// ErrInvalidReorder, because the server has no membership window to +// attribute it to; otherwise every one of them names a real task, in the +// same workspace, that the named step's current membership no longer +// includes — hidden inside the window, or moved to another step, whatever +// the cause — which is the REQ-TASKS-KANBAN-TASK-REORDERING-001.26/.33 +// membership-change conflict, ErrStepChanged. +func (r *Repository) reorderUnresolvedIDsResult( + ctx context.Context, tx *sql.Tx, stepID string, tasks []*models.Task, unresolvedIDs []string, +) ([]*models.Task, int64, error) { + nonexistent, err := r.hasNonexistentReorderID(ctx, tx, stepID, unresolvedIDs) + if err != nil { + return nil, 0, err + } + if nonexistent { + return nil, 0, repoerrors.ErrInvalidReorder + } + revision, err := r.stepOrderRevisionInTx(ctx, tx, stepID) + if err != nil { + return nil, 0, err + } + return sortStepOrder(tasks), revision, repoerrors.ErrStepChanged +} + +// hasNonexistentReorderID reports whether any of ids matches no task row in +// stepID's own workspace. Called only for ids resolveReorderStepMembership +// could not match against the step's live non-hidden tasks, so a false +// result means every id names a real task in that same workspace — the +// server has no way to tell "left the named step during this window" apart +// from "was never in it," so both resolve to the same membership-change +// conflict rather than the malformed-request case. +// +// Scoping the existence check to stepID's workspace (rather than checking +// the whole tasks table) is not just correctness — a task could never have +// raced into or out of a band in a workspace it does not belong to — it is +// also required for per-user scoping (service.authorizeWorkflowID only +// authorizes stepID's own workflow, never the individual submitted ids): a +// task existing in a workspace the caller cannot see must read identically +// to a nonexistent one, the same "no existence leak" invariant +// authorizeTaskID/authorizeWorkflowID are built around. +func (r *Repository) hasNonexistentReorderID(ctx context.Context, tx *sql.Tx, stepID string, ids []string) (bool, error) { + placeholders := make([]string, len(ids)) + args := make([]any, 0, len(ids)+1) + for i, id := range ids { + placeholders[i] = "?" + args = append(args, id) + } + args = append(args, stepID) + query := r.db.Rebind(` + SELECT COUNT(*) FROM tasks WHERE id IN (` + strings.Join(placeholders, ",") + `) AND workspace_id = ( + SELECT w.workspace_id FROM workflow_steps ws JOIN workflows w ON w.id = ws.workflow_id WHERE ws.id = ? + ) + `) + var existingCount int + if err := tx.QueryRowContext(ctx, query, args...).Scan(&existingCount); err != nil { + return false, err + } + return existingCount != len(ids), nil +} + +// sameTaskSet reports whether resolved (already deduplicated, one entry per +// submitted id) names exactly the same tasks as currentBand, regardless of +// order. +func sameTaskSet(resolved, currentBand []*models.Task) bool { + if len(resolved) != len(currentBand) { + return false + } + ids := make(map[string]struct{}, len(currentBand)) + for _, task := range currentBand { + ids[task.ID] = struct{}{} + } + for _, task := range resolved { + if _, ok := ids[task.ID]; !ok { + return false + } + } + return true +} + +// renumberReorderedStep assigns dense positions 0..N-1 across the whole +// step, admitted band first (REQ-TASKS-KANBAN-TASK-REORDERING-001.15): the +// named band in the caller's submitted sequence, the other band in its +// existing step order. +func renumberReorderedStep(band string, orderedNamed, other []*models.Task) []*models.Task { + sort.SliceStable(other, func(i, j int) bool { return models.StepOrderLess(other[i], other[j]) }) + finalAdmitted, finalQueued := orderedNamed, other + if band == ReorderBandQueued { + finalAdmitted, finalQueued = other, orderedNamed + } + renumbered := make([]*models.Task, 0, len(finalAdmitted)+len(finalQueued)) + position := 0 + for _, task := range finalAdmitted { + task.Position = position + renumbered = append(renumbered, task) + position++ + } + for _, task := range finalQueued { + task.Position = position + renumbered = append(renumbered, task) + position++ + } + return renumbered +} + +// sortStepOrder returns tasks sorted by the current, uncommitted step order — +// used only to populate an ErrStepChanged response with the authoritative +// order the caller reconciles to. +func sortStepOrder(tasks []*models.Task) []*models.Task { + sorted := make([]*models.Task, len(tasks)) + copy(sorted, tasks) + sort.SliceStable(sorted, func(i, j int) bool { return models.StepOrderLess(sorted[i], sorted[j]) }) + return sorted +} + +func (r *Repository) stepOrderRevisionInTx(ctx context.Context, tx *sql.Tx, stepID string) (int64, error) { + var revision int64 + err := tx.QueryRowContext(ctx, r.db.Rebind(`SELECT order_revision FROM workflow_steps WHERE id = ?`), stepID).Scan(&revision) + return revision, err +} + +func (r *Repository) bumpStepOrderRevisionInTx(ctx context.Context, tx *sql.Tx, stepID string) (int64, error) { + if _, err := tx.ExecContext(ctx, r.db.Rebind( + `UPDATE workflow_steps SET order_revision = order_revision + 1, updated_at = ? WHERE id = ?`, + ), r.nowUTC(), stepID); err != nil { + return 0, err + } + return r.stepOrderRevisionInTx(ctx, tx, stepID) +} diff --git a/apps/backend/internal/task/repository/sqlite/task_reorder_rigor_test.go b/apps/backend/internal/task/repository/sqlite/task_reorder_rigor_test.go new file mode 100644 index 0000000000..84a0610910 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_reorder_rigor_test.go @@ -0,0 +1,370 @@ +package sqlite + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" +) + +// markHiddenForReorder marks id as a hidden task per Terminology (archived, +// ephemeral, or automation-run), so it is excluded from a reorder's band +// membership. +func markHiddenForReorder(t *testing.T, repo *Repository, id, kind string) { + t.Helper() + var stmt string + switch kind { + case "archived": + stmt = `UPDATE tasks SET archived_at = ? WHERE id = ?` + case "ephemeral": + stmt = `UPDATE tasks SET is_ephemeral = 1 WHERE id = ?` + case "automation_run": + stmt = `UPDATE tasks SET origin = 'automation_run' WHERE id = ?` + default: + t.Fatalf("unknown hidden-task kind %q", kind) + } + var err error + if kind == "archived" { + _, err = repo.db.Exec(repo.db.Rebind(stmt), time.Now().UTC(), id) + } else { + _, err = repo.db.Exec(repo.db.Rebind(stmt), id) + } + if err != nil { + t.Fatalf("markHiddenForReorder(%s, %s): %v", id, kind, err) + } +} + +// TestReorderStepTasksDoesNotTouchOtherStepPositions pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.31: reordering one step's band must +// rewrite no task's position in another step. +func TestReorderStepTasksDoesNotTouchOtherStepPositions(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-other-step") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-other-step", WorkspaceID: "ws-other-step", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-reordered", "wf-other-step") + seedReorderStep(t, repo, "step-bystander", "wf-other-step") + mustCreateReorderTask(t, ctx, repo, "reordered-a", "ws-other-step", "wf-other-step", "step-reordered") + mustCreateReorderTask(t, ctx, repo, "reordered-b", "ws-other-step", "wf-other-step", "step-reordered") + mustCreateReorderTask(t, ctx, repo, "bystander-a", "ws-other-step", "wf-other-step", "step-bystander") + mustCreateReorderTask(t, ctx, repo, "bystander-b", "ws-other-step", "wf-other-step", "step-bystander") + + if _, _, err := repo.ReorderStepTasks(ctx, "step-reordered", ReorderBandAdmitted, []string{"reordered-b", "reordered-a"}); err != nil { + t.Fatalf("ReorderStepTasks: %v", err) + } + + if got := taskPosition(t, ctx, repo, "bystander-a"); got != 0 { + t.Fatalf("bystander-a position = %d, want unchanged 0", got) + } + if got := taskPosition(t, ctx, repo, "bystander-b"); got != 1 { + t.Fatalf("bystander-b position = %d, want unchanged 1", got) + } +} + +// TestReorderStepTasksExcludesHiddenTasksFromMembership pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.33/.31: an archived, ephemeral, or +// automation-run task is never part of band membership, is never required in +// a valid submission, and never has its position rewritten. Naming it +// explicitly is the membership-change conflict of .19/.26, not a malformed +// request, because it still belongs to stepID — only an id that never +// belonged to stepID at all is malformed +// (TestReorderStepTasksNamingForeignTaskIsMalformed covers that case). +func TestReorderStepTasksExcludesHiddenTasksFromMembership(t *testing.T) { + for _, kind := range []string{"archived", "ephemeral", "automation_run"} { + t.Run(kind, func(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + wsID, wfID, stepID := "ws-hidden-"+kind, "wf-hidden-"+kind, "step-hidden-"+kind + seedWorkspace(t, repo, wsID) + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: wfID, WorkspaceID: wsID, Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, stepID, wfID) + mustCreateReorderTask(t, ctx, repo, "visible-a", wsID, wfID, stepID) + mustCreateReorderTask(t, ctx, repo, "visible-b", wsID, wfID, stepID) + mustCreateReorderTask(t, ctx, repo, "hidden-task", wsID, wfID, stepID) + markHiddenForReorder(t, repo, "hidden-task", kind) + hiddenBefore := taskPosition(t, ctx, repo, "hidden-task") + + // The client never saw hidden-task, so it submits only the two + // visible members — and that must succeed, not conflict. + tasks, _, err := repo.ReorderStepTasks(ctx, stepID, ReorderBandAdmitted, []string{"visible-b", "visible-a"}) + if err != nil { + t.Fatalf("ReorderStepTasks: %v", err) + } + if len(tasks) != 2 { + t.Fatalf("returned tasks = %d, want 2 (hidden task excluded)", len(tasks)) + } + for _, task := range tasks { + if task.ID == "hidden-task" { + t.Fatal("hidden task must not appear in the returned membership") + } + } + if got := taskPosition(t, ctx, repo, "hidden-task"); got != hiddenBefore { + t.Fatalf("hidden task position = %d, want unchanged %d", got, hiddenBefore) + } + + // Naming the hidden task explicitly means the client's submission + // reflects a membership it saw before hidden-task became hidden: + // the .26/.33 membership-change conflict (409 step_changed), not + // the .18 malformed-request case (400). + _, _, err = repo.ReorderStepTasks(ctx, stepID, ReorderBandAdmitted, []string{"visible-a", "hidden-task"}) + if !errors.Is(err, repoerrors.ErrStepChanged) { + t.Fatalf("naming a hidden task: err = %v, want ErrStepChanged", err) + } + if got := taskPosition(t, ctx, repo, "hidden-task"); got != hiddenBefore { + t.Fatalf("hidden task position = %d, want unchanged %d after the conflict", got, hiddenBefore) + } + }) + } +} + +// TestReorderStepTasksNamingForeignTaskIsMalformed pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.18: an id that resolves to no task row +// at all is a structurally malformed request (400 invalid_reorder) — the +// server has no membership window to attribute it to, so it cannot be the +// AC.26 conflict. An id naming a real task the named step's own membership +// no longer includes is that conflict instead, whatever moved it there +// (TestReorderStepTasksExcludesHiddenTasksFromMembership, +// TestReorderStepTasksNamingTaskInAnotherStepIsMembershipDrift). +func TestReorderStepTasksNamingForeignTaskIsMalformed(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-foreign-reorder-id") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-foreign-reorder-id", WorkspaceID: "ws-foreign-reorder-id", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-foreign-reorder-id", "wf-foreign-reorder-id") + mustCreateReorderTask(t, ctx, repo, "foreign-visible-a", "ws-foreign-reorder-id", "wf-foreign-reorder-id", "step-foreign-reorder-id") + + _, _, err := repo.ReorderStepTasks(ctx, "step-foreign-reorder-id", ReorderBandAdmitted, []string{"foreign-visible-a", "does-not-exist"}) + if !errors.Is(err, repoerrors.ErrInvalidReorder) { + t.Fatalf("err = %v, want ErrInvalidReorder", err) + } +} + +// TestReorderStepTasksNamingTaskInAnotherStepIsMembershipDrift pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.26: a submitted id naming a real task +// that is not currently in the named step's membership is the same +// conflict (409 step_changed) as a task that became hidden inside the +// window, not the AC.18 malformed case +// (TestReorderStepTasksNamingForeignTaskIsMalformed) — AC.26 lists "moved +// into or out of" the band as a membership-change conflict without a time +// bound on when that move happened, and the server has no client-read-time +// signal to tell "moved away just now, racing this very request" apart from +// "was already elsewhere," so both resolve the same, safe way: a silent +// reconcile rather than an error toast for what may be an ordinary race. +func TestReorderStepTasksNamingTaskInAnotherStepIsMembershipDrift(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-drift-reorder-id") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-drift-reorder-id", WorkspaceID: "ws-drift-reorder-id", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-drift-reorder-id", "wf-drift-reorder-id") + seedReorderStep(t, repo, "step-drift-reorder-id-other", "wf-drift-reorder-id") + mustCreateReorderTask(t, ctx, repo, "drift-visible-a", "ws-drift-reorder-id", "wf-drift-reorder-id", "step-drift-reorder-id") + mustCreateReorderTask(t, ctx, repo, "drift-elsewhere", "ws-drift-reorder-id", "wf-drift-reorder-id", "step-drift-reorder-id-other") + + _, _, err := repo.ReorderStepTasks(ctx, "step-drift-reorder-id", ReorderBandAdmitted, []string{"drift-visible-a", "drift-elsewhere"}) + if !errors.Is(err, repoerrors.ErrStepChanged) { + t.Fatalf("err = %v, want ErrStepChanged", err) + } +} + +// TestReorderStepTasksNamingTaskInAnotherWorkspaceIsMalformed pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.18: a real task that belongs to a +// different workspace entirely was never a candidate for this step's band +// under any race, so it is the malformed case (400 invalid_reorder), not the +// AC.26 membership-change conflict +// (TestReorderStepTasksNamingTaskInAnotherStepIsMembershipDrift, whose named +// task shares the reordered step's own workspace). Distinguishing the two +// with different error codes also matters beyond correctness: per-user +// scoping (apps/backend/AGENTS.md "no existence leak") requires that naming +// a real task in a workspace the caller cannot see be indistinguishable from +// naming a nonexistent id — 409 would confirm the id exists. +func TestReorderStepTasksNamingTaskInAnotherWorkspaceIsMalformed(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-cross-tenant-reorder-id") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-cross-tenant-reorder-id", WorkspaceID: "ws-cross-tenant-reorder-id", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-cross-tenant-reorder-id", "wf-cross-tenant-reorder-id") + mustCreateReorderTask(t, ctx, repo, "cross-tenant-visible-a", "ws-cross-tenant-reorder-id", "wf-cross-tenant-reorder-id", "step-cross-tenant-reorder-id") + + seedWorkspace(t, repo, "ws-cross-tenant-other") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-cross-tenant-other", WorkspaceID: "ws-cross-tenant-other", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-cross-tenant-other", "wf-cross-tenant-other") + mustCreateReorderTask(t, ctx, repo, "cross-tenant-secret", "ws-cross-tenant-other", "wf-cross-tenant-other", "step-cross-tenant-other") + + _, _, err := repo.ReorderStepTasks(ctx, "step-cross-tenant-reorder-id", ReorderBandAdmitted, []string{"cross-tenant-visible-a", "cross-tenant-secret"}) + if !errors.Is(err, repoerrors.ErrInvalidReorder) { + t.Fatalf("err = %v, want ErrInvalidReorder (a foreign-workspace task must read the same as a nonexistent one)", err) + } +} + +// TestReorderStepTasksDepartureLeavesRemainingRelativeOrderIntact pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.30: when a task leaves a band (here, a +// cross-step move), the remaining tasks keep their relative order; position +// values need not stay contiguous. +func TestReorderStepTasksDepartureLeavesRemainingRelativeOrderIntact(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-departure") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-departure", WorkspaceID: "ws-departure", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-departure-src", "wf-departure") + seedReorderStep(t, repo, "step-departure-dst", "wf-departure") + mustCreateReorderTask(t, ctx, repo, "dep-a", "ws-departure", "wf-departure", "step-departure-src") + mid := mustCreateReorderTask(t, ctx, repo, "dep-mid", "ws-departure", "wf-departure", "step-departure-src") + mustCreateReorderTask(t, ctx, repo, "dep-c", "ws-departure", "wf-departure", "step-departure-src") + beforeA := taskPosition(t, ctx, repo, "dep-a") + beforeC := taskPosition(t, ctx, repo, "dep-c") + if beforeA >= beforeC { + t.Fatalf("fixture invariant broken: dep-a (%d) must precede dep-c (%d)", beforeA, beforeC) + } + + if _, err := repo.UpdateTaskWithWorkflowStepAdmission(ctx, mid, "step-departure-src", "step-departure-dst", 0); err != nil { + t.Fatalf("move dep-mid out of the band: %v", err) + } + + if got := taskPosition(t, ctx, repo, "dep-a"); got != beforeA { + t.Fatalf("dep-a position = %d, want unchanged %d (no renumbering on departure)", got, beforeA) + } + if got := taskPosition(t, ctx, repo, "dep-c"); got != beforeC { + t.Fatalf("dep-c position = %d, want unchanged %d (no renumbering on departure)", got, beforeC) + } + if taskPosition(t, ctx, repo, "dep-a") >= taskPosition(t, ctx, repo, "dep-c") { + t.Fatal("relative order of remaining tasks was not preserved") + } +} + +// TestReorderStepTasksConcurrentSameBandSerializes pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.25: two reorders of the same band with +// the same starting membership must apply one at a time; the last to commit +// is authoritative and the revision counter advances exactly once per +// commit, with no lost update. +func TestReorderStepTasksConcurrentSameBandSerializes(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-concurrent-same-band") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-concurrent-same-band", WorkspaceID: "ws-concurrent-same-band", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-concurrent-same-band", "wf-concurrent-same-band") + mustCreateReorderTask(t, ctx, repo, "same-a", "ws-concurrent-same-band", "wf-concurrent-same-band", "step-concurrent-same-band") + mustCreateReorderTask(t, ctx, repo, "same-b", "ws-concurrent-same-band", "wf-concurrent-same-band", "step-concurrent-same-band") + + orders := [][]string{ + {"same-a", "same-b"}, + {"same-b", "same-a"}, + } + var wg sync.WaitGroup + start := make(chan struct{}) + results := make([]int64, len(orders)) + errs := make([]error, len(orders)) + for i, order := range orders { + wg.Add(1) + go func(i int, order []string) { + defer wg.Done() + <-start + _, revision, err := repo.ReorderStepTasks(ctx, "step-concurrent-same-band", ReorderBandAdmitted, order) + results[i], errs[i] = revision, err + }(i, order) + } + close(start) + wg.Wait() + + for i, err := range errs { + if err != nil { + t.Fatalf("reorder %d: %v", i, err) + } + } + // Both submissions had the same starting membership, so both commit + // (AC.25 does not reject either one); each gets its own revision, and + // the two revisions must be distinct (no lost update serialized them + // into the same counter value). + if results[0] == results[1] { + t.Fatalf("both commits produced revision %d; want two distinct revisions", results[0]) + } + // AC.25: "the last committed order shall be authoritative" — the + // persisted positions must match the submission with the higher + // revision, not just be dense/consistent with either. + winner := 0 + if results[1] > results[0] { + winner = 1 + } + wantFirst, wantSecond := orders[winner][0], orders[winner][1] + if got := taskPosition(t, ctx, repo, wantFirst); got != 0 { + t.Fatalf("%s position = %d, want 0 (higher-revision submission %v is authoritative)", wantFirst, got, orders[winner]) + } + if got := taskPosition(t, ctx, repo, wantSecond); got != 1 { + t.Fatalf("%s position = %d, want 1 (higher-revision submission %v is authoritative)", wantSecond, got, orders[winner]) + } +} + +// TestReorderStepTasksConcurrentDifferentBandsDoNotBlockEachOther pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.37: concurrent reorders naming the +// step's two different bands must both succeed, each ending in its own +// submitted order. +func TestReorderStepTasksConcurrentDifferentBandsDoNotBlockEachOther(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-concurrent-diff-bands") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-concurrent-diff-bands", WorkspaceID: "ws-concurrent-diff-bands", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-concurrent-diff-bands", "wf-concurrent-diff-bands") + mustCreateReorderTask(t, ctx, repo, "diff-admitted-a", "ws-concurrent-diff-bands", "wf-concurrent-diff-bands", "step-concurrent-diff-bands") + mustCreateReorderTask(t, ctx, repo, "diff-admitted-b", "ws-concurrent-diff-bands", "wf-concurrent-diff-bands", "step-concurrent-diff-bands") + mustCreateReorderTask(t, ctx, repo, "diff-queued-a", "ws-concurrent-diff-bands", "wf-concurrent-diff-bands", "step-concurrent-diff-bands") + mustCreateReorderTask(t, ctx, repo, "diff-queued-b", "ws-concurrent-diff-bands", "wf-concurrent-diff-bands", "step-concurrent-diff-bands") + markQueuedForReorder(t, repo, "diff-queued-a", "step-concurrent-diff-bands") + markQueuedForReorder(t, repo, "diff-queued-b", "step-concurrent-diff-bands") + + var wg sync.WaitGroup + start := make(chan struct{}) + var admittedErr, queuedErr error + wg.Add(2) + go func() { + defer wg.Done() + <-start + _, _, admittedErr = repo.ReorderStepTasks(ctx, "step-concurrent-diff-bands", ReorderBandAdmitted, []string{"diff-admitted-b", "diff-admitted-a"}) + }() + go func() { + defer wg.Done() + <-start + _, _, queuedErr = repo.ReorderStepTasks(ctx, "step-concurrent-diff-bands", ReorderBandQueued, []string{"diff-queued-b", "diff-queued-a"}) + }() + close(start) + wg.Wait() + + if admittedErr != nil { + t.Fatalf("admitted-band reorder: %v", admittedErr) + } + if queuedErr != nil { + t.Fatalf("queued-band reorder: %v", queuedErr) + } + if got := taskPosition(t, ctx, repo, "diff-admitted-b"); got != 0 { + t.Fatalf("diff-admitted-b position = %d, want 0", got) + } + if got := taskPosition(t, ctx, repo, "diff-admitted-a"); got != 1 { + t.Fatalf("diff-admitted-a position = %d, want 1", got) + } + if got := taskPosition(t, ctx, repo, "diff-queued-b"); got != 2 { + t.Fatalf("diff-queued-b position = %d, want 2", got) + } + if got := taskPosition(t, ctx, repo, "diff-queued-a"); got != 3 { + t.Fatalf("diff-queued-a position = %d, want 3", got) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_reorder_test.go b/apps/backend/internal/task/repository/sqlite/task_reorder_test.go new file mode 100644 index 0000000000..53233cce3f --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_reorder_test.go @@ -0,0 +1,287 @@ +package sqlite + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" +) + +// seedReorderStep inserts a workflow_steps row directly, mirroring the +// pattern in next_queued_task_ordering_pin_test.go: ReorderStepTasks only +// needs the row to exist and hold order_revision, not a full workflow +// repository. +func seedReorderStep(t *testing.T, repo *Repository, stepID, workflowID string) { + t.Helper() + now := time.Now().UTC() + if _, err := repo.db.Exec(repo.db.Rebind(`INSERT INTO workflow_steps + (id, workflow_id, name, position, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)`), + stepID, workflowID, stepID, 0, now, now); err != nil { + t.Fatalf("insert step %s: %v", stepID, err) + } +} + +func mustCreateReorderTask(t *testing.T, ctx context.Context, repo *Repository, id, workspaceID, workflowID, stepID string) *models.Task { + t.Helper() + task := &models.Task{ + ID: id, + WorkspaceID: workspaceID, + WorkflowID: workflowID, + WorkflowStepID: stepID, + Title: id, + } + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("CreateTask(%s): %v", id, err) + } + return task +} + +func markQueuedForReorder(t *testing.T, repo *Repository, id, destinationStepID string) { + t.Helper() + if _, err := repo.db.Exec(repo.db.Rebind( + `UPDATE tasks SET wip_admitted = 0, queued_for_step_id = ? WHERE id = ?`), + destinationStepID, id); err != nil { + t.Fatalf("markQueuedForReorder(%s): %v", id, err) + } +} + +func taskPosition(t *testing.T, ctx context.Context, repo *Repository, id string) int { + t.Helper() + task, err := repo.GetTask(ctx, id) + if err != nil { + t.Fatalf("GetTask(%s): %v", id, err) + } + return task.Position +} + +func TestReorderStepTasksRenumbersAdmittedBandAndBumpsRevision(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-reorder") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-reorder", WorkspaceID: "ws-reorder", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-reorder", "wf-reorder") + mustCreateReorderTask(t, ctx, repo, "task-a", "ws-reorder", "wf-reorder", "step-reorder") + mustCreateReorderTask(t, ctx, repo, "task-b", "ws-reorder", "wf-reorder", "step-reorder") + mustCreateReorderTask(t, ctx, repo, "task-c", "ws-reorder", "wf-reorder", "step-reorder") + + tasks, revision, err := repo.ReorderStepTasks(ctx, "step-reorder", ReorderBandAdmitted, + []string{"task-c", "task-a", "task-b"}) + if err != nil { + t.Fatalf("ReorderStepTasks: %v", err) + } + if revision != 1 { + t.Fatalf("revision = %d, want 1 (first reorder of any step)", revision) + } + if len(tasks) != 3 { + t.Fatalf("tasks = %d, want 3", len(tasks)) + } + want := map[string]int{"task-c": 0, "task-a": 1, "task-b": 2} + for _, task := range tasks { + if task.Position != want[task.ID] { + t.Fatalf("task %s position = %d, want %d", task.ID, task.Position, want[task.ID]) + } + } + for id, position := range want { + if got := taskPosition(t, ctx, repo, id); got != position { + t.Fatalf("persisted %s position = %d, want %d", id, got, position) + } + } +} + +// TestReorderStepTasksBandsAreIndependent pins AC-TASKS-KANBAN-TASK-REORDERING-001.3: +// reordering one band must not disturb the other band's relative order, and +// AC-TASKS-KANBAN-TASK-REORDERING-001.15's admitted-first dense renumbering +// across both. +func TestReorderStepTasksBandsAreIndependent(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-bands") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-bands", WorkspaceID: "ws-bands", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-bands", "wf-bands") + mustCreateReorderTask(t, ctx, repo, "admitted-1", "ws-bands", "wf-bands", "step-bands") + mustCreateReorderTask(t, ctx, repo, "admitted-2", "ws-bands", "wf-bands", "step-bands") + mustCreateReorderTask(t, ctx, repo, "queued-1", "ws-bands", "wf-bands", "step-bands") + mustCreateReorderTask(t, ctx, repo, "queued-2", "ws-bands", "wf-bands", "step-bands") + markQueuedForReorder(t, repo, "queued-1", "step-bands") + markQueuedForReorder(t, repo, "queued-2", "step-bands") + + if _, _, err := repo.ReorderStepTasks(ctx, "step-bands", ReorderBandAdmitted, []string{"admitted-2", "admitted-1"}); err != nil { + t.Fatalf("reorder admitted band: %v", err) + } + if got := taskPosition(t, ctx, repo, "admitted-2"); got != 0 { + t.Fatalf("admitted-2 position = %d, want 0", got) + } + if got := taskPosition(t, ctx, repo, "admitted-1"); got != 1 { + t.Fatalf("admitted-1 position = %d, want 1", got) + } + // The queued band kept its existing step order (creation order) across + // the admitted-only reorder, and it renders after the admitted band. + if got := taskPosition(t, ctx, repo, "queued-1"); got != 2 { + t.Fatalf("queued-1 position = %d, want 2", got) + } + if got := taskPosition(t, ctx, repo, "queued-2"); got != 3 { + t.Fatalf("queued-2 position = %d, want 3", got) + } + + if _, _, err := repo.ReorderStepTasks(ctx, "step-bands", ReorderBandQueued, []string{"queued-2", "queued-1"}); err != nil { + t.Fatalf("reorder queued band: %v", err) + } + // The admitted band's just-committed order must survive an unrelated + // queued-band reorder untouched. + if got := taskPosition(t, ctx, repo, "admitted-2"); got != 0 { + t.Fatalf("admitted-2 position after queued reorder = %d, want 0", got) + } + if got := taskPosition(t, ctx, repo, "admitted-1"); got != 1 { + t.Fatalf("admitted-1 position after queued reorder = %d, want 1", got) + } + if got := taskPosition(t, ctx, repo, "queued-2"); got != 2 { + t.Fatalf("queued-2 position = %d, want 2", got) + } + if got := taskPosition(t, ctx, repo, "queued-1"); got != 3 { + t.Fatalf("queued-1 position = %d, want 3", got) + } +} + +func TestReorderStepTasksIsIdempotentWhenMembershipUnchanged(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-idempotent") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-idempotent", WorkspaceID: "ws-idempotent", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-idempotent", "wf-idempotent") + mustCreateReorderTask(t, ctx, repo, "task-x", "ws-idempotent", "wf-idempotent", "step-idempotent") + mustCreateReorderTask(t, ctx, repo, "task-y", "ws-idempotent", "wf-idempotent", "step-idempotent") + + order := []string{"task-y", "task-x"} + if _, rev1, err := repo.ReorderStepTasks(ctx, "step-idempotent", ReorderBandAdmitted, order); err != nil || rev1 != 1 { + t.Fatalf("first reorder: revision=%d err=%v", rev1, err) + } + tasks, rev2, err := repo.ReorderStepTasks(ctx, "step-idempotent", ReorderBandAdmitted, order) + if err != nil { + t.Fatalf("second reorder: %v", err) + } + if rev2 != 2 { + t.Fatalf("second reorder revision = %d, want 2 (each commit still advances the counter)", rev2) + } + want := map[string]int{"task-y": 0, "task-x": 1} + for _, task := range tasks { + if task.Position != want[task.ID] { + t.Fatalf("task %s position = %d, want %d", task.ID, task.Position, want[task.ID]) + } + } +} + +func TestReorderStepTasksRejectsMembershipDrift(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-drift") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-drift", WorkspaceID: "ws-drift", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-drift", "wf-drift") + mustCreateReorderTask(t, ctx, repo, "drift-a", "ws-drift", "wf-drift", "step-drift") + mustCreateReorderTask(t, ctx, repo, "drift-b", "ws-drift", "wf-drift", "step-drift") + // A third task arrives after the client's snapshot but before the + // reorder request — the classic AC-TASKS-KANBAN-TASK-REORDERING-001.26 + // race: the submitted set is short of the band's current membership. + mustCreateReorderTask(t, ctx, repo, "drift-c", "ws-drift", "wf-drift", "step-drift") + + tasks, revision, err := repo.ReorderStepTasks(ctx, "step-drift", ReorderBandAdmitted, []string{"drift-a", "drift-b"}) + if !errors.Is(err, repoerrors.ErrStepChanged) { + t.Fatalf("err = %v, want ErrStepChanged", err) + } + if revision != 0 { + t.Fatalf("revision = %d, want 0 (step never reordered)", revision) + } + if len(tasks) != 3 { + t.Fatalf("authoritative order = %d tasks, want 3", len(tasks)) + } + // Each task's own arrival position (creation order: a, b, c) must be + // untouched by the rejected reorder. + want := map[string]int{"drift-a": 0, "drift-b": 1, "drift-c": 2} + for id, wantPosition := range want { + if got := taskPosition(t, ctx, repo, id); got != wantPosition { + t.Fatalf("position changed on rejected reorder: %s = %d, want unchanged %d", id, got, wantPosition) + } + } +} + +// TestReorderStepTasksRejectsCrossBandID pins the AC.18/AC.19 split this +// repository resolves: a submitted id that names a real, current member of +// stepID but the OTHER band is band drift (AC.26's "moved into or out of"), +// not a structurally malformed request, so it is ErrStepChanged rather than +// ErrInvalidReorder. +func TestReorderStepTasksRejectsCrossBandID(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-crossband") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-crossband", WorkspaceID: "ws-crossband", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-crossband", "wf-crossband") + mustCreateReorderTask(t, ctx, repo, "admitted-only", "ws-crossband", "wf-crossband", "step-crossband") + mustCreateReorderTask(t, ctx, repo, "queued-only", "ws-crossband", "wf-crossband", "step-crossband") + markQueuedForReorder(t, repo, "queued-only", "step-crossband") + + _, _, err := repo.ReorderStepTasks(ctx, "step-crossband", ReorderBandAdmitted, []string{"queued-only"}) + if !errors.Is(err, repoerrors.ErrStepChanged) { + t.Fatalf("err = %v, want ErrStepChanged", err) + } +} + +func TestReorderStepTasksRejectsUnknownID(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-unknown") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-unknown", WorkspaceID: "ws-unknown", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-unknown", "wf-unknown") + mustCreateReorderTask(t, ctx, repo, "known-task", "ws-unknown", "wf-unknown", "step-unknown") + + _, _, err := repo.ReorderStepTasks(ctx, "step-unknown", ReorderBandAdmitted, []string{"known-task", "ghost-task"}) + if !errors.Is(err, repoerrors.ErrInvalidReorder) { + t.Fatalf("err = %v, want ErrInvalidReorder", err) + } + if got := taskPosition(t, ctx, repo, "known-task"); got != 0 { + t.Fatalf("position changed on rejected reorder: known-task = %d, want unchanged 0", got) + } +} + +func TestReorderStepTasksRejectsMalformedRequests(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-malformed") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-malformed", WorkspaceID: "ws-malformed", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-malformed", "wf-malformed") + mustCreateReorderTask(t, ctx, repo, "task-1", "ws-malformed", "wf-malformed", "step-malformed") + mustCreateReorderTask(t, ctx, repo, "task-2", "ws-malformed", "wf-malformed", "step-malformed") + + cases := []struct { + name string + band string + ids []string + }{ + {name: "invalid band value", band: "bogus", ids: []string{"task-1", "task-2"}}, + {name: "empty list", band: ReorderBandAdmitted, ids: []string{}}, + {name: "duplicate id", band: ReorderBandAdmitted, ids: []string{"task-1", "task-1"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, _, err := repo.ReorderStepTasks(ctx, "step-malformed", tc.band, tc.ids) + if !errors.Is(err, repoerrors.ErrInvalidReorder) { + t.Fatalf("err = %v, want ErrInvalidReorder", err) + } + }) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_selection_coverage_test.go b/apps/backend/internal/task/repository/sqlite/task_selection_coverage_test.go index 1b64968e3c..e62b012611 100644 --- a/apps/backend/internal/task/repository/sqlite/task_selection_coverage_test.go +++ b/apps/backend/internal/task/repository/sqlite/task_selection_coverage_test.go @@ -30,9 +30,19 @@ func TestTaskCountsPullCandidatesQueueAndWorkflowPlacement(t *testing.T) { {ID: "task-high", WorkspaceID: "workspace-selection", WorkflowID: "workflow-selection", WorkflowStepID: "step-feeder", Title: "High", Priority: "high", Position: 1}, {ID: "task-first-position", WorkspaceID: "workspace-selection", WorkflowID: "workflow-selection", WorkflowStepID: "step-feeder", Title: "First", Priority: "none", Position: 0}, } { + // CreateTask now assigns its own arrival position + // (REQ-TASKS-KANBAN-TASK-REORDERING-001.28) and overwrites task.Position + // in place, so the fixture's intended value (this fixture deliberately + // puts two tasks at the same position to exercise the priority tiebreak + // below it) must be captured before the call, not read back off task + // afterward. + wantPosition := task.Position if err := repo.CreateTask(ctx, task); err != nil { t.Fatalf("CreateTask(%s): %v", task.ID, err) } + if _, err := repo.db.Exec(repo.db.Rebind(`UPDATE tasks SET position = ? WHERE id = ?`), wantPosition, task.ID); err != nil { + t.Fatalf("restore position(%s): %v", task.ID, err) + } } if count, err := repo.CountTasksByWorkflow(ctx, "workflow-selection"); err != nil || count != 3 { t.Fatalf("CountTasksByWorkflow = %d, %v", count, err) diff --git a/apps/backend/internal/task/repository/sqlite/task_step_lock_reattach_race_postgres_test.go b/apps/backend/internal/task/repository/sqlite/task_step_lock_reattach_race_postgres_test.go new file mode 100644 index 0000000000..1c7cd70cc7 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_step_lock_reattach_race_postgres_test.go @@ -0,0 +1,262 @@ +package sqlite + +// TestPostgresLockTaskStepForWriteHoldsTaskRowWhenStepGoneForGood, +// TestPostgresLockTaskStepForWriteHoldsTaskRowWhenNeverInAStep, and +// TestPostgresLockTaskStepForWriteLocksNewStepWhenReattachedDuringGap close +// a gap left by the fix in task_step_lock_retry_release_postgres_test.go +// (Review round 9): ROLLBACK TO SAVEPOINT releases every lock taken since +// the savepoint, not only the step lock it was meant to drop. Releasing a +// stale step's lock on the confirming read's own found==false outcome also +// freed that read's FOR UPDATE lock on the task's own row, so +// lockTaskStepForWrite returned success with nothing locked at all. A +// concurrent transaction could then reattach the task to a brand-new step +// before the caller's own mutation (archive, delete, unarchive) ran, and +// that mutation would proceed without ever locking the new step - +// reopening the exact race this whole function exists to prevent: +// REQ-TASKS-KANBAN-TASK-REORDERING-001.15 ("a hidden task's position shall +// not be rewritten") and .26 ("any membership change in the window +// conflicts, whatever caused it"). The same gap existed, unreachable by any +// prior review, on the much older early-return path for a task that has no +// step on its very first (unlocked) read - a task that never had a step +// takes the same finding's remedy. +// +// lockTaskRowIfStepless closes both: whenever lockTaskStepForWrite +// concludes a task currently has no step, it re-verifies under a FOR +// UPDATE lock on the task's OWN row - never a step, so this cannot invert +// the step-lock-before-task-row-lock order lockTaskStepForWrite's own doc +// comment requires - and either keeps that lock through return (still no +// step: the caller's mutation is now protected against any later +// reattachment) or releases it and retries the normal step-lock sequence +// against the task's new step (reattached: there IS a step to protect +// after all). +// +// Skips unless KANDEV_TEST_POSTGRES_DSN is set. + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/jmoiron/sqlx" + + "github.com/kandev/kandev/internal/task/models" +) + +// TestPostgresLockTaskStepForWriteHoldsTaskRowWhenStepGoneForGood proves the +// literal scenario this round's finding was reproduced with: a task leaves +// its step while lockTaskStepForWrite's confirming read is waiting on that +// step's lock, and is never reattached. Releasing the stale step's lock +// must not also leave the task's own row free for a concurrent writer. +func TestPostgresLockTaskStepForWriteHoldsTaskRowWhenStepGoneForGood(t *testing.T) { + const step = "reattach-gone-step-a" + repo := seedVisibilityLockFixture(t, "reattach-gone-ws", "reattach-gone-workflow", step) + ctx := context.Background() + + task := &models.Task{ + ID: "reattach-gone-task", WorkspaceID: "reattach-gone-ws", WorkflowID: "reattach-gone-workflow", + WorkflowStepID: step, Title: "Leaving for good", WIPAdmitted: true, + } + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task: %v", err) + } + + paused := make(chan struct{}) + release := make(chan struct{}) + var releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(releaseFn) + calls := 0 + repo.taskStepLockBeforeAcquireHook = func(candidateStepID string) { + calls++ + if calls != 1 { + t.Errorf("expected exactly one step-lock attempt (the task never gets a step back), got attempt %d for %q", calls, candidateStepID) + return + } + close(paused) + <-release + } + t.Cleanup(func() { repo.taskStepLockBeforeAcquireHook = nil }) + + tx, err := repo.db.BeginTxx(ctx, nil) + if err != nil { + t.Fatalf("begin tx: %v", err) + } + defer func() { _ = tx.Rollback() }() + + lockDone := make(chan error, 1) + go func() { + lockDone <- repo.lockTaskStepForWrite(ctx, tx, task.ID) + }() + <-paused + + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind( + `UPDATE tasks SET workflow_step_id = '' WHERE id = ?`, + ), task.ID); err != nil { + t.Fatalf("simulate concurrent detach: %v", err) + } + releaseFn() + + if err := <-lockDone; err != nil { + t.Fatalf("lockTaskStepForWrite: %v", err) + } + + assertTaskRowBlocksConcurrentWrite(t, ctx, repo, tx, task.ID) +} + +// TestPostgresLockTaskStepForWriteHoldsTaskRowWhenNeverInAStep proves the +// same invariant holds on the much older path: a task that has no step on +// lockTaskStepForWrite's very first (unlocked) read - same shape as a +// config task, or one already detached before the caller was ever invoked +// - must still come out of the function with its own row locked. +func TestPostgresLockTaskStepForWriteHoldsTaskRowWhenNeverInAStep(t *testing.T) { + const step = "reattach-never-step-a" + repo := seedVisibilityLockFixture(t, "reattach-never-ws", "reattach-never-workflow", step) + ctx := context.Background() + + task := &models.Task{ + ID: "reattach-never-task", WorkspaceID: "reattach-never-ws", WorkflowID: "reattach-never-workflow", + WorkflowStepID: "", Title: "Never in a step", WIPAdmitted: false, + } + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed stepless task: %v", err) + } + + tx, err := repo.db.BeginTxx(ctx, nil) + if err != nil { + t.Fatalf("begin tx: %v", err) + } + defer func() { _ = tx.Rollback() }() + + if err := repo.lockTaskStepForWrite(ctx, tx, task.ID); err != nil { + t.Fatalf("lockTaskStepForWrite: %v", err) + } + + assertTaskRowBlocksConcurrentWrite(t, ctx, repo, tx, task.ID) +} + +// TestPostgresLockTaskStepForWriteLocksNewStepWhenReattachedDuringGap proves +// the other half: if the task is reattached to a different step in the gap +// lockTaskRowIfStepless exists to close, lockTaskStepForWrite must lock +// that new step rather than conclude there is nothing to protect. +func TestPostgresLockTaskStepForWriteLocksNewStepWhenReattachedDuringGap(t *testing.T) { + const stepA = "reattach-gap-step-a" + const stepB = "reattach-gap-step-b" + repo := seedVisibilityLockFixture(t, "reattach-gap-ws", "reattach-gap-workflow", stepA) + ctx := context.Background() + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind(` + INSERT INTO workflow_steps (id, workflow_id, name, position) + VALUES (?, ?, ?, ?) + `), stepB, "reattach-gap-workflow", stepB, 1); err != nil { + t.Fatalf("seed step B: %v", err) + } + + task := &models.Task{ + ID: "reattach-gap-task", WorkspaceID: "reattach-gap-ws", WorkflowID: "reattach-gap-workflow", + WorkflowStepID: stepA, Title: "Reattaching", WIPAdmitted: true, + } + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task: %v", err) + } + // Detach before the call even starts, so the unlocked first read already + // finds no step and the race lands in lockTaskRowIfStepless's own + // confirming lock rather than needing to also race the initial step + // lock. + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind( + `UPDATE tasks SET workflow_step_id = '' WHERE id = ?`, + ), task.ID); err != nil { + t.Fatalf("detach before the call: %v", err) + } + + paused := make(chan struct{}) + release := make(chan struct{}) + var releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(releaseFn) + calls := 0 + repo.taskRowReconfirmHook = func() { + calls++ + if calls != 1 { + return + } + close(paused) + <-release + } + t.Cleanup(func() { repo.taskRowReconfirmHook = nil }) + + tx, err := repo.db.BeginTxx(ctx, nil) + if err != nil { + t.Fatalf("begin tx: %v", err) + } + defer func() { _ = tx.Rollback() }() + + lockDone := make(chan error, 1) + go func() { + lockDone <- repo.lockTaskStepForWrite(ctx, tx, task.ID) + }() + <-paused + + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind( + `UPDATE tasks SET workflow_step_id = ? WHERE id = ?`, + ), stepB, task.ID); err != nil { + t.Fatalf("simulate concurrent reattach: %v", err) + } + releaseFn() + + if err := <-lockDone; err != nil { + t.Fatalf("lockTaskStepForWrite: %v", err) + } + + // stepB must now be the one locked: a concurrent ReorderStepTasks(stepB) + // should block until our tx commits. + reorderDone := make(chan error, 1) + go func() { + _, _, err := repo.ReorderStepTasks(ctx, stepB, ReorderBandAdmitted, []string{task.ID}) + reorderDone <- err + }() + select { + case err := <-reorderDone: + t.Fatalf("ReorderStepTasks(stepB) should have blocked behind the caller's lock on stepB, got: %v", err) + case <-time.After(300 * time.Millisecond): + // expected: still blocked while our tx is open + } + + if err := tx.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } + if err := <-reorderDone; err != nil { + t.Fatalf("ReorderStepTasks(stepB) after commit: %v", err) + } +} + +// assertTaskRowBlocksConcurrentWrite proves taskID's own row is locked by +// tx: a second connection's write to it must block until tx commits. A +// NOWAIT probe would also prove absence-of-lock, but this exercises the +// actual hazard lockTaskRowIfStepless exists to prevent (a concurrent +// writer completing unserialized against the caller's own mutation), and +// doubles as proof that a genuinely unrelated write (not a reattachment) +// is also correctly held back, not just rejected outright. +func assertTaskRowBlocksConcurrentWrite(t *testing.T, ctx context.Context, repo *Repository, tx *sqlx.Tx, taskID string) { + t.Helper() + writeDone := make(chan error, 1) + go func() { + _, err := repo.db.ExecContext(ctx, repo.db.Rebind( + `UPDATE tasks SET title = ? WHERE id = ?`, + ), "concurrent write", taskID) + writeDone <- err + }() + select { + case err := <-writeDone: + t.Fatalf("a concurrent write to the task's own row should have blocked (no protective lock held) "+ + "while the caller's tx is still open, got: %v", err) + case <-time.After(300 * time.Millisecond): + // expected: still blocked + } + + if err := tx.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } + if err := <-writeDone; err != nil { + t.Fatalf("concurrent write after commit: %v", err) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_step_lock_retry_release_postgres_test.go b/apps/backend/internal/task/repository/sqlite/task_step_lock_retry_release_postgres_test.go new file mode 100644 index 0000000000..be5ae07570 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_step_lock_retry_release_postgres_test.go @@ -0,0 +1,347 @@ +package sqlite + +// TestPostgresLockTaskStepForWriteReleasesStaleStepLockOnRetry and +// TestPostgresLockTaskStepForWriteReleasesStaleStepLockWhenTaskLeavesStep +// prove lockTaskStepForWrite's confirm-and-retry loop releases a stale step's +// FOR UPDATE lock (via ROLLBACK TO SAVEPOINT) on both outcomes of a mismatch — +// the task moved to a different step, or it left its step entirely — before +// returning or retrying. Each loop iteration's lock-then-confirm-then-release +// sequence is identical regardless of attempt number, so this reasoning +// generalizes, but the two tests below only instrument attempts 1 and 2: +// verified directly that it never holds more than one workflow_steps row lock +// across a single retry, not exhaustively for attempt 3 and beyond. Every +// other site in this package that locks two steps in +// one transaction sorts them ascending first (see lockWorkflowStepsForAdmission), +// specifically to avoid an AB-BA deadlock against another such locker. Before +// this fix, either outcome kept the stale step's lock held — Postgres has no +// per-row unlock short of a savepoint rollback — so the transaction could end +// up holding a step lock nothing still needed, in discovery order rather than +// sorted order: a real deadlock risk against a concurrent +// updateTaskWithWorkflowStepAdmission cross-step move over the same two steps. +// +// TestPostgresLockTaskStepForWriteRetryLeavesNoLockForConcurrentCrossStepMove +// is a weaker, complementary check, not a literal deadlock reproduction: since +// the fix above means the retry never holds more than one step lock, it can +// never actually contend against a concurrent sorted-order locker in this +// harness (the retry goroutine is deliberately paused holding zero locks at +// the moment the concurrent move runs), so it cannot raise Postgres's own +// SQLSTATE 40P01. What it shows instead is that the retry leaves no lock +// behind for an unrelated, correctly-ordered mover to trip over: a genuine +// cross-step move over the very same two steps completes promptly while the +// retry sits paused. Run against the pre-fix code, the equivalent scenario +// doesn't raise 40P01 either — it hangs, because the retry goroutine is +// parked on this harness's own pause channel before it ever issues the second +// lock request Postgres's cycle detector would need to see — so a pre-fix run +// times out rather than surfacing a captured deadlock error. +// +// Skips unless KANDEV_TEST_POSTGRES_DSN is set. + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" +) + +// armTwoStepLockHook arms repo.taskStepLockBeforeAcquireHook to pause on its +// first and second invocation, asserting the candidate step id each time. +// Returns the two pause channels (closed once that invocation is paused) +// and idempotent release functions, both also registered as t.Cleanup so a +// t.Fatalf between pausing and releasing cannot leak the paused goroutine. +func armTwoStepLockHook(t *testing.T, repo *Repository, wantFirst, wantSecond string) (pause1, pause2 chan struct{}, release1, release2 func()) { + t.Helper() + p1 := make(chan struct{}) + p2 := make(chan struct{}) + r1 := make(chan struct{}) + r2 := make(chan struct{}) + var release1Once, release2Once sync.Once + release1 = func() { release1Once.Do(func() { close(r1) }) } + release2 = func() { release2Once.Do(func() { close(r2) }) } + t.Cleanup(release1) + t.Cleanup(release2) + + var mu sync.Mutex + calls := 0 + repo.taskStepLockBeforeAcquireHook = func(candidateStepID string) { + mu.Lock() + calls++ + n := calls + mu.Unlock() + switch n { + case 1: + if candidateStepID != wantFirst { + t.Errorf("first candidate step = %q, want %q", candidateStepID, wantFirst) + } + close(p1) + <-r1 + case 2: + if candidateStepID != wantSecond { + t.Errorf("second candidate step = %q, want %q", candidateStepID, wantSecond) + } + close(p2) + <-r2 + } + } + return p1, p2, release1, release2 +} + +func TestPostgresLockTaskStepForWriteReleasesStaleStepLockOnRetry(t *testing.T) { + const stepA = "retry-release-step-a" + const stepB = "retry-release-step-b" + repo := seedVisibilityLockFixture(t, "retry-release-ws", "retry-release-workflow", stepA) + ctx := context.Background() + + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind(` + INSERT INTO workflow_steps (id, workflow_id, name, position) VALUES (?, ?, ?, ?) + `), stepB, "retry-release-workflow", stepB, 1); err != nil { + t.Fatalf("seed step B: %v", err) + } + + task := &models.Task{ + ID: "retry-release-task", WorkspaceID: "retry-release-ws", WorkflowID: "retry-release-workflow", + WorkflowStepID: stepB, Title: "Moving", WIPAdmitted: true, + } + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task: %v", err) + } + + pause1, pause2, release1, release2 := armTwoStepLockHook(t, repo, stepB, stepA) + t.Cleanup(func() { repo.taskStepLockBeforeAcquireHook = nil }) + + tx, err := repo.db.BeginTxx(ctx, nil) + if err != nil { + t.Fatalf("begin tx: %v", err) + } + defer func() { _ = tx.Rollback() }() + + lockDone := make(chan error, 1) + go func() { + lockDone <- repo.lockTaskStepForWrite(ctx, tx, task.ID) + }() + + <-pause1 // read stepB (the task's original step), about to lock it + + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind( + `UPDATE tasks SET workflow_step_id = ? WHERE id = ?`, + ), stepA, task.ID); err != nil { + t.Fatalf("simulate concurrent move: %v", err) + } + release1() + + <-pause2 // retry: read stepA, about to lock it + + // If the retry released stepB's now-stale lock (via a savepoint rollback) + // before moving on, a second connection can lock it immediately with + // FOR UPDATE NOWAIT. If the stale lock is still held, this errors instead + // of blocking indefinitely, so the assertion is immediate either way. + var lockedID string + probeErr := repo.db.QueryRowContext(ctx, repo.db.Rebind( + `SELECT id FROM workflow_steps WHERE id = ? FOR UPDATE NOWAIT`, + ), stepB).Scan(&lockedID) + if probeErr != nil { + t.Fatalf("stepB should be free once the retry moved on to stepA, but a second connection could not "+ + "acquire it NOWAIT (the stale lock from the first attempt is still held): %v", probeErr) + } + + release2() + if err := <-lockDone; err != nil { + t.Fatalf("lockTaskStepForWrite: %v", err) + } + if err := tx.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } +} + +// TestPostgresLockTaskStepForWriteReleasesStaleStepLockWhenTaskLeavesStep proves +// the confirming re-read's third outcome — the task no longer belongs to any +// step at all (workflow_step_id cleared, e.g. by a concurrent +// RemoveTaskFromWorkflow) rather than having moved to a different one — also +// releases the stale step lock instead of leaving it held for the rest of the +// caller's transaction. This is the same savepoint-lifecycle bug class the +// mismatch-retry path was already fixed for: readTaskWorkflowStepID maps both +// "no such task" and "workflow_step_id is empty" to (found=false, err=nil), so +// treating that only as "return, nothing more to do" without also rolling back +// the just-opened savepoint left the lock dangling. +func TestPostgresLockTaskStepForWriteReleasesStaleStepLockWhenTaskLeavesStep(t *testing.T) { + const stepA = "leaves-step-a" + repo := seedVisibilityLockFixture(t, "leaves-step-ws", "leaves-step-workflow", stepA) + ctx := context.Background() + + task := &models.Task{ + ID: "leaves-step-task", WorkspaceID: "leaves-step-ws", WorkflowID: "leaves-step-workflow", + WorkflowStepID: stepA, Title: "Leaving", WIPAdmitted: true, + } + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task: %v", err) + } + + paused := make(chan struct{}) + release := make(chan struct{}) + var releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(releaseFn) + + calls := 0 + repo.taskStepLockBeforeAcquireHook = func(candidateStepID string) { + calls++ + if calls != 1 { + t.Errorf("expected exactly one lock attempt (no step to retry against once the "+ + "task has left it), got attempt %d for %q", calls, candidateStepID) + return + } + if candidateStepID != stepA { + t.Errorf("candidate step = %q, want %q", candidateStepID, stepA) + } + close(paused) + <-release + } + t.Cleanup(func() { repo.taskStepLockBeforeAcquireHook = nil }) + + tx, err := repo.db.BeginTxx(ctx, nil) + if err != nil { + t.Fatalf("begin tx: %v", err) + } + defer func() { _ = tx.Rollback() }() + + lockDone := make(chan error, 1) + go func() { + lockDone <- repo.lockTaskStepForWrite(ctx, tx, task.ID) + }() + + <-paused // read stepA, about to lock it + + // Simulate a concurrent RemoveTaskFromWorkflow: detach the task from its + // step entirely. Runs on a separate pooled connection and autocommits + // immediately, so it's fully visible once release() lets the paused + // goroutine proceed to its confirming FOR UPDATE read. + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind( + `UPDATE tasks SET workflow_step_id = '' WHERE id = ?`, + ), task.ID); err != nil { + t.Fatalf("simulate concurrent detach: %v", err) + } + releaseFn() + + if err := <-lockDone; err != nil { + t.Fatalf("lockTaskStepForWrite: %v", err) + } + + // If stepA's lock was released (rolled back to the savepoint) once the + // confirming read found no step left to protect, a second connection can + // lock it immediately with FOR UPDATE NOWAIT. If it's still held, this + // errors instead of blocking indefinitely, so the assertion is immediate + // either way. + var lockedID string + probeErr := repo.db.QueryRowContext(ctx, repo.db.Rebind( + `SELECT id FROM workflow_steps WHERE id = ? FOR UPDATE NOWAIT`, + ), stepA).Scan(&lockedID) + if probeErr != nil { + t.Fatalf("stepA should be free once the task left it, but a second connection could not "+ + "acquire it NOWAIT (the stale lock is still held): %v", probeErr) + } + + if err := tx.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } +} + +func TestPostgresLockTaskStepForWriteRetryLeavesNoLockForConcurrentCrossStepMove(t *testing.T) { + const stepA = "retry-deadlock-step-a" + const stepB = "retry-deadlock-step-b" + repo := seedVisibilityLockFixture(t, "retry-deadlock-ws", "retry-deadlock-workflow", stepA) + ctx := context.Background() + + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind(` + INSERT INTO workflow_steps (id, workflow_id, name, position) VALUES (?, ?, ?, ?) + `), stepB, "retry-deadlock-workflow", stepB, 1); err != nil { + t.Fatalf("seed step B: %v", err) + } + + x := &models.Task{ + ID: "retry-deadlock-task-x", WorkspaceID: "retry-deadlock-ws", WorkflowID: "retry-deadlock-workflow", + WorkflowStepID: stepB, Title: "X", WIPAdmitted: true, + } + y := &models.Task{ + ID: "retry-deadlock-task-y", WorkspaceID: "retry-deadlock-ws", WorkflowID: "retry-deadlock-workflow", + WorkflowStepID: stepA, Title: "Y", WIPAdmitted: true, + } + for _, task := range []*models.Task{x, y} { + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task %s: %v", task.ID, err) + } + } + + pause1, pause2, release1, release2 := armTwoStepLockHook(t, repo, stepB, stepA) + t.Cleanup(func() { repo.taskStepLockBeforeAcquireHook = nil }) + + tx, err := repo.db.BeginTxx(ctx, nil) + if err != nil { + t.Fatalf("begin tx: %v", err) + } + defer func() { _ = tx.Rollback() }() + + lockDone := make(chan error, 1) + go func() { + lockDone <- repo.lockTaskStepForWrite(ctx, tx, x.ID) + }() + + <-pause1 // Op1 read stepB (X's original step), about to lock it + + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind( + `UPDATE tasks SET workflow_step_id = ? WHERE id = ?`, + ), stepA, x.ID); err != nil { + t.Fatalf("simulate concurrent move of X: %v", err) + } + release1() + + <-pause2 // Op1's retry read stepA, about to lock it; a fixed implementation + // has already released stepB by this point, so Op1 holds no lock here. + + // Op2: a genuine cross-step move of a DIFFERENT task, which locks stepA + // then stepB (updateTaskWithWorkflowStepAdmission's own established + // ascending order). Op1 holds nothing at this point (see above), so this + // is not contended and completing promptly is expected, not evidence of + // deadlock avoidance under real contention — see the file header for what + // this test does and doesn't prove. + moveDone := make(chan error, 1) + go func() { + _, moveErr := repo.UpdateTaskWithWorkflowStepAdmission(ctx, y, stepA, stepB, 0) + moveDone <- moveErr + }() + + select { + case err := <-moveDone: + if err != nil { + t.Fatalf("cross-step move of Y: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatalf("cross-step move of Y did not complete within 5s — prime suspect is a savepoint-rollback " + + "regression leaving Op1 still holding stepB's lock (Op1 is supposed to hold none at this " + + "point); it is not a captured 40P01, since Op1 never reaches its second lock request while " + + "parked on this harness's own pause channel") + } + + release2() + + select { + case err := <-lockDone: + if err != nil { + t.Fatalf("lockTaskStepForWrite: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatalf("lockTaskStepForWrite did not complete within 5s") + } + + if err := tx.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } + + movedY, err := repo.GetTask(ctx, y.ID) + if err != nil { + t.Fatalf("reload Y: %v", err) + } + if movedY.WorkflowStepID != stepB { + t.Fatalf("Y ended up in step %q, want %q", movedY.WorkflowStepID, stepB) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_step_lock_toctou_postgres_test.go b/apps/backend/internal/task/repository/sqlite/task_step_lock_toctou_postgres_test.go new file mode 100644 index 0000000000..bb1591609a --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_step_lock_toctou_postgres_test.go @@ -0,0 +1,119 @@ +package sqlite + +// TestLockTaskStepForWriteLocksCurrentStepAfterConcurrentMove proves +// lockTaskStepForWrite (used by ArchiveTask, ArchiveTaskIfActive, DeleteTask +// and UnarchiveTask/UnarchiveTaskByCascade) still locks the task's true +// current step when a concurrent move changes that step in the gap between +// its candidate read and its lock acquisition. Before this fix, +// lockTaskStepForWrite read the task's step once, unlocked, and only then +// called lockWorkflowStepForWrite on whatever it read - so a move landing in +// that gap left it locking a step the task had already left, defeating its +// own serialization guarantee against a reorder of the task's real step. +// +// Skips unless KANDEV_TEST_POSTGRES_DSN is set. + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" +) + +func TestLockTaskStepForWriteLocksCurrentStepAfterConcurrentMove(t *testing.T) { + const stepA = "toctou-step-a" + const stepB = "toctou-step-b" + repo := seedVisibilityLockFixture(t, "toctou-ws", "toctou-workflow", stepA) + ctx := context.Background() + + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind(` + INSERT INTO workflow_steps (id, workflow_id, name, position) VALUES (?, ?, ?, ?) + `), stepB, "toctou-workflow", stepB, 1); err != nil { + t.Fatalf("seed step B: %v", err) + } + + task := &models.Task{ + ID: "toctou-task", WorkspaceID: "toctou-ws", WorkflowID: "toctou-workflow", + WorkflowStepID: stepA, Title: "Moving", WIPAdmitted: true, + } + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task: %v", err) + } + + paused := make(chan struct{}) + release := make(chan struct{}) + var pauseOnce sync.Once + var fired bool + repo.taskStepLockBeforeAcquireHook = func(candidateStepID string) { + if fired { + return + } + fired = true + if candidateStepID != stepA { + t.Errorf("first candidate step = %q, want %q", candidateStepID, stepA) + } + pauseOnce.Do(func() { close(paused) }) + <-release + } + var releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(releaseFn) + t.Cleanup(func() { repo.taskStepLockBeforeAcquireHook = nil }) + + tx, err := repo.db.BeginTxx(ctx, nil) + if err != nil { + t.Fatalf("begin tx: %v", err) + } + defer func() { _ = tx.Rollback() }() + + lockDone := make(chan error, 1) + go func() { + lockDone <- repo.lockTaskStepForWrite(ctx, tx, task.ID) + }() + + <-paused // lockTaskStepForWrite read stepA, has not locked it yet + + // A concurrent move commits fully in the exact gap between the read + // above and the lock it is about to take. + if _, err := repo.db.ExecContext(ctx, repo.db.Rebind( + `UPDATE tasks SET workflow_step_id = ? WHERE id = ?`, + ), stepB, task.ID); err != nil { + t.Fatalf("simulate concurrent move: %v", err) + } + + releaseFn() + if err := <-lockDone; err != nil { + t.Fatalf("lockTaskStepForWrite: %v", err) + } + + // tx must now hold stepB's row lock: a second connection trying to lock + // it should block until tx ends. repo.db's pool has spare connections + // (seedVisibilityLockFixture opens it with maxConns=3), so this reaches + // the same isolated schema over a different physical connection. + blocked := make(chan struct{}) + go func() { + var id string + _ = repo.db.QueryRowContext(ctx, repo.db.Rebind( + `SELECT id FROM workflow_steps WHERE id = ? FOR UPDATE`, + ), stepB).Scan(&id) + close(blocked) + }() + + select { + case <-blocked: + t.Fatalf("a second connection locked step %q while lockTaskStepForWrite's transaction should still "+ + "hold it — it locked the task's stale pre-move step instead of its current one", stepB) + case <-time.After(200 * time.Millisecond): + } + + if err := tx.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } + + select { + case <-blocked: + case <-time.After(2 * time.Second): + t.Fatalf("second connection never acquired step %q's lock after commit", stepB) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_update_preserves_position_test.go b/apps/backend/internal/task/repository/sqlite/task_update_preserves_position_test.go new file mode 100644 index 0000000000..21036ea378 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_update_preserves_position_test.go @@ -0,0 +1,121 @@ +package sqlite + +import ( + "context" + "testing" + + "github.com/kandev/kandev/internal/task/models" +) + +// TestUpdateTaskPreservesPositionAcrossConcurrentReorder proves the fix for +// the stale-position clobber: a caller that read a task before a reorder of +// its step committed, and then writes an ordinary field change (not a +// position change) using that pre-reorder snapshot, must not undo the +// reorder. Simulated deterministically rather than with real goroutines: the +// "stale" struct is exactly what a caller's in-memory copy would hold after +// GetTask ran before the reorder. +func TestUpdateTaskPreservesPositionAcrossConcurrentReorder(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-preserve") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-preserve", WorkspaceID: "ws-preserve", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-preserve", "wf-preserve") + mustCreateReorderTask(t, ctx, repo, "task-a", "ws-preserve", "wf-preserve", "step-preserve") + mustCreateReorderTask(t, ctx, repo, "task-b", "ws-preserve", "wf-preserve", "step-preserve") + + staleTaskA, err := repo.GetTask(ctx, "task-a") + if err != nil { + t.Fatalf("GetTask: %v", err) + } + if staleTaskA.Position != 0 { + t.Fatalf("staleTaskA.Position = %d, want 0 before any reorder", staleTaskA.Position) + } + + if _, _, err := repo.ReorderStepTasks(ctx, "step-preserve", ReorderBandAdmitted, + []string{"task-b", "task-a"}); err != nil { + t.Fatalf("ReorderStepTasks: %v", err) + } + if got := taskPosition(t, ctx, repo, "task-a"); got != 1 { + t.Fatalf("task-a position after reorder = %d, want 1", got) + } + + // staleTaskA still holds position 0 from before the reorder. An ordinary + // field edit using it must not write that stale value back. + staleTaskA.Title = "renamed while stale" + if err := repo.UpdateTask(ctx, staleTaskA); err != nil { + t.Fatalf("UpdateTask: %v", err) + } + + if got := taskPosition(t, ctx, repo, "task-a"); got != 1 { + t.Fatalf("task-a position after stale UpdateTask = %d, want 1 (the reorder's value preserved)", got) + } + reloaded, err := repo.GetTask(ctx, "task-a") + if err != nil { + t.Fatalf("GetTask: %v", err) + } + if reloaded.Title != "renamed while stale" { + t.Fatalf("title = %q, want the ordinary edit to still apply", reloaded.Title) + } +} + +// TestUpdateTaskWithExplicitPositionWritesLiteralValue proves the one +// escape hatch (the generic task-update API's explicit position field, +// which predates the reorder contract) still writes exactly what the caller +// supplies, so fixing the stale-write bug above does not silently disable +// it. +func TestUpdateTaskWithExplicitPositionWritesLiteralValue(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-explicit") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-explicit", WorkspaceID: "ws-explicit", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-explicit", "wf-explicit") + task := mustCreateReorderTask(t, ctx, repo, "task-explicit", "ws-explicit", "wf-explicit", "step-explicit") + + task.Position = 42 + if err := repo.UpdateTaskWithExplicitPosition(ctx, task); err != nil { + t.Fatalf("UpdateTaskWithExplicitPosition: %v", err) + } + + if got := taskPosition(t, ctx, repo, "task-explicit"); got != 42 { + t.Fatalf("position = %d, want 42 (caller-supplied value honored)", got) + } +} + +// TestUpdateTaskIfWorkflowMatchesPreservesPosition covers the same-step +// plugin-move path (updateMovedTaskSameStep's CAS-guarded branch), which +// AC-TASKS-KANBAN-TASK-REORDERING-001.28 requires to leave position +// unchanged: it must not reintroduce a stale position either. +func TestUpdateTaskIfWorkflowMatchesPreservesPosition(t *testing.T) { + repo := newRepoForEntityTests(t) + ctx := context.Background() + seedWorkspace(t, repo, "ws-cas-preserve") + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-cas-preserve", WorkspaceID: "ws-cas-preserve", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderStep(t, repo, "step-cas-preserve", "wf-cas-preserve") + mustCreateReorderTask(t, ctx, repo, "task-a", "ws-cas-preserve", "wf-cas-preserve", "step-cas-preserve") + mustCreateReorderTask(t, ctx, repo, "task-b", "ws-cas-preserve", "wf-cas-preserve", "step-cas-preserve") + + staleTaskA, err := repo.GetTask(ctx, "task-a") + if err != nil { + t.Fatalf("GetTask: %v", err) + } + + if _, _, err := repo.ReorderStepTasks(ctx, "step-cas-preserve", ReorderBandAdmitted, + []string{"task-b", "task-a"}); err != nil { + t.Fatalf("ReorderStepTasks: %v", err) + } + + staleTaskA.Description = "same-step plugin move while stale" + if err := repo.UpdateTaskIfWorkflowMatches(ctx, staleTaskA, "wf-cas-preserve"); err != nil { + t.Fatalf("UpdateTaskIfWorkflowMatches: %v", err) + } + + if got := taskPosition(t, ctx, repo, "task-a"); got != 1 { + t.Fatalf("task-a position = %d, want 1 (the reorder's value preserved)", got) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_visibility_lock_postgres_test.go b/apps/backend/internal/task/repository/sqlite/task_visibility_lock_postgres_test.go new file mode 100644 index 0000000000..cf3a3d4cdb --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/task_visibility_lock_postgres_test.go @@ -0,0 +1,403 @@ +package sqlite + +// TestPostgresArchiveLocksStepAgainstConcurrentReorder and +// TestPostgresDeleteLocksStepAgainstConcurrentReorder prove ArchiveTask and +// DeleteTask lock the step a task belongs to (lockTaskStepForWrite) before +// changing its visibility, so a concurrent ReorderStepTasks of that same +// step cannot straddle the change: REQ-TASKS-KANBAN-TASK-REORDERING-001.15 +// (a hidden task's position shall not be rewritten) and .26 (a task leaving +// a band's membership during the race window is a conflict, never a silent +// success). Before this lock existed, ArchiveTask and DeleteTask took no +// step-scoped lock at all, so either could commit in the window between +// ReorderStepTasks' membership read and its blind per-task position write — +// DeleteTask's case is the sharper one: the renumbering UPDATE has no +// RowsAffected check, so it would silently write zero rows for a task +// already gone, and ReorderStepTasks would still report success naming a +// task that no longer existed. +// +// Both tests use reorderPreWriteHook (mirrors the promotion-lock test) to +// pause a reorder transaction after its membership read but before its +// write, run the concurrent archive/delete during that pause, and then +// observe the target row's visibility WHILE the reorder is still paused — +// a genuinely deterministic check, since a transaction blocked on Postgres' +// row lock cannot have committed regardless of timing. +// +// Skips unless KANDEV_TEST_POSTGRES_DSN is set. + +import ( + "context" + "database/sql" + "errors" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/orchestrator/messagequeue" + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" + "github.com/kandev/kandev/internal/testutil" +) + +func seedVisibilityLockFixture(t *testing.T, wsID, workflowID, stepID string) *Repository { + t.Helper() + db := openIsolatedPostgresMultiConn(t, testutil.PostgresDSNFromEnv(t), 3) + repo, err := NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("init postgres schema: %v", err) + } + // ArchiveTask/DeleteTask purge the task's queue, which requires the + // messagequeue package's own tables (not part of this package's schema). + if _, err := messagequeue.NewSQLiteRepository(db, db); err != nil { + t.Fatalf("init messagequeue schema: %v", err) + } + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: wsID, Name: "Visibility lock workspace"}); err != nil { + t.Fatalf("seed workspace: %v", err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: workflowID, WorkspaceID: wsID, Name: "Visibility lock workflow"}); err != nil { + t.Fatalf("seed workflow: %v", err) + } + if _, err := db.Exec(db.Rebind(` + INSERT INTO workflow_steps (id, workflow_id, name, position) + VALUES (?, ?, ?, ?) + `), stepID, workflowID, stepID, 0); err != nil { + t.Fatalf("seed workflow step %s: %v", stepID, err) + } + return repo +} + +// armReorderPause returns a channel closed once a ReorderStepTasks call has +// read stepID's membership and is paused before its write, plus a releaseFn +// that resumes it. releaseFn is safe to call more than once (the second call +// is a no-op) and is also registered as t.Cleanup, so a t.Fatalf between +// pausing and releasing still unblocks the paused reorder goroutine instead +// of leaking it and hanging the schema-drop cleanup. +func armReorderPause(t *testing.T, repo *Repository) (paused chan struct{}, releaseFn func()) { + t.Helper() + paused = make(chan struct{}) + release := make(chan struct{}) + var releaseOnce sync.Once + releaseFn = func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(releaseFn) + + var fired bool + repo.reorderPreWriteHook = func() { + if fired { + return + } + fired = true + close(paused) + <-release + } + return paused, releaseFn +} + +func TestPostgresArchiveLocksStepAgainstConcurrentReorder(t *testing.T) { + const step = "archive-lock-step" + repo := seedVisibilityLockFixture(t, "archive-lock-ws", "archive-lock-workflow", step) + ctx := context.Background() + + archiving := &models.Task{ + ID: "archive-lock-target", WorkspaceID: "archive-lock-ws", WorkflowID: "archive-lock-workflow", + WorkflowStepID: step, Title: "Archiving", WIPAdmitted: true, + } + stays := &models.Task{ + ID: "archive-lock-stays", WorkspaceID: "archive-lock-ws", WorkflowID: "archive-lock-workflow", + WorkflowStepID: step, Title: "Stays", WIPAdmitted: true, + } + for _, task := range []*models.Task{archiving, stays} { + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task %s: %v", task.ID, err) + } + } + + paused, release := armReorderPause(t, repo) + t.Cleanup(func() { repo.reorderPreWriteHook = nil }) + + var wg sync.WaitGroup + var reorderErr, archiveErr error + wg.Add(1) + go func() { + defer wg.Done() + _, _, reorderErr = repo.ReorderStepTasks(ctx, step, ReorderBandAdmitted, []string{archiving.ID, stays.ID}) + }() + + <-paused // reorder holds step's row lock, has already read archiving as still live + + wg.Add(1) + go func() { + defer wg.Done() + archiveErr = repo.ArchiveTask(ctx, archiving.ID) + }() + + // Give the archive goroutine time to either run to completion (unfixed + // code, no step lock) or register its wait against reorder's held step + // lock (fixed code) before we peek at its committed state. + time.Sleep(200 * time.Millisecond) + + var archivedAlready sql.NullTime + if err := repo.db.QueryRowContext(ctx, repo.db.Rebind( + `SELECT archived_at FROM tasks WHERE id = ?`, + ), archiving.ID).Scan(&archivedAlready); err != nil { + t.Fatalf("peek archived_at mid-pause: %v", err) + } + if archivedAlready.Valid { + t.Fatalf("ArchiveTask committed while the reorder still held step %q's lock: it must wait behind "+ + "the reorder instead of racing its read-then-write window", step) + } + + release() + wg.Wait() + + if archiveErr != nil { + t.Fatalf("archive must always succeed: %v", archiveErr) + } + if reorderErr != nil && !errors.Is(reorderErr, repoerrors.ErrStepChanged) { + t.Fatalf("reorder error = %v, want nil or ErrStepChanged", reorderErr) + } + + stored, err := repo.GetTask(ctx, archiving.ID) + if err != nil { + t.Fatalf("reload archived task: %v", err) + } + if stored.ArchivedAt == nil { + t.Fatalf("task %q was not archived", archiving.ID) + } +} + +func TestPostgresDeleteLocksStepAgainstConcurrentReorder(t *testing.T) { + const step = "delete-lock-step" + repo := seedVisibilityLockFixture(t, "delete-lock-ws", "delete-lock-workflow", step) + ctx := context.Background() + + deleting := &models.Task{ + ID: "delete-lock-target", WorkspaceID: "delete-lock-ws", WorkflowID: "delete-lock-workflow", + WorkflowStepID: step, Title: "Deleting", WIPAdmitted: true, + } + stays := &models.Task{ + ID: "delete-lock-stays", WorkspaceID: "delete-lock-ws", WorkflowID: "delete-lock-workflow", + WorkflowStepID: step, Title: "Stays", WIPAdmitted: true, + } + for _, task := range []*models.Task{deleting, stays} { + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task %s: %v", task.ID, err) + } + } + + paused, release := armReorderPause(t, repo) + t.Cleanup(func() { repo.reorderPreWriteHook = nil }) + + var wg sync.WaitGroup + var reorderErr, deleteErr error + wg.Add(1) + go func() { + defer wg.Done() + _, _, reorderErr = repo.ReorderStepTasks(ctx, step, ReorderBandAdmitted, []string{deleting.ID, stays.ID}) + }() + + <-paused // reorder holds step's row lock, has already read deleting as still live + + wg.Add(1) + go func() { + defer wg.Done() + deleteErr = repo.DeleteTask(ctx, deleting.ID) + }() + + // Give the delete goroutine time to either run to completion (unfixed + // code, no step lock) or register its wait against reorder's held step + // lock (fixed code) before we peek at its committed state. + time.Sleep(200 * time.Millisecond) + + var stillExists bool + if err := repo.db.QueryRowContext(ctx, repo.db.Rebind( + `SELECT EXISTS (SELECT 1 FROM tasks WHERE id = ?)`, + ), deleting.ID).Scan(&stillExists); err != nil { + t.Fatalf("peek row existence mid-pause: %v", err) + } + if !stillExists { + t.Fatalf("DeleteTask committed while the reorder still held step %q's lock: it must wait behind "+ + "the reorder instead of racing its read-then-write window", step) + } + + release() + wg.Wait() + + if deleteErr != nil { + t.Fatalf("delete must always succeed: %v", deleteErr) + } + if reorderErr != nil && !errors.Is(reorderErr, repoerrors.ErrStepChanged) { + t.Fatalf("reorder error = %v, want nil or ErrStepChanged", reorderErr) + } + + if _, err := repo.GetTask(ctx, deleting.ID); !errors.Is(err, ErrTaskNotFound) { + t.Fatalf("GetTask(deleted task) error = %v, want ErrTaskNotFound", err) + } +} + +// TestPostgresUnarchiveLocksStepAgainstConcurrentReorder and +// TestPostgresUnarchiveByCascadeLocksStepAgainstConcurrentReorder prove +// UnarchiveTask and UnarchiveTaskByCascade take the same lockTaskStepForWrite +// guard as ArchiveTask/ArchiveTaskIfActive/DeleteTask above. Before this, +// both were bare, non-transactional updates: a task reappearing mid-reorder +// could still hold the stale position it had before it was archived, which +// can collide with (or fall outside) the range the reorder just renumbered +// the step's live tasks into — REQ-TASKS-KANBAN-TASK-REORDERING-001.15's +// dense, gap-free guarantee holds only over the tasks a reorder actually +// saw. +func TestPostgresUnarchiveLocksStepAgainstConcurrentReorder(t *testing.T) { + const step = "unarchive-lock-step" + repo := seedVisibilityLockFixture(t, "unarchive-lock-ws", "unarchive-lock-workflow", step) + ctx := context.Background() + + unarchiving := &models.Task{ + ID: "unarchive-lock-target", WorkspaceID: "unarchive-lock-ws", WorkflowID: "unarchive-lock-workflow", + WorkflowStepID: step, Title: "Unarchiving", WIPAdmitted: true, + } + stays1 := &models.Task{ + ID: "unarchive-lock-stays-1", WorkspaceID: "unarchive-lock-ws", WorkflowID: "unarchive-lock-workflow", + WorkflowStepID: step, Title: "Stays 1", WIPAdmitted: true, + } + stays2 := &models.Task{ + ID: "unarchive-lock-stays-2", WorkspaceID: "unarchive-lock-ws", WorkflowID: "unarchive-lock-workflow", + WorkflowStepID: step, Title: "Stays 2", WIPAdmitted: true, + } + for _, task := range []*models.Task{unarchiving, stays1, stays2} { + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task %s: %v", task.ID, err) + } + } + if err := repo.ArchiveTask(ctx, unarchiving.ID); err != nil { + t.Fatalf("pre-archive %s: %v", unarchiving.ID, err) + } + + paused, release := armReorderPause(t, repo) + t.Cleanup(func() { repo.reorderPreWriteHook = nil }) + + var wg sync.WaitGroup + var reorderErr, unarchiveErr error + wg.Add(1) + go func() { + defer wg.Done() + _, _, reorderErr = repo.ReorderStepTasks(ctx, step, ReorderBandAdmitted, []string{stays1.ID, stays2.ID}) + }() + + <-paused // reorder holds step's row lock, has already read the live membership (unarchiving excluded) + + wg.Add(1) + go func() { + defer wg.Done() + _, unarchiveErr = repo.UnarchiveTask(ctx, unarchiving.ID) + }() + + // Give the unarchive goroutine time to either run to completion (unfixed + // code, no step lock) or register its wait against reorder's held step + // lock (fixed code) before we peek at its committed state. + time.Sleep(200 * time.Millisecond) + + var archivedAtMidPause sql.NullTime + if err := repo.db.QueryRowContext(ctx, repo.db.Rebind( + `SELECT archived_at FROM tasks WHERE id = ?`, + ), unarchiving.ID).Scan(&archivedAtMidPause); err != nil { + t.Fatalf("peek archived_at mid-pause: %v", err) + } + if !archivedAtMidPause.Valid { + t.Fatalf("UnarchiveTask committed while the reorder still held step %q's lock: it must wait behind "+ + "the reorder instead of racing its read-then-write window", step) + } + + release() + wg.Wait() + + if unarchiveErr != nil { + t.Fatalf("unarchive must always succeed: %v", unarchiveErr) + } + if reorderErr != nil && !errors.Is(reorderErr, repoerrors.ErrStepChanged) { + t.Fatalf("reorder error = %v, want nil or ErrStepChanged", reorderErr) + } + + stored, err := repo.GetTask(ctx, unarchiving.ID) + if err != nil { + t.Fatalf("reload unarchived task: %v", err) + } + if stored.ArchivedAt != nil { + t.Fatalf("task %q is still archived", unarchiving.ID) + } +} + +func TestPostgresUnarchiveByCascadeLocksStepAgainstConcurrentReorder(t *testing.T) { + const step = "unarchive-cascade-lock-step" + const cascadeID = "unarchive-cascade-lock-cascade" + repo := seedVisibilityLockFixture(t, "unarchive-cascade-lock-ws", "unarchive-cascade-lock-workflow", step) + ctx := context.Background() + + unarchiving := &models.Task{ + ID: "unarchive-cascade-lock-target", WorkspaceID: "unarchive-cascade-lock-ws", + WorkflowID: "unarchive-cascade-lock-workflow", WorkflowStepID: step, Title: "Unarchiving", WIPAdmitted: true, + } + stays1 := &models.Task{ + ID: "unarchive-cascade-lock-stays-1", WorkspaceID: "unarchive-cascade-lock-ws", + WorkflowID: "unarchive-cascade-lock-workflow", WorkflowStepID: step, Title: "Stays 1", WIPAdmitted: true, + } + stays2 := &models.Task{ + ID: "unarchive-cascade-lock-stays-2", WorkspaceID: "unarchive-cascade-lock-ws", + WorkflowID: "unarchive-cascade-lock-workflow", WorkflowStepID: step, Title: "Stays 2", WIPAdmitted: true, + } + for _, task := range []*models.Task{unarchiving, stays1, stays2} { + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task %s: %v", task.ID, err) + } + } + if _, err := repo.ArchiveTaskIfActive(ctx, unarchiving.ID, cascadeID); err != nil { + t.Fatalf("pre-archive %s: %v", unarchiving.ID, err) + } + + paused, release := armReorderPause(t, repo) + t.Cleanup(func() { repo.reorderPreWriteHook = nil }) + + var wg sync.WaitGroup + var reorderErr, unarchiveErr error + wg.Add(1) + go func() { + defer wg.Done() + _, _, reorderErr = repo.ReorderStepTasks(ctx, step, ReorderBandAdmitted, []string{stays1.ID, stays2.ID}) + }() + + <-paused // reorder holds step's row lock, has already read the live membership (unarchiving excluded) + + wg.Add(1) + go func() { + defer wg.Done() + _, unarchiveErr = repo.UnarchiveTaskByCascade(ctx, unarchiving.ID, cascadeID) + }() + + time.Sleep(200 * time.Millisecond) + + var archivedAtMidPause sql.NullTime + if err := repo.db.QueryRowContext(ctx, repo.db.Rebind( + `SELECT archived_at FROM tasks WHERE id = ?`, + ), unarchiving.ID).Scan(&archivedAtMidPause); err != nil { + t.Fatalf("peek archived_at mid-pause: %v", err) + } + if !archivedAtMidPause.Valid { + t.Fatalf("UnarchiveTaskByCascade committed while the reorder still held step %q's lock: it must wait "+ + "behind the reorder instead of racing its read-then-write window", step) + } + + release() + wg.Wait() + + if unarchiveErr != nil { + t.Fatalf("unarchive must always succeed: %v", unarchiveErr) + } + if reorderErr != nil && !errors.Is(reorderErr, repoerrors.ErrStepChanged) { + t.Fatalf("reorder error = %v, want nil or ErrStepChanged", reorderErr) + } + + stored, err := repo.GetTask(ctx, unarchiving.ID) + if err != nil { + t.Fatalf("reload unarchived task: %v", err) + } + if stored.ArchivedAt != nil { + t.Fatalf("task %q is still archived", unarchiving.ID) + } +} diff --git a/apps/backend/internal/task/repository/sqlite/task_wip_postgres_test.go b/apps/backend/internal/task/repository/sqlite/task_wip_postgres_test.go index 90946a773c..58afd35db1 100644 --- a/apps/backend/internal/task/repository/sqlite/task_wip_postgres_test.go +++ b/apps/backend/internal/task/repository/sqlite/task_wip_postgres_test.go @@ -67,7 +67,7 @@ func TestPostgresUpdateTaskWithWorkflowStepAdmission_ConcurrentLastSlot(t *testi go func(task *models.Task) { defer wg.Done() <-start - admitted, err := repo.UpdateTaskWithWorkflowStepAdmission(ctx, task, targetStep, 2) + admitted, err := repo.UpdateTaskWithWorkflowStepAdmission(ctx, task, "postgres-wip-source", targetStep, 2) results <- struct { admitted bool err error diff --git a/apps/backend/internal/task/repository/sqlite/workspace.go b/apps/backend/internal/task/repository/sqlite/workspace.go index 0e28a258d6..0f114c5010 100644 --- a/apps/backend/internal/task/repository/sqlite/workspace.go +++ b/apps/backend/internal/task/repository/sqlite/workspace.go @@ -217,6 +217,16 @@ func (r *Repository) deleteWorkspaceCascade( if err != nil { return nil, nil, err } + // Lock every workflow_steps row this workspace owns BEFORE any task row: + // ReorderStepTasks and lockTaskStepForWrite's callers (Archive/Delete/ + // Unarchive) both lock a step before the task rows inside it, so this + // cascade must acquire the same two resources in the same order or a + // concurrent reorder of one of these steps can deadlock against it on + // Postgres (each transaction waiting on the resource the other already + // holds). Sorted id order mirrors the task-row locking below. + if err := r.lockWorkspaceStepRowsInTx(ctx, tx, id); err != nil { + return nil, nil, err + } // Establish the global lock order task-row -> queue-session before // purging the queues: lifecycle admission takes the task row first and // then the session lock, so taking session locks first here would invert @@ -403,6 +413,42 @@ func (r *Repository) listWorkspaceCascadeDeleteWorkflows( return scanWorkflowRows(rows) } +// lockWorkspaceStepRowsInTx locks (Postgres FOR UPDATE; no-op on SQLite, +// whose single writer connection already serializes) every workflow_steps +// row belonging to workspaceID's workflows, in sorted id order. Called before +// any task-row lock in the delete cascade so it acquires steps and tasks in +// the same order ReorderStepTasks and lockTaskStepForWrite's callers do. +func (r *Repository) lockWorkspaceStepRowsInTx(ctx context.Context, tx *sqlx.Tx, workspaceID string) error { + rows, err := tx.QueryContext(ctx, r.db.Rebind(` + SELECT id FROM workflow_steps + WHERE workflow_id IN (SELECT id FROM workflows WHERE workspace_id = ?) + ORDER BY id + `), workspaceID) + if err != nil { + return fmt.Errorf("list workspace step rows to lock: %w", err) + } + var stepIDs []string + for rows.Next() { + var stepID string + if err := rows.Scan(&stepID); err != nil { + _ = rows.Close() + return fmt.Errorf("scan workspace step row to lock: %w", err) + } + stepIDs = append(stepIDs, stepID) + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return fmt.Errorf("list workspace step rows to lock: %w", err) + } + _ = rows.Close() + for _, stepID := range stepIDs { + if err := lockWorkflowStepForWrite(ctx, tx, r.db.DriverName(), r.db.Rebind, stepID); err != nil { + return fmt.Errorf("lock workspace cascade step row %s: %w", stepID, err) + } + } + return nil +} + // ListWorkspaces returns all workspaces // ClaimUnownedWorkspaces assigns every pre-auth workspace (empty owner_id) to // ownerID. Called by the auth setup wizard when promoting the instance's diff --git a/apps/backend/internal/task/repository/sqlite/workspace_cascade_lock_postgres_test.go b/apps/backend/internal/task/repository/sqlite/workspace_cascade_lock_postgres_test.go new file mode 100644 index 0000000000..ac5cb517d6 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/workspace_cascade_lock_postgres_test.go @@ -0,0 +1,123 @@ +package sqlite + +// TestPostgresWorkspaceCascadeDeleteLocksStepAgainstConcurrentReorder proves +// DeleteWorkspaceCascade locks a workspace's workflow_steps rows (via +// lockWorkflowStepForWrite) BEFORE it locks or deletes any task row, so a +// concurrent ReorderStepTasks of one of those steps cannot interleave with +// the cascade in a way that inverts this package's established lock order. +// +// Every other writer that touches both a step and its tasks in the same +// transaction (ReorderStepTasks, lockTaskStepForWrite's callers: ArchiveTask, +// ArchiveTaskIfActive, DeleteTask, UnarchiveTask, UnarchiveTaskByCascade) +// locks the step first and task rows second. Before this fix, +// deleteWorkspaceCascade inverted that order: it locked task rows (sorted by +// id, to establish task-row -> queue-session order) and deleted them BEFORE +// ever touching workflow_steps, which it only locked implicitly and late, via +// its closing `DELETE FROM workflow_steps ...`. Two transactions acquiring +// the same two resources in opposite orders is the textbook precondition for +// a real Postgres deadlock: a reorder holding the step lock while waiting on +// a task row the cascade already holds, and the cascade holding that task row +// while waiting on the step lock the reorder already holds, with neither able +// to proceed and Postgres left to abort one after its deadlock_timeout. +// +// This test does not need to provoke the deadlock detector itself (timing- +// dependent and slow); it proves the ordering fix directly, the same way the +// sibling archive/delete/unarchive tests in task_visibility_lock_postgres_test.go +// do: pause a reorder holding stepID's row lock via reorderPreWriteHook, run +// DeleteWorkspaceCascade concurrently, and observe — deterministically, since +// a transaction blocked on a Postgres row lock cannot have committed +// regardless of timing — that the workspace row is still present while the +// reorder is still paused. That is only possible if the cascade is blocked +// behind the step lock, i.e. it now acquires the step lock before proceeding +// to the task rows and the delete, matching ReorderStepTasks' own order. +// +// Skips unless KANDEV_TEST_POSTGRES_DSN is set. + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" +) + +func TestPostgresWorkspaceCascadeDeleteLocksStepAgainstConcurrentReorder(t *testing.T) { + const step = "cascade-lock-step" + const wsID = "cascade-lock-ws" + const workflowID = "cascade-lock-workflow" + repo := seedVisibilityLockFixture(t, wsID, workflowID, step) + ctx := context.Background() + + staying1 := &models.Task{ + ID: "cascade-lock-stays-1", WorkspaceID: wsID, WorkflowID: workflowID, + WorkflowStepID: step, Title: "Stays 1", WIPAdmitted: true, + } + staying2 := &models.Task{ + ID: "cascade-lock-stays-2", WorkspaceID: wsID, WorkflowID: workflowID, + WorkflowStepID: step, Title: "Stays 2", WIPAdmitted: true, + } + for _, task := range []*models.Task{staying1, staying2} { + if err := repo.CreateTask(ctx, task); err != nil { + t.Fatalf("seed task %s: %v", task.ID, err) + } + } + + paused, release := armReorderPause(t, repo) + t.Cleanup(func() { repo.reorderPreWriteHook = nil }) + + var wg sync.WaitGroup + var reorderErr, cascadeErr error + wg.Add(1) + go func() { + defer wg.Done() + _, _, reorderErr = repo.ReorderStepTasks(ctx, step, ReorderBandAdmitted, []string{staying1.ID, staying2.ID}) + }() + + <-paused // reorder holds step's row lock, has already read the live membership + + wg.Add(1) + go func() { + defer wg.Done() + _, _, cascadeErr = repo.DeleteWorkspaceCascade(ctx, wsID) + }() + + // Give the cascade goroutine time to either run to completion (unfixed + // code, no step lock ahead of the task rows/delete) or register its wait + // against reorder's held step lock (fixed code) before we peek at + // committed state. + time.Sleep(200 * time.Millisecond) + + var workspaceStillExists bool + if err := repo.db.QueryRowContext(ctx, repo.db.Rebind( + `SELECT EXISTS (SELECT 1 FROM workspaces WHERE id = ?)`, + ), wsID).Scan(&workspaceStillExists); err != nil { + t.Fatalf("peek workspace existence mid-pause: %v", err) + } + if !workspaceStillExists { + t.Fatalf("DeleteWorkspaceCascade committed while the reorder still held step %q's lock: the cascade "+ + "must lock the workspace's steps before its task rows and delete, so it waits behind the reorder "+ + "instead of acquiring the same two resources in the opposite order", step) + } + + release() + wg.Wait() + + if cascadeErr != nil { + t.Fatalf("workspace cascade delete must always succeed: %v", cascadeErr) + } + if reorderErr != nil && !errors.Is(reorderErr, repoerrors.ErrStepChanged) { + t.Fatalf("reorder error = %v, want nil or ErrStepChanged", reorderErr) + } + + if err := repo.db.QueryRowContext(ctx, repo.db.Rebind( + `SELECT EXISTS (SELECT 1 FROM workspaces WHERE id = ?)`, + ), wsID).Scan(&workspaceStillExists); err != nil { + t.Fatalf("check workspace existence after release: %v", err) + } + if workspaceStillExists { + t.Fatalf("workspace %q was not deleted after the cascade completed", wsID) + } +} diff --git a/apps/backend/internal/task/repository/task_wip_test.go b/apps/backend/internal/task/repository/task_wip_test.go index 2d387e0b15..0f835185a0 100644 --- a/apps/backend/internal/task/repository/task_wip_test.go +++ b/apps/backend/internal/task/repository/task_wip_test.go @@ -23,11 +23,11 @@ type workflowStepAdmissionCreator interface { } type workflowStepMoveAdmissionRepository interface { - UpdateTaskWithWorkflowStepAdmission(context.Context, *models.Task, string, int) (bool, error) + UpdateTaskWithWorkflowStepAdmission(context.Context, *models.Task, string, string, int) (bool, error) } type workflowStepMoveAdmissionWithStateRepository interface { - UpdateTaskWithWorkflowStepAdmissionAndState(context.Context, *models.Task, string, int, *v1.TaskState, bool, string) (bool, error) + UpdateTaskWithWorkflowStepAdmissionAndState(context.Context, *models.Task, string, string, int, *v1.TaskState, bool, string) (bool, error) } type queuedTaskPromoter interface { @@ -206,7 +206,7 @@ func TestUpdateTaskWithWorkflowStepAdmission_QueuesOverflowInPlace(t *testing.T) t.Fatalf("seed candidate: %v", err) } - admitted, err := mover.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, targetStepID, 1) + admitted, err := mover.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, "move-source", targetStepID, 1) if err != nil { t.Fatalf("move candidate: %v", err) } @@ -247,7 +247,7 @@ func TestUpdateTaskWithWorkflowStepAdmission_UnlimitedClearsQueue(t *testing.T) t.Fatalf("seed candidate: %v", err) } - admitted, err := mover.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, "unlimited-target", 0) + admitted, err := mover.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, "move-source", "unlimited-target", 0) if err != nil || !admitted { t.Fatalf("move candidate admitted=%t err=%v, want admitted", admitted, err) } @@ -288,7 +288,7 @@ func TestUpdateTaskWithWorkflowStepAdmissionAndState_PersistsMoveLifecycleAtomic t.Fatalf("seed candidate: %v", err) } admittedState := v1.TaskStateCompleted - admitted, err := mover.UpdateTaskWithWorkflowStepAdmissionAndState(ctx, candidate, targetStepID, 1, &admittedState, true, "") + admitted, err := mover.UpdateTaskWithWorkflowStepAdmissionAndState(ctx, candidate, "atomic-move-source", targetStepID, 1, &admittedState, true, "") if err != nil { t.Fatalf("move candidate: %v", err) } @@ -318,7 +318,7 @@ func TestUpdateTaskWithWorkflowStepAdmissionAndState_PersistsMoveLifecycleAtomic if err != nil { t.Fatalf("load unlimited candidate: %v", err) } - admitted, err = mover.UpdateTaskWithWorkflowStepAdmissionAndState(ctx, admittedCandidate, "atomic-unlimited-target", 0, &admittedState, true, "") + admitted, err = mover.UpdateTaskWithWorkflowStepAdmissionAndState(ctx, admittedCandidate, "atomic-move-source", "atomic-unlimited-target", 0, &admittedState, true, "") if err != nil || !admitted { t.Fatalf("unlimited move admitted=%t err=%v", admitted, err) } @@ -376,7 +376,7 @@ func TestUpdateTaskWithWorkflowStepAdmission_ConcurrentLastSlot(t *testing.T) { go func(task *models.Task) { defer wg.Done() <-start - admitted, err := mover.UpdateTaskWithWorkflowStepAdmission(ctx, task, targetStepID, 2) + admitted, err := mover.UpdateTaskWithWorkflowStepAdmission(ctx, task, "concurrent-move-source", targetStepID, 2) results <- struct { admitted bool err error diff --git a/apps/backend/internal/task/service/handoff_workspace_test.go b/apps/backend/internal/task/service/handoff_workspace_test.go index 0d90bc19ab..30db82598d 100644 --- a/apps/backend/internal/task/service/handoff_workspace_test.go +++ b/apps/backend/internal/task/service/handoff_workspace_test.go @@ -532,6 +532,10 @@ func (r *phase4TaskRepo) UpdateTask(context.Context, *models.Task) error { r.panicNotUsed("UpdateTask") return nil } +func (r *phase4TaskRepo) UpdateTaskWithExplicitPosition(context.Context, *models.Task) error { + r.panicNotUsed("UpdateTaskWithExplicitPosition") + return nil +} func (r *phase4TaskRepo) DeleteTask(context.Context, string) error { r.panicNotUsed("DeleteTask") return nil diff --git a/apps/backend/internal/task/service/service.go b/apps/backend/internal/task/service/service.go index 8bf4a3f90f..c3ea6dbbc7 100644 --- a/apps/backend/internal/task/service/service.go +++ b/apps/backend/internal/task/service/service.go @@ -485,13 +485,32 @@ type Service struct { taskPublicationMu sync.Mutex taskPublications map[string]*taskPublicationQueue // cleanupDoneForTest lets unit tests wait for async cleanup; nil in production. - cleanupDoneForTest chan struct{} - cleanupWorkerMu sync.Mutex - cleanupWorkerCancel context.CancelFunc - cleanupWorkerWG sync.WaitGroup - cleanupWorkerWake chan struct{} - cleanupRunsMu sync.Mutex - cleanupRuns map[*taskResourceCleanupRun]struct{} + cleanupDoneForTest chan struct{} + // bulkMoveAfterTaskForTest is a test-only hook invoked synchronously after + // each task's MoveTask call inside BulkMoveSelectedTasks's and + // BulkMoveTasks's dispatch loops, while their arrival locks are still + // held. Lets a test prove the lock spans the whole loop by blocking a + // concurrent arrival attempt from inside this hook. Nil in production. + bulkMoveAfterTaskForTest func() + // bulkMoveAfterLockForTest is a test-only hook invoked synchronously + // after BulkMoveSelectedTasks/BulkMoveTasks acquire their step lock set, + // before the dispatch loop starts. Lets a test force a concurrent + // opposite-direction MoveTask into the acquisition window and prove the + // two do not deadlock. Nil in production. + bulkMoveAfterLockForTest func() + // bulkMoveBeforeLockForTest is a test-only hook invoked synchronously + // once, before BulkMoveSelectedTasks/BulkMoveTasks make their first + // LockStepArrivalsForBatch attempt. Lets a test move one of the batch's + // tasks to a different source step in that window and prove the lock + // acquisition re-reads and corrects for it instead of locking a step the + // task has already left. Nil in production. + bulkMoveBeforeLockForTest func() + cleanupWorkerMu sync.Mutex + cleanupWorkerCancel context.CancelFunc + cleanupWorkerWG sync.WaitGroup + cleanupWorkerWake chan struct{} + cleanupRunsMu sync.Mutex + cleanupRuns map[*taskResourceCleanupRun]struct{} // repoResolveMu serializes the check-then-create sections of // FindOrCreateRepository and FindOrCreateRepositoryByLocalPath so two // resolvers racing to register the same not-yet-known repository (by diff --git a/apps/backend/internal/task/service/service_access.go b/apps/backend/internal/task/service/service_access.go index 36badbd7d7..76682c2607 100644 --- a/apps/backend/internal/task/service/service_access.go +++ b/apps/backend/internal/task/service/service_access.go @@ -251,6 +251,23 @@ func (s *Service) authorizeWorkflowID(ctx context.Context, workflowID string) er return nil } +// authorizeWorkflowScope checks reach and one action scope for a workflow. +// Workflow access is resolved through its workspace so callers that can read +// a board but cannot write its tasks receive ErrForbidden. +func (s *Service) authorizeWorkflowScope(ctx context.Context, workflowID string, scope authz.Scope) error { + if _, scoped := callerScope(ctx); !scoped { + return nil + } + workflow, err := s.workflows.GetWorkflow(ctx, workflowID) + if err != nil { + return err + } + if workflow.WorkspaceID == "" { + return nil + } + return s.AuthorizeWorkspaceScope(ctx, workflow.WorkspaceID, scope) +} + // AuthorizeTaskAccess is the public form of authorizeTaskID, consumed by the // WS gateway's subscription checks. func (s *Service) AuthorizeTaskAccess(ctx context.Context, taskID string) error { diff --git a/apps/backend/internal/task/service/service_bulk_move_concurrency_test.go b/apps/backend/internal/task/service/service_bulk_move_concurrency_test.go new file mode 100644 index 0000000000..130a6ff790 --- /dev/null +++ b/apps/backend/internal/task/service/service_bulk_move_concurrency_test.go @@ -0,0 +1,101 @@ +package service + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" +) + +// TestService_BulkMoveSelectedTasksHoldsStepLockAcrossWholeBatch proves +// REQ-TASKS-KANBAN-TASK-REORDERING-001.29's batch-scoped consecutiveness: +// BulkMoveSelectedTasks must hold the target step's arrival-position lock +// across its whole sequential dispatch loop, not just within each +// individual MoveTask call's own transaction. Without that, an unrelated +// concurrent arrival (another create, move, WIP promotion, or automatic +// transition) into the same target step can land in the middle of the +// batch's own sequence, breaking "Their position values shall be +// consecutive." +func TestService_BulkMoveSelectedTasksHoldsStepLockAcrossWholeBatch(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + + createMoveTask(t, ctx, repo, "batch-1", "wf-source", "step-source", nil) + createMoveTask(t, ctx, repo, "batch-2", "wf-source", "step-source", nil) + + reachedMidBatch := make(chan struct{}) + proceedBatch := make(chan struct{}) + var hookMu sync.Mutex + hookCalls := 0 + svc.bulkMoveAfterTaskForTest = func() { + hookMu.Lock() + hookCalls++ + first := hookCalls == 1 + hookMu.Unlock() + if !first { + return + } + close(reachedMidBatch) + <-proceedBatch + } + + bulkDone := make(chan error, 1) + go func() { + _, err := svc.BulkMoveSelectedTasks(ctx, []string{"batch-1", "batch-2"}, "wf-target", "step-target") + bulkDone <- err + }() + + select { + case <-reachedMidBatch: + case <-time.After(5 * time.Second): + t.Fatal("bulk move never reached its mid-batch hook") + } + + // Attempt a concurrent, unrelated arrival into the same target step + // while the batch holds it mid-loop. It must block rather than slot in + // between batch-1 and batch-2's positions. + interloperDone := make(chan error, 1) + go func() { + interloperDone <- repo.CreateTask(ctx, &models.Task{ + ID: "interloper", WorkspaceID: "ws-1", WorkflowID: "wf-target", + WorkflowStepID: "step-target", Title: "Interloper", + }) + }() + + select { + case <-interloperDone: + t.Fatal("interloper arrival completed while the batch still held the target step's lock") + case <-time.After(150 * time.Millisecond): + // Expected: still blocked behind the batch's lock. + } + + close(proceedBatch) + + if err := <-bulkDone; err != nil { + t.Fatalf("BulkMoveSelectedTasks: %v", err) + } + if err := <-interloperDone; err != nil { + t.Fatalf("interloper CreateTask: %v", err) + } + + b1, err := repo.GetTask(ctx, "batch-1") + if err != nil { + t.Fatalf("GetTask(batch-1): %v", err) + } + b2, err := repo.GetTask(ctx, "batch-2") + if err != nil { + t.Fatalf("GetTask(batch-2): %v", err) + } + interloper, err := repo.GetTask(ctx, "interloper") + if err != nil { + t.Fatalf("GetTask(interloper): %v", err) + } + if b2.Position != b1.Position+1 { + t.Fatalf("batch positions not consecutive: batch-1=%d, batch-2=%d (interloper=%d)", + b1.Position, b2.Position, interloper.Position) + } +} diff --git a/apps/backend/internal/task/service/service_bulk_move_dangling_step_test.go b/apps/backend/internal/task/service/service_bulk_move_dangling_step_test.go new file mode 100644 index 0000000000..5c0b0341cc --- /dev/null +++ b/apps/backend/internal/task/service/service_bulk_move_dangling_step_test.go @@ -0,0 +1,34 @@ +package service + +import ( + "context" + "testing" +) + +// TestService_BulkMoveTasksToleratesDanglingSourceStep proves +// orderTasksForBulkMove no longer aborts the whole batch when one task's +// source step cannot be resolved (e.g. concurrently deleted): that task is +// ordered last instead, and every task in the batch still moves. +func TestService_BulkMoveTasksToleratesDanglingSourceStep(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + createMoveTask(t, ctx, repo, "task-bulk-resolvable", "wf-source", "step-source", nil) + createMoveTask(t, ctx, repo, "task-bulk-dangling", "wf-source", "step-deleted", nil) + + _, err := svc.BulkMoveTasks(ctx, "wf-source", "", "wf-target", "step-target") + if err != nil { + t.Fatalf("BulkMoveTasks: %v", err) + } + + for _, id := range []string{"task-bulk-resolvable", "task-bulk-dangling"} { + task, err := repo.GetTask(ctx, id) + if err != nil { + t.Fatalf("GetTask(%s): %v", id, err) + } + if task.WorkflowStepID != "step-target" { + t.Fatalf("task %s WorkflowStepID = %q, want step-target", id, task.WorkflowStepID) + } + } +} diff --git a/apps/backend/internal/task/service/service_bulk_move_lock_drift_test.go b/apps/backend/internal/task/service/service_bulk_move_lock_drift_test.go new file mode 100644 index 0000000000..e8c60e1a19 --- /dev/null +++ b/apps/backend/internal/task/service/service_bulk_move_lock_drift_test.go @@ -0,0 +1,205 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" + wfmodels "github.com/kandev/kandev/internal/workflow/models" +) + +// TestService_BulkMoveSelectedTasksRelocksAfterSourceStepDrift proves +// acquireBulkMoveStepLocks corrects for a source step that changes between +// the batch's pre-lock task read (validateSelectedMoveBatch, +// orderTasksForBulkMove) and its first LockStepArrivalsForBatch attempt. +// +// Locking only the stale, pre-drift step set would leave the batch holding +// a lock on a step the task has already left while MoveTask, later in the +// dispatch loop, correctly locks the task's real current step — a window +// where an unrelated mover already holding that real step and waiting on +// this batch's target step produces an AB-BA deadlock. Re-reading under the +// held lock and retrying on mismatch (bulkMoveBeforeLockForTest fires once, +// before the first attempt, letting the test perform the drift +// deterministically instead of racing a real goroutine for it) must instead +// converge on the task's true current step. +func TestService_BulkMoveSelectedTasksRelocksAfterSourceStepDrift(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + + createMoveTask(t, ctx, repo, "batch-1", "wf-source", "step-source", nil) + + svc.bulkMoveBeforeLockForTest = func() { + if _, err := svc.MoveTask(ctx, "batch-1", "wf-source", "step-review-target", 0); err != nil { + t.Errorf("drift MoveTask: %v", err) + } + } + t.Cleanup(func() { svc.bulkMoveBeforeLockForTest = nil }) + + lockAcquired := make(chan struct{}) + proceed := make(chan struct{}) + svc.bulkMoveAfterLockForTest = func() { + close(lockAcquired) + <-proceed + } + t.Cleanup(func() { svc.bulkMoveAfterLockForTest = nil }) + + bulkDone := make(chan error, 1) + go func() { + _, err := svc.BulkMoveSelectedTasks(ctx, []string{"batch-1"}, "wf-target", "step-target") + bulkDone <- err + }() + + select { + case <-lockAcquired: + case <-time.After(5 * time.Second): + t.Fatal("bulk move never reached its post-lock hook") + } + + // If acquireBulkMoveStepLocks correctly re-locked onto + // step-review-target (batch-1's real current step after the drift) + // rather than the stale step-source read before the drift, a + // concurrent arrival into step-review-target must block behind it. + interloperDone := make(chan error, 1) + go func() { + interloperDone <- repo.CreateTask(ctx, &models.Task{ + ID: "interloper", WorkspaceID: "ws-1", WorkflowID: "wf-source", + WorkflowStepID: "step-review-target", Title: "Interloper", + }) + }() + + select { + case <-interloperDone: + t.Fatal("interloper arrival into the drifted-to step completed while the batch should still hold its lock") + case <-time.After(150 * time.Millisecond): + // Expected: still blocked behind the batch's (corrected) lock. + } + + close(proceed) + + if err := <-bulkDone; err != nil { + t.Fatalf("BulkMoveSelectedTasks: %v", err) + } + if err := <-interloperDone; err != nil { + t.Fatalf("interloper CreateTask: %v", err) + } + + moved, err := repo.GetTask(ctx, "batch-1") + if err != nil { + t.Fatalf("GetTask(batch-1): %v", err) + } + if moved.WorkflowStepID != "step-target" { + t.Fatalf("batch-1 step = %q, want step-target", moved.WorkflowStepID) + } +} + +// TestService_BulkMoveSelectedTasksMovesTaskThatDriftedOutOfTargetBeforeLock +// proves the dispatch loop's "already at the target step, skip it" check +// (BulkMoveSelectedTasks's intentional behavior for a batch that includes +// tasks already where the caller wants them) uses the batch's real, +// lock-corrected membership rather than the stale pre-lock read. +// +// A task already at the target step when validateSelectedMoveBatch reads the +// batch is a legitimate member of that batch (BulkMoveSelectedTasks's own +// doc comment: "tasks already in the target step are skipped"). If a +// concurrent move then carries that same task OUT of the target step before +// this batch's locks are acquired, acquireBulkMoveStepLocks correctly +// re-locks its new real step — but the task no longer belongs in the +// "already there" case: the caller still wants it at the target, and it no +// longer is. The dispatch loop must dispatch it, not skip it. +func TestService_BulkMoveSelectedTasksMovesTaskThatDriftedOutOfTargetBeforeLock(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + + createMoveTask(t, ctx, repo, "batch-1", "wf-target", "step-target", nil) + + svc.bulkMoveBeforeLockForTest = func() { + if _, err := svc.MoveTask(ctx, "batch-1", "wf-source", "step-source", 0); err != nil { + t.Errorf("drift MoveTask: %v", err) + } + } + t.Cleanup(func() { svc.bulkMoveBeforeLockForTest = nil }) + + if _, err := svc.BulkMoveSelectedTasks(ctx, []string{"batch-1"}, "wf-target", "step-target"); err != nil { + t.Fatalf("BulkMoveSelectedTasks: %v", err) + } + + moved, err := repo.GetTask(ctx, "batch-1") + if err != nil { + t.Fatalf("GetTask(batch-1): %v", err) + } + if moved.WorkflowStepID != "step-target" { + t.Fatalf("batch-1 step = %q, want step-target (task drifted out of the "+ + "target before the lock was acquired; it must still be moved back "+ + "in, not silently skipped as if it had never left)", moved.WorkflowStepID) + } +} + +// TestService_BulkMoveTasksReordersAfterSourceStepDrift proves BulkMoveTasks's +// sibling of the fix above: a mid-batch source-step drift must correct the +// REQ-TASKS-KANBAN-TASK-REORDERING-001.29 submission order, not just which +// tasks move. orderTasksForBulkMove runs once before the lock (on the stale +// read) and again after (on acquireBulkMoveStepLocks' lock-corrected +// membership); only the second result may reach the dispatch loop. +// +// task-a starts in step-high (ordinal 10) and task-b starts in step-low +// (ordinal 0), so the stale pre-lock order is [task-b, task-a]. Before the +// lock is acquired, task-b drifts into step-highest (ordinal 20) — higher +// than task-a's step. The correct, lock-corrected order is therefore +// [task-a, task-b]. Dispatch order is observable via each task's resulting +// `position` in the (initially empty) target step: MoveTask assigns +// arrival positions in call order, so the first-dispatched task ends up +// with the lower position. +func TestService_BulkMoveTasksReordersAfterSourceStepDrift(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + svc.SetWorkflowStepGetter(&fakeWorkflowStepGetter{steps: map[string]*wfmodels.WorkflowStep{ + "step-low": {ID: "step-low", WorkflowID: "wf-source", Name: "Low", Position: 0}, + "step-high": {ID: "step-high", WorkflowID: "wf-source", Name: "High", Position: 10}, + "step-highest": {ID: "step-highest", WorkflowID: "wf-source", Name: "Highest", Position: 20}, + "step-target": {ID: "step-target", WorkflowID: "wf-target", Name: "Target", Position: 0}, + }}) + + createMoveTask(t, ctx, repo, "task-a", "wf-source", "step-high", nil) + createMoveTask(t, ctx, repo, "task-b", "wf-source", "step-low", nil) + + svc.bulkMoveBeforeLockForTest = func() { + if _, err := svc.MoveTask(ctx, "task-b", "wf-source", "step-highest", 0); err != nil { + t.Errorf("drift MoveTask: %v", err) + } + } + t.Cleanup(func() { svc.bulkMoveBeforeLockForTest = nil }) + + result, err := svc.BulkMoveTasks(ctx, "wf-source", "", "wf-target", "step-target") + if err != nil { + t.Fatalf("BulkMoveTasks: %v", err) + } + if result.MovedCount != 2 { + t.Fatalf("MovedCount = %d, want 2", result.MovedCount) + } + + taskA, err := repo.GetTask(ctx, "task-a") + if err != nil { + t.Fatalf("GetTask(task-a): %v", err) + } + taskB, err := repo.GetTask(ctx, "task-b") + if err != nil { + t.Fatalf("GetTask(task-b): %v", err) + } + if taskA.WorkflowStepID != "step-target" || taskB.WorkflowStepID != "step-target" { + t.Fatalf("both tasks must land in step-target, got task-a=%q task-b=%q", + taskA.WorkflowStepID, taskB.WorkflowStepID) + } + if taskA.Position >= taskB.Position { + t.Fatalf("task-a.Position=%d, task-b.Position=%d: want task-a dispatched "+ + "(and so positioned) before task-b, since after the drift task-a's "+ + "source step (ordinal 10) ranks below task-b's drifted-to source "+ + "step (ordinal 20) — the stale pre-lock order would have dispatched "+ + "task-b first instead", taskA.Position, taskB.Position) + } +} diff --git a/apps/backend/internal/task/service/service_bulk_move_lock_order_test.go b/apps/backend/internal/task/service/service_bulk_move_lock_order_test.go new file mode 100644 index 0000000000..252c842175 --- /dev/null +++ b/apps/backend/internal/task/service/service_bulk_move_lock_order_test.go @@ -0,0 +1,184 @@ +package service + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/task/models" +) + +// TestService_BulkMoveTasksHoldsStepLockAcrossWholeBatch is BulkMoveTasks' +// sibling of TestService_BulkMoveSelectedTasksHoldsStepLockAcrossWholeBatch: +// the admin whole-workflow migration path must hold the same batch-spanning +// arrival lock, not just the per-call one MoveTask already takes. +func TestService_BulkMoveTasksHoldsStepLockAcrossWholeBatch(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + + createMoveTask(t, ctx, repo, "batch-1", "wf-source", "step-source", nil) + createMoveTask(t, ctx, repo, "batch-2", "wf-source", "step-source", nil) + + reachedMidBatch := make(chan struct{}) + proceedBatch := make(chan struct{}) + var hookMu sync.Mutex + hookCalls := 0 + svc.bulkMoveAfterTaskForTest = func() { + hookMu.Lock() + hookCalls++ + first := hookCalls == 1 + hookMu.Unlock() + if !first { + return + } + close(reachedMidBatch) + <-proceedBatch + } + t.Cleanup(func() { svc.bulkMoveAfterTaskForTest = nil }) + + bulkDone := make(chan error, 1) + go func() { + _, err := svc.BulkMoveTasks(ctx, "wf-source", "step-source", "wf-target", "step-target") + bulkDone <- err + }() + + select { + case <-reachedMidBatch: + case <-time.After(5 * time.Second): + t.Fatal("bulk move never reached its mid-batch hook") + } + + // A concurrent, unrelated arrival into the same target step while the + // batch holds it mid-loop must block rather than slot in between + // batch-1 and batch-2's positions. + interloperDone := make(chan error, 1) + go func() { + interloperDone <- repo.CreateTask(ctx, &models.Task{ + ID: "interloper", WorkspaceID: "ws-1", WorkflowID: "wf-target", + WorkflowStepID: "step-target", Title: "Interloper", + }) + }() + + select { + case <-interloperDone: + t.Fatal("interloper arrival completed while the batch still held the target step's lock") + case <-time.After(150 * time.Millisecond): + // Expected: still blocked behind the batch's lock. + } + + close(proceedBatch) + + if err := <-bulkDone; err != nil { + t.Fatalf("BulkMoveTasks: %v", err) + } + if err := <-interloperDone; err != nil { + t.Fatalf("interloper CreateTask: %v", err) + } + + b1, err := repo.GetTask(ctx, "batch-1") + if err != nil { + t.Fatalf("GetTask(batch-1): %v", err) + } + b2, err := repo.GetTask(ctx, "batch-2") + if err != nil { + t.Fatalf("GetTask(batch-2): %v", err) + } + interloper, err := repo.GetTask(ctx, "interloper") + if err != nil { + t.Fatalf("GetTask(interloper): %v", err) + } + if b2.Position != b1.Position+1 { + t.Fatalf("batch positions not consecutive: batch-1=%d, batch-2=%d (interloper=%d)", + b1.Position, b2.Position, interloper.Position) + } +} + +// TestService_BulkMoveDoesNotDeadlockAgainstOppositeDirectionMove proves the +// system design's cross-step lock-ordering rule holds for a bulk move, not +// only a single MoveTask: two steps' arrival locks must always be acquired +// in the same ascending order, whichever caller acquires them. +// +// step-source sorts before step-target lexically. A bulk move from +// step-source to step-target that locked only its target up front, then +// picked up step-source per task inside its loop, would fix its acquisition +// order at target-then-source — the reverse of ascending whenever the +// source id sorts first, as it does here. An ordinary single move in the +// opposite direction (step-target -> step-source) correctly locks +// source-then-target. Interleaved, that is a classic AB-BA deadlock: the +// bulk move holds target and waits on source, the single move holds source +// and waits on target, and neither `sync.Mutex.Lock` call ever times out. +func TestService_BulkMoveDoesNotDeadlockAgainstOppositeDirectionMove(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + + createMoveTask(t, ctx, repo, "batch-1", "wf-source", "step-source", nil) + createMoveTask(t, ctx, repo, "opposite-1", "wf-target", "step-target", nil) + + lockAcquired := make(chan struct{}) + proceed := make(chan struct{}) + svc.bulkMoveAfterLockForTest = func() { + close(lockAcquired) + <-proceed + } + t.Cleanup(func() { svc.bulkMoveAfterLockForTest = nil }) + + bulkDone := make(chan error, 1) + go func() { + _, err := svc.BulkMoveTasks(ctx, "wf-source", "step-source", "wf-target", "step-target") + bulkDone <- err + }() + + select { + case <-lockAcquired: + case <-time.After(5 * time.Second): + t.Fatal("bulk move never reached its post-lock hook") + } + + singleDone := make(chan error, 1) + go func() { + _, err := svc.MoveTask(ctx, "opposite-1", "wf-source", "step-source", 0) + singleDone <- err + }() + + // Give the opposite-direction move a chance to reach its own lock + // acquisition (and, under the pre-fix code, its own half of the cycle) + // before releasing the bulk move to attempt the rest of its locks. + time.Sleep(50 * time.Millisecond) + close(proceed) + + timeout := time.After(5 * time.Second) + for i := 0; i < 2; i++ { + select { + case err := <-bulkDone: + if err != nil { + t.Fatalf("BulkMoveTasks: %v", err) + } + case err := <-singleDone: + if err != nil { + t.Fatalf("MoveTask: %v", err) + } + case <-timeout: + t.Fatal("bulk move and the opposite-direction move deadlocked: neither completed within the timeout") + } + } + + moved, err := repo.GetTask(ctx, "batch-1") + if err != nil { + t.Fatalf("GetTask(batch-1): %v", err) + } + if moved.WorkflowStepID != "step-target" { + t.Fatalf("batch-1 step = %q, want step-target", moved.WorkflowStepID) + } + swapped, err := repo.GetTask(ctx, "opposite-1") + if err != nil { + t.Fatalf("GetTask(opposite-1): %v", err) + } + if swapped.WorkflowStepID != "step-source" { + t.Fatalf("opposite-1 step = %q, want step-source", swapped.WorkflowStepID) + } +} diff --git a/apps/backend/internal/task/service/service_reorder.go b/apps/backend/internal/task/service/service_reorder.go new file mode 100644 index 0000000000..646f4961ab --- /dev/null +++ b/apps/backend/internal/task/service/service_reorder.go @@ -0,0 +1,105 @@ +package service + +import ( + "context" + "errors" + "fmt" + + "go.uber.org/zap" + + "github.com/kandev/kandev/internal/authz" + "github.com/kandev/kandev/internal/events" + "github.com/kandev/kandev/internal/events/bus" + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" +) + +// ReorderStepTasksResult is the whole-step, both-bands view every reorder +// carrier reports: the success body, the step_changed conflict body, and the +// task.reordered event all carry this same shape +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.19, .25). +type ReorderStepTasksResult struct { + WorkflowStepID string + Revision int64 + Tasks []*models.Task +} + +const ( + reorderPayloadPositionKey = "position" + reorderPayloadWorkspaceIDKey = "workspace_id" +) + +// reorderRepository is the narrow capability ReorderStepTasks needs from the +// task repository, following the same runtime-asserted narrow-interface +// pattern as workflowQueuedTaskPromoter. +type reorderRepository interface { + ReorderStepTasks(ctx context.Context, stepID, band string, orderedTaskIDs []string) ([]*models.Task, int64, error) +} + +// ReorderStepTasks rewrites stepID's named band to orderedTaskIDs +// (REQ-TASKS-KANBAN-TASK-REORDERING-001). A caller authorized to move a task +// in a workflow is authorized to reorder that workflow's steps +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.23). On the step_changed conflict the +// returned result still carries the authoritative order the caller +// reconciles to; on any other error the result is nil. +func (s *Service) ReorderStepTasks(ctx context.Context, stepID, band string, orderedTaskIDs []string) (*ReorderStepTasksResult, error) { + if s.workflowStepGetter == nil { + return nil, fmt.Errorf("workflow step getter not configured") + } + step, err := s.workflowStepGetter.GetStep(ctx, stepID) + if err != nil { + return nil, err + } + if err := s.authorizeWorkflowScope(ctx, step.WorkflowID, authz.ScopeTaskWrite); err != nil { + return nil, err + } + reorderer, ok := s.tasks.(reorderRepository) + if !ok { + return nil, fmt.Errorf("task repository does not support reordering") + } + + tasks, revision, err := reorderer.ReorderStepTasks(ctx, stepID, band, orderedTaskIDs) + if err != nil { + if errors.Is(err, repoerrors.ErrStepChanged) { + return &ReorderStepTasksResult{WorkflowStepID: stepID, Revision: revision, Tasks: tasks}, err + } + return nil, err + } + + result := &ReorderStepTasksResult{WorkflowStepID: stepID, Revision: revision, Tasks: tasks} + s.publishTaskReordered(ctx, stepID, band, revision, tasks) + return result, nil +} + +// publishTaskReordered emits task.reordered +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.16), deliberately not task.moved +// (.21) and not one task.updated per task (design's "## Reorder contract" · +// Publication). workspace_id is not part of the client-visible payload +// contract but is required for Hub.BroadcastToWorkspace to scope the event +// to the step's own workspace rather than falling back to a global +// broadcast; every task in tasks shares stepID's workspace, so the first +// entry's is authoritative. tasks is always non-empty here: the repository +// only reaches a committed reorder with at least the named band's submitted +// ids present. +func (s *Service) publishTaskReordered(ctx context.Context, stepID, band string, revision int64, tasks []*models.Task) { + if s.eventBus == nil || len(tasks) == 0 { + return + } + taskEntries := make([]map[string]interface{}, len(tasks)) + for i, task := range tasks { + taskEntries[i] = map[string]interface{}{"id": task.ID, reorderPayloadPositionKey: task.Position} + } + data := map[string]interface{}{ + reorderPayloadWorkspaceIDKey: tasks[0].WorkspaceID, + "workflow_step_id": stepID, + "band": band, + "revision": revision, + "tasks": taskEntries, + } + event := bus.NewEvent(events.TaskReordered, "task-service", data) + if err := s.eventBus.Publish(ctx, events.TaskReordered, event); err != nil { + s.logger.Error("failed to publish task.reordered event", + zap.String("workflow_step_id", stepID), + zap.Error(err)) + } +} diff --git a/apps/backend/internal/task/service/service_reorder_test.go b/apps/backend/internal/task/service/service_reorder_test.go new file mode 100644 index 0000000000..927fdf6640 --- /dev/null +++ b/apps/backend/internal/task/service/service_reorder_test.go @@ -0,0 +1,335 @@ +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/kandev/kandev/internal/auth/authn" + "github.com/kandev/kandev/internal/events" + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" + sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite" + wfmodels "github.com/kandev/kandev/internal/workflow/models" +) + +// seedReorderTestStep inserts a workflow_steps row directly (same shape as +// the repository-level reorder tests) and wires a fakeWorkflowStepGetter so +// Service.ReorderStepTasks can resolve it without a full workflow service. +func seedReorderTestStep(t *testing.T, svc *Service, repo *sqliterepo.Repository, stepID, workflowID string, stepPosition int) { + t.Helper() + now := time.Now().UTC() + if _, err := repo.DB().Exec(`INSERT INTO workflow_steps + (id, workflow_id, name, position, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)`, + stepID, workflowID, stepID, stepPosition, now, now); err != nil { + t.Fatalf("insert step %s: %v", stepID, err) + } + svc.SetWorkflowStepGetter(&fakeWorkflowStepGetter{steps: map[string]*wfmodels.WorkflowStep{ + stepID: {ID: stepID, WorkflowID: workflowID, Name: stepID, Position: stepPosition}, + }}) +} + +func mustCreateReorderServiceTask(t *testing.T, ctx context.Context, repo *sqliterepo.Repository, id, workspaceID, workflowID, stepID string) { + t.Helper() + if err := repo.CreateTask(ctx, &models.Task{ + ID: id, WorkspaceID: workspaceID, WorkflowID: workflowID, WorkflowStepID: stepID, Title: id, + }); err != nil { + t.Fatalf("CreateTask(%s): %v", id, err) + } +} + +func TestService_ReorderStepTasksCommitsAndPublishesEvent(t *testing.T) { + svc, eventBus, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-reorder-svc", Name: "Workspace"}); err != nil { + t.Fatal(err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-reorder-svc", WorkspaceID: "ws-reorder-svc", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderTestStep(t, svc, repo, "step-reorder-svc", "wf-reorder-svc", 0) + mustCreateReorderServiceTask(t, ctx, repo, "svc-task-a", "ws-reorder-svc", "wf-reorder-svc", "step-reorder-svc") + mustCreateReorderServiceTask(t, ctx, repo, "svc-task-b", "ws-reorder-svc", "wf-reorder-svc", "step-reorder-svc") + eventBus.ClearEvents() + + result, err := svc.ReorderStepTasks(ctx, "step-reorder-svc", "admitted", []string{"svc-task-b", "svc-task-a"}) + if err != nil { + t.Fatalf("ReorderStepTasks: %v", err) + } + if result.WorkflowStepID != "step-reorder-svc" || result.Revision != 1 { + t.Fatalf("result = %+v, want step-reorder-svc/revision 1", result) + } + if len(result.Tasks) != 2 || result.Tasks[0].ID != "svc-task-b" || result.Tasks[1].ID != "svc-task-a" { + t.Fatalf("result.Tasks = %+v, want [svc-task-b svc-task-a]", result.Tasks) + } + + found := false + for _, event := range eventBus.GetPublishedEvents() { + if event.Type != events.TaskReordered { + continue + } + found = true + data, ok := event.Data.(map[string]interface{}) + if !ok { + t.Fatalf("task.reordered payload is not a map: %#v", event.Data) + } + if data["workflow_step_id"] != "step-reorder-svc" { + t.Fatalf("payload workflow_step_id = %v, want step-reorder-svc", data["workflow_step_id"]) + } + if data["band"] != "admitted" { + t.Fatalf("payload band = %v, want admitted", data["band"]) + } + if data["workspace_id"] != "ws-reorder-svc" { + t.Fatalf("payload workspace_id = %v, want ws-reorder-svc", data["workspace_id"]) + } + } + if !found { + t.Fatal("no task.reordered event published") + } +} + +func TestService_ReorderStepTasksStepChangedCarriesAuthoritativeOrder(t *testing.T) { + svc, eventBus, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-reorder-conflict", Name: "Workspace"}); err != nil { + t.Fatal(err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-reorder-conflict", WorkspaceID: "ws-reorder-conflict", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderTestStep(t, svc, repo, "step-reorder-conflict", "wf-reorder-conflict", 0) + mustCreateReorderServiceTask(t, ctx, repo, "conflict-a", "ws-reorder-conflict", "wf-reorder-conflict", "step-reorder-conflict") + mustCreateReorderServiceTask(t, ctx, repo, "conflict-b", "ws-reorder-conflict", "wf-reorder-conflict", "step-reorder-conflict") + eventBus.ClearEvents() + + // Submitted set is missing conflict-b: the classic membership-drift race. + result, err := svc.ReorderStepTasks(ctx, "step-reorder-conflict", "admitted", []string{"conflict-a"}) + if !errors.Is(err, repoerrors.ErrStepChanged) { + t.Fatalf("err = %v, want ErrStepChanged", err) + } + if result == nil || len(result.Tasks) != 2 { + t.Fatalf("result = %+v, want the authoritative 2-task order", result) + } + for _, event := range eventBus.GetPublishedEvents() { + if event.Type == events.TaskReordered { + t.Fatal("task.reordered must not publish on a rejected reorder") + } + } +} + +// TestService_ReorderStepTasksLeavesTaskIdentityAndSessionUntouched pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.21: a reorder changes only position — +// never workflow, step, WIP admission, queued destination/time, or state — +// and publishes no task.updated or task.moved event alongside task.reordered. +func TestService_ReorderStepTasksLeavesTaskIdentityAndSessionUntouched(t *testing.T) { + svc, eventBus, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-reorder-untouched", Name: "Workspace"}); err != nil { + t.Fatal(err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-reorder-untouched", WorkspaceID: "ws-reorder-untouched", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderTestStep(t, svc, repo, "step-reorder-untouched", "wf-reorder-untouched", 0) + mustCreateReorderServiceTask(t, ctx, repo, "untouched-a", "ws-reorder-untouched", "wf-reorder-untouched", "step-reorder-untouched") + mustCreateReorderServiceTask(t, ctx, repo, "untouched-b", "ws-reorder-untouched", "wf-reorder-untouched", "step-reorder-untouched") + before, err := repo.GetTask(ctx, "untouched-a") + if err != nil { + t.Fatal(err) + } + eventBus.ClearEvents() + + if _, err := svc.ReorderStepTasks(ctx, "step-reorder-untouched", "admitted", []string{"untouched-b", "untouched-a"}); err != nil { + t.Fatalf("ReorderStepTasks: %v", err) + } + + after, err := repo.GetTask(ctx, "untouched-a") + if err != nil { + t.Fatal(err) + } + if after.Position == before.Position { + t.Fatal("position did not change; the reorder did not commit") + } + if after.WorkflowID != before.WorkflowID || after.WorkflowStepID != before.WorkflowStepID { + t.Fatalf("workflow/step changed: before=%s/%s after=%s/%s", before.WorkflowID, before.WorkflowStepID, after.WorkflowID, after.WorkflowStepID) + } + if after.WIPAdmitted != before.WIPAdmitted || after.QueuedForStepID != before.QueuedForStepID { + t.Fatalf("WIP admission changed: before admitted=%v queued=%q after admitted=%v queued=%q", + before.WIPAdmitted, before.QueuedForStepID, after.WIPAdmitted, after.QueuedForStepID) + } + if after.State != before.State { + t.Fatalf("state changed: before=%s after=%s", before.State, after.State) + } + for _, event := range eventBus.GetPublishedEvents() { + if event.Type == events.TaskMoved || event.Type == events.TaskUpdated { + t.Fatalf("reorder must not publish %s", event.Type) + } + } +} + +// TestService_ReorderStepTasksDeniesCallerWithoutWorkflowAccess pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.23: reorder authority is exactly the +// existing move authority (authorizeWorkflowID), so a caller who cannot see +// the workflow's workspace is denied before any membership is validated or +// written. +func TestService_ReorderStepTasksDeniesCallerWithoutWorkflowAccess(t *testing.T) { + svc, eventBus, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-reorder-denied", Name: "Workspace", OwnerID: "user-b"}); err != nil { + t.Fatal(err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-reorder-denied", WorkspaceID: "ws-reorder-denied", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderTestStep(t, svc, repo, "step-reorder-denied", "wf-reorder-denied", 0) + mustCreateReorderServiceTask(t, ctx, repo, "denied-a", "ws-reorder-denied", "wf-reorder-denied", "step-reorder-denied") + mustCreateReorderServiceTask(t, ctx, repo, "denied-b", "ws-reorder-denied", "wf-reorder-denied", "step-reorder-denied") + before, err := repo.GetTask(ctx, "denied-a") + if err != nil { + t.Fatal(err) + } + eventBus.ClearEvents() + + _, err = svc.ReorderStepTasks(ctxAs("user-a"), "step-reorder-denied", "admitted", []string{"denied-b", "denied-a"}) + if err == nil { + t.Fatal("ReorderStepTasks: want a denial for a caller with no access to the workflow's workspace") + } + + after, err := repo.GetTask(ctx, "denied-a") + if err != nil { + t.Fatal(err) + } + if after.Position != before.Position { + t.Fatalf("position changed on denied reorder: before=%d after=%d", before.Position, after.Position) + } + if len(eventBus.GetPublishedEvents()) != 0 { + t.Fatalf("denied reorder must publish no event, got %+v", eventBus.GetPublishedEvents()) + } + + // The workspace's own owner remains authorized. + if _, err := svc.ReorderStepTasks(ctxAs("user-b"), "step-reorder-denied", "admitted", []string{"denied-b", "denied-a"}); err != nil { + t.Fatalf("owner reorder: %v", err) + } +} + +func TestService_ReorderStepTasksRequiresTaskWriteScope(t *testing.T) { + svc, eventBus, repo := createTestService(t) + seedTeamWorkspace(t, repo, true) + seedUnitViewer(t, "user-carla") + seedReorderTestStep(t, svc, repo, "step-1", "wf-team", 0) + + ctx := ctxAsRole("user-carla", authn.RoleMember) + eventBus.ClearEvents() + _, err := svc.ReorderStepTasks(ctx, "step-1", "admitted", []string{"task-team"}) + if !errors.Is(err, ErrForbidden) { + t.Fatalf("viewer reorder = %v, want ErrForbidden", err) + } + if len(eventBus.GetPublishedEvents()) != 0 { + t.Fatalf("viewer reorder must publish no event, got %+v", eventBus.GetPublishedEvents()) + } +} + +// TestService_ReorderStepTasksNamingTaskInAnotherWorkspaceDoesNotLeakExistence +// pins the "no existence leak" invariant (service_access.go) against +// ReorderStepTasks: authorizeWorkflowID only authorizes the step's own +// workflow, never the individual submitted task ids, so naming a real task +// id from a workspace the caller cannot see must resolve exactly like naming +// a nonexistent id (ErrInvalidReorder) — not ErrStepChanged, which would +// confirm the id exists somewhere the caller has no access to. +func TestService_ReorderStepTasksNamingTaskInAnotherWorkspaceDoesNotLeakExistence(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-a-leak", Name: "A", OwnerID: "user-a"}); err != nil { + t.Fatal(err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-a-leak", WorkspaceID: "ws-a-leak", Name: "WF-A"}); err != nil { + t.Fatal(err) + } + // seedReorderTestStep wires the fake workflow-step getter to know only + // about the step being reordered, matching what the service actually + // resolves for this call. + seedReorderTestStep(t, svc, repo, "step-a-leak", "wf-a-leak", 0) + mustCreateReorderServiceTask(t, ctx, repo, "task-a-leak", "ws-a-leak", "wf-a-leak", "step-a-leak") + + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-b-leak", Name: "B", OwnerID: "user-b"}); err != nil { + t.Fatal(err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-b-leak", WorkspaceID: "ws-b-leak", Name: "WF-B"}); err != nil { + t.Fatal(err) + } + if _, err := repo.DB().Exec(`INSERT INTO workflow_steps (id, workflow_id, name, position, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)`, + "step-b-leak", "wf-b-leak", "step-b-leak", 0, time.Now().UTC(), time.Now().UTC()); err != nil { + t.Fatal(err) + } + mustCreateReorderServiceTask(t, ctx, repo, "task-b-secret-leak", "ws-b-leak", "wf-b-leak", "step-b-leak") + + // user-a is authorized for step-a-leak's own workflow, but has zero + // access to ws-b-leak. Naming task-b-secret-leak (real, but foreign) + // must not be distinguishable from naming an id that does not exist. + _, err := svc.ReorderStepTasks(ctxAs("user-a"), "step-a-leak", "admitted", []string{"task-a-leak", "task-b-secret-leak"}) + if !errors.Is(err, repoerrors.ErrInvalidReorder) { + t.Fatalf("err = %v, want ErrInvalidReorder (a foreign-workspace task id must read the same as a nonexistent one)", err) + } +} + +// TestService_ReorderStepTasksAcceptsStepWithActiveSession pins +// AC-TASKS-KANBAN-TASK-REORDERING-001.22: the active-session restriction that +// guards a step change (validateMoveSessions, checked by MoveTaskWithOptions +// for every cross-step move) must not apply to a same-step reorder. A task +// with a running session sits in the reordered band exactly like any other +// task. +func TestService_ReorderStepTasksAcceptsStepWithActiveSession(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-reorder-active-session", Name: "Workspace"}); err != nil { + t.Fatal(err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-reorder-active-session", WorkspaceID: "ws-reorder-active-session", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderTestStep(t, svc, repo, "step-reorder-active-session", "wf-reorder-active-session", 0) + mustCreateReorderServiceTask(t, ctx, repo, "active-session-a", "ws-reorder-active-session", "wf-reorder-active-session", "step-reorder-active-session") + mustCreateReorderServiceTask(t, ctx, repo, "active-session-b", "ws-reorder-active-session", "wf-reorder-active-session", "step-reorder-active-session") + if err := repo.CreateTaskSession(ctx, &models.TaskSession{ + ID: "session-reorder-active", TaskID: "active-session-a", State: models.TaskSessionStateRunning, + }); err != nil { + t.Fatalf("seed running session: %v", err) + } + + // The same task, same running session, would be rejected by an ordinary + // cross-step move (validateMoveSessions): confirms the fixture actually + // exercises the restriction the reorder path must bypass. + if _, err := svc.MoveTask(ctx, "active-session-a", "wf-reorder-active-session", "step-reorder-active-session", 0); err == nil { + t.Fatal("fixture invalid: MoveTask should reject a task with a running session") + } + + result, err := svc.ReorderStepTasks(ctx, "step-reorder-active-session", "admitted", []string{"active-session-b", "active-session-a"}) + if err != nil { + t.Fatalf("ReorderStepTasks must accept a step with an active session: %v", err) + } + if len(result.Tasks) != 2 || result.Tasks[0].ID != "active-session-b" || result.Tasks[1].ID != "active-session-a" { + t.Fatalf("result.Tasks = %+v, want [active-session-b active-session-a]", result.Tasks) + } +} + +func TestService_ReorderStepTasksInvalidRequestReturnsNilResult(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-reorder-invalid", Name: "Workspace"}); err != nil { + t.Fatal(err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-reorder-invalid", WorkspaceID: "ws-reorder-invalid", Name: "Workflow"}); err != nil { + t.Fatal(err) + } + seedReorderTestStep(t, svc, repo, "step-reorder-invalid", "wf-reorder-invalid", 0) + + result, err := svc.ReorderStepTasks(ctx, "step-reorder-invalid", "not-a-band", []string{"whatever"}) + if !errors.Is(err, repoerrors.ErrInvalidReorder) { + t.Fatalf("err = %v, want ErrInvalidReorder", err) + } + if result != nil { + t.Fatalf("result = %+v, want nil on a malformed request", result) + } +} diff --git a/apps/backend/internal/task/service/service_tasks.go b/apps/backend/internal/task/service/service_tasks.go index 8c85b0f092..82f4845a68 100644 --- a/apps/backend/internal/task/service/service_tasks.go +++ b/apps/backend/internal/task/service/service_tasks.go @@ -2020,9 +2020,15 @@ func (s *Service) UpdateTask(ctx context.Context, id string, req *UpdateTaskRequ Trigger: steptelemetry.TriggerTaskUpdate, ActorKind: actorKind, ActorID: actorID, }) } - if err := s.tasks.UpdateTask(updateCtx, task); err != nil { - s.logger.Error("failed to update task", zap.String("task_id", id), zap.Error(err)) - return nil, err + var updateErr error + if req.Position != nil { + updateErr = s.tasks.UpdateTaskWithExplicitPosition(updateCtx, task) + } else { + updateErr = s.tasks.UpdateTask(updateCtx, task) + } + if updateErr != nil { + s.logger.Error("failed to update task", zap.String("task_id", id), zap.Error(updateErr)) + return nil, updateErr } // UpdateTask may have applied a conditional title/metadata patch because // this snapshot was stale. Publish and return the row that actually won so diff --git a/apps/backend/internal/task/service/service_workflow.go b/apps/backend/internal/task/service/service_workflow.go index 849345d751..40a32421eb 100644 --- a/apps/backend/internal/task/service/service_workflow.go +++ b/apps/backend/internal/task/service/service_workflow.go @@ -5,6 +5,8 @@ import ( "encoding/json" "errors" "fmt" + "math" + "sort" "time" "github.com/google/uuid" @@ -484,13 +486,14 @@ type workflowLimitedMoveRepository interface { } type workflowMoveAdmissionRepository interface { - UpdateTaskWithWorkflowStepAdmission(ctx context.Context, task *models.Task, targetStepID string, limit int) (bool, error) + UpdateTaskWithWorkflowStepAdmission(ctx context.Context, task *models.Task, sourceStepID, targetStepID string, limit int) (bool, error) } type workflowMoveAdmissionWithStateRepository interface { UpdateTaskWithWorkflowStepAdmissionAndState( ctx context.Context, task *models.Task, + sourceStepID string, targetStepID string, limit int, admittedState *v1.TaskState, @@ -626,8 +629,16 @@ func (s *Service) MoveTaskWithOptions( task.WorkflowID = workflowID task.WorkflowStepID = workflowStepID - task.Position = position + // A move naming the task's current step is not an arrival + // (REQ-TASKS-KANBAN-TASK-REORDERING-001.28): it keeps the position it + // already holds rather than the caller-supplied literal, which the + // updateMovedTaskSameStep write path below leaves untouched. A step + // change computes its own arrival position server-side further down + // this call chain (updateTaskWithWorkflowStepAdmission), so the + // caller-supplied position is ignored either way — position here is + // never read again. if stepChanged { + task.Position = position if task.Metadata == nil { task.Metadata = make(map[string]interface{}) } @@ -1019,7 +1030,7 @@ func (s *Service) promoteSameStepQueuedTask(ctx context.Context, candidate *mode if supported { return s.finishAtomicQueuedPromotion(ctx, candidate, targetStep, position, skipped, claimed, err, oldState) } else if admissionRepo, ok := s.tasks.(workflowMoveAdmissionRepository); ok { - claimed, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, targetStep.ID, targetStep.WIPLimit) + claimed, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, fromStepID, targetStep.ID, targetStep.WIPLimit) if err != nil { s.logger.Warn("failed to promote same-step queued task", zap.String("task_id", candidate.ID), zap.Error(err)) skipped[candidate.ID] = struct{}{} @@ -1103,7 +1114,7 @@ func (s *Service) promoteFeederQueuedTask(ctx context.Context, candidate *models s.publishTaskMovedEvent(ctx, candidate, oldWorkflowID, fromStepID, targetStep.ID, sessionID, "") return true } else if admissionRepo, ok := s.tasks.(workflowMoveAdmissionRepository); ok { - claimed, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, targetStep.ID, targetStep.WIPLimit) + claimed, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, candidate, fromStepID, targetStep.ID, targetStep.WIPLimit) if err != nil { s.logger.Warn("failed to promote feeder queued task", zap.String("task_id", candidate.ID), zap.Error(err)) skipped[candidate.ID] = struct{}{} @@ -1250,34 +1261,13 @@ func (s *Service) nextFeederQueuedCandidate( return nil, nil } +// queuedTaskBefore is the WIP promotion comparator +// (REQ-TASKS-KANBAN-TASK-REORDERING-001.1, .36): position, priority rank, +// queued_at (coalesced to created_at when absent), created_at, id. Delegates +// to models.StepOrderLess, the single source of truth this comparator's +// byte-identical orchestrator copy and the reorder repository also use. func queuedTaskBefore(left, right *models.Task) bool { - if left.Position != right.Position { - return left.Position < right.Position - } - priority := func(value string) int { - switch value { - case "critical": - return 0 - case "high": - return 1 - case priorityMedium: - return 2 - case priorityLow: - return 3 - default: - return 4 - } - } - if priority(left.Priority) != priority(right.Priority) { - return priority(left.Priority) < priority(right.Priority) - } - if left.QueuedAt != nil && right.QueuedAt != nil && !left.QueuedAt.Equal(*right.QueuedAt) { - return left.QueuedAt.Before(*right.QueuedAt) - } - if !left.CreatedAt.Equal(right.CreatedAt) { - return left.CreatedAt.Before(right.CreatedAt) - } - return left.ID < right.ID + return models.StepOrderLess(left, right) } func skippedTaskIDs(skipped map[string]struct{}) []string { @@ -1301,7 +1291,7 @@ func (s *Service) updateMovedTask( if targetStep == nil || oldStepID == targetStep.ID { return s.updateMovedTaskSameStep(ctx, task, opts) } - return s.updateMovedTaskCrossStep(ctx, task, targetStep, admittedState, opts) + return s.updateMovedTaskCrossStep(ctx, task, oldStepID, targetStep, admittedState, opts) } // updateMovedTaskSameStep handles the no-step-change branch of updateMovedTask @@ -1339,6 +1329,7 @@ func (s *Service) updateMovedTaskSameStep(ctx context.Context, task *models.Task func (s *Service) updateMovedTaskCrossStep( ctx context.Context, task *models.Task, + oldStepID string, targetStep *wfmodels.WorkflowStep, admittedState *v1.TaskState, opts MoveTaskOptions, @@ -1353,7 +1344,7 @@ func (s *Service) updateMovedTaskCrossStep( } if admissionWithState, ok := s.tasks.(workflowMoveAdmissionWithStateRepository); ok { return admissionWithState.UpdateTaskWithWorkflowStepAdmissionAndState( - ctx, task, targetStep.ID, targetStep.WIPLimit, admittedState, true, expectedWorkflowID, + ctx, task, oldStepID, targetStep.ID, targetStep.WIPLimit, admittedState, true, expectedWorkflowID, ) } if expectedWorkflowID != "" { @@ -1368,7 +1359,7 @@ func (s *Service) updateMovedTaskCrossStep( // Keep compatibility with narrow test/dry-run repositories that expose // only the original admission method. Production repositories implement the // atomic variant above, so this fallback is never used for real moves. - admitted, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, task, targetStep.ID, targetStep.WIPLimit) + admitted, err := admissionRepo.UpdateTaskWithWorkflowStepAdmission(ctx, task, oldStepID, targetStep.ID, targetStep.WIPLimit) if err != nil { return false, err } @@ -1564,25 +1555,253 @@ func (s *Service) BulkMoveSelectedTasks(ctx context.Context, taskIDs []string, t if err != nil { return nil, err } - nextPosition, err := s.tasks.CountTasksByWorkflowStep(ctx, targetStepID) + // The server now computes each arriving task's position from the target + // step's current max (REQ-TASKS-KANBAN-TASK-REORDERING-001.28), so the + // literal passed to MoveTask below is ignored and no longer needs + // precomputing. What still matters is dispatch order: MoveTask is called + // once per task, sequentially, so the final order is simply the call + // order (REQ-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. + orderedTasks, err := s.orderTasksForBulkMove(ctx, tasks) if err != nil { - return nil, fmt.Errorf("failed to count target workflow step tasks: %w", err) + return nil, err + } + + // Hold every step this batch will touch — the target plus each task's + // own source step, known now that orderedTasks is resolved — as one + // ascending-ordered lock set across the whole dispatch loop below, not + // just within each individual MoveTask call's own transaction. A + // per-call-only lock leaves a window between two of this batch's own + // calls where an unrelated arrival (another create, move, WIP promotion, + // or automatic transition) into targetStepID can land in the middle of + // the batch's sequence, breaking the batch-scoped consecutiveness + // REQ-TASKS-KANBAN-TASK-REORDERING-001.29 requires. Locking only the + // target here and letting each per-task MoveTask acquire its own source + // step deadlocks against an ordinary single move running the opposite + // direction between the same two steps. + lockedCtx, lockedTasks, unlock, err := s.acquireBulkMoveStepLocks(ctx, orderedTasks, targetStepID) + if err != nil { + return nil, err + } + ctx = lockedCtx + defer unlock() + // The lock acquisition above may have re-read a task's step after a + // concurrent drift, so re-derive dispatch order from that corrected + // membership rather than the pre-lock orderedTasks — otherwise a task + // whose stale record still shows it at targetStepID is silently skipped + // below even though it has since left, and any task whose real source + // step changed keeps the wrong REQ-TASKS-KANBAN-TASK-REORDERING-001.29 + // submission position. + orderedTasks, err = s.orderTasksForBulkMove(ctx, lockedTasks) + if err != nil { + return nil, err + } + if s.bulkMoveAfterLockForTest != nil { + s.bulkMoveAfterLockForTest() } movedCount := 0 - for _, task := range tasks { + for _, task := range orderedTasks { if task.WorkflowID == targetWorkflowID && task.WorkflowStepID == targetStepID { continue } - if _, err := s.MoveTask(ctx, task.ID, targetWorkflowID, targetStepID, nextPosition+movedCount); err != nil { + if _, err := s.MoveTask(ctx, task.ID, targetWorkflowID, targetStepID, 0); err != nil { return nil, fmt.Errorf("failed to move task %s: %w", task.ID, err) } movedCount++ + if s.bulkMoveAfterTaskForTest != nil { + s.bulkMoveAfterTaskForTest() + } } return &BulkMoveTasksResult{MovedCount: movedCount}, nil } +// stepArrivalBatchLocker is the narrow capability BulkMoveSelectedTasks and +// BulkMoveTasks need from the task repository to hold a batch's whole step +// set — target plus every distinct source step — locked across their +// sequential dispatch loop, following the same runtime-asserted +// narrow-interface pattern as reorderRepository. +type stepArrivalBatchLocker interface { + LockStepArrivalsForBatch(ctx context.Context, stepIDs ...string) (context.Context, func()) +} + +// bulkMoveLockStepIDs returns the target step plus every distinct source +// step among tasks, for a stepArrivalBatchLocker call. Duplicates and the +// empty string are harmless: withStepArrivalLocks dedupes and sorts before +// acquiring. +func bulkMoveLockStepIDs(tasks []*models.Task, targetStepID string) []string { + ids := make([]string, 0, len(tasks)+1) + ids = append(ids, targetStepID) + for _, task := range tasks { + ids = append(ids, task.WorkflowStepID) + } + return ids +} + +// bulkMoveLockRetryLimit bounds acquireBulkMoveStepLocks' re-read/retry loop. +// A source step can only drift a bounded number of times before some other +// caller's own work stalls behind this batch's locks, so a low limit is +// sufficient to converge on the real, uncontended case while still failing +// loudly instead of spinning forever if something is pathologically racing +// this batch on every attempt. +const bulkMoveLockRetryLimit = 8 + +// acquireBulkMoveStepLocks locks every step BulkMoveSelectedTasks/ +// BulkMoveTasks will touch — the target step plus each task's current +// source step — using bulkMoveLockStepIDs' set for a stepArrivalBatchLocker. +// +// tasks is read once, before any lock is held, to compute that initial +// step set. A source step named by that pre-lock read can still change +// between the read and lock acquisition (another mover wins the race), +// which would leave this batch holding a stale source step's lock while a +// concurrent move on the true current source step tries to lock the target +// step this batch already holds — the AB-BA deadlock this exists to avoid. +// So once the lock is held, tasks are re-read by ID under it; if any +// task's step moved, the stale lock set is released and a fresh set is +// acquired for the corrected steps, repeating until the read matches the +// locked set or bulkMoveLockRetryLimit is exhausted. +// +// The returned task slice is the membership the lock was finally acquired +// against, not the pre-lock tasks argument. Callers must dispatch and derive +// REQ-TASKS-KANBAN-TASK-REORDERING-001.29 submission order from this +// returned slice, never from their own pre-lock read: a task that drifted +// out of the target step during acquisition is only reflected here, and a +// caller still using its pre-lock copy would treat that task as if it had +// never left. +func (s *Service) acquireBulkMoveStepLocks( + ctx context.Context, tasks []*models.Task, targetStepID string, +) (context.Context, []*models.Task, func(), error) { + locker, ok := s.tasks.(stepArrivalBatchLocker) + if !ok { + return ctx, tasks, func() {}, nil + } + if s.bulkMoveBeforeLockForTest != nil { + s.bulkMoveBeforeLockForTest() + } + taskIDs := make([]string, len(tasks)) + for i, task := range tasks { + taskIDs[i] = task.ID + } + current := tasks + for attempt := 0; attempt < bulkMoveLockRetryLimit; attempt++ { + lockedCtx, unlock := locker.LockStepArrivalsForBatch(ctx, bulkMoveLockStepIDs(current, targetStepID)...) + fresh, err := s.tasks.GetTasksByIDs(lockedCtx, taskIDs) + if err != nil { + unlock() + return ctx, nil, func() {}, fmt.Errorf("failed to verify bulk move lock set: %w", err) + } + if bulkMoveTaskStepsMatch(current, fresh) { + return lockedCtx, fresh, unlock, nil + } + unlock() + current = fresh + } + return ctx, nil, func() {}, fmt.Errorf("bulk move step lock set did not stabilize after %d attempts", bulkMoveLockRetryLimit) +} + +// bulkMoveTaskStepsMatch reports whether a and b agree on every task's +// current WorkflowStepID, keyed by task ID rather than slice position since +// GetTasksByIDs does not guarantee the requested order. +func bulkMoveTaskStepsMatch(a, b []*models.Task) bool { + if len(a) != len(b) { + return false + } + stepByID := make(map[string]string, len(a)) + for _, task := range a { + stepByID[task.ID] = task.WorkflowStepID + } + for _, task := range b { + if stepByID[task.ID] != task.WorkflowStepID { + return false + } + } + return true +} + +// orderTasksForBulkMove re-derives the +// REQ-TASKS-KANBAN-TASK-REORDERING-001.29 submission order from each task's +// current source step, rather than trusting the caller-supplied list order: +// source step ordinal ascending, ties on source step id ascending +// (a selection can span workflows, so two source steps can share an +// ordinal), then within one source step that step's admitted band in step +// order followed by its queued band in step order. +func (s *Service) orderTasksForBulkMove(ctx context.Context, tasks []*models.Task) ([]*models.Task, error) { + stepOrdinals := make(map[string]int, len(tasks)) + if s.workflowStepGetter == nil { + // No ordinal source: fall back to submission order rather than + // aborting the batch — every task groups under its own step with an + // equal (zero) ordinal, so bulkMoveSubmissionOrder's per-step + // StepOrderLess sort still applies within each source step. + return bulkMoveSubmissionOrder(tasks, stepOrdinals), nil + } + for _, task := range tasks { + if _, ok := stepOrdinals[task.WorkflowStepID]; ok { + continue + } + step, err := s.workflowStepGetter.GetStep(ctx, task.WorkflowStepID) + if err != nil { + // An empty or dangling source step (e.g. deleted concurrently) + // must not abort every other task's move: order it last rather + // than failing the whole batch. + stepOrdinals[task.WorkflowStepID] = math.MaxInt32 + continue + } + stepOrdinals[task.WorkflowStepID] = step.Position + } + return bulkMoveSubmissionOrder(tasks, stepOrdinals), nil +} + +func bulkMoveSubmissionOrder(tasks []*models.Task, stepOrdinals map[string]int) []*models.Task { + type sourceGroup struct { + stepID string + ordinal int + tasks []*models.Task + } + groupsByStep := make(map[string]*sourceGroup, len(tasks)) + var groups []*sourceGroup + for _, task := range tasks { + group, ok := groupsByStep[task.WorkflowStepID] + if !ok { + group = &sourceGroup{stepID: task.WorkflowStepID, ordinal: stepOrdinals[task.WorkflowStepID]} + groupsByStep[task.WorkflowStepID] = group + groups = append(groups, group) + } + group.tasks = append(group.tasks, task) + } + sort.SliceStable(groups, func(i, j int) bool { + if groups[i].ordinal != groups[j].ordinal { + return groups[i].ordinal < groups[j].ordinal + } + return groups[i].stepID < groups[j].stepID + }) + + ordered := make([]*models.Task, 0, len(tasks)) + for _, group := range groups { + admitted, queued := bulkMoveBandSplit(group.tasks, group.stepID) + sort.SliceStable(admitted, func(i, j int) bool { return models.StepOrderLess(admitted[i], admitted[j]) }) + sort.SliceStable(queued, func(i, j int) bool { return models.StepOrderLess(queued[i], queued[j]) }) + ordered = append(ordered, admitted...) + ordered = append(ordered, queued...) + } + return ordered +} + +// bulkMoveBandSplit mirrors the reorder repository's band partition +// (Terminology: the queued band is !wip_admitted && queued_for_step_id == +// stepID; everything else in the step is the admitted band). +func bulkMoveBandSplit(tasks []*models.Task, stepID string) (admitted, queued []*models.Task) { + for _, task := range tasks { + if !task.WIPAdmitted && task.QueuedForStepID == stepID { + queued = append(queued, task) + } else { + admitted = append(admitted, task) + } + } + return admitted, queued +} + func uniqueTaskIDs(taskIDs []string) []string { seen := make(map[string]struct{}, len(taskIDs)) result := make([]string, 0, len(taskIDs)) @@ -1639,10 +1858,44 @@ func (s *Service) BulkMoveTasks(ctx context.Context, sourceWorkflowID, sourceSte if len(tasks) == 0 { return &BulkMoveTasksResult{MovedCount: 0}, nil } - for i, task := range tasks { - if _, err := s.MoveTask(ctx, task.ID, targetWorkflowID, targetStepID, i); err != nil { + + // Re-derive the REQ-TASKS-KANBAN-TASK-REORDERING-001.29 submission order + // from each task's source step, the same as BulkMoveSelectedTasks: the + // server now computes each arriving task's position from the target + // step's current max, so dispatch order alone decides the final order. + orderedTasks, err := s.orderTasksForBulkMove(ctx, tasks) + if err != nil { + return nil, err + } + + // Hold every step this batch will touch, for the same reason and in the + // same ascending-ordered way as BulkMoveSelectedTasks — see its lock + // call for the deadlock this avoids. + lockedCtx, lockedTasks, unlock, err := s.acquireBulkMoveStepLocks(ctx, orderedTasks, targetStepID) + if err != nil { + return nil, err + } + ctx = lockedCtx + defer unlock() + // See BulkMoveSelectedTasks's identical re-derivation: the lock + // acquisition above may have corrected a task's step after a concurrent + // drift, so dispatch order must be re-derived from that membership + // rather than the pre-lock orderedTasks. + orderedTasks, err = s.orderTasksForBulkMove(ctx, lockedTasks) + if err != nil { + return nil, err + } + if s.bulkMoveAfterLockForTest != nil { + s.bulkMoveAfterLockForTest() + } + + for _, task := range orderedTasks { + if _, err := s.MoveTask(ctx, task.ID, targetWorkflowID, targetStepID, 0); err != nil { return nil, fmt.Errorf("failed to move task %s: %w", task.ID, err) } + if s.bulkMoveAfterTaskForTest != nil { + s.bulkMoveAfterTaskForTest() + } } s.logger.Info("bulk moved tasks", diff --git a/apps/backend/internal/task/service/service_workflow_feeder_move_test.go b/apps/backend/internal/task/service/service_workflow_feeder_move_test.go index 697ae3645b..f23ff41dbf 100644 --- a/apps/backend/internal/task/service/service_workflow_feeder_move_test.go +++ b/apps/backend/internal/task/service/service_workflow_feeder_move_test.go @@ -209,10 +209,11 @@ func (r *failAfterMoveRefreshTaskRepository) GetTask(ctx context.Context, id str func (r *failAfterMoveRefreshTaskRepository) UpdateTaskWithWorkflowStepAdmission( ctx context.Context, task *models.Task, + sourceStepID string, targetStepID string, limit int, ) (bool, error) { - admitted, err := r.Repository.UpdateTaskWithWorkflowStepAdmission(ctx, task, targetStepID, limit) + admitted, err := r.Repository.UpdateTaskWithWorkflowStepAdmission(ctx, task, sourceStepID, targetStepID, limit) if err == nil { r.failRefresh.Store(true) } @@ -222,6 +223,7 @@ func (r *failAfterMoveRefreshTaskRepository) UpdateTaskWithWorkflowStepAdmission func (r *failAfterMoveRefreshTaskRepository) UpdateTaskWithWorkflowStepAdmissionAndState( ctx context.Context, task *models.Task, + sourceStepID string, targetStepID string, limit int, admittedState *v1.TaskState, @@ -229,7 +231,7 @@ func (r *failAfterMoveRefreshTaskRepository) UpdateTaskWithWorkflowStepAdmission expectedWorkflowID string, ) (bool, error) { admitted, err := r.Repository.UpdateTaskWithWorkflowStepAdmissionAndState( - ctx, task, targetStepID, limit, admittedState, queueExitPending, expectedWorkflowID, + ctx, task, sourceStepID, targetStepID, limit, admittedState, queueExitPending, expectedWorkflowID, ) if err == nil { r.failRefresh.Store(true) diff --git a/apps/backend/internal/task/service/service_workflow_race_test.go b/apps/backend/internal/task/service/service_workflow_race_test.go index 74369063c0..187d55ff53 100644 --- a/apps/backend/internal/task/service/service_workflow_race_test.go +++ b/apps/backend/internal/task/service/service_workflow_race_test.go @@ -30,6 +30,7 @@ type workflowMoveRaceRepo struct { func (r *workflowMoveRaceRepo) UpdateTaskWithWorkflowStepAdmissionAndState( ctx context.Context, task *models.Task, + sourceStepID string, targetStepID string, limit int, admittedState *v1.TaskState, @@ -41,7 +42,7 @@ func (r *workflowMoveRaceRepo) UpdateTaskWithWorkflowStepAdmissionAndState( r.inject() } return r.Repository.UpdateTaskWithWorkflowStepAdmissionAndState( - ctx, task, targetStepID, limit, admittedState, queueExitPending, expectedWorkflowID, + ctx, task, sourceStepID, targetStepID, limit, admittedState, queueExitPending, expectedWorkflowID, ) } diff --git a/apps/backend/internal/task/service/service_workflow_state_test.go b/apps/backend/internal/task/service/service_workflow_state_test.go index 55af082882..58a9cd55d4 100644 --- a/apps/backend/internal/task/service/service_workflow_state_test.go +++ b/apps/backend/internal/task/service/service_workflow_state_test.go @@ -325,6 +325,32 @@ func TestQueuedTaskBeforeOrdersByPositionPriorityThenAge(t *testing.T) { }, want: false, }, + { + // AC-TASKS-KANBAN-TASK-REORDERING-001.36: a nil queued_at falls back to + // created_at rather than skipping the key, aligning this comparator with + // the SQL promotion query's COALESCE(queued_at, created_at). This is the + // mixed-band case from sqlite/task.go's feeder create-time placement: an + // admitted task with queued_at set sits beside an ordinary admitted task + // with queued_at nil. + name: "a nil queued_at falls back to created_at instead of skipping the key", + left: &models.Task{ + ID: "a", Position: 1, Priority: priorityMedium, QueuedAt: nil, CreatedAt: earlier, + }, + right: &models.Task{ + ID: "b", Position: 1, Priority: priorityMedium, QueuedAt: &earlier, CreatedAt: later, + }, + want: true, + }, + { + name: "a later effective queued_at loses even though created_at would have tied", + left: &models.Task{ + ID: "a", Position: 1, Priority: priorityMedium, QueuedAt: &later, CreatedAt: earlier, + }, + right: &models.Task{ + ID: "b", Position: 1, Priority: priorityMedium, QueuedAt: nil, CreatedAt: earlier, + }, + want: false, + }, } for _, tc := range cases { if got := queuedTaskBefore(tc.left, tc.right); got != tc.want { diff --git a/apps/backend/internal/task/service/service_workflow_test.go b/apps/backend/internal/task/service/service_workflow_test.go index b0d46e5697..48b861be4d 100644 --- a/apps/backend/internal/task/service/service_workflow_test.go +++ b/apps/backend/internal/task/service/service_workflow_test.go @@ -695,12 +695,16 @@ func TestService_MoveTaskAllowsSameStepReorderWhenStepAlreadyOverLimit(t *testin createMoveTask(t, ctx, repo, "task-moving", "wf-source", "step-full", nil) createMoveTask(t, ctx, repo, "task-occupant", "wf-source", "step-full", nil) + // A same-step move is not an arrival (REQ-TASKS-KANBAN-TASK-REORDERING-001.28): + // the caller-supplied position (5) is ignored and the task keeps the + // position it already held. Reordering within a step is now the + // dedicated ReorderStepTasks endpoint's job, not MoveTask's. moved, err := svc.MoveTask(ctx, "task-moving", "wf-source", "step-full", 5) if err != nil { t.Fatalf("same-step reorder should be exempt from WIP limit: %v", err) } - if moved.Task.Position != 5 { - t.Fatalf("position = %d, want 5", moved.Task.Position) + if moved.Task.Position != 0 { + t.Fatalf("position = %d, want 0 (unchanged, caller-supplied position ignored)", moved.Task.Position) } } @@ -1088,6 +1092,175 @@ func TestService_BulkMoveSelectedTasksSkipsCurrentTargetAndAppendsInOrder(t *tes } } +// TestService_BulkMoveSelectedTasksReordersBySourceStepRegardlessOfSubmissionOrder +// pins AC-TASKS-KANBAN-TASK-REORDERING-001.29: the final order is derived +// from each task's source step ordinal (ties on source step id), not from +// the order the caller happened to list the ids in. step-source has ordinal +// 0 and step-review-target has ordinal 1 (both in wf-source, wired by +// seedMoveSteps), so a task from step-source must land before both +// step-review-target tasks even though it is submitted in the middle. +func TestService_BulkMoveSelectedTasksReordersBySourceStepRegardlessOfSubmissionOrder(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + createMoveTask(t, ctx, repo, "late-1", "wf-source", "step-review-target", nil) + createMoveTask(t, ctx, repo, "late-2", "wf-source", "step-review-target", nil) + createMoveTask(t, ctx, repo, "early-1", "wf-source", "step-source", nil) + + result, err := svc.BulkMoveSelectedTasks( + ctx, + []string{"late-1", "early-1", "late-2"}, + "wf-target", + "step-target", + ) + if err != nil { + t.Fatalf("BulkMoveSelectedTasks: %v", err) + } + if result.MovedCount != 3 { + t.Fatalf("MovedCount = %d, want 3", result.MovedCount) + } + + want := map[string]int{"early-1": 0, "late-1": 1, "late-2": 2} + for id, wantPosition := range want { + task, err := repo.GetTask(ctx, id) + if err != nil { + t.Fatalf("GetTask(%s): %v", id, err) + } + if task.Position != wantPosition { + t.Fatalf("%s position = %d, want %d (step-source ordinal 0 before step-review-target ordinal 1)", + id, task.Position, wantPosition) + } + } +} + +// TestService_BulkMoveSelectedTasksOrdersAdmittedBeforeQueuedWithinSourceStep +// pins AC-TASKS-KANBAN-TASK-REORDERING-001.29's second clause for the +// caller-selected path: within one source step, the admitted band goes +// before the queued band, in step order, regardless of selection order. +func TestService_BulkMoveSelectedTasksOrdersAdmittedBeforeQueuedWithinSourceStep(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + + createMoveTask(t, ctx, repo, "sel-queued-1", "wf-source", "step-source", nil) + must(t, repo.UpdateTask(ctx, mustGetTask(t, ctx, repo, "sel-queued-1", func(task *models.Task) { + task.WIPAdmitted = false + task.QueuedForStepID = "step-source" + }))) + createMoveTask(t, ctx, repo, "sel-admitted-1", "wf-source", "step-source", nil) + + result, err := svc.BulkMoveSelectedTasks( + ctx, + // Submitted queued-before-admitted: the final order must not follow + // this submission order, only the band precedence. + []string{"sel-queued-1", "sel-admitted-1"}, + "wf-target", + "step-target", + ) + if err != nil { + t.Fatalf("BulkMoveSelectedTasks: %v", err) + } + if result.MovedCount != 2 { + t.Fatalf("MovedCount = %d, want 2", result.MovedCount) + } + + want := map[string]int{"sel-admitted-1": 0, "sel-queued-1": 1} + for id, wantPosition := range want { + task, err := repo.GetTask(ctx, id) + if err != nil { + t.Fatalf("GetTask(%s): %v", id, err) + } + if task.Position != wantPosition { + t.Fatalf("%s position = %d, want %d (admitted band before queued band)", id, task.Position, wantPosition) + } + } +} + +// TestService_BulkMoveTasksOrdersBySourceStepOrdinal is BulkMoveTasks' sibling +// of TestService_BulkMoveSelectedTasksReordersBySourceStepRegardlessOfSubmissionOrder: +// the admin whole-workflow migration path (no explicit task_ids) must also +// derive AC.29's submission order from source step ordinal, not the +// repository's raw created_at listing order. +func TestService_BulkMoveTasksOrdersBySourceStepOrdinal(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + createMoveTask(t, ctx, repo, "late-1", "wf-source", "step-review-target", nil) + createMoveTask(t, ctx, repo, "late-2", "wf-source", "step-review-target", nil) + createMoveTask(t, ctx, repo, "early-1", "wf-source", "step-source", nil) + + result, err := svc.BulkMoveTasks(ctx, "wf-source", "", "wf-target", "step-target") + if err != nil { + t.Fatalf("BulkMoveTasks: %v", err) + } + if result.MovedCount != 3 { + t.Fatalf("MovedCount = %d, want 3", result.MovedCount) + } + + want := map[string]int{"early-1": 0, "late-1": 1, "late-2": 2} + for id, wantPosition := range want { + task, err := repo.GetTask(ctx, id) + if err != nil { + t.Fatalf("GetTask(%s): %v", id, err) + } + if task.Position != wantPosition { + t.Fatalf("%s position = %d, want %d (step-source ordinal 0 before step-review-target ordinal 1)", + id, task.Position, wantPosition) + } + } +} + +// TestService_BulkMoveTasksOrdersAdmittedBeforeQueuedWithinSourceStep covers +// AC.29's second clause for the same admin path: within one source step, the +// admitted band goes before the queued band, in step order. +func TestService_BulkMoveTasksOrdersAdmittedBeforeQueuedWithinSourceStep(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + seedMoveWorkflows(t, ctx, repo) + seedMoveSteps(svc) + + createMoveTask(t, ctx, repo, "queued-1", "wf-source", "step-source", nil) + must(t, repo.UpdateTask(ctx, mustGetTask(t, ctx, repo, "queued-1", func(task *models.Task) { + task.WIPAdmitted = false + task.QueuedForStepID = "step-source" + }))) + createMoveTask(t, ctx, repo, "admitted-1", "wf-source", "step-source", nil) + + result, err := svc.BulkMoveTasks(ctx, "wf-source", "step-source", "wf-target", "step-target") + if err != nil { + t.Fatalf("BulkMoveTasks: %v", err) + } + if result.MovedCount != 2 { + t.Fatalf("MovedCount = %d, want 2", result.MovedCount) + } + + want := map[string]int{"admitted-1": 0, "queued-1": 1} + for id, wantPosition := range want { + task, err := repo.GetTask(ctx, id) + if err != nil { + t.Fatalf("GetTask(%s): %v", id, err) + } + if task.Position != wantPosition { + t.Fatalf("%s position = %d, want %d (admitted band before queued band)", id, task.Position, wantPosition) + } + } +} + +func mustGetTask(t *testing.T, ctx context.Context, repo interface { + GetTask(context.Context, string) (*models.Task, error) +}, id string, mutate func(*models.Task)) *models.Task { + t.Helper() + task, err := repo.GetTask(ctx, id) + if err != nil { + t.Fatalf("GetTask(%s): %v", id, err) + } + mutate(task) + return task +} + func seedMoveWorkflows(t *testing.T, ctx context.Context, repo interface { CreateWorkspace(context.Context, *models.Workspace) error CreateWorkflow(context.Context, *models.Workflow) error @@ -1130,7 +1303,7 @@ func createMoveTask(t *testing.T, ctx context.Context, repo interface { func setMoveTaskOrder(t *testing.T, ctx context.Context, repo interface { GetTask(context.Context, string) (*models.Task, error) - UpdateTask(context.Context, *models.Task) error + UpdateTaskWithExplicitPosition(context.Context, *models.Task) error }, id string, position int, priority string) { t.Helper() task, err := repo.GetTask(ctx, id) @@ -1139,8 +1312,8 @@ func setMoveTaskOrder(t *testing.T, ctx context.Context, repo interface { } task.Position = position task.Priority = priority - if err := repo.UpdateTask(ctx, task); err != nil { - t.Fatalf("UpdateTask(%s): %v", id, err) + if err := repo.UpdateTaskWithExplicitPosition(ctx, task); err != nil { + t.Fatalf("UpdateTaskWithExplicitPosition(%s): %v", id, err) } } diff --git a/apps/backend/internal/workflow/models/models.go b/apps/backend/internal/workflow/models/models.go index 5803168aba..8f48a4ad1b 100644 --- a/apps/backend/internal/workflow/models/models.go +++ b/apps/backend/internal/workflow/models/models.go @@ -250,9 +250,14 @@ type WorkflowStep struct { // this step's ordinary on_turn_complete actions. CancelTriggersTurnComplete bool `json:"cancel_triggers_turn_complete"` // CompleteTaskOnEnter marks the final step as completing its task on entry. - CompleteTaskOnEnter bool `json:"complete_task_on_enter"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + CompleteTaskOnEnter bool `json:"complete_task_on_enter"` + // OrderRevision is bumped by ReorderStepTasks (AC-TASKS-KANBAN-TASK- + // REORDERING-001.25/.37) each time this step's task order changes. A + // consumer that records the value it last saw can reject a WS event + // carrying a revision no greater than that. + OrderRevision int64 `json:"order_revision"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } // HasOnEnterAction checks if the step has a specific on_enter action type. diff --git a/apps/backend/internal/workflow/repository/sqlite.go b/apps/backend/internal/workflow/repository/sqlite.go index 2e228decf6..210fc72381 100644 --- a/apps/backend/internal/workflow/repository/sqlite.go +++ b/apps/backend/internal/workflow/repository/sqlite.go @@ -80,6 +80,7 @@ func (r *Repository) initSchema() error { auto_advance_requires_signal INTEGER NOT NULL DEFAULT 0, cancel_triggers_turn_complete INTEGER NOT NULL DEFAULT 0, complete_task_on_enter INTEGER NOT NULL DEFAULT 0, + order_revision INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL, FOREIGN KEY (workflow_id) REFERENCES workflows(id) ON DELETE CASCADE @@ -139,6 +140,11 @@ func (r *Repository) initSchema() error { CREATE INDEX IF NOT EXISTS idx_workflow_steps_pull_from ON workflow_steps(pull_from_step_id) `) + // Kanban task reordering (REQ-TASKS-KANBAN-TASK-REORDERING-001.25): + // per-step monotonic counter, incremented once per committed reorder in + // the same serialized section that renumbers the step. Starts at 0 for + // every existing row so a never-reordered step is not a special case. + _ = r.migrate.Apply("workflow_steps.order_revision", `ALTER TABLE workflow_steps ADD COLUMN order_revision INTEGER NOT NULL DEFAULT 0`) // Phase 2 — multi-agent participation tables. Empty rows for a step // preserve today's single-agent behaviour, so existing kanban @@ -705,7 +711,7 @@ func (r *Repository) scanStep(row interface { var color, prompt, eventsJSON, agentProfileID, profileSessionStartPolicy, profileSessionEndPolicy, stageType, pullFromStepID, sessionTargetJSON sql.NullString err := row.Scan(&step.ID, &step.WorkflowID, &step.Name, &step.Position, &color, - &prompt, &eventsJSON, &allowManualMove, &isStartStep, &showInCommandPanel, &autoArchiveAfterHours, &agentProfileID, &profileSessionStartPolicy, &profileSessionEndPolicy, &stageType, &autoAdvanceRequiresSignal, &cancelTriggersTurnComplete, &completeTaskOnEnter, &step.WIPLimit, &pullFromStepID, &sessionTargetJSON, &step.CreatedAt, &step.UpdatedAt) + &prompt, &eventsJSON, &allowManualMove, &isStartStep, &showInCommandPanel, &autoArchiveAfterHours, &agentProfileID, &profileSessionStartPolicy, &profileSessionEndPolicy, &stageType, &autoAdvanceRequiresSignal, &cancelTriggersTurnComplete, &completeTaskOnEnter, &step.WIPLimit, &pullFromStepID, &sessionTargetJSON, &step.OrderRevision, &step.CreatedAt, &step.UpdatedAt) if err != nil { return nil, err @@ -753,7 +759,7 @@ func (r *Repository) scanStep(row interface { return step, nil } -const stepSelectColumns = `id, workflow_id, name, position, color, prompt, events, allow_manual_move, is_start_step, show_in_command_panel, auto_archive_after_hours, agent_profile_id, profile_session_start_policy, profile_session_end_policy, stage_type, auto_advance_requires_signal, cancel_triggers_turn_complete, complete_task_on_enter, wip_limit, pull_from_step_id, session_target, created_at, updated_at` +const stepSelectColumns = `id, workflow_id, name, position, color, prompt, events, allow_manual_move, is_start_step, show_in_command_panel, auto_archive_after_hours, agent_profile_id, profile_session_start_policy, profile_session_end_policy, stage_type, auto_advance_requires_signal, cancel_triggers_turn_complete, complete_task_on_enter, wip_limit, pull_from_step_id, session_target, order_revision, created_at, updated_at` // GetStep retrieves a workflow step by ID. func (r *Repository) GetStep(ctx context.Context, id string) (*models.WorkflowStep, error) { @@ -1026,7 +1032,7 @@ func (r *Repository) ListStepsByWorkflow(ctx context.Context, workflowID string) func (r *Repository) ListStepsByWorkspaceID(ctx context.Context, workspaceID string) ([]*models.WorkflowStep, error) { rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(` SELECT ws.id, ws.workflow_id, ws.name, ws.position, ws.color, ws.prompt, ws.events, - ws.allow_manual_move, ws.is_start_step, ws.show_in_command_panel, ws.auto_archive_after_hours, ws.agent_profile_id, ws.profile_session_start_policy, ws.profile_session_end_policy, ws.stage_type, ws.auto_advance_requires_signal, ws.cancel_triggers_turn_complete, ws.complete_task_on_enter, ws.wip_limit, ws.pull_from_step_id, ws.session_target, ws.created_at, ws.updated_at + ws.allow_manual_move, ws.is_start_step, ws.show_in_command_panel, ws.auto_archive_after_hours, ws.agent_profile_id, ws.profile_session_start_policy, ws.profile_session_end_policy, ws.stage_type, ws.auto_advance_requires_signal, ws.cancel_triggers_turn_complete, ws.complete_task_on_enter, ws.wip_limit, ws.pull_from_step_id, ws.session_target, ws.order_revision, ws.created_at, ws.updated_at FROM workflow_steps ws JOIN workflows w ON ws.workflow_id = w.id WHERE w.workspace_id = ? diff --git a/apps/backend/internal/workflow/repository/sqlite_test.go b/apps/backend/internal/workflow/repository/sqlite_test.go index 6c9f9113da..1acffde647 100644 --- a/apps/backend/internal/workflow/repository/sqlite_test.go +++ b/apps/backend/internal/workflow/repository/sqlite_test.go @@ -92,6 +92,67 @@ func TestStepAgentProfileID_CreateAndGet(t *testing.T) { } } +// TestGetStepAndListStepsByWorkflow_IncludeOrderRevision covers the +// Build-phase fix for missing order_revision on HTTP hydration: GetStep and +// ListStepsByWorkflow must surface the step's current order_revision so the +// frontend can seed its last-known revision before accepting a +// task.reordered WS event. The reorder endpoint bumps order_revision from +// the task repository package (a different package, same table), so this +// test simulates that bump directly against the column rather than +// depending on that package. +func TestGetStepAndListStepsByWorkflow_IncludeOrderRevision(t *testing.T) { + repo := setupTestRepo(t) + ctx := context.Background() + + step := &models.WorkflowStep{ + WorkflowID: "wf-test", + Name: "Test Step", + Position: 0, + Color: "#000000", + } + if err := repo.CreateStep(ctx, step); err != nil { + t.Fatalf("failed to create step: %v", err) + } + + fresh, err := repo.GetStep(ctx, step.ID) + if err != nil { + t.Fatalf("GetStep: %v", err) + } + if fresh.OrderRevision != 0 { + t.Fatalf("OrderRevision = %d, want 0 for a freshly created step", fresh.OrderRevision) + } + + if _, err := repo.db.Exec(`UPDATE workflow_steps SET order_revision = 3 WHERE id = ?`, step.ID); err != nil { + t.Fatalf("bump order_revision: %v", err) + } + + bumped, err := repo.GetStep(ctx, step.ID) + if err != nil { + t.Fatalf("GetStep after bump: %v", err) + } + if bumped.OrderRevision != 3 { + t.Fatalf("OrderRevision = %d, want 3", bumped.OrderRevision) + } + + // "wf-test" also carries the default-template steps seedDefaultWorkflowSteps + // creates for any workflow with none, so find this test's step by ID + // rather than assuming it is the only row. + listed, err := repo.ListStepsByWorkflow(ctx, "wf-test") + if err != nil { + t.Fatalf("ListStepsByWorkflow: %v", err) + } + var found *models.WorkflowStep + for _, s := range listed { + if s.ID == step.ID { + found = s + break + } + } + if found == nil || found.OrderRevision != 3 { + t.Fatalf("ListStepsByWorkflow step %s = %+v, want OrderRevision 3", step.ID, found) + } +} + func TestDeleteStep_ClearsQueuedTaskDestinationAndDeferredLaunch(t *testing.T) { repo, db := setupTestRepoWithDB(t) ctx := context.Background() diff --git a/apps/backend/internal/workflow/stepevents/stepevents.go b/apps/backend/internal/workflow/stepevents/stepevents.go index 51b5be643c..e20a4b40ee 100644 --- a/apps/backend/internal/workflow/stepevents/stepevents.go +++ b/apps/backend/internal/workflow/stepevents/stepevents.go @@ -86,6 +86,7 @@ func payload(step *models.WorkflowStep) map[string]interface{} { "auto_advance_requires_signal": step.AutoAdvanceRequiresSignal, "cancel_triggers_turn_complete": step.CancelTriggersTurnComplete, "complete_task_on_enter": step.CompleteTaskOnEnter, + "order_revision": step.OrderRevision, "created_at": step.CreatedAt, "updated_at": step.UpdatedAt, } diff --git a/apps/backend/internal/workflow/stepevents/stepevents_test.go b/apps/backend/internal/workflow/stepevents/stepevents_test.go index e6f5f9db43..731f629cd3 100644 --- a/apps/backend/internal/workflow/stepevents/stepevents_test.go +++ b/apps/backend/internal/workflow/stepevents/stepevents_test.go @@ -58,6 +58,7 @@ func fullStep() *models.WorkflowStep { AutoAdvanceRequiresSignal: true, CancelTriggersTurnComplete: true, CompleteTaskOnEnter: true, + OrderRevision: 7, CreatedAt: created, UpdatedAt: updated, } @@ -107,6 +108,7 @@ func TestPublishCarriesEveryStepField(t *testing.T) { "auto_advance_requires_signal": step.AutoAdvanceRequiresSignal, "cancel_triggers_turn_complete": step.CancelTriggersTurnComplete, "complete_task_on_enter": step.CompleteTaskOnEnter, + "order_revision": step.OrderRevision, "created_at": step.CreatedAt, "updated_at": step.UpdatedAt, } diff --git a/apps/backend/pkg/pluginsdk/data_types.go b/apps/backend/pkg/pluginsdk/data_types.go index 2399719b68..b14342124a 100644 --- a/apps/backend/pkg/pluginsdk/data_types.go +++ b/apps/backend/pkg/pluginsdk/data_types.go @@ -1248,9 +1248,12 @@ func updateTaskInputFromProto(p *pluginv1.UpdateTaskRequest) UpdateTaskInput { // Unlike Update, Move transitions the task through the same path the board's // own move uses, so on_enter actions (auto-start included) actually fire. // WorkflowID is optional: nil inherits the task's current workflow; a -// pointer to "" is rejected rather than treated as inherit. Position is not -// optional: an omitted position and a position of zero are the same -// request, both placing the task at the top of the target step. +// pointer to "" is rejected rather than treated as inherit. Position stays +// on the struct for wire compatibility but is ignored: the server computes +// an arriving task's position from the target step's current highest +// position, so it always sorts last there rather than displacing work a +// user has already ordered. Naming the task's current step is not an +// arrival and leaves its existing position untouched. type MoveTaskInput struct { TaskID string WorkflowStepID string diff --git a/apps/backend/pkg/websocket/actions.go b/apps/backend/pkg/websocket/actions.go index a1c57ca3e5..a4bada5775 100644 --- a/apps/backend/pkg/websocket/actions.go +++ b/apps/backend/pkg/websocket/actions.go @@ -199,6 +199,7 @@ const ( ActionACPHeartbeat = "acp.heartbeat" ActionTaskCreated = "task.created" ActionTaskUpdated = "task.updated" + ActionTaskReordered = "task.reordered" ActionTaskDeleted = "task.deleted" ActionTaskStateChanged = "task.state_changed" ActionSessionWorkspaceSourcesUpdated = "session.workspace_sources.updated" diff --git a/apps/backend/proto/kandev/plugin/v1/plugin.pb.go b/apps/backend/proto/kandev/plugin/v1/plugin.pb.go index 917809f361..d6ec4a4d7d 100644 --- a/apps/backend/proto/kandev/plugin/v1/plugin.pb.go +++ b/apps/backend/proto/kandev/plugin/v1/plugin.pb.go @@ -6762,8 +6762,11 @@ func (x *UpdateTaskResponse) GetTask() *Task { // MoveTask transitions a task to a workflow step. workflow_id is optional: // omitted inherits the task's current workflow, present-empty is rejected. -// position is not optional: an omitted position and a position of zero are -// the same request, both placing the task at the top of the target step. +// position stays on the wire for compatibility but is ignored: the server +// computes an arriving task's position from the target step's current +// highest position, so it always sorts last there rather than displacing +// work a user has already ordered. Naming the task's current step is not an +// arrival and leaves its existing position untouched. type MoveTaskRequest struct { state protoimpl.MessageState `protogen:"open.v1"` TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` diff --git a/apps/backend/proto/kandev/plugin/v1/plugin.proto b/apps/backend/proto/kandev/plugin/v1/plugin.proto index 1f195d5c2c..a7b5b056e8 100644 --- a/apps/backend/proto/kandev/plugin/v1/plugin.proto +++ b/apps/backend/proto/kandev/plugin/v1/plugin.proto @@ -871,8 +871,11 @@ message UpdateTaskResponse { } // MoveTask transitions a task to a workflow step. workflow_id is optional: // omitted inherits the task's current workflow, present-empty is rejected. -// position is not optional: an omitted position and a position of zero are -// the same request, both placing the task at the top of the target step. +// position stays on the wire for compatibility but is ignored: the server +// computes an arriving task's position from the target step's current +// highest position, so it always sorts last there rather than displacing +// work a user has already ordered. Naming the task's current step is not an +// arrival and leaves its existing position untouched. message MoveTaskRequest { string task_id = 1; string workflow_step_id = 2; diff --git a/apps/web/components/kanban-card-actions.tsx b/apps/web/components/kanban-card-actions.tsx new file mode 100644 index 0000000000..cdc964b49c --- /dev/null +++ b/apps/web/components/kanban-card-actions.tsx @@ -0,0 +1,185 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { IconArrowsMaximize, IconDots } from "@tabler/icons-react"; +import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from "@kandev/ui/dropdown-menu"; +import { KanbanCardDropdownMenuItems } from "@/components/kanban-card-menu-items"; +import type { KanbanCardActionProps } from "@/components/kanban-card-content"; +import { + renderSubagentCountChip, + renderTaskStatusIcon, +} from "@/components/kanban-card-status-icon"; +import { useAppStoreApi } from "@/components/state-provider"; +import { useTaskPendingInput } from "@/hooks/use-task-pending-input"; +import { createDebugLogger, isDebug } from "@/lib/debug/log"; +import { shouldShowTaskRunningSpinner } from "@/lib/ui/state-icons"; +import type { Task } from "@/components/kanban-card"; + +const kanbanStatusDebug = createDebugLogger("kanban:task-status"); + +function OpenFullPageButton({ + task, + onOpenFullPage, +}: { + task: Task; + onOpenFullPage: (task: Task) => void; +}) { + const { t } = useTranslation("common"); + + return ( + + ); +} + +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 ( + { + if (!open && isProcessing) return; + setMenuOpen(open); + }} + > + + + + + + + + ); +} + +export function KanbanCardActions({ + task, + showMaximizeButton, + onOpenFullPage, + menuEntries, + isDeleting, + isArchiving, + menuTriggerRef, +}: KanbanCardActionProps) { + const { t } = useTranslation("common"); + const [menuOpen, setMenuOpen] = useState(false); + const [storePrimarySessionState, setStorePrimarySessionState] = useState(null); + const storeApi = useAppStoreApi(); + const debugEnabled = isDebug(); + const effectiveMenuOpen = menuOpen || Boolean(isDeleting) || Boolean(isArchiving); + const pendingInput = useTaskPendingInput(task.primarySessionId, { + taskId: task.id, + taskPendingAction: task.taskPendingAction, + statusSummary: task.statusSummary, + primarySessionState: task.primarySessionState, + primarySessionPendingAction: task.primarySessionPendingAction, + }); + const showRunningSpinner = shouldShowTaskRunningSpinner(task.state, task.primarySessionState); + const storeWouldShowRunningSpinner = + storePrimarySessionState === null + ? null + : shouldShowTaskRunningSpinner(task.state, storePrimarySessionState); + const hasSpinnerMismatch = + showRunningSpinner && + storeWouldShowRunningSpinner === false && + task.primarySessionState !== storePrimarySessionState; + const statusIcon = renderTaskStatusIcon( + task, + showRunningSpinner, + pendingInput.clarification, + pendingInput.permission, + ); + const hasKnownSession = + Boolean(task.primarySessionId) || Boolean(task.sessionCount && task.sessionCount > 0); + + useEffect(() => { + if (!debugEnabled || !task.primarySessionId) { + setStorePrimarySessionState(null); + return; + } + + const primarySessionId = task.primarySessionId; + const readPrimarySessionState = () => + storeApi.getState().taskSessions.items[primarySessionId]?.state ?? null; + const syncPrimarySessionState = () => { + const nextState = readPrimarySessionState(); + setStorePrimarySessionState((current) => (current === nextState ? current : nextState)); + }; + + syncPrimarySessionState(); + return storeApi.subscribe(syncPrimarySessionState); + }, [debugEnabled, storeApi, task.primarySessionId]); + + useEffect(() => { + if (!hasSpinnerMismatch || !debugEnabled) return; + kanbanStatusDebug("spinner mismatch", { + task_id: task.id, + taskState: task.state ?? "-", + primarySessionId: task.primarySessionId ?? "-", + taskPrimarySessionState: task.primarySessionState ?? "-", + storePrimarySessionState: storePrimarySessionState ?? "-", + showSpinner: showRunningSpinner, + }); + }, [ + debugEnabled, + hasSpinnerMismatch, + showRunningSpinner, + storePrimarySessionState, + task.id, + task.primarySessionId, + task.primarySessionState, + task.state, + ]); + + return ( +
+ {renderSubagentCountChip( + task, + t("common:activeSubagents", { count: task.activeSubagentCount ?? 0 }), + )} + {statusIcon} + {showMaximizeButton && onOpenFullPage && hasKnownSession && ( + + )} + +
+ ); +} diff --git a/apps/web/components/kanban-card-content.tsx b/apps/web/components/kanban-card-content.tsx index ec4e54d416..ba8f561e6f 100644 --- a/apps/web/components/kanban-card-content.tsx +++ b/apps/web/components/kanban-card-content.tsx @@ -1,20 +1,16 @@ "use client"; -import { useEffect, useState, type RefObject } from "react"; +import { type RefObject } from "react"; import { useTranslation } from "react-i18next"; import { CSS, type Transform } from "@dnd-kit/utilities"; import type { DraggableAttributes, DraggableSyntheticListeners } from "@dnd-kit/core"; -import { IconArrowsMaximize, IconDots, IconUsersGroup } from "@tabler/icons-react"; import { Card, CardContent } from "@kandev/ui/card"; import { Checkbox } from "@kandev/ui/checkbox"; -import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from "@kandev/ui/dropdown-menu"; import { PRTaskIcon } from "@/components/github/pr-task-icon"; import { MRTaskIcon } from "@/components/gitlab/mr-task-icon"; import { RegisteredChangeRequestTaskIcon } from "@/components/integrations/registered-change-request-task-icon"; -import { - KanbanCardDropdownMenuItems, - type KanbanCardMenuEntry, -} from "@/components/kanban-card-menu-items"; +import { KanbanCardActions } from "@/components/kanban-card-actions"; +import { type KanbanCardMenuEntry } from "@/components/kanban-card-menu-items"; import { TaskCardIndicators, TaskCardTags } from "@/components/kanban-card-plugin-slots"; import { KanbanCardBadges, @@ -23,24 +19,18 @@ import { } from "@/components/kanban-card-status-strip"; import { KanbanCardPriorityIndicator } from "@/components/kanban-card-priority-indicator"; import { CardTitle } from "@/components/kanban-card-title"; -import { useAppStoreApi } from "@/components/state-provider"; import { RemoteCloudTooltip } from "@/components/task/remote-cloud-tooltip"; -import { useTaskPendingInput } from "@/hooks/use-task-pending-input"; -import { createDebugLogger, isDebug } from "@/lib/debug/log"; import { taskPRInfoFromSummary } from "@/lib/task-pr-info"; -import { - getTaskStateIcon, - shouldShowTaskRunningSpinner, - shouldUsePermissionTaskIcon, - shouldUseQuestionTaskIcon, -} from "@/lib/ui/state-icons"; import { cn } from "@/lib/utils"; import { needsAction } from "@/lib/utils/needs-action"; import type { RepositoryChip, Task } from "@/components/kanban-card"; -const kanbanStatusDebug = createDebugLogger("kanban:task-status"); +export { + renderSubagentCountChip, + renderTaskStatusIcon, +} from "@/components/kanban-card-status-icon"; -type KanbanCardActionProps = { +export type KanbanCardActionProps = { task: Task; showMaximizeButton?: boolean; onOpenFullPage?: (task: Task) => void; @@ -66,6 +56,9 @@ export type KanbanCardShellProps = KanbanCardActionProps & isPreviewed: boolean; onClick: (e: React.MouseEvent) => void; onCheckboxClick: (e: React.MouseEvent) => void; + /** Keyboard reorder (REQ-TASKS-KANBAN-TASK-REORDERING-001.12). */ + onKeyDown?: (event: React.KeyboardEvent) => void; + isPickedUpForReorder?: boolean; }; export function KanbanCardBody({ @@ -116,272 +109,6 @@ export function KanbanCardBody({ ); } -// Status markers that mask the launch spinner and gate the resting no-affordance -// case. Keep them together so the renderer stays easy to audit. -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 - ); -} - -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; -} - -// renderTaskStatusIcon 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 ( - - - ); -} - -function OpenFullPageButton({ - task, - onOpenFullPage, -}: { - task: Task; - onOpenFullPage: (task: Task) => void; -}) { - const { t } = useTranslation("common"); - - return ( - - ); -} - -function KanbanCardActions({ - task, - showMaximizeButton, - onOpenFullPage, - menuEntries, - isDeleting, - isArchiving, - menuTriggerRef, -}: KanbanCardActionProps) { - const { t } = useTranslation("common"); - const [menuOpen, setMenuOpen] = useState(false); - const [storePrimarySessionState, setStorePrimarySessionState] = useState(null); - const storeApi = useAppStoreApi(); - const debugEnabled = isDebug(); - const effectiveMenuOpen = menuOpen || Boolean(isDeleting) || Boolean(isArchiving); - const pendingInput = useTaskPendingInput(task.primarySessionId, { - taskId: task.id, - taskPendingAction: task.taskPendingAction, - statusSummary: task.statusSummary, - primarySessionState: task.primarySessionState, - primarySessionPendingAction: task.primarySessionPendingAction, - }); - const showRunningSpinner = shouldShowTaskRunningSpinner(task.state, task.primarySessionState); - const storeWouldShowRunningSpinner = - storePrimarySessionState === null - ? null - : shouldShowTaskRunningSpinner(task.state, storePrimarySessionState); - const hasSpinnerMismatch = - showRunningSpinner && - storeWouldShowRunningSpinner === false && - task.primarySessionState !== storePrimarySessionState; - const statusIcon = renderTaskStatusIcon( - task, - showRunningSpinner, - pendingInput.clarification, - pendingInput.permission, - ); - const hasKnownSession = - Boolean(task.primarySessionId) || Boolean(task.sessionCount && task.sessionCount > 0); - - useEffect(() => { - if (!debugEnabled || !task.primarySessionId) { - setStorePrimarySessionState(null); - return; - } - - const primarySessionId = task.primarySessionId; - const readPrimarySessionState = () => - storeApi.getState().taskSessions.items[primarySessionId]?.state ?? null; - const syncPrimarySessionState = () => { - const nextState = readPrimarySessionState(); - setStorePrimarySessionState((current) => (current === nextState ? current : nextState)); - }; - - syncPrimarySessionState(); - return storeApi.subscribe(syncPrimarySessionState); - }, [debugEnabled, storeApi, task.primarySessionId]); - - useEffect(() => { - if (!hasSpinnerMismatch || !debugEnabled) return; - kanbanStatusDebug("spinner mismatch", { - task_id: task.id, - taskState: task.state ?? "-", - primarySessionId: task.primarySessionId ?? "-", - taskPrimarySessionState: task.primarySessionState ?? "-", - storePrimarySessionState: storePrimarySessionState ?? "-", - showSpinner: showRunningSpinner, - }); - }, [ - debugEnabled, - hasSpinnerMismatch, - showRunningSpinner, - storePrimarySessionState, - task.id, - task.primarySessionId, - task.primarySessionState, - task.state, - ]); - - return ( -
- {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 ( - { - if (!open && isProcessing) return; - setMenuOpen(open); - }} - > - - - - - - - - ); -} - function KanbanCardCheckbox({ taskId, taskTitle, @@ -410,6 +137,38 @@ function KanbanCardCheckbox({ ); } +function getKanbanCardShellClassName( + task: Task, + state: { + isSelected?: boolean; + isDragging?: boolean; + isPreviewed?: boolean; + isPickedUpForReorder?: boolean; + }, +): string { + const { isSelected, isDragging, isPreviewed, isPickedUpForReorder } = state; + return cn( + "group max-h-48 bg-card rounded-sm data-[size=sm]:py-1 cursor-pointer mb-2 w-full py-0 relative border border-border overflow-visible shadow-none ring-0", + "touch-none md:touch-auto", + needsAction(task) && !isSelected && "border-l-2 border-l-amber-500", + isDragging && "opacity-50 z-50", + isSelected && "ring-1 ring-primary/60 border-primary/60", + isPreviewed && !isSelected && "ring-2 ring-primary border-primary", + isPickedUpForReorder && "ring-2 ring-primary border-primary", + ); +} + +/** Suppresses dnd-kit's drag/keyboard wiring while multi-select is active. */ +function getDragInteractionProps( + isMultiSelectMode: boolean | undefined, + listeners: DraggableSyntheticListeners, + attributes: DraggableAttributes, + onKeyDown: ((event: React.KeyboardEvent) => void) | undefined, +) { + if (isMultiSelectMode) return {}; + return { ...listeners, ...attributes, onKeyDown }; +} + function KanbanCardActionSlot({ isMultiSelectMode, task, @@ -451,6 +210,8 @@ export function KanbanCardShell({ onClick, onCheckboxClick, onOpenFullPage, + onKeyDown, + isPickedUpForReorder, menuEntries, menuTriggerRef, }: KanbanCardShellProps) { @@ -468,17 +229,15 @@ export function KanbanCardShell({ style={style} data-testid={`task-card-${task.id}`} data-kanban-card="" - className={cn( - "group max-h-48 bg-card rounded-sm data-[size=sm]:py-1 cursor-pointer mb-2 w-full py-0 relative border border-border overflow-visible shadow-none ring-0", - "touch-none md:touch-auto", - needsAction(task) && !isSelected && "border-l-2 border-l-amber-500", - isDragging && "opacity-50 z-50", - isSelected && "ring-1 ring-primary/60 border-primary/60", - isPreviewed && !isSelected && "ring-2 ring-primary border-primary", - )} + className={getKanbanCardShellClassName(task, { + isSelected, + isDragging, + isPreviewed, + isPickedUpForReorder, + })} + aria-grabbed={isPickedUpForReorder || undefined} onClick={onClick} - {...(!isMultiSelectMode ? listeners : {})} - {...(!isMultiSelectMode ? attributes : {})} + {...getDragInteractionProps(isMultiSelectMode, listeners, attributes, onKeyDown)} >
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 ( + + + ); +} 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)