feat(chat): persist safe Codex next-turn model selection
This commit is contained in:
+28
-8
@@ -317,6 +317,12 @@ func (c *Chat) Prompt(ctx context.Context, id, text string) error {
|
||||
// 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 {
|
||||
return c.PromptWithMessageIDModel(ctx, id, text, messageID, "")
|
||||
}
|
||||
|
||||
// PromptWithMessageIDModel applies a persisted per-chat choice at the explicit
|
||||
// next-turn boundary. It does not resume a thread or edit global configuration.
|
||||
func (c *Chat) PromptWithMessageIDModel(ctx context.Context, id, text, messageID, model string) error {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return errors.New("empty chat prompt")
|
||||
}
|
||||
@@ -327,6 +333,9 @@ func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID stri
|
||||
if messageID != "" {
|
||||
params["clientUserMessageId"] = messageID
|
||||
}
|
||||
if model != "" {
|
||||
params["model"] = model
|
||||
}
|
||||
_, err := c.call(ctx, "turn/start", params)
|
||||
return err
|
||||
}
|
||||
@@ -379,12 +388,20 @@ func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.Ch
|
||||
return protocol.ChatSession{}, err
|
||||
}
|
||||
var result struct {
|
||||
Thread thread `json:"thread"`
|
||||
Thread thread `json:"thread"`
|
||||
Model string `json:"model"`
|
||||
ModelProvider string `json:"modelProvider"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return protocol.ChatSession{}, err
|
||||
}
|
||||
session := result.Thread.chatSession()
|
||||
if session.Model == "" {
|
||||
session.Model = result.Model
|
||||
}
|
||||
if session.ModelProvider == "" {
|
||||
session.ModelProvider = result.ModelProvider
|
||||
}
|
||||
session.Backend = Backend
|
||||
if strings.TrimSpace(title) != "" {
|
||||
session.Title = strings.TrimSpace(title)
|
||||
@@ -697,13 +714,15 @@ func stepFrame(threadID, status string) protocol.ChatEventFrame {
|
||||
}
|
||||
|
||||
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"`
|
||||
Model string `json:"model"`
|
||||
ModelProvider string `json:"modelProvider"`
|
||||
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 {
|
||||
@@ -731,6 +750,7 @@ func (t thread) chatSession() protocol.ChatSession {
|
||||
}
|
||||
return protocol.ChatSession{
|
||||
ID: t.ID, Title: title, Directory: t.Cwd,
|
||||
Model: t.Model, ModelProvider: t.ModelProvider,
|
||||
CreatedAt: t.CreatedAt * 1000, UpdatedAt: t.UpdatedAt * 1000,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Models uses the thread's actual provider and the account's paginated catalog.
|
||||
// Model.model, not the catalog row's opaque id, is the turn/start override.
|
||||
func (c *Chat) Models(ctx context.Context, id string) ([]protocol.ChatModel, error) {
|
||||
session, found, err := c.Session(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found || session.ModelProvider == "" {
|
||||
return nil, errors.New("Codex thread model provider is unavailable")
|
||||
}
|
||||
models := []protocol.ChatModel{}
|
||||
cursor := ""
|
||||
seen := map[string]bool{}
|
||||
for page := 0; page < 20; page++ {
|
||||
params := map[string]any{"limit": 100, "includeHidden": false}
|
||||
if cursor != "" {
|
||||
params["cursor"] = cursor
|
||||
}
|
||||
raw, err := c.call(ctx, "model/list", params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response struct {
|
||||
Data *[]struct {
|
||||
Model string `json:"model"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Hidden bool `json:"hidden"`
|
||||
} `json:"data"`
|
||||
NextCursor *string `json:"nextCursor"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &response); err != nil || response.Data == nil {
|
||||
return nil, errors.New("invalid Codex model catalog")
|
||||
}
|
||||
for _, model := range *response.Data {
|
||||
if model.Model != "" && !model.Hidden {
|
||||
models = append(models, protocol.ChatModel{ID: model.Model, Provider: session.ModelProvider, Name: model.DisplayName})
|
||||
}
|
||||
}
|
||||
if response.NextCursor == nil || *response.NextCursor == "" {
|
||||
return models, nil
|
||||
}
|
||||
cursor = *response.NextCursor
|
||||
if seen[cursor] {
|
||||
return nil, errors.New("Codex model catalog repeated its cursor")
|
||||
}
|
||||
seen[cursor] = true
|
||||
}
|
||||
return nil, errors.New("Codex model catalog exceeds pagination limit")
|
||||
}
|
||||
|
||||
// SwitchModel validates a selection only. Pipelines persists it before replying
|
||||
// and supplies it to the next explicit turn/start. Never use thread/resume here:
|
||||
// resumption may start a queued goal and is not a safe settings operation.
|
||||
func (c *Chat) SwitchModel(ctx context.Context, id, provider, model string) error {
|
||||
models, err := c.Models(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, available := range models {
|
||||
if available.ID == model && available.Provider == provider {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("the selected Codex model is not available for this thread's provider")
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
)
|
||||
|
||||
const fixtureThread = "01900000-0000-7000-8000-000000000001"
|
||||
|
||||
func modelFixture(t *testing.T, name string) json.RawMessage {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile("testdata/" + name + ".json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func modelTestChat(t *testing.T, handle func(string, json.RawMessage) any) *Chat {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
for {
|
||||
var req rpcMessage
|
||||
if err := wsjson.Read(ctx, conn, &req); err != nil {
|
||||
return
|
||||
}
|
||||
result := handle(req.Method, req.Params)
|
||||
if err := wsjson.Write(ctx, conn, map[string]any{"id": req.ID, "result": result}); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}))
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := &Chat{conn: conn, ctx: ctx, 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()
|
||||
t.Cleanup(func() { c.Close(); srv.Close() })
|
||||
return c
|
||||
}
|
||||
|
||||
func TestModelCatalogAndSelectionNeverResume(t *testing.T) {
|
||||
thread, catalog := modelFixture(t, "thread-read"), modelFixture(t, "model-list")
|
||||
var mu sync.Mutex
|
||||
methods := []string{}
|
||||
chat := modelTestChat(t, func(method string, raw json.RawMessage) any {
|
||||
mu.Lock()
|
||||
methods = append(methods, method)
|
||||
mu.Unlock()
|
||||
var params map[string]any
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
switch method {
|
||||
case "thread/read":
|
||||
if params["threadId"] != fixtureThread || params["includeTurns"] != nil {
|
||||
t.Errorf("thread read params = %s", raw)
|
||||
}
|
||||
return thread
|
||||
case "model/list":
|
||||
if params["includeHidden"] != false || params["limit"] != float64(100) {
|
||||
t.Errorf("catalog params = %s", raw)
|
||||
}
|
||||
if params["cursor"] == nil {
|
||||
return catalog
|
||||
}
|
||||
if params["cursor"] != "page-two" {
|
||||
t.Errorf("cursor = %v", params["cursor"])
|
||||
}
|
||||
return json.RawMessage(`{"data":[{"id":"hidden","model":"fixture-hidden","displayName":"Hidden","hidden":true}],"nextCursor":null}`)
|
||||
case "turn/start":
|
||||
if params["model"] != "fixture-model" || params["threadId"] != fixtureThread || params["clientUserMessageId"] != "msg_fixture" {
|
||||
t.Errorf("turn params = %s", raw)
|
||||
}
|
||||
if params["modelProvider"] != nil {
|
||||
t.Error("turn/start does not accept a provider override")
|
||||
}
|
||||
return json.RawMessage(`{"turn":{"id":"turn-fixture","status":"inProgress","items":[]}}`)
|
||||
default:
|
||||
t.Errorf("unexpected/unsafe model operation: %s", method)
|
||||
return map[string]any{}
|
||||
}
|
||||
})
|
||||
ctx := context.Background()
|
||||
session, found, err := chat.Session(ctx, fixtureThread)
|
||||
if err != nil || !found || session.Model != "fixture-current" || session.ModelProvider != "fixture-provider" {
|
||||
t.Fatalf("session = %+v, %v", session, err)
|
||||
}
|
||||
models, err := chat.Models(ctx, fixtureThread)
|
||||
if err != nil || len(models) != 1 || models[0].ID != "fixture-model" || models[0].Provider != "fixture-provider" {
|
||||
t.Fatalf("catalog = %+v, %v", models, err)
|
||||
}
|
||||
if err := chat.SwitchModel(ctx, fixtureThread, "fixture-provider", "fixture-model"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, pair := range [][2]string{{"wrong-provider", "fixture-model"}, {"fixture-provider", "opaque-picker-id"}, {"fixture-provider", "fixture-hidden"}} {
|
||||
if err := chat.SwitchModel(ctx, fixtureThread, pair[0], pair[1]); err == nil {
|
||||
t.Fatalf("invalid selection accepted: %v", pair)
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
for _, method := range methods {
|
||||
if method != "thread/read" && method != "model/list" {
|
||||
t.Errorf("selection invoked %s", method)
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
if err := chat.PromptWithMessageIDModel(ctx, fixtureThread, "hello", "msg_fixture", "fixture-model"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelCatalogFailsClosed(t *testing.T) {
|
||||
for _, name := range []string{"missing-provider", "invalid-data", "repeated-cursor"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
thread := modelFixture(t, "thread-read")
|
||||
chat := modelTestChat(t, func(method string, _ json.RawMessage) any {
|
||||
switch method {
|
||||
case "thread/read":
|
||||
if name == "missing-provider" {
|
||||
return json.RawMessage(`{"thread":{"id":"fixture-thread","model":null}}`)
|
||||
}
|
||||
return thread
|
||||
case "model/list":
|
||||
if name == "missing-provider" {
|
||||
t.Error("catalog requested with unknown provider")
|
||||
}
|
||||
if name == "repeated-cursor" {
|
||||
return json.RawMessage(`{"data":[],"nextCursor":"same"}`)
|
||||
}
|
||||
return json.RawMessage(`{"data":null,"nextCursor":null}`)
|
||||
default:
|
||||
t.Errorf("unsafe method %s", method)
|
||||
return nil
|
||||
}
|
||||
})
|
||||
if _, err := chat.Models(context.Background(), fixtureThread); err == nil {
|
||||
t.Fatal("invalid catalog accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelMetadataFromThreadStartAndList(t *testing.T) {
|
||||
thread := modelFixture(t, "thread-read")
|
||||
chat := modelTestChat(t, func(method string, _ json.RawMessage) any {
|
||||
switch method {
|
||||
case "thread/start":
|
||||
return json.RawMessage(`{"thread":{"id":"fixture-thread","model":null,"modelProvider":""},"model":"fixture-start","modelProvider":"fixture-provider"}`)
|
||||
case "thread/list":
|
||||
var result struct {
|
||||
Thread json.RawMessage `json:"thread"`
|
||||
}
|
||||
if err := json.Unmarshal(thread, &result); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
return map[string]any{"data": []json.RawMessage{result.Thread}, "nextCursor": nil}
|
||||
default:
|
||||
t.Errorf("unexpected method %s", method)
|
||||
return nil
|
||||
}
|
||||
})
|
||||
created, err := chat.Create(context.Background(), "", "/fixture")
|
||||
if err != nil || created.Model != "fixture-start" || created.ModelProvider != "fixture-provider" {
|
||||
t.Fatalf("create model = %+v, %v", created, err)
|
||||
}
|
||||
listed, err := chat.Sessions(context.Background())
|
||||
if err != nil || len(listed) != 1 || listed[0].Model != "fixture-current" || listed[0].ModelProvider != "fixture-provider" {
|
||||
t.Fatalf("list model = %+v, %v", listed, err)
|
||||
}
|
||||
}
|
||||
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
# Codex model protocol fixtures
|
||||
|
||||
These use synthetic models/providers, never guessed production identifiers.
|
||||
Wire shapes were checked against the official app-server documentation and the
|
||||
generated protocol source matching the installed package manifest (Codex 0.163.0):
|
||||
|
||||
- https://developers.openai.com/codex/app-server
|
||||
- https://github.com/openai/codex/blob/rust-v0.163.0/codex-rs/app-server-protocol/schema/typescript/v2/ModelListResponse.ts
|
||||
- Same directory: `ModelListParams.ts`, `Model.ts`, `Thread.ts`, `ThreadStartResponse.ts`, `TurnStartParams.ts`.
|
||||
|
||||
`Model.model` is the turn override, not the catalog row's opaque `id`.
|
||||
`Thread.model` is current configured/latest persisted metadata, not per-turn
|
||||
execution telemetry. `thread/start` also returns model/provider at the top level.
|
||||
The fixtures project fields consumed by this adapter and retain real casing and
|
||||
pagination shapes. Tests use an isolated fake WebSocket JSON-RPC server.
|
||||
|
||||
Local `codex --version` timed out before output, so schema generation was not reached;
|
||||
the installed `codex-package.json` identified version 0.163.0, so version-tagged
|
||||
generated source was read instead. No live app-server socket was contacted.
|
||||
|
||||
Model selection validates via `thread/read` + `model/list`, persists a Pipelines
|
||||
next-turn choice, and supplies `turn/start.model` only when the user sends a
|
||||
prompt. It never calls `thread/resume`, which can awaken a queued goal, nor any
|
||||
configuration-writing API. The acknowledgement means "saved for the next turn,"
|
||||
not "remote settings changed." The override is supplied again after a Pipelines
|
||||
restart; an already-running turn is not reconfigured.
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"data":[{"id":"opaque-picker-id","model":"fixture-model","displayName":"Fixture Model","description":"Test catalog only","hidden":false,"upgrade":null,"upgradeInfo":null,"availabilityNux":null,"modelSpecialty":null,"supportedReasoningEfforts":[{"reasoningEffort":"medium","description":"Fixture effort"}],"defaultReasoningEffort":"medium","inputModalities":["text","image"],"supportsPersonality":false,"multiAgentVersion":null,"additionalSpeedTiers":[],"serviceTiers":[],"defaultServiceTier":null,"availableAccessPrograms":null,"isDefault":true}],"nextCursor":"page-two"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"thread":{"id":"01900000-0000-7000-8000-000000000001","name":"Fixture chat","preview":"Fixture","cwd":"/fixture","model":"fixture-current","modelProvider":"fixture-provider","createdAt":1,"updatedAt":2,"status":{"type":"notLoaded"},"turns":[]}}
|
||||
@@ -0,0 +1,65 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOperatorModelSelectionMigratesAndPersists(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)
|
||||
}
|
||||
for _, id := range []string{"codex-chat", "other-chat"} {
|
||||
if err := store.RecordOperatorSession(ctx, id, "/fixture", "title", "operator"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := store.SetOperatorSessionBackend(ctx, "codex-chat", "codex"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetChatModelSelection(ctx, "other-chat", "fixture-provider", "fixture-model"); err == nil {
|
||||
t.Fatal("OpenCode row accepted Codex model")
|
||||
}
|
||||
if err := store.SetChatModelSelection(ctx, "missing", "fixture-provider", "fixture-model"); err == nil {
|
||||
t.Fatal("unregistered selection accepted")
|
||||
}
|
||||
if err := store.SetChatModelSelection(ctx, "codex-chat", "fixture-provider", "fixture-model"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _, err := store.OperatorSession(ctx, "codex-chat")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store.Close()
|
||||
store, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
provider, model, err := store.ChatModelSelection(ctx, "codex-chat")
|
||||
if err != nil || provider != "fixture-provider" || model != "fixture-model" {
|
||||
t.Fatalf("restored %q/%q: %v", provider, model, err)
|
||||
}
|
||||
provider, model, err = store.ChatModelSelection(ctx, "other-chat")
|
||||
if err != nil || provider != "" || model != "" {
|
||||
t.Fatalf("selection leaked: %q/%q: %v", provider, model, err)
|
||||
}
|
||||
after, _, err := store.OperatorSession(ctx, "codex-chat")
|
||||
if err != nil || before.UpdatedAt != after.UpdatedAt {
|
||||
t.Fatal("selection changed recency", err)
|
||||
}
|
||||
}
|
||||
@@ -139,6 +139,11 @@ 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"} {
|
||||
if err := s.addColumnIfMissing("operator_sessions", column, "TEXT NOT NULL DEFAULT ''"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0"); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -158,6 +163,35 @@ func (s *Store) migrateOperatorSessions() error {
|
||||
return s.addColumnIfMissing("operator_sessions", "ephemeral", "INTEGER NOT NULL DEFAULT 0")
|
||||
}
|
||||
|
||||
// SetChatModelSelection saves a Pipelines next-turn override, not a remote
|
||||
// Codex settings acknowledgement. Only registered Codex operator chats qualify.
|
||||
func (s *Store) SetChatModelSelection(ctx context.Context, id, provider, model string) error {
|
||||
if provider == "" || model == "" {
|
||||
return errors.New("a model and provider are required")
|
||||
}
|
||||
result, err := s.db.ExecContext(ctx, `UPDATE operator_sessions SET chat_model=?,chat_model_provider=? WHERE session_id=? AND backend='codex' AND tag<>''`, model, provider, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count != 1 {
|
||||
return errors.New("model selection requires a registered Codex operator chat")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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='codex' AND tag<>''`, id).Scan(&provider, &model)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", "", nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// RecordOperatorSession upserts one operator chat session in a single statement:
|
||||
// a new id is inserted with its created_at and last_used_at set to now, and a
|
||||
// repeated id updates directory/title/tag and moves last_used_at to now while
|
||||
|
||||
@@ -169,6 +169,8 @@ type ChatModel struct {
|
||||
|
||||
// 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.
|
||||
Selection string `json:"selection,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model"`
|
||||
@@ -179,6 +181,9 @@ type ChatModelRequest struct {
|
||||
// lifted to Directory, CreatedAt and UpdatedAt.
|
||||
type ChatSession struct {
|
||||
ID string `json:"id"`
|
||||
// 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"`
|
||||
// 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"`
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type selectedModelChat struct {
|
||||
*fakeChat
|
||||
model, nativeID string
|
||||
overrides int
|
||||
}
|
||||
|
||||
func (c *selectedModelChat) PromptWithMessageIDModel(_ context.Context, _, _, nativeID, model string) error {
|
||||
c.model, c.nativeID = model, nativeID
|
||||
c.overrides++
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestCodexModelSelectionSurvivesServerRestart(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-000000000001"
|
||||
if err := store.RecordOperatorSession(ctx, id, "/fixture", "chat", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetOperatorSessionBackend(ctx, id, "codex"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fake := &selectedModelChat{fakeChat: scriptedChat()}
|
||||
fake.models = []protocol.ChatModel{{ID: "fixture-model", Provider: "fixture-provider"}}
|
||||
fake.sessionRecord = protocol.ChatSession{ID: id, Backend: "codex", Model: "fixture-current", ModelProvider: "fixture-provider"}
|
||||
fake.sessionFound = true
|
||||
fake.sessions = []protocol.ChatSession{fake.sessionRecord}
|
||||
manager := &chatManager{codex: fake, registry: store, cache: map[string]string{}}
|
||||
var reply protocol.Message
|
||||
handleChatModelSwitch(ctx, protocol.Message{ID: "choose", ModelRequest: &protocol.ChatModelRequest{SessionID: id, Provider: "fixture-provider", Model: "fixture-model"}}, manager, func(msg protocol.Message) error { reply = msg; return nil })
|
||||
if reply.Type != protocol.ChatModelSelect || reply.ModelRequest.Selection != "next_turn" {
|
||||
t.Fatalf("selection reply = %+v", reply)
|
||||
}
|
||||
if fake.overrides != 0 {
|
||||
t.Fatal("selection started a turn")
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = pipeline.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
// A new manager has neither backend nor model cached in memory.
|
||||
manager = &chatManager{codex: fake, registry: store, cache: map[string]string{}}
|
||||
session, found, err := manager.Session(ctx, id)
|
||||
if err != nil || !found || session.Model != "fixture-model" || session.ModelSelection != "next_turn" {
|
||||
t.Fatalf("restarted session = %+v, %v", session, err)
|
||||
}
|
||||
list, err := manager.Sessions(ctx)
|
||||
if err != nil || len(list) != 1 || list[0].Model != "fixture-model" || list[0].ModelSelection != "next_turn" {
|
||||
t.Fatalf("restarted list = %+v, %v", list, err)
|
||||
}
|
||||
if err := manager.PromptWithMessageID(ctx, id, "hello", "msg_native"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fake.model != "fixture-model" || fake.nativeID != "msg_native" {
|
||||
t.Fatalf("override = %s/%s", fake.model, fake.nativeID)
|
||||
}
|
||||
if err := manager.Prompt(ctx, id, "again"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fake.overrides != 2 {
|
||||
t.Fatal("plain prompt bypassed saved choice")
|
||||
}
|
||||
if err := manager.PromptWithMessageIDFiles(ctx, id, "no attachments", "msg_empty", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fake.overrides != 3 || fake.nativeID != "msg_empty" {
|
||||
t.Fatal("empty attachments bypassed saved choice")
|
||||
}
|
||||
fake.sessionRecord.ModelProvider = "different-provider"
|
||||
if err := manager.Prompt(ctx, id, "must not send"); err == nil {
|
||||
t.Fatal("saved model sent to a different provider")
|
||||
}
|
||||
if fake.overrides != 3 {
|
||||
t.Fatal("mismatched provider started a turn")
|
||||
}
|
||||
// A failed durable save must never acknowledge the next-turn selection.
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply = protocol.Message{}
|
||||
handleChatModelSwitch(ctx, protocol.Message{ID: "failed-save", ModelRequest: &protocol.ChatModelRequest{SessionID: id, Provider: "fixture-provider", Model: "fixture-model"}}, manager, func(msg protocol.Message) error { reply = msg; return nil })
|
||||
if reply.Type != protocol.Error || reply.ModelRequest != nil {
|
||||
t.Fatalf("failed save acknowledged: %+v", reply)
|
||||
}
|
||||
}
|
||||
@@ -119,11 +119,7 @@ func (m *chatManager) Create(ctx context.Context, title, directory string) (prot
|
||||
}
|
||||
|
||||
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)
|
||||
return m.PromptWithMessageID(ctx, sessionID, text, "")
|
||||
}
|
||||
|
||||
func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text, messageID string) error {
|
||||
@@ -131,6 +127,28 @@ func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if m.backendFor(ctx, sessionID) == codex.Backend {
|
||||
provider, model, err := m.chatModelSelection(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if model != "" {
|
||||
session, found, err := adapter.Session(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found || session.ModelProvider != provider {
|
||||
return errors.New("saved model provider no longer matches the Codex thread; select a model again")
|
||||
}
|
||||
withModel, ok := adapter.(interface {
|
||||
PromptWithMessageIDModel(context.Context, string, string, string, string) error
|
||||
})
|
||||
if !ok {
|
||||
return errors.New("this Codex adapter cannot apply the saved next-turn model")
|
||||
}
|
||||
return withModel.PromptWithMessageIDModel(ctx, sessionID, text, messageID, model)
|
||||
}
|
||||
}
|
||||
if withID, ok := adapter.(chatPromptWithMessageID); ok {
|
||||
return withID.PromptWithMessageID(ctx, sessionID, text, messageID)
|
||||
}
|
||||
@@ -140,6 +158,9 @@ func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text,
|
||||
// PromptWithMessageIDFiles forwards a prompt with the private local files the
|
||||
// server wrote for browser attachments. Never silently discard files.
|
||||
func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, text, messageID string, files []opencode.PromptFile) error {
|
||||
if len(files) == 0 {
|
||||
return m.PromptWithMessageID(ctx, sessionID, text, messageID)
|
||||
}
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -147,10 +168,7 @@ func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, t
|
||||
if withFiles, ok := adapter.(chatPromptWithFiles); ok {
|
||||
return withFiles.PromptWithMessageIDFiles(ctx, sessionID, text, messageID, files)
|
||||
}
|
||||
if len(files) > 0 {
|
||||
return errChatAttachmentsUnsupported
|
||||
}
|
||||
return m.PromptWithMessageID(ctx, sessionID, text, messageID)
|
||||
return errChatAttachmentsUnsupported
|
||||
}
|
||||
|
||||
var errChatAttachmentsUnsupported = errors.New("this chat harness does not support attachments")
|
||||
@@ -204,9 +222,53 @@ func (m *chatManager) SwitchModel(ctx context.Context, sessionID, provider, mode
|
||||
if !ok {
|
||||
return errors.New("this chat harness does not support changing models")
|
||||
}
|
||||
if m.backendFor(ctx, sessionID) == codex.Backend {
|
||||
registry, ok := m.registry.(chatModelSelectionRegistry)
|
||||
if !ok {
|
||||
return errors.New("durable chat model selection is not configured")
|
||||
}
|
||||
if err := modeler.SwitchModel(ctx, sessionID, provider, model); err != nil {
|
||||
return err
|
||||
}
|
||||
return registry.SetChatModelSelection(ctx, sessionID, provider, model)
|
||||
}
|
||||
return modeler.SwitchModel(ctx, sessionID, provider, model)
|
||||
}
|
||||
|
||||
type chatModelSelectionRegistry interface {
|
||||
SetChatModelSelection(context.Context, string, string, string) error
|
||||
ChatModelSelection(context.Context, string) (string, string, error)
|
||||
}
|
||||
|
||||
func (m *chatManager) ModelSelectionMode(ctx context.Context, id string) string {
|
||||
if m.backendFor(ctx, id) == codex.Backend {
|
||||
return "next_turn"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *chatManager) chatModelSelection(ctx context.Context, id string) (string, string, error) {
|
||||
if registry, ok := m.registry.(chatModelSelectionRegistry); ok {
|
||||
return registry.ChatModelSelection(ctx, id)
|
||||
}
|
||||
return "", "", nil
|
||||
}
|
||||
|
||||
func (m *chatManager) withModelSelection(ctx context.Context, session protocol.ChatSession) (protocol.ChatSession, error) {
|
||||
if session.Backend != codex.Backend {
|
||||
return session, nil
|
||||
}
|
||||
provider, model, err := m.chatModelSelection(ctx, session.ID)
|
||||
if err != nil {
|
||||
return session, err
|
||||
}
|
||||
if model != "" {
|
||||
session.ModelProvider, session.Model = provider, model
|
||||
session.ModelSelection = "next_turn"
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -270,6 +332,13 @@ func (m *chatManager) Sessions(ctx context.Context) ([]protocol.ChatSession, err
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range sessions {
|
||||
var err error
|
||||
sessions[i], err = m.withModelSelection(ctx, sessions[i])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
@@ -278,7 +347,12 @@ func (m *chatManager) Session(ctx context.Context, sessionID string) (protocol.C
|
||||
if err != nil {
|
||||
return protocol.ChatSession{}, false, err
|
||||
}
|
||||
return adapter.Session(ctx, sessionID)
|
||||
session, found, err := adapter.Session(ctx, sessionID)
|
||||
if err != nil || !found {
|
||||
return session, found, err
|
||||
}
|
||||
session, err = m.withModelSelection(ctx, session)
|
||||
return session, found, err
|
||||
}
|
||||
|
||||
func (m *chatManager) Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error) {
|
||||
|
||||
@@ -166,7 +166,14 @@ func handleChatModelSwitch(ctx context.Context, request protocol.Message, broker
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatModelSelect, ID: request.ID, ModelRequest: body})
|
||||
reply := *body
|
||||
reply.Selection = ""
|
||||
if reporter, ok := broker.(interface {
|
||||
ModelSelectionMode(context.Context, string) string
|
||||
}); ok {
|
||||
reply.Selection = reporter.ModelSelectionMode(ctx, body.SessionID)
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatModelSelect, ID: request.ID, ModelRequest: &reply})
|
||||
}
|
||||
|
||||
// handleChatSubscribe attaches one connection to a session's shared stream so it
|
||||
|
||||
@@ -10,6 +10,15 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu
|
||||
|
||||
### Chat audit follow-up (2026-10-20, partial — fresh UI captures pending)
|
||||
|
||||
Codex model follow-up (partial, fixture-tested; fresh UI captures pending):
|
||||
model controls now include Codex, using the app-server `model/list` catalog and
|
||||
current `thread/read`/`thread/list` model metadata. Selecting a model saves a
|
||||
per-chat Pipelines registry choice, explicitly labelled **next turn**, and adds
|
||||
the verified `model` override to the next user-initiated `turn/start`, including
|
||||
after a Pipelines restart. This does not call `thread/resume`, start a goal, edit
|
||||
Codex configuration, or claim the remote thread changed before a turn is sent.
|
||||
Versioned protocol evidence and synthetic fixtures: `internal/codex/testdata/`.
|
||||
|
||||
The following supersedes older C8/B18 implementation details below:
|
||||
- Web attachments are limited to **1 MiB total and eight files**, matching the
|
||||
server. Unsupported harnesses reject attachments before upload storage/queueing.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Harnesses with a verified catalog and model-selection path. */
|
||||
export function supportsChatModels(backend) {
|
||||
return ["", "opencode", "codex"].includes(String(backend ?? "").trim());
|
||||
}
|
||||
|
||||
/** Never turn an unknown remote model into an invented model name. */
|
||||
export function chatModelLabel(session) {
|
||||
const model = String(session?.model ?? "").trim() || "Model";
|
||||
return session?.model_selection === "next_turn" ? `${model} · next turn` : model;
|
||||
}
|
||||
|
||||
export function chatModelSelectionNote(backend) {
|
||||
return backend === "codex"
|
||||
? "Saved by Pipelines for the next turn you send. Does not resume this thread or edit global Codex configuration."
|
||||
: "Applies to the next turn in this chat.";
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
import { backChevronIcon, h } from "../dom.js";
|
||||
import { readChatStars, writeChatStars } from "../chatStars.js";
|
||||
import { chatModelLabel, chatModelSelectionNote, supportsChatModels } from "../chatModels.js";
|
||||
import { describeError } from "../format.js";
|
||||
import { SHELL_OUTPUT_LIMIT, nativeChatMessageId, newChatOperationId } from "../repository.js";
|
||||
import { codeBlockLabel, parseInline, parseMarkdown } from "../markdown.js";
|
||||
@@ -2578,8 +2579,8 @@ function renderChatSnackbar() {
|
||||
/** The chat header's model control: current model, opens the switcher. */
|
||||
function renderChatModelButton(session) {
|
||||
const backend = String(session?.backend ?? "").trim();
|
||||
if (backend !== "" && backend !== "opencode") return null;
|
||||
const label = String(session?.model ?? "").trim() || "Model";
|
||||
if (!supportsChatModels(backend)) return null;
|
||||
const label = chatModelLabel(session);
|
||||
return h(
|
||||
"button",
|
||||
{
|
||||
@@ -2617,7 +2618,7 @@ function closeChatModelPicker() {
|
||||
|
||||
async function loadChatModels(sessionId) {
|
||||
const backend = state.chatSessions.find((row) => row.id === sessionId)?.backend ?? "opencode";
|
||||
if (backend !== "" && backend !== "opencode") {
|
||||
if (!supportsChatModels(backend)) {
|
||||
state.chatModelsLoading = false;
|
||||
state.chatModelsError = `${chatBackendLabel(backend)} does not support changing models from this client.`;
|
||||
if (state.chatModelPicker?.id === sessionId) renderContent();
|
||||
@@ -2644,8 +2645,8 @@ async function selectChatModel(session, model) {
|
||||
state.chatModelsError = "";
|
||||
renderContent();
|
||||
try {
|
||||
await repo.switchChatModel(session.id, model.provider, model.id);
|
||||
applyChatSessionModel(session.id, model.provider, model.id);
|
||||
const selected = await repo.switchChatModel(session.id, model.provider, model.id);
|
||||
applyChatSessionModel(session.id, model.provider, model.id, selected.selection);
|
||||
state.chatModelPicker = null;
|
||||
} catch (error) {
|
||||
state.chatModelsError = describeError(error);
|
||||
@@ -2655,9 +2656,9 @@ async function selectChatModel(session, model) {
|
||||
}
|
||||
|
||||
/** Apply a successful model switch to the list row and the open thread. */
|
||||
function applyChatSessionModel(sessionId, provider, model) {
|
||||
function applyChatSessionModel(sessionId, provider, model, selection = "") {
|
||||
state.chatSessions = (state.chatSessions ?? []).map((row) =>
|
||||
row.id === sessionId ? { ...row, model, model_provider: provider } : row,
|
||||
row.id === sessionId ? { ...row, model, model_provider: provider, model_selection: selection } : row,
|
||||
);
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (thread) setThread(sessionId, { model, modelProvider: provider });
|
||||
@@ -2682,7 +2683,7 @@ function renderChatModelDialog(session) {
|
||||
panel.append(
|
||||
h("p", {
|
||||
class: "chat-model-helper muted",
|
||||
text: "Applies to the next turn in this chat.",
|
||||
text: chatModelSelectionNote(session.backend),
|
||||
}),
|
||||
);
|
||||
if (state.chatModelsLoading) {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { chatModelLabel, chatModelSelectionNote, supportsChatModels } from "../src/chatModels.js";
|
||||
import { PipelinesRepository } from "../src/repository.js";
|
||||
|
||||
test("Codex and OpenCode expose model selection, unverified backends do not", () => {
|
||||
for (const backend of [undefined, "", "opencode", "codex"]) assert.equal(supportsChatModels(backend), true);
|
||||
for (const backend of ["claude", "unknown"]) assert.equal(supportsChatModels(backend), false);
|
||||
});
|
||||
|
||||
test("model control distinguishes saved next-turn choice from remote current model", () => {
|
||||
assert.equal(chatModelLabel({ model: "fixture-current" }), "fixture-current");
|
||||
assert.equal(chatModelLabel({ model: "fixture-selected", model_selection: "next_turn" }), "fixture-selected · next turn");
|
||||
assert.equal(chatModelLabel({ model: null }), "Model");
|
||||
assert.match(chatModelSelectionNote("codex"), /Saved by Pipelines for the next turn/);
|
||||
assert.match(chatModelSelectionNote("codex"), /Does not resume/);
|
||||
});
|
||||
|
||||
test("model switch reply preserves local next-turn acknowledgement", async () => {
|
||||
let sent;
|
||||
const repo = new PipelinesRepository({ call: async (request) => {
|
||||
sent = request;
|
||||
return { chat_model: { ...request.chat_model, selection: "next_turn" } };
|
||||
} });
|
||||
const selected = await repo.switchChatModel("fixture-thread", "fixture-provider", "fixture-model");
|
||||
assert.deepEqual(sent.chat_model, { session_id: "fixture-thread", provider: "fixture-provider", model: "fixture-model" });
|
||||
assert.equal(selected.selection, "next_turn");
|
||||
});
|
||||
Reference in New Issue
Block a user