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