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.
This commit is contained in:
1 parent
a751be66b3
commit
170fe0250b
60 files changed
+2081
-768
No files matched your search
@@ -19,26 +19,17 @@ type SkillView struct {
|
||||
// beyond what is in the source. It answers the same question a fresh
|
||||
// operator would ask by reading internal/skill/, without the reading.
|
||||
//
|
||||
// The catalogue is scanned from cfg.SkillsDir when configured (a shared
|
||||
// directory meant to be pointed at deliberately), falling back to
|
||||
// cfg.WorkDir's own .agents/skills/ otherwise. Both are legitimate --
|
||||
// skill.Catalog treats a missing directory as "no skills," not an error --
|
||||
// so an unconfigured deployment gets an empty, explained list rather than a
|
||||
// failure.
|
||||
// The catalogue layers project, explicitly shared, and user-global skills.
|
||||
// Earlier roots win when names collide. Missing roots are legitimate and
|
||||
// produce an empty or partial catalogue rather than a failed dashboard.
|
||||
func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Cfg == nil {
|
||||
writeJSON(w, map[string]any{"skills": []SkillView{}, "dir": ""})
|
||||
writeJSON(w, map[string]any{"skills": []SkillView{}})
|
||||
return
|
||||
}
|
||||
|
||||
dir := s.Cfg.SkillsDir
|
||||
source := "shared skills directory"
|
||||
if dir == "" {
|
||||
dir = s.Cfg.WorkDir
|
||||
source = "bundled with this project"
|
||||
}
|
||||
|
||||
catalog, err := skill.Catalog(dir)
|
||||
roots := skill.DefaultRoots(s.Cfg.WorkDir, s.Cfg.SkillsDir)
|
||||
catalog, err := skill.CatalogRoots(roots...)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to read skill catalogue: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -50,9 +41,28 @@ func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) {
|
||||
Name: entry.Name,
|
||||
Description: entry.Description,
|
||||
Workflow: entry.Workflow,
|
||||
Source: source,
|
||||
Source: skillSource(entry.Root, s.Cfg.WorkDir, s.Cfg.SkillsDir),
|
||||
})
|
||||
}
|
||||
|
||||
writeJSON(w, map[string]any{"skills": views, "dir": dir})
|
||||
// Each skill already carries its own Source, which is what the page
|
||||
// renders. A top-level dir/dirs pair had no consumer and implied the
|
||||
// catalog came from one place when it is merged from several.
|
||||
writeJSON(w, map[string]any{"skills": views})
|
||||
}
|
||||
|
||||
// skillSource labels where a skill was loaded from.
|
||||
//
|
||||
// sharedDir is checked first: when it equals workDir the roots collapse to one
|
||||
// entry, and matching workDir first labelled every shared skill as a project
|
||||
// skill.
|
||||
func skillSource(root, workDir, sharedDir string) string {
|
||||
switch root {
|
||||
case sharedDir:
|
||||
return "shared skills"
|
||||
case workDir:
|
||||
return "project skills"
|
||||
default:
|
||||
return "user-global skills"
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func (s *Server) handleSummary(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -64,3 +70,196 @@ func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
writeJSON(w, evs)
|
||||
}
|
||||
|
||||
type taskActionRequest struct {
|
||||
Action string `json:"action"`
|
||||
}
|
||||
|
||||
func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
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)
|
||||
return
|
||||
}
|
||||
task, err := s.Store.TaskByID(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
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
|
||||
}
|
||||
if outcome == nil {
|
||||
return
|
||||
}
|
||||
|
||||
s.emit(events.Event{
|
||||
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})
|
||||
}
|
||||
|
||||
// actionOutcome is what a completed operator action should record.
|
||||
type actionOutcome struct {
|
||||
kind string
|
||||
detail string
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) approveTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
|
||||
if task.Status != store.StatusWaitingHuman {
|
||||
http.Error(w, "task is not awaiting approval", http.StatusConflict)
|
||||
return nil
|
||||
}
|
||||
if storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusWaitingHuman, "implement")) {
|
||||
return nil
|
||||
}
|
||||
return &actionOutcome{events.KindHumanApproved, "approved via the dashboard"}
|
||||
}
|
||||
|
||||
// retryTask requeues a parked task, or retires it once max_retries is spent.
|
||||
//
|
||||
// max_retries was configured, defaulted and reported by /api/config while
|
||||
// nothing enforced it: retry_count climbed forever, so a task that fails
|
||||
// every time could be retried without limit. At the cap the task belongs in
|
||||
// dead, which is what the setting exists to say.
|
||||
func (s *Server) retryTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
|
||||
if task.Status != store.StatusParked {
|
||||
http.Error(w, "task is not parked", http.StatusConflict)
|
||||
return nil
|
||||
}
|
||||
if limit := s.maxRetriesFor(task); limit > 0 && task.RetryCount >= limit {
|
||||
s.retireTask(ctx, task, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit))
|
||||
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, "")) {
|
||||
return nil
|
||||
}
|
||||
if storeFailed(w, s.Store.IncrementRetryCount(ctx, task.ID)) {
|
||||
return nil
|
||||
}
|
||||
return &actionOutcome{events.KindTaskRetried, "retried via the dashboard"}
|
||||
}
|
||||
|
||||
// retireTask moves a spent task to dead. Failure is logged, not returned:
|
||||
// the caller is already answering with the reason it refused the retry.
|
||||
func (s *Server) retireTask(ctx context.Context, task *store.Task, reason string) {
|
||||
if err := s.Store.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, reason); err != nil {
|
||||
s.logf("transition to dead failed", "task", task.ID, "err", err)
|
||||
return
|
||||
}
|
||||
s.emit(events.Event{
|
||||
Kind: events.KindTaskDead, TaskID: task.ID,
|
||||
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Detail: reason,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) rejectTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
|
||||
if task.Status != store.StatusWaitingHuman {
|
||||
http.Error(w, "task is not awaiting approval", http.StatusConflict)
|
||||
return nil
|
||||
}
|
||||
err := s.Store.Transition(ctx, task.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, "rejected via Web UI")
|
||||
if storeFailed(w, err) {
|
||||
return nil
|
||||
}
|
||||
s.closeRejectedIssue(ctx, task)
|
||||
return &actionOutcome{events.KindHumanRejected, "rejected via the dashboard"}
|
||||
}
|
||||
|
||||
// maxRetriesFor resolves the retry cap for a task, honouring a per-repo
|
||||
// override. Zero means unlimited.
|
||||
func (s *Server) maxRetriesFor(task *store.Task) int {
|
||||
if s.Cfg == nil {
|
||||
return 0
|
||||
}
|
||||
for _, repo := range s.Cfg.Repos {
|
||||
if repo.Owner == task.Owner && repo.Name == task.Repo {
|
||||
return repo.EffectiveMaxRetries(s.Cfg.MaxRetries)
|
||||
}
|
||||
}
|
||||
return s.Cfg.MaxRetries
|
||||
}
|
||||
|
||||
// closeRejectedIssue closes the forge issue behind a task the operator has
|
||||
// declined.
|
||||
//
|
||||
// Without this the issue stays open, labelled and assigned, so the next poll
|
||||
// re-enqueues it -- and once the operator uses Clear, which deletes the task
|
||||
// row, that is a second implementation and a second PR for work already
|
||||
// refused. Approve and retry deliberately leave the issue open: the task is
|
||||
// going back to work.
|
||||
//
|
||||
// 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) {
|
||||
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)
|
||||
return
|
||||
}
|
||||
// A chat task's issue number is synthetic and matches no forge issue.
|
||||
if !task.IsForgeBacked() {
|
||||
return
|
||||
}
|
||||
const comment = "Closing: this was rejected from the archie dashboard. " +
|
||||
"Reopen the issue to have archie pick it up again."
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 == "" {
|
||||
return
|
||||
}
|
||||
s.Events.Publish(e)
|
||||
}
|
||||
|
||||
func (s *Server) logf(msg string, args ...any) {
|
||||
if s.Log == nil {
|
||||
return
|
||||
}
|
||||
s.Log.Warn(msg, args...)
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// recordingCloser captures the forge issue-closure calls an action makes.
|
||||
type recordingCloser struct {
|
||||
calls []closeCall
|
||||
err error
|
||||
}
|
||||
|
||||
type closeCall struct {
|
||||
owner, repo string
|
||||
number int
|
||||
comment string
|
||||
}
|
||||
|
||||
func (r *recordingCloser) CloseIssue(_ context.Context, owner, repo string, number int, comment string) error {
|
||||
r.calls = append(r.calls, closeCall{owner, repo, number, comment})
|
||||
return r.err
|
||||
}
|
||||
|
||||
// actionServer builds a dashboard server with a task in the given state, plus
|
||||
// the collaborators the action path needs.
|
||||
func actionServer(t *testing.T, status, parkReason string) (*Server, *store.Task, *recordingCloser, *events.Bus, *events.Sub) {
|
||||
t.Helper()
|
||||
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.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, status, parkReason); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
closer := &recordingCloser{}
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
sub := bus.Subscribe(16)
|
||||
|
||||
srv.Issues = closer
|
||||
srv.Events = bus
|
||||
srv.Cfg = &config.Config{MaxRetries: 3}
|
||||
return srv, task, closer, bus, sub
|
||||
}
|
||||
|
||||
func postAction(t *testing.T, srv *Server, id int64, action string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(id, 10)+"/action",
|
||||
bytes.NewBufferString(fmt.Sprintf(`{"action":%q}`, action)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// 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
|
||||
// belongs in dead, which is what the setting exists to express.
|
||||
func TestRetryEnforcesMaxRetries(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
priorCount int
|
||||
maxRetries int
|
||||
wantStatus int
|
||||
wantTask string
|
||||
}{
|
||||
{name: "under the cap", priorCount: 0, maxRetries: 3, wantStatus: http.StatusOK, wantTask: store.StatusQueued},
|
||||
{name: "one below the cap", priorCount: 2, maxRetries: 3, wantStatus: http.StatusOK, wantTask: store.StatusQueued},
|
||||
{name: "at the cap", priorCount: 3, maxRetries: 3, wantStatus: http.StatusConflict, wantTask: store.StatusDead},
|
||||
{name: "past the cap", priorCount: 5, maxRetries: 3, wantStatus: http.StatusConflict, wantTask: store.StatusDead},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, store.StatusParked, "it broke")
|
||||
srv.Cfg = &config.Config{MaxRetries: tc.maxRetries}
|
||||
ctx := t.Context()
|
||||
for range tc.priorCount {
|
||||
if err := srv.Store.IncrementRetryCount(ctx, task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
w := postAction(t, srv, task.ID, "retry")
|
||||
if w.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.wantStatus, 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 != tc.wantTask {
|
||||
t.Errorf("status = %q, want %q", got.Status, tc.wantTask)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Rejecting a task must stop the forge issue coming back. It stays open,
|
||||
// labelled and assigned otherwise, so the next poll re-enqueues it -- and if
|
||||
// the operator has used the dashboard's Clear, which deletes the row, that is
|
||||
// a second implementation and a second PR for work already declined.
|
||||
func TestRejectClosesTheForgeIssue(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, store.StatusWaitingHuman, "review")
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
if len(closer.calls) != 1 {
|
||||
t.Fatalf("CloseIssue calls = %d, want 1: the issue stays open and is "+
|
||||
"re-polled, so the work is done twice", len(closer.calls))
|
||||
}
|
||||
call := closer.calls[0]
|
||||
if call.owner != "acme" || call.repo != "widget" || call.number != 11 {
|
||||
t.Errorf("closed %s/%s#%d, want acme/widget#11", call.owner, call.repo, call.number)
|
||||
}
|
||||
if call.comment == "" {
|
||||
t.Error("closed with no comment: an issue that closes itself with no " +
|
||||
"explanation reads as archie losing the work")
|
||||
}
|
||||
}
|
||||
|
||||
// Approve and retry put the task back to work, so the issue must stay open.
|
||||
func TestApproveAndRetryDoNotCloseTheIssue(t *testing.T) {
|
||||
for _, tc := range []struct{ action, status, reason string }{
|
||||
{"approve", store.StatusWaitingHuman, "review"},
|
||||
{"retry", store.StatusParked, "it broke"},
|
||||
} {
|
||||
t.Run(tc.action, func(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, tc.status, tc.reason)
|
||||
if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if len(closer.calls) != 0 {
|
||||
t.Errorf("CloseIssue called %d times for %s; the task is going "+
|
||||
"back to work", len(closer.calls), tc.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A chat-sourced task has a synthetic issue number that matches no forge
|
||||
// issue, so closing it would either error or close an unrelated issue.
|
||||
func TestRejectDoesNotCloseAChatTaskIssue(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
closer := &recordingCloser{}
|
||||
srv.Issues = closer
|
||||
srv.Cfg = &config.Config{MaxRetries: 3}
|
||||
|
||||
task, err := srv.Store.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "", 900001)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := srv.Store.ClaimNext(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if len(closer.calls) != 0 {
|
||||
t.Errorf("CloseIssue called for a chat task: issue number %d is synthetic",
|
||||
task.IssueNumber)
|
||||
}
|
||||
}
|
||||
|
||||
// A forge that cannot close the issue must not fail the action: the operator's
|
||||
// decision is already recorded in the store, and reporting failure would
|
||||
// invite them to click again.
|
||||
func TestRejectSurvivesAForgeFailure(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, store.StatusWaitingHuman, "review")
|
||||
closer.err = errors.New("forge unreachable")
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, want 200: the store transition succeeded", w.Code)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != store.StatusClosedWontDo {
|
||||
t.Errorf("status = %q, want %q", got.Status, store.StatusClosedWontDo)
|
||||
}
|
||||
}
|
||||
|
||||
// Actions wrote store rows and nothing else, so the activity stream and the
|
||||
// task timeline never showed that a human had intervened -- the one kind of
|
||||
// event most worth seeing.
|
||||
func TestActionsEmitEvents(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
action string
|
||||
status string
|
||||
reason string
|
||||
wantMsg string
|
||||
}{
|
||||
{name: "approve", action: "approve", status: store.StatusWaitingHuman, reason: "review", wantMsg: "approve"},
|
||||
{name: "retry", action: "retry", status: store.StatusParked, reason: "it broke", wantMsg: "retry"},
|
||||
{name: "reject", action: "reject", status: store.StatusWaitingHuman, reason: "review", wantMsg: "reject"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, sub := actionServer(t, tc.status, tc.reason)
|
||||
|
||||
if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
select {
|
||||
case ev := <-sub.C:
|
||||
if ev.TaskID != task.ID {
|
||||
t.Errorf("event TaskID = %d, want %d", ev.TaskID, task.ID)
|
||||
}
|
||||
if ev.Kind == "" {
|
||||
t.Error("event Kind is empty")
|
||||
}
|
||||
default:
|
||||
t.Fatalf("%s emitted no event: the activity stream and timeline "+
|
||||
"never show that a human intervened", tc.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Error mapping. A store failure is not the client's fault, and returning 409
|
||||
// tells the UI to say "conflict" for what is actually a broken database.
|
||||
func TestTaskActionErrorMapping(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
setup func(t *testing.T, srv *Server, id int64)
|
||||
id func(id int64) string
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "unknown action",
|
||||
body: `{"action":"detonate"}`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "malformed body",
|
||||
body: `not json`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "non-numeric id",
|
||||
body: `{"action":"approve"}`,
|
||||
id: func(int64) string { return "banana" },
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "unknown task",
|
||||
body: `{"action":"approve"}`,
|
||||
id: func(int64) string { return "424242" },
|
||||
wantStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "wrong state",
|
||||
body: `{"action":"retry"}`,
|
||||
// The task is waiting_human, not parked.
|
||||
wantStatus: http.StatusConflict,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, store.StatusWaitingHuman, "review")
|
||||
if tc.setup != nil {
|
||||
tc.setup(t, srv, task.ID)
|
||||
}
|
||||
path := strconv.FormatInt(task.ID, 10)
|
||||
if tc.id != nil {
|
||||
path = tc.id(task.ID)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+path+"/action", bytes.NewBufferString(tc.body))
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A store write failure is a 500, not a 409.
|
||||
func TestTaskActionStoreFailureIs500(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := base.Store.EnqueueIssue(ctx, "acme", "widget", 11, "a task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := base.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := base.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
srv := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, requeueErr: errors.New("db locked")},
|
||||
Log: base.Log,
|
||||
Cfg: &config.Config{MaxRetries: 3},
|
||||
}
|
||||
w := postAction(t, srv, task.ID, "approve")
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500: a store failure is not a conflict", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -39,10 +39,33 @@ type Server struct {
|
||||
// stay frictionless -- see IsLoopback.
|
||||
Token string
|
||||
|
||||
// Issues closes the forge issue behind a rejected task. Optional: the
|
||||
// action still records the operator's decision without it, and says so
|
||||
// in the log. Deliberately the narrowest interface that does the job
|
||||
// rather than the whole forge client -- the dashboard has no business
|
||||
// commenting, labelling or opening PRs.
|
||||
Issues IssueCloser
|
||||
|
||||
// Events publishes operator actions so they reach the task timeline and
|
||||
// the live activity stream. Optional: nil means the action is recorded
|
||||
// in the store but invisible to anyone watching.
|
||||
Events EventPublisher
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[chan events.Event]struct{}
|
||||
}
|
||||
|
||||
// IssueCloser closes the forge issue behind a task.
|
||||
type IssueCloser interface {
|
||||
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
|
||||
}
|
||||
|
||||
// EventPublisher accepts events for the store and the live stream. The bus
|
||||
// in cmd/archied satisfies it.
|
||||
type EventPublisher interface {
|
||||
Publish(events.Event)
|
||||
}
|
||||
|
||||
// Broadcast fans an (ID-stamped) event out to every connected SSE
|
||||
// client; stalled clients drop events rather than blocking the caller.
|
||||
func (s *Server) Broadcast(e events.Event) {
|
||||
@@ -61,6 +84,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/summary", s.handleSummary)
|
||||
mux.HandleFunc("GET /api/setup", s.handleSetup)
|
||||
mux.HandleFunc("GET /api/tasks", s.handleTasks)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction)
|
||||
mux.HandleFunc("GET /api/tasks/{id}", s.handleTask)
|
||||
mux.HandleFunc("GET /api/tasks/clear", s.handleClearTasks)
|
||||
mux.HandleFunc("GET /api/workflows", s.handleWorkflows)
|
||||
|
||||
@@ -49,6 +49,15 @@ type stubStore struct {
|
||||
stageStatsErr error
|
||||
tokensByDayErr error
|
||||
eventsSinceErr error
|
||||
taskEventsErr error
|
||||
requeueErr error
|
||||
}
|
||||
|
||||
func (s *stubStore) Requeue(ctx context.Context, id int64, from, workflow string) error {
|
||||
if s.requeueErr != nil {
|
||||
return s.requeueErr
|
||||
}
|
||||
return s.TaskStore.Requeue(ctx, id, from, workflow)
|
||||
}
|
||||
|
||||
func (s *stubStore) WorkflowStats(ctx context.Context) ([]store.WorkflowStat, error) {
|
||||
@@ -79,6 +88,13 @@ func (s *stubStore) EventsSince(ctx context.Context, sinceID int64, limit int) (
|
||||
return s.TaskStore.EventsSince(ctx, sinceID, limit)
|
||||
}
|
||||
|
||||
func (s *stubStore) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error) {
|
||||
if s.taskEventsErr != nil {
|
||||
return nil, s.taskEventsErr
|
||||
}
|
||||
return s.TaskStore.TaskEvents(ctx, taskID)
|
||||
}
|
||||
|
||||
func TestHandleSummary(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
|
||||
Reference in new issue
Block a user