Files
archie/internal/webui/api_tasks.go
T
sam 23f87c4cea Fix/workflow eda audit (#1627)
* fix(webui): accept the merge task action

The action whitelist omitted merge, so the dashboard's Merge button on a
pr_open task was refused with 400 unknown action.

Closes: archie-core-slpoz

* fix(workflow): give each parallel branch its own outputs

Branches shared the task's Outputs map, so concurrent declared-output
writes raced (or were lost when the map started nil). Each branch now
writes a copy; join merges new outputs in branch-name order and refuses
one written by two branches as a second write.

Closes: archie-core-3a7w2

* fix(postgres): dispatch captures oldest first and keep pending ones

ListUndispatchedCaptures ordered newest first and listed captures no
binding can match (failed HMAC), so sustained intake starved older work
and bad signatures held the batch. It is now oldest first and lists only
dispatchable captures. Count retention no longer evicts a capture that
is still pending for an armed binding. The daemon lists only sources
with an enabled workflow, so captures waiting on a disabled one do not
hold the oldest-first batch.

Closes: archie-core-2et4b, archie-core-o0s0z

* fix(ui): refuse renaming a workflow onto an existing id

Saving upserts by id, so editing a workflow's id to another workflow's
id removed the open one and overwrote the other. The editor now refuses
that save and says why.

Closes: archie-core-wpoz8

* fix(workflow): reject unknown step settings at save

Step factories decoded settings with yaml.Node.Decode, which drops keys
it does not know, and settings-less steps ignored settings entirely, so a
misspelt key (readOnly for read_only) saved and silently did nothing.
Every factory now decodes strictly and settings-less steps refuse
settings; ParseDefinition runs the factories, so the save refuses them.

Closes: archie-core-8b5nk

* fix(postgres): keep a stored capture when its prune fails

InsertCapture committed the capture, then returned the prune's error, so
intake answered 500 and a sender without a delivery header retried into
a duplicate capture and a duplicate dispatch. A failed prune is now
logged and the stored capture's id returned.

Closes: archie-core-3miuh

* fix(crondelivery): fail and advance a job no runner can deliver

Router.Run returned nil for a kind with no runner, so the engine reported
a successful run while the schedule never advanced and the job fired on
every tick. The run now fails with the refusal, which the engine reports,
and the schedule advances (a one-shot is removed). The router's own
refusal event is gone with it.

Closes: archie-core-s6ahh

* fix(taskactions): stop the runs of cancelled callees

CancelExecution cancelled a caller's waited-on callees in the store, but
only the caller's run was stopped, so callee containers ran to the end.
CancelExecution now returns the callees it cancelled (nested included)
in place of the step ids nobody read, and every cancelling action stops
their runs too.

Closes: archie-core-9labz

* fix(workflow): treat a zero json.Number as false in when

Task inputs and step results decode numbers as json.Number, which truthy
did not unpack, so when: inputs.count held for a count of 0.

Closes: archie-core-uv270

* fix(webui): read a workflow's runs with a workflow-filtered page

The workflows page and the canvas run picker filtered the newest 100
tasks of every workflow client-side, so on a busy instance a workflow's
older runs were invisible. GET /api/tasks takes a workflow filter, carried
through the State Store's Tasks request to the query, and both views ask
for the selected workflow's runs.

Closes: archie-core-tpiw1

* fix(ui): load the restored workflow into the editor

Restore Defaults saved the shipped definition but left the open draft in
the editor, still marked unsaved, so a later save re-applied it. The
editor now reloads the restored definition.

Closes: archie-core-85e7w
2026-10-12 03:20:00 +11:00

439 lines
14 KiB
Go

package webui
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
)
func (s *Server) handleSummary(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
statuses, err := s.Store.StatusCounts(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
workflows, err := s.Store.WorkflowStats(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stages, err := s.Store.StageStats(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
days, err := s.Store.TokensByDay(ctx, 14)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
needsYou := 0
for _, id := range needsYouStatuses() {
needsYou += statuses[id]
}
writeJSON(w, map[string]any{
"statuses": statuses, "needs_you": needsYou, "workflows": workflows,
"stages": stages, "tokens_by_day": days,
})
}
// needsYouStatuses are the statuses the "needs you" filter and count group.
func needsYouStatuses() []string {
var ids []string
for _, meta := range taskstate.Statuses() {
if meta.NeedsYou {
ids = append(ids, meta.ID)
}
}
return ids
}
// handleTasks serves one page of tasks, most recently updated first. ?status
// narrows it (needs_you is the grouped filter), ?limit sizes it, and ?cursor
// resumes after the previous page; a full page answers the next cursor in the
// X-Next-Cursor header.
func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) {
page, err := taskPageFrom(r.URL.Query())
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
tasks, err := s.Store.TasksPage(r.Context(), page)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(tasks) == page.Limit {
last := tasks[len(tasks)-1]
w.Header().Set("X-Next-Cursor", fmt.Sprintf("%d.%d", last.UpdatedAt.UnixNano(), last.ID))
}
forge := s.resolveForge(r.Context())
views := make([]taskView, len(tasks))
for i := range tasks {
repoURL, issueURL, prURL := taskURLs(tasks[i], forge(tasks[i]))
views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL}
}
writeJSON(w, views)
}
const defaultTaskPage = 100
// taskPageFrom reads the task list's query parameters.
func taskPageFrom(q url.Values) (storecontract.TaskPage, error) {
page := storecontract.TaskPage{Limit: defaultTaskPage, Workflow: q.Get("workflow")}
switch status := q.Get("status"); status {
case "":
case "needs_you":
page.Statuses = needsYouStatuses()
default:
page.Statuses = []string{status}
}
if raw := q.Get("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > 500 {
return page, fmt.Errorf("limit must be 1 to 500")
}
page.Limit = limit
}
if raw := q.Get("cursor"); raw != "" {
nanos, id, ok := strings.Cut(raw, ".")
n, nerr := strconv.ParseInt(nanos, 10, 64)
i, ierr := strconv.ParseInt(id, 10, 64)
if !ok || nerr != nil || ierr != nil || i <= 0 {
return page, fmt.Errorf("invalid cursor")
}
page.After = storecontract.TaskCursor{UpdatedAt: time.Unix(0, n), ID: i}
}
return page, nil
}
type taskView struct {
task.Task
Actions []taskstate.Action `json:"actions"`
RepoURL string `json:"repo_url,omitempty"`
IssueURL string `json:"issue_url,omitempty"`
PRURL string `json:"pr_url,omitempty"`
}
// forgeCoordinates locate a repository on its forge: the base URL, and the
// forge type that decides the pull-request path segment.
type forgeCoordinates struct {
host string
forgeType string
}
// resolveForge returns a function mapping a task to its forge: by identity
// name, then repository owner, else the default forge.
func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates {
unlinked := func(task.Task) forgeCoordinates { return forgeCoordinates{} }
view, ok, err := s.configSource()(ctx)
if err != nil || !ok {
return unlinked
}
if len(view.Identities) == 0 {
// No per-identity forges published: links are withheld.
if view.MultiIdentity {
return unlinked
}
published := forgeCoordinates{host: view.Identity.ForgeHost, forgeType: view.Identity.ForgeType}
return func(task.Task) forgeCoordinates { return published }
}
return forgeLocator(view)
}
// ownedRepo identifies a repository within an identity's repo list.
type ownedRepo struct{ owner, name string }
// forgeLocator indexes a published projection's per-identity forges once per
// request and resolves each task against them: exact identity name, then repo
// ownership, with an ambiguous repo falling back to the default forge.
func forgeLocator(view ConfigView) func(task.Task) forgeCoordinates {
fallback := forgeCoordinates{host: view.Identity.ForgeHost, forgeType: view.Identity.ForgeType}
byName := make(map[string]forgeCoordinates, len(view.Identities))
byRepo := make(map[ownedRepo]forgeCoordinates)
// ambiguous records a repo two identities both claim, which ownership
// cannot decide -- it is answered by the default forge instead.
ambiguous := make(map[ownedRepo]bool)
for _, identity := range view.Identities {
coords := forgeCoordinates{host: identity.ForgeHost, forgeType: identity.ForgeType}
// First definition of a name wins, as the recovered resolver's
// forward scan did (and as daemon.identityFor still does), so the two
// agree even if a config ever names one identity twice.
if _, seen := byName[identity.Name]; !seen {
byName[identity.Name] = coords
}
for _, repo := range identity.Repos {
key := ownedRepo{owner: repo.Owner, name: repo.Name}
if _, seen := byRepo[key]; seen {
ambiguous[key] = true
continue
}
byRepo[key] = coords
}
}
return func(t task.Task) forgeCoordinates {
if t.Identity != "" {
if coords, ok := byName[t.Identity]; ok {
return coords
}
}
key := ownedRepo{owner: t.Owner, name: t.Repo}
if ambiguous[key] {
return fallback
}
if coords, ok := byRepo[key]; ok {
return coords
}
return fallback
}
}
func taskURLs(task task.Task, forge forgeCoordinates) (repoURL, issueURL, prURL string) {
if forge.host == "" || task.Owner == "" || task.Repo == "" {
return "", "", ""
}
repoURL = strings.TrimRight(forge.host, "/") + "/" + url.PathEscape(task.Owner) + "/" + url.PathEscape(task.Repo)
if task.IsForgeBacked() && task.IssueNumber > 0 {
issueURL = repoURL + "/issues/" + strconv.Itoa(task.IssueNumber)
}
if task.PRNumber > 0 {
segment := "pull"
if forge.forgeType == "gitea" {
segment = "pulls"
}
prURL = repoURL + "/" + segment + "/" + strconv.Itoa(task.PRNumber)
}
return repoURL, issueURL, prURL
}
func (s *Server) handleTask(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
}
evs, err := s.Store.TaskEvents(r.Context(), id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, evs)
}
type taskActionRequest struct {
Action string `json:"action"`
// Instructions is the re-review's focus, required by the rereview action
// and ignored by every other one. The dashboard is the authoritative
// surface that carries operators' instructions; chat is a shortcut with no
// instruction syntax.
Instructions string `json:"instructions"`
// Findings are the keys of the offered findings an approve posts; an
// absent selection means all of them. It is ignored by every other
// action.
Findings []string `json:"findings"`
// RetryMode is the worktree mode for a retry; empty means refresh_onto_base.
RetryMode string `json:"retry_mode"`
// ResumeFrom is the step a retry starts at; empty runs every step.
ResumeFrom string `json:"resume_from"`
}
func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "bad id", http.StatusBadRequest)
return
}
action, res, ok := decodeTaskAction(w, r)
if !ok {
return
}
if err := s.applyOperatorTaskAction(r.Context(), id, action, res); err != nil {
switch {
case errors.Is(err, taskactions.ErrNotFound):
http.Error(w, "task not found", http.StatusNotFound)
case errors.Is(err, taskactions.ErrConflict), errors.Is(err, storecontract.ErrStaleTransition),
errors.Is(err, storecontract.ErrRereviewCapReached):
http.Error(w, err.Error(), http.StatusConflict)
case errors.Is(err, taskactions.ErrUnavailable):
http.Error(w, err.Error(), http.StatusServiceUnavailable)
default:
s.logf("task action failed", "task", id, "err", err)
http.Error(w, "task action failed", http.StatusInternalServerError)
}
return
}
writeJSON(w, map[string]any{"ok": true, "action": action, "task_id": id})
}
func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action, taskactions.ActionPayload, 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 {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
http.Error(w, "action body too large", http.StatusRequestEntityTooLarge)
return "", taskactions.ActionPayload{}, false
}
http.Error(w, "invalid action", http.StatusBadRequest)
return "", taskactions.ActionPayload{}, false
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
http.Error(w, "invalid action", http.StatusBadRequest)
return "", taskactions.ActionPayload{}, false
}
action := taskstate.Action(req.Action)
if !taskMutation(action) {
http.Error(w, "unknown action", http.StatusBadRequest)
return "", taskactions.ActionPayload{}, false
}
// A re-review without instructions is not a request the gate can honour,
// and refusing it here keeps the refusal the operator's to read rather
// than a round trip's conflict. The service re-checks it for the surfaces
// that do not pass through this handler.
if action == taskstate.ActionRereview && strings.TrimSpace(req.Instructions) == "" {
http.Error(w, "a re-review needs instructions", http.StatusBadRequest)
return "", taskactions.ActionPayload{}, false
}
return action, taskactions.ActionPayload{Instructions: req.Instructions, Findings: req.Findings, RetryMode: taskstate.RetryMode(req.RetryMode), ResumeFrom: req.ResumeFrom}, true
}
func taskMutation(action taskstate.Action) bool {
switch action {
case taskstate.ActionCancel, taskstate.ActionStop, taskstate.ActionApprove,
taskstate.ActionReject, taskstate.ActionRereview, taskstate.ActionRetry,
taskstate.ActionAbandon, taskstate.ActionArchive, taskstate.ActionMerge:
return true
default:
return false
}
}
// authorizeTaskMutation requires JSON, a custom header and, when present, a
// same-origin Origin. Forwarded headers are trusted only with
// TrustForwardedHeaders.
func (s *Server) 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)
if err != nil {
http.Error(w, "cross-origin mutation refused", http.StatusForbidden)
return false
}
wantScheme, wantHost := s.expectedOrigin(r)
if !validOrigin(u, wantScheme, wantHost) {
http.Error(w, "cross-origin mutation refused", http.StatusForbidden)
return false
}
return true
}
func (s *Server) expectedOrigin(r *http.Request) (scheme, host string) {
scheme = "http"
if r.TLS != nil {
scheme = "https"
}
host = r.Host
if s == nil || !s.trustForwardedHeaders() {
return scheme, host
}
if proto := firstForwardedValue(r.Header.Get("X-Forwarded-Proto")); proto != "" {
scheme = strings.ToLower(proto)
}
if fHost := firstForwardedValue(r.Header.Get("X-Forwarded-Host")); fHost != "" {
host = fHost
}
return scheme, host
}
func firstForwardedValue(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
if first, _, ok := strings.Cut(raw, ","); ok {
raw = first
}
return strings.TrimSpace(raw)
}
func validOrigin(u *url.URL, wantScheme, wantHost string) bool {
if u == nil || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" {
return false
}
return strings.EqualFold(u.Scheme, wantScheme) && strings.EqualFold(u.Host, wantHost)
}
// applyOperatorTaskAction sends an operator's task action to the Gateway.
func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ActionPayload) error {
if s.Chat == nil || s.Chat.Contract == nil {
return fmt.Errorf("%w: no gateway contract is wired", taskactions.ErrUnavailable)
}
// The actor comes from the credential the middleware resolved and never from
// the request, so a caller cannot claim to be someone it did not authenticate
// as. An unauthenticated request (the shared-token gate) carries no identity,
// and the action is then recorded unattributed rather than as a human's.
actor := taskactions.Actor{}
if value, ok := ActingIdentity(ctx); ok {
actor = taskactions.ActorFor(value)
}
_, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action, res)
return 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(ctx context.Context, e events.Event) {
if e.Kind == "" {
return
}
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) {
if s.Log == nil {
return
}
s.Log.Warn(msg, args...)
}