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