Skip to content

session: legacy reasoning replay fails with "Duplicate item found with id ." #61641

Open

Description

@Z-Ton-Y

Description

On v2.2.5, sending any message to affected existing sessions fails in both TUI and WebUI:

Duplicate item found with id . Remove duplicate items from your input and try again.

New sessions work. The affected history contains legacy reasoning parts such as:

{"type":"reasoning","text":"...","state":{"reasoningField":"reasoning"}}

Replaying these parts produces multiple Responses reasoning input items without an id. The upstream rejects them as duplicate empty identifiers.

Environment

  • OpenCode: v2.2.5
  • OS: Linux / WSL2
  • Clients: TUI and WebUI
  • Provider adapter: @opencode/ai/providers/openai-compatible-responses

Reproduction

  1. Resume a session containing at least two reasoning parts in the legacy shape above.
  2. Send a message through the Responses adapter to an upstream that rejects multiple id-less reasoning items.
  3. The request fails with the error above; subsequent messages encounter the same history and fail again.

The repository bot's reproduction uses an isolated session and local mock endpoint. It reports the same behavior on v2.2.5 and dev (7864a94), and captures two reasoning items with neither id nor encrypted_content. Its script seeds the legacy shape; it does not establish how that shape was originally produced.

Evidence and scope

Direct probes against the affected upstream, with a user message included and store: false:

Reasoning input Result
One item without an id 200
Two items without ids 400, duplicate empty id
Two items with distinct ids 200

The rejection depends on the upstream, but OpenCode's history replay produces the id-less items. This warrants investigating legacy-history replay handling, rather than treating provider switching as the complete solution. It does not establish a defect in all Responses implementations.

The legacy state field is still read as provider metadata, according to the reproduction. Missing ids do not by themselves prove metadata loss or a missing migration; the original writer version and cause remain unverified. Duplicate-id and encrypted-content errors are outside this report's reproduced scope.

Expected behavior

Handle this legacy history with a provider-appropriate replay or recovery path instead of repeatedly sending input the upstream rejects. Preserve valid reasoning metadata and encrypted content; synthetic ids accepted by this upstream are not a general fix for other providers.

Activity

  1. opencodejr commented on Nov 4, 2026

    @opencodejr
    Contributor

    Thanks for the detailed report. I reproduced this on v2.2.5, and it still happens on the latest dev (7864a94).

    What I did:

    1. Configured a custom provider using @opencode/ai/providers/openai-compatible-responses, pointed at a local mock /v1/responses server. The mock rejects requests that contain more than one reasoning item without an id, as your upstream does.
    2. Created a session with one normal turn.
    3. Edited the stored assistant message so it contains two reasoning parts in the old shape ({"type":"reasoning","text":"...","state":{"reasoningField":"reasoning"}}, no itemId).
    4. Sent another message to that session. It failed with Duplicate item found with id . Remove duplicate items from your input and try again.

    The captured request contained two {"type":"reasoning","summary":[...]} input items, with no id and no encrypted_content. The old state field is read back as provider metadata, so the Responses request builder still sends these parts even though they have no item id. Your workaround of writing unique ids into the stored parts addresses the same root cause.

    The script below reproduces it: it starts the mock server, edits the session database and runs both turns. Related: #55357 and its PR #56879 cover reasoning ids dropped when they aren't shaped like rs_…. That is a different case from ids that are missing entirely.

    Reproduction script (repro.sh)
    #!/usr/bin/env bash
    # Reproduces #61641: replaying reasoning parts persisted in the legacy shape
    # ({"type":"reasoning","state":{"reasoningField":"reasoning"}}, no itemId) sends
    # several id-less `reasoning` input items to a Responses endpoint.
    # Usage: ./repro.sh            -> runs `opencode` from PATH
    #        OC_DEV=/path/to/repo ./repro.sh -> runs the CLI from that checkout
    set -euo pipefail
    DIR=$(mktemp -d /tmp/opencode/repro-61641.XXXX)
    export XDG_DATA_HOME=$DIR/data XDG_CONFIG_HOME=$DIR/config XDG_STATE_HOME=$DIR/state XDG_CACHE_HOME=$DIR/cache
    mkdir -p "$DIR/proj" && cd "$DIR/proj" && git init -q
    ocbin() {
      if [ -n "${OC_DEV:-}" ]; then
        bun --conditions=browser --preload="$OC_DEV/packages/tui/node_modules/@opentui/solid/scripts/preload.js" "$OC_DEV/packages/cli/src/index.ts" "$@"
      else opencode "$@"; fi
    }
    # From source, a --standalone child server is spawned without the preload, so start
    # the server ourselves and connect with --server instead.
    oc() {
      if [ -n "${OC_DEV:-}" ] && [ "${1:-}" = run ]; then shift; ocbin run --server "http://127.0.0.1:$SPORT" "${@/--standalone/}"
      else ocbin "$@"; fi
    }
    PORT=$((20000 + RANDOM % 20000)); SPORT=$((PORT + 1))
    export OPENCODE_PASSWORD=repro-61641
    cat > "$DIR/mock.ts" <<'TS'
    // Mock Responses endpoint: logs requests; rejects >1 reasoning items without id (as the report's upstream does).
    let n = 0
    Bun.serve({ port: Number(process.env.PORT), async fetch(req) {
      if (!new URL(req.url).pathname.endsWith("/responses")) return new Response("{}", { status: 404 })
      const body: any = await req.json(); n++
      const r = (body.input ?? []).filter((i: any) => i.type === "reasoning")
      console.log(`request ${n}: reasoning input items=${r.length}, without id=${r.filter((i: any) => !i.id).length}`)
      if (r.length) console.log(JSON.stringify(r))
      if (r.filter((i: any) => !i.id).length > 1)
        return Response.json({ error: { message: "Duplicate item found with id . Remove duplicate items from your input and try again.", type: "invalid_request_error" } }, { status: 400 })
      const rid = `rs_${n}abc`, mid = `msg_${n}abc`, ev = (o: any) => `event: ${o.type}\ndata: ${JSON.stringify(o)}\n\n`
      const resp = { id: `resp_${n}`, object: "response", status: "in_progress", model: body.model, output: [] }
      return new Response([
        ev({ type: "response.created", response: resp }),
        ev({ type: "response.output_item.added", output_index: 0, item: { type: "reasoning", id: rid, summary: [] } }),
        ev({ type: "response.reasoning_summary_part.added", item_id: rid, output_index: 0, summary_index: 0, part: { type: "summary_text", text: "" } }),
        ev({ type: "response.reasoning_summary_text.delta", item_id: rid, output_index: 0, summary_index: 0, delta: "thinking" }),
        ev({ type: "response.reasoning_summary_part.done", item_id: rid, output_index: 0, summary_index: 0, part: { type: "summary_text", text: "thinking" } }),
        ev({ type: "response.output_item.done", output_index: 0, item: { type: "reasoning", id: rid, summary: [{ type: "summary_text", text: "thinking" }] } }),
        ev({ type: "response.output_item.added", output_index: 1, item: { type: "message", id: mid, role: "assistant", status: "in_progress", content: [] } }),
        ev({ type: "response.output_text.delta", item_id: mid, output_index: 1, content_index: 0, delta: "reply " + n }),
        ev({ type: "response.output_item.done", output_index: 1, item: { type: "message", id: mid, role: "assistant", status: "completed", content: [{ type: "output_text", text: "reply " + n, annotations: [] }] } }),
        ev({ type: "response.completed", response: { ...resp, status: "completed", usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 } } }),
      ].join(""), { headers: { "content-type": "text/event-stream" } })
    } })
    TS
    PORT=$PORT bun "$DIR/mock.ts" > "$DIR/mock.log" 2>&1 & MOCK=$!; trap 'kill $MOCK' EXIT; sleep 1
    cat > opencode.json <<JSON
    { "provider": { "mock": { "npm": "@opencode/ai/providers/openai-compatible-responses", "name": "Mock",
      "options": { "baseURL": "http://127.0.0.1:$PORT/v1", "apiKey": "x" },
      "models": { "m1": { "name": "m1", "reasoning": true } } } }, "model": "mock/m1" }
    JSON
    if [ -n "${OC_DEV:-}" ]; then ocbin serve --port $SPORT > "$DIR/serve.log" 2>&1 & SRV=$!; trap 'kill $MOCK $SRV' EXIT; sleep 8; fi
    echo "== opencode $(oc --version)"; echo "== turn 1 (fresh session)"
    oc run --standalone --model mock/m1 "hello one" 2>&1 | tail -3
    # Rewrite the stored assistant message so it holds two legacy id-less reasoning parts.
    cat > "$DIR/seed.ts" <<'TS'
    import { Database } from "bun:sqlite"
    const db = new Database(process.env.DB!)
    const row: any = db.query("select id, session_id, data from session_message where type='assistant' order by time_created desc limit 1").get()
    const d = JSON.parse(row.data)
    const legacy = (text: string) => ({ type: "reasoning", text, time: { created: d.time.created, completed: d.time.created }, state: { reasoningField: "reasoning" } })
    d.content = [legacy("legacy thought A"), legacy("legacy thought B"), ...d.content.filter((p: any) => p.type !== "reasoning")]
    db.query("update session_message set data=? where id=?").run(JSON.stringify(d), row.id)
    console.log(row.session_id)
    TS
    DBF=$XDG_DATA_HOME/opencode/opencode.db; [ -n "${OC_DEV:-}" ] && DBF=$XDG_DATA_HOME/opencode/opencode-local.db
    SID=$(DB=$DBF bun "$DIR/seed.ts")
    echo "== turn 2 (session $SID with legacy reasoning parts)"
    oc run --standalone --model mock/m1 --session "$SID" "hello two" 2>&1 | tail -3 || true
    echo "== mock log"; cat "$DIR/mock.log"

    Run it: bash repro.sh

  2. changed the title [-]session: history with id-less reasoning parts bricks every message with "Duplicate item found with id ."[/-] [+]session: legacy reasoning replay fails with "Duplicate item found with id ."[/+] on Nov 4, 2026
  3. 56wj commented on Nov 4, 2026

    @56wj

    I traced this to packages/ai/src/protocols/open-responses.ts: lowerReasoning can serialize a persisted reasoning part when provider metadata exists but its itemId is absent. I am preparing a focused fix that skips unreplayable id-less reasoning parts and adds regression coverage.

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