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

254 lines
10 KiB
Go

package server
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// operatorDirectoryLimit bounds the chat_directories choices: the operator home
// plus recent operator-session directories, capped at this small fixed number so
// a long history is never returned. It matches the posture of the other small
// fixed list bounds.
const operatorDirectoryLimit = 8
// handleChatSessions answers chat_sessions with the operator's own sessions. The
// registry is the single source of truth for which sessions are listed and for
// their directory, tag, created/recency, so a pipeline stage session (recorded
// in run_steps, never in the operator registry) is always excluded and a session
// with no recorded tag is never listed. FAIL-CLOSED: when no registry is
// configured the result is empty, never the whole endpoint list. broker.Sessions
// is called at most once per request, and the registry once. A session is never
// marked Busy: any number of clients may watch and write one session.
func handleChatSessions(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, 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"})
return
}
response := protocol.Message{Type: protocol.ChatSessions, ID: request.ID}
// No registry (no store and no injection): list nothing rather than the whole
// OpenCode machine.
if registry == nil {
_ = write(response)
return
}
operatorSessions, err := registry.OperatorSessions(ctx)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
// OperatorSessions is already most-recently-used first with a deterministic
// tie-break; keep that order and only include a registry session the broker
// still reports, so a session the operator deleted upstream is not listed.
registered := make(map[string]struct{}, len(operatorSessions))
for _, session := range operatorSessions {
if session.ID != "" {
registered[session.ID] = struct{}{}
}
}
sessions, err := broker.Sessions(ctx)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
present := make(map[string]protocol.ChatSession, len(sessions))
for _, session := range sessions {
if _, ok := registered[session.ID]; ok {
present[session.ID] = session
}
}
for _, operator := range operatorSessions {
session, ok := present[operator.ID]
if !ok {
continue
}
if operator.Title != "" {
session.Title = operator.Title
}
session.Directory = operator.Directory
session.Tag = operator.Tag
session.CreatedAt = operator.CreatedAt
session.UpdatedAt = operator.UpdatedAt
response.ChatSessions = append(response.ChatSessions, session)
}
_ = write(response)
}
// handleChatCreate creates one operator session in a resolved directory and
// records it in the operator registry: the OpenCode session id, the exact
// resolved directory, the title and the operator tag. A blank or omitted
// directory defaults to the operator's home, never the server's working
// directory. A registry write failure answers an error naming the created id, so
// an orphaned session is visible rather than silently reported as success.
func handleChatCreate(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, 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"})
return
}
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
title := ""
directory := ""
if request.ChatCreate != nil {
title = strings.TrimSpace(request.ChatCreate.Title)
directory = strings.TrimSpace(request.ChatCreate.Directory)
}
if title == "" {
title = "New chat"
}
resolved, err := resolveChatDirectory(directory)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
session, err := broker.Create(ctx, title, resolved)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
if err := registry.RecordOperatorSession(ctx, session.ID, resolved, title, protocol.ChatSessionTagOperator); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()})
return
}
session.Directory = resolved
session.Tag = protocol.ChatSessionTagOperator
response := protocol.Message{Type: protocol.ChatCreate, ID: request.ID, ChatSession: &session}
// The same registry row is echoed on the list field so a client can splice it
// into chat_sessions without a re-list.
response.ChatSessions = []protocol.ChatSession{session}
_ = write(response)
}
// handleChatAdopt records a session that already exists on the endpoint in the
// operator registry, using the endpoint's own directory and title verbatim, so
// it appears in chat_sessions and can be continued. It refuses a nil broker, a
// nil registry, a nil payload and an invalid/blank id before any broker call; an
// id the endpoint does not report is an error naming the id and records nothing;
// an endpoint record with an empty directory is refused rather than substituting
// the server's working directory or the operator home. The response echoes the
// adopted session and its registry row like chat_create.
func handleChatAdopt(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, 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"})
return
}
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
if request.ChatAdopt == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat_adopt session id is required"})
return
}
id := strings.TrimSpace(request.ChatAdopt.SessionID)
if !opencode.ValidSessionID(id) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
session, found, err := broker.Session(ctx, id)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
if !found {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + id + " was not found on the OpenCode endpoint"})
return
}
directory := strings.TrimSpace(session.Directory)
if directory == "" {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + id + " has no directory on the OpenCode endpoint"})
return
}
if err := registry.RecordOperatorSession(ctx, session.ID, directory, session.Title, protocol.ChatSessionTagOperator); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was found but could not be recorded: " + err.Error()})
return
}
session.Directory = directory
session.Tag = protocol.ChatSessionTagOperator
response := protocol.Message{Type: protocol.ChatAdopt, ID: request.ID, ChatSession: &session}
// The same registry row is echoed on the list field so a client can splice it
// into chat_sessions without a re-list.
response.ChatSessions = []protocol.ChatSession{session}
_ = write(response)
}
// handleChatDirectories answers chat_directories with the operator's home first,
// then the directories of previous operator sessions most-recently-used first,
// deduplicated against the home directory and capped at operatorDirectoryLimit.
func handleChatDirectories(ctx context.Context, request protocol.Message, registry operatorRegistry, write func(protocol.Message) error) {
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
home, err := OperatorHomeDirectory()
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
directories := []string{home}
seen := map[string]struct{}{home: {}}
recent, err := registry.OperatorDirectories(ctx, operatorDirectoryLimit)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
for _, directory := range recent {
if len(directories) >= operatorDirectoryLimit {
break
}
if directory == "" {
continue
}
if _, ok := seen[directory]; ok {
continue
}
seen[directory] = struct{}{}
directories = append(directories, directory)
}
_ = write(protocol.Message{Type: protocol.ChatDirectories, ID: request.ID, ChatDirectories: directories})
}
// resolveChatDirectory resolves a chat_create directory to an absolute path: an
// omitted/empty value, "~" or a "~/..." value resolves to the operator's home
// (os.UserHomeDir) and never the server's working directory; any other value
// must be an absolute, existing directory, so a relative path cannot silently
// create a session relative to wherever the server was started.
func resolveChatDirectory(directory string) (string, error) {
directory = strings.TrimSpace(directory)
if directory == "" || directory == "~" || strings.HasPrefix(directory, "~/") {
return OperatorHomeDirectory()
}
if !filepath.IsAbs(directory) {
return "", errors.New("chat directory must be absolute or start with ~")
}
info, err := os.Stat(directory)
if err != nil {
return "", errors.New("chat directory " + directory + " is not available: " + err.Error())
}
if !info.IsDir() {
return "", errors.New("chat directory " + directory + " is not a directory")
}
return directory, nil
}
// OperatorHomeDirectory returns the operator's home directory, the default chat
// location. It is resolved through the standard library so it never falls back
// to the process working directory.
func OperatorHomeDirectory() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", errors.New("resolve operator home directory: " + err.Error())
}
if home == "" {
return "", errors.New("operator home directory is empty")
}
return home, nil
}