Files
pipelines/internal/protocol/message.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

186 lines
8.5 KiB
Go

package protocol
import "git.a-wan.net/alan/pipelines/internal/buildinfo"
const (
Ping = "ping"
Pong = "pong"
Error = "error"
Submit = "submit"
Submitted = "submitted"
List = "list_pipelines"
PipelineList = "pipelines"
GetPipeline = "get_pipeline"
Pipeline = "pipeline"
ListTemplates = "list_templates"
Templates = "templates"
Validate = "validate"
Validated = "validated"
)
type Stage struct {
Limits *StageLimits `json:"limits,omitempty"`
Memory map[string]string `json:"memory,omitempty"`
Notify *NotificationPolicy `json:"notify,omitempty"`
Key string `json:"key"`
Type string `json:"type,omitempty"`
Output string `json:"output"`
Prompt string `json:"prompt"`
Configs map[string]string `json:"configs"`
Edges map[string]string `json:"edges"`
FallbackError bool `json:"fallback_error"`
// Additional type-specific Markdown blocks; legacy model fields remain above.
Blocks map[string]string `json:"blocks,omitempty"`
}
// Limits are enforced by the runner and never included in the model prompt.
type StageLimits struct {
MaxVisits int `json:"max_visits"`
On []string `json:"on,omitempty"`
}
type NotificationPolicy struct {
On []string `json:"on"`
Destination string `json:"destination"`
Artifacts []string `json:"artifacts,omitempty"`
}
// Public phone setup only. Never include publishing endpoints or credentials.
type NotificationEndpoint struct {
Destination string `json:"destination"`
ServerURL string `json:"server_url,omitempty"`
Topic string `json:"topic"`
}
type Template struct {
Key string `json:"key"`
Name string `json:"name"`
Description string `json:"description"`
Source string `json:"source"`
Scheduled bool `json:"scheduled"`
}
type Graph struct {
Stages []Stage `json:"stages"`
Settings *Settings `json:"settings,omitempty"`
}
type Settings struct {
Prompt string `json:"prompt"`
Schedules []Schedule `json:"schedules"`
}
type Schedule struct {
Days []string `json:"days,omitempty"`
Times []string `json:"times,omitempty"`
Every string `json:"every,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
type VersionSummary struct {
Version int `json:"version"`
Stages int `json:"stages"`
CreatedAt string `json:"created_at"`
}
type PipelineDetail struct {
PipelineSummary
LatestVersion int `json:"latest_version"`
VersionCreatedAt string `json:"version_created_at"`
ContentHash string `json:"content_hash"`
Source string `json:"source"`
Graph Graph `json:"graph"`
Versions []VersionSummary `json:"versions"`
}
type PipelineSummary struct {
ID int64 `json:"id"`
Name string `json:"name"`
Version int `json:"version"`
Stages int `json:"stages"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// Message is the JSON envelope shared by the server and client. It also brokers
// omni search: a client sends Type "search" with an ID, Query text, an optional
// Kind type filter and an optional Limit, and the server replies with Type
// "search_results", the echoed ID and a ranked SearchResponse. Both search fields
// are optional so older peers ignore them. See search.go for the per-type payloads
// and the ranking/kind/bound vocabulary.
type Message struct {
DefaultHarness string `json:"default_harness,omitempty"`
Build *buildinfo.Info `json:"build,omitempty"`
Protocol int `json:"protocol,omitempty"`
DefaultModel string `json:"default_model,omitempty"`
Evidence []SessionEvidence `json:"evidence,omitempty"`
Usage *UsageStats `json:"usage,omitempty"`
Status *SystemStatus `json:"status,omitempty"`
Graph *Graph `json:"graph,omitempty"`
ExpectedVersion int `json:"expected_version,omitempty"`
Templates []Template `json:"templates,omitempty"`
CreateOnly bool `json:"create_only,omitempty"`
NotificationEndpoints []NotificationEndpoint `json:"notification_endpoints,omitempty"`
Type string `json:"type"`
ID string `json:"id,omitempty"`
Time string `json:"time,omitempty"`
Error string `json:"error,omitempty"`
Name string `json:"name,omitempty"`
Source string `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Version int `json:"version,omitempty"`
Pipelines []PipelineSummary `json:"pipelines,omitempty"`
PipelineID int64 `json:"pipeline_id,omitempty"`
Detail *PipelineDetail `json:"detail,omitempty"`
RunID int64 `json:"run_id,omitempty"`
RunDetail *RunDetail `json:"run_detail,omitempty"`
Runs []RunSummary `json:"runs,omitempty"`
Stage string `json:"stage,omitempty"`
Option string `json:"option,omitempty"`
Feedback string `json:"feedback,omitempty"`
Input map[string]any `json:"input,omitempty"`
AllowTools bool `json:"allow_tools,omitempty"`
WritePaths []string `json:"write_paths,omitempty"`
RequestKey string `json:"request_key,omitempty"`
Workspace string `json:"workspace,omitempty"`
// Model and StageModels are the launch-time model overrides: Model applies to
// every model stage of the run and StageModels overrides individual stages by
// key (per-stage wins over whole-run). Both are optional so older peers ignore
// them; the same fields are echoed on the run record.
Model string `json:"model,omitempty"`
StageModels map[string]string `json:"stage_models,omitempty"`
// Search is the broad, read-only search traffic over pipelines, versions,
// runs, steps, field text and artifacts. See search.go for the per-type
// payloads and the ranking/kind/bound vocabulary.
Search *SearchRequest `json:"search,omitempty"`
SearchResults *SearchResponse `json:"search_results,omitempty"`
// Chat is the brokered OpenCode chat traffic (route B). See chat.go for the
// per-type payload structs and the wire shapes they mirror.
ChatSessions []ChatSession `json:"chat_sessions,omitempty"`
ChatSession *ChatSession `json:"chat_session,omitempty"`
ChatCreate *ChatCreateRequest `json:"chat_create,omitempty"`
ChatAdopt *ChatAdoptRequest `json:"chat_adopt,omitempty"`
ChatQuery *ChatQuery `json:"chat_query,omitempty"`
ChatPrompt *ChatPromptRequest `json:"chat_prompt,omitempty"`
ChatMessages []ChatMessage `json:"chat_messages,omitempty"`
ChatEvent *ChatEventFrame `json:"chat_event,omitempty"`
ChatPermission *ChatPermissionFrame `json:"chat_permission,omitempty"`
ChatReply *ChatReplyRequest `json:"chat_reply,omitempty"`
// ChatSubscribe attaches this connection to one session's shared stream; the
// body names the session like ChatQuery. A chat_prompt response sets
// ChatQueued when the prompt had to wait for an in-flight turn and was
// accepted into the session's queue instead of being sent immediately.
ChatSubscribe *ChatQuery `json:"chat_subscribe,omitempty"`
ChatQueued bool `json:"chat_queued,omitempty"`
// ChatDirectories carries the operator's directory choices on a
// chat_directories response (home first, then recent operator-session
// directories, deduplicated and bounded). Additive/omitempty so older peers
// ignore it.
ChatDirectories []string `json:"chat_directories,omitempty"`
// RunEvent is the server-pushed run state delta (see runevents.go) and
// RunIDs the optional subscribe scope, so a client asks for the runs it
// displays. Both are optional so older peers ignore them.
RunEvent *RunEventFrame `json:"run_event,omitempty"`
RunIDs []int64 `json:"run_ids,omitempty"`
}