fix(codex): load persisted threads only on explicit send after refusal

This commit is contained in:
2026-10-20 18:46:17 +01:00
parent d564765ca5
commit 03a508fa2b
4 changed files with 119 additions and 5 deletions
+8
View File
@@ -66,3 +66,11 @@ It does not call `thread/resume` on open/model selection, so merely watching a
chat cannot awaken a queued goal. Native turn IDs protect the queue/UI from stale
completion events. A real, isolated tool-free turn passed after replacing the
owning connection; no command, permission grant or global setting was involved.
An explicit Send can load a persisted thread if `turn/start` is refused with
the exact application error `thread not found: <owned-thread-id>`. Only then
does the adapter call `thread/resume` (metadata only, no policy/configuration
override) and submit the original message/model/files. Transport failures and
unrelated errors are never retried. This loading is not performed by browsing,
history reads or model selection. As in Codex's native client, explicitly
continuing a thread also resumes that thread's configured execution context.
+36 -4
View File
@@ -74,8 +74,9 @@ type pendingForm struct {
}
type rpcResponse struct {
Result json.RawMessage
Error *rpcError
Result json.RawMessage
Error *rpcError
Transport bool
}
type rpcError struct {
@@ -83,6 +84,13 @@ type rpcError struct {
Message string `json:"message"`
}
type rpcCallError struct {
Code int
Message string
}
func (e *rpcCallError) Error() string { return e.Message }
type rpcMessage struct {
ID json.RawMessage `json:"id"`
Method string `json:"method"`
@@ -195,7 +203,7 @@ func (c *Chat) failPending(err error) {
c.subs = map[string]map[chan protocol.ChatEventFrame]struct{}{}
c.mu.Unlock()
for _, ch := range pending {
ch <- rpcResponse{Error: &rpcError{Message: err.Error()}}
ch <- rpcResponse{Error: &rpcError{Message: err.Error()}, Transport: true}
}
for _, set := range subs {
for ch := range set {
@@ -241,7 +249,10 @@ func (c *Chat) call(ctx context.Context, method string, params any) (json.RawMes
return nil, ctx.Err()
case resp := <-ch:
if resp.Error != nil {
return nil, errors.New(resp.Error.Message)
if resp.Transport {
return nil, errors.New(resp.Error.Message)
}
return nil, &rpcCallError{Code: resp.Error.Code, Message: resp.Error.Message}
}
return resp.Result, nil
}
@@ -350,6 +361,27 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
c.starting[id] = true
c.mu.Unlock()
raw, err := c.call(ctx, "turn/start", params)
// A read-only browser connection may point at a persisted, unloaded thread.
// Only an explicit Send can load it. Retry solely after the provider's exact
// application-level refusal: transport/timeout failures may have admitted a
// turn and must never be blindly repeated.
var refused *rpcCallError
if errors.As(err, &refused) && refused.Message == "thread not found: "+id {
var resumed json.RawMessage
resumed, err = c.call(ctx, "thread/resume", map[string]any{"threadId": id, "excludeTurns": true})
if err == nil {
var response struct {
Thread struct {
ID string `json:"id"`
} `json:"thread"`
}
if json.Unmarshal(resumed, &response) != nil || response.Thread.ID != id {
err = errors.New("Codex did not confirm the requested thread was loaded")
} else {
raw, err = c.call(ctx, "turn/start", params)
}
}
}
var reply struct {
Turn struct {
ID string `json:"id"`
+5 -1
View File
@@ -42,7 +42,11 @@ func modelTestChat(t *testing.T, handle func(string, json.RawMessage) any) *Chat
return
}
result := handle(req.Method, req.Params)
if err := wsjson.Write(ctx, conn, map[string]any{"id": req.ID, "result": result}); err != nil {
response := map[string]any{"id": req.ID, "result": result}
if failure, ok := result.(*rpcError); ok {
response = map[string]any{"id": req.ID, "error": failure}
}
if err := wsjson.Write(ctx, conn, response); err != nil {
return
}
}
+70
View File
@@ -3,6 +3,7 @@ package codex
import (
"context"
"encoding/json"
"errors"
"sync"
"testing"
"time"
@@ -75,3 +76,72 @@ func TestLateCompletionDoesNotClearNewCodexTurn(t *testing.T) {
default:
}
}
func TestExplicitPromptLoadsOnlyAConfirmedUnloadedThread(t *testing.T) {
var methods []string
c := modelTestChat(t, func(method string, params json.RawMessage) any {
methods = append(methods, method)
if method == "turn/start" {
var p map[string]any
json.Unmarshal(params, &p)
if p["model"] != "fixture-model" || p["clientUserMessageId"] != "msg_same" {
t.Errorf("recovery changed explicit turn identity/model: %s", params)
}
}
if len(methods) == 1 {
return &rpcError{Code: -32602, Message: "thread not found: " + fixtureThread}
}
if method == "thread/resume" {
var p map[string]any
json.Unmarshal(params, &p)
if p["threadId"] != fixtureThread || p["excludeTurns"] != true || len(p) != 2 {
t.Errorf("resume changed configuration: %s", params)
}
return map[string]any{"thread": map[string]any{"id": fixtureThread}}
}
return map[string]any{"turn": map[string]any{"id": "loaded-turn"}}
})
if err := c.PromptWithMessageIDModel(context.Background(), fixtureThread, "explicit user message", "msg_same", "fixture-model"); err != nil {
t.Fatal(err)
}
if len(methods) != 3 || methods[0] != "turn/start" || methods[1] != "thread/resume" || methods[2] != "turn/start" {
t.Fatalf("unsafe recovery sequence: %v", methods)
}
}
func TestUnrelatedPromptRefusalIsNeverRetriedOrResumed(t *testing.T) {
methods := []string{}
c := modelTestChat(t, func(method string, _ json.RawMessage) any {
methods = append(methods, method)
return &rpcError{Code: -32602, Message: "controlled provider rejection"}
})
if err := c.Prompt(context.Background(), fixtureThread, "explicit user message"); err == nil {
t.Fatal("refusal ignored")
}
if len(methods) != 1 || methods[0] != "turn/start" {
t.Fatalf("unsafe retry: %v", methods)
}
}
func TestTransportFailureCannotTriggerAnUnloadedThreadRetry(t *testing.T) {
entered, release := make(chan struct{}), make(chan struct{})
var once sync.Once
c := modelTestChat(t, func(method string, _ json.RawMessage) any {
if method != "turn/start" {
t.Errorf("transport failure retried through %s", method)
}
once.Do(func() { close(entered) })
<-release
return map[string]any{"turn": map[string]any{"id": "possibly-admitted"}}
})
result := make(chan error, 1)
go func() { result <- c.Prompt(context.Background(), fixtureThread, "explicit message") }()
<-entered
// Even a transport failure whose text resembles a provider refusal is not
// evidence that the original turn was never admitted.
c.failPending(errors.New("thread not found: " + fixtureThread))
if err := <-result; err == nil {
t.Fatal("transport failure reported success")
}
close(release)
}