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
+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 {