diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 85a69615..57e1aa77 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -296,34 +296,62 @@ func (h *chatHub) ensureObserving(room *chatRoom, broker chatBroker) error { // 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 { + sub, fresh := h.attachSub(sessionID, clientID, label, broker, write, false, false) + if fresh { + go sub.run() + } + return sub +} + +// attachSub is attach without starting a new subscription's writer: fresh +// reports that the caller must start it (go sub.run()), so a subscribe reply +// written meanwhile reaches the connection before any frame queued for it. +// +// With replayTurn, a client attaching while a turn is in flight (the room's, +// one its stream announced, or one the harness reports, busy: a room rebuilt +// after its last client reloaded has no record of an earlier prompt, and a +// browser may attach while the CLI harness works) gets a live +// `step started` marker queued in the same critical section that makes it a +// fan-out target. The marker therefore precedes every live frame of that +// turn the client receives, and is never sent for a turn that started after +// the client attached (whose own frames it sees) or that ended meanwhile. +func (h *chatHub) attachSub(sessionID, clientID, label string, broker chatBroker, write func(protocol.Message) error, replayTurn, busy bool) (*chatSub, bool) { if sessionID == "" || clientID == "" || write == nil { - return nil + return nil, false } h.mu.Lock() + defer h.mu.Unlock() room := h.roomLocked(sessionID) if room.broker == nil { room.broker = broker } - if sub, ok := room.subs[clientID]; ok { + sub, ok := room.subs[clientID] + if ok { if label != "" { sub.label = label } - h.mu.Unlock() - return sub + } else { + 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 } - sub := &chatSub{ - hub: h, - room: room, - clientID: clientID, - label: label, - ch: make(chan protocol.Message, chatRoomSubscriberBuffer), - done: make(chan struct{}), - write: write, + if replayTurn && (room.running || room.observedTurn || busy) { + // A fresh channel has room; an existing subscriber that cannot take + // it is already being dropped. + _ = enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &protocol.ChatEventFrame{ + SessionID: sessionID, + Kind: protocol.ChatEventStep, + Step: &protocol.ChatStep{Status: protocol.ChatStepStarted}, + }}) } - room.subs[clientID] = sub - h.mu.Unlock() - go sub.run() - return sub + return sub, !ok } // detach drops one subscription. The room (and its broker stream and queue) is @@ -665,25 +693,6 @@ func (h *chatHub) flushBuffered(sessionID string) { } } -// turnRunning reports whether the session has a turn in flight. A client that -// subscribes after a turn started (for example the operator's browser while the -// CLI harness is working) needs this to show Stop and the live activity line; -// the room's own frames only cover events after the subscription. A turn the -// room's stream announced counts too, and so does a turn the broker itself -// reports in flight: the room is rebuilt when its last client reloads, so its -// own record of an earlier prompt does not survive the reload. -func (h *chatHub) turnRunning(sessionID string, broker chatBroker) bool { - h.mu.Lock() - room := h.rooms[sessionID] - running := room != nil && (room.running || room.observedTurn) - h.mu.Unlock() - if running { - return true - } - reporter, ok := broker.(chatTurnReporter) - return ok && reporter.TurnRunning(sessionID) -} - // 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. diff --git a/internal/server/chat_stream.go b/internal/server/chat_stream.go index 69cc5796..2cead68c 100644 --- a/internal/server/chat_stream.go +++ b/internal/server/chat_stream.go @@ -246,17 +246,29 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"}) return } - sub := hub.attach(query.SessionID, clientID, "", broker, write) + // A turn already in flight when this client attaches has no `step started` + // frame in its future, so attaching queues the live marker for it. The + // composer's Stop control and the transcript's one activity row read it; + // the later `step ended` frame settles them normally. The harness is asked + // off the hub mutex; the room's own state is read as the client attaches. + reporter, ok := broker.(chatTurnReporter) + busy := ok && reporter.TurnRunning(query.SessionID) + sub, fresh := hub.attachSub(query.SessionID, clientID, "", broker, write, true, busy) if sub == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "could not attach to session " + query.SessionID}) return } // Acknowledge before the stream is allowed to fan out: otherwise an immediately - // available retained shell can overtake the subscribe reply on this connection. - // The reply carries the prompts the server still holds for the session, so - // a reloaded client draws them as Queued without any device storage. + // available retained shell (or the live-turn marker, or a frame of a turn + // another client starts) can overtake the subscribe reply on this + // connection. The reply carries the prompts the server still holds for the + // session, so a reloaded client draws them as Queued without any device + // storage. queue := hub.queueFrame(query.SessionID) _ = write(protocol.Message{Type: protocol.ChatSubscribe, ID: request.ID, ChatQueue: &queue, ChatShown: hub.shownFrame(query.SessionID)}) + if fresh { + go sub.run() + } if err := hub.ensureObserving(sub.room, broker); err != nil { sub.close() _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "could not observe session " + query.SessionID}) @@ -265,17 +277,6 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH // Observe requests from CLI-originated turns and recover after reload; do // not require the browser to send another prompt just to start polling. hub.startRoomPoller(sub.room, broker) - // A turn already in flight when this client attaches has no `step started` - // frame in its future, so replay the live marker. The composer's Stop control - // and the transcript's one activity row read it; the later `step ended` frame - // settles them normally. - if hub.turnRunning(query.SessionID, broker) { - sub.send(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &protocol.ChatEventFrame{ - SessionID: query.SessionID, - Kind: protocol.ChatEventStep, - Step: &protocol.ChatStep{Status: protocol.ChatStepStarted}, - }}) - } // 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.