Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7465 fix(chat): stream Codex deltas end to end (#8536)

Multica Eve043821ab77e9
diff --git a/packages/core/realtime/use-realtime-sync-task-messages.test.tsx b/packages/core/realtime/use-realtime-sync-task-messages.test.tsx
index da95f28a67..c1462d197f 100644
--- a/packages/core/realtime/use-realtime-sync-task-messages.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-task-messages.test.tsx
@@ -126,24 +126,23 @@ describe("useRealtimeSync — task:message fanout guards (MUL-6396)", () => {
// Mounting registers the cache entry immediately; the queryFn above has
// not resolved yet. A frame landing in that window must still be kept.
handler(msg(HELD_TASK, 1));
- vi.advanceTimersByTime(FLUSH_MS);
expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1]);
release();
});
- it("coalesces a burst into a single cache write", () => {
+ it("writes a burst's first frame immediately and coalesces its tail", () => {
const handler = mount();
const release = holdTimeline(HELD_TASK);
const writes = vi.spyOn(qc, "setQueryData");
for (let seq = 1; seq <= 5; seq++) handler(msg(HELD_TASK, seq));
- // Nothing is written until the window closes.
- expect(writes).not.toHaveBeenCalled();
+ expect(writes).toHaveBeenCalledTimes(1);
+ expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1]);
vi.advanceTimersByTime(FLUSH_MS);
- expect(writes).toHaveBeenCalledTimes(1);
+ expect(writes).toHaveBeenCalledTimes(2);
expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1, 2, 3, 4, 5]);
release();
});
@@ -177,9 +176,8 @@ describe("useRealtimeSync — task:message fanout guards (MUL-6396)", () => {
const release = holdTimeline(HELD_TASK);
await vi.waitFor(() => expect(listTaskMessages).toHaveBeenCalled());
- // Live frame arrives and flushes while the request is still open.
+ // The leading-edge live frame lands while the request is still open.
handler(msg(HELD_TASK, 2, { content: "live" }));
- vi.advanceTimersByTime(FLUSH_MS);
expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([2]);
// The response was snapshotted before seq 2 was persisted.
@@ -206,8 +204,10 @@ describe("useRealtimeSync — task:message fanout guards (MUL-6396)", () => {
const release = holdTimeline(HELD_TASK);
await vi.waitFor(() => expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1]));
- // Frame batched while the entry is still held, then the viewer closes.
+ // The leading edge writes immediately. The second frame is batched while
+ // the entry is still held, then the viewer closes.
handler(msg(HELD_TASK, 2, { content: "live" }));
+ handler(msg(HELD_TASK, 3, { content: "batched tail" }));
release();
// GC lands first (50ms), flush second (100ms).
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 7fcfcbde24..6d910b3fb8 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -125,11 +125,10 @@ const chatWsLogger = createLogger("chat.ws");
* Window over which incoming `task:message` frames are batched into a single
* timeline cache write (MUL-6396).
*
- * A fixed window, armed on the first frame and not reset by later ones, so a
- * sustained stream still lands every 100ms rather than being deferred until
- * the stream pauses. Short enough that streamed text still reads as live;
- * long enough that a run emitting several frames per second costs one merge
- * and one render instead of one per frame.
+ * The first frame after an idle window lands immediately; that is the
+ * user-visible leading edge. It also arms a fixed 100ms window for subsequent
+ * frames, not reset by later ones, so a sustained stream still costs at most
+ * one additional merge/render per window instead of one per frame.
*/
const TASK_MESSAGE_FLUSH_MS = 100;
@@ -1388,27 +1387,29 @@ export function useRealtimeSync(
const taskMessageBatches = new Map<string, TaskMessagePayload[]>();
let taskMessageFlushTimer: ReturnType<typeof setTimeout> | null = null;
+ const writeTaskMessageBatch = (taskId: string, batch: TaskMessagePayload[]) => {
+ // Re-check, because a queued batch may be up to one window old and
+ // `setQueryData` does NOT postpone garbage collection — query-core arms
+ // that timer when the last observer leaves and never again on write.
+ // Closing a transcript while its run keeps streaming therefore has the
+ // entry disappear mid-window, and writing then REBUILDS it holding only
+ // this batch. With the app-wide `staleTime: Infinity` the next open
+ // would read that stub as fresh and never fetch, so everything before it
+ // would be missing until the window is reloaded. Dropping the batch
+ // instead costs nothing: the rows are persisted, so the next open fetches
+ // the whole timeline.
+ if (!isTaskMessageTimelineHeld(qc, taskId)) return;
+ qc.setQueryData<TaskMessagePayload[]>(
+ chatKeys.taskMessages(taskId),
+ (old = []) => mergeTaskMessagesBySeq(old, batch),
+ );
+ };
+
const flushTaskMessages = () => {
taskMessageFlushTimer = null;
for (const [taskId, batch] of taskMessageBatches) {
- // Re-check, because holding was last verified up to a window ago and
- // `setQueryData` does NOT postpone garbage collection — query-core arms
- // that timer when the last observer leaves and never again on write.
- // Closing a transcript while its run keeps streaming therefore has the
- // entry disappear mid-window, and writing then REBUILDS it holding only
- // this batch. With the app-wide `staleTime: Infinity` the next open
- // would read that stub as fresh and never fetch, so everything before
- // it would be missing until the window is reloaded. Dropping the batch
- // instead costs nothing: the rows are persisted, so the next open
- // fetches the whole timeline.
- if (!isTaskMessageTimelineHeld(qc, taskId)) {
- continue;
- }
- qc.setQueryData<TaskMessagePayload[]>(
- chatKeys.taskMessages(taskId),
- (old = []) => mergeTaskMessagesBySeq(old, batch),
- );
+ writeTaskMessageBatch(taskId, batch);
}
taskMessageBatches.clear();
};
@@ -1419,14 +1420,17 @@ export function useRealtimeSync(
// hot path for every run in the workspace, not just the visible ones.
if (!isTaskMessageTimelineHeld(qc, payload.task_id)) return;
- const batch = taskMessageBatches.get(payload.task_id);
- if (batch) batch.push(payload);
- else taskMessageBatches.set(payload.task_id, [payload]);
-
- // Fixed window, not a resetting debounce: a continuous stream must still
- // flush every TASK_MESSAGE_FLUSH_MS instead of being starved until a gap.
+ // Leading edge: render the first frame after an idle window now. The
+ // timer is still armed so the remainder of a burst is coalesced and a
+ // continuous stream cannot render more than once per fixed window after
+ // this one immediate write.
if (!taskMessageFlushTimer) {
+ writeTaskMessageBatch(payload.task_id, [payload]);
taskMessageFlushTimer = setTimeout(flushTaskMessages, TASK_MESSAGE_FLUSH_MS);
+ } else {
+ const batch = taskMessageBatches.get(payload.task_id);
+ if (batch) batch.push(payload);
+ else taskMessageBatches.set(payload.task_id, [payload]);
}
chatWsLogger.debug("task:message (global)", {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index c9a93ed724..bf6f88bf71 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -9419,17 +9419,30 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
done := make(chan struct{})
tickerDone := make(chan struct{})
+ firstVisible := make(chan struct{}, 1)
go func() {
defer close(tickerDone)
for {
select {
case <-ticker.C:
flush()
+ case <-firstVisible:
+ flush()
case <-done:
return
}
}
}()
+ // The periodic flush bounds request rate for the rest of the transcript,
+ // but making the first visible event wait for its next 500 ms edge adds
+ // pure presentation latency. Signal at most once per execution; a buffered
+ // channel keeps the drain loop non-blocking while the reporter is busy.
+ var firstVisibleOnce sync.Once
+ flushFirstVisible := func() {
+ firstVisibleOnce.Do(func() {
+ firstVisible <- struct{}{}
+ })
+ }
var sessionPinned atomic.Bool
for {
@@ -9512,6 +9525,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
Input: redact.InputMap(msg.Input),
})
mu.Unlock()
+ flushFirstVisible()
case agent.MessageToolResult:
// Decrement only when the count would stay >= 0. A stray
// tool_result with no matching tool_use (backend bug or
@@ -9549,13 +9563,20 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
OutputTruncated: &outputTruncated,
})
mu.Unlock()
+ flushFirstVisible()
case agent.MessageThinking:
appendPending("thinking", msg.Content, observedAt)
+ if msg.Content != "" {
+ flushFirstVisible()
+ }
case agent.MessageText:
if msg.Content != "" {
taskLog.Debug("agent", "text", truncateLog(msg.Content, 200))
}
appendPending("text", msg.Content, observedAt)
+ if msg.Content != "" {
+ flushFirstVisible()
+ }
case agent.MessageError:
taskLog.Error("agent error", "content", msg.Content)
mu.Lock()
@@ -9568,6 +9589,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
CreatedAt: observedAt,
})
mu.Unlock()
+ flushFirstVisible()
}
case <-drainCtx.Done():
goto drainDone
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index faa6a03e0e..135788ad2d 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -2691,6 +2691,84 @@ func TestExecuteAndDrain_FlushesTranscriptBeforeReturningResult(t *testing.T) {
}
}
+type firstVisibleTranscriptBackend struct {
+ emitted chan time.Time
+ release chan struct{}
+}
+
+func (b firstVisibleTranscriptBackend) Execute(ctx context.Context, _ string, _ agent.ExecOptions) (*agent.Session, error) {
+ msgCh := make(chan agent.Message)
+ resCh := make(chan agent.Result, 1)
+ go func() {
+ defer close(msgCh)
+ msgCh <- agent.Message{Type: agent.MessageText, Content: "first visible text"}
+ b.emitted <- time.Now()
+ select {
+ case <-b.release:
+ resCh <- agent.Result{Status: "completed", Output: "done"}
+ case <-ctx.Done():
+ resCh <- agent.Result{Status: "cancelled", Error: ctx.Err().Error()}
+ }
+ close(resCh)
+ }()
+ return &agent.Session{Messages: msgCh, Result: resCh}, nil
+}
+
+// TestExecuteAndDrain_ReportsFirstVisibleMessageWithoutTickerDelay pins the
+// leading edge of the daemon-to-server path. Later chunks remain batched, but
+// the first user-visible content must not sit behind the 500 ms periodic flush.
+func TestExecuteAndDrain_ReportsFirstVisibleMessageWithoutTickerDelay(t *testing.T) {
+ emitted := make(chan time.Time, 1)
+ release := make(chan struct{})
+ reported := make(chan time.Time, 1)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/messages") {
+ var body struct {
+ Messages []TaskMessageData `json:"messages"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode messages: %v", err)
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ if len(body.Messages) > 0 {
+ select {
+ case reported <- time.Now():
+ default:
+ }
+ }
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{client: NewClient(srv.URL), logger: slog.Default()}
+ done := make(chan error, 1)
+ go func() {
+ _, _, err := d.executeAndDrain(context.Background(), firstVisibleTranscriptBackend{
+ emitted: emitted,
+ release: release,
+ }, "p", agent.ExecOptions{}, slog.Default(), "task-first-visible", "", new(atomic.Int32))
+ done <- err
+ }()
+
+ emittedAt := <-emitted
+ select {
+ case reportedAt := <-reported:
+ delay := reportedAt.Sub(emittedAt)
+ t.Logf("first visible message reached the server in %s", delay.Round(time.Millisecond))
+ if delay >= 300*time.Millisecond {
+ t.Fatalf("first visible message report delay = %s, want <300ms", delay.Round(time.Millisecond))
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for first visible message report")
+ }
+ close(release)
+ if err := <-done; err != nil {
+ t.Fatalf("executeAndDrain: %v", err)
+ }
+}
+
// timedTranscriptBackend keeps a tool open long enough to prove the daemon
// records event occurrence time rather than giving a whole flush batch one
// server insertion time.
@@ -2765,20 +2843,33 @@ func TestExecuteAndDrain_ReportsFirstBufferedChunkTimestamp(t *testing.T) {
}
got := rec.snapshot()
- if len(got) != 2 {
- t.Fatalf("reported %d messages, want thinking and text: %+v", len(got), got)
+ var thinking, text strings.Builder
+ var thinkingAt, textAt time.Time
+ for _, message := range got {
+ switch message.Type {
+ case "thinking":
+ thinking.WriteString(message.Content)
+ if thinkingAt.IsZero() {
+ thinkingAt = message.CreatedAt
+ }
+ case "text":
+ text.WriteString(message.Content)
+ if textAt.IsZero() {
+ textAt = message.CreatedAt
+ }
+ }
}
- if got[0].Type != "thinking" || got[0].Content != "think one think two" {
- t.Fatalf("thinking message = %+v", got[0])
+ if thinking.String() != "think one think two" {
+ t.Fatalf("thinking content = %q, want complete ordered chunks; messages=%+v", thinking.String(), got)
}
- if boundary := <-backend.thinkingSecondStartedAt; !got[0].CreatedAt.Before(boundary) {
- t.Fatalf("thinking created_at = %s, want before second chunk started at %s", got[0].CreatedAt, boundary)
+ if boundary := <-backend.thinkingSecondStartedAt; !thinkingAt.Before(boundary) {
+ t.Fatalf("first thinking created_at = %s, want before second chunk started at %s", thinkingAt, boundary)
}
- if got[1].Type != "text" || got[1].Content != "text one text two" {
- t.Fatalf("text message = %+v", got[1])
+ if text.String() != "text one text two" {
+ t.Fatalf("text content = %q, want complete ordered chunks; messages=%+v", text.String(), got)
}
- if boundary := <-backend.textSecondStartedAt; !got[1].CreatedAt.Before(boundary) {
- t.Fatalf("text created_at = %s, want before second chunk started at %s", got[1].CreatedAt, boundary)
+ if boundary := <-backend.textSecondStartedAt; !textAt.Before(boundary) {
+ t.Fatalf("first text created_at = %s, want before second chunk started at %s", textAt, boundary)
}
}
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index 1a9dd2ddf6..f66bae1211 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -698,12 +698,14 @@ type claudeControlRequestPayload struct {
// ── Shared helpers ──
-func trySend(ch chan<- Message, msg Message) {
+func trySend(ch chan<- Message, msg Message) bool {
select {
case ch <- msg:
+ return true
default:
// Channel full — drop message. Result.Output is finalized independently,
// so only live transcript consumers are affected.
+ return false
}
}
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 2845308392..98de9bfdf4 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -79,6 +79,14 @@ const (
// their default separate without slowing failures for lightweight RPCs.
defaultCodexThreadHandshakeTimeout = 60 * time.Second
codexVersionDiagnosticTimeout = 2 * time.Second
+ // Keep a raw agent-message tail small enough that a slow daemon does not
+ // make the stdout reader retain token-sized channel entries indefinitely.
+ // At one sixty-fourth of the scanner's maximum completed-snapshot line, any
+ // reconcilable item occupies at most 65 of the 256 message slots (the leading
+ // delta plus 64 aggregates), reserving the rest for status and tool events.
+ // A single provider event may be larger, in which case that event is flushed
+ // as one chunk rather than split at an arbitrary byte boundary.
+ codexAgentMessageAggregateBytes = agentStreamMaxLineBytes / 64
// codexGracefulShutdownTimeout bounds how long the lifecycle goroutine
// waits for codex to exit on its own after stdin is closed, before forcing
// a context-cancel kill. A clean exit lets codex run its shutdown path and
@@ -1198,6 +1206,18 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// race between the lifecycle goroutine writing and the reader reading.
turnDone := make(chan bool, 1) // true = aborted
+ observeMessage := func(msg Message) {
+ logCodexAgentMessage(b.cfg.Logger, msg)
+ activity := describeCodexSemanticActivity(msg)
+ if activity == "status:running" {
+ firstItemWait.start(time.Now())
+ }
+ trySendString(semanticActivityCh, activity)
+ if activity != "" {
+ semanticObserved.Store(true)
+ }
+ }
+
c := &codexClient{
cfg: b.cfg,
stdin: stdin,
@@ -1217,21 +1237,27 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
semanticObserved.Store(true)
},
onMessage: func(msg Message) {
- logCodexAgentMessage(b.cfg.Logger, msg)
- if msg.Type == MessageText {
- outputMu.Lock()
- lastAgentMessage = msg.Content
- outputMu.Unlock()
- }
- activity := describeCodexSemanticActivity(msg)
- if activity == "status:running" {
- firstItemWait.start(time.Now())
- }
+ observeMessage(msg)
trySend(msgCh, msg)
- trySendString(semanticActivityCh, activity)
- if activity != "" {
- semanticObserved.Store(true)
- }
+ },
+ onAgentMessageChunk: func(text string) bool {
+ msg := Message{Type: MessageText, Content: text}
+ observeMessage(msg)
+ // Agent text is the user-visible transcript, so unlike auxiliary
+ // progress events it participates in reconciliation. A false return
+ // leaves the text pending for completed/terminal/EOF retry. Keep the
+ // send non-blocking because Session.Messages is optional; bounded
+ // coalescing prevents a token burst from filling the channel while
+ // preserving the reader's EOF and cancellation liveness.
+ return trySend(msgCh, msg)
+ },
+ onAgentMessage: func(text string) {
+ // Delta events make MessageText incremental. Keep Result.Output's
+ // legacy fallback authoritative by updating it from the completed
+ // agent-message snapshot, not whichever delta happened to arrive last.
+ outputMu.Lock()
+ lastAgentMessage = text
+ outputMu.Unlock()
},
onFinalAnswer: func(text string) {
outputMu.Lock()
@@ -1263,6 +1289,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
c.handleLine(line)
}
+ // A cancelled or crashed app-server may close stdout without an
+ // item/completed snapshot. Preserve every complete delta JSON event
+ // already parsed; an incomplete final JSON token is ignored by
+ // handleLine and can never enter this buffer.
+ c.flushAgentMessageDeltas()
if err := scanner.Err(); err != nil {
// %w on BOTH: callers match errCodexProcessExited to decide the
// process is gone, and bufio.ErrTooLong to tell "we could not read
@@ -2308,8 +2339,17 @@ type codexClient struct {
turnIDMu sync.RWMutex
turnID string
onMessage func(Message)
- onSemanticActivity func(description string)
- onTurnDone func(aborted bool)
+ // onAgentMessageChunk reports whether a text chunk was handed to the
+ // daemon-facing message channel. Raw delta reconciliation advances only on
+ // true, so channel pressure cannot turn observed provider bytes into a false
+ // delivered prefix. Unit clients may leave this nil and use onMessage.
+ onAgentMessageChunk func(text string) bool
+ // onAgentMessage receives the authoritative completed text for one agent
+ // message. onAgentMessageChunk may deliver that text incrementally, so
+ // Result.Output fallbacks must use this callback rather than the last chunk.
+ onAgentMessage func(text string)
+ onSemanticActivity func(description string)
+ onTurnDone func(aborted bool)
// onFinalAnswer fires only for an agent message the app-server itself
// labelled `phase: "final_answer"` — the turn's deliverable, as opposed to
// the intermediate agent messages that narrate work between tool calls.
@@ -2324,6 +2364,12 @@ type codexClient struct {
// suppressing an initialize retry after observed activity) without letting
// filtered history mutate current-turn output or lifecycle state.
onDiscardedNotification func(method string, params map[string]any)
+ // agentMessageStreams tracks raw-v2 agent text on the single stdout reader.
+ // The first delta is handed off immediately; subsequent deltas are aggregated
+ // into bounded chunks and reconciled against item/completed. delivered is
+ // advanced only after onAgentMessageChunk confirms daemon handoff.
+ agentMessageStreams map[string]*codexAgentMessageStream
+ agentMessageOrder []string
notificationProtocol string // "unknown", "legacy", "raw"
turnCompleted bool
@@ -2340,6 +2386,11 @@ type codexClient struct {
turnError string // captured from turn/completed status=failed or terminal error notifications
}
+type codexAgentMessageStream struct {
+ delivered strings.Builder
+ pending strings.Builder
+}
+
// codexTurnNotificationGate keeps resume-time history replay from mutating the
// output or ending the new turn. Codex app-server can emit notifications before
// the turn/start RPC response, so the gate is armed before that request and uses
@@ -3280,6 +3331,9 @@ func (c *codexClient) handleEvent(msg map[string]any) {
if text != "" && c.onMessage != nil {
c.onMessage(Message{Type: MessageText, Content: text})
}
+ if text != "" && c.onAgentMessage != nil {
+ c.onAgentMessage(text)
+ }
case "exec_command_begin":
callID, _ := msg["call_id"].(string)
command, _ := msg["command"].(string)
@@ -3403,6 +3457,11 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any
c.extractUsageFromMap(turn)
}
+ // Some cancellation and transport-failure paths do not emit an
+ // item/completed snapshot. Flush the aggregate of every complete delta
+ // notification before publishing the terminal boundary.
+ c.flushAgentMessageDeltas()
+
if c.onTurnDone != nil {
c.onTurnDone(aborted)
}
@@ -3452,18 +3511,155 @@ func (c *codexClient) isNotificationFromOtherThread(params map[string]any) bool
return currentThreadID != "" && threadID != currentThreadID
}
+func (c *codexClient) emitAgentMessageChunk(text string) bool {
+ if text == "" {
+ return true
+ }
+ if c.onAgentMessageChunk != nil {
+ return c.onAgentMessageChunk(text)
+ }
+ if c.onMessage != nil {
+ c.onMessage(Message{Type: MessageText, Content: text})
+ return true
+ }
+ return false
+}
+
+func (c *codexClient) agentMessageStream(itemID string) *codexAgentMessageStream {
+ if c.agentMessageStreams == nil {
+ c.agentMessageStreams = make(map[string]*codexAgentMessageStream)
+ }
+ stream := c.agentMessageStreams[itemID]
+ if stream == nil {
+ stream = &codexAgentMessageStream{}
+ c.agentMessageStreams[itemID] = stream
+ c.agentMessageOrder = append(c.agentMessageOrder, itemID)
+ }
+ return stream
+}
+
+func (c *codexClient) handleAgentMessageDelta(itemID, delta string) {
+ if itemID == "" || delta == "" {
+ return
+ }
+
+ stream := c.agentMessageStream(itemID)
+ // The leading delta is the latency-critical event. Deliver it immediately;
+ // coalesce the rest so a burst of token notifications cannot fill the
+ // daemon channel before its consumer is scheduled.
+ if stream.delivered.Len() == 0 && stream.pending.Len() == 0 {
+ if c.emitAgentMessageChunk(delta) {
+ stream.delivered.WriteString(delta)
+ return
+ }
+ }
+
+ stream.pending.WriteString(delta)
+ if stream.pending.Len() >= codexAgentMessageAggregateBytes {
+ c.flushAgentMessageStream(stream)
+ }
+}
+
+func (c *codexClient) flushAgentMessageStream(stream *codexAgentMessageStream) bool {
+ if stream == nil || stream.pending.Len() == 0 {
+ return true
+ }
+ text := stream.pending.String()
+ if !c.emitAgentMessageChunk(text) {
+ return false
+ }
+ stream.delivered.WriteString(text)
+ stream.pending.Reset()
+ return true
+}
+
+// flushAgentMessageDeltas preserves complete delta events when a turn is
+// cancelled or stdout ends before item/completed. agentMessageOrder retains
+// provider order; iterating the map directly would make two unfinished items
+// nondeterministic.
+func (c *codexClient) flushAgentMessageDeltas() {
+ for _, itemID := range c.agentMessageOrder {
+ stream := c.agentMessageStreams[itemID]
+ if stream == nil {
+ continue
+ }
+ if c.flushAgentMessageStream(stream) {
+ delete(c.agentMessageStreams, itemID)
+ }
+ }
+}
+
+func (c *codexClient) completeAgentMessage(itemID, text string) {
+ stream := c.agentMessageStreams[itemID]
+ if text == "" {
+ if c.flushAgentMessageStream(stream) {
+ delete(c.agentMessageStreams, itemID)
+ }
+ return
+ }
+
+ delivered := ""
+ if stream != nil {
+ delivered = stream.delivered.String()
+ } else {
+ stream = c.agentMessageStream(itemID)
+ }
+
+ if !strings.HasPrefix(text, delivered) {
+ // Already-persisted text cannot be retracted without a new event/schema.
+ // Appending the full snapshot would duplicate it, but every complete delta
+ // event still belongs in the append-only transcript. Flush pending normally;
+ // if the channel refuses it, leave the stream intact for terminal/EOF retry.
+ // onAgentMessage remains the authoritative Result.Output fallback.
+ if c.cfg.Logger != nil {
+ c.cfg.Logger.Warn("codex agent-message delta did not match completed text",
+ "item_id", itemID, "delivered_bytes", len(delivered), "completed_bytes", len(text))
+ }
+ if c.flushAgentMessageStream(stream) {
+ delete(c.agentMessageStreams, itemID)
+ }
+ return
+ }
+
+ // With an acknowledged prefix match, the completed snapshot supersedes
+ // observed-but-unacknowledged bytes and supplies their authoritative suffix.
+ stream.pending.Reset()
+ suffix := strings.TrimPrefix(text, delivered)
+ if suffix == "" || c.emitAgentMessageChunk(suffix) {
+ delete(c.agentMessageStreams, itemID)
+ return
+ }
+ // A process cancellation can race the final handoff. Keep the authoritative
+ // suffix so the stdout-EOF flush gets one more chance without duplicating the
+ // prefix that was already accepted.
+ stream.pending.WriteString(suffix)
+}
+
func (c *codexClient) handleItemNotification(method string, params map[string]any) {
item, _ := params["item"].(map[string]any)
itemType, _ := item["type"].(string)
itemID, _ := item["id"].(string)
+ if method == "item/agentMessage/delta" {
+ // Unlike item/started and item/completed, the real app-server delta
+ // schema is flat: {threadId, turnId, itemId, delta}.
+ itemType = "agentMessage"
+ itemID, _ = params["itemId"].(string)
+ }
if isCodexItemProgressActivity(method) && c.onSemanticActivity != nil {
c.onSemanticActivity(describeCodexItemProgressActivity(method, itemType, itemID))
}
- if item == nil {
+ if item == nil && method != "item/agentMessage/delta" {
return
}
switch {
+ case method == "item/agentMessage/delta" && itemType == "agentMessage":
+ // JSON-RPC framing remains authoritative: handleLine invokes us only
+ // after a whole newline-delimited JSON event parsed successfully. Stream
+ // the event's text payload, not arbitrary stdout bytes.
+ delta, _ := params["delta"].(string)
+ c.handleAgentMessageDelta(itemID, delta)
+
case method == "item/started" && itemType == "commandExecution":
command, _ := item["command"].(string)
if c.onMessage != nil {
@@ -3532,9 +3728,10 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an
case method == "item/completed" && itemType == "agentMessage":
text, _ := item["text"].(string)
- if text != "" && c.onMessage != nil {
- c.onMessage(Message{Type: MessageText, Content: text})
+ if text != "" && c.onAgentMessage != nil {
+ c.onAgentMessage(text)
}
+ c.completeAgentMessage(itemID, text)
phase, _ := item["phase"].(string)
if phase == "final_answer" {
// The gate exists so a subagent or a replayed history turn cannot
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 922cb7167b..4ffb3698da 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"log/slog"
"os"
"path/filepath"
@@ -1414,11 +1415,283 @@ func TestCodexRawItemAgentMessageFinalAnswerWaitsForTurnCompleted(t *testing.T)
}
}
+func TestCodexRawItemAgentMessageReconciliation(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ deltas []string
+ completed string
+ rejectFirstHandoff bool
+ wantStream string
+ wantAuthoritativeOut string
+ }{
+ {
+ name: "exact prefix is not duplicated",
+ deltas: []string{"Hel", "lo"},
+ completed: "Hello",
+ wantStream: "Hello",
+ wantAuthoritativeOut: "Hello",
+ },
+ {
+ name: "completed fills a missing last delta",
+ deltas: []string{"Hel"},
+ completed: "Hello",
+ wantStream: "Hello",
+ wantAuthoritativeOut: "Hello",
+ },
+ {
+ name: "unacknowledged delta is not counted as delivered",
+ deltas: []string{"Hel"},
+ completed: "Hello",
+ rejectFirstHandoff: true,
+ wantStream: "Hello",
+ wantAuthoritativeOut: "Hello",
+ },
+ {
+ name: "mismatch keeps append-only stream without duplicating snapshot",
+ deltas: []string{"Hx", "llo"},
+ completed: "Hello",
+ wantStream: "Hxllo",
+ wantAuthoritativeOut: "Hello",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+
+ var chunks []string
+ var completed string
+ handoffs := 0
+ c.onAgentMessageChunk = func(text string) bool {
+ handoffs++
+ if tt.rejectFirstHandoff && handoffs == 1 {
+ return false
+ }
+ chunks = append(chunks, text)
+ return true
+ }
+ c.onAgentMessage = func(text string) { completed = text }
+
+ for _, delta := range tt.deltas {
+ c.handleLine(fmt.Sprintf(`{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-1","turnId":"turn-1","itemId":"msg-1","delta":%q}}`, delta))
+ }
+ // item/completed keeps its documented nested item; itemId is flat only
+ // on item/agentMessage/delta.
+ c.handleLine(fmt.Sprintf(`{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-1","turnId":"turn-1","item":{"type":"agentMessage","id":"msg-1","text":%q}}}`, tt.completed))
+
+ if got := strings.Join(chunks, ""); got != tt.wantStream {
+ t.Fatalf("streamed text = %q, want %q exactly once (chunks=%q)", got, tt.wantStream, chunks)
+ }
+ if completed != tt.wantAuthoritativeOut {
+ t.Fatalf("authoritative output = %q, want %q", completed, tt.wantAuthoritativeOut)
+ }
+ })
+ }
+}
+
+func TestCodexRawAgentMessageMismatchRetriesRejectedPendingAtTerminal(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ messages := make(chan Message, 2)
+ c.onAgentMessageChunk = func(text string) bool {
+ return trySend(messages, Message{Type: MessageText, Content: text})
+ }
+ var completed string
+ c.onAgentMessage = func(text string) { completed = text }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"itemId":"msg-1","delta":"Hx"}}`)
+ // Fill the remaining slot after Hx was accepted. The mismatch path's first
+ // attempt to hand off pending "llo" must fail without clearing it.
+ messages <- Message{Type: MessageStatus, Status: "filler"}
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"itemId":"msg-1","delta":"llo"}}`)
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg-1","text":"Hello"}}}`)
+
+ stream := c.agentMessageStreams["msg-1"]
+ if stream == nil {
+ t.Fatal("rejected mismatch pending stream was deleted")
+ }
+ if got := stream.pending.String(); got != "llo" {
+ t.Fatalf("rejected mismatch pending = %q, want retained llo", got)
+ }
+ first := <-messages
+ if first.Type != MessageText || first.Content != "Hx" {
+ t.Fatalf("first delivered message = %+v, want Hx", first)
+ }
+
+ // Consuming Hx frees one slot. The terminal flush must retry llo exactly
+ // once, then clear the stream without appending completed="Hello".
+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"id":"turn-1","status":"completed"}}}`)
+ var tail strings.Builder
+ for len(messages) > 0 {
+ msg := <-messages
+ if msg.Type == MessageText {
+ tail.WriteString(msg.Content)
+ }
+ }
+ c.flushAgentMessageDeltas()
+ if len(messages) != 0 {
+ t.Fatalf("second terminal/EOF flush duplicated text: %+v", <-messages)
+ }
+ if got := first.Content + tail.String(); got != "Hxllo" {
+ t.Fatalf("append-only mismatch transcript = %q, want Hxllo", got)
+ }
+ if completed != "Hello" {
+ t.Fatalf("authoritative completed output = %q, want Hello", completed)
+ }
+ if c.agentMessageStreams["msg-1"] != nil {
+ t.Fatal("mismatch stream remained after successful terminal retry")
+ }
+}
+
+func TestCodexRawAgentMessageBurstDoesNotLoseTextUnderChannelPressure(t *testing.T) {
+ t.Parallel()
+
+ for _, status := range []string{"completed", "interrupted"} {
+ status := status
+ t.Run(status, func(t *testing.T) {
+ t.Parallel()
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ messages := make(chan Message, 256)
+ c.onAgentMessageChunk = func(text string) bool {
+ return trySend(messages, Message{Type: MessageText, Content: text})
+ }
+
+ var want strings.Builder
+ for i := 0; i < 300; i++ {
+ delta := fmt.Sprintf("%03d", i)
+ want.WriteString(delta)
+ c.handleLine(fmt.Sprintf(`{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-1","turnId":"turn-1","itemId":"msg-1","delta":%q}}`, delta))
+ }
+ // There is deliberately no item/completed. A terminal turn must flush
+ // the coalesced tail for both normal and cancellation paths.
+ c.handleLine(fmt.Sprintf(`{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-1","turn":{"id":"turn-1","status":%q}}}`, status))
+
+ var got strings.Builder
+ for len(messages) > 0 {
+ got.WriteString((<-messages).Content)
+ }
+ if got.String() != want.String() {
+ t.Fatalf("delivered %d/%d bytes under pressure", got.Len(), want.Len())
+ }
+ })
+ }
+}
+
+func TestCodexRawAgentMessageDeltaFraming(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ text := make(chan string, 1)
+ c.onAgentMessageChunk = func(chunk string) bool {
+ text <- chunk
+ return true
+ }
+
+ reader, writer := io.Pipe()
+ done := make(chan error, 1)
+ go func() {
+ scanner := newAgentStreamScanner(reader)
+ for scanner.Scan() {
+ c.handleLine(strings.TrimSpace(scanner.Text()))
+ }
+ c.flushAgentMessageDeltas()
+ done <- scanner.Err()
+ }()
+
+ first := `{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-1","turnId":"turn-1","itemId":"msg-1","delta":"Hel`
+ if _, err := writer.Write([]byte(first)); err != nil {
+ t.Fatalf("write first JSON fragment: %v", err)
+ }
+ select {
+ case leaked := <-text:
+ t.Fatalf("incomplete JSON bytes leaked as text: %q", leaked)
+ default:
+ }
+ if _, err := writer.Write([]byte("lo\"}}\n")); err != nil {
+ t.Fatalf("write final JSON fragment: %v", err)
+ }
+ if got := <-text; got != "Hello" {
+ t.Fatalf("complete JSON delta = %q, want Hello", got)
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatalf("close pipe: %v", err)
+ }
+ if err := <-done; err != nil {
+ t.Fatalf("scan split JSON: %v", err)
+ }
+}
+
+func TestCodexRawAgentMessageMalformedAndIncompleteEOFDoNotLeak(t *testing.T) {
+ t.Parallel()
+
+ for _, input := range []string{
+ "not-json\n",
+ `{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"itemId":"msg-1","delta":"must not leak"}`,
+ } {
+ input := input
+ t.Run(input[:min(len(input), 8)], func(t *testing.T) {
+ t.Parallel()
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ var chunks []string
+ c.onAgentMessageChunk = func(chunk string) bool {
+ chunks = append(chunks, chunk)
+ return true
+ }
+ scanner := newAgentStreamScanner(strings.NewReader(input))
+ for scanner.Scan() {
+ c.handleLine(scanner.Text())
+ }
+ c.flushAgentMessageDeltas()
+ if err := scanner.Err(); err != nil {
+ t.Fatalf("scan malformed fixture: %v", err)
+ }
+ if len(chunks) != 0 {
+ t.Fatalf("malformed/incomplete JSON leaked text: %q", chunks)
+ }
+ })
+ }
+}
+
+func TestCodexRawAgentMessageAbnormalEOFFlushesCompleteDeltas(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ var chunks []string
+ c.onAgentMessageChunk = func(chunk string) bool {
+ chunks = append(chunks, chunk)
+ return true
+ }
+ input := "" +
+ `{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"itemId":"msg-1","delta":"Hel"}}` + "\n" +
+ `{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"itemId":"msg-1","delta":"lo"}}` + "\n"
+ scanner := newAgentStreamScanner(strings.NewReader(input))
+ for scanner.Scan() {
+ c.handleLine(scanner.Text())
+ }
+ c.flushAgentMessageDeltas()
+ if err := scanner.Err(); err != nil {
+ t.Fatalf("scan EOF fixture: %v", err)
+ }
+ if got := strings.Join(chunks, ""); got != "Hello" {
+ t.Fatalf("abnormal EOF delivered %q, want Hello", got)
+ }
+}
+
// TestCodexDeliverableOutputExcludesNarration pins Result.Output to the turn's
// deliverable. Codex used to concatenate every agent message, so a tool-using
// run shipped its intermediate narration to Slack and Lark along with the answer
-// (GH #6006). The wiring mirrors executeOnce: onMessage tracks the last agent
-// message, onFinalAnswer captures the phase-labelled one, and
+// (GH #6006). The wiring mirrors executeOnce: onAgentMessage tracks the last
+// authoritative completed message, onFinalAnswer captures the phase-labelled one, and
// codexDeliverableOutput picks between them.
func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {
t.Parallel()
@@ -1468,10 +1741,10 @@ func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {
var streamed []string
c.onMessage = func(msg Message) {
if msg.Type == MessageText {
- lastAgentMessage = msg.Content
streamed = append(streamed, msg.Content)
}
}
+ c.onAgentMessage = func(text string) { lastAgentMessage = text }
c.onFinalAnswer = func(text string) { finalAnswer = text }
for _, line := range tc.lines {
@@ -3260,6 +3533,7 @@ func TestCodexExecuteCancellationInterruptsTurnAndPreservesUsage(t *testing.T) {
`read line`+"\n"+
`echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
`echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-cancel-usage","turn":{"id":"turn-cancel-usage"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-cancel-usage","turnId":"turn-cancel-usage","itemId":"msg-partial","delta":"partial before cancel"}}'`+"\n"+
`echo started > `+startedPath+"\n"+
`read line`+"\n"+
`printf '%s\n' "$line" > `+interruptPath+"\n"+
@@ -3282,8 +3556,15 @@ func TestCodexExecuteCancellationInterruptsTurnAndPreservesUsage(t *testing.T) {
if err != nil {
t.Fatalf("execute: %v", err)
}
+ var messagesMu sync.Mutex
+ var messages []Message
+ messagesDone := make(chan struct{})
go func() {
- for range session.Messages {
+ defer close(messagesDone)
+ for message := range session.Messages {
+ messagesMu.Lock()
+ messages = append(messages, message)
+ messagesMu.Unlock()
}
}()
@@ -3317,6 +3598,18 @@ func TestCodexExecuteCancellationInterruptsTurnAndPreservesUsage(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatal("timeout waiting for cancelled Codex result")
}
+ <-messagesDone
+ messagesMu.Lock()
+ var partial string
+ for _, message := range messages {
+ if message.Type == MessageText {
+ partial += message.Content
+ }
+ }
+ messagesMu.Unlock()
+ if partial != "partial before cancel" {
+ t.Fatalf("cancelled turn streamed text = %q, want its pre-cancel delta preserved", partial)
+ }
rawInterrupt, err := os.ReadFile(interruptPath)
if err != nil {
@@ -3690,7 +3983,7 @@ func TestCodexExecuteSemanticInactivityAllowsContinuousDeltaProgress(t *testing.
`echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-delta","turn":{"id":"turn-delta"}}}'`+"\n"+
`echo '{"jsonrpc":"2.0","method":"item/commandExecution/outputDelta","params":{"threadId":"thr-delta","item":{"type":"commandExecution","id":"cmd-1"},"delta":"line 1\n"}}'`+"\n"+
`sleep 0.05`+"\n"+
- `echo '{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-delta","item":{"type":"agentMessage","id":"msg-1"},"delta":"thinking"}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-delta","turnId":"turn-delta","itemId":"msg-1","delta":"thinking"}}'`+"\n"+
`sleep 0.05`+"\n"+
`echo '{"jsonrpc":"2.0","method":"item/fileChange/outputDelta","params":{"threadId":"thr-delta","item":{"type":"fileChange","id":"patch-1"},"delta":"patched"}}'`+"\n"+
`sleep 0.05`+"\n"+
@@ -3707,6 +4000,108 @@ func TestCodexExecuteSemanticInactivityAllowsContinuousDeltaProgress(t *testing.
}
}
+// TestCodexExecuteStreamsCompleteJSONDeltaBeforeItemCompleted is the latency
+// regression for chat: app-server emits agent text as JSON-RPC delta events
+// before the authoritative item/completed snapshot. A JSON event may itself be
+// split across pipe writes, so no text is visible until its newline-delimited
+// frame is complete; once complete, however, the adapter must not wait for the
+// later item/completed event.
+func TestCodexExecuteStreamsCompleteJSONDeltaBeforeItemCompleted(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := writeFakeCodexAppServer(t, ""+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"+
+ `read line`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-stream"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-stream","turn":{"id":"turn-stream"}}}'`+"\n"+
+ `printf '%s' '{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-stream","turnId":"turn-stream","itemId":"msg-1","delta":"Hel'`+"\n"+
+ `sleep 0.05`+"\n"+
+ `printf '%s\n' 'lo"}}'`+"\n"+
+ `sleep 0.8`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-stream","turnId":"turn-stream","item":{"type":"agentMessage","id":"msg-1","text":"Hello","phase":"final_answer"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-stream","turn":{"id":"turn-stream","status":"completed"}}}'`+"\n")
+
+ cfg := Config{ExecutablePath: fakePath, Logger: slog.Default()}
+ backend, err := New("codex", cfg)
+ if err != nil {
+ t.Fatalf("new codex backend: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+
+ var started time.Time
+ for {
+ select {
+ case msg, ok := <-session.Messages:
+ if !ok {
+ t.Fatal("message stream closed before the delta became visible")
+ }
+ if msg.Type == MessageStatus && msg.Status == "running" {
+ started = time.Now()
+ continue
+ }
+ if msg.Type != MessageText {
+ continue
+ }
+ if started.IsZero() {
+ t.Fatal("text delta arrived before turn/started")
+ }
+ if msg.Content != "Hello" {
+ t.Fatalf("first streamed text = %q, want Hello", msg.Content)
+ }
+ elapsed := time.Since(started)
+ t.Logf("complete delta JSON became visible %s after turn/started", elapsed.Round(time.Millisecond))
+ if elapsed >= 500*time.Millisecond {
+ t.Fatalf("first streamed text arrived after %s; adapter waited for item/completed", elapsed.Round(time.Millisecond))
+ }
+ return
+ case <-time.After(5 * time.Second):
+ t.Fatal("timed out waiting for streamed text")
+ }
+ }
+}
+
+func TestCodexExecutePhaseLessCompletedMessageRemainsAuthoritative(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := writeFakeCodexAppServer(t, ""+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"+
+ `read line`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-output"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-output","turn":{"id":"turn-output"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-output","turnId":"turn-output","itemId":"msg-1","delta":"Hel"}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-output","turnId":"turn-output","item":{"type":"agentMessage","id":"msg-1","text":"Hello"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-output","turn":{"id":"turn-output","status":"completed"}}}'`+"\n")
+
+ result := executeFakeCodex(t, fakePath, ExecOptions{
+ Timeout: 5 * time.Second,
+ SemanticInactivityTimeout: 5 * time.Second,
+ })
+ if result.Status != "completed" {
+ t.Fatalf("status = %q, want completed (error=%q)", result.Status, result.Error)
+ }
+ if result.Output != "Hello" {
+ t.Fatalf("phase-less Result.Output = %q, want authoritative Hello", result.Output)
+ }
+}
+
func TestCodexExecuteSemanticInactivityDoesNotAffectNormalTurnCompletion(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {