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.
This commit is contained in:
2026-10-16 09:21:50 +01:00
parent dca72a09ee
commit 1818a06d2f
11 changed files with 711 additions and 38 deletions
+104
View File
@@ -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")