Files
archie/internal/webui/api_tasks_test.go
T
sam 170fe0250b fix: close the duplicate-work loop and the dead paths around it
Applies the four-reviewer pass over the forge/dashboard-actions work.
The through-line is that several capabilities were wired but inert, and
one of them could cost real work.

DUPLICATE WORK. "Closes #N" was dropped from PR bodies in favour of
LinkBranch, which is sidebar linkage on Gitea and a no-op stub on
GitHub -- neither closes anything, and nothing else did either. So a
merged task left its issue open, labelled and assigned; the next poll
re-enqueued it, and once the dashboard's Clear removed the task row that
became a second implementation and a second PR for work already merged.
reconcilePRs now closes the issue on merge, and a rejected task closes
its issue too. A PR closed without merging deliberately leaves the issue
open: that usually means "try again".

MAX RETRIES. Configured, defaulted and reported by /api/config, and
enforced nowhere -- markDead was unreachable and EffectiveMaxRetries had
no callers, so the dashboard's retry incremented retry_count forever.
The retry action now retires a task to dead at the cap.

DEAD ON ARRIVAL. Tasks() never selected plan or source, so the
"Decision required" panel could not render and chat tasks -- whose issue
number is synthetic -- linked to forge issues that do not exist.

COSMETIC FAILURE, FATAL RESULT. OpenPR failed the whole stage when
LinkBranch errored, so the pull request was never opened and the task
parked; a retry re-links the same branch, which Gitea answers with a
conflict, so every retry parked again. It is best-effort now.

INVISIBLE ACTIONS. Approve/retry/reject wrote store rows and nothing
else, so the timeline and activity stream never showed that a human had
intervened. They emit events now.

Also: store write failures answer 500 rather than 409; the dashboard
surfaces the server's actual reason instead of "409 Conflict"; action
buttons stop propagation (acting on a task no longer also expands it),
disable in flight, keep per-task errors instead of one shared string,
and confirm before rejecting.

Removed: the maybeRetryParked shim and markDead with their now-vacuous
tests, WaitingTasks (no consumers; its tests were rewritten to assert
the same routing through TaskByID), write-only Daemon.Runtime, and
dir/dirs response bloat from /api/skills. skillSource checked workDir
before sharedDir, mislabelling every shared skill when the two are equal.
DefaultRoots now dedupes roots differing only by a trailing separator.

The air build rule claiming to keep ui/dist current never ran -- it
required one file to satisfy include_dir and include_file together, and
ui/ is excluded from the walk. Deleted with the comment that promised it.
task test:ui joins task check and CI; it ran nowhere before, so the
dashboard suite could rot silently.

Docs corrected where they described behaviour that no longer exists:
parks no longer comment on the issue, state labels no longer drive
retries, and forgerpc's doc claimed four proxied methods while listing
three of five.
2026-08-05 03:54:25 +10:00

164 lines
5.5 KiB
Go

package webui
// Tests for the task-timeline route. The dashboard's "Click a row for its
// timeline" interaction depends on GET /api/tasks/{id} returning exactly that
// task's events, ordered, and on the literal /api/tasks/clear route beating
// the {id} wildcard.
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/store"
)
// Approve requeues from the task's own recorded state rather than anything
// the caller supplies, so a stale dashboard cannot approve a task twice.
func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) {
srv := newTestServer(t)
ctx := t.Context()
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "approve me", "", "", ""); err != nil {
t.Fatal(err)
}
task, err := srv.Store.ClaimNext(ctx)
if err != nil || task == nil {
t.Fatalf("claim = (%+v, %v)", task, err)
}
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusWaitingHuman, "review"); err != nil {
t.Fatal(err)
}
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")
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("approve status = %d, body = %s", w.Code, w.Body)
}
got, err := srv.Store.TaskByID(ctx, task.ID)
if err != nil || got == nil {
t.Fatalf("TaskByID = (%+v, %v)", got, err)
}
if got.Status != store.StatusQueued || got.Workflow != "implement" {
t.Fatalf("approved task = %+v, want queued/implement", got)
}
}
func TestHandleTaskActionRetriesParkedTask(t *testing.T) {
srv := newTestServer(t)
ctx := t.Context()
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "retry me", "", "", ""); err != nil {
t.Fatal(err)
}
task, err := srv.Store.ClaimNext(ctx)
if err != nil || task == nil {
t.Fatalf("claim = (%+v, %v)", task, err)
}
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "failed"); err != nil {
t.Fatal(err)
}
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"retry"}`))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("retry status = %d, body = %s", w.Code, w.Body)
}
got, err := srv.Store.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("retried task = %+v, want queued/retry_count=1", got)
}
}
// TestHandleTaskIsolatesTasks returns the timeline for one task, and only
// that task: another task's events must not leak into the response.
func TestHandleTaskIsolatesTasks(t *testing.T) {
srv := newTestServer(t)
ctx := t.Context()
for _, ev := range []events.Event{
{TaskID: 7, Kind: "stage_start", Stage: "plan", Detail: "bootstrap"},
{TaskID: 7, Kind: "stage_end", Stage: "plan"},
{TaskID: 8, Kind: "stage_start", Stage: "implement"},
} {
if _, err := srv.Store.InsertEvent(ctx, ev); err != nil {
t.Fatal(err)
}
}
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks/7", 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 []events.Event
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if len(got) != 2 {
t.Fatalf("timeline has %d events, want 2 (task 8 must not leak in)", len(got))
}
if got[0].Kind != "stage_start" || got[0].Stage != "plan" {
t.Errorf("first event = %+v, want stage_start/plan", got[0])
}
}
// TestHandleTaskUnknownID returns an empty list, not an error, for a task id
// that has no events yet -- the UI renders "No events yet" from that.
func TestHandleTaskUnknownID(t *testing.T) {
srv := newTestServer(t)
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/999", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if body := strings.TrimSpace(w.Body.String()); body != "null" && body != "[]" {
t.Fatalf("body = %s, want an empty timeline", body)
}
}
// TestHandleTaskBadID is covered in webui_test.go (400 on a non-numeric id).
// TestHandleTaskStoreError proves a store failure surfaces as 500 -- the UI
// shows its "Could not load timeline" state and offers a retry.
func TestHandleTaskStoreError(t *testing.T) {
base := newTestServer(t)
srv := &Server{
Store: &stubStore{TaskStore: base.Store, taskEventsErr: fmt.Errorf("db locked")},
Log: base.Log,
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/7", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500", w.Code)
}
}
// 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) {
srv := newTestServer(t)
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)
}
}