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 {