Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(opencode): settle pending approvals on session teardown #7173

Closedmaslinedwin(GitHub profile, opens in a new tab)wants to merge 5 commits intomain fromrefs/pull/7173/headopened View on GitHub

Summary

Fixes #7113.

OpenCodeAdapter never resolved pending permission (or question) requests when a session tore down. Those rows stayed pending in projection_pending_approvals, pending_approval_count never returned to zero, and the thread could not be settled.

Stop, replace-session, stopAll, and unexpected-exit paths now emit request.resolved / user-input.resolved as cancelled before tearing down the session — the same contract Claude and Grok already follow.

Test plan

  • Start an OpenCode thread, trigger a permission prompt, stop the session
  • Confirm the thread can be settled without editing state.sqlite
  • Confirm a follow-up turn on a new session still works

Note

Medium Risk Touches session lifecycle and runtime event projection for approvals, but behavior is localized to OpenCodeAdapter and aligned with other providers, with targeted tests.

Overview Fixes stuck pending approval/user-input state when an OpenCode session ends without a user response (threads could not settle because projection_pending_approvals never cleared).

OpenCodeAdapter now runs settleOpenCodePendingAsCancelled before teardown: emits request.resolved with decision cancel for open permissions and user-input.resolved with empty answers for open questions. This is wired into stopSession, stopAll, session replace in startSession, unexpected exit, and the layer finalizer (provider remove/replace without stopAll).

Each session gets acceptingRequests plus a pendingGate semaphore so teardown cannot race with in-flight permission.asked / question.asked handlers (late events auto-cancel instead of opening new requests). Tests cover stop, stopAll, and scope close.

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

Note

Settle pending permission and question requests as cancelled on session teardown

  • Adds settleOpenCodePendingAsCancelled to OpenCodeAdapter.ts, which emits request.resolved (decision cancel) and user-input.resolved (empty answers) for all pending requests before session teardown.
  • Wires settlement into stopSession, stopAll, startSession (when replacing an existing session), the adapter finalizer, and the unexpected-termination handler.
  • Adds acceptingRequests (Ref<boolean>) and pendingGate (Semaphore) to each session context to block new requests once teardown begins and serialize event handling against settlement.
  • Behavioral Change: incoming permission.asked and question.asked events received after teardown starts are now auto-cancelled/resolved instead of opening new requests.
Macroscope summarized debfa76.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 175e3795-ade8-4e05-89ee-bb0847290918

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. One issue found in settleOpenCodePendingAsCancelled: both Effect.forEach callbacks use yield* inside a plain (non-generator) arrow function, which does not compile.

      Posted via Macroscope — Effect Service Conventions
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      This PR introduces new concurrency synchronization (Semaphore, acceptingRequests flag) to settle pending permissions on session teardown. While well-tested, the addition of concurrency primitives and changes to event emission timing across multiple teardown paths represents significant runtime behavior change warranting human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. One finding: the new teardown behavior changes backend event semantics but has no focused test coverage.

      Posted via Macroscope — Effect Service Conventions
      @@ -670,0 +694,21 @@
      694+ }),
      695+ { discard: true },
      696+ );
      697+ const questions = [...context.pendingQuestions.keys()];
      698+ yield* Effect.forEach(
      699+ questions,
      700+ (requestId) =>
      701+ Effect.gen(function* () {
      702+ yield* emit({
      703+ ...(yield* buildEventBase({
      704+ threadId: context.session.threadId,
      705+ requestId,
      706+ })),
      707+ type: "user-input.resolved",
      708+ payload: { answers: {} },
      709+ });
      710+ context.pendingQuestions.delete(requestId);
      711+ }),
      712+ { discard: true },
      713+ );
      714+ });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      This changes backend behavior (pending permissions/questions are now settled as cancel / empty answers on stop, resume-restart, unexpected exit, and stopAll, and late permission.asked / question.asked events are auto-resolved once acceptingRequests is false), but no tests accompany it. Consider adding focused cases to OpenCodeAdapter.test.ts — the existing it.layer(OpenCodeAdapterTestLayer) harness can push a permission.asked event and then assert the emitted request.resolved on stop/stopAll — so the new settle path is pinned.

      Posted via Macroscope — Effect Service Conventions

      Added focused OpenCodeAdapter tests in cead9c1b: a permission.asked event is opened, then stopSession / stopAll emit request.resolved with decision: "cancel".

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    6. This looks like the right fix - thank you!

      I hit this exact OpenCode failure mode: one completed thread retained 4 historical pending permission requests after interrupted/error turns. The UI showed the stale provider-callback error, and the thread could not be settled.

      With T3 fully quit, I manually resolved those rows as cancel and recomputed pending_approval_count to 0, which immediately removed the approval blocker. This PR’s teardown settlement matches what was missing and should prevent recurrence.

      Small follow-up thought, probably separate scope: already-affected users may need a migration or reconciliation path for historically valid but now-unanswerable pending requests.

    7. Cursor Bugbot has reviewed your changes using high 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 debfa7617dbaab3000bb98800671c53883d82a44. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -653,4 +709,8 @@
      653709 // the remaining cleanups.
      654710 yield* Effect.forEach(
      655711 contexts,
      656- (context) => Effect.ignoreCause(stopOpenCodeContext(context)),
      712+ (context) =>
      713+ Effect.ignoreCause(
      714+ settleOpenCodePendingAsCancelled(context).pipe(
      715+ Effect.andThen(stopOpenCodeContext(context)),
      716+ ),

      Settle failure skips session teardown

      Medium Severity

      settleOpenCodePendingAsCancelled is chained with Effect.andThen(stopOpenCodeContext) under Effect.ignoreCause in stopAll and the layer finalizer. If settlement fails after flipping acceptingRequests, teardown never runs and the error is swallowed, so the OpenCode session scope and child process can leak. emitUnexpectedExit already ignores settle failures and continues teardown; replace/stopSession share the same settle-then-stop short-circuit.

      Additional Locations (2)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit debfa7617dbaab3000bb98800671c53883d82a44. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -976,0 +1035,21 @@
      1035+ }
      1036+ context.pendingPermissions.set(event.properties.id, event.properties);
      1037+ yield* emit({
      1038+ ...(yield* buildEventBase({
      1039+ threadId: context.session.threadId,
      1040+ turnId,
      1041+ requestId: event.properties.id,
      1042+ raw: event,
      1043+ })),
      1044+ type: "request.opened",
      1045+ payload: {
      1046+ requestType: mapPermissionToRequestType(event.properties.permission),
      1047+ detail:
      1048+ event.properties.patterns.length > 0
      1049+ ? event.properties.patterns.join("\n")
      1050+ : event.properties.permission,
      1051+ args: event.properties.metadata,
      1052+ },
      1053+ });
      1054+ }),
      1055+ );

      Reply handlers race with settlement

      Medium Severity

      permission.replied, question.replied, and question.rejected still mutate pending maps and emit resolves outside pendingGate, while settlement snapshots and cancels under that gate. A reply in flight during stop can emit an accept/answer resolve alongside teardown’s cancel for the same id, so projection keeps the last decision and the activity log shows conflicting resolutions.

      Additional Locations (2)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit debfa7617dbaab3000bb98800671c53883d82a44. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. Closing as a duplicate of #8441, which covers the same OpenCode teardown cleanup and also handles interruption and request races. Keeping the work and review there. Thanks!

    9. juliusmarminge closed this

Sign in to join this conversation.