chat: add the Codex backend

Store a chat's harness with its operator session, expose chat_backends and a
backend choice in New chat, and route each session through a manager. The Codex
adapter uses the App Server's Unix WebSocket for threads, turns, history,
questions and interrupt; OpenCode remains the default and Claude is not
advertised until its sidecar and login are wired.
This commit is contained in:
2026-10-20 12:10:39 +01:00
parent 74b74adee7
commit f7a3a49f94
25 changed files with 1287 additions and 32 deletions
+7
View File
@@ -121,6 +121,13 @@ func main() {
openCodeStatus.Health = "unavailable"
}
options.OpenCodeStatus = openCodeStatus
// One manager routes each chat to its owning harness. OpenCode remains the
// default; Codex is attached when its app-server control socket is present.
chats := server.NewChatManager(ctx, options.Chat, store)
if len(chats.Backends()) > 0 {
options.Chat = chats
defer chats.Close()
}
srv := &http.Server{Addr: *addr, Handler: server.HandlerWithOptions(ctx, options, store), ReadHeaderTimeout: 5 * time.Second}
defer server.WaitRuns(srv.Handler)
go func() {
+21
View File
@@ -0,0 +1,21 @@
# Chat backends
Chats can be created on more than one harness. OpenCode remains the default;
Codex is available when its App Server control socket exists. The selected
backend is stored on the operator-session row and returned as `backend` on every
`chat_sessions` row, so a restart does not have to guess from the session id.
## Codex
The adapter in `internal/codex` connects to the Codex App Server's Unix
WebSocket control socket (`$CODEX_HOME/app-server-control/app-server-control.sock`,
falling back to `~/.codex`). It uses the operator's existing Codex login. A new
chat issues `thread/start`; a prompt issues `turn/start`; history comes from
`thread/read`; questions map from `item/tool/requestUserInput` to the normal
question card and `chat_answer` returns the JSON-RPC response. Threads created
this way are ordinary Codex threads and remain visible to the Codex app.
The adapter creates threads with `approvalPolicy: never` and
`sandbox: workspace-write`; Codex approvals are not brokered through the chat
permission card yet. Claude is not advertised as a backend until its sidecar and
login flow are wired.
+765
View File
@@ -0,0 +1,765 @@
// Package codex brokers an operator chat through the Codex App Server.
//
// Codex exposes threads, turns and items over JSON-RPC. The App Server is
// normally reached over a Unix WebSocket socket (the desktop app and the CLI use
// the same control socket). This adapter owns one client connection and mirrors
// the protocol into the Pipelines chat frames; it never starts a second Codex
// daemon or changes the operator's Codex configuration.
package codex
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/coder/websocket"
)
// Backend is the wire value stored in the operator-session registry.
const Backend = "codex"
// DefaultSocketPath is the Codex desktop app-server control socket.
func DefaultSocketPath() string {
home := os.Getenv("CODEX_HOME")
if home == "" {
userHome, err := os.UserHomeDir()
if err != nil {
return ""
}
home = filepath.Join(userHome, ".codex")
}
return filepath.Join(home, "app-server-control", "app-server-control.sock")
}
// Chat is one owned App Server connection.
type Chat struct {
conn *websocket.Conn
ctx context.Context
cancel context.CancelFunc
writeMu sync.Mutex
nextID int64
mu sync.Mutex
pending map[string]chan rpcResponse
subs map[string]map[chan protocol.ChatEventFrame]struct{}
forms map[string]pendingForm
turns map[string]string
emitted map[string]bool
closed bool
}
type pendingForm struct {
requestID json.RawMessage
threadID string
form protocol.ChatForm
}
type rpcResponse struct {
Result json.RawMessage
Error *rpcError
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type rpcMessage struct {
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
Result json.RawMessage `json:"result"`
Error *rpcError `json:"error"`
}
// Open connects to the app-server socket and performs the initialize handshake.
func Open(ctx context.Context) (*Chat, error) {
socket := DefaultSocketPath()
if socket == "" {
return nil, errors.New("Codex home is unavailable")
}
transport := &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
},
}
client := &http.Client{Transport: transport}
conn, _, err := websocket.Dial(ctx, "ws://localhost/", &websocket.DialOptions{HTTPClient: client})
if err != nil {
return nil, fmt.Errorf("connect Codex app-server: %w", err)
}
conn.SetReadLimit(16 << 20)
child, cancel := context.WithCancel(ctx)
c := &Chat{
conn: conn, ctx: child, cancel: cancel,
pending: map[string]chan rpcResponse{},
subs: map[string]map[chan protocol.ChatEventFrame]struct{}{},
forms: map[string]pendingForm{},
turns: map[string]string{},
emitted: map[string]bool{},
}
go c.readLoop()
initCtx, initCancel := context.WithTimeout(ctx, 10*time.Second)
defer initCancel()
if _, err := c.call(initCtx, "initialize", map[string]any{
"clientInfo": map[string]any{"name": "pipelines", "title": "Pipelines", "version": "0.1"},
}); err != nil {
c.Close()
return nil, fmt.Errorf("initialize Codex app-server: %w", err)
}
return c, nil
}
// Available reports whether the app-server control socket exists.
func Available() bool {
path := DefaultSocketPath()
if path == "" {
return false
}
info, err := os.Stat(path)
return err == nil && info.Mode()&os.ModeSocket != 0
}
// Close shuts the owned client connection down.
func (c *Chat) Close() {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return
}
c.closed = true
c.mu.Unlock()
c.cancel()
_ = c.conn.Close(websocket.StatusNormalClosure, "")
}
func (c *Chat) readLoop() {
for {
_, data, err := c.conn.Read(c.ctx)
if err != nil {
c.failPending(err)
return
}
var msg rpcMessage
if err := json.Unmarshal(data, &msg); err != nil {
continue
}
if len(msg.ID) > 0 && msg.Method != "" {
c.handleServerRequest(msg)
continue
}
if len(msg.ID) > 0 {
key := string(msg.ID)
c.mu.Lock()
ch := c.pending[key]
delete(c.pending, key)
c.mu.Unlock()
if ch != nil {
ch <- rpcResponse{Result: msg.Result, Error: msg.Error}
}
continue
}
if msg.Method != "" {
c.handleNotification(msg)
}
}
}
func (c *Chat) failPending(err error) {
c.mu.Lock()
pending := c.pending
c.pending = map[string]chan rpcResponse{}
subs := c.subs
c.subs = map[string]map[chan protocol.ChatEventFrame]struct{}{}
c.mu.Unlock()
for _, ch := range pending {
ch <- rpcResponse{Error: &rpcError{Message: err.Error()}}
}
for _, set := range subs {
for ch := range set {
close(ch)
}
}
}
func (c *Chat) call(ctx context.Context, method string, params any) (json.RawMessage, error) {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil, errors.New("Codex connection is closed")
}
c.nextID++
id := c.nextID
ch := make(chan rpcResponse, 1)
c.pending[strconv.FormatInt(id, 10)] = ch
c.mu.Unlock()
payload := map[string]any{"id": id, "method": method}
if params != nil {
payload["params"] = params
}
data, err := json.Marshal(payload)
if err != nil {
return nil, err
}
c.writeMu.Lock()
err = c.conn.Write(ctx, websocket.MessageText, data)
c.writeMu.Unlock()
if err != nil {
c.mu.Lock()
delete(c.pending, strconv.FormatInt(id, 10))
c.mu.Unlock()
return nil, err
}
select {
case <-ctx.Done():
c.mu.Lock()
delete(c.pending, strconv.FormatInt(id, 10))
c.mu.Unlock()
return nil, ctx.Err()
case resp := <-ch:
if resp.Error != nil {
return nil, errors.New(resp.Error.Message)
}
return resp.Result, nil
}
}
func (c *Chat) respond(id json.RawMessage, result any) {
payload := map[string]any{"id": id, "result": result}
data, err := json.Marshal(payload)
if err != nil {
return
}
c.writeMu.Lock()
_ = c.conn.Write(c.ctx, websocket.MessageText, data)
c.writeMu.Unlock()
}
func (c *Chat) emit(frame protocol.ChatEventFrame) {
c.mu.Lock()
set := c.subs[frame.SessionID]
var targets []chan protocol.ChatEventFrame
for ch := range set {
targets = append(targets, ch)
}
c.mu.Unlock()
for _, ch := range targets {
select {
case ch <- frame:
default:
// A slow client must not block the shared Codex connection. The hub
// will repair from history on its next subscription.
}
}
}
func (c *Chat) subscribe(id string) chan protocol.ChatEventFrame {
ch := make(chan protocol.ChatEventFrame, 256)
c.mu.Lock()
if c.subs[id] == nil {
c.subs[id] = map[chan protocol.ChatEventFrame]struct{}{}
}
c.subs[id][ch] = struct{}{}
c.mu.Unlock()
return ch
}
func (c *Chat) unsubscribe(id string, ch chan protocol.ChatEventFrame) {
c.mu.Lock()
if set := c.subs[id]; set != nil {
delete(set, ch)
if len(set) == 0 {
delete(c.subs, id)
}
}
c.mu.Unlock()
}
// Stream exposes one thread's notifications as chat frames.
func (c *Chat) Stream(ctx context.Context, id string, ready func(), emit func(protocol.ChatEventFrame) error) error {
ch := c.subscribe(id)
defer c.unsubscribe(id, ch)
if ready != nil {
ready()
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case frame, ok := <-ch:
if !ok {
return errors.New("Codex connection closed")
}
if err := emit(frame); err != nil {
return err
}
}
}
}
// Prompt starts one turn. The user turn is already broadcast by the server, so
// the adapter only forwards the assistant's items.
func (c *Chat) Prompt(ctx context.Context, id, text string) error {
return c.PromptWithMessageID(ctx, id, text, "")
}
// PromptWithMessageID carries the client's native user-message id so the
// optimistic browser bubble and the authoritative history item can reconcile.
func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID string) error {
if strings.TrimSpace(text) == "" {
return errors.New("empty chat prompt")
}
params := map[string]any{
"threadId": id,
"input": []any{map[string]any{"type": "text", "text": text}},
}
if messageID != "" {
params["clientUserMessageId"] = messageID
}
_, err := c.call(ctx, "turn/start", params)
return err
}
// Permissions is empty: Codex approvals are disabled on threads this adapter
// creates (approvalPolicy never), and questions arrive as requestUserInput.
func (c *Chat) Permissions(context.Context, string) ([]protocol.ChatPermissionFrame, error) {
return nil, nil
}
// Shells is empty: Codex background terminals are not exposed through the chat
// surface yet.
func (c *Chat) Shells(context.Context, string) ([]protocol.ChatShell, error) {
return nil, nil
}
// Reply is unused because Codex approvals are not created for these threads.
func (c *Chat) Reply(context.Context, protocol.ChatReplyRequest) error {
return errors.New("Codex approvals are not enabled for this chat backend")
}
// ActivateSkill is an OpenCode-only chat concept.
func (c *Chat) ActivateSkill(context.Context, string, string) error {
return errors.New("Codex chat has no out-of-band skill activation")
}
// Interrupt cancels the thread's active turn.
func (c *Chat) Interrupt(ctx context.Context, id string) error {
c.mu.Lock()
turn := c.turns[id]
c.mu.Unlock()
if turn == "" {
return nil
}
_, err := c.call(ctx, "turn/interrupt", map[string]any{"threadId": id, "turnId": turn})
return err
}
// Create starts one Codex thread in directory.
func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
if strings.TrimSpace(directory) == "" {
return protocol.ChatSession{}, errors.New("a directory is required")
}
raw, err := c.call(ctx, "thread/start", map[string]any{
"cwd": directory,
"approvalPolicy": "never",
"sandbox": "workspace-write",
})
if err != nil {
return protocol.ChatSession{}, err
}
var result struct {
Thread thread `json:"thread"`
}
if err := json.Unmarshal(raw, &result); err != nil {
return protocol.ChatSession{}, err
}
session := result.Thread.chatSession()
session.Backend = Backend
if strings.TrimSpace(title) != "" {
session.Title = strings.TrimSpace(title)
}
if title != "" {
_, _ = c.call(ctx, "thread/name/set", map[string]any{"threadId": session.ID, "name": title})
}
return session, nil
}
// Session returns one thread's current record.
func (c *Chat) Session(ctx context.Context, id string) (protocol.ChatSession, bool, error) {
raw, err := c.call(ctx, "thread/read", map[string]any{"threadId": id})
if err != nil {
return protocol.ChatSession{}, false, err
}
var result struct {
Thread thread `json:"thread"`
}
if err := json.Unmarshal(raw, &result); err != nil {
return protocol.ChatSession{}, false, err
}
if result.Thread.ID == "" {
return protocol.ChatSession{}, false, nil
}
session := result.Thread.chatSession()
session.Backend = Backend
return session, true, nil
}
// Sessions lists Codex threads (bounded) so the server can intersect them with
// the operator registry.
func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
raw, err := c.call(ctx, "thread/list", map[string]any{"limit": 200})
if err != nil {
return nil, err
}
var result struct {
Data []thread `json:"data"`
}
if err := json.Unmarshal(raw, &result); err != nil {
return nil, err
}
sessions := make([]protocol.ChatSession, 0, len(result.Data))
for _, t := range result.Data {
session := t.chatSession()
session.Backend = Backend
sessions = append(sessions, session)
}
return sessions, nil
}
// Messages reads a thread's turns and flattens them into chat messages.
func (c *Chat) Messages(ctx context.Context, id string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
_ = limit
_ = cursor
raw, err := c.call(ctx, "thread/read", map[string]any{"threadId": id, "includeTurns": true})
if err != nil {
return protocol.ChatHistoryPage{}, err
}
var result struct {
Thread thread `json:"thread"`
}
if err := json.Unmarshal(raw, &result); err != nil {
return protocol.ChatHistoryPage{}, err
}
messages := []protocol.ChatMessage{}
for _, turn := range result.Thread.Turns {
for _, item := range turn.Items {
if msg, ok := item.chatMessage(id); ok {
messages = append(messages, msg)
}
}
}
return protocol.ChatHistoryPage{Messages: messages}, nil
}
// Answer replies to a pending requestUserInput request.
func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
c.mu.Lock()
pending, ok := c.forms[request.FormID]
if ok {
delete(c.forms, request.FormID)
}
c.mu.Unlock()
if !ok {
return errors.New("the Codex question is no longer awaiting an answer")
}
answers := map[string]any{}
for key, value := range request.Answers {
switch v := value.(type) {
case []any:
answers[key] = map[string]any{"answers": v}
case []string:
answers[key] = map[string]any{"answers": v}
case string:
answers[key] = map[string]any{"answers": []string{v}}
default:
answers[key] = map[string]any{"answers": []string{fmt.Sprint(v)}}
}
}
c.respond(pending.requestID, map[string]any{"answers": answers})
c.emit(protocol.ChatEventFrame{
SessionID: pending.threadID,
Kind: protocol.ChatEventForm,
Form: &protocol.ChatForm{ID: pending.form.ID, SessionID: pending.threadID, Resolved: true},
})
return nil
}
func (c *Chat) handleServerRequest(msg rpcMessage) {
switch msg.Method {
case "item/tool/requestUserInput":
var params struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
ItemID string `json:"itemId"`
Questions []struct {
ID string `json:"id"`
Header string `json:"header"`
Question string `json:"question"`
IsOther bool `json:"isOther"`
IsSecret bool `json:"isSecret"`
Options []struct {
Value string `json:"value"`
Label string `json:"label"`
Description string `json:"description"`
} `json:"options"`
} `json:"questions"`
}
if err := json.Unmarshal(msg.Params, &params); err != nil || params.ThreadID == "" || params.ItemID == "" {
c.respond(msg.ID, map[string]any{"answers": map[string]any{}})
return
}
form := protocol.ChatForm{
ID: params.ItemID,
SessionID: params.ThreadID,
Title: "Question",
Kind: "question",
}
for _, q := range params.Questions {
field := protocol.ChatFormField{
Key: q.ID, Title: q.Question, Description: q.Header,
Type: "string", Custom: q.IsOther, Required: true,
}
for _, option := range q.Options {
value := option.Value
if value == "" {
value = option.Label
}
field.Options = append(field.Options, protocol.ChatFormOption{
Value: value, Label: option.Label, Description: option.Description,
})
}
form.Fields = append(form.Fields, field)
}
c.mu.Lock()
c.forms[form.ID] = pendingForm{requestID: msg.ID, threadID: params.ThreadID, form: form}
c.mu.Unlock()
c.emit(protocol.ChatEventFrame{SessionID: params.ThreadID, Kind: protocol.ChatEventForm, Form: &form})
case "item/commandExecution/requestApproval", "item/fileChange/requestApproval":
// The thread is created with approvalPolicy never; if a provider still asks,
// deny rather than leave the turn hanging.
c.respond(msg.ID, map[string]any{"decision": "deny"})
default:
// Unknown server requests must not stall the shared connection.
c.respond(msg.ID, map[string]any{})
}
}
func (c *Chat) handleNotification(msg rpcMessage) {
var params struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
ItemID string `json:"itemId"`
Delta string `json:"delta"`
Item json.RawMessage `json:"item"`
Turn struct {
ID string `json:"id"`
Status string `json:"status"`
} `json:"turn"`
Status struct {
Type string `json:"type"`
} `json:"status"`
}
if err := json.Unmarshal(msg.Params, &params); err != nil || params.ThreadID == "" {
return
}
switch msg.Method {
case "turn/started":
c.mu.Lock()
c.turns[params.ThreadID] = params.TurnID
if c.turns[params.ThreadID] == "" {
c.turns[params.ThreadID] = params.Turn.ID
}
c.mu.Unlock()
c.emit(stepFrame(params.ThreadID, "started"))
case "turn/completed":
c.mu.Lock()
delete(c.turns, params.ThreadID)
c.mu.Unlock()
c.emit(stepFrame(params.ThreadID, protocol.ChatStepEnded))
case "item/started":
c.handleItem(params.ThreadID, params.ItemID, params.Item, false)
case "item/completed":
c.handleItem(params.ThreadID, params.ItemID, params.Item, true)
case "item/agentMessage/delta", "item/agentMessage/streaming":
if params.ItemID != "" && params.Delta != "" {
c.markEmitted(params.ItemID)
c.emit(textFrame(params.ThreadID, params.ItemID, protocol.ChatEventText, params.Delta))
}
case "item/reasoning/delta":
if params.ItemID != "" && params.Delta != "" {
c.markEmitted(params.ItemID)
c.emit(textFrame(params.ThreadID, params.ItemID, protocol.ChatEventReasoning, params.Delta))
}
}
}
func (c *Chat) handleItem(threadID, itemID string, raw json.RawMessage, completed bool) {
var item struct {
ID string `json:"id"`
Type string `json:"type"`
Text string `json:"text"`
Status string `json:"status"`
Command string `json:"command"`
Query string `json:"query"`
Name string `json:"name"`
Input any `json:"input"`
Error string `json:"error"`
}
if err := json.Unmarshal(raw, &item); err != nil {
return
}
if item.ID == "" {
item.ID = itemID
}
switch item.Type {
case "agentMessage":
if completed && item.Text != "" && !c.wasEmitted(item.ID) {
c.emit(textFrame(threadID, item.ID, protocol.ChatEventText, item.Text))
}
case "reasoning":
if completed && item.Text != "" && !c.wasEmitted(item.ID) {
c.emit(textFrame(threadID, item.ID, protocol.ChatEventReasoning, item.Text))
}
case "commandExecution", "fileChange", "mcpToolCall", "webSearch":
status := protocol.ChatToolRunning
if completed {
if strings.EqualFold(item.Status, "failed") || item.Error != "" {
status = protocol.ChatToolError
} else {
status = protocol.ChatToolCompleted
}
}
name := item.Type
var input any
switch item.Type {
case "commandExecution":
name = "shell"
input = map[string]any{"command": item.Command}
case "webSearch":
name = "websearch"
input = map[string]any{"query": item.Query}
default:
if item.Name != "" {
name = item.Name
}
input = item.Input
}
encoded, _ := json.Marshal(input)
state := &protocol.ChatToolState{Status: status, Input: encoded}
if item.Text != "" {
state.Content = []protocol.ChatToolContent{{Type: "text", Text: item.Text}}
}
if item.Error != "" {
state.Error = &protocol.ChatError{Message: item.Error}
}
c.emit(protocol.ChatEventFrame{
SessionID: threadID, MessageID: item.ID, Kind: protocol.ChatEventTool,
Part: &protocol.ChatPart{Type: protocol.ChatPartTool, ID: item.ID, Name: name, State: state},
})
}
}
func (c *Chat) markEmitted(id string) {
c.mu.Lock()
c.emitted[id] = true
c.mu.Unlock()
}
func (c *Chat) wasEmitted(id string) bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.emitted[id]
}
func textFrame(threadID, itemID, kind, delta string) protocol.ChatEventFrame {
return protocol.ChatEventFrame{
SessionID: threadID, MessageID: itemID, Kind: kind, Delta: delta,
Part: &protocol.ChatPart{Type: kind, ID: protocol.ChatDeltaPartID(itemID, kind, 0)},
}
}
func stepFrame(threadID, status string) protocol.ChatEventFrame {
return protocol.ChatEventFrame{
SessionID: threadID, Kind: protocol.ChatEventStep,
Step: &protocol.ChatStep{Status: status},
}
}
type thread struct {
ID string `json:"id"`
Name string `json:"name"`
Preview string `json:"preview"`
Cwd string `json:"cwd"`
CreatedAt int64 `json:"createdAt"`
UpdatedAt int64 `json:"updatedAt"`
Turns []turn `json:"turns"`
}
type turn struct {
Items []item `json:"items"`
}
type item struct {
ID string `json:"id"`
ClientID string `json:"clientId"`
Type string `json:"type"`
Text string `json:"text"`
Content json.RawMessage `json:"content"`
Status string `json:"status"`
Command string `json:"command"`
Query string `json:"query"`
Name string `json:"name"`
Input any `json:"input"`
Error string `json:"error"`
}
func (t thread) chatSession() protocol.ChatSession {
title := strings.TrimSpace(t.Name)
if title == "" {
title = strings.TrimSpace(t.Preview)
}
return protocol.ChatSession{
ID: t.ID, Title: title, Directory: t.Cwd,
CreatedAt: t.CreatedAt * 1000, UpdatedAt: t.UpdatedAt * 1000,
}
}
func (i item) chatMessage(sessionID string) (protocol.ChatMessage, bool) {
msg := protocol.ChatMessage{ID: i.ID, SessionID: sessionID}
switch i.Type {
case "userMessage":
msg.Role = protocol.ChatRoleUser
if i.ClientID != "" {
msg.ID = i.ClientID
}
var content []struct {
Type string `json:"type"`
Text string `json:"text"`
}
_ = json.Unmarshal(i.Content, &content)
for _, part := range content {
if part.Type == "text" && part.Text != "" {
msg.Parts = append(msg.Parts, protocol.ChatPart{Type: protocol.ChatPartText, Text: part.Text})
}
}
case "agentMessage":
msg.Role = protocol.ChatRoleAssistant
if i.Text != "" {
msg.Parts = append(msg.Parts, protocol.ChatPart{Type: protocol.ChatPartText, Text: i.Text})
}
default:
return protocol.ChatMessage{}, false
}
return msg, len(msg.Parts) > 0
}
+20 -5
View File
@@ -23,6 +23,9 @@ type OperatorSession struct {
Directory string
Title string
Tag string
// Backend names the chat harness that owns the session: opencode, codex or
// claude. Rows created before backends existed default to opencode.
Backend string
CreatedAt int64
UpdatedAt int64
// ClosedAt is the epoch-millisecond time the operator finished with the
@@ -63,7 +66,7 @@ func (s *Store) initOperatorSessions() error {
session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL,
closed_at INTEGER NOT NULL DEFAULT 0, starred_at INTEGER NOT NULL DEFAULT 0,
ephemeral INTEGER NOT NULL DEFAULT 0);
backend TEXT NOT NULL DEFAULT 'opencode', ephemeral INTEGER NOT NULL DEFAULT 0);
CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`)
if err != nil {
return err
@@ -144,6 +147,11 @@ func (s *Store) migrateOperatorSessions() error {
if err := s.addColumnIfMissing("operator_sessions", "starred_at", "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
// backend records which harness owns the session so a restart can route a
// chat without guessing from its id. Existing rows are OpenCode.
if err := s.addColumnIfMissing("operator_sessions", "backend", "TEXT NOT NULL DEFAULT 'opencode'"); err != nil {
return err
}
// ephemeral marks a chat created for automated verification. It is hidden from
// OperatorSessions but still a real row, so the session stays usable and
// closable. Existing rows default to 0 (a normal, listed chat).
@@ -221,6 +229,13 @@ func (s *Store) SetOperatorSessionTitle(ctx context.Context, sessionID, title st
return err
}
// SetOperatorSessionBackend records which harness owns a session. It is called
// once after a create; the backend never changes for an existing session.
func (s *Store) SetOperatorSessionBackend(ctx context.Context, sessionID, backend string) error {
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET backend=? WHERE session_id=?", backend, sessionID)
return err
}
// SetOperatorSessionStar records the shared star state in one UPDATE. A session
// id that is not an operator session updates no row and is not an error, so a
// pipeline-owned run session is never affected.
@@ -238,9 +253,9 @@ func (s *Store) SetOperatorSessionStar(ctx context.Context, sessionID string, st
// returned). It is one indexed lookup and never mutates the row.
func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) {
var session OperatorSession
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at,starred_at
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at
FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return OperatorSession{}, false, nil
}
@@ -259,7 +274,7 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
// operator can still see and reopen what they finished. It is one bounded
// statement; recency is never mutated here.
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) {
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at,starred_at
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at
FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
if err != nil {
return nil, err
@@ -268,7 +283,7 @@ FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at D
sessions := []OperatorSession{}
for rows.Next() {
var session OperatorSession
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
return nil, err
}
sessions = append(sessions, session)
+12 -3
View File
@@ -43,6 +43,9 @@ const (
// ChatRename records the operator's shared chat title on the server. Unlike
// a local override, every browser and device then lists the same name.
ChatRename = "chat_rename"
// ChatBackends lists the installed chat harnesses the server can create a
// session on. The reply is a bounded array of backend names.
ChatBackends = "chat_backends"
// ChatStar records the operator's star on the server, so every browser and
// device shows the same starred group. It takes a ChatQuery with SessionID
// and Starred, and echoes the updated session like close/reopen.
@@ -154,7 +157,10 @@ const (
// phone: the nested location.directory and time{created,updated} fields are
// lifted to Directory, CreatedAt and UpdatedAt.
type ChatSession struct {
ID string `json:"id"`
ID string `json:"id"`
// Backend names the harness that owns this session: opencode, codex or
// claude. Empty on older peers and for legacy OpenCode rows.
Backend string `json:"backend,omitempty"`
Title string `json:"title,omitempty"`
Agent string `json:"agent,omitempty"`
Model string `json:"model,omitempty"`
@@ -203,8 +209,11 @@ type ChatCloseResult struct {
// correlation. Clients retrying a create across reconnects must retain it. The
// response carries the created session in Message.ChatSession.
type ChatCreateRequest struct {
Title string `json:"title,omitempty"`
Directory string `json:"directory,omitempty"`
Title string `json:"title,omitempty"`
Directory string `json:"directory,omitempty"`
// Backend selects the chat harness for a new session. Empty means opencode,
// preserving older clients and the default.
Backend string `json:"backend,omitempty"`
OperationID string `json:"operation_id,omitempty"`
// Ephemeral creates a chat for automated verification: the session is created,
// bootstrapped and usable exactly like a normal one, but no operator-registry
+3
View File
@@ -188,6 +188,9 @@ type Message struct {
ChatAnswer *ChatAnswerRequest `json:"chat_answer,omitempty"`
// ChatRename is the chat_rename body; the reply echoes the updated session.
ChatRename *ChatRenameRequest `json:"chat_rename,omitempty"`
// ChatBackends is the chat_backends reply: the installed harnesses a new
// chat can use.
ChatBackends []string `json:"chat_backends,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
+14
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"regexp"
"strconv"
"sync/atomic"
@@ -92,6 +93,16 @@ type operatorRegistry interface {
ReopenOperatorSession(ctx context.Context, sessionID string) error
SetOperatorSessionStar(ctx context.Context, sessionID string, starred bool) error
SetOperatorSessionTitle(ctx context.Context, sessionID, title string) error
SetOperatorSessionBackend(ctx context.Context, sessionID, backend string) error
}
// validChatSessionID accepts the opaque id shapes of the supported harnesses
// (OpenCode ses_…, Codex/Claude UUIDs). The owning adapter still validates the
// exact shape before any provider call; this only rejects clearly unsafe ids.
var chatSessionIDPattern = regexp.MustCompile(`^(?:ses_[A-Za-z0-9_]+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$`)
func validChatSessionID(id string) bool {
return len(id) <= 200 && chatSessionIDPattern.MatchString(id)
}
var chatTokenSequence atomic.Uint64
@@ -157,6 +168,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatRename:
handleChatRename(ctx, request, registry, write)
return true
case protocol.ChatBackends:
handleChatBackends(request, broker, write)
return true
case protocol.ChatShells:
handleChatShells(ctx, request, broker, registry, write)
return true
+1 -2
View File
@@ -3,7 +3,6 @@ package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -23,7 +22,7 @@ func handleChatAnswer(ctx context.Context, request protocol.Message, broker chat
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat_answer payload is required"})
return
}
if !opencode.ValidSessionID(answer.SessionID) {
if !validChatSessionID(answer.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
+23
View File
@@ -0,0 +1,23 @@
package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// handleChatBackends lists the installed chat harnesses. Older servers answer
// with the empty field, which clients treat as OpenCode-only.
func handleChatBackends(request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
backends := []string{"opencode"}
if lister, ok := broker.(interface{ Backends() []string }); ok {
backends = lister.Backends()
}
_ = write(protocol.Message{Type: protocol.ChatBackends, ID: request.ID, ChatBackends: backends})
}
// chatCreateBackend is the optional create-with-backend surface implemented by
// the multi-harness manager. A single-broker installation keeps using Create.
type chatCreateBackend interface {
CreateBackend(ctx context.Context, title, directory, backend string) (protocol.ChatSession, error)
}
+3 -3
View File
@@ -4,7 +4,6 @@ import (
"context"
"strings"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -28,7 +27,7 @@ func handleChatClose(ctx context.Context, request protocol.Message, broker chatB
return
}
query := request.ChatQuery
if query == nil || !opencode.ValidSessionID(query.SessionID) {
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
@@ -88,7 +87,7 @@ func handleChatReopen(ctx context.Context, request protocol.Message, registry op
return
}
query := request.ChatQuery
if query == nil || !opencode.ValidSessionID(query.SessionID) {
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
@@ -135,6 +134,7 @@ func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSess
Tag: session.Tag,
CreatedAt: session.CreatedAt,
UpdatedAt: session.UpdatedAt,
Backend: session.Backend,
}
if session.ClosedAt > 0 {
out.Closed = true
+3 -4
View File
@@ -4,13 +4,12 @@ import (
"context"
"strings"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func handleChatMessages(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, write func(protocol.Message) error) {
query := request.ChatQuery
if query == nil || !opencode.ValidSessionID(query.SessionID) {
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
@@ -39,7 +38,7 @@ func handleChatSimple(ctx context.Context, request protocol.Message, broker chat
}
if request.Type == protocol.ChatInterrupt {
query := request.ChatQuery
if query == nil || !opencode.ValidSessionID(query.SessionID) {
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
@@ -51,7 +50,7 @@ func handleChatSimple(ctx context.Context, request protocol.Message, broker chat
return
}
reply := request.ChatReply
if reply == nil || !opencode.ValidSessionID(reply.SessionID) {
if reply == nil || !validChatSessionID(reply.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
+292
View File
@@ -0,0 +1,292 @@
package server
import (
"context"
"errors"
"sort"
"sync"
"git.a-wan.net/alan/pipelines/internal/codex"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatManager routes one session to the harness that owns it. OpenCode remains
// the default; Codex is attached when its app-server control socket exists.
// The operator registry is the durable record of the backend, so a restart does
// not have to guess from a session id.
type chatManager struct {
opencode chatBroker
codex chatBroker
registry operatorRegistry
mu sync.Mutex
cache map[string]string // session id -> backend
}
func NewChatManager(ctx context.Context, open chatBroker, registry operatorRegistry) *chatManager {
m := &chatManager{opencode: open, registry: registry, cache: map[string]string{}}
if codex.Available() {
client, err := codex.Open(ctx)
if err == nil {
m.codex = client
}
}
return m
}
// Close releases the owned Codex client, if any.
func (m *chatManager) Close() {
if closer, ok := m.codex.(interface{ Close() }); ok {
closer.Close()
}
}
// Backends lists the harnesses available for a new session.
func (m *chatManager) Backends() []string {
backends := []string{}
if m.opencode != nil {
backends = append(backends, "opencode")
}
if m.codex != nil {
backends = append(backends, codex.Backend)
}
sort.Strings(backends)
return backends
}
func (m *chatManager) adapter(backend string) chatBroker {
switch backend {
case "", "opencode":
return m.opencode
case codex.Backend:
return m.codex
default:
return nil
}
}
func (m *chatManager) backendFor(ctx context.Context, sessionID string) string {
m.mu.Lock()
backend := m.cache[sessionID]
m.mu.Unlock()
if backend != "" {
return backend
}
if m.registry != nil {
if row, found, err := m.registry.OperatorSession(ctx, sessionID); err == nil && found && row.Backend != "" {
m.mu.Lock()
m.cache[sessionID] = row.Backend
m.mu.Unlock()
return row.Backend
}
}
return "opencode"
}
func (m *chatManager) brokerFor(ctx context.Context, sessionID string) (chatBroker, error) {
backend := m.backendFor(ctx, sessionID)
adapter := m.adapter(backend)
if adapter == nil {
return nil, errors.New("chat backend " + backend + " is not available")
}
return adapter, nil
}
// CreateBackend creates a session on the requested harness. An empty backend
// keeps the OpenCode default.
func (m *chatManager) CreateBackend(ctx context.Context, title, directory, backend string) (protocol.ChatSession, error) {
if backend == "" {
backend = "opencode"
}
adapter := m.adapter(backend)
if adapter == nil {
return protocol.ChatSession{}, errors.New("chat backend " + backend + " is not available")
}
session, err := adapter.Create(ctx, title, directory)
if err != nil {
return protocol.ChatSession{}, err
}
session.Backend = backend
m.mu.Lock()
m.cache[session.ID] = backend
m.mu.Unlock()
return session, nil
}
func (m *chatManager) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
return m.CreateBackend(ctx, title, directory, "opencode")
}
func (m *chatManager) Prompt(ctx context.Context, sessionID, text string) error {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return err
}
return adapter.Prompt(ctx, sessionID, text)
}
func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text, messageID string) error {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return err
}
if withID, ok := adapter.(chatPromptWithMessageID); ok {
return withID.PromptWithMessageID(ctx, sessionID, text, messageID)
}
return adapter.Prompt(ctx, sessionID, text)
}
func (m *chatManager) Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return err
}
return adapter.Stream(ctx, sessionID, ready, emit)
}
func (m *chatManager) Interrupt(ctx context.Context, sessionID string) error {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return err
}
return adapter.Interrupt(ctx, sessionID)
}
func (m *chatManager) Messages(ctx context.Context, sessionID string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return protocol.ChatHistoryPage{}, err
}
return adapter.Messages(ctx, sessionID, limit, cursor)
}
func (m *chatManager) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
sessions := []protocol.ChatSession{}
seen := map[string]bool{}
for _, adapter := range []chatBroker{m.opencode, m.codex} {
if adapter == nil {
continue
}
list, err := adapter.Sessions(ctx)
if err != nil {
continue
}
for _, session := range list {
if session.ID == "" || seen[session.ID] {
continue
}
seen[session.ID] = true
sessions = append(sessions, session)
}
}
// A backend that cannot enumerate its own store still has registry rows.
// Resolve those individually so an older/restarted backend never silently
// drops a chat from the list.
if m.registry != nil {
if rows, err := m.registry.OperatorSessions(ctx); err == nil {
for _, row := range rows {
if seen[row.ID] || row.Backend == "" || row.Backend == "opencode" {
continue
}
adapter := m.adapter(row.Backend)
if adapter == nil {
continue
}
if session, found, err := adapter.Session(ctx, row.ID); err == nil && found {
seen[row.ID] = true
sessions = append(sessions, session)
}
}
}
}
return sessions, nil
}
func (m *chatManager) Session(ctx context.Context, sessionID string) (protocol.ChatSession, bool, error) {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return protocol.ChatSession{}, false, err
}
return adapter.Session(ctx, sessionID)
}
func (m *chatManager) Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error) {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return nil, err
}
if permissions, ok := adapter.(interface {
Permissions(context.Context, string) ([]protocol.ChatPermissionFrame, error)
}); ok {
return permissions.Permissions(ctx, sessionID)
}
return nil, nil
}
func (m *chatManager) Shells(ctx context.Context, sessionID string) ([]protocol.ChatShell, error) {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return nil, err
}
if shells, ok := adapter.(interface {
Shells(context.Context, string) ([]protocol.ChatShell, error)
}); ok {
return shells.Shells(ctx, sessionID)
}
return nil, nil
}
func (m *chatManager) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
adapter, err := m.brokerFor(ctx, request.SessionID)
if err != nil {
return err
}
return adapter.Reply(ctx, request)
}
func (m *chatManager) ActivateSkill(ctx context.Context, sessionID, skill string) error {
// Skill bootstrap is an OpenCode chat concept. Other harnesses return from
// create without a manager skill and must not fail the create.
if m.backendFor(ctx, sessionID) != "opencode" {
return nil
}
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return err
}
return adapter.ActivateSkill(ctx, sessionID, skill)
}
func (m *chatManager) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
adapter, err := m.brokerFor(ctx, request.SessionID)
if err != nil {
return err
}
answerer, ok := adapter.(chatAnswerer)
if !ok {
return errors.New("this chat backend cannot answer questions")
}
return answerer.Answer(ctx, request)
}
func (m *chatManager) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
adapter, err := m.brokerFor(ctx, query.SessionID)
if err != nil {
return protocol.ChatShellOutputPage{}, err
}
reader, ok := adapter.(chatShellOutputReader)
if !ok {
return protocol.ChatShellOutputPage{}, errors.New("this chat backend has no shell output")
}
return reader.ShellOutput(ctx, query)
}
func (m *chatManager) ReleaseShells(sessionID string) {
m.mu.Lock()
backend := m.cache[sessionID]
m.mu.Unlock()
adapter := m.adapter(backend)
if releaser, ok := adapter.(chatShellReleaser); ok {
releaser.ReleaseShells(sessionID)
}
}
+1 -2
View File
@@ -5,7 +5,6 @@ import (
"strings"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -25,7 +24,7 @@ func handleChatRename(ctx context.Context, request protocol.Message, registry op
return
}
rename := request.ChatRename
if rename == nil || !opencode.ValidSessionID(rename.SessionID) {
if rename == nil || !validChatSessionID(rename.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
+20 -3
View File
@@ -7,7 +7,6 @@ import (
"path/filepath"
"strings"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -72,6 +71,7 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
}
session.Directory = operator.Directory
session.Tag = operator.Tag
session.Backend = operator.Backend
session.CreatedAt = operator.CreatedAt
session.UpdatedAt = operator.UpdatedAt
// The closed state comes from the registry, so every client sees the same
@@ -107,11 +107,15 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
title := ""
directory := ""
operationID := ""
backend := "opencode"
ephemeral := false
if request.ChatCreate != nil {
title = strings.TrimSpace(request.ChatCreate.Title)
directory = strings.TrimSpace(request.ChatCreate.Directory)
operationID = strings.TrimSpace(request.ChatCreate.OperationID)
if value := strings.TrimSpace(request.ChatCreate.Backend); value != "" {
backend = value
}
ephemeral = request.ChatCreate.Ephemeral
}
// Legacy clients did not carry a durable create identity. Give each received
@@ -146,7 +150,15 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
chatCreateConflictError(request, err, write)
return
}
session, err = broker.Create(ctx, title, resolved)
if creator, ok := broker.(chatCreateBackend); ok {
session, err = creator.CreateBackend(ctx, title, resolved, backend)
} else {
if backend != "opencode" {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat backend " + backend + " is not available"})
return
}
session, err = broker.Create(ctx, title, resolved)
}
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
@@ -199,6 +211,10 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()})
return
}
if err := registry.SetOperatorSessionBackend(ctx, session.ID, backend); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was recorded but its backend could not be saved: " + err.Error()})
return
}
if err := registry.AdvanceChatCreate(ctx, operationID, "recording", "recorded"); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was recorded but durable bootstrap state could not be saved: " + err.Error()})
return
@@ -209,6 +225,7 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
}
session.Directory = resolved
session.Tag = protocol.ChatSessionTagOperator
session.Backend = backend
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. An ephemeral create has no listed row
@@ -250,7 +267,7 @@ func handleChatAdopt(ctx context.Context, request protocol.Message, broker chatB
return
}
id := strings.TrimSpace(request.ChatAdopt.SessionID)
if !opencode.ValidSessionID(id) {
if !validChatSessionID(id) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
+2 -2
View File
@@ -28,7 +28,7 @@ func handleChatShells(ctx context.Context, request protocol.Message, broker chat
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
if query == nil || !opencode.ValidSessionID(query.SessionID) {
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
@@ -50,7 +50,7 @@ func handleChatShellOutput(ctx context.Context, request protocol.Message, broker
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
if query == nil || !opencode.ValidSessionID(query.SessionID) || !validShellID(query.ShellID) || query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
if query == nil || !validChatSessionID(query.SessionID) || !validShellID(query.ShellID) || query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid bounded shell output query is required"})
return
}
+1 -2
View File
@@ -3,7 +3,6 @@ package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -20,7 +19,7 @@ func handleChatStar(ctx context.Context, request protocol.Message, registry oper
return
}
query := request.ChatQuery
if query == nil || !opencode.ValidSessionID(query.SessionID) {
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
+2 -2
View File
@@ -31,7 +31,7 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat prompt payload is required"})
return
}
if !opencode.ValidSessionID(prompt.SessionID) {
if !validChatSessionID(prompt.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
@@ -104,7 +104,7 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH
// 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) {
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
+1
View File
@@ -165,6 +165,7 @@ to it, but the server never lists it and a reload drops it.
| B2 | Pipeline list mini graph | `list_pipelines` (`shape`) | done — each summary now carries the current version's parsed graph as `shape`; the browser draws a label-free miniature from the real `layoutGraph` with terminal-free stage routes. The row shows the name, the shape and only `{N stages}`; the cryptic `id {n} · v{n} · …` line is gone. Verified at 390×844 against the live server: 9 rows, 9 miniatures, and the detail still owns the full Graph tab. Additive field; older clients ignore it. |
| B3 | Equal phone dock cells | — | done — the narrow dock is a four-cell grid (one cell per destination plus Search) with a subgrid for the tablist, so every control has the same width and height. At 390×844 the measured widths are 92/92/92/92 and the row is 48px high. The phone shell uses `100svh` so a browser toolbar cannot hide the tab row while leaving only the Connected/Settings status row visible. |
| B4 | Full-height pipeline Source | — | done — the Source block no longer caps itself at `60vh`; it is as tall as its content and the detail pane owns the scroll. Verified at 390×844: a 4386px definition sits in the full pane (656px viewport) and scrolls. |
| B13 | Codex chat backend | `chat_backends`, `chat_create.backend` | done — OpenCode stays the default. `chat_backends` lists `codex` when the Codex App Server control socket is present; New chat shows a harness choice, the selected backend is stored on the operator-session row and echoed on every session. The Codex adapter connects to the existing App Server over its Unix WebSocket, maps `thread/start`, `turn/start`, `thread/read`, item/tool events, `item/tool/requestUserInput` to the existing question card, and carries the native user-message id so optimistic and history turns reconcile. Verified live: created a Codex chat from the browser, sent a prompt, saw the streamed answer, read it back through `chat_messages`, and saw the Codex chip and title in the list. Claude is not advertised yet: its OAuth session is expired and the SDK/CLI sidecar is still to be built. |
| B12 | One detail header, optimistic sends, thinking above the bubble | — | done — every non-chat detail (pipeline, run, template) now extracts its own `#detailTitle` into a shared `.detail-head` with the same 44px chevron Back control; on phones the button and title are vertically centred, and on wide screens the back control is hidden while the title stays in the header. Chat/create already use the same control. Sending now appends the operator's optimistic user turn immediately (using the native message id OpenCode persists), so the running placeholder cannot appear before their message. While a turn runs, Send stays present beside Stop; a follow-up is queued. The reasoning/thinking block moved outside and above the answer bubble, like the tool summary below it. |
| B11 | Enter composes; live shell bars stay in place | — | done — Enter now inserts a newline (a real CDP Enter produced `first\n` and no prompt), while Ctrl/Cmd+Enter sends; a slash draft still runs its command on Enter. The chat star reserves a 26px corner in the row head, so it no longer covers Streaming/New/Idle. Background-shell frames patch the tasks bar in place instead of full-rendering the pane, keeping the composer mounted. The shell cache was bumped to v2 so an installed PWA picks up these client changes. |
| B10 | Chat titles are shared across devices | `chat_rename` | done — the rename dialog writes the title to the server's operator-session registry (`SetOperatorSessionTitle`) instead of a device-local override. `chat_sessions` already prefers that title, so a second browser opened with a fresh profile showed `Shared rename probe` without any local storage; restoring it to `New chat` did the same. Old local titles are uploaded once on the next list load and then removed. The helper now reads `This name is shared with every device.` |
+16
View File
@@ -949,3 +949,19 @@
.chat-composer-input { padding: 10px 12px; font-size: 15px; }
.chat-turn { font-size: 15px; }
}
/* Chat harness selection and the row's non-OpenCode backend chip. */
.chat-create-backends { display: flex; flex-wrap: wrap; gap: 8px; }
.chat-create-backend { padding: 6px 12px; border: 1px solid var(--border); color: var(--muted); }
.chat-create-backend.selected { border-color: var(--accent); background: var(--tint-selected); color: var(--text); }
.chat-backend-chip {
flex: 0 0 auto;
padding: 1px 6px;
border: 1px solid var(--border);
border-radius: var(--radius-pill);
color: var(--muted);
font-size: 10px;
line-height: 16px;
text-transform: uppercase;
letter-spacing: 0.04em;
}
+2 -1
View File
@@ -336,6 +336,7 @@ const state = {
chatDirectoriesLoaded: false,
chatDirectoriesError: "",
chatCreate: null,
chatBackends: ["opencode"],
};
// The app-wide run-event watch (R10), owned by the connection rather than any
@@ -1692,7 +1693,6 @@ async function applyRoute(route) {
if (!state.chatLoaded) await loadCurrentView();
if (r.kind === "chat") {
state.chatActiveId = null;
state.chatCreate = null;
renderContent();
return;
}
@@ -1710,6 +1710,7 @@ async function applyRoute(route) {
renderContent();
return;
}
state.chatCreate = null;
state.chatActiveId = r.id;
renderContent();
await openChatSession(r.id, { updateRoute: false });
+8
View File
@@ -936,6 +936,7 @@ export function defaultDirectoryChoice(choices) {
export function newChatCreateState(operationId) {
return {
directory: HOME_DIRECTORY,
backend: "opencode",
operationId: str(operationId),
creating: false,
error: "",
@@ -954,6 +955,13 @@ export function selectChatDirectory(create, choice) {
return { ...create, directory, error: "" };
}
/** Choose the harness for a new chat. */
export function selectChatBackend(create, backend) {
const value = str(backend);
if (value === "") return { ...create };
return { ...create, backend: value, error: "" };
}
/** The create failed: stop sending and keep the server's own reason in the pane. */
export function chatCreateFailed(create, message) {
return { ...create, creating: false, error: str(message) };
+2
View File
@@ -62,6 +62,7 @@ export const Protocol = Object.freeze({
CHAT_REOPEN: "chat_reopen",
CHAT_STAR: "chat_star",
CHAT_RENAME: "chat_rename",
CHAT_BACKENDS: "chat_backends",
// The shared live stream (C5). `chat_subscribe` attaches this connection to one
// session's stream (body: the session id); the server then pushes `chat_event`
// frames without a matching request id, so every client watching a session sees
@@ -116,6 +117,7 @@ export const ChatKeys = Object.freeze({
EVENT: "chat_event",
ANSWER: "chat_answer",
RENAME: "chat_rename",
BACKENDS: "chat_backends",
// The composer's payloads (C8/C9). `chat_interrupt` deliberately has no key of
// its own: its body is the same `chat_query` the other session-scoped commands
// carry (internal/protocol/chat.go ChatQuery, Chat.kt interruptRequest), so a
+13 -2
View File
@@ -234,6 +234,11 @@ export class PipelinesRepository {
return (await this.#client.call({ type: Protocol.CHAT_SESSIONS }))[ChatKeys.SESSIONS] ?? [];
}
/** The installed chat harnesses a new session can use. */
async chatBackends() {
return (await this.#client.call({ type: Protocol.CHAT_BACKENDS }))[ChatKeys.BACKENDS] ?? ["opencode"];
}
/**
* Loads a bounded chronological history page. `cursor` is the opaque
* continuation the server returned as `next_cursor`; it is passed back
@@ -469,10 +474,16 @@ export class PipelinesRepository {
* `chat_sessions` for the operator. Automated checks that drive this real page
* set it, so a run can never leave a stray "New chat" in the operator's list.
*/
async chatCreate(title, directory, operationId = newChatOperationId(), { ephemeral = false } = {}) {
async chatCreate(title, directory, operationId = newChatOperationId(), { backend = "opencode", ephemeral = false } = {}) {
const response = await this.#client.call({
type: Protocol.CHAT_CREATE,
[ChatKeys.CREATE]: { title, directory, operation_id: operationId, ...(ephemeral ? { ephemeral: true } : {}) },
[ChatKeys.CREATE]: {
title,
directory,
operation_id: operationId,
...(backend && backend !== "opencode" ? { backend } : {}),
...(ephemeral ? { ephemeral: true } : {}),
},
});
const session = response[ChatKeys.SESSION];
if (!session) {
+52 -1
View File
@@ -135,6 +135,7 @@ import {
seedChatSeen,
sessionActivity,
sessionActivityBadge,
selectChatBackend as selectChatBackendModel,
selectChatDirectory as selectChatDirectoryModel,
sessionTitle,
sessionWorkLabel,
@@ -396,6 +397,22 @@ function currentChatPosition(el) {
return { index, offset };
}
/** The installed chat harnesses, loaded when the create pane opens. */
async function loadChatBackends() {
try {
const backends = await repo.chatBackends();
if (Array.isArray(backends) && backends.length) state.chatBackends = backends;
} catch {
// Keep the OpenCode default; create reports an unavailable backend clearly.
}
renderContent();
}
function selectChatBackend(value) {
state.chatCreate = selectChatBackendModel(state.chatCreate, value);
renderContent();
}
/** The list of the server's operator sessions, narrowed by the search field. */
async function loadChatSessions(force = false) {
if (state.connection.kind !== "connected") {
@@ -490,6 +507,7 @@ function startNewChat() {
renderContent();
focusDetailHeading();
loadChatDirectories();
loadChatBackends();
}
/**
@@ -543,7 +561,9 @@ async function createNewChat() {
try {
// Not ephemeral: this is the operator's own create path (the UI smoke uses the
// same path for its one real session and closes it afterwards).
const created = await repo.chatCreate("New chat", create.directory, create.operationId);
const created = await repo.chatCreate("New chat", create.directory, create.operationId, {
backend: create.backend,
});
state.chatCreate = null;
state.chatSessions = chatCreateSucceeded(state.chatSessions, created);
await openChatSession(created.id);
@@ -1906,6 +1926,11 @@ function renderChatRow(session, duplicateTitles = new Set()) {
});
const head = h("span", { class: "row-head" });
head.append(h("span", { class: "row-title chat-row-title", text: sessionTitle(session) }));
if (session.backend && session.backend !== "opencode") {
head.append(
h("span", { class: "chat-backend-chip", text: chatBackendLabel(session.backend) }),
);
}
// Only the status word, coloured, with no dot and no operator chip. A closed
// session says so here instead of carrying a second chip.
const statusWord = session.closed ? "Closed" : badge;
@@ -1932,6 +1957,15 @@ function renderChatRow(session, duplicateTitles = new Set()) {
* order, the model note and the footer naming the value that will be sent. Every
* server string is set with textContent.
*/
function chatBackendLabel(backend) {
switch (backend) {
case "codex": return "Codex";
case "claude": return "Claude";
case "opencode": return "OpenCode";
default: return String(backend ?? "");
}
}
function renderChatCreate() {
const create = state.chatCreate;
const pane = h("div", { class: "detail chat-detail chat-create" });
@@ -1976,6 +2010,23 @@ function renderChatCreate() {
} else {
pane.append(h("div", { class: "chat-create-prompt muted", text: CHAT_CREATE_PROMPT }));
if ((state.chatBackends ?? []).length > 1) {
const harness = h("div", { class: "chat-create-backends", role: "group", "aria-label": "Chat harness" });
for (const backend of state.chatBackends) {
const active = (create.backend ?? "opencode") === backend;
harness.append(
h("button", {
class: `ghost chat-create-backend${active ? " selected" : ""}`,
type: "button",
"aria-pressed": active ? "true" : "false",
text: chatBackendLabel(backend),
onclick: () => selectChatBackend(backend),
}),
);
}
pane.append(harness);
}
const choices = directoryChoices(state.chatDirectories);
const selected =
choices.find((choice) => choice.createDirectory === create.directory) ??
+3
View File
@@ -1722,6 +1722,7 @@ test("the home row is the only one with a secondary path; recents are labelled b
test("newChatCreateState starts on home, not sending, with the caller's operation id", () => {
assert.deepEqual(newChatCreateState("web-chat-op"), {
directory: HOME_DIRECTORY,
backend: "opencode",
operationId: "web-chat-op",
creating: false,
error: "",
@@ -1733,6 +1734,7 @@ test("selectChatDirectory sends the chosen value and clears a previous refusal",
const recent = { label: "/repo/a", path: "/repo/a", home: false, createDirectory: "/repo/a", secondary: null };
assert.deepEqual(selectChatDirectory(state, recent), {
directory: "/repo/a",
backend: "opencode",
operationId: "op",
creating: false,
error: "",
@@ -1745,6 +1747,7 @@ test("chatCreateFailed keeps the pane open with the server's message; success st
const creating = { ...newChatCreateState("op"), creating: true };
assert.deepEqual(chatCreateFailed(creating, "the directory is not available"), {
directory: "~",
backend: "opencode",
operationId: "op",
creating: false,
error: "the directory is not available",