Skip to content

client: delayed transcript hydration discards a live assistant message #56725

Open
RealBhupesh/opencode
#2

Description

@521ox

client: delayed transcript hydration discards a live assistant message

Summary

An in-flight transcript read can replace a newer assistant message already built from live events. Subsequent text and completion events do not recreate the missing assistant, leaving the client cache without the answer even after execution succeeds.

This reproduces with the real createData, without a model, server, database, or rendered UI. It is a client projection problem, not evidence of persisted-message loss.

Environment

  • Windows build 22631; Bun 1.4.2.
  • Executed checkout: custom fork at 72d0dce8ea437ea061e0680110fa19a81aa118fd, client package 2.0.32.
  • Source comparison: the affected behavior also exists at official 63c1a27af5a391d9caa55b82694f496911e1859b. Comparison with dev 60a5a6c found only three AI-file changes and no client changes. Those official revisions were not dynamically tested.
  • Headless Bun test with --conditions=browser; injected in-memory fetch, no plugins or real service involved.

Reproduction

Use the deferred-fetch/listener fixture from packages/client/test/solid-inbox-race.test.ts:15-35 around the real Promise client and createData. The helper is local to that test, so adapt its setup in a scratch test rather than importing the test file. No reducer needs to be copied or mocked.

  1. Remember an existing session with data.session.remember(info). Do not emit session.created, which has a separate initial-read workaround.
  2. Call data.session.message.sync(sessionID). In the injected fetch, signal that the first message GET arrived, then hold its response. Its captured history contains only:
    const user = { id: "msg_history", type: "user", text: "Continue", time: { created: 1 } }
  3. After that request arrives, emit these (type, data) pairs in order through setup.emit, wrapping each in a complete event with unique id, increasing created, durable: { aggregateID: sessionID, seq, version: 1 }, and location: { directory: "/project" }:
    const startingEvents = [
      ["session.execution.started", { sessionID }],
      ["session.step.started", {
        sessionID, assistantMessageID: "msg_assistant",
        agent: "build", model: { providerID: "audit", id: "fixture" }, started: 3,
      }],
      ["session.text.started", { sessionID, assistantMessageID: "msg_assistant", ordinal: 0 }],
      ["session.text.delta", {
        sessionID, assistantMessageID: "msg_assistant", ordinal: 0, delta: "Hello",
      }],
    ] as const
  4. Confirm the real cache contains the assistant with Hello. Release the held HTTP response as Response.json({ data: [user], cursor: {} }), then await the original sync.
  5. Emit the remaining terminal events:
    const terminalEvents = [
      ["session.text.ended", {
        sessionID, assistantMessageID: "msg_assistant", ordinal: 0, text: "Hello world",
      }],
      ["session.step.ended", {
        sessionID, assistantMessageID: "msg_assistant", finish: "stop", cost: 0,
        tokens: { input: 1, output: 2, reasoning: 0, cache: { read: 0, write: 0 } },
      }],
      ["session.execution.succeeded", { sessionID }],
    ] as const
  6. Let pending mock requests and one event-loop turn settle, without calling another message sync. Answer the metadata GET triggered by execution completion normally. If a second message GET occurs, allow it to return the complete current history rather than blocking recovery in the fixture.

Control: release and await the same old history before emitting any of the events. This preserves the completed assistant with Hello world, finish: "stop", and a completion timestamp. The control passed.

Expected Behavior

Older hydration must not erase a newer assistant already observed through the event stream. After the terminal events, the cache should contain the completed assistant and its full text.

Actual Behavior

Checkpoint Actual cached messages Status
Before releasing old history Assistant containing Hello running
After old history commits Only msg_history; assistant absent running
After terminal events settle msg_history plus succeeded idle marker; assistant still absent idle

There was one initial explicit message sync and one message GET. Completion caused a metadata GET, but no message refetch. The contract assertion fails because msg_assistant is missing; the non-interleaved control passes with identical expected content.

Additional Context

Related historical fix: merged PR #30300 handled a similar live-part/hydration race in the older packages/opencode TUI SyncProvider. This report reproduces the current V2 packages/client data owner; it does not assume that the old implementation or regression test covers this newer path.

Source references below use checkout 72d0dce:

  • packages/client/src/solid/data.ts:1696-1721: hydration replaces the transcript, preserving additional outbox/pending rows but not the new assistant.
  • packages/client/src/solid/data.ts:471-499: assistant/part edits do nothing when the target is absent.
  • packages/client/src/solid/data.ts:1073-1111: completion refetches messages conditionally for cached unfinished tools, not for this missing pure-text assistant.
  • Official 63c1a27 has the corresponding merge at packages/client/src/solid/data.ts:1709.

This test establishes missing client state on the exercised completion path. It does not establish permanent failure across later reconnects, persisted-data loss, or a rendered-UI hang. Occurrence frequency with a real remote connection was not measured.

Suggested solution — not implemented

Have the data owner reconcile live updates received during hydration, or use a consistent read/version boundary and revalidate when the snapshot is superseded. The existing inbox pendingUpdates and activity activeUpdates mechanisms provide nearby precedents for event precedence. Initial history must still hydrate successfully; merely aborting or discarding overlapping reads without a convergence path is insufficient. No broader synchronization framework is proposed.

Activity

  1. opencode-agent commented on Oct 18, 2026

    @opencode-agent
    Contributor

    Thanks for the detailed report. I reproduced this on packages/client from v2.0.32, and it still happens on the latest dev (60a5a6c).

    The script below is a headless Bun test that uses the real Promise client and createData with an injected fetch:

    1. session.remember(info), then session.message.sync(sessionID) while the message GET is held.
    2. Emit execution.started, step.started, text.started and text.delta("Hello"). The cache now has msg_assistant with Hello.
    3. Release the old history ([msg_history]). The transcript becomes [msg_history] and the assistant is gone.
    4. Emit text.ended, step.ended and execution.succeeded. The final transcript has msg_history plus the idle marker, with no msg_assistant, and there is only one message GET, so nothing refetches.

    The control (history released before any events) keeps the completed assistant with Hello world and finish: "stop".

    It looks like session.message.sync in packages/client/src/solid/data.ts keeps only outbox and admitted pending rows when it replaces the transcript. Unlike the session-status and inbox hydration paths, it has nothing that lets live events take precedence.

    Related: #56726 (the same kind of race for forms) and #30300 (an earlier fix for this race in the old v1 TUI).

    Reproduction script (repro-56725.test.ts)
    // Repro for anomalyco/opencode#56725: a delayed transcript read discards a live assistant message.
    // Copy to packages/client/test/ in an opencode checkout, then from packages/client run: bun test --conditions=browser test/repro-56725.test.ts
    import { expect, test } from "bun:test"
    import { createRoot } from "solid-js"
    import { createData, type CreateDataInput } from "../src/solid"
    import { OpenCode, type OpenCodeEvent, type SessionInfo } from "../src/promise"
    
    const sessionID = "ses_race"
    const info: SessionInfo = {
      id: sessionID,
      projectID: "project",
      cost: 0,
      tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
      outcome: "succeeded",
      time: { created: 0, updated: 0, idle: 2, viewed: 1 },
      location: { directory: "/project" },
    } as SessionInfo
    const user = { id: "msg_history", type: "user", text: "Continue", time: { created: 1 } }
    
    function fixture(fetch: (request: Request) => Promise<Response>) {
      const listeners = new Set<Parameters<CreateDataInput["event"]["listen"]>[0]>()
      const api = OpenCode.make({
        baseUrl: "http://opencode.local",
        fetch: (input, init) => fetch(input instanceof Request ? input : new Request(input, init)),
      })
      return createRoot((dispose) => ({
        data: createData({
          api: () => api,
          directory: "/project",
          event: {
            on: () => () => {},
            listen(handler) {
              listeners.add(handler)
              return () => listeners.delete(handler)
            },
          },
        }),
        emit: (event: OpenCodeEvent) => listeners.forEach((l) => l({ name: event.type, details: event })),
        dispose,
      }))
    }
    
    let seq = 0
    const ev = (type: string, data: any) =>
      ({
        id: `evt_${++seq}`,
        type,
        created: 10 + seq,
        durable: { aggregateID: sessionID, seq, version: 1 },
        location: { directory: "/project" },
        data,
      }) as unknown as OpenCodeEvent
    
    const starting = () => [
      ev("session.execution.started", { sessionID }),
      ev("session.step.started", {
        sessionID,
        assistantMessageID: "msg_assistant",
        agent: "build",
        model: { providerID: "audit", id: "fixture" },
        started: 3,
      }),
      ev("session.text.started", { sessionID, assistantMessageID: "msg_assistant", ordinal: 0 }),
      ev("session.text.delta", { sessionID, assistantMessageID: "msg_assistant", ordinal: 0, delta: "Hello" }),
    ]
    const terminal = () => [
      ev("session.text.ended", { sessionID, assistantMessageID: "msg_assistant", ordinal: 0, text: "Hello world" }),
      ev("session.step.ended", {
        sessionID,
        assistantMessageID: "msg_assistant",
        finish: "stop",
        cost: 0,
        tokens: { input: 1, output: 2, reasoning: 0, cache: { read: 0, write: 0 } },
      }),
      ev("session.execution.succeeded", { sessionID }),
    ]
    
    async function run(interleave: boolean) {
      seq = 0
      const held = Promise.withResolvers<Response>()
      const arrived = Promise.withResolvers<void>()
      let messageGets = 0
      const setup = fixture(async (request) => {
        const url = new URL(request.url)
        if (request.method === "GET" && url.pathname.includes("/message")) {
          messageGets++
          if (messageGets === 1) {
            arrived.resolve()
            return held.promise
          }
          return Response.json({ data: [], cursor: {} })
        }
        if (request.method === "GET") return Response.json({ data: info })
        return Response.json({ data: {} })
      })
      try {
        setup.data.session.remember(info)
        const reading = setup.data.session.message.sync(sessionID)
        await arrived.promise
        if (interleave) {
          starting().forEach(setup.emit)
          const before = setup.data.session.message.get(sessionID, "msg_assistant")
          console.log("before release:", JSON.stringify(before)?.slice(0, 200))
          expect(before).toBeDefined()
          held.resolve(Response.json({ data: [user], cursor: {} }))
          await reading
          console.log("after hydration:", setup.data.session.message.list(sessionID).map((m: any) => m.id))
        } else {
          held.resolve(Response.json({ data: [user], cursor: {} }))
          await reading
          starting().forEach(setup.emit)
        }
        terminal().forEach(setup.emit)
        await new Promise((r) => setTimeout(r, 20))
        const list = setup.data.session.message.list(sessionID)
        console.log(interleave ? "interleaved" : "control", "final:", JSON.stringify(list), "messageGETs:", messageGets)
        return setup.data.session.message.get(sessionID, "msg_assistant")
      } finally {
        setup.dispose()
      }
    }
    
    test("control: history before events keeps the assistant", async () => {
      expect(await run(false)).toBeDefined()
    })
    
    test("interleaved: delayed history must not discard the live assistant (#56725)", async () => {
      expect(await run(true)).toBeDefined()
    })

    Run it: bun repro-56725.test.ts

  2. added a commit that references this issue on Oct 18, 2026
    471caa4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions