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:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user