6cb61578de
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.
663 lines
20 KiB
Go
663 lines
20 KiB
Go
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)
|
|
}
|