chat: give the operator their own sessions, separate from run sessions

chat_sessions used to list exactly the OpenCode sessions the pipelines own,
filtered through pipeline.SessionOwner (run_steps/run_session_owners), so an
operator-created chat was an accident of the run-ownership table and the
operator's working sessions were mixed with the internals of running pipelines.

Add a first-class operator session:

- internal/pipeline/operator_sessions.go: a dedicated operator_sessions table
  (session_id PK, directory, title, tag, created_at, last_used_at) with
  RecordOperatorSession (upsert preserving created_at), a one-statement
  TouchOperatorSession (no-op for a non-operator id), OperatorSessions bounded to
  128 rows most-recently-used first, and OperatorDirectories (bounded MRU,
  deduped). run_steps/run_session_owners and SessionOwner/OwnedSessions are
  untouched.
- internal/server/chat.go: chat_sessions returns operator sessions only - it
  reads the registry once, intersects it with one broker session-list call, fills
  directory/tag/created/updated from the registry, sets busy for a session held
  by another connection, keeps MRU order, and stays fail-closed (empty list, never
  the endpoint's whole list). A pipeline stage session and an untagged row can
  never be listed. chat_create resolves the directory (empty/'~'/'~/...' ->
  operator home; relative or missing rejected before any OpenCode call), calls
  broker.Create(title, resolved) and records the row with the operator tag.
  chat_directories returns home first then bounded (8) deduped recents. A
  successful prompt touches the operator session without affecting pipeline
  prompts.
- internal/opencode, internal/protocol, internal/server/websocket.go and
  message.go: unscoped session list, Create posts {"title":...,
  "location":{"directory":...}} to POST /api/session, additive protocol fields
  (omitempty) and the ChatDirectories request/response, plus the OperatorRegistry
  option defaulting to the first store. One OpenCode transport per server is
  unchanged.

Docs and references: docs/cli.md gains a "Chat sessions" section documenting the
operator-only fail-closed list, directory defaulting/rejection, chat_directories
(home first, deduped, bounded 8) and why a dedicated request was chosen.
internal/author/skill/references/operations.md's stale "Brokered OpenCode chat"
text (chat_create unbrokered, run_steps filtering, "listed the owned scratch
session" evidence) is rewritten to the operator-session registry, the fail-closed
filter, directory defaulting and the corrected live-test wording. No new
reference file, so internal/author/install.go's inventory is unchanged.

Checked for staleness elsewhere: README.md, the docs/ topic pages and the
packaged server/TUI templates carry no chat-session ownership claims, so none
needed updating.

Verified: gofmt -l clean; go vet and go build ./... clean; go test -count=1
./internal/pipeline/... ./internal/protocol/... ./internal/opencode/...
./internal/server/... and the full go test -count=1 ./... pass.
This commit is contained in:
2026-10-17 11:14:25 +01:00
parent 8692561bc7
commit 18398dfa5b
16 changed files with 1258 additions and 219 deletions
+192 -51
View File
@@ -6,6 +6,8 @@ import (
"encoding/hex"
"errors"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
@@ -27,14 +29,27 @@ type chatBroker interface {
Interrupt(ctx context.Context, sessionID string) error
Messages(ctx context.Context, sessionID string, limit int) ([]protocol.ChatMessage, error)
// Sessions lists the endpoint's OpenCode sessions so the handler can
// restrict them to the ones this server owns.
// restrict them to the operator's own recorded sessions.
Sessions(ctx context.Context) ([]protocol.ChatSession, error)
// Create creates one OpenCode session in the given directory and returns it.
Create(ctx context.Context, title, directory string) (protocol.ChatSession, error)
// Permissions lists the session's pending OpenCode approval requests so the
// handler can push chat_permission frames.
Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error)
Reply(ctx context.Context, request protocol.ChatReplyRequest) error
}
// operatorRegistry is the server-side operator-session seam. *pipeline.Store
// satisfies it. It is a table of its own, separate from the pipeline stage
// ownership (SessionOwner/run_session_owners) that settles a run: chat_sessions
// lists operator sessions only and never consults stage ownership.
type operatorRegistry interface {
RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error
TouchOperatorSession(ctx context.Context, sessionID string) error
OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error)
OperatorDirectories(ctx context.Context, limit int) ([]string, error)
}
// chatPermissionPollInterval is the fixed interval between permission polls: one
// GET per poll through the shared Connection bounds, never a busy loop. The first
// poll runs immediately so a request pending when the prompt is sent is surfaced
@@ -55,6 +70,12 @@ const chatRetainedLimit = opencode.MaxResponse
// least-recently-updated turn is evicted once the cap is exceeded.
const chatMaxTurns = 128
// operatorDirectoryLimit bounds the chat_directories choices: the operator home
// plus recent operator-session directories, capped at this small fixed number so
// a long history is never returned. It matches the posture of the other small
// fixed list bounds.
const operatorDirectoryLimit = 8
// chatClientToken returns an unguessable per-connection identity. It attributes
// a session claim so two clients on the same server cannot silently write the
// same conversation; a fresh token per connection means a reconnected client is
@@ -433,10 +454,10 @@ func (h *chatHub) forgetPermission(sessionID, requestID string) {
// the generic response). Frames are pushed after the ack, each through the
// connection-scoped write function so the read loop and the stream goroutine
// never interleave partial websocket writes.
func handleChat(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, owners func(context.Context) ([]pipeline.SessionOwner, error), clientID string, write func(protocol.Message) error) bool {
func handleChat(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) bool {
switch request.Type {
case protocol.ChatPrompt:
handleChatPrompt(ctx, request, broker, hub, clientID, write)
handleChatPrompt(ctx, request, broker, hub, registry, clientID, write)
return true
case protocol.ChatMessages:
handleChatMessages(ctx, request, broker, hub, write)
@@ -448,90 +469,202 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
handleChatSimple(ctx, request, broker, hub, write)
return true
case protocol.ChatSessions:
handleChatSessions(ctx, request, broker, hub, owners, clientID, write)
handleChatSessions(ctx, request, broker, hub, registry, clientID, write)
return true
case protocol.ChatCreate:
// chat_create remains declared for the client but is not implemented yet.
// Answer explicitly so the client never mistakes the generic Pong for a
// chat reply, and the boundary stays visible instead of silently
// dropping.
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "creating a chat is not implemented yet"})
handleChatCreate(ctx, request, broker, registry, write)
return true
case protocol.ChatDirectories:
handleChatDirectories(ctx, request, registry, write)
return true
}
return false
}
// handleChatSessions answers chat_sessions with the OpenCode sessions this
// server owns, marking any another client currently holds (or an active run) as
// Busy. FAIL-CLOSED: when no ownership source is configured the result is empty,
// never the whole endpoint list. broker.Sessions is called at most once per
// request.
func handleChatSessions(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, owners func(context.Context) ([]pipeline.SessionOwner, error), clientID string, write func(protocol.Message) error) {
// handleChatSessions answers chat_sessions with the operator's own sessions,
// marking any another client currently holds as Busy. The registry is the single
// source of truth for which sessions are listed and for their directory, tag,
// created/recency, so a pipeline stage session (recorded in run_steps, never in
// the operator registry) is always excluded and a session with no recorded tag
// is never listed. FAIL-CLOSED: when no registry is configured the result is
// empty, never the whole endpoint list. broker.Sessions is called at most once
// per request, and the registry once.
func handleChatSessions(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
owned, err := ownedSessionSet(ctx, owners)
response := protocol.Message{Type: protocol.ChatSessions, ID: request.ID}
// No registry (no store and no injection): list nothing rather than the whole
// OpenCode machine.
if registry == nil {
_ = write(response)
return
}
operatorSessions, err := registry.OperatorSessions(ctx)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
// OperatorSessions is already most-recently-used first with a deterministic
// tie-break; keep that order and only include a registry session the broker
// still reports, so a session the operator deleted upstream is not listed.
registered := make(map[string]struct{}, len(operatorSessions))
for _, session := range operatorSessions {
if session.ID != "" {
registered[session.ID] = struct{}{}
}
}
sessions, err := broker.Sessions(ctx)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
response := protocol.Message{Type: protocol.ChatSessions, ID: request.ID}
present := make(map[string]protocol.ChatSession, len(sessions))
for _, session := range sessions {
owner, ok := owned[session.ID]
if _, ok := registered[session.ID]; ok {
present[session.ID] = session
}
}
for _, operator := range operatorSessions {
session, ok := present[operator.ID]
if !ok {
continue
}
if session.Directory == "" {
session.Directory = owner.Directory
}
if owner.Active || hub.busyForOther(session.ID, clientID) {
session.Busy = true
if operator.Title != "" {
session.Title = operator.Title
}
session.Directory = operator.Directory
session.Tag = operator.Tag
session.CreatedAt = operator.CreatedAt
session.UpdatedAt = operator.UpdatedAt
session.Busy = hub.busyForOther(operator.ID, clientID)
response.ChatSessions = append(response.ChatSessions, session)
}
_ = write(response)
}
// ownedSessionSet reads the ownership source once and returns a set keyed by
// session id, deduped in favour of an active owner and a non-empty directory.
// A nil source (no store and no injection) yields an empty set: chat_sessions
// then lists nothing rather than the whole OpenCode machine.
func ownedSessionSet(ctx context.Context, owners func(context.Context) ([]pipeline.SessionOwner, error)) (map[string]pipeline.SessionOwner, error) {
set := map[string]pipeline.SessionOwner{}
if owners == nil {
return set, nil
// handleChatCreate creates one operator session in a resolved directory and
// records it in the operator registry: the OpenCode session id, the exact
// resolved directory, the title and the operator tag. A blank or omitted
// directory defaults to the operator's home, never the server's working
// directory. A registry write failure answers an error naming the created id, so
// an orphaned session is visible rather than silently reported as success.
func handleChatCreate(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
list, err := owners(ctx)
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
title := ""
directory := ""
if request.ChatCreate != nil {
title = strings.TrimSpace(request.ChatCreate.Title)
directory = strings.TrimSpace(request.ChatCreate.Directory)
}
if title == "" {
title = "New chat"
}
resolved, err := resolveChatDirectory(directory)
if err != nil {
return nil, err
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
for _, owner := range list {
if owner.ID == "" {
continue
}
existing, ok := set[owner.ID]
if !ok {
set[owner.ID] = owner
continue
}
if owner.Active && !existing.Active {
existing.Active = true
}
if existing.Directory == "" {
existing.Directory = owner.Directory
}
set[owner.ID] = existing
session, err := broker.Create(ctx, title, resolved)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
return set, nil
if err := registry.RecordOperatorSession(ctx, session.ID, resolved, title, protocol.ChatSessionTagOperator); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()})
return
}
session.Directory = resolved
session.Tag = protocol.ChatSessionTagOperator
response := protocol.Message{Type: protocol.ChatCreate, ID: request.ID, ChatSession: &session}
// The same registry row is echoed on the list field so a client can splice it
// into chat_sessions without a re-list.
response.ChatSessions = []protocol.ChatSession{session}
_ = write(response)
}
func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, clientID string, write func(protocol.Message) error) {
// handleChatDirectories answers chat_directories with the operator's home first,
// then the directories of previous operator sessions most-recently-used first,
// deduplicated against the home directory and capped at operatorDirectoryLimit.
func handleChatDirectories(ctx context.Context, request protocol.Message, registry operatorRegistry, write func(protocol.Message) error) {
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
home, err := OperatorHomeDirectory()
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
directories := []string{home}
seen := map[string]struct{}{home: {}}
recent, err := registry.OperatorDirectories(ctx, operatorDirectoryLimit)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
for _, directory := range recent {
if len(directories) >= operatorDirectoryLimit {
break
}
if directory == "" {
continue
}
if _, ok := seen[directory]; ok {
continue
}
seen[directory] = struct{}{}
directories = append(directories, directory)
}
_ = write(protocol.Message{Type: protocol.ChatDirectories, ID: request.ID, ChatDirectories: directories})
}
// resolveChatDirectory resolves a chat_create directory to an absolute path: an
// omitted/empty value, "~" or a "~/..." value resolves to the operator's home
// (os.UserHomeDir) and never the server's working directory; any other value
// must be an absolute, existing directory, so a relative path cannot silently
// create a session relative to wherever the server was started.
func resolveChatDirectory(directory string) (string, error) {
directory = strings.TrimSpace(directory)
if directory == "" || directory == "~" || strings.HasPrefix(directory, "~/") {
return OperatorHomeDirectory()
}
if !filepath.IsAbs(directory) {
return "", errors.New("chat directory must be absolute or start with ~")
}
info, err := os.Stat(directory)
if err != nil {
return "", errors.New("chat directory " + directory + " is not available: " + err.Error())
}
if !info.IsDir() {
return "", errors.New("chat directory " + directory + " is not a directory")
}
return directory, nil
}
// OperatorHomeDirectory returns the operator's home directory, the default chat
// location. It is resolved through the standard library so it never falls back
// to the process working directory.
func OperatorHomeDirectory() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", errors.New("resolve operator home directory: " + err.Error())
}
if home == "" {
return "", errors.New("operator home directory is empty")
}
return home, nil
}
func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
@@ -612,6 +745,14 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
// Recency is one UPDATE: it moves the operator session to the front of
// chat_sessions. A session id that is not an operator session updates no row
// and is not an error, so pipeline stage prompts are unaffected.
if registry != nil {
if err := registry.TouchOperatorSession(ctx, sessionID); err != nil {
log.Printf("touch operator session %s: %v", sessionID, err)
}
}
// Acknowledge the accepted prompt with the echoed request id, then stream the
// reply. The prompt is sent exactly once and never re-sent on resume.
if err := write(protocol.Message{Type: protocol.ChatPrompt, ID: request.ID}); err != nil {
+120 -81
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -18,13 +19,14 @@ import (
)
// TestChatLiveEndToEnd drives the real brokered chat path against the installed
// OpenCode: it opens the server's single owned endpoint, creates a scratch
// session, and pushes chat_sessions, chat_messages, a completed chat_prompt and
// an interrupted chat_prompt through a real /connect websocket. It is opt-in
// (real inference) and never touches the deployed server, ntfy or any lane; it
// runs on an in-process handler and a t.TempDir workspace. The model defaults to
// the pipeline's own and is overridable with
// PIPELINES_TEST_OPENCODE_CHAT_MODEL=provider/model.
// OpenCode: it opens the server's single owned endpoint, creates an operator
// session through chat_create in a chosen directory, lists it through
// chat_sessions, prompts it, and reads its history through chat_messages — all on
// a scratch store and an in-process handler. Its key proof is that a genuine
// pipeline stage session (created as a raw OpenCode session and recorded in
// run_steps/run_session_owners exactly as a run does) never appears in
// chat_sessions. It is opt-in (real inference) and never touches the deployed
// server, ntfy or any lane; it runs on a t.TempDir workspace.
func TestChatLiveEndToEnd(t *testing.T) {
if os.Getenv("PIPELINES_TEST_OPENCODE_CHAT_LIVE") != "1" {
t.Skip("set PIPELINES_TEST_OPENCODE_CHAT_LIVE=1 to run the live OpenCode chat end-to-end check")
@@ -39,40 +41,13 @@ func TestChatLiveEndToEnd(t *testing.T) {
defer conn.Close()
t.Logf("owned OpenCode endpoint %s (backend %s)", conn.URL, conn.Backend)
provider, model := "opencode-go", "deepseek-v4.1-flash"
if override := os.Getenv("PIPELINES_TEST_OPENCODE_CHAT_MODEL"); override != "" {
if parts := strings.SplitN(override, "/", 2); len(parts) == 2 {
provider, model = parts[0], parts[1]
}
}
created, err := conn.Call(ctx, "post", "/api/session", map[string]any{
"title": "pipelines chat live check",
"location": map[string]string{"directory": dir},
"model": map[string]string{"providerID": provider, "id": model},
"permissions": []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}},
})
store, err := pipeline.Open(filepath.Join(t.TempDir(), "chat-live.db"))
if err != nil {
t.Fatalf("create session: %v", err)
t.Fatal(err)
}
var session struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
if err := json.Unmarshal(created, &session); err != nil || session.Data.ID == "" {
t.Fatalf("created session response %s (err %v)", created, err)
}
sid := session.Data.ID
defer conn.Call(context.Background(), "delete", "/api/session/"+sid, nil)
t.Logf("scratch session %s on %s/%s", sid, provider, model)
defer store.Close()
options := Options{
Chat: opencode.NewChat(conn),
OwnedSessions: func(context.Context) ([]pipeline.SessionOwner, error) {
return []pipeline.SessionOwner{{ID: sid, Directory: dir}}, nil
},
}
srv := httptest.NewServer(HandlerWithOptions(ctx, options))
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{Chat: opencode.NewChat(conn), OperatorRegistry: store}))
defer srv.Close()
ws, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
@@ -80,18 +55,60 @@ func TestChatLiveEndToEnd(t *testing.T) {
}
defer ws.CloseNow()
// chat_sessions must list exactly the owned scratch session.
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); err != nil {
// chat_directories returns the operator's home first.
home, err := os.UserHomeDir()
if err != nil {
t.Fatal(err)
}
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatDirectories, ID: "d1"}); err != nil {
t.Fatal(err)
}
_, resp := readChatResponse(t, ctx, ws)
if resp.Type != protocol.ChatSessions || resp.ID != "s1" {
t.Fatalf("chat_sessions response = %+v", resp)
if resp.Type != protocol.ChatDirectories || len(resp.ChatDirectories) == 0 || resp.ChatDirectories[0] != home {
t.Fatalf("chat_directories = %+v, want home %q first", resp, home)
}
if len(resp.ChatSessions) != 1 || resp.ChatSessions[0].ID != sid {
t.Fatalf("chat_sessions = %+v, want the owned session %s", resp.ChatSessions, sid)
t.Logf("chat_directories = %+v", resp.ChatDirectories)
// chat_create records the operator session in the chosen directory with the
// operator tag.
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatCreate, ID: "c1", ChatCreate: &protocol.ChatCreateRequest{Title: "pipelines chat live check", Directory: dir}}); err != nil {
t.Fatal(err)
}
t.Logf("chat_sessions listed %d owned session(s): %+v", len(resp.ChatSessions), resp.ChatSessions)
_, resp = readChatResponse(t, ctx, ws)
if resp.Type != protocol.ChatCreate || resp.ChatSession == nil {
t.Fatalf("chat_create response = %+v", resp)
}
sid := resp.ChatSession.ID
if sid == "" || resp.ChatSession.Directory != dir || resp.ChatSession.Tag != protocol.ChatSessionTagOperator {
t.Fatalf("created operator session = %+v, want directory %q and tag operator", resp.ChatSession, dir)
}
defer conn.Call(context.Background(), "delete", "/api/session/"+sid, nil)
t.Logf("chat_create created operator session %s in %s (tag %s)", sid, resp.ChatSession.Directory, resp.ChatSession.Tag)
// chat_sessions lists exactly the created operator session, with its registry
// directory and tag.
sessions := listLiveSessions(t, ctx, ws)
if len(sessions) != 1 || sessions[0].ID != sid || sessions[0].Tag != protocol.ChatSessionTagOperator || sessions[0].Directory != dir {
t.Fatalf("chat_sessions = %+v, want the created operator session %s", sessions, sid)
}
t.Logf("chat_sessions listed %d operator session(s): %+v", len(sessions), sessions)
// A genuine pipeline stage session is created as a raw OpenCode session and
// recorded in run_steps/run_session_owners exactly as a run does; chat_sessions
// must never list it.
stageID := createRawLiveSession(t, ctx, conn, dir)
defer conn.Call(context.Background(), "delete", "/api/session/"+stageID, nil)
recordLiveStageSession(t, ctx, store, stageID, dir)
sessions = listLiveSessions(t, ctx, ws)
for _, session := range sessions {
if session.ID == stageID {
t.Fatalf("pipeline stage session %s was listed: %+v", stageID, sessions)
}
}
if len(sessions) != 1 || sessions[0].ID != sid {
t.Fatalf("chat_sessions = %+v, want only the operator session %s", sessions, sid)
}
t.Logf("chat_sessions still listed only the operator session after recording stage session %s", stageID)
// chat_messages resumes retained/readback history without error.
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatMessages, ID: "m1", ChatQuery: &protocol.ChatQuery{SessionID: sid}}); err != nil {
@@ -115,50 +132,72 @@ func TestChatLiveEndToEnd(t *testing.T) {
completed := collectUntilStepEnded(t, ctx, ws, frames)
assertLiveFrames(t, sid, completed)
t.Logf("completed turn: %d chat_event frame(s) [%s]; first text delta %q", len(completed), frameKinds(completed), firstDelta(completed))
}
// An interrupted turn: post a long prompt, wait for its ack, then answer it
// with chat_interrupt and confirm the ack.
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatPrompt, ID: "p2", ChatPrompt: &protocol.ChatPromptRequest{SessionID: sid, Text: "Write a 400 line epic poem about the sea. Output every line as it comes."}}); err != nil {
// listLiveSessions issues one chat_sessions request and returns the listed
// sessions.
func listLiveSessions(t *testing.T, ctx context.Context, ws *websocket.Conn) []protocol.ChatSession {
t.Helper()
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); err != nil {
t.Fatal(err)
}
if _, ack = readChatResponse(t, ctx, ws); ack.Type != protocol.ChatPrompt || ack.ID != "p2" {
t.Fatalf("second prompt ack = %+v", ack)
_, resp := readChatResponse(t, ctx, ws)
if resp.Type != protocol.ChatSessions {
t.Fatalf("chat_sessions response = %+v", resp)
}
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatInterrupt, ID: "i1", ChatQuery: &protocol.ChatQuery{SessionID: sid}}); err != nil {
return resp.ChatSessions
}
// createRawLiveSession creates a bare OpenCode session in dir through the shared
// connection, mirroring how a pipeline run creates the session a stage drives.
func createRawLiveSession(t *testing.T, ctx context.Context, conn *opencode.Connection, dir string) string {
t.Helper()
created, err := conn.Call(ctx, "post", "/api/session", map[string]any{
"title": "pipelines stage session live check",
"location": map[string]string{"directory": dir},
"permissions": []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}},
})
if err != nil {
t.Fatalf("create raw session: %v", err)
}
var session struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
if err := json.Unmarshal(created, &session); err != nil || session.Data.ID == "" {
t.Fatalf("raw session response %s (err %v)", created, err)
}
return session.Data.ID
}
// recordLiveStageSession records sessionID as a genuine pipeline stage session
// through the same store calls a run uses (CreateRun/BeginStep/RunSession), so it
// is present in run_steps and run_session_owners and proven to be excluded from
// chat_sessions by the operator filter, not by being unrecorded.
func recordLiveStageSession(t *testing.T, ctx context.Context, store *pipeline.Store, sessionID, dir string) {
t.Helper()
if _, err := store.Submit(ctx, "chat-live-stage", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
for {
message := readChatMessage(t, ctx, ws)
if message.Type == protocol.ChatInterrupt {
if message.ID != "i1" {
t.Fatalf("interrupt ack = %+v, want i1", message)
}
break
}
items, err := store.List(ctx)
if err != nil {
t.Fatal(err)
}
// The interrupt must actually end the running turn: the session leaves the
// V2 active set. This is the observable proof the ack alone is not.
deadline := time.Now().Add(30 * time.Second)
for {
active, err := conn.Call(ctx, "get", "/api/session/active", nil)
if err != nil {
t.Fatalf("active check: %v", err)
}
var state struct {
Data map[string]json.RawMessage `json:"data"`
}
if err := json.Unmarshal(active, &state); err != nil {
t.Fatalf("active response %s (err %v)", active, err)
}
if _, running := state.Data[sid]; !running {
break
}
if time.Now().After(deadline) {
t.Fatalf("session %s is still active after chat_interrupt", sid)
}
time.Sleep(500 * time.Millisecond)
definition, err := store.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
run, _, err := store.CreateRun(ctx, definition, "chat-live-stage-run", dir, false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, run, 1, "one", map[string]any{"prompt": "task"}); err != nil {
t.Fatal(err)
}
if err := store.RunSession(ctx, run, 1, sessionID, true, "v2", dir); err != nil {
t.Fatal(err)
}
t.Logf("chat_interrupt acked and the interrupted turn left the active set")
}
// readChatResponse reads until a non-event response message arrives, returning
+323 -30
View File
@@ -6,6 +6,8 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
@@ -20,6 +22,19 @@ import (
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// newOperatorStore opens a scratch store for the operator-session registry, so
// the chat tests exercise the real SQL-backed registry (record, list, delete)
// rather than a second fake of it.
func newOperatorStore(t *testing.T) *pipeline.Store {
t.Helper()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "operator.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
return store
}
// fakeChat is a scripted chatBroker. It counts calls and either emits a fixed
// frame sequence or blocks until the caller's context is canceled.
type fakeChat struct {
@@ -51,6 +66,11 @@ type fakeChat struct {
subscribed bool
promptBeforeSubscribe bool
interruptErr error
createCalls int
createTitle string
createDirectory string
created protocol.ChatSession
createErr error
}
func (f *fakeChat) Prompt(context.Context, string, string) error {
@@ -168,6 +188,32 @@ func (f *fakeChat) sessionQuery() int {
return f.sessionCalls
}
// Create records the title and directory the handler forwarded and returns the
// seeded created session. A blank created id defaults to "ses_created" so a test
// only asserts what it cares about.
func (f *fakeChat) Create(_ context.Context, title, directory string) (protocol.ChatSession, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.createCalls++
f.createTitle = title
f.createDirectory = directory
if f.createErr != nil {
return protocol.ChatSession{}, f.createErr
}
session := f.created
if session.ID == "" {
session.ID = "ses_created"
}
return session, nil
}
// createQuery reports the recorded chat_create call count, title and directory.
func (f *fakeChat) createQuery() (int, string, string) {
f.mu.Lock()
defer f.mu.Unlock()
return f.createCalls, f.createTitle, f.createDirectory
}
// replyQuery reports the recorded chat_reply count and the last forwarded
// request, so a test can assert the exact session/request/decision.
func (f *fakeChat) replyQuery() (int, protocol.ChatReplyRequest) {
@@ -965,38 +1011,214 @@ func TestChatPromptRejectsEmptyText(t *testing.T) {
}
}
// TestChatCreateAnswersExplicitly pins the declared-but-unbrokered boundary:
// chat_create is answered with a protocol error rather than falling through to
// the generic Pong. chat_sessions is now brokered and covered by
// TestChatSessionsListsOnlyOwned and TestChatSessionsBusyRejectsSecondClient.
func TestChatCreateAnswersExplicitly(t *testing.T) {
// TestChatCreateRecordsOperatorSession is the chat_create acceptance test: the
// broker creates the session in the resolved directory, the handler records it in
// the operator registry with the operator tag, and the response carries the
// created session and the registry row (directory, tag). The registry can then
// list it.
func TestChatCreateRecordsOperatorSession(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "c1"}); err != nil {
broker.created = protocol.ChatSession{ID: "ses_new", Title: "demo"}
dir := t.TempDir()
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "c1", ChatCreate: &protocol.ChatCreateRequest{Title: "demo", Directory: dir}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "c1" {
t.Fatalf("chat_create did not answer with an explicit error: %+v", response)
if response.Type != protocol.ChatCreate || response.ID != "c1" || response.ChatSession == nil {
t.Fatalf("chat_create response = %+v", response)
}
if response.ChatSession.ID != "ses_new" || response.ChatSession.Directory != dir || response.ChatSession.Tag != protocol.ChatSessionTagOperator {
t.Fatalf("created session = %+v", response.ChatSession)
}
if len(response.ChatSessions) != 1 || response.ChatSessions[0].ID != "ses_new" || response.ChatSessions[0].Tag != protocol.ChatSessionTagOperator {
t.Fatalf("created session not echoed as a registry row: %+v", response.ChatSessions)
}
if calls, title, directory := broker.createQuery(); calls != 1 || title != "demo" || directory != dir {
t.Fatalf("broker.Create = %d/%q/%q, want 1/demo/%q", calls, title, directory, dir)
}
recorded, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(recorded) != 1 || recorded[0].ID != "ses_new" || recorded[0].Directory != dir || recorded[0].Tag != protocol.ChatSessionTagOperator || recorded[0].Title != "demo" {
t.Fatalf("registry row = %+v", recorded)
}
}
// TestChatSessionsListsOnlyOwned is the task evidence for ownership: the broker
// lists two OpenCode sessions (one owned by this server, one foreign) and
// chat_sessions returns exactly the owned one, asking the broker once.
func TestChatSessionsListsOnlyOwned(t *testing.T) {
// TestChatCreateDirectoryResolution pins directory defaulting and rejection: an
// omitted/empty/"~"/"~/..." directory resolves to the operator's home (never the
// server's working directory), an explicit existing directory is recorded
// unchanged, and a relative or missing directory is rejected before any OpenCode
// call.
func TestChatCreateDirectoryResolution(t *testing.T) {
home, err := os.UserHomeDir()
if err != nil {
t.Fatal(err)
}
explicit := t.TempDir()
cases := []struct {
name string
omitted bool
directory string
wantDirectory string
wantErr string
}{
{name: "omitted", omitted: true, wantDirectory: home},
{name: "empty", directory: "", wantDirectory: home},
{name: "tilde", directory: "~", wantDirectory: home},
{name: "tilde path", directory: "~/project", wantDirectory: home},
{name: "explicit", directory: explicit, wantDirectory: explicit},
{name: "relative", directory: "relative/dir", wantErr: "absolute"},
{name: "missing", directory: filepath.Join(t.TempDir(), "missing"), wantErr: "not available"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
request := protocol.Message{Type: protocol.ChatCreate, ID: "c1"}
if !tc.omitted {
request.ChatCreate = &protocol.ChatCreateRequest{Title: "demo", Directory: tc.directory}
}
if err := wsjson.Write(ctx, conn, request); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if tc.wantErr != "" {
if response.Type != protocol.Error || !strings.Contains(response.Error, tc.wantErr) {
t.Fatalf("directory %q not rejected: %+v", tc.directory, response)
}
if calls, _, _ := broker.createQuery(); calls != 0 {
t.Fatalf("rejected directory still reached OpenCode: %d calls", calls)
}
if recorded, err := store.OperatorSessions(ctx); err != nil || len(recorded) != 0 {
t.Fatalf("rejected directory recorded a session: %+v %v", recorded, err)
}
return
}
if response.Type != protocol.ChatCreate || response.ChatSession == nil || response.ChatSession.Directory != tc.wantDirectory {
t.Fatalf("directory %q resolved wrong: %+v", tc.directory, response)
}
if calls, _, directory := broker.createQuery(); calls != 1 || directory != tc.wantDirectory {
t.Fatalf("broker.Create = %d/%q, want 1/%q", calls, directory, tc.wantDirectory)
}
})
}
}
// TestChatDirectoriesHomeThenBoundedRecents pins chat_directories: the operator's
// home first, then the directories of previous operator sessions
// most-recently-used first, deduplicated and capped at the fixed bound even with
// more directory history seeded than the cap.
func TestChatDirectoriesHomeThenBoundedRecents(t *testing.T) {
home, err := os.UserHomeDir()
if err != nil {
t.Fatal(err)
}
store := newOperatorStore(t)
ctx, _, conn := dialChatOptions(t, Options{OperatorRegistry: store})
// Seed more directories than the bound, oldest first.
seeded := make([]string, 0, operatorDirectoryLimit+4)
for i := 0; i < operatorDirectoryLimit+4; i++ {
directory := filepath.Join(t.TempDir(), fmt.Sprintf("d%02d", i))
seeded = append(seeded, directory)
if err := store.RecordOperatorSession(ctx, fmt.Sprintf("ses_%02d", i), directory, "s", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
time.Sleep(2 * time.Millisecond)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatDirectories, ID: "d1"}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatDirectories || response.ID != "d1" {
t.Fatalf("chat_directories response = %+v", response)
}
if len(response.ChatDirectories) != operatorDirectoryLimit {
t.Fatalf("directories = %+v, want the bound of %d", response.ChatDirectories, operatorDirectoryLimit)
}
if response.ChatDirectories[0] != home {
t.Fatalf("home not first: %+v", response.ChatDirectories)
}
// The remainder are the most recently recorded directories, MRU first.
for i := 1; i < len(response.ChatDirectories); i++ {
want := seeded[len(seeded)-i]
if response.ChatDirectories[i] != want {
t.Fatalf("directory %d = %q, want %q (MRU order): %+v", i, response.ChatDirectories[i], want, response.ChatDirectories)
}
}
}
// TestChatSessionsListsOperatorSessionsOnly is the task evidence for the
// operator-session filter: the broker lists an operator-registered session, a
// genuine pipeline stage session recorded in run_steps/run_session_owners, and a
// foreign session; chat_sessions returns exactly the operator session, carrying
// its registry directory and operator tag, and asks the broker once. The stage
// session is proven to be genuinely recorded through store.OwnedSessions.
func TestChatSessionsListsOperatorSessionsOnly(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
if err := store.RecordOperatorSession(ctx, "ses_op", "/work/op", "Operator chat", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if _, err := store.Submit(ctx, "chatsrv", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, err := store.List(ctx)
if err != nil {
t.Fatal(err)
}
definition, err := store.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
run, _, err := store.CreateRun(ctx, definition, "stage-run", "/work/stage", false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, run, 1, "one", map[string]any{"prompt": "task"}); err != nil {
t.Fatal(err)
}
if err := store.RunSession(ctx, run, 1, "ses_stage", true, "v2", "/work/stage"); err != nil {
t.Fatal(err)
}
// Prove ses_stage is a real owned pipeline session, so its exclusion is the
// operator filter at work, not an unrecorded id.
owned, err := store.OwnedSessions(ctx)
if err != nil {
t.Fatal(err)
}
sawStage := false
for _, owner := range owned {
if owner.ID == "ses_stage" {
sawStage = true
}
if owner.ID == "ses_op" {
t.Fatalf("operator session leaked into pipeline ownership: %+v", owner)
}
}
if !sawStage {
t.Fatalf("stage session was not recorded in run_steps: %+v", owned)
}
broker := scriptedChat()
broker.sessions = []protocol.ChatSession{
{ID: "ses_owned", Title: "ours", Directory: "/work"},
{ID: "ses_op", Title: "upstream", Directory: "/upstream"},
{ID: "ses_stage", Title: "pipeline internal", Directory: "/work/stage"},
{ID: "ses_foreign", Title: "someone else's", Directory: "/elsewhere"},
}
owners := func(context.Context) ([]pipeline.SessionOwner, error) {
return []pipeline.SessionOwner{{ID: "ses_owned", Directory: "/work"}}, nil
}
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OwnedSessions: owners})
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); err != nil {
t.Fatal(err)
}
@@ -1007,20 +1229,86 @@ func TestChatSessionsListsOnlyOwned(t *testing.T) {
if response.Type != protocol.ChatSessions || response.ID != "s1" {
t.Fatalf("chat_sessions response = %+v", response)
}
if len(response.ChatSessions) != 1 || response.ChatSessions[0].ID != "ses_owned" {
t.Fatalf("foreign session leaked into the list: %+v", response.ChatSessions)
if len(response.ChatSessions) != 1 || response.ChatSessions[0].ID != "ses_op" {
t.Fatalf("non-operator session leaked into the list: %+v", response.ChatSessions)
}
if response.ChatSessions[0].Busy {
t.Fatalf("inactive owned session marked busy: %+v", response.ChatSessions[0])
got := response.ChatSessions[0]
if got.Directory != "/work/op" || got.Tag != protocol.ChatSessionTagOperator {
t.Fatalf("operator session shape = %+v", got)
}
if got.Busy {
t.Fatalf("inactive operator session marked busy: %+v", got)
}
if calls := broker.sessionQuery(); calls != 1 {
t.Fatalf("broker.Sessions called %d times, want 1", calls)
}
}
// TestChatSessionsFailsClosedWithoutOwnership pins the default when no ownership
// source is available: chat_sessions returns an empty list, never the full
// OpenCode machine.
// TestChatSessionsNeverListsUntagged pins that a row with no recorded tag is not
// an operator session and is never listed, even when the broker still reports it.
func TestChatSessionsNeverListsUntagged(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
if err := store.RecordOperatorSession(ctx, "ses_untagged", "/work/untagged", "no tag", ""); err != nil {
t.Fatal(err)
}
broker := scriptedChat()
broker.sessions = []protocol.ChatSession{{ID: "ses_untagged"}}
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatSessions || len(response.ChatSessions) != 0 {
t.Fatalf("untagged session was listed: %+v", response)
}
}
// TestChatSessionsMostRecentlyUsedFirst pins the list order: sessions come back
// most-recently-used first by registry recency (later creation wins), with the
// directory and tag from the registry.
func TestChatSessionsMostRecentlyUsedFirst(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
if err := store.RecordOperatorSession(ctx, "ses_old", "/work/old", "old", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
time.Sleep(3 * time.Millisecond)
if err := store.RecordOperatorSession(ctx, "ses_new", "/work/new", "new", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
broker := scriptedChat()
// The broker lists them oldest-updated-first, so the handler's registry order
// is what decides the result.
broker.sessions = []protocol.ChatSession{
{ID: "ses_old", UpdatedAt: 100},
{ID: "ses_new", UpdatedAt: 50},
}
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if len(response.ChatSessions) != 2 {
t.Fatalf("chat_sessions = %+v, want 2", response.ChatSessions)
}
if response.ChatSessions[0].ID != "ses_new" || response.ChatSessions[1].ID != "ses_old" {
t.Fatalf("not most-recently-used first: %+v", response.ChatSessions)
}
if response.ChatSessions[0].Directory != "/work/new" || response.ChatSessions[0].Tag != protocol.ChatSessionTagOperator {
t.Fatalf("registry fields not applied: %+v", response.ChatSessions[0])
}
}
// TestChatSessionsFailsClosedWithoutOwnership pins the default when no operator
// registry (store or injection) is available: chat_sessions returns an empty list
// without consulting the broker, never the full OpenCode machine.
func TestChatSessionsFailsClosedWithoutOwnership(t *testing.T) {
broker := scriptedChat()
broker.sessions = []protocol.ChatSession{{ID: "ses_1"}, {ID: "ses_2"}}
@@ -1033,7 +1321,10 @@ func TestChatSessionsFailsClosedWithoutOwnership(t *testing.T) {
t.Fatal(err)
}
if response.Type != protocol.ChatSessions || len(response.ChatSessions) != 0 {
t.Fatalf("unowned sessions were exposed: %+v", response)
t.Fatalf("unregistered sessions were exposed: %+v", response)
}
if calls := broker.sessionQuery(); calls != 0 {
t.Fatalf("fail-closed list consulted the broker %d times, want 0", calls)
}
}
@@ -1043,14 +1334,16 @@ func TestChatSessionsFailsClosedWithoutOwnership(t *testing.T) {
// broker.Prompt call; after A disconnects the claim is released and a later list
// is no longer busy.
func TestChatSessionsBusyRejectsSecondClient(t *testing.T) {
ctx := context.Background()
store := newOperatorStore(t)
if err := store.RecordOperatorSession(ctx, "ses_1", "/work", "operator chat", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
broker := scriptedChat()
broker.block = true
broker.done = make(chan struct{})
broker.sessions = []protocol.ChatSession{{ID: "ses_1"}}
owners := func(context.Context) ([]pipeline.SessionOwner, error) {
return []pipeline.SessionOwner{{ID: "ses_1"}}, nil
}
ctx, _, conns := dialChatConns(t, Options{Chat: broker, OwnedSessions: owners}, 2)
ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 2)
connA, connB := conns[0], conns[1]
if err := wsjson.Write(ctx, connA, protocol.Message{Type: protocol.ChatPrompt, ID: "a1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil {
+13 -12
View File
@@ -27,11 +27,12 @@ type Options struct {
// 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)
// OperatorRegistry is the operator-session registry chat_sessions lists and
// chat_create/chat_directories read. When nil, HandlerWithOptions derives it
// from the first store; when neither is available chat_sessions returns an
// empty list (never the endpoint's whole session list) and chat_create is
// refused. Purely pipeline stage ownership is unaffected.
OperatorRegistry operatorRegistry
// 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.
@@ -78,12 +79,12 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
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
// chat_sessions lists the operator's own recorded sessions. Prefer an
// injected registry; 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
registry := options.OperatorRegistry
if registry == nil && len(stores) > 0 {
registry = stores[0]
}
mux.HandleFunc("GET /artifacts/{run}/{step}/{name...}", func(w http.ResponseWriter, r *http.Request) {
if runs == nil {
@@ -154,7 +155,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
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) {
if handleChat(connCtx, request, options.Chat, hub, registry, clientID, write) {
continue
}
if handleRunEvents(request, events, runs, clientID, write) {
@@ -243,7 +244,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
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) {
} 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: