Files
pipelines/internal/server/chat.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

98 lines
4.4 KiB
Go

package server
import (
"context"
"crypto/rand"
"encoding/hex"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatBroker is the server-side OpenCode chat seam. *opencode.Chat implements
// it; tests substitute a scripted broker. Keeping it an interface means the
// /connect handler never builds a second OpenCode transport.
type chatBroker interface {
Prompt(ctx context.Context, sessionID, text string) error
// Stream subscribes to the session's OpenCode event stream. ready is called
// once the subscription is attached, before any frame is read, so the caller
// can order the prompt after the subscription.
Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error
Interrupt(ctx context.Context, sessionID string) error
Messages(ctx context.Context, sessionID string, limit int) ([]protocol.ChatMessage, error)
// Sessions lists the endpoint's OpenCode sessions so the handler can
// restrict them to the operator's own recorded sessions.
Sessions(ctx context.Context) ([]protocol.ChatSession, error)
// Create creates one OpenCode session in the given directory and returns it.
Create(ctx context.Context, title, directory string) (protocol.ChatSession, error)
// Session returns the endpoint's own record of one existing session so an
// adopted session carries the endpoint's directory and title; found is false
// when the endpoint does not list sessionID.
Session(ctx context.Context, sessionID string) (protocol.ChatSession, bool, error)
// Permissions lists the session's pending OpenCode approval requests so the
// handler can push chat_permission frames.
Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error)
Reply(ctx context.Context, request protocol.ChatReplyRequest) error
}
// operatorRegistry is the server-side operator-session seam. *pipeline.Store
// satisfies it. It is a table of its own, separate from the pipeline stage
// ownership (SessionOwner/run_session_owners) that settles a run: chat_sessions
// lists operator sessions only and never consults stage ownership.
type operatorRegistry interface {
RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error
TouchOperatorSession(ctx context.Context, sessionID string) error
OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error)
OperatorDirectories(ctx context.Context, limit int) ([]string, error)
}
// 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 {
return "conn-unknown"
}
return "conn-" + hex.EncodeToString(b[:])
}
// handleChat dispatches one chat_* request. It returns true when the request was
// a chat type and has been fully answered (the caller must not fall through to
// the generic response). Frames are pushed after the ack, each through the
// connection-scoped write function so the read loop and the stream goroutine
// never interleave partial websocket writes.
func handleChat(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) bool {
switch request.Type {
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
case protocol.ChatInterrupt:
handleChatSimple(ctx, request, broker, hub, write)
return true
case protocol.ChatReply:
handleChatSimple(ctx, request, broker, hub, write)
return true
case protocol.ChatSessions:
handleChatSessions(ctx, request, broker, hub, registry, write)
return true
case protocol.ChatCreate:
handleChatCreate(ctx, request, broker, registry, write)
return true
case protocol.ChatAdopt:
handleChatAdopt(ctx, request, broker, registry, write)
return true
case protocol.ChatDirectories:
handleChatDirectories(ctx, request, registry, write)
return true
}
return false
}