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], ¤t) != 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)) } // ThreadItem.contextCompaction has no running/completed field in history; // never infer running from its presence. A terminal turn can, however, // authoritatively settle a retained live compaction after a stream reattach. if terminalTurn(last.turn) { c.mu.Lock() matching := c.turns[id] == last.turn.ID if matching { delete(c.turns, id) } c.mu.Unlock() if matching { c.emit(stepFrame(id, protocol.ChatStepEnded, 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)) } } } } // ProbeTurn reports whether the thread's latest turn is still in progress in // the App Server, which outlives a Pipelines restart. The server uses it once // at start to resume observing a turn a previous process left running. func (c *Chat) ProbeTurn(ctx context.Context, id string) (bool, error) { last, err := c.latestTurn(ctx, id) if err != nil { return false, err } return activeTurn(last.turn), nil }