Skip to content

fix(client): keep session timelines in step with the server on flaky connections - #61785

Open
Hona wants to merge 3 commits into
devfrom
transcript-catch-up
Open

Hona wants to merge 3 commits into
devfrom
transcript-catch-up

Conversation

@Hona

@Hona Hona commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

On a bad connection the timeline drifts from the server: a prompt the server already delivered stays Pending at the bottom, under its own reply, and rows go missing or out of order until the session is reopened.

The live stream (/api/event) is volatile by design (specs/v2/session.md: "no replay guarantee"; request/response consumers use authoritative projections). The client broke that contract in four places:

Gap What happened
Catch-up read raced the stream After a reconnect, message.sync replaced the transcript with a page read before events that had already been applied live, wiping replies and prompt deliveries.
Catch-up was one-shot A failed reconnect read was swallowed and never retried, so a lost session.inbox.delivered stayed lost.
Accepted prompts needed a transcript read pending.sync never cleared a prompt the server accepted (outbox kept it), so only a transcript page that happened to contain it could settle it.
A dead stream was rejoined SharedEvents kept the socket open while another subscriber (the /goal RPC) held it, so a stall or resync reconnected to the same dead socket.

Ordering reads against the stream

GET /api/session/:id/message now returns experimental.seq: the Session's durable sequence, read in the same transaction as the page. Projections and the sequence advance in one write transaction (Bus commit), so the page reflects exactly the durable events up to seq.

sequenceDiagram
  participant S as Server
  participant C as Client data
  C->>S: GET /message (transcript read starts)
  Note over C: Session events are held
  S-->>C: step.started (seq 3), text.delta
  S->>C: page at seq 2
  Note over C: apply page, then held events in order
  Note over C: seq ≤ 2: page has it, only pending/status/info effects
  Note over C: seq > 2: fold into the page
Loading
  • Held, then replayed: events for a Session wait while its transcript read is in flight and apply on top of the page (transcriptReads, handleEvent).
  • Covered events: a durable event at or below the page's seq skips the folds that mirror the projection (message.update); pending-input overlays still apply (message.overlay).
  • Deltas: they carry no sequence and the page does not mark finished text, so they apply once the stream has delivered the event the page was read at. Earlier ones could extend text the page already holds in full.
  • Bounded: a read ends on disconnect or after 30 s, and its held events apply as they would have live. A read that started while the stream was down never stands in for one after it reconnects (createSync(offline)).
  • Older servers without seq keep today's behavior: the page wins.

Settling prompts the server accepted

// prompt(): the POST resolved, so the server admitted it durably
if (outbox.delete(id)) acknowledged.set(id, ++admissions)

// pending.sync(): a read sent after acceptance is authoritative for it
const inflight = previous.filter((item) => outbox.has(item.id) || (acknowledged.get(item.id) ?? 0) > accepted)
  • A prompt missing from such a read was delivered or cancelled. Its pending overlay row goes, and a delivered prompt comes back from the transcript in its real position.
  • A read that overlapped the POST cannot decide, so acceptance reads the inbox again.
  • Compactions have no overlay: their transcript row shares the inbox ID, so a consumed compaction only leaves the pending list.

Catching up reliably

  • data.session.hydrate(id, { signal }) loads the transcript and pending input and retries failed reads (500 ms → 5 s) while connected. The app's session resolution and the TUI's rows use it on every (re)connect and abort it when the target changes.
  • SharedEvents.reset() drops the shared stream for every subscriber; the connection calls it on a stall, a connect timeout and a forced resync, so the reconnect opens a new socket.

Visual

<svg xmlns="http://www.w3.org/2000/svg" width="240" height="72" viewBox="0 0 240 72" fill="none" stroke="currentColor">
  <style>
    .pending{animation:settle 4s ease-in-out infinite}
    .reply{animation:reply 4s ease-in-out infinite}
    @keyframes settle{0%,30%{transform:translateY(40px)}55%,100%{transform:translateY(0)}}
    @keyframes reply{0%,30%{transform:translateY(-28px)}55%,100%{transform:translateY(0)}}
    @media (prefers-reduced-motion:reduce){.pending,.reply{animation:none}}
  </style>
  <g class="pending">
    <rect x="120" y="6" width="112" height="18" rx="5" opacity=".5"/>
    <circle cx="130" cy="15" r="3" fill="currentColor" opacity=".6"/>
    <line x1="140" y1="15" x2="220" y2="15" stroke-width="3" stroke-linecap="round" opacity=".6"/>
  </g>
  <g class="reply" opacity=".7">
    <line x1="8" y1="38" x2="200" y2="38" stroke-width="3" stroke-linecap="round"/>
    <line x1="8" y1="50" x2="170" y2="50" stroke-width="3" stroke-linecap="round"/>
    <line x1="8" y1="62" x2="120" y2="62" stroke-width="3" stroke-linecap="round" opacity=".6"/>
  </g>
</svg>

Added by the opencode bot (AI-generated).

Fixes #56725

Related: #59615, #59542, #56748

Public API: adds optional experimental.seq to the session messages response, SharedEvents.reset() and data.session.hydrate() (backwards compatible)

@Hona
Hona requested a review from Brendonovich as a code owner November 4, 2026 20:44
Copilot AI balanced review requested due to automatic review settings November 4, 2026 20:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The approach looks sound. Ordering a page against the stream with a seq read in the same transaction is the right layer for this race. I checked it by running the PR's race tests against the base: 8 of the 17 fail there and all pass here. The client, server message and TUI data tests also pass, and I ran a TUI smoke test with the simulated model.

Public API: GET /api/session/:id/message (both the plain and the media-URI response) gains an optional experimental: { seq?: Event.Seq }. It is only set on a first page of a Session that has durable events. The client types gain MessageListOutput.experimental / SessionMessagesResponse.experimental, and two new functions are added: SharedEvents.reset() and data.session.hydrate(id, { signal }). Existing callers are unaffected. The app and TUI move from message.sync + pending.sync to hydrate, but both functions remain. All of this is backwards compatible, and older servers without seq keep today's behavior.

One thing to fix: packages/protocol/openapi.json was not regenerated. bun run check:generated in packages/protocol passes on the base and fails on this branch, so please run bun run generate there. There is also a small note on the test helper inline.

Fixes #56725
Related: #59615, #59542, #56748

}
})

async function settled() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

settled() waits a fixed 50 microtask turns. Several tests rely on that being enough for the fetch, decode and store chain to finish, so they will break silently if that chain gains a few more awaits. Could these tests await the specific read, like the ones using Promise.withResolvers, or wait for a condition instead?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

client: delayed transcript hydration discards a live assistant message

2 participants