diff --git a/cmd/archied/task_actions_test.go b/cmd/archied/task_actions_test.go index 88eade7a6..b63d7cfd6 100644 --- a/cmd/archied/task_actions_test.go +++ b/cmd/archied/task_actions_test.go @@ -77,6 +77,8 @@ func TestDashboardAndChatAgreeOnTerminalStates(t *testing.T) { req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"`+tc.action+`"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Archie-CSRF", "1") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { diff --git a/internal/nell/adapter.go b/internal/nell/adapter.go index 506fac492..771f38eea 100644 --- a/internal/nell/adapter.go +++ b/internal/nell/adapter.go @@ -328,6 +328,9 @@ func (a *Adapter) Transition(ctx context.Context, taskID int64, from, to, detail // iterations, park_reason, watch_comment_id. Status and identity fields // (owner, repo, issue_number, title, body, labels) are preserved. func (a *Adapter) Update(ctx context.Context, t *store.Task) error { + a.mu.Lock() + defer a.mu.Unlock() + key := taskKey(t.Owner, t.Repo, t.IssueNumber) doc, err := a.tasks.Get(ctx, key) if err != nil { @@ -379,6 +382,61 @@ func (a *Adapter) Requeue(ctx context.Context, taskID int64, fromStatus, workflo return a.putTaskByID(ctx, t) } +// RetryTask updates both lifecycle state and retry accounting with one Nell +// document write under the same mutation lock used by transitions. +func (a *Adapter) RetryTask(ctx context.Context, taskID int64, fromStatus, workflow string) error { + a.mu.Lock() + defer a.mu.Unlock() + + t, err := a.findTaskByID(ctx, taskID) + if err != nil { + return err + } + if t == nil { + return fmt.Errorf("nell: task %d not found", taskID) + } + if t.Status != fromStatus { + return store.ErrStaleTransition + } + t.Status = store.StatusQueued + t.RetryCount++ + if workflow != "" { + t.Workflow = workflow + } + t.Stage = "" + t.ParkReason = "" + return a.putTaskByID(ctx, t) +} + +// ArchiveTask removes one terminal task from the active task collection. +// NellDB has no conditional delete, so the adapter mutex makes the guarded +// read and remove one process-local operation, matching Transition/Requeue. +func (a *Adapter) ArchiveTask( + ctx context.Context, + taskID int64, + fromStatus string, + audit events.Event, +) (int64, error) { + a.mu.Lock() + defer a.mu.Unlock() + + t, err := a.findTaskByID(ctx, taskID) + if err != nil { + return 0, err + } + if t == nil || t.Status != fromStatus { + return 0, store.ErrStaleTransition + } + eventID, err := a.insertEventLocked(ctx, audit) + if err != nil { + return 0, err + } + if _, err := a.tasks.Remove(ctx, taskKey(t.Owner, t.Repo, t.IssueNumber)); err != nil { + return 0, fmt.Errorf("nell: archive task after audit %d: %w", eventID, err) + } + return eventID, nil +} + // RecoverStale re-queues all tasks left in "running" status. Returns the // number of tasks recovered. func (a *Adapter) RecoverStale(ctx context.Context) (int64, error) { @@ -468,7 +526,7 @@ func (a *Adapter) ClearTerminalTasks(ctx context.Context) (int64, error) { } t := docToTask(row.Doc) switch t.Status { - case store.StatusMerged, store.StatusParked, store.StatusRejected, store.StatusClosedWontDo: + case store.StatusMerged, store.StatusRejected, store.StatusDead, store.StatusClosedWontDo: if _, err := a.tasks.Remove(ctx, row.ID); err != nil { return count, err } @@ -484,7 +542,13 @@ func (a *Adapter) ClearTerminalTasks(ctx context.Context) (int64, error) { func (a *Adapter) InsertEvent(ctx context.Context, e events.Event) (int64, error) { a.mu.Lock() defer a.mu.Unlock() + return a.insertEventLocked(ctx, e) +} +func (a *Adapter) insertEventLocked(ctx context.Context, e events.Event) (int64, error) { + if e.At.IsZero() { + e.At = time.Now().UTC() + } id, err := a.nextEventID(ctx) if err != nil { return 0, err diff --git a/internal/nell/adapter_test.go b/internal/nell/adapter_test.go index a3dc49e1b..0b1827ec4 100644 --- a/internal/nell/adapter_test.go +++ b/internal/nell/adapter_test.go @@ -2,6 +2,7 @@ package nell import ( "context" + "errors" "path/filepath" "strings" "sync" @@ -41,6 +42,41 @@ func TestEnqueueIdempotent(t *testing.T) { } } +func TestArchiveTaskIsGuardedAndScoped(t *testing.T) { + s := openTest(t) + ctx := context.Background() + for number := 1; number <= 2; number++ { + if _, err := s.EnqueueIssue(ctx, "acme", "widget", number, "t", "b", "", ""); err != nil { + t.Fatal(err) + } + } + task, err := s.TaskByIssue(ctx, "acme", "widget", 1) + if err != nil || task == nil { + t.Fatalf("TaskByIssue = (%+v, %v)", task, err) + } + if err := s.Transition(ctx, task.ID, store.StatusQueued, store.StatusMerged, "done"); err != nil { + t.Fatal(err) + } + + audit := events.Event{Kind: events.KindTaskArchiveRequested, TaskID: task.ID} + if _, err := s.ArchiveTask(ctx, task.ID, store.StatusQueued, audit); !errors.Is(err, store.ErrStaleTransition) { + t.Fatalf("ArchiveTask stale guard = %v, want ErrStaleTransition", err) + } + eventID, err := s.ArchiveTask(ctx, task.ID, store.StatusMerged, audit) + if err != nil { + t.Fatalf("ArchiveTask = %v", err) + } + if eventID == 0 { + t.Fatal("ArchiveTask returned no durable event ID") + } + if got, err := s.TaskByID(ctx, task.ID); err != nil || got != nil { + t.Fatalf("archived task = (%+v, %v), want nil", got, err) + } + if other, err := s.TaskByIssue(ctx, "acme", "widget", 2); err != nil || other == nil { + t.Fatalf("archive removed another task: (%+v, %v)", other, err) + } +} + func TestClaimNextAndRecovery(t *testing.T) { s := openTest(t) ctx := context.Background() @@ -210,8 +246,8 @@ func TestClearTerminalTasks(t *testing.T) { } n, err := s.ClearTerminalTasks(ctx) - if err != nil || n != 4 { - t.Fatalf("ClearTerminalTasks = (%d, %v), want (4, nil)", n, err) + if err != nil || n != 3 { + t.Fatalf("ClearTerminalTasks = (%d, %v), want (3, nil)", n, err) } counts, err := s.StatusCounts(ctx) @@ -221,6 +257,61 @@ func TestClearTerminalTasks(t *testing.T) { if counts[store.StatusQueued] != 1 { t.Fatalf("expected 1 queued, got %d", counts[store.StatusQueued]) } + if counts[store.StatusParked] != 1 { + t.Fatalf("recoverable parked task was cleared: count = %d", counts[store.StatusParked]) + } +} + +func TestUpdateUsesTaskMutationLock(t *testing.T) { + a, ok := openTest(t).(*Adapter) + if !ok { + t.Fatal("OpenStore did not return *Adapter") + } + ctx := t.Context() + if _, err := a.EnqueueIssue(ctx, "acme", "widget", 1, "t", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := a.TaskByIssue(ctx, "acme", "widget", 1) + if err != nil || task == nil { + t.Fatalf("TaskByIssue = (%+v, %v)", task, err) + } + task.Stage = "write-tests" + + a.mu.Lock() + done := make(chan error, 1) + go func() { done <- a.Update(ctx, task) }() + select { + case err := <-done: + a.mu.Unlock() + t.Fatalf("Update bypassed task mutation lock: %v", err) + case <-time.After(25 * time.Millisecond): + } + a.mu.Unlock() + if err := <-done; err != nil { + t.Fatal(err) + } +} + +func TestRetryTaskRequeuesAndIncrementsTogether(t *testing.T) { + s := openTest(t) + ctx := t.Context() + if _, err := s.EnqueueIssue(ctx, "acme", "widget", 1, "t", "", "", ""); err != nil { + t.Fatal(err) + } + task, _ := s.ClaimNext(ctx) + if err := s.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "failed"); err != nil { + t.Fatal(err) + } + if err := s.RetryTask(ctx, task.ID, store.StatusParked, ""); err != nil { + t.Fatal(err) + } + got, err := s.TaskByID(ctx, task.ID) + if err != nil || got == nil { + t.Fatalf("TaskByID = (%+v, %v)", got, err) + } + if got.Status != store.StatusQueued || got.RetryCount != 1 { + t.Fatalf("task = status %q retry_count %d, want queued/1", got.Status, got.RetryCount) + } } func TestPersistenceAcrossRestart(t *testing.T) { diff --git a/internal/store/interface.go b/internal/store/interface.go index 51fe89990..0e36fdd6b 100644 --- a/internal/store/interface.go +++ b/internal/store/interface.go @@ -17,6 +17,8 @@ type TaskStore interface { TaskLifecycle TaskEvents TaskQueries + TaskArchiver + TaskRetryer } // TaskLifecycle manages the core task state machine and enqueuing. @@ -31,6 +33,19 @@ type TaskLifecycle interface { RecoverStale(ctx context.Context) (int64, error) } +// TaskArchiver removes one terminal task's local record with an optimistic +// status guard. It is separate from the already broad lifecycle contract so +// consumers that only run tasks do not acquire an operator-only capability. +type TaskArchiver interface { + ArchiveTask(ctx context.Context, taskID int64, fromStatus string, audit events.Event) (eventID int64, err error) +} + +// TaskRetryer atomically requeues recoverable work and accounts for the new +// attempt so a partial write cannot evade the retry cap. +type TaskRetryer interface { + RetryTask(ctx context.Context, taskID int64, fromStatus, workflow string) error +} + // TaskQueries groups read-only task accessors. type TaskQueries interface { TaskByIssue(ctx context.Context, owner, repo string, number int) (*Task, error) diff --git a/internal/store/store.go b/internal/store/store.go index bf435e146..8607f9236 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -15,6 +15,7 @@ import ( _ "modernc.org/sqlite" + "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/taskstate" ) @@ -394,6 +395,76 @@ func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, workflow return tx.Commit() } +// RetryTask requeues a task and increments retry_count in the same guarded +// transaction. A queued task with an uncounted retry would make max_retries a +// suggestion rather than a cap. +func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, workflow string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + + res, err := tx.ExecContext(ctx, ` + UPDATE tasks SET status='queued', retry_count=retry_count+1, + workflow=CASE WHEN ?='' THEN workflow ELSE ? END, + stage='', park_reason='', updated_at=datetime('now') + WHERE id=? AND status=?`, workflow, workflow, taskID, fromStatus) + if err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil { + return err + } + if n == 0 { + return ErrStaleTransition + } + if _, err := tx.ExecContext(ctx, + `INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, 'queued', ?)`, + taskID, fromStatus, "retried "+workflow); err != nil { + return err + } + return tx.Commit() +} + +// ArchiveTask removes one terminal task from the active task board. The +// expected status is part of the delete predicate so a stale browser cannot +// remove a task that has since resumed or otherwise changed state. Historical +// transition and activity rows remain as the operator audit trail. +func (s *Store) ArchiveTask( + ctx context.Context, + taskID int64, + fromStatus string, + audit events.Event, +) (int64, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return 0, err + } + defer func() { _ = tx.Rollback() }() + + eventID, err := insertEvent(ctx, tx, audit) + if err != nil { + return 0, err + } + res, err := tx.ExecContext(ctx, `DELETE FROM tasks WHERE id=? AND status=?`, taskID, fromStatus) + if err != nil { + return 0, err + } + n, err := res.RowsAffected() + if err != nil { + return 0, err + } + if n == 0 { + return 0, ErrStaleTransition + } + if err := tx.Commit(); err != nil { + return 0, err + } + return eventID, nil +} + // RecoverStale re-queues tasks left running by a crashed daemon. func (s *Store) RecoverStale(ctx context.Context) (int64, error) { res, err := s.db.ExecContext(ctx, @@ -426,11 +497,11 @@ func (s *Store) OpenPRs(ctx context.Context) (tasks []Task, retErr error) { return tasks, rows.Err() } -// ClearTerminalTasks deletes tasks whose status is terminal (merged, parked, -// rejected, closed_wont_do). Returns the number of rows removed. +// ClearTerminalTasks deletes tasks whose status is terminal. Parked work is +// deliberately excluded because it is recoverable. func (s *Store) ClearTerminalTasks(ctx context.Context) (int64, error) { res, err := s.db.ExecContext(ctx, - `DELETE FROM tasks WHERE status IN ('merged','parked','rejected','closed_wont_do')`) + `DELETE FROM tasks WHERE status IN ('merged','rejected','dead','closed_wont_do')`) if err != nil { return 0, err } diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 7751688f3..76c243c9f 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -2,6 +2,7 @@ package store import ( "context" + "errors" "path/filepath" "testing" "unicode/utf8" @@ -82,8 +83,8 @@ func TestClearTerminalTasks(t *testing.T) { } n, err := s.ClearTerminalTasks(ctx) - if err != nil || n != 4 { - t.Fatalf("ClearTerminalTasks = (%d, %v), want (4, nil)", n, err) + if err != nil || n != 3 { + t.Fatalf("ClearTerminalTasks = (%d, %v), want (3, nil)", n, err) } counts, err := s.StatusCounts(ctx) @@ -93,7 +94,10 @@ func TestClearTerminalTasks(t *testing.T) { if counts[StatusQueued] != 1 { t.Fatalf("expected 1 queued, got %d", counts[StatusQueued]) } - for _, status := range []string{StatusMerged, StatusParked, StatusRejected, StatusClosedWontDo} { + if counts[StatusParked] != 1 { + t.Fatalf("recoverable parked task was cleared: count = %d", counts[StatusParked]) + } + for _, status := range []string{StatusMerged, StatusRejected, StatusClosedWontDo} { if counts[status] != 0 { t.Fatalf("expected 0 for %s, got %d", status, counts[status]) } @@ -106,6 +110,71 @@ func TestClearTerminalTasks(t *testing.T) { } } +func TestArchiveTaskIsGuardedAndScoped(t *testing.T) { + s := openTest(t) + ctx := context.Background() + for number := 1; number <= 2; number++ { + if _, err := s.EnqueueIssue(ctx, "acme", "widget", number, "t", "b", "", ""); err != nil { + t.Fatal(err) + } + } + task, err := s.TaskByIssue(ctx, "acme", "widget", 1) + if err != nil || task == nil { + t.Fatalf("TaskByIssue = (%+v, %v)", task, err) + } + if err := s.Transition(ctx, task.ID, StatusQueued, StatusMerged, "done"); err != nil { + t.Fatal(err) + } + + audit := events.Event{Kind: events.KindTaskArchiveRequested, TaskID: task.ID} + if _, err := s.ArchiveTask(ctx, task.ID, StatusQueued, audit); !errors.Is(err, ErrStaleTransition) { + t.Fatalf("ArchiveTask stale guard = %v, want ErrStaleTransition", err) + } + if got, err := s.TaskByID(ctx, task.ID); err != nil || got == nil { + t.Fatalf("stale archive removed task: (%+v, %v)", got, err) + } + eventID, err := s.ArchiveTask(ctx, task.ID, StatusMerged, audit) + if err != nil { + t.Fatalf("ArchiveTask = %v", err) + } + if eventID == 0 { + t.Fatal("ArchiveTask returned no durable event ID") + } + if got, err := s.TaskByID(ctx, task.ID); err != nil || got != nil { + t.Fatalf("archived task = (%+v, %v), want nil", got, err) + } + if other, err := s.TaskByIssue(ctx, "acme", "widget", 2); err != nil || other == nil { + t.Fatalf("archive removed another task: (%+v, %v)", other, err) + } +} + +func TestArchiveAuditFailurePreservesTask(t *testing.T) { + s := openTest(t) + ctx := t.Context() + if _, err := s.EnqueueIssue(ctx, "acme", "widget", 1, "t", "", "", ""); err != nil { + t.Fatal(err) + } + task, _ := s.TaskByIssue(ctx, "acme", "widget", 1) + if err := s.Transition(ctx, task.ID, StatusQueued, StatusMerged, "done"); err != nil { + t.Fatal(err) + } + if _, err := s.db.ExecContext(ctx, ` + CREATE TRIGGER fail_archive_audit BEFORE INSERT ON events + WHEN NEW.kind = 'task_archive_requested' + BEGIN SELECT RAISE(FAIL, 'audit failed'); END`); err != nil { + t.Fatal(err) + } + + if _, err := s.ArchiveTask(ctx, task.ID, StatusMerged, events.Event{ + Kind: events.KindTaskArchiveRequested, TaskID: task.ID, + }); err == nil { + t.Fatal("ArchiveTask succeeded despite forced audit failure") + } + if got, err := s.TaskByID(ctx, task.ID); err != nil || got == nil { + t.Fatalf("audit failure deleted task: (%+v, %v)", got, err) + } +} + func TestEnqueueIsIdempotent(t *testing.T) { s := openTest(t) ctx := context.Background() @@ -288,6 +357,63 @@ func TestIncrementRetryCount(t *testing.T) { } } +func TestRetryTaskAtomicallyRequeuesAndIncrements(t *testing.T) { + s := openTest(t) + ctx := t.Context() + if _, err := s.EnqueueIssue(ctx, "acme", "todo", 1, "t", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := s.ClaimNext(ctx) + if err != nil || task == nil { + t.Fatalf("ClaimNext = (%+v, %v)", task, err) + } + if err := s.Transition(ctx, task.ID, StatusRunning, StatusParked, "failed"); err != nil { + t.Fatal(err) + } + + if err := s.RetryTask(ctx, task.ID, StatusParked, ""); err != nil { + t.Fatal(err) + } + got, err := s.TaskByID(ctx, task.ID) + if err != nil || got == nil { + t.Fatalf("TaskByID = (%+v, %v)", got, err) + } + if got.Status != StatusQueued || got.RetryCount != 1 { + t.Fatalf("task = status %q retry_count %d, want queued/1", got.Status, got.RetryCount) + } + if err := s.RetryTask(ctx, task.ID, StatusParked, ""); !errors.Is(err, ErrStaleTransition) { + t.Fatalf("stale RetryTask error = %v, want ErrStaleTransition", err) + } +} + +func TestRetryTaskWriteFailureLeavesParkedCountUnchanged(t *testing.T) { + s := openTest(t) + ctx := t.Context() + if _, err := s.EnqueueIssue(ctx, "acme", "todo", 1, "t", "", "", ""); err != nil { + t.Fatal(err) + } + task, _ := s.ClaimNext(ctx) + if err := s.Transition(ctx, task.ID, StatusRunning, StatusParked, "failed"); err != nil { + t.Fatal(err) + } + if _, err := s.db.ExecContext(ctx, ` + CREATE TRIGGER fail_retry BEFORE UPDATE OF retry_count ON tasks + BEGIN SELECT RAISE(FAIL, 'retry failed'); END`); err != nil { + t.Fatal(err) + } + + if err := s.RetryTask(ctx, task.ID, StatusParked, ""); err == nil { + t.Fatal("RetryTask succeeded despite forced write failure") + } + got, err := s.TaskByID(ctx, task.ID) + if err != nil || got == nil { + t.Fatalf("TaskByID = (%+v, %v)", got, err) + } + if got.Status != StatusParked || got.RetryCount != 0 { + t.Fatalf("partial retry write: status %q retry_count %d", got.Status, got.RetryCount) + } +} + func TestRetryCountColumn(t *testing.T) { s := openTest(t) ctx := context.Background() diff --git a/internal/taskstate/taskstate.go b/internal/taskstate/taskstate.go index 73db39a4a..bc1cdc501 100644 --- a/internal/taskstate/taskstate.go +++ b/internal/taskstate/taskstate.go @@ -15,7 +15,28 @@ // has no dependencies, so both can import it and the copy can go. package taskstate -import "fmt" +import ( + "fmt" + "slices" +) + +// Action is an operator control whose availability is determined solely by a +// task's persisted lifecycle state. The Web API returns these values with each +// task so every presentation surface derives from this table instead of +// keeping its own copy. +type Action string + +const ( + ActionCancel Action = "cancel" + ActionStop Action = "stop" + ActionApprove Action = "approve" + ActionReject Action = "reject" + ActionRetry Action = "retry" + ActionAbandon Action = "abandon" + ActionOpenPR Action = "open_pr" + ActionOpenIssue Action = "open_issue" + ActionArchive Action = "archive" +) // Task lifecycle statuses. The store persists these strings, so they are // part of the on-disk format: renaming one is a migration, not a rename. @@ -49,6 +70,35 @@ func Terminal(status string) bool { } } +// Actions returns the ordered controls valid for status. Callers receive a +// fresh slice so presentation code cannot mutate the lifecycle table. +func Actions(status string) []Action { + var actions []Action + switch status { + case Queued: + actions = []Action{ActionCancel} + case Running: + actions = []Action{ActionStop} + case WaitingHuman: + actions = []Action{ActionApprove, ActionReject} + case Parked: + actions = []Action{ActionRetry, ActionAbandon} + case PROpen: + actions = []Action{ActionOpenPR, ActionOpenIssue} + case Merged, Rejected, Dead, Declined: + actions = []Action{ActionArchive} + } + return actions +} + +// CheckAction rejects stale, illegal and unknown operator controls. +func CheckAction(status string, action Action) error { + if slices.Contains(Actions(status), action) { + return nil + } + return fmt.Errorf("action %q is not available while task is %s", action, status) +} + // CheckApprove reports whether a task in this status can be approved. // // Approval releases work that is waiting on a human decision, so it is only @@ -75,20 +125,16 @@ func CheckRetry(status string) error { // CheckDecline reports whether a task in this status can be declined. // -// Work that is still progressing can be declined -- including a running task, -// which is the case most worth being able to stop. Callers that can interrupt -// running work should do so before recording the state, or the task may write -// its own outcome afterwards and win. -// -// Parked is refused along with the terminal states. A parked task is not -// progressing, so there is nothing to stop; it is retried, or left. Both the -// dashboard and chat already behaved this way and this package preserves it -// rather than widening the rule while unifying it. If declining a parked task -// is ever wanted, change it here and both paths get it at once -- which is -// the point. +// The legacy chat command expresses cancel, stop, reject and abandon as one +// operation. It remains available only where the canonical action table +// exposes one of those controls; unknown, PR-open and terminal states fail +// closed instead of permitting an arbitrary transition. func CheckDecline(status string) error { - if Terminal(status) || status == Parked { - return fmt.Errorf("task is already %s", status) + for _, action := range Actions(status) { + switch action { + case ActionCancel, ActionStop, ActionReject, ActionAbandon: + return nil + } } - return nil + return fmt.Errorf("task cannot be declined while %s", status) } diff --git a/internal/taskstate/taskstate_test.go b/internal/taskstate/taskstate_test.go index b5c5ce7b4..256739f64 100644 --- a/internal/taskstate/taskstate_test.go +++ b/internal/taskstate/taskstate_test.go @@ -1,6 +1,9 @@ package taskstate -import "testing" +import ( + "slices" + "testing" +) // The rules must be the same wherever an operator acts. These cases are the // contract both the dashboard and chat are held to; a divergence between them @@ -10,16 +13,17 @@ func TestActionRules(t *testing.T) { status string approve, retry, decline bool terminal bool + actions []Action }{ - {status: Queued, decline: true}, - {status: Running, decline: true}, - {status: WaitingHuman, approve: true, decline: true}, - {status: PROpen, decline: true}, - {status: Parked, retry: true}, - {status: Merged, terminal: true}, - {status: Rejected, terminal: true}, - {status: Dead, terminal: true}, - {status: Declined, terminal: true}, + {status: Queued, decline: true, actions: []Action{ActionCancel}}, + {status: Running, decline: true, actions: []Action{ActionStop}}, + {status: WaitingHuman, approve: true, decline: true, actions: []Action{ActionApprove, ActionReject}}, + {status: PROpen, actions: []Action{ActionOpenPR, ActionOpenIssue}}, + {status: Parked, retry: true, decline: true, actions: []Action{ActionRetry, ActionAbandon}}, + {status: Merged, terminal: true, actions: []Action{ActionArchive}}, + {status: Rejected, terminal: true, actions: []Action{ActionArchive}}, + {status: Dead, terminal: true, actions: []Action{ActionArchive}}, + {status: Declined, terminal: true, actions: []Action{ActionArchive}}, } for _, tc := range tests { @@ -36,6 +40,14 @@ func TestActionRules(t *testing.T) { if got := Terminal(tc.status); got != tc.terminal { t.Errorf("Terminal = %v, want %v", got, tc.terminal) } + if got := Actions(tc.status); !slices.Equal(got, tc.actions) { + t.Errorf("Actions = %v, want %v", got, tc.actions) + } + for _, action := range tc.actions { + if err := CheckAction(tc.status, action); err != nil { + t.Errorf("CheckAction(%q) = %v", action, err) + } + } }) } } @@ -50,10 +62,8 @@ func TestUnknownStatusIsNotApprovable(t *testing.T) { if err := CheckRetry(unknown); err == nil { t.Error("CheckRetry allowed an unknown status") } - // Declining is deliberately permissive: refusing work archie does not - // recognise is safer than being unable to stop it. - if err := CheckDecline(unknown); err != nil { - t.Errorf("CheckDecline refused an unknown status: %v", err) + if err := CheckDecline(unknown); err == nil { + t.Error("CheckDecline allowed an unknown status") } } @@ -68,3 +78,11 @@ func TestRejectedAndDeclinedAreDistinct(t *testing.T) { t.Error("both must be terminal") } } + +func TestActionsReturnsIndependentSlices(t *testing.T) { + first := Actions(WaitingHuman) + first[0] = ActionArchive + if got := Actions(WaitingHuman); !slices.Equal(got, []Action{ActionApprove, ActionReject}) { + t.Fatalf("mutating returned actions changed lifecycle table: %v", got) + } +} diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 9d4aa5ce8..af2299935 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -3,9 +3,14 @@ package webui import ( "context" "encoding/json" + "errors" "fmt" + "io" + "mime" "net/http" + "net/url" "strconv" + "strings" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/store" @@ -46,16 +51,16 @@ func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - writeJSON(w, tasks) + views := make([]taskView, len(tasks)) + for i := range tasks { + views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status)} + } + writeJSON(w, views) } -func (s *Server) handleClearTasks(w http.ResponseWriter, r *http.Request) { - deleted, err := s.Store.ClearTerminalTasks(r.Context()) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - writeJSON(w, map[string]any{"deleted": deleted}) +type taskView struct { + store.Task + Actions []taskstate.Action `json:"actions"` } func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) { @@ -77,81 +82,223 @@ type taskActionRequest struct { } func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { + if !authorizeTaskMutation(w, r) { + return + } id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.Error(w, "bad id", http.StatusBadRequest) return } - var req taskActionRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, "invalid action", http.StatusBadRequest) + action, ok := decodeTaskAction(w, r) + if !ok { return } task, err := s.Store.TaskByID(r.Context(), id) if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + s.logf("task action lookup failed", "task", id, "err", err) + http.Error(w, "task action failed", http.StatusInternalServerError) return } if task == nil { http.Error(w, "task not found", http.StatusNotFound) return } + if err := taskstate.CheckAction(task.Status, action); err != nil { + http.Error(w, err.Error(), http.StatusConflict) + return + } // Each action reports the event to record, or writes its own error // response and returns nothing. Keeping the dispatch flat here and the // rules in one function each is what stops this growing back into a // single branch nobody can read. - ctx := r.Context() - var outcome *actionOutcome - switch req.Action { - case "approve": - outcome = s.approveTask(ctx, w, task) - case "retry": - outcome = s.retryTask(ctx, w, task) - case "reject": - outcome = s.rejectTask(ctx, w, task) - default: - http.Error(w, "unknown action", http.StatusBadRequest) - return - } + outcome := s.applyTaskAction(r.Context(), w, task, action) if outcome == nil { return } - s.emit(events.Event{ + s.emit(r.Context(), events.Event{ + ID: outcome.eventID, Kind: outcome.kind, TaskID: task.ID, Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Detail: outcome.detail, }) - writeJSON(w, map[string]any{"ok": true, "action": req.Action, "task_id": id}) + writeJSON(w, map[string]any{"ok": true, "action": action, "task_id": id}) +} + +func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action, bool) { + r.Body = http.MaxBytesReader(w, r.Body, 4096) + var req taskActionRequest + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&req); err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + http.Error(w, "action body too large", http.StatusRequestEntityTooLarge) + return "", false + } + http.Error(w, "invalid action", http.StatusBadRequest) + return "", false + } + if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + http.Error(w, "invalid action", http.StatusBadRequest) + return "", false + } + action := taskstate.Action(req.Action) + if !taskMutation(action) { + http.Error(w, "unknown action", http.StatusBadRequest) + return "", false + } + return action, true +} + +func (s *Server) applyTaskAction( + ctx context.Context, + w http.ResponseWriter, + task *store.Task, + action taskstate.Action, +) *actionOutcome { + switch action { + case taskstate.ActionCancel: + return s.declineTask(ctx, w, task, store.StatusQueued, events.KindTaskCancelled, "cancelled") + case taskstate.ActionStop: + return s.stopTask(ctx, w, task) + case taskstate.ActionApprove: + return s.approveTask(ctx, w, task) + case taskstate.ActionRetry: + return s.retryTask(ctx, w, task) + case taskstate.ActionReject: + return s.rejectTask(ctx, w, task) + case taskstate.ActionAbandon: + return s.declineTask(ctx, w, task, store.StatusParked, events.KindTaskAbandoned, "abandoned") + case taskstate.ActionArchive: + return s.archiveTask(ctx, w, task) + default: + return nil + } +} + +func taskMutation(action taskstate.Action) bool { + switch action { + case taskstate.ActionCancel, taskstate.ActionStop, taskstate.ActionApprove, + taskstate.ActionReject, taskstate.ActionRetry, taskstate.ActionAbandon, + taskstate.ActionArchive: + return true + default: + return false + } +} + +// authorizeTaskMutation applies the browser mutation contract at the handler +// boundary: JSON only, a non-simple custom header, and a matching Origin when +// the browser supplies one. The custom header forces cross-origin callers +// through a CORS preflight, which this server never permits. +func authorizeTaskMutation(w http.ResponseWriter, r *http.Request) bool { + if r.Header.Get("X-Archie-CSRF") != "1" { + http.Error(w, "missing CSRF header", http.StatusForbidden) + return false + } + mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || mediaType != "application/json" { + http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType) + return false + } + origin := r.Header.Get("Origin") + if origin == "" { + return true + } + u, err := url.Parse(origin) + wantScheme := "http" + if r.TLS != nil { + wantScheme = "https" + } + if err != nil || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || + !strings.EqualFold(u.Scheme, wantScheme) || !strings.EqualFold(u.Host, r.Host) { + http.Error(w, "cross-origin mutation refused", http.StatusForbidden) + return false + } + return true } // actionOutcome is what a completed operator action should record. type actionOutcome struct { - kind string - detail string + kind string + detail string + eventID int64 } // storeFailed writes the response for a failed store write and reports // whether it did. A store write that fails is not the caller's fault; // answering 409 made the UI say "conflict" for a broken database. -func storeFailed(w http.ResponseWriter, err error) bool { +func (s *Server) storeFailed(w http.ResponseWriter, err error) bool { if err == nil { return false } - http.Error(w, err.Error(), http.StatusInternalServerError) + if errors.Is(err, store.ErrStaleTransition) { + http.Error(w, "task changed state; refresh and try again", http.StatusConflict) + return true + } + s.logf("task action store write failed", "err", err) + http.Error(w, "task action failed", http.StatusInternalServerError) return true } +func (s *Server) declineTask( + ctx context.Context, + w http.ResponseWriter, + task *store.Task, + from, kind, verb string, +) *actionOutcome { + detail := verb + " via the dashboard" + if s.storeFailed(w, s.Store.Transition(ctx, task.ID, from, store.StatusClosedWontDo, detail)) { + return nil + } + s.closeDeclinedIssue(ctx, task, verb) + return &actionOutcome{kind: kind, detail: detail} +} + +func (s *Server) stopTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome { + if s.TaskStopper == nil { + http.Error(w, "runtime task control is unavailable", http.StatusServiceUnavailable) + return nil + } + cancelled := s.TaskStopper.CancelTask(task.ID) + detail := "stopped via the dashboard; recoverable work remains parked" + if !cancelled { + // A running row without a runtime entry is stale work from a crashed or + // migrated process. Nothing is executing, but parking the guarded row + // still gives the operator the promised recoverable state. + detail = "no active execution was found; recoverable work was parked via the dashboard" + } + if s.storeFailed(w, s.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, detail)) { + return nil + } + return &actionOutcome{kind: events.KindTaskStopped, detail: detail} +} + +func (s *Server) archiveTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome { + detail := "archive requested via the dashboard" + eventID, err := s.Store.ArchiveTask(ctx, task.ID, task.Status, events.Event{ + Kind: events.KindTaskArchiveRequested, TaskID: task.ID, + Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, + Detail: detail, + }) + if s.storeFailed(w, err) { + return nil + } + return &actionOutcome{kind: events.KindTaskArchiveRequested, detail: detail, eventID: eventID} +} + func (s *Server) approveTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome { if err := taskstate.CheckApprove(task.Status); err != nil { http.Error(w, err.Error(), http.StatusConflict) return nil } - if storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusWaitingHuman, "implement")) { + if s.storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusWaitingHuman, "implement")) { return nil } - return &actionOutcome{events.KindHumanApproved, "approved via the dashboard"} + return &actionOutcome{kind: events.KindHumanApproved, detail: "approved via the dashboard"} } // retryTask requeues a parked task, or retires it once max_retries is spent. @@ -170,13 +317,10 @@ func (s *Server) retryTask(ctx context.Context, w http.ResponseWriter, task *sto http.Error(w, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit), http.StatusConflict) return nil } - if storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusParked, "")) { + if s.storeFailed(w, s.Store.RetryTask(ctx, task.ID, store.StatusParked, "")) { return nil } - if storeFailed(w, s.Store.IncrementRetryCount(ctx, task.ID)) { - return nil - } - return &actionOutcome{events.KindTaskRetried, "retried via the dashboard"} + return &actionOutcome{kind: events.KindTaskRetried, detail: "retried via the dashboard"} } // retireTask moves a spent task to dead. Failure is logged, not returned: @@ -186,7 +330,7 @@ func (s *Server) retireTask(ctx context.Context, task *store.Task, reason string s.logf("transition to dead failed", "task", task.ID, "err", err) return } - s.emit(events.Event{ + s.emit(ctx, events.Event{ Kind: events.KindTaskDead, TaskID: task.ID, Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Detail: reason, }) @@ -200,11 +344,11 @@ func (s *Server) rejectTask(ctx context.Context, w http.ResponseWriter, task *st return nil } err := s.Store.Transition(ctx, task.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, "declined from the dashboard") - if storeFailed(w, err) { + if s.storeFailed(w, err) { return nil } - s.closeRejectedIssue(ctx, task) - return &actionOutcome{events.KindHumanRejected, "rejected via the dashboard"} + s.closeDeclinedIssue(ctx, task, "rejected") + return &actionOutcome{kind: events.KindHumanRejected, detail: "rejected via the dashboard"} } // maxRetriesFor resolves the retry cap for a task, honouring a per-repo @@ -232,7 +376,7 @@ func (s *Server) maxRetriesFor(task *store.Task) int { // // Failure is logged, not returned. The operator's decision is already // recorded, and reporting an error would invite them to click again. -func (s *Server) closeRejectedIssue(ctx context.Context, task *store.Task) { +func (s *Server) closeDeclinedIssue(ctx context.Context, task *store.Task, verb string) { if s.Issues == nil { s.logf("task rejected but no forge is wired; the issue stays open and will be re-polled", "task", task.ID, "issue", task.IssueNumber) @@ -242,8 +386,8 @@ func (s *Server) closeRejectedIssue(ctx context.Context, task *store.Task) { if !task.IsForgeBacked() { return } - const comment = "Closing: this was rejected from the archie dashboard. " + - "Reopen the issue to have archie pick it up again." + comment := fmt.Sprintf("Closing: this task was %s from the archie dashboard. "+ + "Reopen the issue to have archie pick it up again.", verb) if err := s.Issues.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil { s.logf("closing rejected issue failed; it stays open and will be re-polled", "task", task.ID, "issue", task.IssueNumber, "err", err) @@ -253,11 +397,21 @@ func (s *Server) closeRejectedIssue(ctx context.Context, task *store.Task) { // emit publishes an operator action so it reaches the task timeline and the // live activity stream. A nil publisher is not an error: the action is still // recorded in the store. -func (s *Server) emit(e events.Event) { - if s.Events == nil || e.Kind == "" { +func (s *Server) emit(ctx context.Context, e events.Event) { + if e.Kind == "" { return } - s.Events.Publish(e) + if e.ID == 0 { + id, err := s.Store.InsertEvent(ctx, e) + if err != nil { + s.logf("operator activity persistence failed", "kind", e.Kind, "task", e.TaskID, "err", err) + } else { + e.ID = id + } + } + if s.Events != nil { + s.Events.Publish(e) + } } func (s *Server) logf(msg string, args ...any) { diff --git a/internal/webui/api_tasks_actions_test.go b/internal/webui/api_tasks_actions_test.go index e18c7ad1a..c6c4e2ff6 100644 --- a/internal/webui/api_tasks_actions_test.go +++ b/internal/webui/api_tasks_actions_test.go @@ -3,11 +3,14 @@ package webui import ( "bytes" "context" + "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" + "slices" "strconv" + "strings" "testing" "github.com/samcharles93/archie-core/internal/config" @@ -67,11 +70,41 @@ func postAction(t *testing.T, srv *Server, id int64, action string) *httptest.Re "/api/tasks/"+strconv.FormatInt(id, 10)+"/action", bytes.NewBufferString(fmt.Sprintf(`{"action":%q}`, action))) req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Archie-CSRF", "1") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) return w } +type recordingTaskStopper struct { + calls []int64 + result bool +} + +type archiveFailingStore struct { + store.TaskStore + err error +} + +func (s *archiveFailingStore) ArchiveTask( + context.Context, + int64, + string, + events.Event, +) (int64, error) { + return 0, s.err +} + +func (s *recordingTaskStopper) CancelTask(id int64) bool { + s.calls = append(s.calls, id) + return s.result +} + +func setTaskStopper(t *testing.T, srv *Server, stopper *recordingTaskStopper) { + t.Helper() + srv.TaskStopper = stopper +} + // max_retries is configured, defaulted and shown in /api/config, but nothing // enforced it: the Web UI retry incremented retry_count with no cap, so a // task that fails every time could be retried forever. At the cap the task @@ -258,6 +291,7 @@ func TestTaskActionErrorMapping(t *testing.T) { setup func(t *testing.T, srv *Server, id int64) id func(id int64) string wantStatus int + wantHidden string }{ { name: "unknown action", @@ -281,6 +315,15 @@ func TestTaskActionErrorMapping(t *testing.T) { id: func(int64) string { return "424242" }, wantStatus: http.StatusNotFound, }, + { + name: "store lookup failure is redacted", + body: `{"action":"approve"}`, + setup: func(_ *testing.T, srv *Server, _ int64) { + srv.Store = &stubStore{TaskStore: srv.Store, taskByIDErr: errors.New("database password leaked")} + }, + wantStatus: http.StatusInternalServerError, + wantHidden: "password", + }, { name: "wrong state", body: `{"action":"retry"}`, @@ -302,12 +345,17 @@ func TestTaskActionErrorMapping(t *testing.T) { req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/tasks/"+path+"/action", bytes.NewBufferString(tc.body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Archie-CSRF", "1") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != tc.wantStatus { t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.wantStatus, w.Body) } + if tc.wantHidden != "" && strings.Contains(w.Body.String(), tc.wantHidden) { + t.Fatalf("response exposed internal error: %s", w.Body) + } }) } } @@ -337,3 +385,232 @@ func TestTaskActionStoreFailureIs500(t *testing.T) { t.Fatalf("status = %d, want 500: a store failure is not a conflict", w.Code) } } + +func TestTaskListExposesLifecycleActions(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + want := map[string][]string{ + store.StatusQueued: {"cancel"}, + store.StatusRunning: {"stop"}, + store.StatusWaitingHuman: {"approve", "reject"}, + store.StatusParked: {"retry", "abandon"}, + store.StatusPROpen: {"open_pr", "open_issue"}, + store.StatusMerged: {"archive"}, + store.StatusRejected: {"archive"}, + store.StatusDead: {"archive"}, + store.StatusClosedWontDo: {"archive"}, + } + + number := 1 + for status := range want { + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", number, status, "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", number) + if err != nil || task == nil { + t.Fatalf("TaskByIssue(%s) = (%+v, %v)", status, task, err) + } + if status != store.StatusQueued { + if err := srv.Store.Transition(ctx, task.ID, store.StatusQueued, status, "test"); err != nil { + t.Fatal(err) + } + } + number++ + } + + req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + var got []struct { + Status string `json:"status"` + Actions []string `json:"actions"` + } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + for _, task := range got { + if !slices.Equal(task.Actions, want[task.Status]) { + t.Errorf("actions for %s = %v, want %v", task.Status, task.Actions, want[task.Status]) + } + } +} + +func TestLifecycleSpecificTaskActions(t *testing.T) { + tests := []struct { + name, from, action, want string + stopperResult bool + closesIssue bool + }{ + {name: "cancel queued", from: store.StatusQueued, action: "cancel", want: store.StatusClosedWontDo, closesIssue: true}, + {name: "stop running", from: store.StatusRunning, action: "stop", want: store.StatusParked, stopperResult: true}, + {name: "park stale running row", from: store.StatusRunning, action: "stop", want: store.StatusParked}, + {name: "abandon parked", from: store.StatusParked, action: "abandon", want: store.StatusClosedWontDo, closesIssue: true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 11, "a task", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 11) + if err != nil || task == nil { + t.Fatalf("TaskByIssue = (%+v, %v)", task, err) + } + if tc.from != store.StatusQueued { + if err := srv.Store.Transition(ctx, task.ID, store.StatusQueued, tc.from, "test"); err != nil { + t.Fatal(err) + } + } + closer := &recordingCloser{} + srv.Issues = closer + bus := events.NewBus() + t.Cleanup(bus.Close) + srv.Events = bus + sub := bus.Subscribe(1) + if tc.action == "stop" { + setTaskStopper(t, srv, &recordingTaskStopper{result: tc.stopperResult}) + } + if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + got, err := srv.Store.TaskByID(ctx, task.ID) + if err != nil || got == nil || got.Status != tc.want { + t.Fatalf("task = (%+v, %v), want status %s", got, err, tc.want) + } + if got := len(closer.calls) > 0; got != tc.closesIssue { + t.Errorf("forge issue closed = %v, want %v", got, tc.closesIssue) + } + select { + case event := <-sub.C: + if event.TaskID != task.ID || event.Kind == "" { + t.Errorf("event = %+v", event) + } + default: + t.Error("operator action emitted no activity event") + } + }) + } +} + +func TestArchiveRemovesOnlyOneTerminalTask(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + for number := 1; number <= 2; number++ { + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", number, "done", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", number) + if err != nil || task == nil { + t.Fatalf("TaskByIssue = (%+v, %v)", task, err) + } + if err := srv.Store.Transition(ctx, task.ID, store.StatusQueued, store.StatusMerged, "done"); err != nil { + t.Fatal(err) + } + } + task, _ := srv.Store.TaskByIssue(ctx, "acme", "widget", 1) + bus := events.NewBus() + t.Cleanup(bus.Close) + srv.Events = bus + sub := bus.Subscribe(1) + if w := postAction(t, srv, task.ID, "archive"); w.Code != http.StatusOK { + t.Fatalf("archive status = %d, body %s", w.Code, w.Body) + } + if got, err := srv.Store.TaskByID(ctx, task.ID); err != nil || got != nil { + t.Fatalf("archived task = (%+v, %v), want nil", got, err) + } + if other, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 2); err != nil || other == nil { + t.Fatalf("archive removed another task: (%+v, %v)", other, err) + } + history, err := srv.Store.EventsSince(ctx, 0, 10) + if err != nil { + t.Fatal(err) + } + if len(history) != 1 || history[0].Kind != events.KindTaskArchiveRequested || history[0].ID == 0 { + t.Fatalf("durable archive audit = %+v", history) + } + select { + case event := <-sub.C: + if event.Kind != events.KindTaskArchiveRequested || event.TaskID != task.ID { + t.Errorf("archive event = %+v", event) + } + default: + t.Error("archive emitted no activity event") + } +} + +func TestArchiveAuditFailurePreservesTaskAndFailsRequest(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "done", "", "", ""); err != nil { + t.Fatal(err) + } + task, _ := srv.Store.TaskByIssue(ctx, "acme", "widget", 1) + if err := srv.Store.Transition(ctx, task.ID, store.StatusQueued, store.StatusMerged, "done"); err != nil { + t.Fatal(err) + } + base := srv.Store + srv.Store = &archiveFailingStore{TaskStore: base, err: errors.New("audit unavailable")} + + if w := postAction(t, srv, task.ID, "archive"); w.Code != http.StatusInternalServerError { + t.Fatalf("archive status = %d, want 500", w.Code) + } + if got, err := base.TaskByID(ctx, task.ID); err != nil || got == nil { + t.Fatalf("failed archive removed task: (%+v, %v)", got, err) + } +} + +func TestTaskActionRejectsUnsafeRequests(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "queued", "", "", ""); err != nil { + t.Fatal(err) + } + task, _ := srv.Store.TaskByIssue(ctx, "acme", "widget", 1) + path := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/action" + tests := []struct { + name, body, contentType, csrf, origin string + want int + }{ + {name: "cross origin", body: `{"action":"cancel"}`, contentType: "application/json", csrf: "1", origin: "https://evil.example", want: http.StatusForbidden}, + {name: "non JSON", body: `{"action":"cancel"}`, contentType: "text/plain", csrf: "1", want: http.StatusUnsupportedMediaType}, + {name: "oversized", body: strings.Repeat(" ", 5000) + `{"action":"cancel"}`, contentType: "application/json", csrf: "1", want: http.StatusRequestEntityTooLarge}, + {name: "unknown field", body: `{"action":"cancel","status":"queued"}`, contentType: "application/json", csrf: "1", want: http.StatusBadRequest}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + req := httptest.NewRequestWithContext(ctx, http.MethodPost, path, strings.NewReader(tc.body)) + req.Header.Set("Content-Type", tc.contentType) + req.Header.Set("X-Archie-CSRF", tc.csrf) + if tc.origin != "" { + req.Header.Set("Origin", tc.origin) + } + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + if w.Code != tc.want { + t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.want, w.Body) + } + }) + } +} + +func TestTaskActionRequiresCSRFHeader(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "queued", "", "", ""); err != nil { + t.Fatal(err) + } + task, _ := srv.Store.TaskByIssue(ctx, "acme", "widget", 1) + req := httptest.NewRequestWithContext(ctx, http.MethodPost, + "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", + bytes.NewBufferString(`{"action":"cancel"}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + if w.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403 without CSRF header (body %s)", w.Code, w.Body) + } +} diff --git a/internal/webui/api_tasks_test.go b/internal/webui/api_tasks_test.go index 04d3af5ba..f77ebb165 100644 --- a/internal/webui/api_tasks_test.go +++ b/internal/webui/api_tasks_test.go @@ -37,6 +37,7 @@ func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) { req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"approve"}`)) req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Archie-CSRF", "1") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { @@ -66,6 +67,8 @@ func TestHandleTaskActionRetriesParkedTask(t *testing.T) { } req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"retry"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Archie-CSRF", "1") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { @@ -149,15 +152,20 @@ func TestHandleTaskStoreError(t *testing.T) { } } -// TestHandleClearTasksProvenance proves the literal /api/tasks/clear route is -// not captured by the {id} wildcard (which would 400 on "clear"). -func TestHandleClearTasksProvenance(t *testing.T) { +func TestBulkClearRouteCannotMutateTasks(t *testing.T) { srv := newTestServer(t) + if _, err := srv.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/clear", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200 — /api/tasks/clear was captured by {id}", w.Code) + if w.Code == http.StatusOK { + t.Fatal("GET /api/tasks/clear still exposes a destructive mutation") + } + tasks, err := srv.Store.Tasks(t.Context(), 10) + if err != nil || len(tasks) != 1 { + t.Fatalf("tasks after legacy clear request = (%d, %v), want one preserved", len(tasks), err) } } diff --git a/ui/src/css/layout.css b/ui/src/css/layout.css index e3f8cf52b..87d9b50df 100644 --- a/ui/src/css/layout.css +++ b/ui/src/css/layout.css @@ -67,7 +67,8 @@ body { font-weight: 700; } -/* Compact icon navigation: one pill, icons only, label on the active item. */ +/* Navigation is always labelled. Operators should never have to memorise an + icon vocabulary just to move around the control plane. */ .nav { display: flex; align-items: center; @@ -101,14 +102,9 @@ body { background: var(--accent); color: var(--accent-fg); font-weight: 500; - padding-right: var(--sp-4); } .nav-item .nav-label { - display: none; -} - -.nav-item[aria-current="page"] .nav-label { display: inline; } @@ -146,6 +142,10 @@ body { color: var(--fg-subtle); } +.mobile-search-toggle { + display: none; +} + .icon-btn { display: grid; place-items: center; @@ -192,6 +192,23 @@ body { overflow-x: hidden; } +/* ── Constrained desktop ────────────────────────────────────────────────── */ + +@media (max-width: 1220px) and (min-width: 901px) { + .topbar { + flex-wrap: wrap; + } + + .nav { + order: 3; + width: 100%; + margin: 0; + justify-content: center; + flex-wrap: wrap; + border-radius: var(--radius-lg); + } +} + /* ── Narrow screens ─────────────────────────────────────────────────────── */ /* The frame is a desktop affordance. Below the breakpoint the workspace goes @@ -220,6 +237,7 @@ body { width: 100%; overflow-x: auto; justify-content: flex-start; + flex-wrap: nowrap; border-radius: var(--radius-lg); scrollbar-width: none; } @@ -232,9 +250,43 @@ body { display: inline; } - .topbar-search { - display: none; - } + + .topbar-search { + padding: 0; + border: 0; + background: transparent; + overflow: hidden; + } + + .topbar-search-icon { + display: none; + } + + .mobile-search-toggle { + display: grid; + } + + .topbar-search input { + width: 0; + padding: 0; + opacity: 0; + pointer-events: none; + transition: width var(--transition), opacity var(--transition); + } + + .topbar-search.is-open, + .topbar-search:focus-within { + padding-right: var(--sp-2); + border: 1px solid var(--hairline); + background: var(--surface-glass-strong); + } + + .topbar-search.is-open input, + .topbar-search:focus-within input { + width: min(9rem, 34vw); + opacity: 1; + pointer-events: auto; + } .main { padding: var(--sp-4); diff --git a/ui/src/dashboard/setup-preference.js b/ui/src/dashboard/setup-preference.js new file mode 100644 index 000000000..4ba13a9c6 --- /dev/null +++ b/ui/src/dashboard/setup-preference.js @@ -0,0 +1,21 @@ +export const SETUP_DISMISSAL_KEY = "archie.setup-complete.dismissed.v1"; + +// setupPanelState reconciles persisted presentation state with current setup +// truth. If setup later becomes incomplete, an old dismissal is cleared so +// the operator cannot miss the new work. +export function setupPanelState(setup, storage = globalThis.localStorage) { + if (!setup?.steps?.length) return { kind: "omit", remaining: [] }; + const remaining = setup.steps.filter((step) => !step.done); + if (remaining.length) { + storage?.removeItem?.(SETUP_DISMISSAL_KEY); + return { kind: "incomplete", remaining }; + } + if (storage?.getItem?.(SETUP_DISMISSAL_KEY) === "1") { + return { kind: "dismissed", remaining: [] }; + } + return { kind: "complete", remaining: [] }; +} + +export function dismissSetupComplete(storage = globalThis.localStorage) { + storage?.setItem?.(SETUP_DISMISSAL_KEY, "1"); +} diff --git a/ui/src/dashboard/task-targets.js b/ui/src/dashboard/task-targets.js new file mode 100644 index 000000000..8d027dded --- /dev/null +++ b/ui/src/dashboard/task-targets.js @@ -0,0 +1,21 @@ +const ATTENTION_STATUSES = new Set(["waiting_human", "parked"]); + +// Dashboard task links are derived from the actual task list, not just count +// aggregates, so a single item can open directly while a group opens a useful +// filtered board. +export function dashboardTaskTargets(tasks = []) { + const attention = tasks.filter((task) => ATTENTION_STATUSES.has(task.status)); + const running = tasks.filter((task) => task.status === "running"); + return { + attention: { + count: attention.length, + href: attention.length === 1 + ? `#/tasks?task=${encodeURIComponent(attention[0].id)}` + : "#/tasks?status=needs_you", + }, + running: { + count: running.length, + href: "#/tasks?status=running", + }, + }; +} diff --git a/ui/src/tasks/task-filters.js b/ui/src/tasks/task-filters.js new file mode 100644 index 000000000..574cef5a1 --- /dev/null +++ b/ui/src/tasks/task-filters.js @@ -0,0 +1,24 @@ +const ATTENTION_STATUSES = new Set(["waiting_human", "parked"]); +const TASK_STATUSES = new Set([ + "needs_you", + "queued", + "running", + "waiting_human", + "pr_open", + "merged", + "parked", + "dead", + "rejected", + "closed_wont_do", +]); + +export function initialTaskFilter(params) { + const requested = params?.get?.("status") || ""; + return TASK_STATUSES.has(requested) ? requested : ""; +} + +export function taskMatchesStatus(task, status) { + if (!status) return true; + if (status === "needs_you") return ATTENTION_STATUSES.has(task.status); + return task.status === status; +} diff --git a/ui/src/tasks/tasks.css b/ui/src/tasks/tasks.css index 5e40a17c5..b871b9c97 100644 --- a/ui/src/tasks/tasks.css +++ b/ui/src/tasks/tasks.css @@ -83,6 +83,7 @@ display: flex; gap: var(--sp-1); white-space: nowrap; + flex-wrap: wrap; } .btn-small { @@ -108,6 +109,16 @@ background: var(--surface); } +.task-detail-actions { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--sp-3); + margin-bottom: var(--sp-4); + padding-bottom: var(--sp-3); + border-bottom: 1px solid var(--hairline); +} + .task-decision-title { color: var(--fg); font-weight: 600; @@ -133,6 +144,92 @@ .task-filter { flex: 1 1 100%; } + + /* The task table becomes stacked cards instead of forcing the action + column off-screen. It remains a semantic table for assistive technology; + only its visual layout changes. */ + .table-scroll:has(.task-row) { + overflow: visible; + } + + .table:has(.task-row), + .table:has(.task-row) tbody { + display: block; + } + + .table-scroll > .table:has(.task-row) { + width: 100%; + min-width: 0; + } + + .table:has(.task-row) thead { + display: none; + } + + .task-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: var(--sp-2) var(--sp-4); + margin-bottom: var(--sp-3); + padding: var(--sp-3); + border: 1px solid var(--hairline); + border-radius: var(--radius-lg); + background: var(--surface-glass); + } + + .task-row td { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--sp-2); + padding: var(--sp-1) 0; + border: 0; + text-align: right; + } + + .task-row td::before { + content: attr(data-label); + color: var(--fg-subtle); + font-size: var(--text-xs); + font-weight: 500; + text-align: left; + } + + .task-row td:nth-child(3), + .task-row td:last-child { + grid-column: 1 / -1; + } + + .task-row td:last-child { + align-items: flex-start; + } + + .task-timeline-row, + .task-timeline-row td { + display: block; + width: 100%; + } + + .task-timeline-row td { + margin: calc(var(--sp-2) * -1) 0 var(--sp-4); + border-radius: 0 0 var(--radius-lg) var(--radius-lg); + } + + .task-detail-actions { + align-items: flex-start; + flex-direction: column; + } +} + +@media (max-width: 480px) { + .task-row { + grid-template-columns: 1fr; + } + + .task-row td:nth-child(3), + .task-row td:last-child { + grid-column: auto; + } } .task-timeline-row td { diff --git a/ui/src/tasks/tasks.js b/ui/src/tasks/tasks.js index b42dcbc2c..6759909a1 100644 --- a/ui/src/tasks/tasks.js +++ b/ui/src/tasks/tasks.js @@ -3,6 +3,7 @@ import { api } from "../base/api.js"; import { ago, el, empty, mount, pill, statusKind } from "../base/dom.js"; import { statTile } from "../base/statTile.js"; import { taskRowA11y } from "./task-row.js"; +import { initialTaskFilter, taskMatchesStatus } from "./task-filters.js"; /** * Plain-language status labels. One place, so "waiting_human" only ever @@ -34,6 +35,20 @@ export function tasksPage(params = new URLSearchParams()) { const root = el("div"); const summaryRow = el("div.grid.grid-4.task-summary"); const body = el("tbody"); + let tasks = []; + let filterStatus = initialTaskFilter(params); + let search = ""; + const requestedTask = Number(params.get("task")); + let expandedId = Number.isFinite(requestedTask) && requestedTask > 0 ? requestedTask : null; + let focusRequestedTask = expandedId !== null; + let forgeHost = ""; + const eventCache = new Map(); + // Keyed by task id. A single shared string leaked one row's failure into + // every other row's action cell. + const actionErrors = new Map(); + // Tasks with an action in flight, so the buttons can be disabled rather + // than letting an impatient second click fire the same action twice. + const actionsInFlight = new Set(); const searchInput = el("input.task-search", { type: "search", placeholder: "Search by title or repo…", @@ -51,23 +66,11 @@ export function tasksPage(params = new URLSearchParams()) { }, }, el("option", { value: "" }, "All statuses"), - ...Object.entries(STATUS_LABELS).map(([value, label]) => el("option", { value }, label)), + el("option", { value: "needs_you", selected: filterStatus === "needs_you" }, "Needs you"), + ...Object.entries(STATUS_LABELS).map(([value, label]) => + el("option", { value, selected: filterStatus === value }, label)), ); - let tasks = []; - let filterStatus = ""; - let search = ""; - const requestedTask = Number(params.get("task")); - let expandedId = Number.isFinite(requestedTask) && requestedTask > 0 ? requestedTask : null; - let forgeHost = ""; - const eventCache = new Map(); - // Keyed by task id. A single shared string leaked one row's failure into - // every other row's action cell. - const actionErrors = new Map(); - // Tasks with an action in flight, so the buttons can be disabled rather - // than letting an impatient second click fire the same action twice. - const actionsInFlight = new Set(); - render(); load(); @@ -120,6 +123,7 @@ export function tasksPage(params = new URLSearchParams()) { if (expandedId && tasks.some((task) => String(task.id) === String(expandedId))) { loadTimeline(expandedId); } + focusDirectTask(); } catch (err) { mount(summaryRow, el("div.card", empty("Cannot reach archied", String(err.message || err)))); mount(body, el("tr", el("td", { colspan: 8 }, empty("Cannot reach archied", String(err.message || err))))); @@ -162,7 +166,7 @@ export function tasksPage(params = new URLSearchParams()) { function filtered() { return tasks.filter((t) => { - if (filterStatus && t.status !== filterStatus) return false; + if (!taskMatchesStatus(t, filterStatus)) return false; if (!search) return true; const hay = `${t.title} ${t.repo}`.toLowerCase(); return hay.includes(search); @@ -197,6 +201,18 @@ export function tasksPage(params = new URLSearchParams()) { body.append(taskRow(t)); if (expandedId === t.id) body.append(timelineRow(t)); } + focusDirectTask(); + } + + function focusDirectTask() { + if (!focusRequestedTask || !expandedId) return; + focusRequestedTask = false; + requestAnimationFrame(() => { + const row = document.getElementById(`task-row-${expandedId}`); + if (!row) return; + row.focus({ preventScroll: true }); + row.scrollIntoView({ block: "center", behavior: "smooth" }); + }); } function taskRow(t) { @@ -212,6 +228,7 @@ export function tasksPage(params = new URLSearchParams()) { "tr.task-row", { ...taskRowA11y(t, expanded), + id: `task-row-${t.id}`, tabindex: "0", onkeydown: (event) => { if (event.key !== "Enter" && event.key !== " ") return; @@ -222,24 +239,33 @@ export function tasksPage(params = new URLSearchParams()) { }, el( "td.mono", - el("button.task-expand", { - type: "button", - "aria-expanded": String(expanded), - "aria-controls": timelineID, - "aria-label": `${expanded ? "Collapse" : "Expand"} timeline for ${t.title || "untitled task"}`, - onclick: toggle, - }, expanded ? "−" : "+"), + { "data-label": "Repository" }, + el( + "button.task-expand", + { + type: "button", + "aria-expanded": String(expanded), + "aria-controls": timelineID, + "aria-label": `${expanded ? "Collapse" : "Expand"} timeline for ${t.title || "untitled task"}`, + onclick: toggle, + }, + expanded ? "−" : "+", + ), repoLink(t) ?? `${t.owner}/${t.repo}`, ), - el("td.mono", issueLink(t) ?? `#${t.issue_number}`), - el("td.strong", t.title || "(untitled)"), - el("td", pill(statusLabel(t.status), statusKind(t.status))), - el("td", t.workflow || "—"), - el("td", t.stage || "—"), + el("td.mono", { "data-label": "Issue" }, issueLink(t) ?? `#${t.issue_number}`), + el("td.strong", { "data-label": "Title" }, t.title || "(untitled)"), + el("td", { "data-label": "Status" }, pill(statusLabel(t.status), statusKind(t.status))), + el("td", { "data-label": "Workflow" }, t.workflow || "—"), + el("td", { "data-label": "Stage" }, t.stage || "—"), // updated_at moves on every transition, so this reads as "how long has // it been sitting like this" rather than "how old is the task". - el("td", { title: t.created_at ? `Created ${ago(t.created_at)}` : "" }, ago(t.updated_at)), - el("td", taskActions(t)), + el( + "td", + { "data-label": "Last activity", title: t.created_at ? `Created ${ago(t.created_at)}` : "" }, + ago(t.updated_at), + ), + el("td", { "data-label": "Actions" }, taskActions(t)), ); } @@ -265,23 +291,57 @@ export function tasksPage(params = new URLSearchParams()) { label, ); - if (t.status === "waiting_human") { - return el( - "div.task-actions", - error, - button("button.btn.btn-small", "approve", "Approve"), - button( - "button.btn.btn-small.btn-quiet", - "reject", - "Reject", - `Reject "${t.title || "this task"}"? This closes the forge issue and cannot be undone from here.`, - ), - ); - } - if (t.status === "parked") { - return el("div.task-actions", error, button("button.btn.btn-small", "retry", "Retry")); - } - return error || "—"; + const controls = (t.actions || []).map((action) => { + switch (action) { + case "cancel": + return button( + "button.btn.btn-small.btn-quiet", + action, + "Cancel", + `Cancel "${t.title || "this task"}"? This closes the forge issue.`, + ); + case "stop": + return button( + "button.btn.btn-small", + action, + "Stop", + `Stop "${t.title || "this task"}"? Recoverable work will remain parked.`, + ); + case "approve": + return button("button.btn.btn-small", action, "Approve"); + case "reject": + return button( + "button.btn.btn-small.btn-quiet", + action, + "Reject", + `Reject "${t.title || "this task"}"? This closes the forge issue.`, + ); + case "retry": + return button("button.btn.btn-small", action, "Retry"); + case "abandon": + return button( + "button.btn.btn-small.btn-quiet", + action, + "Abandon", + `Abandon "${t.title || "this task"}"? This closes the forge issue.`, + ); + case "archive": + return button( + "button.btn.btn-small.btn-quiet", + action, + "Archive", + `Archive the local record for "${t.title || "this task"}"?`, + ); + case "open_pr": + return taskLink(t, "pulls", t.pr_number, "Open PR"); + case "open_issue": + return taskLink(t, "issues", t.issue_number, "Open issue"); + default: + return null; + } + }); + if (!controls.length && !error) return "—"; + return el("div.task-actions", error, controls); } async function performAction(id, action) { @@ -291,6 +351,7 @@ export function tasksPage(params = new URLSearchParams()) { try { await api.taskAction(id, action); actionsInFlight.delete(id); + if (action === "archive") expandedId = null; await load(); } catch (err) { actionsInFlight.delete(id); @@ -306,6 +367,27 @@ export function tasksPage(params = new URLSearchParams()) { return `${forgeHost.replace(/\/+$/, "")}/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`; } + function taskLink(t, kind, number, label) { + const base = forgeBase(t); + if (!base || !number || (kind === "issues" && t.source === "chat")) { + return el( + "button.btn.btn-small", + { type: "button", disabled: true, title: `${label} is unavailable` }, + label, + ); + } + return el( + "a.btn.btn-small", + { + href: `${base}/${kind}/${number}`, + target: "_blank", + rel: "noreferrer", + onclick: (event) => event.stopPropagation(), + }, + label, + ); + } + function repoLink(t) { const base = forgeBase(t); if (!base) return null; @@ -348,6 +430,11 @@ export function tasksPage(params = new URLSearchParams()) { el( "td", { colspan: 8 }, + el( + "div.task-detail-actions", + el("div.task-decision-title", "Available actions"), + taskActions(t), + ), t.status === "waiting_human" && t.plan ? el("div.task-decision", el("div.task-decision-title", "Decision required"), el("div.task-decision-plan", t.plan)) : t.status === "parked" && t.park_reason diff --git a/ui/test/operator-controls.test.js b/ui/test/operator-controls.test.js new file mode 100644 index 000000000..3882a27c8 --- /dev/null +++ b/ui/test/operator-controls.test.js @@ -0,0 +1,48 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { dashboardTaskTargets } from "../src/dashboard/task-targets.js"; +import { + SETUP_DISMISSAL_KEY, + dismissSetupComplete, + setupPanelState, +} from "../src/dashboard/setup-preference.js"; +import { initialTaskFilter, taskMatchesStatus } from "../src/tasks/task-filters.js"; + +function memoryStorage() { + const values = new Map(); + return { + getItem: (key) => values.get(key) ?? null, + setItem: (key, value) => values.set(key, String(value)), + removeItem: (key) => values.delete(key), + }; +} + +test("dashboard links one attention task directly and groups multiple", () => { + assert.equal(dashboardTaskTargets([{ id: 7, status: "parked" }]).attention.href, "#/tasks?task=7"); + assert.equal(dashboardTaskTargets([ + { id: 7, status: "parked" }, + { id: 8, status: "waiting_human" }, + ]).attention.href, "#/tasks?status=needs_you"); + assert.equal(dashboardTaskTargets([{ id: 9, status: "running" }]).running.href, "#/tasks?status=running"); +}); + +test("setup completion dismissal is versioned and resets on regression", () => { + const storage = memoryStorage(); + const complete = { steps: [{ done: true }] }; + const incomplete = { steps: [{ done: false }] }; + assert.equal(setupPanelState(complete, storage).kind, "complete"); + dismissSetupComplete(storage); + assert.equal(storage.getItem(SETUP_DISMISSAL_KEY), "1"); + assert.equal(setupPanelState(complete, storage).kind, "dismissed"); + assert.equal(setupPanelState(incomplete, storage).kind, "incomplete"); + assert.equal(storage.getItem(SETUP_DISMISSAL_KEY), null); +}); + +test("needs-you filtering includes only parked and waiting tasks", () => { + const params = new URLSearchParams("status=needs_you"); + assert.equal(initialTaskFilter(params), "needs_you"); + assert.equal(taskMatchesStatus({ status: "parked" }, "needs_you"), true); + assert.equal(taskMatchesStatus({ status: "waiting_human" }, "needs_you"), true); + assert.equal(taskMatchesStatus({ status: "running" }, "needs_you"), false); + assert.equal(initialTaskFilter(new URLSearchParams("status=made_up")), ""); +});