Files
pipelines/internal/server/websocket.go
T
alan bd09c55c47 Merge lane-go: titles, verdicts, human stage, line result format, stale-client guard
Integrates nine commits of reviewed work from the lane-go branch after the
automated resolver failed on this merge five times (each attempt dying on the
malformed-result defect whose fix is contained in this same merge).

Integration decisions:
- Search: kept main's shipped design (Store.Search + SearchResponse.Results) and
  dropped lane-go's parallel, older attempt (an unused Message.Matches field, an
  absent runs.search, and two partial TUI plumbing blocks). lane-go itself did not
  compile: protocol.SearchMatch was undefined and model.go referenced searchNav,
  requestSearch and applyRunNav, which exist nowhere. Those partial TUI blocks are
  removed; the queued TUI omni-search item will implement the surface properly on
  main's design.
- Both sides' additions are kept where they are independent: run titles and
  provenance, the human decision stage and its CLI/TUI surface, the derived stage
  verdict, the stale-client guard, the line-oriented result format, and main's
  search command.
- The search key's help label is now "/ omni search"; the two tests asserting the
  old label are updated rather than the label reverted.
- docs/cli.md and the packaged operations reference carry both sides' text.

Verified: go build ./... , go vet ./... and the full go test ./... suite pass.
2026-10-16 22:21:43 +01:00

307 lines
11 KiB
Go

package server
import (
"context"
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/examples"
"git.a-wan.net/alan/pipelines/internal/buildinfo"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/summarise"
)
// Options configures the HTTP handler.
type Options struct {
// ArtifactsRoot overrides where stage artifacts live. Empty uses the store's
// directory (the database's parent), matching the data-directory default.
ArtifactsRoot string
// Chat brokers OpenCode chat traffic over /connect. Nil answers every
// chat_* request with a protocol error; a configured server passes an
// *opencode.Chat bound to the owned endpoint.
Chat chatBroker
// OwnedSessions reports the OpenCode sessions this server owns so
// chat_sessions is restricted to them. When nil, HandlerWithOptions derives
// it from the first store; when neither is available chat_sessions returns an
// empty list rather than the endpoint's whole session list.
OwnedSessions func(context.Context) ([]pipeline.SessionOwner, error)
// RunTitles generates the operator-facing title stored with each new run.
// When nil, run creation stores the prompt-derived fallback without a model
// call, which keeps tests and unconfigured servers deterministic.
RunTitles func(context.Context, string) summarise.Title
// StepVerdicts generates the bounded one-line reason stored with each
// completed stage visit. When nil, the store derives the verdict's reason at
// read time with no model call, which keeps tests and unconfigured servers
// deterministic.
StepVerdicts func(context.Context, map[string]any) string
}
// Handler serves the persistent connection with default options. Canceling ctx
// stops active clients.
func Handler(ctx context.Context, stores ...*pipeline.Store) http.Handler {
return HandlerWithOptions(ctx, Options{}, stores...)
}
// HandlerWithOptions serves the persistent connection and the stage-artifact
// endpoint. Canceling ctx stops active clients.
func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipeline.Store) http.Handler {
build := buildinfo.Current()
started := time.Now()
hub := newChatHub()
mux := http.NewServeMux()
var runs *runner
var runErr error
if len(stores) > 0 {
runs, runErr = newRunner(ctx, stores[0])
if runErr == nil && options.ArtifactsRoot != "" {
runs.artifactsRoot = options.ArtifactsRoot
}
if runErr == nil && options.RunTitles != nil {
runs.title = options.RunTitles
}
if runErr == nil && options.StepVerdicts != nil {
runs.verdict = options.StepVerdicts
}
if runErr == nil {
runs.schedulerWG.Add(1)
go runs.scheduleLoop()
}
}
// chat_sessions is restricted to the sessions this server owns. Prefer an
// injected source; otherwise derive it from the store. With neither, the
// handler fails closed to an empty list.
owned := options.OwnedSessions
if owned == nil && len(stores) > 0 {
owned = stores[0].OwnedSessions
}
mux.HandleFunc("GET /artifacts/{run}/{step}/{name...}", func(w http.ResponseWriter, r *http.Request) {
if runs == nil {
http.NotFound(w, r)
return
}
runs.serveArtifact(w, r)
})
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if runErr != nil {
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte(`{"healthy":false}`))
return
}
_, _ = w.Write([]byte(`{"healthy":true}`))
})
mux.HandleFunc("GET /connect", func(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
if err != nil {
return
}
defer conn.CloseNow()
conn.SetReadLimit(2 << 20)
// connCtx is canceled when this connection's read loop returns, so a
// chat subscription started for the client stops on disconnect. A single
// write mutex serializes the read loop's responses and the chat stream
// goroutine, which must never interleave partial websocket writes.
connCtx, connCancel := context.WithCancel(ctx)
defer connCancel()
var writeMu sync.Mutex
write := func(message protocol.Message) error {
// Every server frame (responses, the welcome and chat events) carries
// the build identity and protocol so an older client fails fast or
// warns once instead of silently misreading a field. build is
// computed once per handler.
if message.Build == nil {
message.Build = &build
}
if message.Protocol == 0 {
message.Protocol = protocol.ProtocolVersion
}
writeMu.Lock()
defer writeMu.Unlock()
writeCtx, cancel := context.WithTimeout(connCtx, 5*time.Second)
defer cancel()
return wsjson.Write(writeCtx, conn, message)
}
// clientID is this connection's identity for chat session claims: a
// second client is refused a session another connection holds.
clientID := chatClientToken()
if len(stores) > 0 {
items, err := stores[0].List(ctx)
if err != nil {
log.Printf("list pipelines: %v", err)
return
}
if err := write(protocol.Message{Type: protocol.PipelineList, Pipelines: items, NotificationEndpoints: notificationEndpoints()}); err != nil {
return
}
}
for {
var request protocol.Message
if err := wsjson.Read(ctx, conn, &request); err != nil {
return
}
log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version)
if handleChat(connCtx, request, options.Chat, hub, owned, clientID, write) {
continue
}
response := protocol.Message{Type: protocol.Pong, ID: request.ID}
if request.Type == protocol.List || request.Type == protocol.Submit {
response.NotificationEndpoints = notificationEndpoints()
}
if request.Type == protocol.GetStatus {
response.Type = protocol.Status
response.Status = systemStatus(r, started, runErr)
} else if request.Type == protocol.Ping {
response.Time = time.Now().UTC().Format(time.RFC3339)
} else if request.Type == protocol.ListTemplates {
response.Type = protocol.Templates
response.Templates = examples.Catalog()
model, backend := starterDefaults()
for i := range response.Templates {
response.Templates[i].Source = pipeline.WithDefaults(response.Templates[i].Source, model, backend)
}
} else if request.Type == protocol.Validate {
graph, err := pipeline.Parse(request.Source)
response.Type = protocol.Validated
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
} else {
response.Graph = &graph
}
} else if request.Type == protocol.Submit && len(stores) > 0 {
response.Type = protocol.Submitted
response.Name = strings.TrimSpace(request.Name)
version, err := stores[0].SubmitChecked(ctx, request.Name, request.Source, request.CreateOnly, request.ExpectedVersion)
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
} else {
response.Version = version
response.Pipelines, err = stores[0].List(ctx)
if err != nil {
log.Printf("list pipelines after submission: %v", err)
}
for _, item := range response.Pipelines {
if item.Name == response.Name {
response.Detail, err = stores[0].Get(ctx, item.ID, version)
if err != nil {
log.Printf("load submitted pipeline: %v", err)
}
break
}
}
}
} else if request.Type == protocol.GetPipeline && len(stores) > 0 {
response.Type = protocol.Pipeline
detail, err := stores[0].Get(ctx, request.PipelineID, request.Version)
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
} else {
response.Detail = detail
}
} else if request.Type == protocol.List && len(stores) > 0 {
response.Type = protocol.PipelineList
response.DefaultModel, response.DefaultHarness = starterDefaults()
items, err := stores[0].List(ctx)
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
} else {
response.Pipelines = items
}
} else if request.Type == protocol.Search {
if len(stores) == 0 {
response.Type = protocol.Error
response.Error = "search unavailable: no store"
} else if request.Search == nil {
response.Type = protocol.Error
response.Error = "search requires a query"
} else {
response.Type = protocol.SearchResults
var err error
response.SearchResults, err = stores[0].Search(ctx, *request.Search, time.Now())
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
}
}
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence) {
var err error
switch request.Type {
case protocol.GetRunEvidence:
response.Type = protocol.RunEvidence
response.Evidence, err = runs.evidence(ctx, request.RunID)
case protocol.RunPipeline:
response.Type = protocol.RunStarted
response.RunDetail, err = runs.start(request)
case protocol.RetryRun:
response.Type = protocol.RunStarted
response.RunDetail, err = runs.retry(request)
case protocol.DecideRun:
response.Type = protocol.Run
response.RunDetail, err = runs.decide(request)
case protocol.SetRunTitle:
response.Type = protocol.Run
response.RunDetail, err = runs.setTitle(request.RunID, request.Title)
case protocol.ListRuns:
response.Type = protocol.Runs
response.Runs, err = runs.listRuns()
if err == nil {
response.Usage, err = stores[0].UsageStats(ctx)
}
case protocol.GetRun:
response.Type = protocol.Run
response.RunDetail, err = runs.getRun(request.RunID)
case protocol.CancelRun:
response.Type = protocol.Run
err = runs.cancel(request.RunID)
if err == nil {
response.RunDetail, err = runs.getRun(request.RunID)
}
}
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
}
} else {
response.Type = protocol.Error
response.Error = "unknown command: " + request.Type
if runErr != nil {
response.Error = "execution unavailable: " + runErr.Error()
}
}
if err := write(response); err != nil {
log.Printf("write response: %v", err)
return
}
selectedVersion := response.Version
if response.Detail != nil {
selectedVersion = response.Detail.Version
}
log.Printf("response sent: client=%s type=%q id=%q time=%q error=%q version=%d", r.RemoteAddr, response.Type, response.ID, response.Time, response.Error, selectedVersion)
}
})
return &runHandler{Handler: mux, runner: runs}
}
type runHandler struct {
http.Handler
runner *runner
}
// WaitRuns drains active execution before the database is closed on shutdown.
func WaitRuns(handler http.Handler) {
if h, ok := handler.(*runHandler); ok && h.runner != nil {
h.runner.schedulerWG.Wait()
h.runner.wg.Wait()
}
}