feat(webui): route dashboard task actions through the Gateway contract

The dashboard composed its own taskactions.Service over whatever handles
happened to be set on webui.Server. In the extracted UI process those are
all nil, and each nil silently removes a guarantee: no Cfg means max_retries
stops being enforced, no Issues means a rejected task's forge issue stays
open and the poller re-enqueues it, no Events means operator actions never
reach the timeline, no TaskStopper means Stop cannot interrupt running work.
The handler now asks whoever owns task execution, through
ApplyOperatorTaskAction, and Issues/TaskStopper leave the dashboard entirely.

That path crosses two hops that both flatten errors, so the sentinels the
handler maps to 404/409/503 travel explicitly: a kind beside the message on
the NATS envelope, a gRPC code on the Gateway contract, each restored on
arrival. Without them a task that simply moved on reports as a broken daemon.

The action tests keep running the real service, now behind a local contract
the way the daemon serves it in production, so retry limits, forge closure,
events, archiving and log removal stay covered where they were.
This commit is contained in:
sam committed 2026-09-09 23:29:11 +10:00
1 parent 4e641478c2
commit fcf64a610d
14 files changed
+512 -84

No files matched your search

-5
View File
@@ -400,10 +400,6 @@ func (b *boot) setupObservability() {
}
return b.restartTelegram()
}
// The dashboard closes the forge issue behind a rejected task, or the
// issue is re-polled and the work is done again. It gets only that one
// method, not the forge client.
b.web.Issues = b.forgeClient
b.wireWebStoreSurfaces()
sink := bus.Subscribe(256)
go persistAndBroadcastEvents(sink, b.stateStore, b.web, log)
@@ -1286,7 +1282,6 @@ func (b *boot) buildDaemon() {
TaskLogs: b.taskLogs,
AgentStatus: b.agentStatus,
}
b.web.TaskStopper = b.d
// Curator observability (archie-core-1786637489932-6): GET
// /api/curators reads registered names, health and recent activity
// straight off the live registry the daemon already holds.
+11 -1
View File
@@ -3,6 +3,7 @@ package archied
import (
"bytes"
"context"
"log/slog"
"net/http"
"net/http/httptest"
"path/filepath"
@@ -100,7 +101,16 @@ func runChatAction(t *testing.T, ctx context.Context, st store.TaskStore, action
// rejected.
func runDashboardAction(t *testing.T, ctx context.Context, st store.TaskStore, action string, taskID int64) {
t.Helper()
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{MaxRetries: 3})}
// The dashboard reaches task actions through the Gateway contract, which
// in production carries them back to this daemon's own service. Wiring
// that service behind a local adapter keeps both surfaces in this test
// driving the one implementation, which is the whole point of it.
actor := testTaskActor{&boot{st: st, stateStore: st, cfg: config.Config{MaxRetries: 3}, log: slog.New(slog.DiscardHandler)}}
srv := &webui.Server{
Store: st,
Cfg: config.NewHolder(config.Config{MaxRetries: 3}),
Chat: &webui.ChatService{Contract: &gateway.LocalChatAdapter{TaskActor: actor}},
}
req := httptest.NewRequestWithContext(ctx, http.MethodPost,
"/api/tasks/"+strconv.FormatInt(taskID, 10)+"/action",
bytes.NewBufferString(`{"action":"`+action+`"}`))
+2 -2
View File
@@ -34,8 +34,8 @@ type deps struct {
// through a narrow admin contract. The shared holder is removed from the
// daemon's own wiring by archie-core-8cda.5.4.
// - LogFeed, TaskLogs, Events, Channels, ReloadChannel, Curators, Memory,
// Issues, TaskStopper, Workflows, WorkRequests, RunningVersions,
// Chat.Updates, UpdateReportPath: no contract exists for these yet.
// Workflows, WorkRequests, RunningVersions, Chat.Updates,
// UpdateReportPath: no contract exists for these yet.
// Defining one amends the owning service's contract first
// (docs/prds/ui-service-boundary.md:205-207); the route migration is
// archie-core-8cda.5.3.
-2
View File
@@ -84,8 +84,6 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
"LastReload": srv.LastReload,
"ReloadChannel": srv.ReloadChannel,
"RunningVersions": srv.RunningVersions,
"TaskStopper": srv.TaskStopper,
"Issues": srv.Issues,
"Events": srv.Events,
"Curators": srv.Curators,
"Memory": srv.Memory,
+2 -2
View File
@@ -85,7 +85,7 @@ func (c *Client) SetPersona(ctx context.Context, id, name string) (bool, error)
func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action) (gateway.TaskActionResult, error) {
v, err := c.client.ApplyTaskAction(ctx, &pb.ApplyTaskActionRequest{Identity: identity, TaskId: taskID, Action: string(action)})
if err != nil {
return gateway.TaskActionResult{}, err
return gateway.TaskActionResult{}, taskActionError(err)
}
return gateway.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil
}
@@ -93,7 +93,7 @@ func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID in
func (c *Client) ApplyOperatorTaskAction(ctx context.Context, taskID int64, action taskstate.Action) (gateway.TaskActionResult, error) {
v, err := c.client.ApplyOperatorTaskAction(ctx, &pb.ApplyOperatorTaskActionRequest{TaskId: taskID, Action: string(action)})
if err != nil {
return gateway.TaskActionResult{}, err
return gateway.TaskActionResult{}, taskActionError(err)
}
return gateway.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil
}
@@ -2,8 +2,11 @@ package gatewayrpc
import (
"context"
"errors"
"fmt"
"net"
"reflect"
"strings"
"testing"
"time"
@@ -12,7 +15,9 @@ import (
"google.golang.org/grpc/test/bufconn"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -166,3 +171,45 @@ func TestTaskActionScopeSurvivesTheWire(t *testing.T) {
})
}
}
// failingTaskActor reports one error, whatever the action.
type failingTaskActor struct{ err error }
func (a failingTaskActor) ApplyChatTaskAction(
context.Context, *string, int64, taskstate.Action,
) (gateway.TaskActionResult, error) {
return gateway.TaskActionResult{}, a.err
}
// TestTaskActionErrorsKeepTheirSentinelOverGRPC: the dashboard answers 404,
// 409 or 503 by matching these sentinels, and gRPC carries a code and a
// string, not a Go error. Losing the class here turns "that task already
// moved on" into "the daemon is broken".
func TestTaskActionErrorsKeepTheirSentinelOverGRPC(t *testing.T) {
for _, tc := range []struct {
name string
err error
}{
{name: "not found", err: fmt.Errorf("task 7: %w", taskactions.ErrNotFound)},
{name: "conflict", err: fmt.Errorf("%w: action \"approve\" is not available while task is parked", taskactions.ErrConflict)},
{name: "stale transition", err: fmt.Errorf("stop task 7: %w", store.ErrStaleTransition)},
{name: "unavailable", err: taskactions.ErrUnavailable},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := t.Context()
local := &gateway.LocalChatAdapter{TaskActor: failingTaskActor{err: tc.err}}
chat := remoteChat(t, local)
_, err := chat.ApplyOperatorTaskAction(ctx, 7, taskstate.ActionApprove)
if err == nil {
t.Fatalf("ApplyOperatorTaskAction error = nil, want %v", tc.err)
}
if !errors.Is(err, errors.Unwrap(tc.err)) && !errors.Is(err, tc.err) {
t.Fatalf("error %v is not the daemon's sentinel %v", err, tc.err)
}
if !strings.Contains(err.Error(), tc.err.Error()) {
t.Fatalf("error message = %q, want it to carry the daemon's %q", err.Error(), tc.err.Error())
}
})
}
}
+2 -2
View File
@@ -93,7 +93,7 @@ func (s *server) SetPersona(ctx context.Context, r *pb.SetPersonaRequest) (*pb.S
func (s *server) ApplyTaskAction(ctx context.Context, r *pb.ApplyTaskActionRequest) (*pb.ApplyTaskActionResponse, error) {
v, err := s.chat.ApplyTaskAction(ctx, r.Identity, r.TaskId, taskstate.Action(r.Action))
if err != nil {
return nil, err
return nil, taskActionStatus(err)
}
return &pb.ApplyTaskActionResponse{TaskId: v.TaskID, Action: v.Action, Message: v.Message}, nil
}
@@ -101,7 +101,7 @@ func (s *server) ApplyTaskAction(ctx context.Context, r *pb.ApplyTaskActionReque
func (s *server) ApplyOperatorTaskAction(ctx context.Context, r *pb.ApplyOperatorTaskActionRequest) (*pb.ApplyOperatorTaskActionResponse, error) {
v, err := s.chat.ApplyOperatorTaskAction(ctx, r.TaskId, taskstate.Action(r.Action))
if err != nil {
return nil, err
return nil, taskActionStatus(err)
}
return &pb.ApplyOperatorTaskActionResponse{TaskId: v.TaskID, Action: v.Action, Message: v.Message}, nil
}
@@ -0,0 +1,71 @@
package gatewayrpc
import (
"errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/store"
)
// taskActionCodes pairs each sentinel the daemon's action service reports
// with the gRPC code that carries it. The dashboard picks its HTTP status by
// matching these (404, 409, 503), and gRPC transports a code and a string,
// not a Go error, so the class travels as the code and is restored on
// arrival. Adding a sentinel a caller matches on without adding it here
// silently degrades that case to a 500.
var taskActionCodes = []struct {
code codes.Code
err error
}{
{code: codes.NotFound, err: taskactions.ErrNotFound},
{code: codes.FailedPrecondition, err: taskactions.ErrConflict},
{code: codes.Aborted, err: store.ErrStaleTransition},
{code: codes.Unavailable, err: taskactions.ErrUnavailable},
}
// taskActionStatus classifies an action error for the wire, keeping the
// daemon's own wording as the status message.
func taskActionStatus(err error) error {
if err == nil {
return nil
}
for _, candidate := range taskActionCodes {
if errors.Is(err, candidate.err) {
return status.Error(candidate.code, err.Error())
}
}
return err
}
// remoteTaskActionError restores a classified error on the caller's side,
// keeping the message the daemon produced.
type remoteTaskActionError struct {
message string
sentinel error
}
func (e remoteTaskActionError) Error() string { return e.message }
func (e remoteTaskActionError) Unwrap() error { return e.sentinel }
// taskActionError is taskActionStatus's inverse. A code with no sentinel
// behind it (including a transport failure) is returned untouched, so an
// unclassified failure stays a server error rather than being dressed up as
// a known one.
func taskActionError(err error) error {
if err == nil {
return nil
}
reported, ok := status.FromError(err)
if !ok {
return err
}
for _, candidate := range taskActionCodes {
if reported.Code() == candidate.code {
return remoteTaskActionError{message: reported.Message(), sentinel: candidate.err}
}
}
return err
}
+53 -2
View File
@@ -3,6 +3,7 @@ package taskactions
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"
@@ -12,6 +13,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/natsrpc"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -29,8 +31,54 @@ type actionRequest struct {
Action taskstate.Action `json:"action"`
}
// actionResponse carries the error's class beside its message. This hop
// reduces an error to a JSON string, and the dashboard chooses its HTTP
// status from the sentinel (404, 409, 503), so the class has to cross
// explicitly or every failure arrives as an opaque 500.
type actionResponse struct {
natsrpc.Envelope
Kind string `json:"kind,omitempty"`
}
// actionErrorKinds names the sentinels a caller matches on. Anything absent
// crosses as a message alone, which is the honest result: an unclassified
// failure is a server error at every consumer.
var actionErrorKinds = []struct {
kind string
err error
}{
{kind: "not_found", err: taskactions.ErrNotFound},
{kind: "conflict", err: taskactions.ErrConflict},
{kind: "stale_transition", err: store.ErrStaleTransition},
{kind: "unavailable", err: taskactions.ErrUnavailable},
}
func actionErrorKind(err error) string {
for _, candidate := range actionErrorKinds {
if errors.Is(err, candidate.err) {
return candidate.kind
}
}
return ""
}
// remoteActionError restores a sentinel the daemon reported, keeping the
// daemon's own wording as the message.
type remoteActionError struct {
message string
sentinel error
}
func (e remoteActionError) Error() string { return e.message }
func (e remoteActionError) Unwrap() error { return e.sentinel }
func actionErrorFor(kind string, err error) error {
for _, candidate := range actionErrorKinds {
if candidate.kind == kind {
return remoteActionError{message: err.Error(), sentinel: candidate.err}
}
}
return err
}
// Register exposes only identity-scoped operator actions on the daemon. The
@@ -49,7 +97,10 @@ func Register(nc *nats.Conn, service taskactions.Service, log *slog.Logger) (fun
return
}
err := service.Apply(context.Background(), req.Identity, req.TaskID, req.Action)
natsrpc.Respond(msg, log, "taskactions", actionResponse{Envelope: natsrpc.NewEnvelope(err)})
natsrpc.Respond(msg, log, "taskactions", actionResponse{
Envelope: natsrpc.NewEnvelope(err),
Kind: actionErrorKind(err),
})
},
}})
}
@@ -74,7 +125,7 @@ func (c Client) ApplyChatTaskAction(ctx context.Context, identity *string, id in
return gateway.TaskActionResult{}, err
}
if err := resp.Err(); err != nil {
return gateway.TaskActionResult{}, err
return gateway.TaskActionResult{}, actionErrorFor(resp.Kind, err)
}
return gateway.TaskActionResult{TaskID: id, Action: string(action), Message: fmt.Sprintf("Applied %s to task %d.", action, id)}, nil
}
@@ -0,0 +1,167 @@
package taskactions
import (
"context"
"errors"
"log/slog"
"testing"
"github.com/nats-io/nats-server/v2/server"
natssrv "github.com/nats-io/nats-server/v2/test"
"github.com/nats-io/nats.go"
domain "github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
)
func startEmbedded(t *testing.T) *server.Server {
t.Helper()
srv := natssrv.RunRandClientPortServer()
t.Cleanup(srv.Shutdown)
return srv
}
func connect(t *testing.T, url string) *nats.Conn {
t.Helper()
nc, err := nats.Connect(url)
if err != nil {
t.Fatalf("nats connect: %v", err)
}
t.Cleanup(nc.Close)
return nc
}
// stubStore returns one task, or none, and fails every mutation with err.
type stubStore struct {
task *domain.Task
err error
}
func (s stubStore) TaskByID(context.Context, int64) (*domain.Task, error) { return s.task, nil }
func (s stubStore) Transition(context.Context, int64, string, string, string) error { return s.err }
func (s stubStore) Requeue(context.Context, int64, string, string) error { return s.err }
func (s stubStore) RetryTask(context.Context, int64, string, string) error { return s.err }
func (s stubStore) ArchiveTask(context.Context, int64, string, events.Event) (int64, error) {
return 0, s.err
}
func (s stubStore) InsertEvent(context.Context, events.Event) (int64, error) { return 0, s.err }
// TestActionErrorKeepsItsSentinelAcrossNATS: the dashboard picks its HTTP
// status from these sentinels (404, 409, 503), and this hop reduces an error
// to a JSON string. Without a kind alongside the message every failure
// arrives indistinguishable and the operator is told to check the daemon
// over a task that simply moved on.
func TestActionErrorKeepsItsSentinelAcrossNATS(t *testing.T) {
parked := &domain.Task{ID: 7, Owner: "acme", Repo: "widget", Status: "parked"}
running := &domain.Task{ID: 7, Owner: "acme", Repo: "widget", Status: "running"}
for _, tc := range []struct {
name string
store stubStore
cancel func(int64) bool
action taskstate.Action
want error
}{
{
name: "missing task",
store: stubStore{},
action: taskstate.ActionAbandon,
want: domain.ErrNotFound,
},
{
name: "action the status forbids",
store: stubStore{task: parked},
action: taskstate.ActionApprove,
want: domain.ErrConflict,
},
{
name: "no runtime control wired",
store: stubStore{task: running},
action: taskstate.ActionStop,
want: domain.ErrUnavailable,
},
{
name: "store refused a stale transition",
store: stubStore{task: running, err: store.ErrStaleTransition},
cancel: func(int64) bool { return true },
action: taskstate.ActionStop,
want: store.ErrStaleTransition,
},
} {
t.Run(tc.name, func(t *testing.T) {
srv := startEmbedded(t)
nc := connect(t, srv.ClientURL())
service := domain.Service{Store: tc.store, CancelTask: tc.cancel, Warn: func(string, ...any) {}}
stop, err := Register(nc, service, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("register responder: %v", err)
}
t.Cleanup(stop)
if err := nc.Flush(); err != nil {
t.Fatalf("flush: %v", err)
}
_, err = Client{Conn: nc}.ApplyChatTaskAction(t.Context(), nil, 7, tc.action)
if err == nil {
t.Fatalf("ApplyChatTaskAction(%s) error = nil, want %v", tc.action, tc.want)
}
if !errors.Is(err, tc.want) {
t.Fatalf("error %v (%T) is not %v", err, err, tc.want)
}
// The wording the operator reads survives too, not just the class.
direct := service.Apply(t.Context(), nil, 7, tc.action)
if direct == nil || err.Error() != direct.Error() {
t.Fatalf("remote message = %q, want the daemon's own %v", err.Error(), direct)
}
})
}
}
// TestActionScopeCrossesNATS pins the operator scope over the same hop: a nil
// identity is an authenticated dashboard operator, and JSON has to carry that
// absence rather than an empty name. The service records which one acted, so
// the timeline is the observable.
func TestActionScopeCrossesNATS(t *testing.T) {
for _, tc := range []struct {
name string
identity *string
want string
}{
{name: "operator", want: "abandoned via the dashboard"},
{name: "chat identity", identity: new("scout"), want: "abandoned via chat"},
} {
t.Run(tc.name, func(t *testing.T) {
srv := startEmbedded(t)
nc := connect(t, srv.ClientURL())
var published events.Event
service := domain.Service{
Store: stubStore{task: &domain.Task{ID: 7, Owner: "acme", Repo: "widget", Identity: "scout", Status: "parked"}},
Publish: func(e events.Event) { published = e },
}
stop, err := Register(nc, service, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("register responder: %v", err)
}
t.Cleanup(stop)
if err := nc.Flush(); err != nil {
t.Fatalf("flush: %v", err)
}
result, err := Client{Conn: nc}.ApplyChatTaskAction(t.Context(), tc.identity, 7, taskstate.ActionAbandon)
if err != nil {
t.Fatalf("apply: %v", err)
}
if result.TaskID != 7 {
t.Fatalf("result = %+v, want task 7", result)
}
if published.Detail != tc.want {
t.Fatalf("event detail = %q, want %q", published.Detail, tc.want)
}
})
}
}
+16 -41
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
@@ -15,7 +16,6 @@ import (
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -148,7 +148,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if err := s.TaskActionService().Apply(r.Context(), nil, id, action); err != nil {
if err := s.applyOperatorTaskAction(r.Context(), id, action); err != nil {
switch {
case errors.Is(err, taskactions.ErrNotFound):
http.Error(w, "task not found", http.StatusNotFound)
@@ -275,46 +275,21 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool {
return strings.EqualFold(u.Scheme, wantScheme) && strings.EqualFold(u.Host, wantHost)
}
// TaskActionService supplies the same operator action implementation used by
// the daemon's task-control endpoint.
func (s *Server) TaskActionService() taskactions.Service {
return taskactionstore.NewService(
taskactionstore.Store{TaskStore: s.Store},
taskactionstore.MaxRetries(s.Cfg),
s.taskStopper(),
s.issueCloser(),
s.logRemover(),
s.eventPublisher(),
s.logf,
)
}
func (s *Server) taskStopper() func(int64) bool {
if s.TaskStopper == nil {
return nil
// applyOperatorTaskAction sends the action to whoever owns task execution.
// The dashboard operator is authenticated and acts across identities, which
// the Gateway contract carries as its own method (archie-core-8cda.5.4).
//
// The UI process cannot run this itself: retry limits come from the daemon's
// configuration, closing the forge issue needs its forge client, the
// timeline needs its event bus, and stopping running work needs the
// goroutine or container that is executing it. Composing a local service
// over the task store alone would silently drop all four.
func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action) error {
if s.Chat == nil || s.Chat.Contract == nil {
return fmt.Errorf("%w: no gateway contract is wired", taskactions.ErrUnavailable)
}
return s.TaskStopper.CancelTask
}
func (s *Server) issueCloser() func(context.Context, string, string, int, string) error {
if s.Issues == nil {
return nil
}
return s.Issues.CloseIssue
}
func (s *Server) logRemover() func(int64) error {
if s.TaskLogs == nil {
return nil
}
return s.TaskLogs.Remove
}
func (s *Server) eventPublisher() func(events.Event) {
if s.Events == nil {
return nil
}
return s.Events.Publish
_, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, id, action)
return err
}
// emit publishes an operator action so it reaches the task timeline and the
+135 -4
View File
@@ -17,8 +17,11 @@ import (
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// recordingCloser captures the forge issue-closure calls an action makes.
@@ -38,6 +41,93 @@ func (r *recordingCloser) CloseIssue(_ context.Context, owner, repo string, numb
return r.err
}
// daemonActions stands in for the daemon behind the Gateway contract. The
// dashboard no longer composes a task-action service of its own: it asks
// whoever owns task execution, reaching the same taskactions.Service over
// gRPC and NATS in production (internal/infrastructure/taskactions). Running
// that service directly here keeps these tests on real behaviour -- retry
// limits, forge closure, timeline events, archiving -- rather than on a stub
// that would agree with any handler.
//
// The service is rebuilt per call because tests attach collaborators after
// the server exists, exactly as the daemon rebuilds it per request.
type daemonActions struct {
srv *Server
issues *recordingCloser
stopper *recordingTaskStopper
// scopes records the identity each action arrived with, one per call.
scopes []*string
}
func (d *daemonActions) ApplyChatTaskAction(
ctx context.Context, identity *string, id int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
d.scopes = append(d.scopes, identity)
service := taskactionstore.NewService(
taskactionstore.Store{TaskStore: d.srv.Store},
taskactionstore.MaxRetries(d.srv.Cfg),
d.cancelTask(),
d.closeIssue(),
d.removeLogs(),
d.publish(),
d.srv.logf,
)
if err := service.Apply(ctx, identity, id, action); err != nil {
return gateway.TaskActionResult{}, err
}
return gateway.TaskActionResult{TaskID: id, Action: string(action)}, nil
}
func (d *daemonActions) cancelTask() func(int64) bool {
if d.stopper == nil {
return nil
}
return d.stopper.CancelTask
}
func (d *daemonActions) closeIssue() func(context.Context, string, string, int, string) error {
if d.issues == nil {
return nil
}
return d.issues.CloseIssue
}
func (d *daemonActions) removeLogs() func(int64) error {
if d.srv.TaskLogs == nil {
return nil
}
return d.srv.TaskLogs.Remove
}
func (d *daemonActions) publish() func(events.Event) {
if d.srv.Events == nil {
return nil
}
return d.srv.Events.Publish
}
// wireOperatorActions gives srv a task-action owner, the way composition
// gives the dashboard a Gateway contract.
func wireOperatorActions(srv *Server) *daemonActions {
actions := &daemonActions{srv: srv}
srv.Chat = &ChatService{Contract: &gateway.LocalChatAdapter{TaskActor: actions}}
return actions
}
// operatorActions returns the stand-in daemon behind srv's contract.
func operatorActions(t *testing.T, srv *Server) *daemonActions {
t.Helper()
local, ok := srv.Chat.Contract.(*gateway.LocalChatAdapter)
if !ok {
t.Fatalf("chat contract is %T, want the local adapter these tests wire", srv.Chat.Contract)
}
actions, ok := local.TaskActor.(*daemonActions)
if !ok {
t.Fatalf("task actor is %T, want the stand-in daemon", local.TaskActor)
}
return actions
}
// 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, *workflow.Task, *recordingCloser, *events.Bus, *events.Sub) {
@@ -61,7 +151,7 @@ func actionServer(t *testing.T, status, parkReason string) (*Server, *workflow.T
t.Cleanup(bus.Close)
sub := bus.Subscribe(16)
srv.Issues = closer
operatorActions(t, srv).issues = closer
srv.Events = bus
srv.Cfg = config.NewHolder(config.Config{MaxRetries: 3})
return srv, task, closer, bus, sub
@@ -105,7 +195,7 @@ func (s *recordingTaskStopper) CancelTask(id int64) bool {
func setTaskStopper(t *testing.T, srv *Server, stopper *recordingTaskStopper) {
t.Helper()
srv.TaskStopper = stopper
operatorActions(t, srv).stopper = stopper
}
// max_retries is configured, defaulted and shown in /api/config, but nothing
@@ -203,7 +293,7 @@ func TestRejectDoesNotCloseAChatTaskIssue(t *testing.T) {
srv := newTestServer(t)
ctx := t.Context()
closer := &recordingCloser{}
srv.Issues = closer
operatorActions(t, srv).issues = closer
srv.Cfg = config.NewHolder(config.Config{MaxRetries: 3})
task, err := srv.Store.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "")
@@ -368,6 +458,46 @@ func TestTaskActionErrorMapping(t *testing.T) {
}
}
// TestTaskActionIsUnscopedAndRemote covers what routing through the Gateway
// contract has to preserve: the dashboard operator is authenticated and acts
// across identities, so the action must arrive unscoped rather than claiming
// some identity of the UI process's own invention.
func TestTaskActionIsUnscopedAndRemote(t *testing.T) {
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
if w := postAction(t, srv, task.ID, "approve"); w.Code != http.StatusOK {
t.Fatalf("status = %d, body %s", w.Code, w.Body)
}
actions := operatorActions(t, srv)
if len(actions.scopes) != 1 {
t.Fatalf("task-action owner saw %d calls, want the handler to have made exactly 1", len(actions.scopes))
}
if actions.scopes[0] != nil {
t.Fatalf("dashboard action arrived scoped to %q, want an unscoped operator", *actions.scopes[0])
}
}
// TestTaskActionWithoutAContractIsUnavailable: the dashboard has no local
// task-action implementation to fall back on, and must say so rather than
// half-applying an action over the task store it can reach.
func TestTaskActionWithoutAContractIsUnavailable(t *testing.T) {
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
srv.Chat = nil
w := postAction(t, srv, task.ID, "approve")
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503 with no gateway contract wired", 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 != workflow.StatusWaitingHuman {
t.Fatalf("task status = %q, want it untouched at %q", got.Status, workflow.StatusWaitingHuman)
}
}
// A store write failure is a 500, not a 409.
func TestTaskActionStoreFailureIs500(t *testing.T) {
base := newTestServer(t)
@@ -388,6 +518,7 @@ func TestTaskActionStoreFailureIs500(t *testing.T) {
Log: base.Log,
Cfg: config.NewHolder(config.Config{MaxRetries: 3}),
}
wireOperatorActions(srv)
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)
@@ -481,7 +612,7 @@ func TestLifecycleSpecificTaskActions(t *testing.T) {
}
}
closer := &recordingCloser{}
srv.Issues = closer
operatorActions(t, srv).issues = closer
bus := events.NewBus()
t.Cleanup(bus.Close)
srv.Events = bus
-22
View File
@@ -133,23 +133,11 @@ 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
// TaskStopper reaches work that is actually executing. A store row cannot
// stop a goroutine or container; the daemon supplies this narrow runtime
// seam so the Stop action cancels work before parking its task record.
TaskStopper TaskStopper
// Captures persists unbound webhook captures (docs/prds/event-capture-storage.md).
// Optional: nil makes POST /webhooks/capture/{source} answer 503 rather
// than the dashboard failing to start -- capture is a precondition for
@@ -251,22 +239,12 @@ func (s *Server) SetProvenance(origins []ConfigOrigin) {
s.ConfigProvenance.Store(&origins)
}
// 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)
}
// TaskStopper interrupts one task currently executing in the daemon.
type TaskStopper interface {
CancelTask(taskID int64) bool
}
// 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) {
+6 -1
View File
@@ -38,7 +38,12 @@ func newTestServer(t *testing.T) *Server {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
return &Server{Store: s, Log: slog.New(slog.DiscardHandler)}
srv := &Server{Store: s, Log: slog.New(slog.DiscardHandler)}
// Composition always gives the dashboard a Gateway contract; task
// actions travel through it now, so a test server without one could
// only ever answer 503.
wireOperatorActions(srv)
return srv
}
// stubStore wraps a real TaskStore and overrides selected methods to