From 1818a06d2ff5dce8fd7210af72078cd04833f6c2 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 09:21:50 +0100 Subject: [PATCH] Restrict chat_sessions to server-owned sessions chat_sessions now brokers GET /api/session but filters the global list to the sessions this server recorded in run_steps, deduped by session id, and fails closed to an empty list when no ownership source is configured. A session another client holds (in-server claim, released on stream end or disconnect) or an active run is marked busy; a second client's chat_prompt for a held session is rejected before any OpenCode call. chat_create stays unbrokered. --- .../author/skill/references/operations.md | 23 +- internal/opencode/chat.go | 86 ++++++++ internal/opencode/chat_test.go | 104 +++++++++ internal/opencode/native.go | 7 + internal/pipeline/runs.go | 44 +++- internal/pipeline/runs_test.go | 63 ++++++ internal/protocol/chat.go | 5 + internal/protocol/chat_test.go | 1 + internal/server/chat.go | 198 +++++++++++++++-- internal/server/chat_test.go | 201 ++++++++++++++++-- internal/server/websocket.go | 17 +- 11 files changed, 711 insertions(+), 38 deletions(-) diff --git a/internal/author/skill/references/operations.md b/internal/author/skill/references/operations.md index e1a5f039..44273aba 100644 --- a/internal/author/skill/references/operations.md +++ b/internal/author/skill/references/operations.md @@ -179,12 +179,23 @@ traversal, absolute paths, symlink escapes and unknown runs/steps. The protocol declares the brokered `chat_*` surface (`chat_sessions`, `chat_create`, `chat_prompt`, `chat_messages`, `chat_interrupt`, `chat_permission`, -`chat_reply`). The server dispatches `chat_prompt`, `chat_messages`, `chat_interrupt` -and `chat_reply`, answers the declared `chat_sessions`/`chat_create` with an explicit -protocol error because they are not yet brokered, and pushes `chat_event` frames -derived from OpenCode's global `/api/event` firehose, with retained -per-session/per-message state so a reconnecting client re-syncs instead of replaying -deltas. +`chat_reply`). The server dispatches `chat_sessions`, `chat_prompt`, +`chat_messages`, `chat_interrupt` and `chat_reply`, answers the declared +`chat_create` with an explicit protocol error because it is not yet brokered, and +pushes `chat_event` frames derived from OpenCode's global `/api/event` firehose, +with retained per-session/per-message state so a reconnecting client re-syncs +instead of replaying deltas. + +`chat_sessions` is brokered but restricted: OpenCode's `GET /api/session` lists +every session on the machine, so the server filters it to the sessions recorded +in `run_steps` as owned by this server (deduped by session id), fills any missing +directory from the owning run's workspace, and fails closed to an empty list when +no ownership source is configured rather than exposing the operator's whole +environment. A session another client currently holds (an in-server claim, +released when the stream ends or the client disconnects) or that this server +records as an active run is marked `busy` so the phone can show it read-only; a +second client's `chat_prompt` for a held session is rejected before any OpenCode +call. `chat_create` remains unbrokered. While a `chat_prompt` subscription is open the server also polls `GET /api/permission/request` on a fixed small interval (first poll immediately) and diff --git a/internal/opencode/chat.go b/internal/opencode/chat.go index 130ee793..ce20f0f6 100644 --- a/internal/opencode/chat.go +++ b/internal/opencode/chat.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io" + "sort" "strings" "sync" @@ -109,6 +110,22 @@ func (c *Chat) Messages(ctx context.Context, id string, limit int) ([]protocol.C return decodeChatMessages(id, data) } +// 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. +func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) { + data, err := c.call(ctx, "get", "/api/session", nil) + if err != nil { + return nil, err + } + return decodeChatSessions(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) { @@ -548,3 +565,72 @@ func decodeChatMessages(sessionID string, data []byte) ([]protocol.ChatMessage, } return messages, nil } + +// nativeChatSession is one listed session in the verified V2 shape +// ({id,title,agent,model,cost,tokens,outcome,time,title,location.directory, +// parentID,permissions}); only the fields the protocol surfaces are read. The +// native v1 serve readback of the same list is not covered by the research, so +// its records decode through the same tolerant envelope but any additional +// nesting is not asserted. +type nativeChatSession struct { + ID string `json:"id"` + Title string `json:"title"` + Agent string `json:"agent"` + Model nativeChatModel `json:"model"` + ParentID string `json:"parentID"` + Location struct { + Directory string `json:"directory"` + } `json:"location"` + Time struct { + Created int64 `json:"created"` + Updated int64 `json:"updated"` + } `json:"time"` +} + +// chatSessionRecords accepts both session-list envelopes: the V2 HTTP API wraps +// them in {"data":[...]} while the native serve readback returns a bare array. +// An unrecognised body is an error, never an empty list. +func chatSessionRecords(data []byte) ([]nativeChatSession, error) { + if records, ok := chatEnvelope[nativeChatSession](data); ok { + return records, nil + } + var records []nativeChatSession + if err := json.Unmarshal(data, &records); err != nil { + return nil, fmt.Errorf("invalid OpenCode session response") + } + return records, nil +} + +// 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 +// deterministic. +func decodeChatSessions(data []byte) ([]protocol.ChatSession, error) { + records, err := chatSessionRecords(data) + if err != nil { + return nil, err + } + sessions := make([]protocol.ChatSession, 0, len(records)) + for _, record := range records { + 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, + }) + } + sort.SliceStable(sessions, func(i, j int) bool { + if sessions[i].UpdatedAt != sessions[j].UpdatedAt { + return sessions[i].UpdatedAt > sessions[j].UpdatedAt + } + return sessions[i].ID < sessions[j].ID + }) + return sessions, nil +} diff --git a/internal/opencode/chat_test.go b/internal/opencode/chat_test.go index b3c5a579..53181de7 100644 --- a/internal/opencode/chat_test.go +++ b/internal/opencode/chat_test.go @@ -499,6 +499,110 @@ 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. +func TestChatSessionsListsAndLiftsShape(t *testing.T) { + var reads atomic.Int32 + 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) + 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}}, + {"id":"ses_new","title":"newer","agent":"general","model":{"id":"m2"},"location":{"directory":"/proj"},"time":{"created":30,"updated":50}} + ],"cursor":{"next":null}}`)) + })) + defer srv.Close() + + chat := NewChat(&Connection{Backend: "v2", URL: srv.URL}) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + sessions, err := chat.Sessions(ctx) + if err != nil { + t.Fatalf("sessions: %v", err) + } + if reads.Load() != 1 { + t.Fatalf("session endpoint read %d times, want 1", reads.Load()) + } + if len(sessions) != 2 { + t.Fatalf("sessions = %+v, want 2", sessions) + } + newer, older := sessions[0], sessions[1] + if newer.ID != "ses_new" || older.ID != "ses_old" { + t.Fatalf("not ordered newest-updated first: %+v", sessions) + } + if newer.Title != "newer" || newer.Agent != "general" || newer.Model != "m2" || newer.Directory != "/proj" || newer.CreatedAt != 30 || newer.UpdatedAt != 50 { + t.Fatalf("lifted fields wrong: %+v", newer) + } + if older.ParentID != "ses_new" || older.UpdatedAt != 20 || older.Title != "older" || older.Model != "m1" { + t.Fatalf("older session fields wrong: %+v", older) + } +} + +// TestChatSessionsTolerantEnvelopes pins the decoder's edge cases: a bare array +// (the native serve readback) is accepted, records without a valid session id +// are dropped, and an unparseable body or a data:null envelope is an error, not +// a silent empty success. +func TestChatSessionsTolerantEnvelopes(t *testing.T) { + sessions, err := decodeChatSessions([]byte(`[ + {"id":"ses_1","title":"kept","time":{"updated":5}}, + {"id":"","title":"dropped empty"}, + {"id":"msg_not_a_session","title":"dropped invalid"} + ]`)) + if err != nil { + t.Fatalf("bare array decode: %v", err) + } + if len(sessions) != 1 || sessions[0].ID != "ses_1" || sessions[0].Title != "kept" { + t.Fatalf("bare array mapping wrong: %+v", sessions) + } + if sessions, err := decodeChatSessions([]byte(`{"data":[]}`)); err != nil || len(sessions) != 0 { + t.Fatalf("empty data array must decode to no sessions: %+v %v", sessions, err) + } + for _, raw := range []string{`{"data":null}`, `not json`, `{"location":{"directory":"/work"}}`} { + if _, err := decodeChatSessions([]byte(raw)); err == nil { + t.Fatalf("body %q must be an error, not empty success", raw) + } + } +} + +// TestChatSessionsV1Translation pins the native serve path: GET /api/session is +// translated to the native GET /session (a bare array), so chat_sessions works +// on the backend that currently enables brokered chat. The native list shape is +// not covered by the research; this asserts the translated endpoint and the +// shared tolerant decode, not an unverified service shape. +func TestChatSessionsV1Translation(t *testing.T) { + var sawList bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet || r.URL.Path != "/session" { + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + return + } + sawList = true + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"id":"ses_1","title":"native","time":{"created":1,"updated":2}}]`)) + })) + defer srv.Close() + + chat := NewChat(&Connection{Backend: "v1", URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}}) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + sessions, err := chat.Sessions(ctx) + if err != nil { + t.Fatalf("sessions: %v", err) + } + if !sawList { + t.Fatal("GET /api/session was not translated to the native GET /session") + } + if len(sessions) != 1 || sessions[0].ID != "ses_1" || sessions[0].Title != "native" || sessions[0].UpdatedAt != 2 { + t.Fatalf("native session list mapped wrong: %+v", sessions) + } +} + func TestChatStreamRejectsMalformedEvent(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream") diff --git a/internal/opencode/native.go b/internal/opencode/native.go index e613a381..4b195d53 100644 --- a/internal/opencode/native.go +++ b/internal/opencode/native.go @@ -115,6 +115,13 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([ c.models[session.ID] = map[string]string{"providerID": request.Model["providerID"], "modelID": request.Model["id"]} return json.Marshal(map[string]any{"data": map[string]string{"id": session.ID}}) } + // The brokered chat session list is GET /api/session on the V2 HTTP API; the + // native serve surface lists sessions at /session and returns a bare array, + // which the adapter's tolerant decoder accepts. This keeps chat_sessions + // working on the backend that currently enables brokered chat. + if path == "/api/session" && method == "get" { + return c.Native(ctx, "get", "/session", nil) + } clean := strings.SplitN(path, "?", 2)[0] // The brokered approval surface is implemented against the V2 HTTP API: the // documented endpoints are GET /api/permission/request and POST diff --git a/internal/pipeline/runs.go b/internal/pipeline/runs.go index 5707b375..03c8ca6f 100644 --- a/internal/pipeline/runs.go +++ b/internal/pipeline/runs.go @@ -26,6 +26,7 @@ input_json TEXT NOT NULL, output_json TEXT NOT NULL DEFAULT '{}', diagnostic TEX session_id TEXT NOT NULL DEFAULT '', agent_active INTEGER NOT NULL DEFAULT 0, transcript TEXT NOT NULL DEFAULT '', started_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, finished_at TEXT, PRIMARY KEY(run_id,sequence)); CREATE INDEX IF NOT EXISTS run_latest ON pipeline_runs(id DESC); +CREATE INDEX IF NOT EXISTS run_steps_session ON run_steps(session_id); CREATE TABLE IF NOT EXISTS step_notifications ( run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, receipts_json TEXT NOT NULL, PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence)); @@ -335,6 +336,8 @@ type SessionOwner struct { // RunID is the owning run, used to tell an orphaned session (no active run) // from one owned by a run that is active right now. RunID int64 + // Active is true while the owning step records the session as agent-active. + Active bool } func (s *Store) RunSessionOwner(ctx context.Context, id int64, sequence int) (SessionOwner, error) { @@ -343,19 +346,54 @@ func (s *Store) RunSessionOwner(ctx context.Context, id int64, sequence int) (Se return owner, err } +// sessionOwnerScanLimit bounds the ownership scan so a long-lived database with +// thousands of historical sessions cannot make one chat_sessions request scan +// them all. Rows are read newest-run first, so the bound only ever drops the +// oldest owners, never the sessions a client can still be writing. +const sessionOwnerScanLimit = 1024 + +// ActiveSessionOwners reports every currently active agent session, deduped by +// session id (newest owning run wins). func (s *Store) ActiveSessionOwners(ctx context.Context) ([]SessionOwner, error) { - rows, err := s.db.QueryContext(ctx, `SELECT s.session_id,COALESCE(o.backend,'v2'),r.workspace,COALESCE(o.reference,''),s.run_id -FROM run_steps s JOIN pipeline_runs r ON r.id=s.run_id LEFT JOIN run_session_owners o ON o.run_id=s.run_id AND o.sequence=s.sequence WHERE s.agent_active=1 AND s.session_id<>''`) + return s.sessionOwners(ctx, true) +} + +// OwnedSessions reports every session the server ever recorded in run_steps, +// deduped by session id (newest owning run wins) and including inactive ones, so +// chat_sessions can be restricted to sessions this server created. +func (s *Store) OwnedSessions(ctx context.Context) ([]SessionOwner, error) { + return s.sessionOwners(ctx, false) +} + +// sessionOwners is the single ownership query both ActiveSessionOwners and +// OwnedSessions run, so the SQL is not duplicated. It reads one bounded, +// newest-run-first window and drops repeated session ids in favour of the most +// recent owning run's directory and active flag. +func (s *Store) sessionOwners(ctx context.Context, activeOnly bool) ([]SessionOwner, error) { + query := `SELECT s.session_id,COALESCE(o.backend,'v2'),r.workspace,COALESCE(o.reference,''),s.run_id,s.agent_active +FROM run_steps s JOIN pipeline_runs r ON r.id=s.run_id LEFT JOIN run_session_owners o ON o.run_id=s.run_id AND o.sequence=s.sequence WHERE s.session_id<>''` + if activeOnly { + query += " AND s.agent_active=1" + } + query += " ORDER BY s.run_id DESC LIMIT ?" + rows, err := s.db.QueryContext(ctx, query, sessionOwnerScanLimit) if err != nil { return nil, err } defer rows.Close() + seen := map[string]struct{}{} var owners []SessionOwner for rows.Next() { var owner SessionOwner - if err = rows.Scan(&owner.ID, &owner.Backend, &owner.Directory, &owner.Reference, &owner.RunID); err != nil { + var active int + if err = rows.Scan(&owner.ID, &owner.Backend, &owner.Directory, &owner.Reference, &owner.RunID, &active); err != nil { return nil, err } + owner.Active = active != 0 + if _, ok := seen[owner.ID]; ok { + continue + } + seen[owner.ID] = struct{}{} owners = append(owners, owner) } return owners, rows.Err() diff --git a/internal/pipeline/runs_test.go b/internal/pipeline/runs_test.go index bd1a281c..ec165034 100644 --- a/internal/pipeline/runs_test.go +++ b/internal/pipeline/runs_test.go @@ -149,3 +149,66 @@ func TestActiveAgentSessionsAreScopedToRun(t *testing.T) { t.Fatalf("second run's own session was affected: %v %v", sessions, err) } } + +// TestOwnedSessionsListsRecordedWithActiveFlag proves OwnedSessions returns every +// session the server ever recorded (active or not) in run_steps, deduped by +// session id in favour of the newest owning run, with that run's workspace +// directory and the active flag. +func TestOwnedSessionsListsRecordedWithActiveFlag(t *testing.T) { + ctx := context.Background() + store, err := Open(filepath.Join(t.TempDir(), "owned.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if _, err := store.Submit(ctx, "owned", 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) + } + record := func(key, workspace, session string, active bool) { + t.Helper() + run, _, err := store.CreateRun(ctx, definition, key, workspace, false, nil, nil) + 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, session, active, "v2", "/repo"); err != nil { + t.Fatal(err) + } + } + record("owned-a", "/work/a", "ses_active", true) + record("owned-b", "/work/b", "ses_idle", false) + // The same session recorded by a newer run must dedupe to one entry, taking + // the newest run's workspace and active flag. + record("owned-c", "/work/c", "ses_idle", true) + + owners, err := store.OwnedSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(owners) != 2 { + t.Fatalf("owned sessions = %+v, want 2 deduped", owners) + } + byID := map[string]SessionOwner{} + for _, owner := range owners { + byID[owner.ID] = owner + } + if owner, ok := byID["ses_active"]; !ok || !owner.Active || owner.Directory != "/work/a" { + t.Fatalf("active owner = %+v", owner) + } + if owner, ok := byID["ses_idle"]; !ok || !owner.Active || owner.Directory != "/work/c" { + t.Fatalf("deduped owner should come from the newest run: %+v", owner) + } + if active, err := store.ActiveSessionOwners(ctx); err != nil || len(active) != 2 { + t.Fatalf("ActiveSessionOwners = %+v %v, want both now-active sessions", active, err) + } +} diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index 2d848f19..33ce57e0 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -87,6 +87,11 @@ type ChatSession struct { ParentID string `json:"parent_id,omitempty"` CreatedAt int64 `json:"created_at,omitempty"` UpdatedAt int64 `json:"updated_at,omitempty"` + // Busy marks a session another client currently holds (or one the server + // itself owns as an active run), so the phone can show it read-only instead + // of letting two clients silently write the same conversation. It is + // additive and optional: older peers ignore it. + Busy bool `json:"busy,omitempty"` } // ChatCreateRequest is the chat_create request body: a title and an optional diff --git a/internal/protocol/chat_test.go b/internal/protocol/chat_test.go index 8b71040c..046a9ced 100644 --- a/internal/protocol/chat_test.go +++ b/internal/protocol/chat_test.go @@ -21,6 +21,7 @@ func chatSamples() []struct { ID: "ses_1", Title: "demo", Agent: "build", Model: "deepseek-v4.1-flash", Directory: "/work", ParentID: "ses_0", CreatedAt: 1792112366711, UpdatedAt: 1792112367999, }}, + {"session_busy", ChatSession{ID: "ses_2", Title: "held", Busy: true}}, {"create", ChatCreateRequest{Title: "demo", Directory: "/work"}}, {"query", ChatQuery{SessionID: "ses_1", Limit: 50}}, {"prompt", ChatPromptRequest{SessionID: "ses_1", Text: "hello", Model: "m", Agent: "build", Files: []string{"file:///tmp/a.png"}}}, diff --git a/internal/server/chat.go b/internal/server/chat.go index ecc759db..4541cf4b 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -2,6 +2,8 @@ package server import ( "context" + "crypto/rand" + "encoding/hex" "errors" "log" "strings" @@ -9,6 +11,7 @@ import ( "time" "git.a-wan.net/alan/pipelines/internal/opencode" + "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" ) @@ -23,6 +26,9 @@ type chatBroker interface { Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error 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. + Sessions(ctx context.Context) ([]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) @@ -49,6 +55,18 @@ const chatRetainedLimit = opencode.MaxResponse // least-recently-updated turn is evicted once the cap is exceeded. const chatMaxTurns = 128 +// 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 +// a new writer and must re-claim. +func chatClientToken() string { + var b [8]byte + if _, err := rand.Read(b[:]); err != nil { + return "conn-unknown" + } + return "conn-" + hex.EncodeToString(b[:]) +} + // chatHub retains the accumulated turn state per session, independently of any // single connection, so a reconnecting client can re-sync what it missed. State // is keyed by session and then by message id (a session holds many turns), and @@ -57,6 +75,10 @@ type chatHub struct { mu sync.Mutex turns map[string]*chatTurn now func() time.Time + // claims maps a session to the client currently writing it so a second + // client is rejected; claimOrder bounds the map like chatMaxTurns. + claims map[string]string + claimOrder []string } // chatPart is the retained form of one part. Text and reasoning deltas append to @@ -223,6 +245,70 @@ func (h *chatHub) evictLocked() { } } +// claim reserves sessionID for clientID. It reports true when the session is +// free or already held by the same client (so a client may re-prompt its own +// session) and false when another client holds it. The claim map is bounded by +// chatMaxTurns with oldest-eviction so a stuck client cannot grow it without +// limit. +func (h *chatHub) claim(sessionID, clientID string) bool { + if sessionID == "" || clientID == "" { + return false + } + h.mu.Lock() + defer h.mu.Unlock() + if h.claims == nil { + h.claims = map[string]string{} + } + if holder, ok := h.claims[sessionID]; ok { + return holder == clientID + } + h.evictClaimsLocked() + h.claims[sessionID] = clientID + h.claimOrder = append(h.claimOrder, sessionID) + return true +} + +// release drops the same client's claim on sessionID; a claim held by a +// different client is left untouched so a stale release cannot free a live one. +func (h *chatHub) release(sessionID, clientID string) { + h.mu.Lock() + defer h.mu.Unlock() + if holder, ok := h.claims[sessionID]; !ok || holder != clientID { + return + } + delete(h.claims, sessionID) + for i, id := range h.claimOrder { + if id == sessionID { + h.claimOrder = append(h.claimOrder[:i], h.claimOrder[i+1:]...) + break + } + } +} + +// busyForOther reports whether another client currently holds sessionID. +func (h *chatHub) busyForOther(sessionID, clientID string) bool { + h.mu.Lock() + defer h.mu.Unlock() + holder, ok := h.claims[sessionID] + return ok && holder != clientID +} + +// evictClaimsLocked drops the oldest claim when the cap is reached, keeping the +// claim map bounded like the retained turns. Callers must hold h.mu. +func (h *chatHub) evictClaimsLocked() { + if len(h.claims) < chatMaxTurns { + return + } + for len(h.claimOrder) > 0 { + oldest := h.claimOrder[0] + h.claimOrder = h.claimOrder[1:] + if _, ok := h.claims[oldest]; ok { + delete(h.claims, oldest) + return + } + } +} + // turnLocked returns the session's retained turn, creating it (and evicting the // least-recently-updated turn first when the cap is reached) and refreshing its // update time. It is the shared turn-initialization path for apply and @@ -347,10 +433,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, write func(protocol.Message) error) bool { +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 { switch request.Type { case protocol.ChatPrompt: - handleChatPrompt(ctx, request, broker, hub, write) + handleChatPrompt(ctx, request, broker, hub, clientID, write) return true case protocol.ChatMessages: handleChatMessages(ctx, request, broker, hub, write) @@ -361,17 +447,91 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker case protocol.ChatReply: handleChatSimple(ctx, request, broker, hub, write) return true - case protocol.ChatSessions, protocol.ChatCreate: - // Declared in the protocol for the client but not yet brokered. 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: "chat_sessions and chat_create are not yet brokered"}) + case protocol.ChatSessions: + handleChatSessions(ctx, request, broker, hub, owners, clientID, write) + return true + case protocol.ChatCreate: + // chat_create remains declared for the client but not yet brokered. + // 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: "chat_create is not yet brokered"}) return true } return false } -func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, write func(protocol.Message) error) { +// 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) { + 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) + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + 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} + for _, session := range sessions { + owner, ok := owned[session.ID] + if !ok { + continue + } + if session.Directory == "" { + session.Directory = owner.Directory + } + if owner.Active || hub.busyForOther(session.ID, clientID) { + session.Busy = true + } + 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 + } + list, err := owners(ctx) + if err != nil { + return nil, err + } + 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 + } + return set, nil +} + +func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, 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 @@ -395,12 +555,19 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat prompt exceeds 64 KiB"}) return } + // Claim the session before subscribing or prompting: a second client must be + // rejected here, before any broker call, so two clients cannot silently write + // the same conversation. The same client may re-prompt its own session. + sessionID := prompt.SessionID + if !hub.claim(sessionID, clientID) { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is busy with another client"}) + return + } // Subscribe to the OpenCode firehose before posting the prompt: the stream // has no replay cursor (research 2.4), so a delta emitted between the POST // and the subscription would otherwise be lost. Frames that arrive before the // ack is written are buffered and flushed in order after it. - sessionID := prompt.SessionID streamCtx, streamCancel := context.WithCancel(ctx) attached := make(chan struct{}) var attachOnce sync.Once @@ -428,17 +595,20 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat case <-attached: case err := <-streamResult: streamCancel() + hub.release(sessionID, clientID) if err != nil && ctx.Err() == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat stream: " + err.Error()}) } return case <-ctx.Done(): streamCancel() + hub.release(sessionID, clientID) return } if err := broker.Prompt(ctx, sessionID, prompt.Text); err != nil { streamCancel() + hub.release(sessionID, clientID) _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) return } @@ -446,6 +616,7 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat // 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 { streamCancel() + hub.release(sessionID, clientID) return } // Flush frames buffered while the prompt was accepted, then resume live @@ -460,11 +631,12 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat if err := write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}); err != nil { bufferMu.Unlock() streamCancel() + hub.release(sessionID, clientID) return } } bufferMu.Unlock() - go drainChatStream(ctx, streamResult, streamCancel, sessionID, write) + go drainChatStream(ctx, streamResult, streamCancel, hub, sessionID, clientID, write) // Poll for pending approval requests alongside the event stream, sharing // streamCtx so the poller stops when the stream ends or the client // disconnects. The first poll runs immediately. @@ -532,9 +704,11 @@ func pushChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, s } // drainChatStream reports the terminal error of a chat subscription and releases -// its context once the stream has ended. -func drainChatStream(ctx context.Context, result <-chan error, cancel context.CancelFunc, sessionID string, write func(protocol.Message) error) { +// its context and the session claim once the stream has ended, so a later client +// is no longer blocked and nothing leaks. +func drainChatStream(ctx context.Context, result <-chan error, cancel context.CancelFunc, hub *chatHub, sessionID, clientID string, write func(protocol.Message) error) { defer cancel() + defer hub.release(sessionID, clientID) if err := <-result; err != nil && ctx.Err() == nil { log.Printf("chat stream session=%s: %v", sessionID, err) _ = write(protocol.Message{Type: protocol.Error, Error: "chat stream: " + err.Error()}) diff --git a/internal/server/chat_test.go b/internal/server/chat_test.go index d7184520..e4c58fbb 100644 --- a/internal/server/chat_test.go +++ b/internal/server/chat_test.go @@ -16,6 +16,7 @@ import ( "github.com/coder/websocket/wsjson" "git.a-wan.net/alan/pipelines/internal/opencode" + "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" ) @@ -36,6 +37,9 @@ type fakeChat struct { permissionSessionID string permissions []protocol.ChatPermissionFrame permissionErr error + sessionCalls int + sessions []protocol.ChatSession + sessionErr error permBlock bool permDone chan struct{} permOnce sync.Once @@ -148,6 +152,22 @@ func (f *fakeChat) permissionQuery() (int, string) { return f.permissionCalls, f.permissionSessionID } +// Sessions returns the seeded session list and counts each call so a test can +// assert the list handler asks the broker at most once per request. +func (f *fakeChat) Sessions(context.Context) ([]protocol.ChatSession, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.sessionCalls++ + return f.sessions, f.sessionErr +} + +// sessionQuery reports the recorded chat_sessions call count. +func (f *fakeChat) sessionQuery() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.sessionCalls +} + // 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) { @@ -176,16 +196,33 @@ func scriptedChat() *fakeChat { } func dialChat(t *testing.T, broker chatBroker) (context.Context, context.CancelFunc, *websocket.Conn) { + t.Helper() + return dialChatOptions(t, Options{Chat: broker}) +} + +func dialChatOptions(t *testing.T, options Options) (context.Context, context.CancelFunc, *websocket.Conn) { + t.Helper() + ctx, cancel, conns := dialChatConns(t, options, 1) + return ctx, cancel, conns[0] +} + +// dialChatConns starts one server and dials n connections to the same hub, so a +// test can exercise two clients contending for one session. +func dialChatConns(t *testing.T, options Options, n int) (context.Context, context.CancelFunc, []*websocket.Conn) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - srv := httptest.NewServer(HandlerWithOptions(ctx, Options{Chat: broker})) + srv := httptest.NewServer(HandlerWithOptions(ctx, options)) t.Cleanup(func() { srv.Close(); cancel() }) - conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil) - if err != nil { - t.Fatal(err) + conns := make([]*websocket.Conn, 0, n) + for i := 0; i < n; i++ { + conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { conn.CloseNow() }) + conns = append(conns, conn) } - t.Cleanup(func() { conn.CloseNow() }) - return ctx, cancel, conn + return ctx, cancel, conns } func readChatTurn(t *testing.T, ctx context.Context, conn *websocket.Conn) []protocol.ChatEventFrame { @@ -928,23 +965,155 @@ func TestChatPromptRejectsEmptyText(t *testing.T) { } } -// TestChatSessionsAndCreateAnswerExplicitly pins the declared-but-unbrokered -// boundary: chat_sessions and chat_create are answered with a protocol error -// rather than falling through to the generic Pong. -func TestChatSessionsAndCreateAnswerExplicitly(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) { broker := scriptedChat() ctx, _, conn := dialChat(t, broker) - for _, typ := range []string{protocol.ChatSessions, protocol.ChatCreate} { - if err := wsjson.Write(ctx, conn, protocol.Message{Type: typ, ID: "c1"}); err != nil { + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "c1"}); 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) + } +} + +// 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) { + broker := scriptedChat() + broker.sessions = []protocol.ChatSession{ + {ID: "ses_owned", Title: "ours", Directory: "/work"}, + {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}) + 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 || 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 response.ChatSessions[0].Busy { + t.Fatalf("inactive owned session marked busy: %+v", response.ChatSessions[0]) + } + 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. +func TestChatSessionsFailsClosedWithoutOwnership(t *testing.T) { + broker := scriptedChat() + broker.sessions = []protocol.ChatSession{{ID: "ses_1"}, {ID: "ses_2"}} + ctx, _, conn := dialChat(t, broker) + 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("unowned sessions were exposed: %+v", response) + } +} + +// TestChatSessionsBusyRejectsSecondClient is the task evidence for busy state: +// while client A holds ses_1 with a blocking prompt, client B's chat_sessions +// reports ses_1 Busy=true and B's chat_prompt for ses_1 is rejected before any +// broker.Prompt call; after A disconnects the claim is released and a later list +// is no longer busy. +func TestChatSessionsBusyRejectsSecondClient(t *testing.T) { + 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) + 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 { + t.Fatal(err) + } + var ack protocol.Message + if err := wsjson.Read(ctx, connA, &ack); err != nil { + t.Fatal(err) + } + if ack.Type != protocol.ChatPrompt || ack.ID != "a1" { + t.Fatalf("prompt ack = %+v", ack) + } + + if err := wsjson.Write(ctx, connB, protocol.Message{Type: protocol.ChatSessions, ID: "b1"}); err != nil { + t.Fatal(err) + } + var listing protocol.Message + if err := wsjson.Read(ctx, connB, &listing); err != nil { + t.Fatal(err) + } + if listing.Type != protocol.ChatSessions || len(listing.ChatSessions) != 1 || !listing.ChatSessions[0].Busy { + t.Fatalf("held session not marked busy: %+v", listing) + } + + if err := wsjson.Write(ctx, connB, protocol.Message{Type: protocol.ChatPrompt, ID: "b2", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hello"}}); err != nil { + t.Fatal(err) + } + var rejected protocol.Message + if err := wsjson.Read(ctx, connB, &rejected); err != nil { + t.Fatal(err) + } + if rejected.Type != protocol.Error || !strings.Contains(rejected.Error, "busy") { + t.Fatalf("second client's prompt was not rejected as busy: %+v", rejected) + } + if prompts, _, _ := broker.counts(); prompts != 1 { + t.Fatalf("busy prompt reached OpenCode: %d prompt calls, want 1", prompts) + } + + // Disconnecting A releases the claim so a later client is no longer blocked. + if err := connA.Close(websocket.StatusNormalClosure, ""); err != nil { + t.Fatal(err) + } + select { + case <-broker.done: + case <-time.After(5 * time.Second): + t.Fatal("stream did not stop after disconnect") + } + deadline := time.Now().Add(5 * time.Second) + for { + if err := wsjson.Write(ctx, connB, protocol.Message{Type: protocol.ChatSessions, ID: "b3"}); err != nil { t.Fatal(err) } - var response protocol.Message - if err := wsjson.Read(ctx, conn, &response); err != nil { + var after protocol.Message + if err := wsjson.Read(ctx, connB, &after); err != nil { t.Fatal(err) } - if response.Type != protocol.Error || response.ID != "c1" { - t.Fatalf("%s did not answer with an explicit error: %+v", typ, response) + if after.Type == protocol.ChatSessions && len(after.ChatSessions) == 1 && !after.ChatSessions[0].Busy { + return } + if time.Now().After(deadline) { + t.Fatalf("claim not released after disconnect: %+v", after) + } + time.Sleep(10 * time.Millisecond) } } diff --git a/internal/server/websocket.go b/internal/server/websocket.go index e237010a..e311d376 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -26,6 +26,11 @@ 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) } // Handler serves the persistent connection with default options. Canceling ctx @@ -53,6 +58,13 @@ 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 + // handler fails closed to an empty list. + owned := options.OwnedSessions + if owned == nil && len(stores) > 0 { + owned = stores[0].OwnedSessions + } mux.HandleFunc("GET /artifacts/{run}/{step}/{name...}", func(w http.ResponseWriter, r *http.Request) { if runs == nil { http.NotFound(w, r) @@ -90,6 +102,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin defer cancel() return wsjson.Write(writeCtx, conn, message) } + // clientID is this connection's identity for chat session claims: a + // second client is refused a session another connection holds. + clientID := chatClientToken() if len(stores) > 0 { items, err := stores[0].List(ctx) if err != nil { @@ -106,7 +121,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, write) { + if handleChat(connCtx, request, options.Chat, hub, owned, clientID, write) { continue } response := protocol.Message{Type: protocol.Pong, ID: request.ID}