Files
pipelines/internal/server/chat_permissions.go
T
alan 6cb61578de 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.
2026-10-18 00:09:14 +01:00

116 lines
3.9 KiB
Go

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
// seenPermission records requestID as pushed for the session and reports whether
// it is newly seen (true) or a duplicate (false). The retained ids are bounded:
// the oldest is dropped once the session exceeds chatPermissionRetainedLimit, so
// the same pending request is pushed at most once while the state stays bounded.
func (h *chatHub) seenPermission(sessionID, requestID string) bool {
if sessionID == "" || requestID == "" {
return false
}
h.mu.Lock()
defer h.mu.Unlock()
turn := h.turnLocked(sessionID)
if turn.permissions == nil {
turn.permissions = map[string]struct{}{}
}
if _, ok := turn.permissions[requestID]; ok {
return false
}
turn.permissions[requestID] = struct{}{}
turn.permissionOrder = append(turn.permissionOrder, requestID)
if len(turn.permissionOrder) > chatPermissionRetainedLimit {
oldest := turn.permissionOrder[0]
turn.permissionOrder = turn.permissionOrder[1:]
delete(turn.permissions, oldest)
}
return true
}
// 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 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.resolutions, requestID)
for i, id := range turn.resolutionOrder {
if id == requestID {
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)
}
}