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
+16 -1
View File
@@ -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}