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
+79 -17
View File
@@ -115,20 +115,45 @@ func (c *Chat) Messages(ctx context.Context, id string, limit int) ([]protocol.C
// Sessions lists the OpenCode sessions on the endpoint. On the V2 HTTP API that
// is GET /api/session; the native v1 serve translation maps it to GET /session.
// It decodes the verified {"data":[...]} envelope (tolerating a bare array like
// chatMessageRecords), lifts the nested location.directory and
// time{created,updated} into protocol.ChatSession, drops records without a valid
// session id, and orders newest-updated first so the list is deterministic. The
// service's list is global; the caller is responsible for restricting it to the
// sessions this server owns.
// It reads the list unscoped by the connection's directory (see
// Connection.SessionList): the V2 list is otherwise restricted to the
// connection's own directory, while an operator session may live in any
// directory, and the caller is responsible for restricting the result to the
// operator's recorded sessions. It decodes the verified {"data":[...]} envelope
// (tolerating a bare array like chatMessageRecords), lifts the nested
// location.directory and time{created,updated} into protocol.ChatSession, drops
// records without a valid session id, and orders newest-updated first so the list
// is deterministic.
func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
data, err := c.call(ctx, "get", "/api/session", nil)
c.mu.Lock()
data, err := c.conn.SessionList(ctx)
c.mu.Unlock()
if err != nil {
return nil, err
}
return decodeChatSessions(data)
}
// Create creates one OpenCode session in the given directory, mirroring the
// verified V2 shape POST /api/session {"title":...,"location":{"directory":...}}.
// It deliberately sends no model or permission override here: the endpoint's own
// defaults apply, exactly as the live check creates a session. The created
// session is returned with its directory lifted from location.directory.
func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
body := struct {
Title string `json:"title"`
Location struct {
Directory string `json:"directory"`
} `json:"location"`
}{Title: title}
body.Location.Directory = directory
data, err := c.call(ctx, "post", "/api/session", body)
if err != nil {
return protocol.ChatSession{}, err
}
return decodeChatSession(data)
}
// Reply posts a permission decision, mirroring the documented endpoint.
func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
if !sessionID.MatchString(request.SessionID) {
@@ -629,6 +654,39 @@ func chatSessionRecords(data []byte) ([]nativeChatSession, error) {
return records, nil
}
// chatSessionRecord reads one created session, accepting the {"data":{...}}
// envelope the V2 API returns and tolerating a bare object. An unrecognised body
// is an error, never an empty session.
func chatSessionRecord(data []byte) (nativeChatSession, error) {
var response struct {
Data *nativeChatSession `json:"data"`
}
if err := json.Unmarshal(data, &response); err == nil && response.Data != nil {
return *response.Data, nil
}
var record nativeChatSession
if err := json.Unmarshal(data, &record); err != nil || record.ID == "" {
return nativeChatSession{}, fmt.Errorf("invalid OpenCode session response")
}
return record, nil
}
// chatSessionFields lifts the nested location.directory and time{created,updated}
// of one native session record onto protocol.ChatSession. It is the single field
// mapping shared by the list decoder and Create, so the two cannot drift.
func chatSessionFields(record nativeChatSession) protocol.ChatSession {
return protocol.ChatSession{
ID: record.ID,
Title: record.Title,
Agent: record.Agent,
Model: record.Model.ID,
Directory: record.Location.Directory,
ParentID: record.ParentID,
CreatedAt: record.Time.Created,
UpdatedAt: record.Time.Updated,
}
}
// decodeChatSessions maps the listed sessions onto protocol.ChatSession, dropping
// every record whose id is not a valid OpenCode session id (an empty or foreign
// id cannot be addressed) and ordering by UpdatedAt then id so the result is
@@ -643,16 +701,7 @@ func decodeChatSessions(data []byte) ([]protocol.ChatSession, error) {
if !sessionID.MatchString(record.ID) {
continue
}
sessions = append(sessions, protocol.ChatSession{
ID: record.ID,
Title: record.Title,
Agent: record.Agent,
Model: record.Model.ID,
Directory: record.Location.Directory,
ParentID: record.ParentID,
CreatedAt: record.Time.Created,
UpdatedAt: record.Time.Updated,
})
sessions = append(sessions, chatSessionFields(record))
}
sort.SliceStable(sessions, func(i, j int) bool {
if sessions[i].UpdatedAt != sessions[j].UpdatedAt {
@@ -662,3 +711,16 @@ func decodeChatSessions(data []byte) ([]protocol.ChatSession, error) {
})
return sessions, nil
}
// decodeChatSession maps one created session, rejecting an empty or foreign id
// (an unaddressable session is an error, never a silent success).
func decodeChatSession(data []byte) (protocol.ChatSession, error) {
record, err := chatSessionRecord(data)
if err != nil {
return protocol.ChatSession{}, err
}
if !sessionID.MatchString(record.ID) {
return protocol.ChatSession{}, fmt.Errorf("invalid OpenCode session response")
}
return chatSessionFields(record), nil
}