Skip to content

fix: reseed Cursor after another model answered in the session - #32

Closed
zcl0621 wants to merge 3 commits into
oakimov:mainfrom
zcl0621:fix/reset-on-foreign-history
Closed

zcl0621 wants to merge 3 commits into
oakimov:mainfrom
zcl0621:fix/reset-on-foreign-history

Conversation

@zcl0621

@zcl0621 zcl0621 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A sticky Cursor conversation only contains what Cursor produced. When an OpenCode session switches to another provider, a local model, or a different Cursor model and then back, the next fresh Run resumes the old checkpoint. Cursor never sees the other model's turns, and in practice those Runs regularly ended with Cursor API error (code=internal) after visible output or stateful server activity; automatic retry unsafe. Composer-only sessions were unaffected.
  • The provider now records, per OpenCode session, the text and tool call ids it emitted in its latest non-empty step (src/protocol/turn-provenance.ts; persisted as a new optional field 12 in the conversation cache, so it survives a restart and older readers skip it; the in-memory map is LRU-bounded like other per-session state and re-hydrates from that cache). Before a fresh Run it compares that record with the host's latest assistant turn. A turn it did not emit (foreign-assistant), or a different Cursor wire model id than the conversation's last Run (model-switch), rotates the conversation like the existing history-rewrite path and resends history images like a recovery rebase (trace: conversation reset: reason=foreign-history:<reason>).
  • That rebase seeds from the full host history with toolResults: "all", the same host-observation form compaction already uses, because the other model's work exists only in OpenCode history. If the rebased history is estimated above 80% of the model context, the provider throws a 413 APICallError ("prompt is too long") before opening a Run, so OpenCode classifies it as context overflow and compacts first.
  • Detection is conservative: no record for the current conversation, or an assistant turn with no text or tool calls, keeps today's behavior. Reasoning parts are ignored, because hosts replay another model's reasoning as text.

Design note: AGENTS.md says prompt identity and host-agent changes must never remint, for Cursor CLI parity. This PR does not remint on those. It does remint on a Cursor→Cursor model switch, which the CLI would keep on one conversation. I kept it because the failing sessions mixed Cursor models as well as other providers, and I could not isolate which switches triggered internal. I'm happy to drop the model-switch reason and keep only foreign-assistant if you'd rather preserve CLI behavior there.

Test plan

  • bun run typecheck / bun test (1231 pass; 17 new in test/turn-provenance.test.ts: detection cases incl. step boundaries, LRU bound, "all" replay, overflow error shape, and a pump → persist → hydrate round trip)
  • test/architecture.test.ts passes; no new dependencies
  • OpenCode 2.0: in a session switching between Cursor models, another provider and a local model, the code=internal failures no longer reproduced

🤖 Generated with Claude Code

A Cursor conversation only contains what Cursor produced. When a session
switches to another provider, a local model, or a different Cursor model and
then back, resuming the old checkpoint hides that work from Cursor and has
been observed to end Runs with `Cursor API error (code=internal)` after
visible output, where automatic retry is unsafe.

Record the text and tool call ids this provider emits per OpenCode session
(persisted with the conversation cache). Before a fresh Run, compare them with
the host's latest assistant turn; on a model switch or a foreign turn, start a
new Cursor conversation seeded with the full host history including tool
results. If that history would exceed 80% of the model context, raise a 413
"prompt is too long" APICallError before opening the Run so the host compacts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@zcl0621
zcl0621 marked this pull request as ready for review October 1, 2026 00:51
Copilot AI balanced review requested due to automatic review settings October 1, 2026 00:51

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Detection can miss repeated foreign replies, rebases can omit prior images, and provenance storage is unbounded.

Review effort: Balanced
Findings: 3 Medium severity

Open (3)
What changed in this PR

Reseeds Cursor conversations when host history comes from another model, preventing stale checkpoint reuse.

Changes:

  • Tracks and persists emitted-turn provenance.
  • Detects foreign/model-switched history and performs bounded full-history rebases.
  • Adds coverage and user-facing documentation.
File Description
src/​protocol/​turn-provenance.ts Tracks and detects foreign assistant turns.
src/​protocol/​conversation-state.ts Hydrates and persists provenance.
src/​protocol/​conversation-persistence.ts Adds provenance to the cache schema.
src/​language-model.ts Triggers rebases and context-overflow handling.
test/​turn-provenance.test.ts Tests detection, rebasing, and persistence.
README.md Documents model-switch reseeding.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/language-model.ts Resolved
Comment thread src/protocol/turn-provenance.ts Outdated

export type ForeignHistoryReason = "model-switch" | "foreign-assistant"

const provenanceBySession = new Map<string, TurnProvenance>()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c4cc176: the map is LRU-bounded at MAX_PROVENANCE_SESSIONS (mirrors MAX_TURN_STATE_SESSIONS), the unused clearTurnProvenance is gone, and an evicted entry is re-hydrated from the persisted conversation cache before detection (hydrateTurnProvenance). Each entry now holds only the latest step.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Follow-up in c0c0c8e: each entry is now at most 64 tool call ids plus the first 4 KiB of the latest step text (compared as a prefix), so the 256-session LRU holds ~1 MiB worst case instead of ~16 MiB. Eviction is coordinated with durable state: TurnEnded persists the entry with the conversation cache, and hydrateTurnProvenance restores an evicted entry from it before detection; until it is restored, detection returns "no opinion" rather than forcing a rebase.

Comment thread src/protocol/turn-provenance.ts Resolved
- Record only the latest non-empty host step and require an exact match, so
  a foreign "Done." no longer matches an older Cursor turn's text.
- Cap tracked sessions at MAX_PROVENANCE_SESSIONS (LRU, mirrors
  MAX_TURN_STATE_SESSIONS) and re-hydrate an evicted entry from the
  persisted conversation cache.
- A foreign-history reseed resends history images like a recovery rebase.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot review overview

🔵 Needs a closer look

Cursor-to-Cursor model switches unnecessarily discard valid checkpoints and prompt-cache continuity.

Review effort: Balanced
Findings: 1 Medium severity

Open (1)
Resolved since last review (2)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Avoid reseeding checkpoints on ordinary Cursor model switches

src/​protocol/​turn-provenance.ts:157

A Cursor-to-Cursor model change is not evidence that host history moved past the sticky conversation: Cursor's own CLI keeps the same conversation across model changes, so the prior checkpoint already contains this assistant turn. Returning here before inspecting the assistant provenance forces every ordinary model switch to discard the checkpoint/blob graph and replay all history, which loses prompt-cache continuity and can trigger the new 80% compaction path even when no foreign work exists. Please scope reseeding to foreign-assistant (or first establish a protocol incompatibility specific to Cursor model switches).

Identify a step by its first 64 tool call ids and first 4 KiB of text, so
the LRU-bounded map holds at most ~1 MiB instead of ~16 MiB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@zcl0621

zcl0621 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

On the Copilot note about Cursor→Cursor model switches (turn-provenance.ts:157): I'm keeping the model-switch reason for now, deliberately, and leaving the final call to the maintainer.

  • The failing sessions switched between Cursor models as well as to other providers and a local model, and I could not isolate which switches produced Cursor API error (code=internal). With both reasons enabled the failures stopped in real use on OpenCode 2.0. I have not verified a build without model-switch.
  • My guess, which I have not verified against the protocol: the checkpoint can carry model-specific state from the previous backend (reasoning/thinking artifacts), and continuing it on a different vendor's model is where Cursor's server fails. Cursor's own CLI keeping one conversation across model changes argues against this, so it's a hypothesis, not established.
  • Cost is bounded to the switch turn: one uncached replay of the host history. The 80% compaction path only fires when that history is already close to the target model's context.

If you'd rather keep CLI parity here, dropping it is a one-line change (remove the modelId comparison in detectForeignHistory). I'm happy to push that.

@zcl0621

zcl0621 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Soak-tested together with #33 on OpenCode 2.0.21: 150 runs across parallel sessions mixing Cursor and DeepSeek parents and subagents, with MCP disconnect/reconnect, skill add/modify/remove and server restarts in between. 0 code=internal. Every reset was this PR's model-switch path, and it fired only on parent sessions. Details: #33 (comment)

@zcl0621

zcl0621 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Closing in favor of a single consolidated PR. It combines this change with the related fixes found during soak testing on OpenCode 2.x (subagent session key, foreign-history reseed, system-notice continuations, missing-blob reseed) and includes the full test results. I'll link it here once it's open.

@zcl0621

zcl0621 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Consolidated PR: #34

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.

2 participants