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":[]}}
|
||||
Reference in New Issue
Block a user