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
}
+70 -2
View File
@@ -502,15 +502,21 @@ func TestDecodeChatMessagesSkipsUnknownPartsAndRoles(t *testing.T) {
// TestChatSessionsListsAndLiftsShape loads the verified V2 session list
// (GET /api/session: {"data":[{id,...,location.directory,time{created,updated},
// parentID}]}) and asserts the adapter reads it exactly once, lifts the nested
// directory/time onto protocol.ChatSession, and orders newest-updated first.
// directory/time onto protocol.ChatSession, orders newest-updated first, and does
// not scope the list to the connection's own directory (so operator sessions in
// other directories are returned for the caller to filter).
func TestChatSessionsListsAndLiftsShape(t *testing.T) {
var reads atomic.Int32
var scoped bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/session" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
reads.Add(1)
if r.URL.Query().Get("directory") != "" {
scoped = true
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[
{"id":"ses_old","title":"older","agent":"build","model":{"id":"m1"},"parentID":"ses_new","location":{"directory":"/proj"},"time":{"created":10,"updated":20}},
@@ -519,7 +525,7 @@ func TestChatSessionsListsAndLiftsShape(t *testing.T) {
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL, Directory: "/repo"})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
sessions, err := chat.Sessions(ctx)
@@ -529,6 +535,9 @@ func TestChatSessionsListsAndLiftsShape(t *testing.T) {
if reads.Load() != 1 {
t.Fatalf("session endpoint read %d times, want 1", reads.Load())
}
if scoped {
t.Fatal("session list was scoped to the connection directory; it must list every directory")
}
if len(sessions) != 2 {
t.Fatalf("sessions = %+v, want 2", sessions)
}
@@ -631,6 +640,65 @@ func TestChatStreamRequiresEndpoint(t *testing.T) {
}
}
// TestChatCreatePostsSessionEndpoint pins the outbound create call: the adapter
// must POST exactly once to /api/session with the verified V2 body
// {"title":...,"location":{"directory":...}} (no invented mechanism, no model or
// permission override), read exactly that one path, and lift the nested
// location.directory from the {"data":{...}} response.
func TestChatCreatePostsSessionEndpoint(t *testing.T) {
type request struct{ method, path, body string }
var mu sync.Mutex
var requests []request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := io.ReadAll(r.Body)
mu.Lock()
requests = append(requests, request{method: r.Method, path: r.URL.Path, body: string(data)})
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":{"id":"ses_new","title":"demo","location":{"directory":"/work/proj"},"time":{"created":11,"updated":22}}}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
session, err := chat.Create(ctx, "demo", "/work/proj")
if err != nil {
t.Fatalf("create: %v", err)
}
mu.Lock()
got := append([]request(nil), requests...)
mu.Unlock()
if len(got) != 1 {
t.Fatalf("create requests = %d, want 1: %+v", len(got), got)
}
if got[0].method != http.MethodPost || got[0].path != "/api/session" {
t.Fatalf("create request = %+v", got[0])
}
if got[0].body != `{"title":"demo","location":{"directory":"/work/proj"}}` {
t.Fatalf("create body = %q", got[0].body)
}
if session.ID != "ses_new" || session.Title != "demo" || session.Directory != "/work/proj" || session.CreatedAt != 11 || session.UpdatedAt != 22 {
t.Fatalf("created session = %+v", session)
}
}
// TestChatCreateRejectsMalformedSession pins that a response without a valid
// session id is an error, not a silent empty success.
func TestChatCreateRejectsMalformedSession(t *testing.T) {
for _, raw := range []string{`{"data":{}}`, `{"data":{"id":""}}`, `{"data":{"id":"msg_not_a_session"}}`, `not json`} {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(raw))
}))
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if _, err := chat.Create(context.Background(), "demo", "/work"); err == nil {
t.Fatalf("response %q must be an error, not empty success", raw)
}
srv.Close()
}
}
func TestNormalizeChatEventWithoutMessageID(t *testing.T) {
for _, payload := range []string{
`{"type":"session.text.delta","data":{"sessionID":"ses_1","ordinal":0,"delta":"x"}}`,
+12 -3
View File
@@ -316,15 +316,24 @@ func (c *Connection) Close() {
}
func (c *Connection) Native(ctx context.Context, method, path string, body any) ([]byte, error) {
return c.nativeRequest(ctx, method, path, body, c.Directory)
}
// nativeRequest is the shared Native request path. An empty directory omits the
// ?directory= query parameter; the V2 session list then returns sessions across
// every directory instead of only the connection's own.
func (c *Connection) nativeRequest(ctx context.Context, method, path string, body any, directory string) ([]byte, error) {
c.LastHTTPStatus = 0
c.LastHTTPOperation = strings.ToUpper(method) + " " + path
u, err := url.Parse(c.URL + path)
if err != nil {
return nil, err
}
query := u.Query()
query.Set("directory", c.Directory)
u.RawQuery = query.Encode()
if directory != "" {
query := u.Query()
query.Set("directory", directory)
u.RawQuery = query.Encode()
}
var data []byte
if body != nil {
data, err = json.Marshal(body)
+17
View File
@@ -63,6 +63,23 @@ func messageText(data []byte) (string, error) {
return text, nil
}
// SessionList reads the endpoint's whole OpenCode session list without the
// connection's directory scope, so the brokered chat handler can filter it to
// the operator's own sessions across every directory. The V2 HTTP API scopes
// GET /api/session to ?directory= when given; omitting it lists every session,
// which is required because an operator session may live in any directory. The
// native serve list is /session. It reuses the same authenticated request path
// (no second transport or endpoint); only the directory query is omitted.
func (c *Connection) SessionList(ctx context.Context) ([]byte, error) {
if c.Backend == "v1" {
return c.nativeRequest(ctx, "get", "/session", nil, "")
}
if c.URL == "" {
return nil, fmt.Errorf("native adapter requires the serve backend")
}
return c.nativeRequest(ctx, "get", "/api/session", nil, "")
}
// Call adapts the pipeline's existing V2 command contract to the native stable API.
// Sessions still use the same account/database; only our loopback serve process is owned.
// A connection whose backend already speaks the /api HTTP surface forwards the path