diff --git a/internal/webui/server.go b/internal/webui/server.go index 342c7a8b8..454efa967 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -312,17 +312,7 @@ func (s *Server) registerCoreRoutes(mux *http.ServeMux) { } func (s *Server) registerTaskRoutes(mux *http.ServeMux) { - mux.HandleFunc("GET /api/tasks", s.handleTasks) - mux.HandleFunc("GET /api/task-meta", s.handleTaskMeta) - mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction) - mux.HandleFunc("GET /api/tasks/{id}", s.handleTask) - mux.HandleFunc("GET /api/tasks/{id}/attempts", s.handleTaskAttempts) - mux.HandleFunc("GET /api/tasks/{id}/changes", s.handleTaskChanges) - mux.HandleFunc("GET /api/tasks/{id}/debug", s.handleTaskDebug) - mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs) - mux.HandleFunc("GET /api/tasks/{id}/transcript", s.handleTaskTranscript) - mux.HandleFunc("GET /api/tasks/{id}/sandbox", s.handleTaskSandbox) - mux.HandleFunc("GET /api/tasks/{id}/logs/download", s.handleTaskLogDownload) + newTasksAPI(s).register(mux) } func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) { diff --git a/internal/webui/tasks.go b/internal/webui/tasks.go new file mode 100644 index 000000000..9d58c8825 --- /dev/null +++ b/internal/webui/tasks.go @@ -0,0 +1,60 @@ +package webui + +import ( + "log/slog" + "net/http" + + "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" +) + +// tasksAPI owns the /api/tasks routes and /api/task-meta. Optional +// dependencies (steps, taskLogs, sandbox, chat) stay nil-safe: each handler +// reports the feature unavailable rather than the module being absent. +type tasksAPI struct { + store storecontract.TaskStore + steps storecontract.StepReader + taskLogs TaskLogSource + sandbox SandboxView + chat *ChatService + log *slog.Logger + + authorize func(http.ResponseWriter, *http.Request) bool + configSource func() ConfigViewSource + recovery func(*http.Request, *task.Task) *taskRecoveryView +} + +func newTasksAPI(s *Server) *tasksAPI { + return &tasksAPI{ + store: s.Store, + steps: s.Steps, + taskLogs: s.TaskLogs, + sandbox: s.SandboxView, + chat: s.Chat, + log: s.Log, + authorize: s.authorizeTaskMutation, + configSource: s.configSource, + recovery: s.taskRecovery, + } +} + +func (a *tasksAPI) logf(msg string, args ...any) { + if a.log == nil { + return + } + a.log.Warn(msg, args...) +} + +func (a *tasksAPI) register(mux *http.ServeMux) { + mux.HandleFunc("GET /api/tasks", a.handleTasks) + mux.HandleFunc("GET /api/task-meta", a.handleTaskMeta) + mux.HandleFunc("POST /api/tasks/{id}/action", a.handleTaskAction) + mux.HandleFunc("GET /api/tasks/{id}", a.handleTask) + mux.HandleFunc("GET /api/tasks/{id}/attempts", a.handleTaskAttempts) + mux.HandleFunc("GET /api/tasks/{id}/changes", a.handleTaskChanges) + mux.HandleFunc("GET /api/tasks/{id}/debug", a.handleTaskDebug) + mux.HandleFunc("GET /api/tasks/{id}/logs", a.handleTaskLogs) + mux.HandleFunc("GET /api/tasks/{id}/transcript", a.handleTaskTranscript) + mux.HandleFunc("GET /api/tasks/{id}/sandbox", a.handleTaskSandbox) + mux.HandleFunc("GET /api/tasks/{id}/logs/download", a.handleTaskLogDownload) +} diff --git a/internal/webui/api_tasks_attempts.go b/internal/webui/tasks_attempts.go similarity index 95% rename from internal/webui/api_tasks_attempts.go rename to internal/webui/tasks_attempts.go index 6d6c9a317..028fca271 100644 --- a/internal/webui/api_tasks_attempts.go +++ b/internal/webui/tasks_attempts.go @@ -86,19 +86,19 @@ type taskAgentView struct { // handleTaskAttempts returns a task's attempts from its events, each with the // stages recorded as step executions. -func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) { - t, ok := s.taskByPathID(w, r) +func (a *tasksAPI) handleTaskAttempts(w http.ResponseWriter, r *http.Request) { + t, ok := a.taskByPathID(w, r) if !ok { return } - evs, err := s.Store.TaskEvents(r.Context(), t.ID) + evs, err := a.store.TaskEvents(r.Context(), t.ID) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } var steps []task.StepExecution - if s.Steps != nil { - steps, err = s.Steps.ListSteps(r.Context(), t.ID, 0) + if a.steps != nil { + steps, err = a.steps.ListSteps(r.Context(), t.ID, 0) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -117,7 +117,7 @@ func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) { Inputs: t.Inputs, Outputs: t.Outputs, CalledBy: t.CallParentTaskID, - Recovery: s.taskRecovery(r, t), + Recovery: a.recovery(r, t), }) } @@ -125,13 +125,13 @@ func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) { // request itself and reporting false when it cannot. An unknown task is 404 // plain text -- TaskByID says "no such row" the same way it says "here is the // row", so the distinction is drawn here rather than leaked to the page. -func (s *Server) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Task, bool) { +func (a *tasksAPI) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Task, bool) { id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.Error(w, "bad id", http.StatusBadRequest) return nil, false } - t, err := s.Store.TaskByID(r.Context(), id) + t, err := a.store.TaskByID(r.Context(), id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return nil, false @@ -145,8 +145,8 @@ func (s *Server) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Tas // taskAttemptTarget resolves the task in {id} and the requested attempt, // defaulting to the current one. -func (s *Server) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*task.Task, int, bool) { - t, ok := s.taskByPathID(w, r) +func (a *tasksAPI) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*task.Task, int, bool) { + t, ok := a.taskByPathID(w, r) if !ok { return nil, 0, false } diff --git a/internal/webui/api_tasks_attempts_test.go b/internal/webui/tasks_attempts_test.go similarity index 100% rename from internal/webui/api_tasks_attempts_test.go rename to internal/webui/tasks_attempts_test.go diff --git a/internal/webui/api_tasks_changes.go b/internal/webui/tasks_changes.go similarity index 97% rename from internal/webui/api_tasks_changes.go rename to internal/webui/tasks_changes.go index 6829a53e7..b62a76abd 100644 --- a/internal/webui/api_tasks_changes.go +++ b/internal/webui/tasks_changes.go @@ -100,12 +100,12 @@ func structKeys(t reflect.Type) map[string]struct{} { } // handleTaskChanges serves the changed files one attempt produced. -func (s *Server) handleTaskChanges(w http.ResponseWriter, r *http.Request) { - t, attempt, ok := s.taskAttemptTarget(w, r) +func (a *tasksAPI) handleTaskChanges(w http.ResponseWriter, r *http.Request) { + t, attempt, ok := a.taskAttemptTarget(w, r) if !ok { return } - evs, err := s.Store.TaskEvents(r.Context(), t.ID) + evs, err := a.store.TaskEvents(r.Context(), t.ID) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -116,7 +116,7 @@ func (s *Server) handleTaskChanges(w http.ResponseWriter, r *http.Request) { // re-derived: the capture's own owner/repo/pr decide the URL, so a capture // taken before the PR existed has no pull-request link instead of one // pointing at a later attempt's PR. - forge := s.resolveForge(r.Context()) + forge := a.resolveForge(r.Context()) for i := range captures { target := task.Task{ Owner: captures[i].Owner, Repo: captures[i].Repo, diff --git a/internal/webui/api_tasks_debug.go b/internal/webui/tasks_debug.go similarity index 82% rename from internal/webui/api_tasks_debug.go rename to internal/webui/tasks_debug.go index bd68aecca..74f30eec9 100644 --- a/internal/webui/api_tasks_debug.go +++ b/internal/webui/tasks_debug.go @@ -18,12 +18,12 @@ type taskDebugView struct { // handleTaskDebug serves the task's raw record together with its whole event // list, for whichever attempt the request names. -func (s *Server) handleTaskDebug(w http.ResponseWriter, r *http.Request) { - t, attempt, ok := s.taskAttemptTarget(w, r) +func (a *tasksAPI) handleTaskDebug(w http.ResponseWriter, r *http.Request) { + t, attempt, ok := a.taskAttemptTarget(w, r) if !ok { return } - evs, err := s.Store.TaskEvents(r.Context(), t.ID) + evs, err := a.store.TaskEvents(r.Context(), t.ID) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/internal/webui/api_tasks.go b/internal/webui/tasks_handlers.go similarity index 93% rename from internal/webui/api_tasks.go rename to internal/webui/tasks_handlers.go index d99eb1078..d426ab87b 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/tasks_handlers.go @@ -67,13 +67,13 @@ func needsAttentionStatuses() []string { // narrows it (needs_attention 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) { +func (a *tasksAPI) 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) + tasks, err := a.store.TasksPage(r.Context(), page) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -82,11 +82,11 @@ func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) { 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()) + forge := a.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), Approval: taskstate.ApprovalKind(tasks[i].Status, tasks[i].ReviewGate), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL, Recovery: s.taskRecovery(r, &tasks[i])} + views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), Approval: taskstate.ApprovalKind(tasks[i].Status, tasks[i].ReviewGate), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL, Recovery: a.recovery(r, &tasks[i])} } writeJSON(w, views) } @@ -144,9 +144,9 @@ type forgeCoordinates struct { // resolveForge returns a function mapping a task to the instance forge. A // multi-identity install withholds links: its tasks reach forges through // organisation connections this projection does not carry. -func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates { +func (a *tasksAPI) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates { unlinked := func(task.Task) forgeCoordinates { return forgeCoordinates{} } - view, ok, err := s.configSource()(ctx) + view, ok, err := a.configSource()(ctx) if err != nil || !ok || view.MultiIdentity { return unlinked } @@ -172,13 +172,13 @@ func taskURLs(task task.Task, forge forgeCoordinates) (repoURL, issueURL, prURL return repoURL, issueURL, prURL } -func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) { +func (a *tasksAPI) 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) + evs, err := a.store.TaskEvents(r.Context(), id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -206,8 +206,8 @@ type taskActionRequest struct { CurrentDefinition bool `json:"current_definition"` } -func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { - if !s.authorizeTaskMutation(w, r) { +func (a *tasksAPI) handleTaskAction(w http.ResponseWriter, r *http.Request) { + if !a.authorize(w, r) { return } id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) @@ -219,7 +219,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { if !ok { return } - if err := s.applyOperatorTaskAction(r.Context(), id, action, res); err != nil { + if err := a.applyOperatorTaskAction(r.Context(), id, action, res); err != nil { switch { case errors.Is(err, taskactions.ErrNotFound): http.Error(w, "task not found", http.StatusNotFound) @@ -229,7 +229,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { case errors.Is(err, taskactions.ErrUnavailable): http.Error(w, err.Error(), http.StatusServiceUnavailable) default: - s.logf("task action failed", "task", id, "err", err) + a.logf("task action failed", "task", id, "err", err) http.Error(w, "task action failed", http.StatusInternalServerError) } return @@ -348,8 +348,8 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool { } // 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 { +func (a *tasksAPI) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ActionPayload) error { + if a.chat == nil || a.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 @@ -360,7 +360,7 @@ func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action t if value, ok := ActingIdentity(ctx); ok { actor = taskactions.ActorFor(value) } - _, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action, res) + _, err := a.chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action, res) return err } diff --git a/internal/webui/api_tasks_logs.go b/internal/webui/tasks_logs.go similarity index 90% rename from internal/webui/api_tasks_logs.go rename to internal/webui/tasks_logs.go index 04b453b83..fe07827ba 100644 --- a/internal/webui/api_tasks_logs.go +++ b/internal/webui/tasks_logs.go @@ -14,12 +14,12 @@ import ( // handleTaskLogs serves one attempt's log history, defaulting to the current // attempt. No reader reports disabled; no log file reports found=false. -func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) { - id, attempt, ok := s.taskLogTarget(w, r) +func (a *tasksAPI) handleTaskLogs(w http.ResponseWriter, r *http.Request) { + id, attempt, ok := a.taskLogTarget(w, r) if !ok { return } - reader := s.taskLogReader() + reader := a.taskLogs if reader == nil { writeDisabledTaskLogs(w, attempt) return @@ -83,12 +83,12 @@ func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) { // handleTaskLogDownload serves one attempt's raw log as a download. No reader // answers 503. -func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) { - id, attempt, ok := s.taskLogTarget(w, r) +func (a *tasksAPI) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) { + id, attempt, ok := a.taskLogTarget(w, r) if !ok { return } - reader := s.taskLogReader() + reader := a.taskLogs if reader == nil { http.Error(w, logging.ErrTaskLogsUnavailable.Error(), http.StatusServiceUnavailable) return @@ -114,7 +114,7 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) { // Once a 200 and a body are on the wire there is no status left to // send, so a failure partway through is logged where an operator can // find it rather than silently truncating the file. - s.logf("task log download failed", "task", id, "attempt", attempt, "err", err) + a.logf("task log download failed", "task", id, "attempt", attempt, "err", err) return } if !found { @@ -125,8 +125,8 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) { // taskLogTarget resolves the task and attempt for a log read, answering the // request itself on failure. -func (s *Server) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) { - t, attempt, ok := s.taskAttemptTarget(w, r) +func (a *tasksAPI) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) { + t, attempt, ok := a.taskAttemptTarget(w, r) if !ok { return 0, 0, false } @@ -206,14 +206,6 @@ func taskLogFilename(taskID int64, attempt int) string { return "task-" + strconv.FormatInt(taskID, 10) + "-attempt-" + strconv.Itoa(attempt) + ".log" } -// taskLogReader returns this process's task-log reader, or nil. -func (s *Server) taskLogReader() TaskLogSource { - if s == nil { - return nil - } - return s.TaskLogs -} - // TaskLogSource is the read seam the task-log handlers consume. It is the // logging package's own reader contract, so a registry and a remote client // satisfy it without either one restating the log format -- the package that diff --git a/internal/webui/api_task_meta.go b/internal/webui/tasks_meta.go similarity index 96% rename from internal/webui/api_task_meta.go rename to internal/webui/tasks_meta.go index a47e39d3a..32b3e2958 100644 --- a/internal/webui/api_task_meta.go +++ b/internal/webui/tasks_meta.go @@ -47,6 +47,6 @@ func buildTaskMeta() taskMetaView { } // handleTaskMeta serves the catalog. See buildTaskMeta for what it carries. -func (s *Server) handleTaskMeta(w http.ResponseWriter, _ *http.Request) { +func (a *tasksAPI) handleTaskMeta(w http.ResponseWriter, _ *http.Request) { writeJSON(w, buildTaskMeta()) } diff --git a/internal/webui/api_tasks_sandbox.go b/internal/webui/tasks_sandbox.go similarity index 87% rename from internal/webui/api_tasks_sandbox.go rename to internal/webui/tasks_sandbox.go index 0fefb6533..361f1e16d 100644 --- a/internal/webui/api_tasks_sandbox.go +++ b/internal/webui/tasks_sandbox.go @@ -24,8 +24,8 @@ type SandboxView interface { // handleTaskSandbox streams a running attempt's sandbox output to a WebSocket. // Reading it is the same authority as reading the task's log, decided before // this handler runs. Input from the browser is discarded: a view has no stdin. -func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) { - if s.SandboxView == nil { +func (a *tasksAPI) handleTaskSandbox(w http.ResponseWriter, r *http.Request) { + if a.sandbox == nil { http.Error(w, "sandbox view not configured", http.StatusServiceUnavailable) return } @@ -33,7 +33,7 @@ func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) { http.Error(w, "websocket upgrade required", http.StatusUpgradeRequired) return } - t, attempt, ok := s.taskAttemptTarget(w, r) + t, attempt, ok := a.taskAttemptTarget(w, r) if !ok { return } @@ -46,9 +46,9 @@ func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithCancel(ws.Request().Context()) defer cancel() go func() { _, _ = io.Copy(io.Discard, ws); cancel() }() - view, err := s.SandboxView.OpenRun(ctx, string(org.OrgFromContext(ws.Request().Context())), t.ID, int64(attempt)) + view, err := a.sandbox.OpenRun(ctx, string(org.OrgFromContext(ws.Request().Context())), t.ID, int64(attempt)) if err != nil { - s.logf("open sandbox view", "err", err, "task", t.ID, "attempt", attempt) + a.logf("open sandbox view", "err", err, "task", t.ID, "attempt", attempt) _, _ = io.WriteString(ws, sandboxRefusal(err)) return } diff --git a/internal/webui/api_tasks_sandbox_test.go b/internal/webui/tasks_sandbox_test.go similarity index 96% rename from internal/webui/api_tasks_sandbox_test.go rename to internal/webui/tasks_sandbox_test.go index b06634458..20c79472e 100644 --- a/internal/webui/api_tasks_sandbox_test.go +++ b/internal/webui/tasks_sandbox_test.go @@ -45,8 +45,9 @@ func TestSandboxStreamLifetime(t *testing.T) { pr, pw := io.Pipe() view := &sandboxStream{PipeReader: pr, closed: make(chan struct{})} s := &Server{Store: sandboxTasks{}, SandboxView: view} + a := newTasksAPI(s) mux := http.NewServeMux() - mux.HandleFunc("GET /api/tasks/{id}/sandbox", s.handleTaskSandbox) + mux.HandleFunc("GET /api/tasks/{id}/sandbox", a.handleTaskSandbox) server := httptest.NewServer(mux) defer server.Close() defer view.Close() diff --git a/internal/webui/api_tasks_test.go b/internal/webui/tasks_test.go similarity index 100% rename from internal/webui/api_tasks_test.go rename to internal/webui/tasks_test.go diff --git a/internal/webui/api_tasks_transcript.go b/internal/webui/tasks_transcript.go similarity index 76% rename from internal/webui/api_tasks_transcript.go rename to internal/webui/tasks_transcript.go index c57f498c4..c202f9c60 100644 --- a/internal/webui/api_tasks_transcript.go +++ b/internal/webui/tasks_transcript.go @@ -14,12 +14,12 @@ type taskTranscriptView struct { Entries []events.Event `json:"entries"` } -func (s *Server) handleTaskTranscript(w http.ResponseWriter, r *http.Request) { - t, attempt, ok := s.taskAttemptTarget(w, r) +func (a *tasksAPI) handleTaskTranscript(w http.ResponseWriter, r *http.Request) { + t, attempt, ok := a.taskAttemptTarget(w, r) if !ok { return } - entries, err := s.Store.TaskTranscript(r.Context(), t.ID, attempt) + entries, err := a.store.TaskTranscript(r.Context(), t.ID, attempt) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return