feat(chat): per-chat permission modes for Claude, Codex and OpenCode

This commit is contained in:
2026-10-24 18:16:10 +01:00
parent ef575898f2
commit 6d430948a6
29 changed files with 1512 additions and 3 deletions
+3
View File
@@ -171,6 +171,9 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
s.appliedModel = requested
s.mu.Unlock()
}
if err := s.applyMode(ctx, proc); err != nil {
return err
}
content, err := promptContent(text, files)
if err != nil {
return err
+1
View File
@@ -234,6 +234,7 @@ type session struct {
directory string
title string
model string // CLI model selection (alias or full id); "" uses the CLI default
mode string // permission mode id; "" uses the CLI's own default
createdAt int64
proc *process
+55
View File
@@ -456,3 +456,58 @@ func TestSignedOutCLIReturnsAnActionableError(t *testing.T) {
t.Fatalf("error is not actionable: %v", err)
}
}
func TestPermissionModeStartsTheCLIAndSwitchesALiveOne(t *testing.T) {
chat := testChat(t)
modeLog := filepath.Join(t.TempDir(), "modes.log")
t.Setenv("FAKE_CLAUDE_MODE_LOG", modeLog)
session := newCreatedChat(t, chat)
ctx := context.Background()
if err := chat.SetMode(ctx, session.ID, "dontAsk"); err == nil {
t.Fatal("an unlisted mode was accepted")
}
modes, err := chat.Modes(ctx, session.ID)
if err != nil || len(modes) != 5 || modes[0].ID != defaultMode || modes[3].ID != "auto" {
t.Fatalf("modes: %+v %v", modes, err)
}
if err := chat.SetMode(ctx, session.ID, "auto"); err != nil {
t.Fatal(err)
}
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(ctx, session.ID, "hello"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
entries := readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))
if argValue(entries[len(entries)-1].Args, "--permission-mode") != "auto" {
t.Fatalf("spawn did not start in the chosen mode: %+v", entries)
}
if _, err := os.Stat(modeLog); err == nil {
t.Fatal("a process started in its mode was switched again")
}
// A running CLI switches in place, without a restart.
if err := chat.SetMode(ctx, session.ID, "plan"); err != nil {
t.Fatal(err)
}
if data, _ := os.ReadFile(modeLog); strings.TrimSpace(string(data)) != "plan" {
t.Fatalf("live switch sent %q", data)
}
if count := len(readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))); count != len(entries) {
t.Fatalf("the live switch restarted the CLI: %d spawns", count)
}
// Back to the default: the flag is omitted on a fresh process.
if err := chat.SetMode(ctx, session.ID, defaultMode); err != nil {
t.Fatal(err)
}
chat.session(session.ID).closeProcess()
if err := chat.Prompt(ctx, session.ID, "again"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
entries = readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))
if argValue(entries[len(entries)-1].Args, "--permission-mode") != "" {
t.Fatalf("the default mode passed a flag: %+v", entries[len(entries)-1])
}
}
+89
View File
@@ -0,0 +1,89 @@
package claude
import (
"context"
"errors"
"fmt"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// defaultMode is Claude Code's own ask-for-permission mode. The CLI flag has no
// spelling for it, so a process in this mode is started without the flag; the
// control request accepts it by name.
const defaultMode = "default"
// chatModes are the Claude Code permission modes a chat can run in, in the
// order the CLI cycles them. dontAsk is left out: it silently denies anything
// not pre-approved, which a chat on a phone cannot recover from.
var chatModes = []protocol.ChatMode{
{ID: defaultMode, Name: "Ask for permission", Description: "Ask before edits and commands."},
{ID: "acceptEdits", Name: "Accept edits", Description: "Make file edits without asking; ask for other actions."},
{ID: "plan", Name: "Plan", Description: "Explore and plan without changing anything."},
{ID: "auto", Name: "Auto", Description: "Act without asking, with Claude Code's safety checks."},
{ID: "bypassPermissions", Name: "Bypass permissions", Description: "Never ask. Everything runs without checks."},
}
// Modes lists the permission modes a Claude chat can switch to.
func (c *Chat) Modes(context.Context, string) ([]protocol.ChatMode, error) {
return append([]protocol.ChatMode(nil), chatModes...), nil
}
func knownMode(mode string) bool {
for _, known := range chatModes {
if known.ID == mode {
return true
}
}
return false
}
// SetMode records the session's permission mode and applies it to a running
// CLI at once; a later process starts in it.
func (c *Chat) SetMode(ctx context.Context, id, mode string) error {
if !knownMode(mode) {
return fmt.Errorf("unknown Claude permission mode %q", mode)
}
s := c.session(id)
if s == nil {
meta, ok := transcriptSession(id)
if !ok {
return errors.New("unknown Claude session " + id)
}
s = c.sessionFor(id, meta.Directory)
}
s.mu.Lock()
previous := s.mode
s.mode = mode
proc := s.proc
s.mu.Unlock()
if proc == nil {
return nil
}
if err := s.applyMode(ctx, proc); err != nil {
s.mu.Lock()
s.mode = previous
s.mu.Unlock()
return err
}
return nil
}
// applyMode tells a running CLI the session's mode when it runs in another.
func (s *session) applyMode(ctx context.Context, proc *process) error {
s.mu.Lock()
requested, current := s.mode, proc.mode
s.mu.Unlock()
if requested == "" || requested == current || (current == "" && requested == defaultMode) {
return nil
}
setCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
defer cancel()
if _, err := proc.request(setCtx, "set_permission_mode", map[string]any{"mode": requested}); err != nil {
return fmt.Errorf("switch Claude permission mode: %w", err)
}
s.mu.Lock()
proc.mode = requested
s.mu.Unlock()
return nil
}
+11 -1
View File
@@ -44,6 +44,10 @@ type process struct {
exitErr error
done chan struct{}
stderrDone chan struct{}
// mode is the permission mode this process runs in, guarded by the
// session's mu: set at spawn and after a confirmed set_permission_mode.
mode string
}
type controlReply struct {
@@ -80,6 +84,12 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
if s.model != "" {
args = append(args, "--model", s.model)
}
s.mu.Lock()
mode := s.mode
s.mu.Unlock()
if mode != "" && mode != defaultMode {
args = append(args, "--permission-mode", mode)
}
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
cmd.Dir = s.directory
cmd.Env = s.chat.auth.resolve(s.chat.ctx, s.chat.binary, withServiceToken(os.Environ()))
@@ -99,7 +109,7 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start Claude Code: %w", err)
}
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{})}
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{}), mode: mode}
go p.readStderr(stderr)
go p.readStdout(stdout)
go p.wait()
+8 -1
View File
@@ -2,7 +2,8 @@
"""Deterministic stand-in for the Claude Code CLI's SDK stdio protocol.
It implements only what Pipelines' adapter uses: initialize, stream-json turns,
can_use_tool approvals, AskUserQuestion, set_model, interrupt, usage queries and
can_use_tool approvals, AskUserQuestion, set_model, set_permission_mode,
interrupt, usage queries and
a session transcript. It never contacts a provider.
"""
import json
@@ -157,6 +158,12 @@ def handle(line):
elif subtype == "set_model":
state["model"] = request.get("model")
respond(value.get("request_id"), {"model": request.get("model")})
elif subtype == "set_permission_mode":
mode_log = os.environ.get("FAKE_CLAUDE_MODE_LOG")
if mode_log:
with open(mode_log, "a", encoding="utf-8") as log:
log.write(request.get("mode", "") + "\n")
respond(value.get("request_id"), {"mode": request.get("mode")})
elif subtype == "interrupt":
respond(value.get("request_id"), {"still_queued": [], "cancelled": []})
if state["pending"]:
+2
View File
@@ -67,6 +67,7 @@ type Chat struct {
endedTurns map[string]string
usage map[string]usageSnapshot
usageOrder uint64
modes map[string]string
}
type pendingForm struct {
@@ -407,6 +408,7 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
if model != "" {
params["model"] = model
}
c.applyMode(id, params)
c.mu.Lock()
if c.starting == nil {
c.starting = map[string]bool{}
+69
View File
@@ -0,0 +1,69 @@
package codex
import (
"context"
"fmt"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// codexMode is one approval/sandbox preset, applied as turn/start overrides
// that Codex keeps for the thread's later turns too.
type codexMode struct {
protocol.ChatMode
approval string
sandbox string
}
// The presets mirror Codex's own: ask in the workspace sandbox (the thread
// default chats start with), act without asking inside it, or full access.
var codexModes = []codexMode{
{protocol.ChatMode{ID: "ask", Name: "Ask for approval", Description: "Work in the project sandbox and ask when an action needs more."}, "on-request", "workspaceWrite"},
{protocol.ChatMode{ID: "auto", Name: "Auto", Description: "Work in the project sandbox without asking."}, "never", "workspaceWrite"},
{protocol.ChatMode{ID: "full", Name: "Full access", Description: "No sandbox and no approvals. Everything runs."}, "never", "dangerFullAccess"},
}
// Modes lists the approval/sandbox presets a Codex chat can switch to.
func (c *Chat) Modes(context.Context, string) ([]protocol.ChatMode, error) {
modes := make([]protocol.ChatMode, len(codexModes))
for index, mode := range codexModes {
modes[index] = mode.ChatMode
}
return modes, nil
}
// SetMode records the thread's preset; it is sent with the next turn/start.
func (c *Chat) SetMode(_ context.Context, id, mode string) error {
if _, ok := codexModeFor(mode); !ok {
return fmt.Errorf("unknown Codex mode %q", mode)
}
c.mu.Lock()
defer c.mu.Unlock()
if c.modes == nil {
c.modes = map[string]string{}
}
c.modes[id] = mode
return nil
}
func codexModeFor(id string) (codexMode, bool) {
for _, mode := range codexModes {
if mode.ID == id {
return mode, true
}
}
return codexMode{}, false
}
// applyMode adds the thread's preset to turn/start params, if one was chosen.
func (c *Chat) applyMode(id string, params map[string]any) {
c.mu.Lock()
chosen := c.modes[id]
c.mu.Unlock()
mode, ok := codexModeFor(chosen)
if !ok {
return
}
params["approvalPolicy"] = mode.approval
params["sandboxPolicy"] = map[string]any{"type": mode.sandbox}
}
+59
View File
@@ -0,0 +1,59 @@
package codex
import (
"context"
"encoding/json"
"sync"
"testing"
)
func TestModePresetRidesOnTheNextTurn(t *testing.T) {
var mu sync.Mutex
var turns []map[string]any
chat := modelTestChat(t, func(method string, raw json.RawMessage) any {
if method != "turn/start" {
t.Errorf("unexpected operation: %s", method)
return map[string]any{}
}
var params map[string]any
_ = json.Unmarshal(raw, &params)
mu.Lock()
turns = append(turns, params)
mu.Unlock()
return json.RawMessage(`{"turn":{"id":"turn-fixture","status":"inProgress","items":[]}}`)
})
ctx := context.Background()
if err := chat.SetMode(ctx, fixtureThread, "yolo"); err == nil {
t.Fatal("an unlisted mode was accepted")
}
if err := chat.Prompt(ctx, fixtureThread, "plain"); err != nil {
t.Fatal(err)
}
if err := chat.SetMode(ctx, fixtureThread, "auto"); err != nil {
t.Fatal(err)
}
if err := chat.Prompt(ctx, fixtureThread, "auto"); err != nil {
t.Fatal(err)
}
if err := chat.SetMode(ctx, fixtureThread, "full"); err != nil {
t.Fatal(err)
}
if err := chat.Prompt(ctx, fixtureThread, "full"); err != nil {
t.Fatal(err)
}
mu.Lock()
defer mu.Unlock()
if len(turns) != 3 {
t.Fatalf("turns = %d", len(turns))
}
if turns[0]["approvalPolicy"] != nil || turns[0]["sandboxPolicy"] != nil {
t.Fatalf("no mode chosen, yet overrides were sent: %v", turns[0])
}
sandbox := func(turn map[string]any) any { return turn["sandboxPolicy"].(map[string]any)["type"] }
if turns[1]["approvalPolicy"] != "never" || sandbox(turns[1]) != "workspaceWrite" {
t.Fatalf("auto turn = %v", turns[1])
}
if turns[2]["approvalPolicy"] != "never" || sandbox(turns[2]) != "dangerFullAccess" {
t.Fatalf("full turn = %v", turns[2])
}
}
+5
View File
@@ -45,6 +45,8 @@ type Chat struct {
mu sync.Mutex
usageMu sync.Mutex
usageModels map[string]usageModelCache
modeMu sync.Mutex
agents map[string]string
}
// NewChat brokers chat for one owned OpenCode endpoint. The connection must be
@@ -131,6 +133,9 @@ func (c *Chat) PromptWithMessageIDFiles(ctx context.Context, id, text, messageID
if messageID != "" {
body["id"] = messageID
}
if agent := c.agentFor(id); agent != "" {
body["agent"] = agent
}
if len(files) > 0 {
attachments := make([]map[string]string, 0, len(files))
for _, file := range files {
+44
View File
@@ -0,0 +1,44 @@
package opencode
import (
"context"
"fmt"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatModes are OpenCode's two primary agents. What each may do without asking
// is the agent's own permission configuration; Pipelines only picks the agent.
var chatModes = []protocol.ChatMode{
{ID: "build", Name: "Build", Description: "OpenCode's default agent: edits and runs commands under its permission settings."},
{ID: "plan", Name: "Plan", Description: "Analyse and plan; edits and commands are restricted."},
}
// Modes lists the agents an OpenCode chat can switch to.
func (c *Chat) Modes(context.Context, string) ([]protocol.ChatMode, error) {
return append([]protocol.ChatMode(nil), chatModes...), nil
}
// SetMode records the session's agent; every later prompt names it.
func (c *Chat) SetMode(_ context.Context, id, mode string) error {
known := false
for _, candidate := range chatModes {
known = known || candidate.ID == mode
}
if !known {
return fmt.Errorf("unknown OpenCode agent %q", mode)
}
c.modeMu.Lock()
defer c.modeMu.Unlock()
if c.agents == nil {
c.agents = map[string]string{}
}
c.agents[id] = mode
return nil
}
func (c *Chat) agentFor(id string) string {
c.modeMu.Lock()
defer c.modeMu.Unlock()
return c.agents[id]
}
+45
View File
@@ -0,0 +1,45 @@
package opencode
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestChosenAgentRidesOnEveryPrompt(t *testing.T) {
for _, backend := range []string{"v2", "v1"} {
t.Run(backend, func(t *testing.T) {
var bodies []map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var body map[string]any
_ = json.Unmarshal(raw, &body)
bodies = append(bodies, body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`))
}))
defer srv.Close()
conn := &Connection{Backend: backend, URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}}
chat := NewChat(conn)
ctx := context.Background()
if err := chat.SetMode(ctx, "ses_1", "auto"); err == nil {
t.Fatal("an unknown agent was accepted")
}
if err := chat.Prompt(ctx, "ses_1", "before"); err != nil {
t.Fatal(err)
}
if err := chat.SetMode(ctx, "ses_1", "plan"); err != nil {
t.Fatal(err)
}
if err := chat.Prompt(ctx, "ses_1", "after"); err != nil {
t.Fatal(err)
}
if len(bodies) != 2 || bodies[0]["agent"] != nil || bodies[1]["agent"] != "plan" {
t.Fatalf("prompt bodies = %v", bodies)
}
})
}
}
+4
View File
@@ -199,6 +199,7 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
Prompt string `json:"prompt"`
Text string `json:"text"`
ID string `json:"id"`
Agent string `json:"agent"`
Format json.RawMessage `json:"format"`
Parts []struct {
Text string `json:"text"`
@@ -226,6 +227,9 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
if request.ID != "" {
payload["id"] = request.ID
}
if request.Agent != "" {
payload["agent"] = request.Agent
}
if len(request.Format) > 0 {
supported, err := c.supportsFormat(ctx, request.Format)
if err != nil {
+58
View File
@@ -0,0 +1,58 @@
package pipeline
import (
"context"
"database/sql"
"path/filepath"
"testing"
)
func TestOperatorChatModeMigratesAndPersists(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "old.db")
db, err := sql.Open("sqlite", path)
if err != nil {
t.Fatal(err)
}
_, err = db.Exec(`CREATE TABLE operator_sessions (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)`)
if err != nil {
t.Fatal(err)
}
db.Close()
store, err := Open(path)
if err != nil {
t.Fatal(err)
}
if err := store.RecordOperatorSession(ctx, "chat", "/fixture", "title", "operator"); err != nil {
t.Fatal(err)
}
if mode, err := store.ChatMode(ctx, "chat"); err != nil || mode != "" {
t.Fatalf("fresh mode %q: %v", mode, err)
}
if err := store.SetChatMode(ctx, "missing", "auto"); err == nil {
t.Fatal("unregistered chat accepted a mode")
}
before, _, err := store.OperatorSession(ctx, "chat")
if err != nil {
t.Fatal(err)
}
if err := store.SetChatMode(ctx, "chat", "auto"); err != nil {
t.Fatal(err)
}
store.Close()
store, err = Open(path)
if err != nil {
t.Fatal(err)
}
defer store.Close()
if mode, err := store.ChatMode(ctx, "chat"); err != nil || mode != "auto" {
t.Fatalf("restored mode %q: %v", mode, err)
}
if mode, err := store.ChatMode(ctx, "missing"); err != nil || mode != "" {
t.Fatalf("missing chat mode %q: %v", mode, err)
}
after, _, err := store.OperatorSession(ctx, "chat")
if err != nil || before.UpdatedAt != after.UpdatedAt {
t.Fatal("mode changed recency", err)
}
}
+29 -1
View File
@@ -139,7 +139,7 @@ func (s *Store) AdvanceChatCreate(ctx context.Context, requestID, from, to strin
// row valid and open (0), so an upgrade is idempotent across repeated Open calls
// and no session is silently reported as closed.
func (s *Store) migrateOperatorSessions() error {
for _, column := range []string{"chat_model", "chat_model_provider"} {
for _, column := range []string{"chat_model", "chat_model_provider", "chat_mode"} {
if err := s.addColumnIfMissing("operator_sessions", column, "TEXT NOT NULL DEFAULT ''"); err != nil {
return err
}
@@ -183,6 +183,34 @@ func (s *Store) SetChatModelSelection(ctx context.Context, id, provider, model s
return nil
}
// SetChatMode stores one operator chat's permission mode. The harness validates
// the mode id; this only records it for later turns and restarts.
func (s *Store) SetChatMode(ctx context.Context, id, mode string) error {
result, err := s.db.ExecContext(ctx, `UPDATE operator_sessions SET chat_mode=? WHERE session_id=? AND tag<>''`, mode, id)
if err != nil {
return err
}
count, err := result.RowsAffected()
if err != nil {
return err
}
if count != 1 {
return errors.New("a mode can only be set on a registered operator chat")
}
return nil
}
// ChatMode reads one operator chat's stored mode without touching recency; ""
// when none was chosen or the session is not an operator chat.
func (s *Store) ChatMode(ctx context.Context, id string) (string, error) {
var mode string
err := s.db.QueryRowContext(ctx, `SELECT chat_mode FROM operator_sessions WHERE session_id=? AND tag<>''`, id).Scan(&mode)
if errors.Is(err, sql.ErrNoRows) {
return "", nil
}
return mode, err
}
// ChatModelSelection reads a durable next-turn choice without touching recency.
func (s *Store) ChatModelSelection(ctx context.Context, id string) (provider, model string, err error) {
err = s.db.QueryRowContext(ctx, `SELECT chat_model_provider,chat_model FROM operator_sessions WHERE session_id=? AND backend IN ('codex','claude') AND tag<>''`, id).Scan(&provider, &model)
+26
View File
@@ -51,6 +51,13 @@ const (
ChatModels = "chat_models"
// ChatModelSelect switches one session's model for subsequent turns.
ChatModelSelect = "chat_model"
// ChatModes lists the permission modes the chat's harness offers (Claude
// Code's permission modes, Codex approval/sandbox presets, OpenCode agents);
// its request body is ChatQuery and the reply also carries the current mode.
ChatModes = "chat_modes"
// ChatModeSelect switches one session's mode. The choice is stored with the
// operator session and applied now and before every later turn.
ChatModeSelect = "chat_mode"
// 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.
@@ -169,6 +176,19 @@ type ChatModel struct {
Name string `json:"name,omitempty"`
}
// ChatMode is one permission mode a chat harness offers.
type ChatMode struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
// ChatModeRequest switches one session's mode; the reply echoes the stored mode.
type ChatModeRequest struct {
SessionID string `json:"session_id"`
Mode string `json:"mode"`
}
// ChatModelRequest switches the model for one session's subsequent turns.
type ChatModelRequest struct {
// Selection is reply-only: next_turn means a durable local override was saved.
@@ -186,6 +206,12 @@ type ChatSession struct {
// ModelSelection == next_turn denotes a durable Pipelines override, not an
// acknowledgement that a remote thread's current configuration changed.
ModelSelection string `json:"model_selection,omitempty"`
// Mode is the stored permission mode (a ChatMode id); empty is the
// harness's own default.
Mode string `json:"mode,omitempty"`
// ModeName is Mode's display name. With no stored mode both name the
// harness default, so a client can show the mode without a chat_modes read.
ModeName string `json:"mode_name,omitempty"`
// InstructionStatus is the observed create-time preload outcome: applied,
// unsupported, failed, or not_requested. Ordinary list rows omit it.
InstructionStatus string `json:"instruction_status,omitempty"`
+5
View File
@@ -210,6 +210,11 @@ type Message struct {
ChatModels []ChatModel `json:"chat_models,omitempty"`
// ModelRequest is the chat_model body and echoed selection.
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
// ChatModes is the chat_modes reply: the permission modes the session's
// harness offers, with the session's current mode in ModeRequest.
ChatModes []ChatMode `json:"chat_modes,omitempty"`
// ModeRequest is the chat_mode body and echoed selection.
ModeRequest *ChatModeRequest `json:"chat_mode,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
+6
View File
@@ -203,6 +203,12 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatModelSelect:
handleChatModelSwitch(ctx, request, broker, write)
return true
case protocol.ChatModes:
handleChatModes(ctx, request, broker, write)
return true
case protocol.ChatModeSelect:
handleChatModeSwitch(ctx, request, broker, write)
return true
case protocol.ChatShells:
handleChatShells(ctx, request, broker, registry, write)
return true
+7
View File
@@ -179,6 +179,9 @@ func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text,
if err != nil {
return err
}
if err := m.applyStoredMode(ctx, adapter, sessionID); err != nil {
return err
}
if isModelBackend(m.backendFor(ctx, sessionID)) {
model, err := m.promptModel(ctx, adapter, sessionID)
if err != nil {
@@ -231,6 +234,9 @@ func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, t
if err != nil {
return err
}
if err := m.applyStoredMode(ctx, adapter, sessionID); err != nil {
return err
}
if isModelBackend(m.backendFor(ctx, sessionID)) {
model, err := m.promptModel(ctx, adapter, sessionID)
if err != nil {
@@ -349,6 +355,7 @@ func (m *chatManager) chatModelSelection(ctx context.Context, id string) (string
}
func (m *chatManager) withModelSelection(ctx context.Context, session protocol.ChatSession) (protocol.ChatSession, error) {
session = m.withMode(ctx, session)
if !isModelBackend(session.Backend) {
return session, nil
}
+158
View File
@@ -0,0 +1,158 @@
package server
import (
"context"
"errors"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatModer is the optional permission-mode surface of a chat harness.
type chatModer interface {
Modes(ctx context.Context, sessionID string) ([]protocol.ChatMode, error)
SetMode(ctx context.Context, sessionID, mode string) error
}
// chatModeRegistry stores each operator chat's chosen mode.
type chatModeRegistry interface {
SetChatMode(ctx context.Context, id, mode string) error
ChatMode(ctx context.Context, id string) (string, error)
}
var errChatModesUnsupported = errors.New("this chat harness does not support changing modes")
// Modes lists the modes the session's harness offers.
func (m *chatManager) Modes(ctx context.Context, sessionID string) ([]protocol.ChatMode, error) {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return nil, err
}
moder, ok := adapter.(chatModer)
if !ok {
return nil, errChatModesUnsupported
}
return moder.Modes(ctx, sessionID)
}
// SetMode applies a mode to the harness now and stores it, so it survives a
// restart and is re-applied before every later turn.
func (m *chatManager) SetMode(ctx context.Context, sessionID, mode string) error {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return err
}
moder, ok := adapter.(chatModer)
if !ok {
return errChatModesUnsupported
}
registry, ok := m.registry.(chatModeRegistry)
if !ok {
return errors.New("durable chat modes are not configured")
}
if err := moder.SetMode(ctx, sessionID, mode); err != nil {
return err
}
return registry.SetChatMode(ctx, sessionID, mode)
}
// CurrentMode is the session's stored mode, "" for the harness default.
func (m *chatManager) CurrentMode(ctx context.Context, sessionID string) string {
registry, ok := m.registry.(chatModeRegistry)
if !ok {
return ""
}
mode, err := registry.ChatMode(ctx, sessionID)
if err != nil {
return ""
}
return mode
}
// withMode names the session's mode on a listed row: the stored mode, else the
// harness default (listed first). A harness without modes leaves both empty.
func (m *chatManager) withMode(ctx context.Context, session protocol.ChatSession) protocol.ChatSession {
moder, ok := m.adapter(session.Backend).(chatModer)
if !ok {
return session
}
modes, err := moder.Modes(ctx, session.ID)
if err != nil || len(modes) == 0 {
return session
}
stored := m.CurrentMode(ctx, session.ID)
chosen := modes[0]
for _, mode := range modes {
if mode.ID == stored {
chosen = mode
}
}
session.Mode, session.ModeName = chosen.ID, chosen.Name
return session
}
// applyStoredMode hands the stored mode to the harness before a turn. Adapters
// treat a repeat as a no-op, and this covers a server restart that lost the
// adapter's in-memory choice.
func (m *chatManager) applyStoredMode(ctx context.Context, adapter chatBroker, sessionID string) error {
moder, ok := adapter.(chatModer)
if !ok {
return nil
}
mode := m.CurrentMode(ctx, sessionID)
if mode == "" {
return nil
}
return moder.SetMode(ctx, sessionID, mode)
}
// handleChatModes lists a session's modes and reports the current one.
func handleChatModes(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
query := request.ChatQuery
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
return
}
moder, ok := broker.(chatModer)
if !ok {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: errChatModesUnsupported.Error()})
return
}
modes, err := moder.Modes(ctx, query.SessionID)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
current := protocol.ChatModeRequest{SessionID: query.SessionID}
if reporter, ok := broker.(interface {
CurrentMode(context.Context, string) string
}); ok {
current.Mode = reporter.CurrentMode(ctx, query.SessionID)
}
_ = write(protocol.Message{Type: protocol.ChatModes, ID: request.ID, ChatModes: modes, ModeRequest: &current})
}
// handleChatModeSwitch changes one session's mode and echoes the stored mode.
func handleChatModeSwitch(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
body := request.ModeRequest
if body == nil || !validChatSessionID(body.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
return
}
mode := strings.TrimSpace(body.Mode)
if mode == "" {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a mode is required"})
return
}
moder, ok := broker.(chatModer)
if !ok {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: errChatModesUnsupported.Error()})
return
}
if err := moder.SetMode(ctx, body.SessionID, mode); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
reply := protocol.ChatModeRequest{SessionID: body.SessionID, Mode: mode}
_ = write(protocol.Message{Type: protocol.ChatModeSelect, ID: request.ID, ModeRequest: &reply})
}
+102
View File
@@ -0,0 +1,102 @@
package server
import (
"context"
"errors"
"path/filepath"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// modedChat records the modes the manager hands to the harness.
type modedChat struct {
*fakeChat
applied []string
}
func (c *modedChat) Modes(context.Context, string) ([]protocol.ChatMode, error) {
return []protocol.ChatMode{{ID: "default", Name: "Ask"}, {ID: "auto", Name: "Auto"}}, nil
}
func (c *modedChat) SetMode(_ context.Context, _, mode string) error {
if mode != "default" && mode != "auto" {
return errors.New("unknown mode " + mode)
}
c.applied = append(c.applied, mode)
return nil
}
func TestChatModeIsStoredAppliedAndSurvivesRestart(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "chat.db")
store, err := pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
id := "01900000-0000-7000-8000-000000000002"
if err := store.RecordOperatorSession(ctx, id, "/fixture", "chat", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if err := store.SetOperatorSessionBackend(ctx, id, "claude"); err != nil {
t.Fatal(err)
}
fake := &modedChat{fakeChat: scriptedChat()}
fake.sessionRecord = protocol.ChatSession{ID: id, Backend: "claude"}
fake.sessionFound = true
fake.sessions = []protocol.ChatSession{fake.sessionRecord}
manager := &chatManager{claude: fake, registry: store, cache: map[string]string{}}
var reply protocol.Message
capture := func(msg protocol.Message) error { reply = msg; return nil }
if session, _, err := manager.Session(ctx, id); err != nil || session.Mode != "default" || session.ModeName != "Ask" {
t.Fatalf("fresh session names %q/%q, want the harness default: %v", session.Mode, session.ModeName, err)
}
handleChatModes(ctx, protocol.Message{ID: "list", ChatQuery: &protocol.ChatQuery{SessionID: id}}, manager, capture)
if reply.Type != protocol.ChatModes || len(reply.ChatModes) != 2 || reply.ModeRequest == nil || reply.ModeRequest.Mode != "" {
t.Fatalf("modes reply = %+v", reply)
}
handleChatModeSwitch(ctx, protocol.Message{ID: "bad", ModeRequest: &protocol.ChatModeRequest{SessionID: id, Mode: "yolo"}}, manager, capture)
if reply.Type != protocol.Error {
t.Fatalf("unknown mode accepted: %+v", reply)
}
handleChatModeSwitch(ctx, protocol.Message{ID: "auto", ModeRequest: &protocol.ChatModeRequest{SessionID: id, Mode: "auto"}}, manager, capture)
if reply.Type != protocol.ChatModeSelect || reply.ModeRequest.Mode != "auto" || len(fake.applied) != 1 {
t.Fatalf("switch reply = %+v, applied %v", reply, fake.applied)
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
store, err = pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
defer store.Close()
// A restarted server forgot the harness state; the stored mode is listed and
// re-applied before the next turn.
fake.applied = nil
manager = &chatManager{claude: fake, registry: store, cache: map[string]string{}}
session, found, err := manager.Session(ctx, id)
if err != nil || !found || session.Mode != "auto" || session.ModeName != "Auto" {
t.Fatalf("restarted session = %+v, %v", session, err)
}
list, err := manager.Sessions(ctx)
if err != nil || len(list) != 1 || list[0].Mode != "auto" {
t.Fatalf("restarted list = %+v, %v", list, err)
}
handleChatModes(ctx, protocol.Message{ID: "again", ChatQuery: &protocol.ChatQuery{SessionID: id}}, manager, capture)
if reply.ModeRequest == nil || reply.ModeRequest.Mode != "auto" {
t.Fatalf("current mode after restart = %+v", reply)
}
if err := manager.Prompt(ctx, id, "hello"); err != nil {
t.Fatal(err)
}
if err := manager.PromptWithMessageIDFiles(ctx, id, "again", "msg", nil); err != nil {
t.Fatal(err)
}
if len(fake.applied) != 2 || fake.applied[0] != "auto" || fake.applied[1] != "auto" {
t.Fatalf("stored mode not re-applied before turns: %v", fake.applied)
}
}