fix(codex): reconcile cold connections without resuming queued goals

This commit is contained in:
2026-10-20 18:33:20 +01:00
parent b3bcfa3826
commit d564765ca5
14 changed files with 355 additions and 34 deletions
+8
View File
@@ -58,3 +58,11 @@ endpoint, process control, resumed turn or experimental flag is invented.
Output reads are bounded and verify thread ownership. The installed Codex Output reads are bounded and verify thread ownership. The installed Codex
version exposes no API for controlling an agent-owned terminal through the version exposes no API for controlling an agent-owned terminal through the
separate, client-owned `command/exec` process IDs; those IDs are never conflated. separate, client-owned `command/exec` process IDs; those IDs are never conflated.
A fresh Codex connection can accept a turn without subscribing to its native
thread notifications. The adapter therefore reconciles the latest turn through
the read-only paged API and emits an authoritative-history resync when it changes.
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.
+5
View File
@@ -331,6 +331,11 @@ returns the corresponding action/content; other Codex questions accept answers
only. Permission frames may provide `always_label: "Allow for session"` to avoid only. Permission frames may provide `always_label: "Allow for session"` to avoid
misrepresenting a session-scoped grant as a permanent policy change. misrepresenting a session-scoped grant as a permanent policy change.
Chat streams may send `chat_event.kind="resync"` to request an authoritative
history refresh without inventing text deltas or ending a queued prompt. Native
step markers may include `step.turn_id`; a terminal marker for an older turn
must not clear a newer turn's Stop control or release its queue slot.
The brokered OpenCode chat exposes the operator's own sessions, separate from the The brokered OpenCode chat exposes the operator's own sessions, separate from the
sessions pipeline runs create. The protocol types are: sessions pipeline runs create. The protocol types are:
+54 -24
View File
@@ -58,6 +58,7 @@ type Chat struct {
approvals map[string]pendingApproval approvals map[string]pendingApproval
commands map[string]map[string]commandSnapshot commands map[string]map[string]commandSnapshot
commandOrder uint64 commandOrder uint64
starting map[string]bool
turns map[string]string turns map[string]string
emitted map[string]bool emitted map[string]bool
closed bool closed bool
@@ -299,24 +300,7 @@ func (c *Chat) unsubscribe(id string, ch chan protocol.ChatEventFrame) {
// Stream exposes one thread's notifications as chat frames. // Stream exposes one thread's notifications as chat frames.
func (c *Chat) Stream(ctx context.Context, id string, ready func(), emit func(protocol.ChatEventFrame) error) error { func (c *Chat) Stream(ctx context.Context, id string, ready func(), emit func(protocol.ChatEventFrame) error) error {
ch := c.subscribe(id) return c.streamWithReadback(ctx, id, ready, emit)
defer c.unsubscribe(id, ch)
if ready != nil {
ready()
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case frame, ok := <-ch:
if !ok {
return errors.New("Codex connection closed")
}
if err := emit(frame); err != nil {
return err
}
}
}
} }
// Prompt starts one turn. The user turn is already broadcast by the server, so // Prompt starts one turn. The user turn is already broadcast by the server, so
@@ -359,7 +343,30 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
if model != "" { if model != "" {
params["model"] = model params["model"] = model
} }
_, err = c.call(ctx, "turn/start", params) c.mu.Lock()
if c.starting == nil {
c.starting = map[string]bool{}
}
c.starting[id] = true
c.mu.Unlock()
raw, err := c.call(ctx, "turn/start", params)
var reply struct {
Turn struct {
ID string `json:"id"`
} `json:"turn"`
}
if err == nil {
_ = json.Unmarshal(raw, &reply)
}
c.mu.Lock()
delete(c.starting, id)
if reply.Turn.ID != "" {
c.turns[id] = reply.Turn.ID
}
c.mu.Unlock()
if err == nil && reply.Turn.ID != "" {
c.emit(stepFrame(id, protocol.ChatStepStarted, reply.Turn.ID))
}
return err return err
} }
@@ -493,6 +500,10 @@ func (c *Chat) Messages(ctx context.Context, id string, limit int, cursor string
messages = append(messages, msg) messages = append(messages, msg)
} }
} }
if turn.ID != "" && rawText(turn.Error) != "" {
part := item{ID: turn.ID + "#error", Type: "Codex turn", Status: "failed", Error: turn.Error, Input: map[string]any{"turn_id": turn.ID}}.toolPart(true)
messages = append(messages, protocol.ChatMessage{ID: part.ID, SessionID: id, Role: protocol.ChatRoleAssistant, Parts: []protocol.ChatPart{part}})
}
} }
page := protocol.ChatHistoryPage{Messages: messages} page := protocol.ChatHistoryPage{Messages: messages}
if result.NextCursor != nil { if result.NextCursor != nil {
@@ -664,13 +675,25 @@ func (c *Chat) handleNotification(msg rpcMessage) {
if c.turns[params.ThreadID] == "" { if c.turns[params.ThreadID] == "" {
c.turns[params.ThreadID] = params.Turn.ID c.turns[params.ThreadID] = params.Turn.ID
} }
nativeID := c.turns[params.ThreadID]
c.mu.Unlock() c.mu.Unlock()
c.emit(stepFrame(params.ThreadID, "started")) c.emit(stepFrame(params.ThreadID, "started", nativeID))
case "turn/completed": case "turn/completed":
completedID := params.TurnID
if completedID == "" {
completedID = params.Turn.ID
}
if completedID == "" {
return
}
c.mu.Lock() c.mu.Lock()
if current := c.turns[params.ThreadID]; current != "" && current != completedID {
c.mu.Unlock()
return
}
delete(c.turns, params.ThreadID) delete(c.turns, params.ThreadID)
c.mu.Unlock() c.mu.Unlock()
c.emit(stepFrame(params.ThreadID, protocol.ChatStepEnded)) c.emit(stepFrame(params.ThreadID, protocol.ChatStepEnded, completedID))
case "item/started": case "item/started":
c.handleItem(params.ThreadID, params.ItemID, params.Item, false) c.handleItem(params.ThreadID, params.ItemID, params.Item, false)
case "item/completed": case "item/completed":
@@ -740,10 +763,14 @@ func textFrame(threadID, itemID, kind, delta string) protocol.ChatEventFrame {
} }
} }
func stepFrame(threadID, status string) protocol.ChatEventFrame { func stepFrame(threadID, status string, nativeID ...string) protocol.ChatEventFrame {
step := &protocol.ChatStep{Status: status}
if len(nativeID) > 0 {
step.TurnID = nativeID[0]
}
return protocol.ChatEventFrame{ return protocol.ChatEventFrame{
SessionID: threadID, Kind: protocol.ChatEventStep, SessionID: threadID, Kind: protocol.ChatEventStep,
Step: &protocol.ChatStep{Status: status}, Step: step,
} }
} }
@@ -760,7 +787,10 @@ type thread struct {
} }
type turn struct { type turn struct {
Items []item `json:"items"` ID string `json:"id"`
Status string `json:"status"`
Error json.RawMessage `json:"error"`
Items []item `json:"items"`
} }
type item struct { type item struct {
+109
View File
@@ -0,0 +1,109 @@
package codex
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
type turnReadback struct {
turn turn
digest [32]byte
}
func (c *Chat) latestTurn(ctx context.Context, id string) (turnReadback, error) {
read, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
raw, err := c.call(read, "thread/turns/list", map[string]any{"threadId": id, "limit": 1, "sortDirection": "desc", "itemsView": "full"})
if err != nil {
return turnReadback{}, err
}
var page struct {
Data []json.RawMessage `json:"data"`
}
if json.Unmarshal(raw, &page) != nil || page.Data == nil {
return turnReadback{}, errors.New("invalid Codex turn readback")
}
if len(page.Data) == 0 {
return turnReadback{}, nil
}
var current turn
if json.Unmarshal(page.Data[0], &current) != nil {
return turnReadback{}, errors.New("invalid Codex turn readback")
}
return turnReadback{turn: current, digest: sha256.Sum256(page.Data[0])}, nil
}
func activeTurn(t turn) bool { return t.ID != "" && t.Status == "inProgress" }
func terminalTurn(t turn) bool {
return t.ID != "" && (t.Status == "completed" || t.Status == "failed" || t.Status == "interrupted")
}
// A fresh App Server connection may accept turn/start without sending thread
// notifications. Reconcile read-only history instead of thread/resume, which
// can awaken queued goals. Resync requests replace history, never fake deltas.
func (c *Chat) streamWithReadback(ctx context.Context, id string, ready func(), emit func(protocol.ChatEventFrame) error) error {
ch := c.subscribe(id)
defer c.unsubscribe(id, ch)
last, _ := c.latestTurn(ctx, id)
if ready != nil {
ready()
}
if activeTurn(last.turn) {
c.mu.Lock()
c.turns[id] = last.turn.ID
c.mu.Unlock()
c.emit(stepFrame(id, protocol.ChatStepStarted, last.turn.ID))
}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case frame, ok := <-ch:
if !ok {
return errors.New("Codex connection closed")
}
if err := emit(frame); err != nil {
return err
}
case <-ticker.C:
current, err := c.latestTurn(ctx, id)
if err != nil {
return err
}
if current.digest == last.digest {
continue
}
c.mu.Lock()
pending := c.starting[id]
expected := c.turns[id]
if pending || (expected != "" && current.turn.ID != "" && expected != current.turn.ID) {
c.mu.Unlock()
continue
}
started := activeTurn(current.turn) && !activeTurn(last.turn)
if activeTurn(current.turn) {
c.turns[id] = current.turn.ID
}
ended := terminalTurn(current.turn) && expected == current.turn.ID
if ended {
delete(c.turns, id)
}
c.mu.Unlock()
last = current
if started {
c.emit(stepFrame(id, protocol.ChatStepStarted, current.turn.ID))
}
c.emit(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventResync})
if ended {
c.emit(stepFrame(id, protocol.ChatStepEnded, current.turn.ID))
}
}
}
}
+77
View File
@@ -0,0 +1,77 @@
package codex
import (
"context"
"encoding/json"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestStreamReconcilesAcceptedTurnWithoutNativeNotifications(t *testing.T) {
var mu sync.Mutex
started := false
c := modelTestChat(t, func(method string, _ json.RawMessage) any {
mu.Lock()
defer mu.Unlock()
switch method {
case "turn/start":
started = true
return map[string]any{"turn": map[string]any{"id": "turn-new"}}
case "thread/turns/list":
if !started {
return json.RawMessage(`{"data":[],"nextCursor":null}`)
}
return json.RawMessage(`{"data":[{"id":"turn-new","status":"completed","items":[{"id":"reply","type":"agentMessage","text":"done"}]}],"nextCursor":null}`)
default:
t.Errorf("readback must never resume/configure: %s", method)
return nil
}
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ready, ended := make(chan struct{}), make(chan struct{})
var once sync.Once
sawResync := false
go c.Stream(ctx, fixtureThread, func() { close(ready) }, func(frame protocol.ChatEventFrame) error {
if frame.Kind == protocol.ChatEventResync {
sawResync = true
}
if frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded {
if frame.Step.TurnID != "turn-new" {
t.Error("wrong turn completed")
}
once.Do(func() { close(ended) })
}
return nil
})
<-ready
if err := c.Prompt(ctx, fixtureThread, "tool-free verification"); err != nil {
t.Fatal(err)
}
select {
case <-ended:
if !sawResync {
t.Fatal("completion without authoritative history refresh")
}
case <-time.After(4 * time.Second):
t.Fatal("accepted turn stayed running without native notifications")
}
}
func TestLateCompletionDoesNotClearNewCodexTurn(t *testing.T) {
c := &Chat{turns: map[string]string{fixtureThread: "new"}, subs: map[string]map[chan protocol.ChatEventFrame]struct{}{}}
ch := c.subscribe(fixtureThread)
defer c.unsubscribe(fixtureThread, ch)
c.handleNotification(rpcMessage{Method: "turn/completed", Params: json.RawMessage(`{"threadId":"` + fixtureThread + `","turn":{"id":"old","status":"completed"}}`)})
if c.turns[fixtureThread] != "new" {
t.Fatal("old completion released new turn")
}
select {
case <-ch:
t.Fatal("stale terminal frame emitted")
default:
}
}
+2
View File
@@ -105,6 +105,7 @@ const (
ChatEventReasoning = ChatPartReasoning ChatEventReasoning = ChatPartReasoning
ChatEventTool = ChatPartTool ChatEventTool = ChatPartTool
ChatEventStep = "step" ChatEventStep = "step"
ChatEventResync = "resync"
ChatEventUsage = "usage" ChatEventUsage = "usage"
ChatEventUser = "user" ChatEventUser = "user"
// ChatEventShell reports the lifecycle of one shell the agent started. It // ChatEventShell reports the lifecycle of one shell the agent started. It
@@ -443,6 +444,7 @@ type ChatEventFrame struct {
// ChatStep is a progress marker for the current step of a turn. // ChatStep is a progress marker for the current step of a turn.
type ChatStep struct { type ChatStep struct {
Status string `json:"status"` Status string `json:"status"`
TurnID string `json:"turn_id,omitempty"`
Index int `json:"index,omitempty"` Index int `json:"index,omitempty"`
// Intermediate distinguishes a provider step from authoritative turn completion. // Intermediate distinguishes a provider step from authoritative turn completion.
Intermediate bool `json:"intermediate,omitempty"` Intermediate bool `json:"intermediate,omitempty"`
+7
View File
@@ -147,6 +147,13 @@ func checkChatBrowserLifecycle(t *testing.T, backend string) {
handler := HandlerWithOptions(ctx, Options{Chat: browserModelFixture{fake, forms}}, store) handler := HandlerWithOptions(ctx, Options{Chat: browserModelFixture{fake, forms}}, store)
defer func() { cancel(); WaitRuns(handler) }() defer func() { cancel(); WaitRuns(handler) }()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/fixture-resync" && req.Method == http.MethodPost {
fake.mu.Lock()
fake.messages = append(fake.messages, protocol.ChatMessage{ID: "msg_resync", Role: protocol.ChatRoleAssistant, Parts: []protocol.ChatPart{{Type: protocol.ChatPartText, Text: "Authoritative resync evidence"}}})
fake.mu.Unlock()
w.WriteHeader(http.StatusNoContent)
return
}
if req.URL.Path == "/fixture-shell" && req.Method == http.MethodPost { if req.URL.Path == "/fixture-shell" && req.Method == http.MethodPost {
fake.mu.Lock() fake.mu.Lock()
fake.shells = []protocol.ChatShell{{ID: "sh_" + backend + "_fixture", Status: protocol.ChatShellRunning, Command: "printf controlled"}} fake.shells = []protocol.ChatShell{{ID: "sh_" + backend + "_fixture", Status: protocol.ChatShellRunning, Command: "printf controlled"}}
+12
View File
@@ -147,6 +147,7 @@ type chatRoom struct {
pollerStarted bool pollerStarted bool
wake chan struct{} wake chan struct{}
turnDone chan struct{} turnDone chan struct{}
nativeTurnID string
} }
func newChatRoom(base context.Context, sessionID string) *chatRoom { func newChatRoom(base context.Context, sessionID string) *chatRoom {
@@ -373,6 +374,15 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) {
h.mu.Unlock() h.mu.Unlock()
return return
} }
if room != nil && frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.TurnID != "" && !frame.Step.Intermediate {
if frame.Step.Status == protocol.ChatStepStarted {
room.nativeTurnID = frame.Step.TurnID
}
if frame.Step.Status == protocol.ChatStepEnded && room.nativeTurnID != frame.Step.TurnID {
h.mu.Unlock()
return
}
}
h.applyLocked(frame) h.applyLocked(frame)
buffered := false buffered := false
var targets []*chatSub var targets []*chatSub
@@ -475,6 +485,7 @@ func (h *chatHub) replaceShellsLocked(sessionID string, shells []protocol.ChatSh
// wait. Callers must hold h.mu. // wait. Callers must hold h.mu.
func (h *chatHub) finishTurnLocked(room *chatRoom) { func (h *chatHub) finishTurnLocked(room *chatRoom) {
room.running = false room.running = false
room.nativeTurnID = ""
if room.turnDone != nil { if room.turnDone != nil {
close(room.turnDone) close(room.turnDone)
room.turnDone = nil room.turnDone = nil
@@ -660,6 +671,7 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{},
p := room.queue[0] p := room.queue[0]
room.queue = room.queue[1:] room.queue = room.queue[1:]
room.running = true room.running = true
room.nativeTurnID = ""
room.turnDone = make(chan struct{}) room.turnDone = make(chan struct{})
done := room.turnDone done := room.turnDone
h.mu.Unlock() h.mu.Unlock()
@@ -0,0 +1,25 @@
package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/protocol"
"testing"
)
func TestLateHarnessCompletionCannotReleaseNextChatTurn(t *testing.T) {
h := newChatHub()
room := newChatRoom(context.Background(), "ses_turn")
defer room.cancel()
room.running = true
room.nativeTurnID = "new"
room.turnDone = make(chan struct{})
h.rooms[room.sessionID] = room
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "old"}})
if !room.running {
t.Fatal("old terminal frame freed next turn queue")
}
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "new"}})
if room.running {
t.Fatal("matching terminal frame did not finish turn")
}
}
+8
View File
@@ -273,6 +273,14 @@ protocol shapes are tested. Read-only live Codex validation passed history,
command listing and model listing without starting/resuming a turn or changing command listing and model listing without starting/resuming a turn or changing
settings. No real Codex command or permission grant was used for testing. settings. No real Codex command or permission grant was used for testing.
Cold-connection Codex follow-up: live verification reproduced an accepted turn
with no native completion events. Read-only latest-turn reconciliation now asks
the browser to resync authoritative history and delivers completion, guarded by
native turn identity. A real isolated tool-free turn passed after replacing the
owning connection. Browser regressions for both harness identities verify resync
without composer replacement or lost draft; stale terminal events cannot clear
the next turn. No automatic thread resume or queued-goal activation is used.
Typed-tool follow-up: number/integer/boolean/default/conditional/secret and Typed-tool follow-up: number/integer/boolean/default/conditional/secret and
external-link fields use native controls, preserve JSON types and validate before external-link fields use native controls, preserve JSON types and validate before
sending. `typed-question-controls.png` and the scratch browser regression cover sending. `typed-question-controls.png` and the scratch browser regression cover
+6 -1
View File
@@ -1208,6 +1208,7 @@ export const EVENT_USAGE = "usage";
export const EVENT_USER = "user"; export const EVENT_USER = "user";
export const EVENT_SHELL = "shell"; export const EVENT_SHELL = "shell";
export const EVENT_FORM = "form"; export const EVENT_FORM = "form";
export const EVENT_RESYNC = "resync";
/** ChatStep.Status values. `ended` is the one status that settles a turn. */ /** ChatStep.Status values. `ended` is the one status that settles a turn. */
export const STEP_ENDED = "ended"; export const STEP_ENDED = "ended";
@@ -1603,6 +1604,8 @@ export function applyChatForm(thread, form) {
* targets is created on first sight, so a live turn never gains a second bubble. * targets is created on first sight, so a live turn never gains a second bubble.
*/ */
export function applyChatEvent(thread, frame, now = Date.now()) { export function applyChatEvent(thread, frame, now = Date.now()) {
if (frame?.kind === EVENT_RESYNC) return thread ?? newChatThread(str(frame?.session_id));
if (frame?.kind === EVENT_STEP && frame.step?.status === STEP_ENDED && frame.step?.turn_id && frame.step.turn_id !== thread?.nativeTurnId) return thread ?? newChatThread(str(frame?.session_id));
const current = thread?.queued const current = thread?.queued
? { ...thread, queued: false } ? { ...thread, queued: false }
: (thread ?? newChatThread(str(frame?.session_id))); : (thread ?? newChatThread(str(frame?.session_id)));
@@ -1616,7 +1619,9 @@ export function applyChatEvent(thread, frame, now = Date.now()) {
return applyTool(current, frame, now); return applyTool(current, frame, now);
case EVENT_STEP: case EVENT_STEP:
if (frame?.step?.intermediate) return current; if (frame?.step?.intermediate) return current;
return setThreadRunning(current, str(frame?.step?.status) !== STEP_ENDED, now); if (frame?.step?.turn_id && frame.step.status === STEP_ENDED && frame.step.turn_id !== current.nativeTurnId) return current;
return { ...setThreadRunning(current, str(frame?.step?.status) !== STEP_ENDED, now),
nativeTurnId: frame.step?.status === STEP_ENDED ? "" : frame.step?.turn_id || current.nativeTurnId || "" };
// A shell frame only folds its shell into the retained set: it NEVER marks // A shell frame only folds its shell into the retained set: it NEVER marks
// the thread running, because a background process is not the turn — a shell // the thread running, because a background process is not the turn — a shell
// that outlives the turn keeps showing after the turn's own indicator is gone. // that outlives the turn keeps showing after the turn's own indicator is gone.
+24 -8
View File
@@ -347,13 +347,16 @@ let pendingComposerFocus = null;
* frame would steal focus and the operator could not type a queued message. * frame would steal focus and the operator could not type a queued message.
*/ */
function captureChatFocus() { function captureChatFocus() {
const input = document.getElementById("chatInput"); const input = document.activeElement;
if (!input || document.activeElement !== input) { const question = input?.matches?.(".chat-question-input") ? input.closest(".chat-question") : null;
if (!input || (input !== document.getElementById("chatInput") && !question)) {
pendingComposerFocus = null; pendingComposerFocus = null;
return; return;
} }
pendingComposerFocus = { pendingComposerFocus = {
sessionId: state.chatActiveId ?? "", sessionId: state.chatActiveId ?? "",
formId: question?.dataset.formId ?? "",
fieldKey: input.dataset.fieldKey ?? "",
start: input.selectionStart, start: input.selectionStart,
end: input.selectionEnd, end: input.selectionEnd,
direction: input.selectionDirection, direction: input.selectionDirection,
@@ -366,7 +369,9 @@ function restoreChatFocus() {
pendingComposerFocus = null; pendingComposerFocus = null;
if (!pending) return; if (!pending) return;
if (state.chatActiveId !== pending.sessionId) return; if (state.chatActiveId !== pending.sessionId) return;
const input = document.getElementById("chatInput"); const input = pending.formId
? document.querySelector(`[data-form-id="${CSS.escape(pending.formId)}"] [data-field-key="${CSS.escape(pending.fieldKey)}"]`)
: document.getElementById("chatInput");
if (!input) return; if (!input) return;
input.focus({ preventScroll: true }); input.focus({ preventScroll: true });
try { try {
@@ -778,6 +783,11 @@ function refreshChatTranscript(sessionId) {
function onChatEvent(frame) { function onChatEvent(frame) {
const sessionId = String(frame?.session_id ?? "").trim(); const sessionId = String(frame?.session_id ?? "").trim();
if (!sessionId || !state.chatThreads.has(sessionId)) return; if (!sessionId || !state.chatThreads.has(sessionId)) return;
if (frame.kind === "resync") {
markBackgroundChatUnseen(sessionId);
scheduleHistorySync(sessionId, "", {force:true});
return;
}
markBackgroundChatUnseen(sessionId); markBackgroundChatUnseen(sessionId);
const thread = state.chatThreads.get(sessionId); const thread = state.chatThreads.get(sessionId);
const messageId = String(frame?.message_id ?? ""); const messageId = String(frame?.message_id ?? "");
@@ -807,10 +817,10 @@ function onChatEvent(frame) {
/** At most one history read per unseen turn, and only for the open conversation. */ /** At most one history read per unseen turn, and only for the open conversation. */
const historySyncTimers = new Map(); const historySyncTimers = new Map();
const historySyncedFor = new Map(); const historySyncedFor = new Map();
function scheduleHistorySync(sessionId, messageId) { function scheduleHistorySync(sessionId, messageId, {force=false} = {}) {
if (!messageId || state.view !== "chat" || sessionId !== state.chatActiveId) return; if ((!messageId && !force) || state.view !== "chat" || sessionId !== state.chatActiveId) return;
if (historySyncedFor.get(sessionId) === messageId) return; if (!force && historySyncedFor.get(sessionId) === messageId) return;
historySyncedFor.set(sessionId, messageId); if (!force) historySyncedFor.set(sessionId, messageId);
if (historySyncTimers.has(sessionId)) return; if (historySyncTimers.has(sessionId)) return;
const timer = setTimeout(() => { const timer = setTimeout(() => {
historySyncTimers.delete(sessionId); historySyncTimers.delete(sessionId);
@@ -1020,10 +1030,14 @@ async function resyncOpenChat() {
} }
/** Load (or reload) a session's newest history page and merge it in. */ /** Load (or reload) a session's newest history page and merge it in. */
const historyReadGenerations = new Map();
async function loadChatHistory(id) { async function loadChatHistory(id) {
const generation=(historyReadGenerations.get(id) ?? 0)+1;
historyReadGenerations.set(id,generation);
const previous = state.chatThreads.get(id) ?? newChatThread(id); const previous = state.chatThreads.get(id) ?? newChatThread(id);
try { try {
const page = await repo.chatHistory(id); const page = await repo.chatHistory(id);
if (historyReadGenerations.get(id)!==generation) return;
// The merged page replaces only the history fields; spreading it over the // The merged page replaces only the history fields; spreading it over the
// held thread keeps the composer's draft, attachments and flags intact (a // held thread keeps the composer's draft, attachments and flags intact (a
// draft typed while the page was loading is not lost). // draft typed while the page was loading is not lost).
@@ -1032,6 +1046,7 @@ async function loadChatHistory(id) {
// the just-delivered interaction (and any draft typed during the read). // the just-delivered interaction (and any draft typed during the read).
setThread(id, mergeHistoryPage(state.chatThreads.get(id) ?? previous, page, { older: false })); setThread(id, mergeHistoryPage(state.chatThreads.get(id) ?? previous, page, { older: false }));
} catch (error) { } catch (error) {
if (historyReadGenerations.get(id)!==generation) return;
setThread(id, { loading: false, loaded: true, error: describeError(error) }); setThread(id, { loading: false, loaded: true, error: describeError(error) });
} }
// A streaming turn triggers this resync after its first unseen message. Keep // A streaming turn triggers this resync after its first unseen message. Keep
@@ -3175,7 +3190,7 @@ function renderChatQuestion(sessionId, form) {
continue; continue;
} }
if (field.type === "boolean") { if (field.type === "boolean") {
const select = h("select", {class:"chat-question-input", "aria-label":field.title || key}, const select = h("select", {class:"chat-question-input", "data-field-key":key, "aria-label":field.title || key},
h("option",{value:"",text:"Choose Yes or No"}),h("option",{value:"true",text:"Yes"}),h("option",{value:"false",text:"No"})); h("option",{value:"",text:"Choose Yes or No"}),h("option",{value:"true",text:"Yes"}),h("option",{value:"false",text:"No"}));
select.value = typeof answers[key] === "boolean" ? String(answers[key]) : ""; select.value = typeof answers[key] === "boolean" ? String(answers[key]) : "";
select.addEventListener("change",()=>{const value=formFieldValue(field,select.value);if(value===undefined)delete answers[key];else answers[key]=value;paintVisibility();}); select.addEventListener("change",()=>{const value=formFieldValue(field,select.value);if(value===undefined)delete answers[key];else answers[key]=value;paintVisibility();});
@@ -3232,6 +3247,7 @@ function renderChatQuestion(sessionId, form) {
if (field.custom === true || options.length === 0) { if (field.custom === true || options.length === 0) {
const input = h("input", { const input = h("input", {
class: "chat-question-input", class: "chat-question-input",
"data-field-key": key,
type: field.secret ? "password" : ["number","integer"].includes(field.type) ? "number" : field.format === "email" ? "email" : field.format === "uri" ? "url" : field.format === "date" ? "date" : "text", type: field.secret ? "password" : ["number","integer"].includes(field.type) ? "number" : field.format === "email" ? "email" : field.format === "uri" ? "url" : field.format === "date" ? "date" : "text",
step: field.type === "number" ? "any" : field.type === "integer" ? "1" : null, step: field.type === "number" ? "any" : field.type === "integer" ? "1" : null,
min: typeof field.minimum === "number" ? String(field.minimum) : null, min: typeof field.minimum === "number" ? String(field.minimum) : null,
+6
View File
@@ -152,6 +152,12 @@ try {
await page.click('.chat-bg-task'); await page.click('.chat-bg-task');
await eventually(()=>page.evaluate("document.querySelector('.chat-bg-task-output')?.textContent==='Controlled background output'")); await eventually(()=>page.evaluate("document.querySelector('.chat-bg-task-output')?.textContent==='Controlled background output'"));
if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'harness-background-output.png')); if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'harness-background-output.png'));
await page.fill('#chatInput','Keep this draft through readback');
await page.evaluate("window.__resyncComposer=document.querySelector('#chatInput')");
assert.equal((await fetch(`http://${target}/fixture-resync`,{method:'POST'})).status,204);
await emit({kind:'resync'});
await eventually(()=>page.evaluate("document.querySelector('#chatTranscript').textContent.includes('Authoritative resync evidence')"));
assert.equal(await page.evaluate("document.querySelector('#chatInput')===window.__resyncComposer && document.querySelector('#chatInput').value==='Keep this draft through readback'"),true);
assert.deepEqual(await page.evaluate("window.__errors"), []); assert.deepEqual(await page.evaluate("window.__errors"), []);
console.log("Model dialog, stable activity mark, keyboard/caret, Back restoration, send-to-bottom and all recovered approvals/questions passed."); console.log("Model dialog, stable activity mark, keyboard/caret, Back restoration, send-to-bottom and all recovered approvals/questions passed.");
} finally { } finally {
+12 -1
View File
@@ -1,6 +1,6 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms, approvalCard } from '../src/chat.js'; import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms, approvalCard, applyChatEvent } from '../src/chat.js';
test('parallel approvals stay independently actionable and resolve by identity',()=>{ test('parallel approvals stay independently actionable and resolve by identity',()=>{
let thread={}; let thread={};
@@ -12,6 +12,17 @@ test('parallel approvals stay independently actionable and resolve by identity',
assert.deepEqual(chatApprovalCards(thread),[]); assert.deepEqual(chatApprovalCards(thread),[]);
}); });
test('native turn identity rejects late completion and resync preserves queued intent',()=>{
let thread=applyChatEvent({messages:[],queued:true},{kind:'step',step:{status:'started',turn_id:'new'}},1);
thread={...thread,queued:true};
assert.equal(applyChatEvent(thread,{kind:'resync'}),thread);
thread=applyChatEvent(thread,{kind:'step',step:{status:'ended',turn_id:'old'}},2);
assert.equal(thread.running,true);
assert.equal(thread.queued,true);
thread=applyChatEvent(thread,{kind:'step',step:{status:'ended',turn_id:'new'}},3);
assert.equal(thread.running,false);
});
test('Codex session-scoped approval is never described as a permanent grant',()=>{ test('Codex session-scoped approval is never described as a permanent grant',()=>{
const card=approvalCard({request_id:'a',always_label:'Allow for session',resolved:true,decision:'always'},''); const card=approvalCard({request_id:'a',always_label:'Allow for session',resolved:true,decision:'always'},'');
assert.equal(card.headline,'Allowed for session'); assert.equal(card.headline,'Allowed for session');