Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(remote): stop button gives immediate feedback and prevents stuck thinking on remote server #8619

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

Fixes #8618. Related: #4713, #8802.

Problem

Using a remote T3 Code server (relay/tunnel), clicking the red Stop button gives no UI feedback and the thread can stay stuck in Thinking / Working indefinitely.

Root causes, all verified on current main:

  1. No optimistic stopping state — onInterrupt fires and waits silently; the Stop button has no pending/disabled variant (contrast isStoppingBackgroundWork → Stopping...).
  2. Stale turnId drops the interrupt — the client only includes turnId when the snapshot has it, and both the client reducer (threadReducer.ts) and the server projection (ProjectionPipeline.ts) early-return for turnId === undefined.
  3. Session hang on success — ProviderCommandReactor only tears down on interrupt failure. When the provider ignores the abort (or the turn already ended without a session-set), the session stays running and every further Stop is accepted with no effect.
  4. Queue buildup — interruptTurn is serial per thread, so rapid Stop clicks pile up behind each other.

Fix

  • Immediate feedback (web + mobile): isStoppingTurn / isStoppingThread set on click, cleared on failure or when the session leaves running/starting, reset on thread switch. The Stop button shows a spinner, is disabled, and announces Stopping.
  • turnId fallback: turnId-less thread.turn-interrupt-requested falls back to the session-pinned turn in both the client reducer and the server projection.
  • Server escalation: the reactor releases wedged sessions on Stop — immediately when the pinned turn already ended before this request (completedAt < createdAt guard keeps healthy in-flight interrupts on the normal path), or when a repeat Stop arrives 5s+ after the previous one for the same still-running session. Release = best-effort stopSession + forced session-set stopped with a visible reason, so the thread is resumable (same end state as the manual SIGTERM workaround in #4713).
  • interruptTurn is now singleFlight per thread so rapid clicks share one in-flight request.

Also restores the @t3tools/shared/stripTerminalEscapes export dropped while merging main (fixes server typecheck).

Verification

  • vp test run — ProviderCommandReactor.test.ts (54, incl. 3 new: zombie release, repeat-stop escalation, in-grace negative), ProjectionPipeline.test.ts (28, incl. 1 new turnId-less fallback), threadReducer.test.ts (36, incl. 2 new), ComposerPrimaryActions.test.tsx (17, incl. 1 new), plus threads-atoms / threads-sync.
  • Scoped typechecks green: t3 (server), @t3tools/client-runtime, @t3tools/web, @t3tools/mobile, @t3tools/shared. Scoped vp lint exit 0.
  • Manual (remote): npx t3 --share on remote, connect via pairing URL, start a long turn, click Stop → button feedback instantly, Thinking/Working clears even if the provider is wedged; repeat Stop escalates within seconds.

Note

Fix stop button feedback and escalate repeat-stop for stuck remote sessions

  • Adds optimistic stopping state to web and mobile stop buttons. Buttons disable, show a "Stopping" label or spinner, and clear the state on interrupt failure or when work finishes.
  • Fixes client and server projection for interrupt events without turnId by falling back to the thread session's activeTurnId.
  • Adds repeat-stop escalation in ProviderCommandReactor to stop wedged sessions. A repeated stop after 5 seconds invokes a full session stop instead of a normal interrupt.
  • Adds stripTerminalEscapes and sanitizeTerminalValue utilities in stripTerminalEscapes.ts to remove terminal escape sequences from CLI output and model option values.
  • Risk: ThreadRouteContent retains the prior stopping value when switching directly between two active threads, as the identity change does not clear the state.
Macroscope summarized c8b4b3f.
    1. 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: 4c863cd9-f882-4a7c-83ef-003675af4709

      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

      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. @@ -0,0 +1,17 @@
      1+/**
      2+ * Strip terminal escape sequences from captured CLI stdout.
      3+ *
      4+ * OpenCode's CLI (and potentially other provider CLIs) can emit OSC title
      5+ * sequences (`ESC ]0;<title> BEL` / `ESC \`) and ANSI CSI color codes directly
      6+ * to stdout, even when stdout is a pipe. When T3 Code captures that output
      7+ * via `ChildProcessSpawner`, those bytes pollute structured parsing — e.g.
      8+ * `opencode agent list` becomes `\x1b]0;t3code: ready\x07build (primary)`
      9+ * instead of `build (primary)`, causing the agent inventory to store a
      10+ * polluted id that later fails with `Agent not found`.
      11+ *
      12+ * This is defensive for any provider CLI; the regexes are intentionally
      13+ * permissive and also handle Ghostty/Zsh title integrations that can leak
      14+ * through `shell: true` spawns.
      15+ */
      16+const OSC_RE = /\x1b\].*?(?:\x07|\x1b\\)/g;
      17+const CSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/stripTerminalEscapes.ts:17

      stripTerminalEscapes leaves colon-form CSI sequences in the output, so \x1b[38:2::255:0:0mbuild (primary) becomes 38:2::255:0:0mbuild (primary) and the OpenCode agent-list parser drops that agent. CSI_RE only accepts [0-9;?], excluding valid ECMA-48 parameter bytes such as :, so match the complete 0x30–0x3f range.

      Suggested change
      17-const CSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
      17+const CSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/shared/src/stripTerminalEscapes.ts around line 17:
      
      `stripTerminalEscapes` leaves colon-form CSI sequences in the output, so `\x1b[38:2::255:0:0mbuild (primary)` becomes `38:2::255:0:0mbuild (primary)` and the OpenCode agent-list parser drops that agent. `CSI_RE` only accepts `[0-9;?]`, excluding valid ECMA-48 parameter bytes such as `:`, so match the complete `0x30`–`0x3f` range.
    4. One finding: the new optimistic stopping state in ChatView.tsx is never rendered, so the Stop button still gives no feedback on remote.

      Posted via Macroscope — UI Consistency
    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This is a broad production behavior change spanning remote session orchestration, event projection, command concurrency, and web/mobile Stop-state handling, including forced provider-session teardown. Unresolved substantive findings identify cases where Stop can remain unusable or leak its disabled state across threads, so the change warrants human review.

      Not approved because:

      • 3 blocking correctness issues found at or above your repo's Minimum Blocking Severity
      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. @@ -1245,0 +1363,21 @@
      1363+ // this repeat Stop escalates to a full session stop (#8618).
      1364+ if (
      1365+ previous !== undefined &&
      1366+ previous.turnId === activeTurnId &&
      1367+ Number.isFinite(requestedAtMs) &&
      1368+ requestedAtMs - previous.requestedAtMs >= INTERRUPT_ESCALATION_GRACE_MS
      1369+ ) {
      1370+ recentTurnInterrupts.delete(input.threadId);
      1371+ yield* releaseWedgedSession({
      1372+ threadId: input.threadId,
      1373+ turnId: activeTurnId,
      1374+ reason:
      1375+ `Stop did not settle the session within ` +
      1376+ `${INTERRUPT_ESCALATION_GRACE_MS / 1000}s; the session was stopped.`,
      1377+ createdAt: input.createdAt,
      1378+ });
      1379+ return true;
      1380+ }
      1381+ // Remember this request so a later repeat Stop can escalate.
      1382+ if (Number.isFinite(requestedAtMs)) {
      1383+ recentTurnInterrupts.set(input.threadId, { turnId: activeTurnId, requestedAtMs });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/ProviderCommandReactor.ts:1383

      recentTurnInterrupts grows without bound when abandoned wedged threads never emit a cleanup event, so a long-lived server accumulates one entry per thread indefinitely. Bound the map (or expire entries) when recording a stop request.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration/Layers/ProviderCommandReactor.ts around line 1383:
      
      `recentTurnInterrupts` grows without bound when abandoned wedged threads never emit a cleanup event, so a long-lived server accumulates one entry per thread indefinitely. Bound the map (or expire entries) when recording a stop request.
      @@ -1245,0 +1326,21 @@
      1326+ readonly threadId: ThreadId;
      1327+ readonly session: OrchestrationSession;
      1328+ readonly latestTurn: OrchestrationLatestTurn | null;
      1329+ readonly createdAt: string;
      1330+ }) {
      1331+ if (input.session.status !== "running") {
      1332+ return false;
      1333+ }
      1334+ const activeTurnId = input.session.activeTurnId;
      1335+ const latestTurn = input.latestTurn;
      1336+ // The pinned turn already reached a terminal state but the session still
      1337+ // claims running — release it now (#4713, #8802). The completedAt guard
      1338+ // matters: this very event's own projection also settles the turn with
      1339+ // completedAt === createdAt, and that healthy in-flight interrupt must
      1340+ // proceed to the provider instead of being mistaken for a zombie.
      1341+ if (
      1342+ latestTurn !== null &&
      1343+ (activeTurnId === null || latestTurn.turnId === activeTurnId) &&
      1344+ latestTurn.state !== "running" &&
      1345+ latestTurn.completedAt !== null &&
      1346+ latestTurn.completedAt < input.createdAt

      🟡 Medium Layers/ProviderCommandReactor.ts:1346

      The zombie check fails to release an already-completed turn when completedAt and createdAt use different valid timezone offsets, because their ISO strings are compared lexicographically rather than chronologically. Parse both IsoDateTime values before comparing them so a wedged session is released correctly.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration/Layers/ProviderCommandReactor.ts around line 1346:
      
      The zombie check fails to release an already-completed turn when `completedAt` and `createdAt` use different valid timezone offsets, because their ISO strings are compared lexicographically rather than chronologically. Parse both `IsoDateTime` values before comparing them so a wedged session is released correctly.
    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).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c8b4b3f1a1d06a407b893554c9f0fa2ab3b41d74. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -2525,3 +2525,16 @@
      25252525 threadError,
      25262526 });
      25272527 const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
      2528+ // Optimistic stopping state for remote: mirrors isStoppingBackgroundWork so Stop
      2529+ // gives immediate feedback even though session stays "running" until provider settles.
      2530+ // See fix-remote-stop-no-feedback-stuck-thinking-7h3k9p2m (issue #8618).
      2531+ const [isStoppingTurn, setIsStoppingTurn] = useState(false);
      2532+ useEffect(() => {
      2533+ if (!isWorking) {
      2534+ setIsStoppingTurn(false);
      2535+ }
      2536+ }, [isWorking]);
      2537+ useEffect(() => {
      2538+ // Per-thread: switching threads must not leak Stopping... to B
      2539+ setIsStoppingTurn(false);
      2540+ }, [activeThreadId]);

      Disabled Stop blocks wedged-session release

      High Severity

      A successful interrupt leaves isStoppingTurn / isStoppingThread set until the session leaves running, which disables Stop. maybeReleaseWedgedSession only calls stopSession on a later Stop after the 5s grace. When the provider ignores the abort, the control never re-enables and Thinking/Working never clears.

      Additional Locations (2)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c8b4b3f1a1d06a407b893554c9f0fa2ab3b41d74. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -214,3 +214,15 @@
      214214 const gitActions = useSelectedThreadGitActions();
      215215 const requests = useSelectedThreadRequests();
      216216 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
      217+ const [isStoppingThread, setIsStoppingThread] = useState(false);
      218+ const selectedThreadSessionStatus = selectedThread?.session?.status ?? null;
      219+ const selectedThreadIdentity = selectedThread
      220+ ? scopedThreadKey(selectedThread.environmentId, selectedThread.id)
      221+ : null;
      222+ useEffect(() => {
      223+ // "Stopping" holds until the session leaves running/starting; per-thread
      224+ // so a switch never leaks the state onto another thread.
      225+ if (selectedThreadSessionStatus !== "running" && selectedThreadSessionStatus !== "starting") {
      226+ setIsStoppingThread(false);
      227+ }
      228+ }, [selectedThreadIdentity, selectedThreadSessionStatus]);

      Stopping state leaks across threads

      Medium Severity

      isStoppingThread is a single boolean, and the reset effect only clears it when the newly selected session is not running or starting. Switching from a stopping thread onto another live thread leaves that thread’s Stop disabled and announced as Stopping.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c8b4b3f1a1d06a407b893554c9f0fa2ab3b41d74. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. Note

      This comment is posted by Julius' dot

      This combines the Stop feedback and session recovery fix with a separate fix for terminal escape sequences in OpenCode model, agent, skill, and variant parsing. The stripTerminalEscapes helper and its parsing callers work independently of the Stop path. The one problem rule requires these fixes to be split, so I’m closing this PR. Submit the parsing fix separately and keep the Stop changes focused; include before/after images and a short recording of the changed web and mobile Stop interaction before requesting reconsideration.

    9. juliusmarminge closed this

Sign in to join this conversation.