Fan a chat session out to every client and share approvals exactly-once
A session was owned by one connection: the claim map in chat_claims.go let the
first client hold it, every other client saw the session Busy and read-only, and
a second client's prompt was rejected. Replace the claim with a per-session
"room" so the operator's phone, tablet and terminal all watch and write the same
conversation, and a pending approval is a shared, exactly-once object.
Server (internal/server, internal/protocol):
- New chat_room.go: one room per session holding the session's single broker
stream, its one bounded prompt queue (8) and the fan-out to every attached
client. A chat_subscribe frame attaches a connection to a session's shared
stream and replays the still-unresolved approval requests the room holds.
- chat_stream.go: handleChatPrompt accepts a prompt from any client. It attaches
the sender, either starts a turn or queues the prompt behind the in-flight turn
and acknowledges it with chat_queued:true ("queued" is the chosen behaviour,
stated on the wire and in docs/cli.md), and echoes the user turn to every other
client attributed to the sender's label. The prompt handler no longer owns the
stream; one turn runner per room drains the queue, so two turns never
interleave. Per-connection write serialisation is unchanged (each chatSub has
its own writer goroutine and bounded buffer).
- chat_permissions.go / chat_commands.go: an approval is reserved by the first
answer and confirmed once delivered; the first answer wins, is recorded with
the answering client's label, and the resolution is pushed to every watching
client as chat_permission with resolved/decision/resolved_by so their cards
clear. A later answer is refused with an error naming the client that answered,
and never reaches the agent twice; a reservation whose reply failed is
released.
- chat_hub.go / chat_sessions.go / chat.go: the hub now owns rooms and the
user-turn id sequence; the resulting user turns are retained (role and client
carried) so a reconnect re-syncs who said what. chat_sessions no longer marks a
session Busy and its clientID parameter is gone; the protocol keeps the Busy
field for wire compatibility only. websocket.go detaches a connection's chat
subscriptions when the read loop ends.
- chat_claims.go is removed, not left vestigial: the only exclusive thing left is
a turn, and the room's queue is that.
App (android):
- PipelinesRepository carries a stable per-device client label (Build.MODEL, with
a fallback) on prompts and replies, and adds chatSubscribe; AppViewModel
subscribes on opening a chat (best-effort, an older server's error frame does
not stop history loading) and records the queued ack.
- ChatStore folds a user frame from another client into the transcript once,
attributed by the sender's label, and never receives its own prompt back, so
the sender's own message is never duplicated. ChatThread.readOnly is gone:
canSend no longer depends on another client, the composer says "Queued - it
will send when the current turn finishes." instead of disabling input, and the
status label is Running/Idle only. Scroll/follow behaviour is untouched.
- Tests: ChatProtocolTest round-trips the new wire fields, ChatFormatTest asserts
the stale Busy flag cannot produce a read-only label, MultiChatStateTest asserts
a session another client watches stays writable.
Reflected where it belongs: no packaged template changes (no bundled starter
embeds the chat protocol). Checked the packaged authoring skill references: none
of them describes the chat wire beyond operations.md, and
internal/author/skill/references/operations.md is now stale - its "Brokered
OpenCode chat" section still says chat_sessions marks "busy" when another client
holds the session and that a second client's chat_prompt is rejected, and it does
not mention chat_subscribe, the per-session prompt queue/chat_queued, the
per-client label or the shared exactly-once approval (it also still describes the
per-subscription permission poller, which the room's single poller replaced). The
supported semantics are the ones in docs/cli.md, updated in this commit; the
operations.md section needs a rewrite to match. No README or other shared
document was edited here.
Checks run on the committed tree: gofmt -l internal cmd examples (nothing), go
build ./..., go vet ./internal/... ./cmd/..., go test ./internal/server
./internal/protocol ./internal/stage ./internal/pipeline.
This commit is contained in:
@@ -46,10 +46,10 @@ type operatorRegistry interface {
|
||||
OperatorDirectories(ctx context.Context, limit int) ([]string, error)
|
||||
}
|
||||
|
||||
// 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.
|
||||
// chatClientToken returns an unguessable per-connection identity. Its only role
|
||||
// is to key a connection's chat-room subscriptions and to exclude the sender from
|
||||
// its own fan-out; it carries no ownership. A fresh token per connection means a
|
||||
// reconnected client is a new identity and simply reattaches.
|
||||
func chatClientToken() string {
|
||||
var b [8]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
@@ -68,6 +68,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatPrompt:
|
||||
handleChatPrompt(ctx, request, broker, hub, registry, clientID, write)
|
||||
return true
|
||||
case protocol.ChatSubscribe:
|
||||
handleChatSubscribe(request, broker, hub, clientID, write)
|
||||
return true
|
||||
case protocol.ChatMessages:
|
||||
handleChatMessages(ctx, request, broker, hub, write)
|
||||
return true
|
||||
@@ -78,7 +81,7 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
handleChatSimple(ctx, request, broker, hub, write)
|
||||
return true
|
||||
case protocol.ChatSessions:
|
||||
handleChatSessions(ctx, request, broker, hub, registry, clientID, write)
|
||||
handleChatSessions(ctx, request, broker, hub, registry, write)
|
||||
return true
|
||||
case protocol.ChatCreate:
|
||||
handleChatCreate(ctx, request, broker, registry, write)
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
package server
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,9 +68,27 @@ func handleChatSimple(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid permission decision is required"})
|
||||
return
|
||||
}
|
||||
// A pending approval is shared and exactly-once: the first answer wins and is
|
||||
// recorded with the client that gave it, and a later answer is refused as
|
||||
// already answered rather than reaching the agent twice.
|
||||
label := sanitizeChatClientLabel(reply.Client)
|
||||
if hub != nil {
|
||||
if prior, ok := hub.reservePermission(reply.SessionID, reply.RequestID, label); !ok {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: permissionRefusal(prior, reply.RequestID)})
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := broker.Reply(ctx, *reply); err != nil {
|
||||
if hub != nil {
|
||||
hub.releasePermission(reply.SessionID, reply.RequestID)
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatReply, ID: request.ID})
|
||||
if hub != nil {
|
||||
// Push the resolution to every client watching the session so each card
|
||||
// clears and shows the outcome and which device answered.
|
||||
hub.confirmPermission(reply.SessionID, reply.RequestID, label, reply.Decision)
|
||||
}
|
||||
}
|
||||
|
||||
+73
-15
@@ -1,7 +1,9 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -22,15 +24,18 @@ const chatMaxTurns = 128
|
||||
// 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
|
||||
// is capped at chatRetainedLimit.
|
||||
// is capped at chatRetainedLimit. It also owns the per-session live rooms: the
|
||||
// one broker stream, the prompt queue and the fan-out to every attached client.
|
||||
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
|
||||
mu sync.Mutex
|
||||
turns map[string]*chatTurn
|
||||
rooms map[string]*chatRoom
|
||||
baseCtx context.Context
|
||||
registry operatorRegistry
|
||||
now func() time.Time
|
||||
// userSeq is a monotonic source of ids for the user turns the server echoes
|
||||
// to the other clients, so each retained user message has a stable id.
|
||||
userSeq int
|
||||
}
|
||||
|
||||
// chatPart is the retained form of one part. Text and reasoning deltas append to
|
||||
@@ -40,12 +45,16 @@ type chatPart struct {
|
||||
text []byte
|
||||
}
|
||||
|
||||
// chatMessage is one retained assistant turn. Its parts keep the exact ids the
|
||||
// supporting chat_event frames carried, so a resume preserves attribution.
|
||||
// chatMessage is one retained turn. Its parts keep the exact ids the supporting
|
||||
// chat_event frames carried, so a resume preserves attribution. Role and client
|
||||
// are carried for a user turn the server echoed (a prompt another client sent),
|
||||
// so a resumed transcript still says who sent it.
|
||||
type chatMessage struct {
|
||||
id string
|
||||
order []string
|
||||
parts map[string]*chatPart
|
||||
id string
|
||||
role string
|
||||
client string
|
||||
order []string
|
||||
parts map[string]*chatPart
|
||||
}
|
||||
|
||||
type chatTurn struct {
|
||||
@@ -62,10 +71,33 @@ type chatTurn struct {
|
||||
// bounds it to chatPermissionRetainedLimit.
|
||||
permissions map[string]struct{}
|
||||
permissionOrder []string
|
||||
// resolutions records the shared exactly-once answers to permission requests,
|
||||
// keyed by request id, so a second answer is refused and the recorded outcome
|
||||
// survives the clients that gave it; resolutionOrder bounds it to
|
||||
// chatPermissionRetainedLimit like the dedup set above.
|
||||
resolutions map[string]*chatResolution
|
||||
resolutionOrder []string
|
||||
}
|
||||
|
||||
// chatResolution is the shared answer to one permission request. answered is
|
||||
// false while the first answer is still being delivered to the agent, so a
|
||||
// concurrent second answer is refused without ever reaching the agent twice.
|
||||
type chatResolution struct {
|
||||
client string
|
||||
decision string
|
||||
answered bool
|
||||
}
|
||||
|
||||
func newChatHub() *chatHub {
|
||||
return &chatHub{turns: map[string]*chatTurn{}, now: time.Now}
|
||||
return &chatHub{turns: map[string]*chatTurn{}, rooms: map[string]*chatRoom{}, baseCtx: context.Background(), now: time.Now}
|
||||
}
|
||||
|
||||
// nextUserMessageID mints a stable id for one echoed user turn.
|
||||
func (h *chatHub) nextUserMessageID() string {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.userSeq++
|
||||
return "usr_" + strconv.Itoa(h.userSeq)
|
||||
}
|
||||
|
||||
func (h *chatHub) clock() time.Time {
|
||||
@@ -100,11 +132,33 @@ func (h *chatHub) apply(frame protocol.ChatEventFrame) {
|
||||
}
|
||||
message := turn.messages[frame.MessageID]
|
||||
if message == nil {
|
||||
message = &chatMessage{id: frame.MessageID, parts: map[string]*chatPart{}}
|
||||
role := protocol.ChatRoleAssistant
|
||||
client := ""
|
||||
if frame.Kind == protocol.ChatEventUser {
|
||||
role = protocol.ChatRoleUser
|
||||
client = frame.Client
|
||||
}
|
||||
message = &chatMessage{id: frame.MessageID, role: role, client: client, parts: map[string]*chatPart{}}
|
||||
turn.order = append(turn.order, frame.MessageID)
|
||||
turn.messages[frame.MessageID] = message
|
||||
} else if message.client == "" && frame.Kind == protocol.ChatEventUser {
|
||||
message.client = frame.Client
|
||||
}
|
||||
switch frame.Kind {
|
||||
case protocol.ChatEventUser:
|
||||
if frame.Part == nil || frame.Part.ID == "" || frame.Part.Text == "" || turn.overflow {
|
||||
return
|
||||
}
|
||||
if !turn.retain(len(frame.Part.Text)) {
|
||||
return
|
||||
}
|
||||
part, ok := message.parts[frame.Part.ID]
|
||||
if !ok {
|
||||
part = &chatPart{part: protocol.ChatPart{Type: protocol.ChatPartText, ID: frame.Part.ID}}
|
||||
message.order = append(message.order, frame.Part.ID)
|
||||
message.parts[frame.Part.ID] = part
|
||||
}
|
||||
part.text = append(part.text, frame.Part.Text...)
|
||||
case protocol.ChatEventText, protocol.ChatEventReasoning:
|
||||
id := ""
|
||||
if frame.Part != nil {
|
||||
@@ -255,6 +309,10 @@ func (h *chatHub) snapshot(sessionID string) []protocol.ChatMessage {
|
||||
continue
|
||||
}
|
||||
out := protocol.ChatMessage{ID: id, SessionID: sessionID, Role: protocol.ChatRoleAssistant}
|
||||
if message.role != "" {
|
||||
out.Role = message.role
|
||||
}
|
||||
out.Client = message.client
|
||||
for _, partID := range message.order {
|
||||
if part, ok := message.parts[partID]; ok {
|
||||
piece := part.part
|
||||
|
||||
@@ -0,0 +1,472 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// channelChat is a broker whose stream is driven frame-by-frame from a channel,
|
||||
// so a test can hold a turn in flight and prove prompt serialisation, fan-out and
|
||||
// exactly-once approval behaviour without a real OpenCode service.
|
||||
type channelChat struct {
|
||||
mu sync.Mutex
|
||||
prompts []string
|
||||
perm []protocol.ChatPermissionFrame
|
||||
replies []protocol.ChatReplyRequest
|
||||
frames chan protocol.ChatEventFrame
|
||||
ready chan struct{}
|
||||
once sync.Once
|
||||
// promptErrAt, when nonzero, is the 1-based index of the Prompt call that
|
||||
// fails, so a test can prove a broker failure is reported to the client that
|
||||
// sent the prompt.
|
||||
promptErrAt int
|
||||
}
|
||||
|
||||
func newChannelChat() *channelChat {
|
||||
return &channelChat{frames: make(chan protocol.ChatEventFrame, 32), ready: make(chan struct{})}
|
||||
}
|
||||
|
||||
func (c *channelChat) Prompt(_ context.Context, _, text string) error {
|
||||
c.mu.Lock()
|
||||
c.prompts = append(c.prompts, text)
|
||||
fail := c.promptErrAt != 0 && len(c.prompts) == c.promptErrAt
|
||||
c.mu.Unlock()
|
||||
if fail {
|
||||
return errors.New("broker rejected the prompt")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *channelChat) Stream(ctx context.Context, _ string, ready func(), emit func(protocol.ChatEventFrame) error) error {
|
||||
c.once.Do(func() {
|
||||
close(c.ready)
|
||||
if ready != nil {
|
||||
ready()
|
||||
}
|
||||
})
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case frame := <-c.frames:
|
||||
if err := emit(frame); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *channelChat) Interrupt(context.Context, string) error { return nil }
|
||||
|
||||
func (c *channelChat) Messages(context.Context, string, int) ([]protocol.ChatMessage, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *channelChat) Sessions(context.Context) ([]protocol.ChatSession, error) { return nil, nil }
|
||||
|
||||
func (c *channelChat) Create(_ context.Context, title, directory string) (protocol.ChatSession, error) {
|
||||
return protocol.ChatSession{ID: "ses_created", Title: title, Directory: directory}, nil
|
||||
}
|
||||
|
||||
func (c *channelChat) Session(context.Context, string) (protocol.ChatSession, bool, error) {
|
||||
return protocol.ChatSession{}, false, nil
|
||||
}
|
||||
|
||||
func (c *channelChat) Permissions(context.Context, string) ([]protocol.ChatPermissionFrame, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return append([]protocol.ChatPermissionFrame(nil), c.perm...), nil
|
||||
}
|
||||
|
||||
func (c *channelChat) Reply(_ context.Context, request protocol.ChatReplyRequest) error {
|
||||
c.mu.Lock()
|
||||
c.replies = append(c.replies, request)
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *channelChat) push(frame protocol.ChatEventFrame) {
|
||||
c.frames <- frame
|
||||
}
|
||||
|
||||
func (c *channelChat) promptCount() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return len(c.prompts)
|
||||
}
|
||||
|
||||
func (c *channelChat) promptTexts() []string {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return append([]string(nil), c.prompts...)
|
||||
}
|
||||
|
||||
func (c *channelChat) replyCount() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return len(c.replies)
|
||||
}
|
||||
|
||||
// dialChatServer starts one server and dials n connections, returning the server
|
||||
// so a test can reconnect a dropped client to the same hub.
|
||||
func dialChatServer(t *testing.T, options Options, n int) (context.Context, context.CancelFunc, *httptest.Server, []*websocket.Conn) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
srv := httptest.NewServer(HandlerWithOptions(ctx, options))
|
||||
t.Cleanup(func() { srv.Close(); cancel() })
|
||||
conns := make([]*websocket.Conn, 0, n)
|
||||
for i := 0; i < n; i++ {
|
||||
conns = append(conns, dialChatConn(t, ctx, srv))
|
||||
}
|
||||
return ctx, cancel, srv, conns
|
||||
}
|
||||
|
||||
func dialChatConn(t *testing.T, ctx context.Context, srv *httptest.Server) *websocket.Conn {
|
||||
t.Helper()
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { conn.CloseNow() })
|
||||
return conn
|
||||
}
|
||||
|
||||
// readUntil reads messages until one of type want arrives, failing on a server
|
||||
// error frame; interleaved push frames are skipped.
|
||||
func readUntil(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) protocol.Message {
|
||||
t.Helper()
|
||||
for {
|
||||
var message protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &message); err != nil {
|
||||
t.Fatalf("read (waiting for %s): %v", want, err)
|
||||
}
|
||||
if message.Type == protocol.Error {
|
||||
t.Fatalf("server error frame while waiting for %s: %s", want, message.Error)
|
||||
}
|
||||
if message.Type == want {
|
||||
return message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nextEvent reads the next chat_event frame strictly, so a test can assert the
|
||||
// order of the turn's frames.
|
||||
func nextEvent(t *testing.T, ctx context.Context, conn *websocket.Conn) protocol.ChatEventFrame {
|
||||
t.Helper()
|
||||
for {
|
||||
var message protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &message); err != nil {
|
||||
t.Fatalf("read event: %v", err)
|
||||
}
|
||||
if message.Type == protocol.Error {
|
||||
t.Fatalf("server error frame: %s", message.Error)
|
||||
}
|
||||
if message.Type == protocol.ChatEvent && message.ChatEvent != nil {
|
||||
return *message.ChatEvent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nextPermission reads the next chat_permission frame for requestID.
|
||||
func nextPermission(t *testing.T, ctx context.Context, conn *websocket.Conn, requestID string) protocol.ChatPermissionFrame {
|
||||
t.Helper()
|
||||
for {
|
||||
var message protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &message); err != nil {
|
||||
t.Fatalf("read permission: %v", err)
|
||||
}
|
||||
if message.Type == protocol.Error {
|
||||
t.Fatalf("server error frame: %s", message.Error)
|
||||
}
|
||||
if message.Type == protocol.ChatPermission && message.ChatPermission != nil && message.ChatPermission.RequestID == requestID {
|
||||
return *message.ChatPermission
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeChat(t *testing.T, ctx context.Context, conn *websocket.Conn, message protocol.Message) {
|
||||
t.Helper()
|
||||
if err := wsjson.Write(ctx, conn, message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatFanoutToSeveralClients is the multi-client acceptance test: a prompt
|
||||
// from one client is accepted, its user turn is pushed live to the other client
|
||||
// attributed to the sending device, and the turn's streaming frames reach every
|
||||
// watching client, not only the one that prompted.
|
||||
func TestChatFanoutToSeveralClients(t *testing.T) {
|
||||
broker := newChannelChat()
|
||||
ctx, _, _, conns := dialChatServer(t, Options{Chat: broker}, 2)
|
||||
phone, tablet := conns[0], conns[1]
|
||||
|
||||
// The tablet watches the session before anything is sent.
|
||||
writeChat(t, ctx, tablet, protocol.Message{Type: protocol.ChatSubscribe, ID: "s1", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}})
|
||||
readUntil(t, ctx, tablet, protocol.ChatSubscribe)
|
||||
|
||||
// The phone prompts. Its ack is not a queue acknowledgement.
|
||||
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ChatPrompt, ID: "p1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "from the phone", Client: "Pixel 9"}})
|
||||
ack := readUntil(t, ctx, phone, protocol.ChatPrompt)
|
||||
if ack.ID != "p1" || ack.ChatQueued {
|
||||
t.Fatalf("phone prompt ack = %+v, want accepted (not queued)", ack)
|
||||
}
|
||||
|
||||
// The tablet sees the phone's message, attributed to the phone.
|
||||
userFrame := nextEvent(t, ctx, tablet)
|
||||
if userFrame.Kind != protocol.ChatEventUser || userFrame.Client != "Pixel 9" || userFrame.Part == nil || userFrame.Part.Text != "from the phone" {
|
||||
t.Fatalf("tablet user frame = %+v, want the phone's message attributed to Pixel 9", userFrame)
|
||||
}
|
||||
|
||||
// The turn's streaming output reaches both clients in order.
|
||||
broker.push(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventText, Delta: "hel", Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1#0"}})
|
||||
broker.push(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventText, Delta: "lo", Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1#0"}})
|
||||
broker.push(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, Index: 1}})
|
||||
|
||||
for _, client := range []struct {
|
||||
name string
|
||||
conn *websocket.Conn
|
||||
}{{"phone", phone}, {"tablet", tablet}} {
|
||||
var text strings.Builder
|
||||
for i := 0; i < 2; i++ {
|
||||
frame := nextEvent(t, ctx, client.conn)
|
||||
if frame.Kind != protocol.ChatEventText {
|
||||
t.Fatalf("%s frame %d = %+v, want text", client.name, i, frame)
|
||||
}
|
||||
text.WriteString(frame.Delta)
|
||||
}
|
||||
if text.String() != "hello" {
|
||||
t.Fatalf("%s saw %q, want the streamed turn output", client.name, text.String())
|
||||
}
|
||||
if end := nextEvent(t, ctx, client.conn); end.Kind != protocol.ChatEventStep || end.Step == nil || end.Step.Status != protocol.ChatStepEnded {
|
||||
t.Fatalf("%s step frame = %+v, want ended", client.name, end)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPromptSerialisedPerSession pins that two prompts for one session never
|
||||
// interleave: the second is accepted as queued and only posted once the first
|
||||
// turn ends.
|
||||
func TestChatPromptSerialisedPerSession(t *testing.T) {
|
||||
broker := newChannelChat()
|
||||
ctx, _, _, conns := dialChatServer(t, Options{Chat: broker}, 2)
|
||||
phone, tablet := conns[0], conns[1]
|
||||
|
||||
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ChatPrompt, ID: "p1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "one"}})
|
||||
if ack := readUntil(t, ctx, phone, protocol.ChatPrompt); ack.ChatQueued {
|
||||
t.Fatalf("first prompt should start immediately: %+v", ack)
|
||||
}
|
||||
|
||||
// The tablet's prompt while the turn is in flight is queued, and it is told so.
|
||||
writeChat(t, ctx, tablet, protocol.Message{Type: protocol.ChatPrompt, ID: "p2", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "two"}})
|
||||
if ack := readUntil(t, ctx, tablet, protocol.ChatPrompt); !ack.ChatQueued {
|
||||
t.Fatalf("second prompt should be acknowledged as queued: %+v", ack)
|
||||
}
|
||||
if broker.promptCount() != 1 {
|
||||
t.Fatalf("prompts forwarded = %d, want 1 while the first turn is in flight", broker.promptCount())
|
||||
}
|
||||
|
||||
// End the first turn; the queued prompt is then posted.
|
||||
broker.push(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, Index: 1}})
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for broker.promptCount() < 2 {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("queued prompt was never posted: %v", broker.promptTexts())
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if got := broker.promptTexts(); len(got) != 2 || got[0] != "one" || got[1] != "two" {
|
||||
t.Fatalf("prompts = %v, want [one two] in order", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatApprovalFirstAnswerWins is the exactly-once acceptance test: a pending
|
||||
// approval is shared, the first answer is recorded with the client that gave it
|
||||
// and broadcast to every client, and a later answer is refused.
|
||||
func TestChatApprovalFirstAnswerWins(t *testing.T) {
|
||||
broker := newChannelChat()
|
||||
broker.perm = []protocol.ChatPermissionFrame{{SessionID: "ses_1", RequestID: "req_1", Action: "bash", Resources: []string{"rm -rf /tmp"}}}
|
||||
ctx, _, _, conns := dialChatServer(t, Options{Chat: broker}, 2)
|
||||
phone, tablet := conns[0], conns[1]
|
||||
|
||||
// A turn starts so the poller runs and pushes the pending request.
|
||||
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ChatPrompt, ID: "p1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "run it"}})
|
||||
readUntil(t, ctx, phone, protocol.ChatPrompt)
|
||||
|
||||
pending := nextPermission(t, ctx, phone, "req_1")
|
||||
if pending.Resolved {
|
||||
t.Fatalf("request already marked resolved: %+v", pending)
|
||||
}
|
||||
|
||||
// A second client attaches and is replayed the still-pending request, so its
|
||||
// card is answerable too.
|
||||
writeChat(t, ctx, tablet, protocol.Message{Type: protocol.ChatSubscribe, ID: "s1", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}})
|
||||
readUntil(t, ctx, tablet, protocol.ChatSubscribe)
|
||||
replay := nextPermission(t, ctx, tablet, "req_1")
|
||||
if replay.Resolved || replay.Action != "bash" {
|
||||
t.Fatalf("replayed permission = %+v, want the pending request", replay)
|
||||
}
|
||||
|
||||
// The phone answers first.
|
||||
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ChatReply, ID: "a1", ChatReply: &protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce, Client: "Pixel 9"}})
|
||||
readUntil(t, ctx, phone, protocol.ChatReply)
|
||||
|
||||
// Both clients see the resolution, with the answering device recorded.
|
||||
for _, client := range []struct {
|
||||
name string
|
||||
conn *websocket.Conn
|
||||
}{{"phone", phone}, {"tablet", tablet}} {
|
||||
resolution := nextPermission(t, ctx, client.conn, "req_1")
|
||||
if !resolution.Resolved || resolution.Decision != protocol.ChatDecisionOnce || resolution.ResolvedBy != "Pixel 9" {
|
||||
t.Fatalf("%s resolution = %+v, want resolved once by Pixel 9", client.name, resolution)
|
||||
}
|
||||
}
|
||||
|
||||
// The tablet's later answer is refused, and it never reaches the agent.
|
||||
writeChat(t, ctx, tablet, protocol.Message{Type: protocol.ChatReply, ID: "a2", ChatReply: &protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionAlways, Client: "Pixel 10 Pro Fold"}})
|
||||
var refused protocol.Message
|
||||
if err := wsjson.Read(ctx, tablet, &refused); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if refused.Type != protocol.Error || !strings.Contains(refused.Error, "already answered by Pixel 9") {
|
||||
t.Fatalf("second answer was not refused as already answered: %+v", refused)
|
||||
}
|
||||
if broker.replyCount() != 1 {
|
||||
t.Fatalf("broker replies = %d, want the agent to receive exactly one answer", broker.replyCount())
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatSubscribeWireShape pins the exact wire body the Android app sends for
|
||||
// chat_subscribe (ChatProtocol.subscribeRequest): the session id travels in the
|
||||
// chat_subscribe field, not chat_query. The handler once read chat_query, so the
|
||||
// unit tests passed while the shipped app's subscribe was silently rejected; this
|
||||
// test writes the raw JSON, attaches the connection and proves a prompt from
|
||||
// another client reaches it.
|
||||
func TestChatSubscribeWireShape(t *testing.T) {
|
||||
broker := newChannelChat()
|
||||
ctx, _, _, conns := dialChatServer(t, Options{Chat: broker}, 2)
|
||||
phone, watch := conns[0], conns[1]
|
||||
|
||||
if err := watch.Write(ctx, websocket.MessageText, []byte(`{"type":"chat_subscribe","id":"s1","chat_subscribe":{"session_id":"ses_1"}}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ack := readUntil(t, ctx, watch, protocol.ChatSubscribe); ack.ID != "s1" {
|
||||
t.Fatalf("subscribe ack = %+v, want id s1", ack)
|
||||
}
|
||||
|
||||
// The watcher is attached: another client's prompt is fanned out to it.
|
||||
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ChatPrompt, ID: "p1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "ping", Client: "Pixel 9"}})
|
||||
readUntil(t, ctx, phone, protocol.ChatPrompt)
|
||||
frame := nextEvent(t, ctx, watch)
|
||||
if frame.Kind != protocol.ChatEventUser || frame.Client != "Pixel 9" || frame.Part == nil || frame.Part.Text != "ping" {
|
||||
t.Fatalf("watcher frame = %+v, want the phone's message (subscribe did not attach)", frame)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatQueuedPromptFailureSurfaced pins that a prompt accepted as queued whose
|
||||
// delivery to the agent later fails is reported to the client that sent it,
|
||||
// instead of leaving its composer showing "Queued" with no error.
|
||||
func TestChatQueuedPromptFailureSurfaced(t *testing.T) {
|
||||
broker := newChannelChat()
|
||||
broker.promptErrAt = 2 // the queued (second) prompt fails to reach the agent
|
||||
ctx, _, _, conns := dialChatServer(t, Options{Chat: broker}, 2)
|
||||
phone, tablet := conns[0], conns[1]
|
||||
|
||||
// The phone's prompt starts a turn held in flight.
|
||||
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ChatPrompt, ID: "p1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "one"}})
|
||||
if ack := readUntil(t, ctx, phone, protocol.ChatPrompt); ack.ChatQueued {
|
||||
t.Fatalf("first prompt should start immediately: %+v", ack)
|
||||
}
|
||||
|
||||
// The tablet's prompt is accepted as queued and acknowledged as such.
|
||||
writeChat(t, ctx, tablet, protocol.Message{Type: protocol.ChatPrompt, ID: "p2", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "two"}})
|
||||
if ack := readUntil(t, ctx, tablet, protocol.ChatPrompt); !ack.ChatQueued {
|
||||
t.Fatalf("second prompt should be acknowledged as queued: %+v", ack)
|
||||
}
|
||||
|
||||
// End the first turn; the queued prompt is posted and the broker rejects it.
|
||||
broker.push(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, Index: 1}})
|
||||
|
||||
for {
|
||||
var message protocol.Message
|
||||
if err := wsjson.Read(ctx, tablet, &message); err != nil {
|
||||
t.Fatalf("read (waiting for the queued prompt failure): %v", err)
|
||||
}
|
||||
if message.Type != protocol.Error {
|
||||
continue
|
||||
}
|
||||
if message.ID != "p2" || !strings.Contains(message.Error, "broker rejected the prompt") {
|
||||
t.Fatalf("queued prompt failure = %+v, want an error for p2 naming the broker failure", message)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPendingApprovalsAllReplayed pins that every unresolved approval request
|
||||
// a room holds is replayed to a client that attaches afterwards, not only the
|
||||
// most recent one, so both cards are answerable on the late client.
|
||||
func TestChatPendingApprovalsAllReplayed(t *testing.T) {
|
||||
broker := newChannelChat()
|
||||
broker.perm = []protocol.ChatPermissionFrame{
|
||||
{SessionID: "ses_1", RequestID: "req_1", Action: "bash", Resources: []string{"rm -rf /tmp"}},
|
||||
{SessionID: "ses_1", RequestID: "req_2", Action: "write", Resources: []string{"/etc/hosts"}},
|
||||
}
|
||||
ctx, _, _, conns := dialChatServer(t, Options{Chat: broker}, 2)
|
||||
phone, tablet := conns[0], conns[1]
|
||||
|
||||
// A turn starts so the poller pushes both pending requests to the phone.
|
||||
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ChatPrompt, ID: "p1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "run them"}})
|
||||
readUntil(t, ctx, phone, protocol.ChatPrompt)
|
||||
nextPermission(t, ctx, phone, "req_1")
|
||||
nextPermission(t, ctx, phone, "req_2")
|
||||
|
||||
// A client that attaches afterwards is replayed both.
|
||||
writeChat(t, ctx, tablet, protocol.Message{Type: protocol.ChatSubscribe, ID: "s1", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}})
|
||||
readUntil(t, ctx, tablet, protocol.ChatSubscribe)
|
||||
first := nextPermission(t, ctx, tablet, "req_1")
|
||||
second := nextPermission(t, ctx, tablet, "req_2")
|
||||
if first.Resolved || second.Resolved || first.Action != "bash" || second.Action != "write" {
|
||||
t.Fatalf("replayed permissions = %+v / %+v, want both still-pending requests", first, second)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatResyncAfterReconnect is the resync acceptance test: a client that drops
|
||||
// and reconnects re-syncs the whole conversation from retained state, including
|
||||
// the user turn and who sent it.
|
||||
func TestChatResyncAfterReconnect(t *testing.T) {
|
||||
broker := scriptedChat()
|
||||
ctx, _, srv, conns := dialChatServer(t, Options{Chat: broker}, 1)
|
||||
phone := conns[0]
|
||||
|
||||
writeChat(t, ctx, phone, protocol.Message{Type: protocol.ChatPrompt, ID: "p1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi", Client: "Pixel 9"}})
|
||||
readUntil(t, ctx, phone, protocol.ChatPrompt)
|
||||
readChatTurn(t, ctx, phone)
|
||||
|
||||
// The phone's socket drops.
|
||||
phone.CloseNow()
|
||||
|
||||
// A fresh connection re-syncs from retained state.
|
||||
reconnected := dialChatConn(t, ctx, srv)
|
||||
writeChat(t, ctx, reconnected, protocol.Message{Type: protocol.ChatMessages, ID: "m1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}})
|
||||
response := readUntil(t, ctx, reconnected, protocol.ChatMessages)
|
||||
if len(response.ChatMessages) != 2 {
|
||||
t.Fatalf("resync returned %d messages, want user+assistant: %+v", len(response.ChatMessages), response.ChatMessages)
|
||||
}
|
||||
user := response.ChatMessages[0]
|
||||
if user.Role != protocol.ChatRoleUser || user.Client != "Pixel 9" || len(user.Parts) != 1 || user.Parts[0].Text != "hi" {
|
||||
t.Fatalf("resynced user turn = %+v", user)
|
||||
}
|
||||
assistant := response.ChatMessages[1]
|
||||
if assistant.Role != protocol.ChatRoleAssistant || assistant.ID != "msg_1" {
|
||||
t.Fatalf("resynced assistant turn = %+v", assistant)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package server
|
||||
|
||||
import "git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
|
||||
// chatPermissionRetainedLimit bounds the dedup set of already-pushed permission
|
||||
// request ids one session retains, so a long turn cannot grow it without limit.
|
||||
const chatPermissionRetainedLimit = 256
|
||||
@@ -31,24 +33,83 @@ func (h *chatHub) seenPermission(sessionID, requestID string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// forgetPermission releases a request id reserved by seenPermission when its
|
||||
// frame could not be written, so a later poll re-pushes it instead of the id
|
||||
// staying "seen" while the phone never received the request.
|
||||
func (h *chatHub) forgetPermission(sessionID, requestID string) {
|
||||
// reservePermission claims the shared right to answer requestID for client. It
|
||||
// returns true when this caller is the first to answer (the only caller allowed
|
||||
// to reach the agent), and false with the recorded resolution when the request is
|
||||
// already answered or is already being answered, so a later answer is refused
|
||||
// rather than delivered twice. The reservation is bounded like the dedup set.
|
||||
func (h *chatHub) reservePermission(sessionID, requestID, client string) (*chatResolution, bool) {
|
||||
if sessionID == "" || requestID == "" {
|
||||
return
|
||||
return nil, false
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turnLocked(sessionID)
|
||||
if turn.resolutions == nil {
|
||||
turn.resolutions = map[string]*chatResolution{}
|
||||
}
|
||||
if prior, ok := turn.resolutions[requestID]; ok {
|
||||
return prior, false
|
||||
}
|
||||
turn.resolutions[requestID] = &chatResolution{client: client}
|
||||
turn.resolutionOrder = append(turn.resolutionOrder, requestID)
|
||||
if len(turn.resolutionOrder) > chatPermissionRetainedLimit {
|
||||
oldest := turn.resolutionOrder[0]
|
||||
turn.resolutionOrder = turn.resolutionOrder[1:]
|
||||
delete(turn.resolutions, oldest)
|
||||
}
|
||||
return nil, true
|
||||
}
|
||||
|
||||
// releasePermission drops a reservation whose answer never reached the agent, so
|
||||
// a later attempt can win instead of the request staying permanently refused.
|
||||
func (h *chatHub) releasePermission(sessionID, requestID string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turns[sessionID]
|
||||
if turn == nil {
|
||||
return
|
||||
}
|
||||
delete(turn.permissions, requestID)
|
||||
for i, id := range turn.permissionOrder {
|
||||
delete(turn.resolutions, requestID)
|
||||
for i, id := range turn.resolutionOrder {
|
||||
if id == requestID {
|
||||
turn.permissionOrder = append(turn.permissionOrder[:i], turn.permissionOrder[i+1:]...)
|
||||
turn.resolutionOrder = append(turn.resolutionOrder[:i], turn.resolutionOrder[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// confirmPermission records the delivered answer and pushes the resolution to
|
||||
// every watching client, so each one's approval card clears and shows the
|
||||
// outcome and which client gave it.
|
||||
func (h *chatHub) confirmPermission(sessionID, requestID, client, decision string) {
|
||||
h.mu.Lock()
|
||||
if turn := h.turns[sessionID]; turn != nil {
|
||||
if resolution, ok := turn.resolutions[requestID]; ok {
|
||||
resolution.decision = decision
|
||||
resolution.answered = true
|
||||
}
|
||||
}
|
||||
frame := protocol.ChatPermissionFrame{SessionID: sessionID, RequestID: requestID}
|
||||
var targets []*chatSub
|
||||
if room := h.rooms[sessionID]; room != nil {
|
||||
for i := range room.pending {
|
||||
if room.pending[i].RequestID == requestID {
|
||||
frame = room.pending[i]
|
||||
room.pending = append(room.pending[:i], room.pending[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, sub := range room.subs {
|
||||
targets = append(targets, sub)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
frame.Resolved = true
|
||||
frame.Decision = decision
|
||||
frame.ResolvedBy = client
|
||||
msg := protocol.Message{Type: protocol.ChatPermission, ChatPermission: &frame}
|
||||
for _, sub := range targets {
|
||||
sub.send(msg)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,662 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// The chat room is one session's shared live channel. Many clients attach to it
|
||||
// (the operator's phone, tablet and terminal) and every frame any turn produces
|
||||
// is fanned out to all of them, so each device sees the same conversation
|
||||
// including the other devices' prompts and the turn's streaming output. The room
|
||||
// owns the session's one broker stream and its one prompt queue, so a session is
|
||||
// never read-only for a client and two turns never interleave: a prompt that
|
||||
// arrives while a turn is in flight is queued (bounded) and its client is told so
|
||||
// in the ack.
|
||||
const (
|
||||
// chatRoomSubscriberBuffer bounds one attached client's pending frames. A
|
||||
// client that falls this far behind is dropped rather than blocking the turn
|
||||
// or the other clients; it re-syncs from history when it reattaches.
|
||||
chatRoomSubscriberBuffer = 64
|
||||
// chatRoomQueueLimit bounds the prompts one session may hold while a turn is
|
||||
// in flight. A prompt that would exceed it is refused with a visible error
|
||||
// instead of being silently dropped.
|
||||
chatRoomQueueLimit = 8
|
||||
// chatClientLabelMax bounds the human-readable client label the server stores
|
||||
// and echoes, so a long device name cannot grow a frame without limit.
|
||||
chatClientLabelMax = 48
|
||||
// chatClientLabelFallback labels a prompt whose sender did not name itself, so
|
||||
// a transcript always has something to attribute the message to.
|
||||
chatClientLabelFallback = "Another device"
|
||||
// chatRoomPendingLimit bounds how many unresolved approval requests one room
|
||||
// retains for replay to a client that attaches after they were raised, so a
|
||||
// long turn cannot grow the replay state without limit.
|
||||
chatRoomPendingLimit = 16
|
||||
)
|
||||
|
||||
// chatSub is one client's attachment to a session's shared stream. Frames reach
|
||||
// it through a dedicated writer goroutine so a slow or broken client never stalls
|
||||
// the turn or the other subscribers; the buffered channel bounds how far behind
|
||||
// it may fall.
|
||||
type chatSub struct {
|
||||
hub *chatHub
|
||||
room *chatRoom
|
||||
clientID string
|
||||
label string
|
||||
ch chan protocol.Message
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
write func(protocol.Message) error
|
||||
}
|
||||
|
||||
func (s *chatSub) run() {
|
||||
for {
|
||||
select {
|
||||
case <-s.done:
|
||||
return
|
||||
case msg := <-s.ch:
|
||||
if err := s.write(msg); err != nil {
|
||||
s.close()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *chatSub) send(msg protocol.Message) {
|
||||
select {
|
||||
case <-s.done:
|
||||
return
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case s.ch <- msg:
|
||||
default:
|
||||
// The client is not draining: drop it rather than block the fan-out. Its
|
||||
// next attach re-syncs from history.
|
||||
s.close()
|
||||
}
|
||||
}
|
||||
|
||||
// close detaches the subscription and stops its writer goroutine exactly once.
|
||||
func (s *chatSub) close() {
|
||||
s.once.Do(func() {
|
||||
close(s.done)
|
||||
s.hub.detach(s.room.sessionID, s)
|
||||
})
|
||||
}
|
||||
|
||||
// chatQueuedPrompt is one prompt waiting for the session's in-flight turn to
|
||||
// finish. acked marks a prompt the handler already acknowledged as queued, so the
|
||||
// turn runner does not send a second (success) acknowledgement for the same
|
||||
// request id; write is kept either way so a later broker failure is still
|
||||
// reported to the client that sent it.
|
||||
type chatQueuedPrompt struct {
|
||||
text string
|
||||
requestID string
|
||||
write func(protocol.Message) error
|
||||
acked bool
|
||||
}
|
||||
|
||||
// chatRoom is one session's shared live channel. Every field is guarded by the
|
||||
// owning chatHub's mutex.
|
||||
type chatRoom struct {
|
||||
sessionID string
|
||||
broker chatBroker
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
subs map[string]*chatSub
|
||||
queue []*chatQueuedPrompt
|
||||
running bool
|
||||
streaming bool
|
||||
// buffering holds the turn's frames until the prompting client's ack has been
|
||||
// written, so the ack always precedes the frames it acknowledges. It is set
|
||||
// only while the very first turn subscribes to the firehose.
|
||||
buffering bool
|
||||
buffered []protocol.ChatEventFrame
|
||||
// pending holds the room's unresolved approval requests, in the order they
|
||||
// were raised, replayed to a client that attaches after they were raised. A
|
||||
// request is removed once it is resolved.
|
||||
pending []protocol.ChatPermissionFrame
|
||||
pollerStarted bool
|
||||
wake chan struct{}
|
||||
turnDone chan struct{}
|
||||
}
|
||||
|
||||
func newChatRoom(base context.Context, sessionID string) *chatRoom {
|
||||
if base == nil {
|
||||
base = context.Background()
|
||||
}
|
||||
roomCtx, cancel := context.WithCancel(base)
|
||||
return &chatRoom{
|
||||
sessionID: sessionID,
|
||||
ctx: roomCtx,
|
||||
cancel: cancel,
|
||||
subs: map[string]*chatSub{},
|
||||
wake: make(chan struct{}, 1),
|
||||
}
|
||||
}
|
||||
|
||||
// roomLocked returns the session's room, creating it (and its turn runner) when
|
||||
// it is the first client to watch the session. Callers must hold h.mu.
|
||||
func (h *chatHub) roomLocked(sessionID string) *chatRoom {
|
||||
if h.rooms == nil {
|
||||
h.rooms = map[string]*chatRoom{}
|
||||
}
|
||||
if room := h.rooms[sessionID]; room != nil {
|
||||
return room
|
||||
}
|
||||
room := newChatRoom(h.baseCtx, sessionID)
|
||||
h.rooms[sessionID] = room
|
||||
go h.runRoom(room)
|
||||
return room
|
||||
}
|
||||
|
||||
// attach registers write as one client's subscription to sessionID's stream and
|
||||
// returns it, or the existing subscription when the same connection has already
|
||||
// attached. It is idempotent so a client may prompt and subscribe without
|
||||
// registering twice.
|
||||
func (h *chatHub) attach(sessionID, clientID, label string, broker chatBroker, write func(protocol.Message) error) *chatSub {
|
||||
if sessionID == "" || clientID == "" || write == nil {
|
||||
return nil
|
||||
}
|
||||
h.mu.Lock()
|
||||
room := h.roomLocked(sessionID)
|
||||
if room.broker == nil {
|
||||
room.broker = broker
|
||||
}
|
||||
if sub, ok := room.subs[clientID]; ok {
|
||||
if label != "" {
|
||||
sub.label = label
|
||||
}
|
||||
h.mu.Unlock()
|
||||
return sub
|
||||
}
|
||||
sub := &chatSub{
|
||||
hub: h,
|
||||
room: room,
|
||||
clientID: clientID,
|
||||
label: label,
|
||||
ch: make(chan protocol.Message, chatRoomSubscriberBuffer),
|
||||
done: make(chan struct{}),
|
||||
write: write,
|
||||
}
|
||||
room.subs[clientID] = sub
|
||||
h.mu.Unlock()
|
||||
go sub.run()
|
||||
return sub
|
||||
}
|
||||
|
||||
// detach drops one subscription. The room (and its broker stream and queue) is
|
||||
// released once its last client leaves, so a session with no watchers holds no
|
||||
// goroutine.
|
||||
func (h *chatHub) detach(sessionID string, sub *chatSub) {
|
||||
h.mu.Lock()
|
||||
room := h.rooms[sessionID]
|
||||
if room == nil || room.subs[sub.clientID] != sub {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
delete(room.subs, sub.clientID)
|
||||
if len(room.subs) == 0 {
|
||||
delete(h.rooms, sessionID)
|
||||
room.cancel()
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// detachClient drops every chat subscription one connection holds; the read loop
|
||||
// calls it when the connection ends so no subscriber goroutine outlives it.
|
||||
func (h *chatHub) detachClient(clientID string) {
|
||||
if clientID == "" {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
var subs []*chatSub
|
||||
for _, room := range h.rooms {
|
||||
if sub, ok := room.subs[clientID]; ok {
|
||||
subs = append(subs, sub)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
for _, sub := range subs {
|
||||
sub.close()
|
||||
}
|
||||
}
|
||||
|
||||
// fanout delivers one frame to every client watching sessionID except the one
|
||||
// named by except (the sender, who already has it locally).
|
||||
func (h *chatHub) fanout(sessionID string, msg protocol.Message, except string) {
|
||||
h.mu.Lock()
|
||||
var targets []*chatSub
|
||||
if room := h.rooms[sessionID]; room != nil {
|
||||
for id, sub := range room.subs {
|
||||
if id == except {
|
||||
continue
|
||||
}
|
||||
targets = append(targets, sub)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
for _, sub := range targets {
|
||||
sub.send(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// broadcastUser retains a prompt as a user turn and pushes it live to every other
|
||||
// client watching the session, attributed to the sending client's label. The
|
||||
// sender already has the message locally, so it is excluded to keep its own
|
||||
// transcript from duplicating it.
|
||||
func (h *chatHub) broadcastUser(frame protocol.ChatEventFrame, exceptClientID string) {
|
||||
h.apply(frame)
|
||||
h.fanout(frame.SessionID, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}, exceptClientID)
|
||||
}
|
||||
|
||||
// emit folds one broker frame into the retained state and fans it out. While the
|
||||
// first turn's ack is still pending the frames are buffered and flushed in order
|
||||
// once it is written. A step-ended frame finishes the turn, letting the queue
|
||||
// advance.
|
||||
func (h *chatHub) emit(frame protocol.ChatEventFrame) {
|
||||
h.apply(frame)
|
||||
h.mu.Lock()
|
||||
room := h.rooms[frame.SessionID]
|
||||
buffered := false
|
||||
var targets []*chatSub
|
||||
if room != nil {
|
||||
if room.buffering {
|
||||
room.buffered = append(room.buffered, frame)
|
||||
buffered = true
|
||||
} else {
|
||||
for _, sub := range room.subs {
|
||||
targets = append(targets, sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
if room != nil && frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded {
|
||||
h.finishTurnLocked(room)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
if buffered {
|
||||
return
|
||||
}
|
||||
msg := protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}
|
||||
for _, sub := range targets {
|
||||
sub.send(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// finishTurnLocked marks the room's turn finished and releases the turn runner's
|
||||
// wait. Callers must hold h.mu.
|
||||
func (h *chatHub) finishTurnLocked(room *chatRoom) {
|
||||
room.running = false
|
||||
if room.turnDone != nil {
|
||||
close(room.turnDone)
|
||||
room.turnDone = nil
|
||||
}
|
||||
}
|
||||
|
||||
// flushBuffered releases the frames held while the ack was pending and delivers
|
||||
// them in order. It is a no-op once the room is no longer buffering.
|
||||
func (h *chatHub) flushBuffered(sessionID string) {
|
||||
h.mu.Lock()
|
||||
room := h.rooms[sessionID]
|
||||
var pending []protocol.ChatEventFrame
|
||||
var targets []*chatSub
|
||||
if room != nil && room.buffering {
|
||||
room.buffering = false
|
||||
pending = room.buffered
|
||||
room.buffered = nil
|
||||
for _, sub := range room.subs {
|
||||
targets = append(targets, sub)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
for i := range pending {
|
||||
frame := pending[i]
|
||||
msg := protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}
|
||||
for _, sub := range targets {
|
||||
sub.send(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// submitPrompt accepts one prompt: it starts the turn runner immediately when no
|
||||
// turn is in flight, or queues it (bounded) when one is. It returns whether the
|
||||
// prompt was queued or refused.
|
||||
func (h *chatHub) submitPrompt(sessionID string, p *chatQueuedPrompt) (queued bool, refused bool) {
|
||||
h.mu.Lock()
|
||||
room := h.roomLocked(sessionID)
|
||||
if room.running || len(room.queue) > 0 {
|
||||
if len(room.queue) >= chatRoomQueueLimit {
|
||||
h.mu.Unlock()
|
||||
return false, true
|
||||
}
|
||||
// The client is acknowledged as queued by the handler, so the turn runner
|
||||
// must not acknowledge the same request again once it runs. The write is
|
||||
// still kept so a later broker failure reaches the client that sent it.
|
||||
p.acked = true
|
||||
room.queue = append(room.queue, p)
|
||||
signalWake(room.wake)
|
||||
h.mu.Unlock()
|
||||
return true, false
|
||||
}
|
||||
room.queue = append(room.queue, p)
|
||||
signalWake(room.wake)
|
||||
h.mu.Unlock()
|
||||
return false, false
|
||||
}
|
||||
|
||||
// pendingFrames returns a copy of the room's unresolved approval requests so a
|
||||
// client that attaches after they were raised can be shown every one of them. It
|
||||
// returns nil when the room holds none.
|
||||
func (h *chatHub) pendingFrames(sessionID string) []protocol.ChatPermissionFrame {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
room := h.rooms[sessionID]
|
||||
if room == nil || len(room.pending) == 0 {
|
||||
return nil
|
||||
}
|
||||
frames := make([]protocol.ChatPermissionFrame, len(room.pending))
|
||||
copy(frames, room.pending)
|
||||
return frames
|
||||
}
|
||||
|
||||
// pushPermission publishes one newly seen pending approval request to every
|
||||
// client watching the session and remembers it (bounded) for a client that
|
||||
// attaches later. A request already seen (or already resolved) is not pushed
|
||||
// again.
|
||||
func (h *chatHub) pushPermission(sessionID string, frame protocol.ChatPermissionFrame) {
|
||||
if frame.RequestID == "" || frame.Resolved {
|
||||
return
|
||||
}
|
||||
if !h.seenPermission(sessionID, frame.RequestID) {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
var targets []*chatSub
|
||||
if room := h.rooms[sessionID]; room != nil {
|
||||
known := false
|
||||
for i := range room.pending {
|
||||
if room.pending[i].RequestID == frame.RequestID {
|
||||
room.pending[i] = frame
|
||||
known = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
room.pending = append(room.pending, frame)
|
||||
if len(room.pending) > chatRoomPendingLimit {
|
||||
room.pending = room.pending[len(room.pending)-chatRoomPendingLimit:]
|
||||
}
|
||||
}
|
||||
for _, sub := range room.subs {
|
||||
targets = append(targets, sub)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
msg := protocol.Message{Type: protocol.ChatPermission, ChatPermission: &frame}
|
||||
for _, sub := range targets {
|
||||
sub.send(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// runRoom is the session's turn runner: it takes queued prompts one at a time,
|
||||
// posts each to the broker and waits for the turn to end, so two prompts of one
|
||||
// session can never interleave.
|
||||
func (h *chatHub) runRoom(room *chatRoom) {
|
||||
for {
|
||||
p, done, ok := h.nextPrompt(room)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.runTurn(room, p, done)
|
||||
}
|
||||
}
|
||||
|
||||
// nextPrompt pops the next queued prompt, blocking until one arrives or the room
|
||||
// is released. It marks the room running and creates the turn's completion
|
||||
// channel so a stale signal from a previous turn can never end the next one.
|
||||
func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{}, bool) {
|
||||
for {
|
||||
h.mu.Lock()
|
||||
if len(room.queue) > 0 {
|
||||
p := room.queue[0]
|
||||
room.queue = room.queue[1:]
|
||||
room.running = true
|
||||
room.turnDone = make(chan struct{})
|
||||
done := room.turnDone
|
||||
h.mu.Unlock()
|
||||
return p, done, true
|
||||
}
|
||||
h.mu.Unlock()
|
||||
select {
|
||||
case <-room.ctx.Done():
|
||||
return nil, nil, false
|
||||
case <-room.wake:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runTurn subscribes to the broker stream when needed, posts one prompt, writes
|
||||
// its ack and waits for the turn to end.
|
||||
func (h *chatHub) runTurn(room *chatRoom, p *chatQueuedPrompt, done chan struct{}) {
|
||||
broker := h.roomBroker(room)
|
||||
first := false
|
||||
h.mu.Lock()
|
||||
if !room.streaming {
|
||||
first = true
|
||||
room.buffering = true
|
||||
}
|
||||
h.mu.Unlock()
|
||||
defer h.flushBuffered(room.sessionID)
|
||||
|
||||
if broker == nil {
|
||||
h.failPrompt(room, p, errors.New("chat is not configured on this server"))
|
||||
return
|
||||
}
|
||||
if first {
|
||||
if err := h.startStream(room, broker); err != nil {
|
||||
h.failPrompt(room, p, err)
|
||||
h.endRoomTurn(room)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := broker.Prompt(room.ctx, room.sessionID, p.text); err != nil {
|
||||
h.failPrompt(room, p, err)
|
||||
h.endRoomTurn(room)
|
||||
return
|
||||
}
|
||||
if h.registry != nil {
|
||||
if err := h.registry.TouchOperatorSession(room.ctx, room.sessionID); err != nil {
|
||||
log.Printf("touch operator session %s: %v", room.sessionID, err)
|
||||
}
|
||||
}
|
||||
if p.write != nil && !p.acked {
|
||||
_ = p.write(protocol.Message{Type: protocol.ChatPrompt, ID: p.requestID})
|
||||
}
|
||||
h.flushBuffered(room.sessionID)
|
||||
// Start the approval poller once, after the first ack, so a pending request
|
||||
// is surfaced after the prompt is acknowledged and shared with every client.
|
||||
h.mu.Lock()
|
||||
startPoller := !room.pollerStarted
|
||||
room.pollerStarted = true
|
||||
h.mu.Unlock()
|
||||
if startPoller {
|
||||
go h.pollRoom(room, broker)
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-room.ctx.Done():
|
||||
}
|
||||
}
|
||||
|
||||
// endRoomTurn releases the turn slot after a prompt that never entered flight,
|
||||
// so the queue advances immediately instead of waiting for a step that never
|
||||
// comes.
|
||||
func (h *chatHub) endRoomTurn(room *chatRoom) {
|
||||
h.mu.Lock()
|
||||
h.finishTurnLocked(room)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// failPrompt reports a refused prompt to the client that sent it, so a prompt
|
||||
// that never reached the agent is visible on the device that sent it rather than
|
||||
// leaving its composer waiting. It is reported for a queued prompt too, whose
|
||||
// success ack was already sent but whose delivery may still fail.
|
||||
func (h *chatHub) failPrompt(room *chatRoom, p *chatQueuedPrompt, err error) {
|
||||
if p.write == nil || err == nil {
|
||||
return
|
||||
}
|
||||
_ = p.write(protocol.Message{Type: protocol.Error, ID: p.requestID, Error: err.Error()})
|
||||
}
|
||||
|
||||
// roomBroker returns the broker bound to the room.
|
||||
func (h *chatHub) roomBroker(room *chatRoom) chatBroker {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return room.broker
|
||||
}
|
||||
|
||||
// startStream attaches the room to the broker firehose, waiting until the
|
||||
// subscription is ready so no delta emitted between subscribing and posting a
|
||||
// prompt is lost. The permission poller starts alongside it.
|
||||
func (h *chatHub) startStream(room *chatRoom, broker chatBroker) error {
|
||||
attached := make(chan struct{})
|
||||
var once sync.Once
|
||||
result := make(chan error, 1)
|
||||
ctx := room.ctx
|
||||
go func() {
|
||||
result <- broker.Stream(ctx, room.sessionID, func() {
|
||||
once.Do(func() { close(attached) })
|
||||
}, func(frame protocol.ChatEventFrame) error {
|
||||
h.emit(frame)
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
select {
|
||||
case <-attached:
|
||||
case err := <-result:
|
||||
if err == nil {
|
||||
err = errors.New("chat stream ended before it was subscribed")
|
||||
}
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
h.mu.Lock()
|
||||
room.streaming = true
|
||||
h.mu.Unlock()
|
||||
go h.drainStream(room, result)
|
||||
return nil
|
||||
}
|
||||
|
||||
// drainStream reports the terminal error of a room's subscription and clears the
|
||||
// streaming flag so a later turn re-subscribes; it also releases a turn still
|
||||
// waiting on a stream that ended.
|
||||
func (h *chatHub) drainStream(room *chatRoom, result <-chan error) {
|
||||
err := <-result
|
||||
h.mu.Lock()
|
||||
room.streaming = false
|
||||
h.finishTurnLocked(room)
|
||||
h.mu.Unlock()
|
||||
if err != nil && room.ctx.Err() == nil {
|
||||
log.Printf("chat stream session=%s: %v", room.sessionID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// pollRoom polls the broker's pending-approval list for the room on a fixed
|
||||
// interval and pushes each newly seen request to every attached client. The
|
||||
// first poll runs immediately; the loop stops with the room's context.
|
||||
func (h *chatHub) pollRoom(room *chatRoom, broker chatBroker) {
|
||||
ticker := time.NewTicker(chatPermissionPollInterval)
|
||||
defer ticker.Stop()
|
||||
reported := false
|
||||
for {
|
||||
if err := h.pollPermissionsOnce(room.ctx, broker, room.sessionID); err != nil {
|
||||
if room.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, opencode.ErrPermissionUnsupported) {
|
||||
log.Printf("chat permission poll session=%s: %v", room.sessionID, err)
|
||||
return
|
||||
}
|
||||
if reported {
|
||||
log.Printf("chat permission poll session=%s: %v", room.sessionID, err)
|
||||
} else {
|
||||
reported = true
|
||||
h.fanout(room.sessionID, protocol.Message{Type: protocol.Error, Error: "chat permission poll: " + err.Error()}, "")
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-room.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pollPermissionsOnce performs one poll and pushes each newly seen request of the
|
||||
// session to every client watching it.
|
||||
func (h *chatHub) pollPermissionsOnce(ctx context.Context, broker chatBroker, sessionID string) error {
|
||||
pending, err := broker.Permissions(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, request := range pending {
|
||||
if request.SessionID != sessionID || request.RequestID == "" {
|
||||
continue
|
||||
}
|
||||
h.pushPermission(sessionID, request)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// signalWake nudges a room's turn runner without blocking. The channel is
|
||||
// buffered, so a signal already pending is enough.
|
||||
func signalWake(ch chan struct{}) {
|
||||
select {
|
||||
case ch <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// sanitizeChatClientLabel cleans a client-supplied device label for storage and
|
||||
// echo: control characters are dropped, the length is bounded and a blank label
|
||||
// becomes the generic fallback, so a transcript can always attribute a message.
|
||||
func sanitizeChatClientLabel(label string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range label {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
continue
|
||||
}
|
||||
b.WriteRune(r)
|
||||
}
|
||||
out := strings.TrimSpace(b.String())
|
||||
if len(out) > chatClientLabelMax {
|
||||
out = strings.TrimSpace(out[:chatClientLabelMax])
|
||||
}
|
||||
if out == "" {
|
||||
return chatClientLabelFallback
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// permissionRefusal explains why a second answer to an already-answered request
|
||||
// is refused, naming the client that won so the operator sees what happened.
|
||||
func permissionRefusal(prior *chatResolution, requestID string) string {
|
||||
if prior == nil {
|
||||
return "permission request " + requestID + " is already resolved"
|
||||
}
|
||||
if prior.answered {
|
||||
return fmt.Sprintf("permission request %s was already answered by %s", requestID, prior.client)
|
||||
}
|
||||
return fmt.Sprintf("permission request %s is already being answered by %s", requestID, prior.client)
|
||||
}
|
||||
@@ -17,15 +17,15 @@ import (
|
||||
// fixed list bounds.
|
||||
const operatorDirectoryLimit = 8
|
||||
|
||||
// handleChatSessions answers chat_sessions with the operator's own sessions,
|
||||
// marking any another client currently holds as Busy. The registry is the single
|
||||
// source of truth for which sessions are listed and for their directory, tag,
|
||||
// created/recency, so a pipeline stage session (recorded in run_steps, never in
|
||||
// the operator registry) is always excluded and a session with no recorded tag
|
||||
// is never listed. FAIL-CLOSED: when no registry is configured the result is
|
||||
// empty, never the whole endpoint list. broker.Sessions is called at most once
|
||||
// per request, and the registry once.
|
||||
func handleChatSessions(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) {
|
||||
// handleChatSessions answers chat_sessions with the operator's own sessions. The
|
||||
// registry is the single source of truth for which sessions are listed and for
|
||||
// their directory, tag, created/recency, so a pipeline stage session (recorded
|
||||
// in run_steps, never in the operator registry) is always excluded and a session
|
||||
// with no recorded tag is never listed. FAIL-CLOSED: when no registry is
|
||||
// configured the result is empty, never the whole endpoint list. broker.Sessions
|
||||
// is called at most once per request, and the registry once. A session is never
|
||||
// marked Busy: any number of clients may watch and write one session.
|
||||
func handleChatSessions(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, 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
|
||||
@@ -74,7 +74,6 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
|
||||
session.Tag = operator.Tag
|
||||
session.CreatedAt = operator.CreatedAt
|
||||
session.UpdatedAt = operator.UpdatedAt
|
||||
session.Busy = hub.busyForOther(operator.ID, clientID)
|
||||
response.ChatSessions = append(response.ChatSessions, session)
|
||||
}
|
||||
_ = write(response)
|
||||
|
||||
+67
-156
@@ -2,10 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
@@ -14,10 +11,16 @@ import (
|
||||
|
||||
// chatPermissionPollInterval is the fixed interval between permission polls: one
|
||||
// GET per poll through the shared Connection bounds, never a busy loop. The first
|
||||
// poll runs immediately so a request pending when the prompt is sent is surfaced
|
||||
// poll runs immediately so a request pending when a turn starts is surfaced
|
||||
// without waiting a full interval.
|
||||
const chatPermissionPollInterval = 2 * time.Second
|
||||
|
||||
// handleChatPrompt accepts a prompt from any client. It never rejects a prompt
|
||||
// because another client is watching the session: the client attaches to the
|
||||
// session's shared room and the prompt either starts a turn or is queued behind
|
||||
// the one in flight, with the ack saying which. The prompt is echoed live to
|
||||
// every other client, attributed to the sending device's label, and the turn's
|
||||
// output is fanned out to all of them.
|
||||
func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, 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"})
|
||||
@@ -42,170 +45,78 @@ 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"})
|
||||
sub := hub.attach(sessionID, clientID, sanitizeChatClientLabel(prompt.Client), broker, write)
|
||||
if sub == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "could not attach to session " + sessionID})
|
||||
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.
|
||||
streamCtx, streamCancel := context.WithCancel(ctx)
|
||||
attached := make(chan struct{})
|
||||
var attachOnce sync.Once
|
||||
streamResult := make(chan error, 1)
|
||||
var bufferMu sync.Mutex
|
||||
buffering := true
|
||||
var buffered []protocol.ChatEventFrame
|
||||
go func() {
|
||||
streamResult <- broker.Stream(streamCtx, sessionID, func() {
|
||||
attachOnce.Do(func() { close(attached) })
|
||||
}, func(frame protocol.ChatEventFrame) error {
|
||||
bufferMu.Lock()
|
||||
if buffering {
|
||||
buffered = append(buffered, frame)
|
||||
bufferMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
bufferMu.Unlock()
|
||||
hub.apply(frame)
|
||||
return write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame})
|
||||
})
|
||||
}()
|
||||
|
||||
select {
|
||||
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)
|
||||
// The user turn every *other* client sees, carrying the sender's label. The
|
||||
// sender's own client appended it locally, so it is excluded below.
|
||||
userFrame := protocol.ChatEventFrame{
|
||||
SessionID: sessionID,
|
||||
MessageID: hub.nextUserMessageID(),
|
||||
Kind: protocol.ChatEventUser,
|
||||
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: prompt.Text},
|
||||
Client: sub.label,
|
||||
}
|
||||
queued, refused := hub.submitPrompt(sessionID, &chatQueuedPrompt{
|
||||
text: prompt.Text,
|
||||
requestID: request.ID,
|
||||
write: write,
|
||||
})
|
||||
if refused {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " already has the maximum number of prompts queued"})
|
||||
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
|
||||
// Publish the user turn to every other client; the sender already has it.
|
||||
hub.broadcastUser(userFrame, clientID)
|
||||
if queued {
|
||||
// The client that sent it is told the prompt is waiting for the in-flight
|
||||
// turn, so it shows queued/steering instead of blocking or silently
|
||||
// dropping the message. The turn runner acknowledges it once it runs, so
|
||||
// clear the ack on the queued entry to avoid a second ack for the same id.
|
||||
_ = write(protocol.Message{Type: protocol.ChatPrompt, ID: request.ID, ChatQueued: true})
|
||||
}
|
||||
// Recency is one UPDATE: it moves the operator session to the front of
|
||||
// chat_sessions. A session id that is not an operator session updates no row
|
||||
// and is not an error, so pipeline stage prompts are unaffected.
|
||||
if registry != nil {
|
||||
// Recency is one UPDATE: it moves the operator session to the front of
|
||||
// chat_sessions. A session id that is not an operator session updates no
|
||||
// row and is not an error, so pipeline stage prompts are unaffected.
|
||||
if err := registry.TouchOperatorSession(ctx, sessionID); err != nil {
|
||||
log.Printf("touch operator session %s: %v", sessionID, err)
|
||||
// Best-effort; the turn runner also touches on delivery.
|
||||
_ = err
|
||||
}
|
||||
}
|
||||
// Acknowledge the accepted prompt with the echoed request id, then stream the
|
||||
// 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)
|
||||
}
|
||||
|
||||
// handleChatSubscribe attaches one connection to a session's shared stream so it
|
||||
// receives every frame any client's turn produces, its own or another device's.
|
||||
// It replays the session's still-pending approval requests, if the room holds
|
||||
// any, so a device that joins late still shows the cards.
|
||||
func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatHub, clientID string, write func(protocol.Message) error) {
|
||||
// The wire body of chat_subscribe is the chat_subscribe field (the app's
|
||||
// subscribeRequest and docs/cli.md both use it), not the chat_query body the
|
||||
// other session-scoped commands carry.
|
||||
query := request.ChatSubscribe
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
// Flush frames buffered while the prompt was accepted, then resume live
|
||||
// delivery. Holding bufferMu preserves order: the stream goroutine either
|
||||
// buffered before this flush or waits and writes after it.
|
||||
bufferMu.Lock()
|
||||
buffering = false
|
||||
pending := buffered
|
||||
buffered = nil
|
||||
for _, frame := range pending {
|
||||
hub.apply(frame)
|
||||
if err := write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}); err != nil {
|
||||
bufferMu.Unlock()
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
return
|
||||
}
|
||||
if broker == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
||||
return
|
||||
}
|
||||
bufferMu.Unlock()
|
||||
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.
|
||||
go pollChatPermissions(streamCtx, broker, hub, sessionID, write)
|
||||
}
|
||||
|
||||
// pollChatPermissions polls the broker's pending-approval list on a fixed
|
||||
// interval, sharing the chat subscription's context so it stops on disconnect or
|
||||
// when the turn's stream ends. The hub dedups the request ids, so each pending
|
||||
// request is pushed at most once; a poll failure is surfaced once through the
|
||||
// same write closure instead of staying silent. A backend that does not expose
|
||||
// the approval surface (opencode.ErrPermissionUnsupported) stops the poller
|
||||
// quietly, so the documented limitation is not reported as a per-prompt error.
|
||||
func pollChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) {
|
||||
ticker := time.NewTicker(chatPermissionPollInterval)
|
||||
defer ticker.Stop()
|
||||
reported := false
|
||||
for {
|
||||
if err := pushChatPermissions(ctx, broker, hub, sessionID, write); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, opencode.ErrPermissionUnsupported) {
|
||||
log.Printf("chat permission poll session=%s: %v", sessionID, err)
|
||||
return
|
||||
}
|
||||
if reported {
|
||||
log.Printf("chat permission poll session=%s: %v", sessionID, err)
|
||||
} else {
|
||||
reported = true
|
||||
_ = write(protocol.Message{Type: protocol.Error, Error: "chat permission poll: " + err.Error()})
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pushChatPermissions performs one poll and writes a chat_permission frame for
|
||||
// every newly seen request of the session, through the same connection-scoped
|
||||
// write closure as the chat stream. It never re-pushes a request id, and releases
|
||||
// the reservation on a write failure so the frame is not silently dropped.
|
||||
func pushChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) error {
|
||||
pending, err := broker.Permissions(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, request := range pending {
|
||||
if request.SessionID != sessionID || request.RequestID == "" {
|
||||
continue
|
||||
}
|
||||
if !hub.seenPermission(sessionID, request.RequestID) {
|
||||
continue
|
||||
}
|
||||
frame := request
|
||||
if err := write(protocol.Message{Type: protocol.ChatPermission, ChatPermission: &frame}); err != nil {
|
||||
hub.forgetPermission(sessionID, request.RequestID)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// drainChatStream reports the terminal error of a chat subscription and releases
|
||||
// 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()})
|
||||
sub := hub.attach(query.SessionID, clientID, "", broker, write)
|
||||
if sub == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "could not attach to session " + query.SessionID})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatSubscribe, ID: request.ID})
|
||||
// Replay every still-unresolved approval request the room holds, not only the
|
||||
// most recent one, so a client that attaches after two requests were raised
|
||||
// still sees both cards.
|
||||
for _, pending := range hub.pendingFrames(query.SessionID) {
|
||||
frame := pending
|
||||
sub.send(protocol.Message{Type: protocol.ChatPermission, ChatPermission: &frame})
|
||||
}
|
||||
}
|
||||
|
||||
+29
-111
@@ -436,10 +436,18 @@ func TestChatMessagesResumesRetainedState(t *testing.T) {
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != protocol.ChatMessages || response.ID != "r2" || len(response.ChatMessages) != 1 {
|
||||
if response.Type != protocol.ChatMessages || response.ID != "r2" || len(response.ChatMessages) != 2 {
|
||||
t.Fatalf("resume response = %+v", response)
|
||||
}
|
||||
message := response.ChatMessages[0]
|
||||
// The prompt is retained as a user turn and the assistant reply beside it, so
|
||||
// a reconnecting client re-syncs a conversation that still says who sent
|
||||
// what. The user turn carries the sending client's label (the generic
|
||||
// fallback when the prompt did not name one).
|
||||
user := response.ChatMessages[0]
|
||||
if user.Role != protocol.ChatRoleUser || len(user.Parts) != 1 || user.Parts[0].Type != protocol.ChatPartText || user.Parts[0].Text != "hi" || user.Client != chatClientLabelFallback {
|
||||
t.Fatalf("resumed user turn = %+v", user)
|
||||
}
|
||||
message := response.ChatMessages[1]
|
||||
if message.ID != "msg_1" || message.Role != protocol.ChatRoleAssistant || len(message.Parts) != 2 {
|
||||
t.Fatalf("resumed message = %+v", message)
|
||||
}
|
||||
@@ -1361,88 +1369,6 @@ func TestChatSessionsFailsClosedWithoutOwnership(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
ctx := context.Background()
|
||||
store := newOperatorStore(t)
|
||||
if err := store.RecordOperatorSession(ctx, "ses_1", "/work", "operator chat", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broker := scriptedChat()
|
||||
broker.block = true
|
||||
broker.done = make(chan struct{})
|
||||
broker.sessions = []protocol.ChatSession{{ID: "ses_1"}}
|
||||
ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 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 after protocol.Message
|
||||
if err := wsjson.Read(ctx, connB, &after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPromptPushesPermissionAndForwardsReply is the task evidence: with a
|
||||
// blocking scripted stream keeping the subscription open, a seeded pending
|
||||
// approval request is pushed as a chat_permission frame carrying the seeded
|
||||
@@ -1522,11 +1448,29 @@ func TestChatPermissionDedupesRepeatedPolls(t *testing.T) {
|
||||
mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
if sub := hub.attach("ses_1", "c1", "phone", broker, write); sub == nil {
|
||||
t.Fatal("attach returned nil")
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := pushChatPermissions(context.Background(), broker, hub, "ses_1", write); err != nil {
|
||||
if err := hub.pollPermissionsOnce(context.Background(), broker, "ses_1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
mu.Lock()
|
||||
count := len(pushed)
|
||||
mu.Unlock()
|
||||
if count > 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("no permission frame was pushed")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
// Give a duplicate a chance to arrive before asserting there is none.
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(pushed) != 1 {
|
||||
@@ -1684,32 +1628,6 @@ func TestChatPermissionUnsupportedBackendIsQuiet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPermissionWriteFailureDoesNotDropRequest pins that a request id is not
|
||||
// retained as "seen" when its frame could not be written, so the next poll
|
||||
// re-pushes it instead of silently dropping the approval request.
|
||||
func TestChatPermissionWriteFailureDoesNotDropRequest(t *testing.T) {
|
||||
broker := scriptedChat()
|
||||
broker.permissions = []protocol.ChatPermissionFrame{{SessionID: "ses_1", RequestID: "req_1", Action: "bash"}}
|
||||
hub := newChatHub()
|
||||
attempts := 0
|
||||
write := func(protocol.Message) error {
|
||||
attempts++
|
||||
if attempts == 1 {
|
||||
return fmt.Errorf("connection closed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := pushChatPermissions(context.Background(), broker, hub, "ses_1", write); err == nil {
|
||||
t.Fatal("a failed write must surface an error")
|
||||
}
|
||||
if err := pushChatPermissions(context.Background(), broker, hub, "ses_1", write); err != nil {
|
||||
t.Fatalf("retry after a failed write: %v", err)
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Fatalf("push attempts = %d, want the request re-pushed after the failure", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatAdoptRecordsEndpointSession is the chat_adopt acceptance test: the
|
||||
// endpoint's own record supplies the directory and title, the handler records
|
||||
// the row with the operator tag, and the response echoes the session and its
|
||||
|
||||
@@ -86,6 +86,8 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
if registry == nil && len(stores) > 0 {
|
||||
registry = stores[0]
|
||||
}
|
||||
hub.baseCtx = ctx
|
||||
hub.registry = registry
|
||||
mux.HandleFunc("GET /artifacts/{run}/{step}/{name...}", func(w http.ResponseWriter, r *http.Request) {
|
||||
if runs == nil {
|
||||
http.NotFound(w, r)
|
||||
@@ -139,6 +141,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
// Drop every run subscription this connection holds when the read loop
|
||||
// returns, so no subscriber, goroutine or timer outlives the connection.
|
||||
defer events.unsubscribeClient(clientID)
|
||||
// Drop every chat subscription too, so a chat room held only by this
|
||||
// connection releases its broker stream and turn runner.
|
||||
defer hub.detachClient(clientID)
|
||||
if len(stores) > 0 {
|
||||
items, err := stores[0].List(ctx)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user