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:
+186
-12
@@ -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()})
|
||||
|
||||
+185
-16
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
Reference in New Issue
Block a user