Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): harden Cursor adapter turn lifecycle #9051

ClosedNeon-Wang(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/9051/headopened View on GitHub

Summary

Ports the four turn-lifecycle fixes verified in #9038 (omp provider) back to the Cursor adapter they were inherited from. Closes #9047.

  1. activeTurnId bound too late — promptsInFlight += 1 and the activeTurnId assignment were separated by effectful session configuration; a concurrent sendTurn in that window steered onto the previous turn. The id is now bound in the same synchronous stretch.
  2. No terminal event on started-turn failure — failures after turn.started (attachment reads, session configuration, acp.prompt) now emit turn.completed { state: "failed", errorMessage } before propagating, guarded on the last-in-flight rule and !ctx.stopped so a late failure never publishes onto a stopped or replacement session. Pre-start failures remain owned by ProviderCommandReactor.handleTurnStartFailure as before.
  3. Cancellation during preparation ignored — interruptTurn records the active turn id in a per-session set; sendTurn checks it before turn.started and again before acp.prompt, settling cancelled turns as cancelled without ever sending the prompt. Ids are removed on settle.
  4. threadLocksRef grew forever — per-thread semaphores are now deleted on stopSession/stopAll/finalizer and on startSession failure. The startSession replacement path deliberately keeps the lock it is holding.

Verification

  • Two new tests ported from the omp side: prompt failure after turn.started emits turn.completed(failed) (and sendTurn still fails); an interrupt landing mid-preparation (mock delayed via the new env-gated T3_ACP_SET_CONFIG_OPTION_DELAY_MS sleep, additive and off by default) settles as cancelled with zero session/prompt requests.
  • CursorAdapter.test.ts 21/21 green; full src/provider/Layers + src/provider/acp suites (123 tests) green against the shared mock; apps/server typecheck clean.

Model: kimi-code/k3 via Oh My Pi (omp)


Note

Medium Risk Changes core Cursor turn/cancel/interrupt semantics and terminal event ordering; mistakes could leave turns stuck or cancel the wrong prompt, but behavior is heavily covered by new adapter tests.

Overview Hardens CursorAdapter turn lifecycle so cancellation, steering, failures, and permissions behave predictably under races.

sendTurn now binds activeTurnId in the same synchronous step as promptsInFlight, avoiding steers attaching to the wrong turn during slow session config. Pre-prompt cancels use a per-session cancelledTurnIds set (checked before turn.started and before session/prompt) because acp.cancel does not apply until the prompt is on the wire. A settled guard plus ensuring logic publishes one terminal turn.completed across success, cancel, steer-drain, and late interrupts. Errors after turn.started emit turn.completed with state: "failed" and a trimmed errorMessage while still failing sendTurn.

interruptTurn accepts an optional turnId: stale cancels for a completed turn no longer call session/cancel on the active prompt; targeted cancels during prepare only record markers.

Permission responses use selectCursorPermissionOptionId so wire replies use the agent’s advertised optionId for the decision kind, not only the generic hyphenated fallback.

The ACP mock gains T3_ACP_SET_CONFIG_OPTION_DELAY_MS to stretch prepare-phase tests; CursorAdapter.test.ts adds coverage for prompt failure, prepare cancel, stale interrupt, steered cancel, double-settle, and custom permission option ids.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c18df1db96b3501cf143c67b22de86e5a58a9fdf. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Harden CursorAdapter turn lifecycle: add pre-prompt cancellation, single-terminal guarantees, and targeted interrupts

  • sendTurn now supports pre-prompt cancellation via a cancelledTurnIds set on CursorSessionContext; if a turn is marked cancelled before the prompt reaches the wire, it skips sending session/prompt and publishes exactly one turn.completed with state cancelled.
  • Ensures only one terminal event is published per turn across success, failure, and cancellation paths by tracking settled and turnStartedEmitted flags; errors after turn.started now emit a failed terminal event with an error message trimmed to CURSOR_TURN_ERROR_MAX_CHARS (1,000 chars).
  • interruptTurn accepts an optional turnId; interrupts targeting a non-active or completed turn record a cancel marker without calling acp.cancel, preventing accidental cancellation of the wrong prompt.
  • selectCursorPermissionOptionId maps approval decisions to the actual agent-advertised optionId instead of a generic fallback, fixing permission responses when agent-provided options exist.
  • Adds T3_ACP_SET_CONFIG_OPTION_DELAY_MS support to the mock agent to simulate delayed config writes for cancellation race tests.
  • Behavioral Change: interruptTurn signature changed to accept an optional turnId; callers that do not pass it get the prior behavior (interrupt active turn). Interrupts addressed to completed turns are now silently ignored rather than sending session/cancel.
Macroscope summarized c18df1d.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — The production Cursor adapter now uses new concurrency and cancellation state to change when prompts execute and when terminal runtime events are emitted, while also changing permission-response behavior. Although the scope is contained and extensively tested, these are material request-path lifecycle changes that warrant human review.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. Hi @juliusmarminge @t3dotgg — quick ping on this small one when convenient. 🙂

      It's the Cursor-side port of the turn-lifecycle fixes that were reviewed in #9038 (issue #9047): cancellation targeting, terminal event on started-turn failure, semaphore retention, and the double-settle race. All checks green, all threads resolved, 25/25 adapter tests passing including regression tests for each fix. Should be a quick read — happy to tweak anything.

    4. Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c18df1db96b3501cf143c67b22de86e5a58a9fdf. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -935,0 +979,21 @@
      979+ return false;
      980+ }
      981+ if (ctx.promptsInFlight !== 1) {
      982+ // A steered sibling prompt for this same turn is still in
      983+ // flight or preparing: skip the wire but keep the marker — the
      984+ // last draining prompt settles the turn (here once
      985+ // promptsInFlight === 1, or in the ensuring once it hits 0).
      986+ return true;
      987+ }
      988+ ctx.cancelledTurnIds.delete(turnId);
      989+ settled = true;
      990+ yield* offerRuntimeEvent({
      991+ type: "turn.completed",
      992+ ...(yield* makeEventStamp()),
      993+ provider: PROVIDER,
      994+ threadId: input.threadId,
      995+ turnId,
      996+ payload: { state: "cancelled", stopReason: "cancelled" },
      997+ });
      998+ return true;
      999+ });

      Cancelled settle ignores stopped sessions

      High Severity

      settleIfCancelled publishes turn.completed whenever the last in-flight prompt sees a cancel marker, but it never checks ctx.stopped. The failure and ensuring paths already skip in that case so a late failure cannot land on a torn-down or replaced session. A cancel that lands during preparation, followed by stopSession or a startSession replacement, still emits that terminal event on the shared thread. Ingestion can then apply it after session.exited and move a stopped session back to ready, or clear a replacement session that is still starting.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c18df1db96b3501cf143c67b22de86e5a58a9fdf. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -1091,0 +1193,21 @@
      1193+ ? error.message
      1194+ : undefined;
      1195+ const collapsed = (typeof rawMessage === "string" ? rawMessage : String(error))
      1196+ .replace(/\s+/g, " ")
      1197+ .trim();
      1198+ yield* offerRuntimeEvent({
      1199+ type: "turn.completed",
      1200+ ...(yield* makeEventStamp()),
      1201+ provider: PROVIDER,
      1202+ threadId: input.threadId,
      1203+ turnId,
      1204+ payload: {
      1205+ state: "failed",
      1206+ stopReason: null,
      1207+ errorMessage:
      1208+ collapsed.length > CURSOR_TURN_ERROR_MAX_CHARS
      1209+ ? `${collapsed.slice(0, CURSOR_TURN_ERROR_MAX_CHARS - 1)}…`
      1210+ : collapsed,
      1211+ },
      1212+ });
      1213+ }),

      Steering failures settle unstarted turns

      Medium Severity

      The post-start failure handler treats every steering sendTurn as already started. tapError emits turn.completed { failed } unless turnStartedEmitted is false and steeringTurnId is unset. A follow-up that steers onto a turn still in session configuration can therefore be the last in-flight prompt, fail before any turn.started, and still publish a failed completion. That contradicts the pre-start rule (those errors stay with handleTurnStartFailure) and can mark the session error for a turn the UI never opened. If the original prompt was already cancelled, the failure path also drops the cancel marker and reports failed instead of cancelled.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c18df1db96b3501cf143c67b22de86e5a58a9fdf. Configure [here](https://www.cursor.com/dashboard/bugbot).
    5. Note: GPT-6 on behalf of shivam (@shivamhwp).

      Cancellation-marker cleanup still has two gaps. The stale-target branch in interruptTurn adds an arbitrary non-active ID whenever a prompt is in flight. That ID has no matching prompt or finalizer to remove it. Separately, a late interrupt can re-add the completed turn's ID, but !settled && ... && cancelledTurnIds.delete(turnId) skips deletion once the terminal event has been published. Repeated stale or late interrupts retain these IDs for the session's lifetime.

      Ignore non-active targeted interrupts, add an active cancellation marker only while prompts are in flight, and let the last finalizer remove its marker even when settled already prevents another terminal event. Keep the shared marker until all steering prompts drain. The deliberate decision to retain per-thread semaphores remains valid and should stay separate from cancellation-marker cleanup.

    6. Note

      This comment is posted by Julius' dot

      This also changes approval responses to select the agent's advertised permission option IDs, with a separate wire-level regression test. That fixes a different problem from turn ownership, cancellation and terminal-event settlement, so the PR does not meet the one-problem rule. Please split the permission-option mapping and its test from the lifecycle work, then request reconsideration of the focused PRs.

    7. juliusmarminge closed this

Sign in to join this conversation.