Skip to content

recover from corrupt ace multi-select editor state - #18424

Merged
gtritchie merged 5 commits into
mainfrom
bugfix/13605-multiselect-corruption
Aug 4, 2026
Merged

gtritchie merged 5 commits into
mainfrom
bugfix/13605-multiselect-corruption

Conversation

@kevinushey

@kevinushey kevinushey commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

Addresses #13605.

The problem

An exception escaping into Ace's multi-select machinery permanently corrupts a source editor tab, producing the long-reported symptom cluster from #13605 (and the related #13436): mouse text selection stops working, typed input is silently discarded, multi-select mode cannot be exited, and editor commands (e.g. Ctrl+Shift+M) can land in a previously focused tab. Only reloading the IDE recovers.

Root cause: Ace's forEachSelection() and $moveLines() temporarily mutate selection state -- swapping in a throwaway Selection, silencing the real selection's _eventRegistry, setting inVirtualSelectionMode, detaching the range list -- and restore it only on the way out, with no exception protection. One mid-operation throw (from any document/selection listener) strands all of it. The stranded state is silent: with the listeners gone, nothing throws afterward; the editor just stops responding.

The fix (RStudio-side only; bundled Ace untouched)

Ace behavior is deliberately left as-is so the defects can be filed upstream against stock Ace with the deterministic repro developed here (a follow-up task).

  • acesupport/acemixins/multi_select_guard.js (the load-bearing piece): wraps Editor.forEachSelection / Editor.$moveLines with snapshot/restore semantics. The wrappers know nothing about what the wrapped code does in between, so they should survive Ace updates. Exceptions still propagate; only cleanup becomes unconditional.
  • AceEditorNative.isMultiSelectStateCorrupt() / resetMultiSelectState(): extends the mouse cannot select any text in source editor #13436 mouse-handler recovery to detect and repair leftover multi-select corruption (stranded temporary selection, editor/selection mode-flag disagreement, empty or desynced range bookkeeping, detached range list). Runs on tab activation and now also (deferred) on editor focus, with a Debug.log line so dailies show which corruption fires in the wild.
  • AceEditor.focus() eagerly updates s_lastFocusedEditor, so EXECUTION_POLICY_FOCUSED command routing cannot go stale when the DOM focus event doesn't re-fire (the "shortcuts appear in another tab" symptom).
  • applyChanges() / doSetCode() exit multi-select mode first; these run from async contexts (e.g. visual-mode canonical save) and previously drove Ace command streams through multi-select handling mid-corruption-window.
  • AceEditorNative.setHandler() is now $entry-wrapped -- it was the one Ace-to-GWT callback that let GWT exceptions propagate raw into Ace's synchronous dispatch.
  • Removed a stray debugger; statement that has shipped in both ace bundles since the add null check in multiselect change handler #14804 null guard (June 2024); it froze the IDE whenever devtools were open and the guard line was reached -- exactly the situation when we ask reporters to debug. Note: the corresponding patch in the rstudio/rstudio-ace fork branch (rstudio/globemaster-allium) should also be amended, or the next sync-ace-commits will resurrect it.

Reviewed but intentionally not changed: ShortcutManager's disableCount_ (a stuck counter kills app-wide shortcuts). The ModalDialogBase open/close pairing is already idempotent and correctly ordered; a heuristic reset risks enabling shortcuts during a modal, so it stays as-is.

Testing

New Playwright spec multiselect_recovery.test.ts:

  1. Exception during multi-cursor edit: injects a one-shot throwing document change listener, types with 3 cursors active, and asserts the abort was real (marker exception recorded, partial per-range application) and that the editor survives (no stranded temporary selection, inVirtualSelectionMode clear, Escape exits multi-select, typing still lands).
  2. Recovery on reactivation: manually plants the stuck flags, switches tabs away and back, and asserts the corrupt state was detected and reset.

Negative control (validated locally, not committed): with only the mixin's require commented out, test 1 deterministically reproduces the #13605 corruption -- inVirtualSelectionMode stuck true, temporary selection (selection.index === 2) still installed -- and fails. This doubles as the upstream repro recipe.

Companion spec multiselect_basic.test.ts pins the everyday multi-select behaviors the guard wrappers must leave intact -- typing at keyboard-added cursors, single-step undo of a multi-cursor edit, splitIntoLines, and moving lines with multiple cursors -- driven through the real keyboard shortcuts (so Ctrl+Alt+Down dispatches the addCursorBelow AppCommand, also exercising the EXECUTION_POLICY_FOCUSED routing).

Also run locally: ant test (572 unit tests OK; 608 testpage assertions pass, exercising the modified acesupport), ant draft, and e2e typecheck.

Note for reviewers: ant acesupport alone does not update what the dev shim serves -- acesupport.js is inlined into the compiled GWT output as a ClientBundle resource, so acesupport changes need ant draft to be visible.

An exception escaping into Ace's multi-select machinery could leave a
source editor permanently broken until the IDE was reloaded: mouse text
selection dead, typed input silently discarded, multi-select mode
impossible to exit, and editor commands landing in a previously focused
tab. Ace's forEachSelection() and $moveLines() mutate selection state
(temporary Selection object, silenced event registry,
inVirtualSelectionMode, detached range list) and restore it with no
exception protection, so a single mid-operation throw stranded that
state permanently.

This change fixes and hardens things on the RStudio side, leaving the
bundled Ace behavior untouched so the defects can be reported upstream
against stock Ace:

- acesupport mixin (mixins/multi_select_guard) wraps forEachSelection
  and $moveLines with snapshot/restore semantics, so an aborting
  exception no longer strands the temporary selection, the silenced
  event registry, inVirtualSelectionMode, or a detached range list
- AceEditorNative gains isMultiSelectStateCorrupt() and
  resetMultiSelectState(), extending the #13436 mouse-handler recovery
  to detect and repair leftover multi-select corruption; the check now
  also runs (deferred) when an editor regains focus
- AceEditor.focus() updates the last-focused-editor tracking eagerly,
  so editor commands (e.g. insert pipe operator) cannot target a
  previously focused tab when the DOM focus event does not re-fire
- applyChanges() and doSetCode() exit multi-select mode before driving
  command streams / replacing the document from async contexts
- AceEditorNative.setHandler() callback is now $entry-wrapped, closing
  the one Ace-to-GWT callback that let GWT exceptions propagate raw
  into Ace's dispatch
- removed a stray debugger; statement (shipped in both ace bundles
  since the #14804 null guard) that froze the IDE whenever devtools
  were open and the guard was reached

The new Playwright spec injects a throwing document listener during a
multi-cursor edit and asserts the editor survives; without the mixin it
reproduces the corruption (stuck inVirtualSelectionMode, stranded
temporary selection) deterministically.

Addresses #13605.
@kevinushey kevinushey added this to the 2026.08 (Yellow Yarrow) milestone Jul 31, 2026
@posit-snyk-bot

posit-snyk-bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@kevinushey

Copy link
Copy Markdown
Collaborator Author

Upstream issue filed with the deterministic repro from this PR's negative control, verified against stock ace-builds 1.44.0: ajaxorg/ace#5996

@kevinushey
kevinushey requested a review from gtritchie July 31, 2026 00:45
@github-actions

github-actions Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
1944 0 360 6
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ desktop-linux 482 0 90 1
✅ desktop-macos 486 0 86 2
✅ desktop-windows 488 0 90 1
✅ server-linux 468 0 94 2
✅ setup 20 0 0 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit c40c40273014981d86729750634804d5d4d0044d - Run #436

@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Actionable items from an automated multi-agent review. Claims below were traced against the bundled Ace source (.../text/ace/ace-uncompressed.js) rather than assumed.

Critical

  1. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorWidget.java:176 — the new deferred focus check makes the pre-existing mouse-handler check fire in the middle of an Alt+drag block selection, collapsing the user's rectangular selection. Trace: multi_select's onMouseDown block branch (ace-uncompressed.js:57012-57015) calls e.stop() and sets inVirtualSelectionMode = true for the drag. e.stop() sets defaultPrevented, so _dispatchEvent (:899-901) skips DefaultHandlers.onMouseDown → captureMouse never runs → $mouseHandler.isMousePressed stays false. focusEditor is a separate DOM mousedown listener on the same element (:40677, registered :40704), and MouseEvent.stopPropagation is not stopImmediatePropagation, so it still runs → editor.focus() → Ace "focus" signal → the new deferred checkForCorruptEditorState(). That runs isMouseHandlerStateCorrupt(), whose inVirtualSelectionMode && !handler.isMousePressed branch (AceEditorNative.java:660) is now true, so resetMouseHandlerState() (:605) clears inVirtualSelectionMode and $clickSelection mid-drag. onMouseSelectionEnd's selection.addRange(rectSel[i]) loop then reaches $checkMultiselectChange (:57536), which calls toSingleRange(...). Precondition is only that the editor wasn't already focused when the Alt+drag started (e.g. clicking from the Console straight into a column selection). The add path (Ctrl+Alt drag) is unaffected — it doesn't call e.stop(), so isMousePressed is true. Fix: don't run the mouse-handler branch from the focus path, or skip the whole deferred check while inVirtualSelectionMode is set at focus time.

Important

  1. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/AceEditorNative.java:768 — resetMultiSelectState() tears down multi-select by hand and never restores session.$undoSelect. Entering multi-select sets it false (ace-uncompressed.js:57228); Ace restores it in $onRemoveRange (:57272), which this path bypasses. undoChanges/redoChanges gate cursor restoration on it (:45757, :45775), so after a "successful" recovery, undo/redo silently stops moving the cursor to the reverted region for the rest of that document's life. Fix: set session.$undoSelect = true; alongside selection.inMultiSelectMode = false;.

  2. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java:1213 and :1331 — exitMultiSelectMode() is a silent no-op in exactly the state these calls guard against. Ace's implementation (ace-uncompressed.js:57530-57533) returns early when inVirtualSelectionMode is set — the flag isMultiSelectStateCorrupt() deliberately declines to treat as corruption (AceEditorNative.java:710-719). So when the editor is stranded, doSetCode/applyChanges replaces the document with the stale multi-select bookkeeping still in place, which is what the comments at :1208-1211 and :1327-1330 say they prevent. AceEditorNative.exitMultiSelectMode() (:479) is a bare passthrough, so no caller can detect the no-op. Fix: re-check inMultiSelectMode() afterwards and fall back to resetMultiSelectState().

  3. e2e/rstudio/tests/panes/editor/multiselect_recovery.test.ts:94 — the drainClientExceptions assertion appears unreachable, which would make test 1 fail (or, if the assertion is relaxed, make the fault injection unverifiable). window.rstudio.errors is fed only by GWT's UncaughtExceptionHandler wrapper (ApplicationAutomation.java:361-381) and an unhandledrejection listener (:892); there is no window.onerror hook. The injected document change listener throws from inside Ace's _signal (ace-uncompressed.js:903-910, no try/catch), reached from Ace's raw textarea input listener — the $entry frames near that path (AceKeyboardPreviewer.java:69, the session-change handler at AceEditorNative.java:162) have already unwound. So the throw escapes as a raw pageerror, which rstudio.fixture.ts:58 only buffers for failure diagnostics. Please confirm by running the spec. Fix if confirmed: have injectThrowingChangeListener (e2e/rstudio/pages/ace_editor.page.ts:274) set a window sentinel immediately before throwing and assert on that instead — the intent (prove the injection fired) is right, the routing assumption isn't.

  4. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java:1539 — focus() claims s_lastFocusedEditor before calling widget_.getEditor().focus(), so the field is claimed even when the DOM focus never lands (hidden or detached widget, deferred/dialog-callback focus() on a tab the user has since left). Nothing undoes it except detach() when it happens to match (:541) or the next successful focus. That field is the sole routing key for EXECUTION_POLICY_FOCUSED commands (:594) and for addin getEditorContext in visual mode, so a focus() that doesn't take now produces the same "shortcuts land in another tab" symptom this PR fixes. Fix: widget_.getEditor().focus(); if (widget_.getEditor().isFocused()) s_lastFocusedEditor = this; — isFocused() already exists at AceEditorNative.java:134.

  5. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorWidget.java:766 — the field diagnostics don't work, which undercuts the stated reason for the logging. isMultiSelectStateCorrupt() has seven distinct return true sites (AceEditorNative.java:686, 688, 692, 698, 702, 704, 707) collapsed into one boolean and one fixed string, so a report can't say which fired. And Debug.log is GWT.log + console.log (core/client/Debug.java:44-48); GWT.log is optimized out in production, leaving only console.log — invisible on Server unless devtools happen to be open, and debug-level (off by default) on Desktop. Fix: return a reason code instead of a boolean and report through the Server.logException(ClientException.create(...)) path the uncaught handler already uses.

  6. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/AceEditorNative.java:772-775 — a partial $onSingleSelect() failure is recorded as success and permanently silences the detector. $onSingleSelect (ace-uncompressed.js:57451-57460) sets inMultiSelectMode = false first, then unsets the style, removes the multi-select keyboard handler, and removes the "exec" default handler. A throw before removeDefaultHandler leaves $onMultiSelectExec installed — which routes every subsequent command back into forEachSelection and re-adds a range per command (:57461-57467). The empty catch swallows it and line 775 sets inMultiSelectMode = false anyway, so isMultiSelectStateCorrupt()'s flag-mismatch check (:692) sees both flags false and reports healthy from then on. Fix: log in the catch, retry commands.removeDefaultHandler("exec", this.$onMultiSelectExec) explicitly, and leave inMultiSelectMode untouched so the detector keeps flagging.

  7. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/AceEditorNative.java:776-781 — the outer logging catch is unreachable for every failure it claims to report. The four inner catch (e) { } blocks at :741, :753, :759, :773 intercept the only four operations in the function that can plausibly throw; what's left inside the outer try is property assignment, .slice(), and ranges.length = 0. As written, "no error logged" does not mean "reset succeeded" — which is the opposite of what the comment promises.

Test gaps

  1. e2e/rstudio/tests/panes/editor/multiselect_recovery.test.ts — no test that a legitimate multi-cursor selection survives a tab switch or refocus. isMultiSelectStateCorrupt() now runs on every activate and every focus, evaluating six independent heuristics; a false positive silently destroys the user's extra cursors (see finding 1 for a concrete instance). Suggested: 3 cursors via addCursorBelow, documentOpen away and back, assert rangeCount === 3 and that typing lands on all three lines.

  2. e2e/rstudio/tests/panes/editor/multiselect_recovery.test.ts:104-110 — test 2 covers the weakest detector branch and the least realistic corrupt shape. Planting inMultiSelectMode/inVirtualSelectionMode on the editor with selection.inMultiSelectMode left false trips only the flag-mismatch check at AceEditorNative.java:692. The shapes a real abort leaves — temp Selection still installed (:686, :688), multi-select with stale/desynced ranges (:698, :704, :707) — are never exercised. In the planted state Ace's multi-select keyboard and "exec" handlers were never installed, so resetMultiSelectState()'s $onSingleSelect() teardown is a no-op and the "recovered editor accepts input" assertion at :137-140 would pass even if the reset removed nothing. Suggested: build a real 3-cursor selection, corrupt it in a way the JS guard can't mask (e.g. selection.rangeList.detach(), tripping :707), reactivate, then assert typing inserts exactly one character (full-value equality, not toContain).

  3. src/gwt/acesupport/acemixins/multi_select_guard.js:79-104 — the $moveLines guard has no coverage. Reachable with the helpers already added: 3 cursors → injectThrowingChangeListener → execCommand('movelinesdown') → assert inVirtualSelectionMode === false and the range list re-attached. getMultiSelectState() (e2e/rstudio/pages/ace_editor.page.ts:246) doesn't expose rangeList.session, so add e.g. rangeListAttached.

  4. e2e/rstudio/tests/panes/editor/multiselect_recovery.test.ts:113-116 — the test can't attribute the repair to tab activation. documentOpen also focuses the editor, so the deferred focus check (AceEditorWidget.java:176) fires too; removing checkForCorruptEditorState() from onActivate() (:738) would likely leave the test green despite its name. Either split into two tests (focus path: keep the tab active, activateConsole then activateSource) or rename to "on reactivation or refocus".

  5. e2e/rstudio/tests/panes/editor/multiselect_recovery.test.ts:53-55, 88, 140 — assertions too weak to prove what they claim. :53-55 asserts only editorInMultiSelectMode === true, not that there are three cursors — assert rangeCount === 3. toContain('Z') (:88) and toContain('Q') (:140) would pass with a stuck multi-select inserting three characters — assert the full expected value.

Comments

  1. src/gwt/acesupport/acemixins/multi_select_guard.js:18-21 — the header attributes the union of both functions' behavior to each. forEachSelection (ace-uncompressed.js:57487-57527) swaps in a temp Selection, silences _eventRegistry, and sets inVirtualSelectionMode; it never touches the range list. $moveLines (:49993-50044) sets inVirtualSelectionMode and detaches the range list; it never creates a temp Selection and never touches _eventRegistry. The wrappers below are per-function correct, so the header contradicts its own implementation — a maintainer could reasonably "fix" the $moveLines wrapper by adding an event-registry restore it doesn't need. Fix: one sentence per function.

  2. src/gwt/acesupport/acemixins/multi_select_guard.js:30-32 — "They intentionally know nothing about what the wrapped functions do in between, so they should remain valid across Ace updates" is contradicted 26 lines later by the file's own comments at :58-60 and :94-95. The wrappers depend on four Ace-private details: reassignment of session.selection, Selection.detach(), the private field _eventRegistry, and the private field rangeList.session. If Ace renames any of them the guard degrades to a silent no-op. Fix: state the coupling and the fields to re-verify on an Ace update.

  3. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/AceEditorNative.java:669-671 and e2e/rstudio/tests/panes/editor/multiselect_recovery.test.ts:3-5 — both describe forEachSelection in the present tense as having "no exception protection", which this PR removes by wrapping it. Stale on landing. The detector's real remaining justification is the multi-select paths the guard doesn't cover (toSingleRange, addRange, $onRemoveRange) and state that predates the mixin.

  4. e2e/rstudio/tests/panes/editor/multiselect_recovery.test.ts:104-105 — "simulate the stuck state left behind by an aborted multi-select operation (editor flags set with no ranges)" misdescribes both the planted state and the detection. A real abort leaves a temp Selection on session.selection with selection.inMultiSelectMode still true; and "with no ranges" implies the !selection.rangeCount branch fires, which it can't — that branch is nested inside if (selection.inMultiSelectMode) (AceEditorNative.java:695), false here. Detection actually comes from the mismatch at :692. This matters because the comment is what tells a maintainer which branch the test guards.

  5. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/AceEditorNative.java:770-771 — "and the cursor style": $onSingleSelect calls unsetStyle("ace_multiselect") (an editor CSS class) plus renderer.updateCursor(). The phrase conflates the two and matches neither. Fix: "the ace_multiselect style class".

  6. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/AceEditorNative.java:683-684 — "'session.multiSelect' always refers to the session's real selection object" is true only once the session has been attached to an editor; on a session that hasn't, the property doesn't exist, which the very next line's session.multiSelect && ... guard tacitly admits. Fix: scope the claim, and note that "only temporary selections carry an index" is an absence claim over the vendored bundle that should be re-checked on Ace updates — if a future Ace sets index on a real selection, every focus event reports corruption and silently drops the user's cursors.

  7. e2e/rstudio/utils/ace.ts:55-57 — "session.selection may briefly point elsewhere during multi-select operations (see Ace's multi_select.js onSessionChange)" points at the wrong function. onSessionChange (ace-uncompressed.js:57804-57811) assigns multiSelect; it never repoints session.selection. That happens in forEachSelection (:57501, :57510, :57516).

Suggestions

  1. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java:1331 — applyChanges is reached from the canonical-save path (TextEditingTarget.java:3669), so a routine Ctrl+S silently collapses a user's N cursors to one with no message and no log line. The tradeoff is defensible (it beats applying every diff hunk at every cursor), but in a PR whose thesis is that silent state loss is the bug, it deserves at least a Debug.log — or a NEWS.md note so a user who notices can find the explanation.

  2. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/AceEditorNative.java:752-754 — a mid-loop throw in removeSelectionMarkers (ace-uncompressed.js:57419-57430) leaves the remaining markers rendered and selectionMarkerCount stale, and the reset then zeroes rangeCount and clears multi-select mode so Ace's normal cleanup path can never run again. isMultiSelectStateCorrupt() checks neither $selectionMarkers nor selectionMarkerCount, so ghost highlighting would survive until reload. Low probability; worth at least logging rather than swallowing.

  3. src/gwt/acesupport/acemixins/multi_select_guard.js:66 — the bare catch (e) { } around tmpSel.detach() is justified (it's in a finally; rethrowing would mask the exception that aborted the operation) but the reason isn't written down, and a partial detach — Selection.detach is lead.detach(); anchor.detach(); (ace-uncompressed.js:42050) — leaks a document change listener. Fix: keep the swallow, add the rationale, and log via the global $Debug (injected at RStudio.java:129).

  4. src/gwt/acesupport/acemixins/multi_select_guard.js — the file has no logging at all, yet its two finally blocks are the only code that observes real Source editor randomly becomes inoperable (dysfunctional text select, multi-line editing, & inputs appear in wrong tab)  #13605 corruption at the instant it occurs and knows which state was stranded (temp selection at :61, silenced event registry at :72, stuck inVirtualSelectionMode at :75, detached range list at :96-99). All repaired silently. The propagating exception only tells you an exception happened, not whether multi-select state was stranded — which is the field-diagnosis question this PR exists to answer.

  5. src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorWidget.java:244-273 — with setHandler() now $entry-wrapped, a throw from toggleBreakpointAtPosition means the gutter click does nothing at all (arg.invokeDefaultHandler is skipped too) with no user-facing signal. The $entry change itself is right — it reports to the uncaught handler instead of unwinding into Ace's dispatch, and brings this in line with the ten other $entry sites in the file — but the sole consumer could use a targeted try/catch that tells the user the breakpoint didn't take.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Feedback posted

- run only the multi-select corruption check from the focus path: the
  mouse-handler check misfires during an Alt+drag block selection, whose
  mousedown stops the event before the default capture handler runs
  (isMousePressed stays false while inVirtualSelectionMode is set)
- have the corruption detector return a reason string so recovery logs
  say which corruption branch fired
- resetMultiSelectState: restore session.$undoSelect (addRange clears
  it, and the bypassed $onRemoveRange is what normally restores it);
  log failures in the individual recovery steps; repair the selection
  marker count after a failed marker removal; and on a $onSingleSelect
  failure remove the 'exec' rerouting handler explicitly and keep the
  editor flagged as corrupt so the reset is retried
- doSetCode/applyChanges: reset stranded corrupt state instead of
  calling the silently no-op exitMultiSelectMode; log when extra
  cursors are dropped
- focus(): claim s_lastFocusedEditor only when focus actually landed,
  so focusing a hidden or detached editor can't steal command routing
- multi_select_guard: describe each wrapped function's behavior
  separately, name the Ace internals the wrappers depend on, and log
  which stranded state a finally block repaired
- e2e: prove fault injection with a window sentinel instead of
  exception routing; assert exact cursor and insertion counts; add
  coverage for the $moveLines guard, a healthy multi-cursor selection
  surviving tab switches, a detached-range-list corruption shape, and
  focus-path repair without a tab switch
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Applied in d34fbb7 -- item-by-item, numbered as in the review:

1: Confirmed the mid-drag reset (e.stop() -> captureMouse skipped -> focusEditor -> deferred check), fixed by keeping the mouse-handler check on the activation path only. One correction: the selection-collapse mechanism doesn't hold -- editor.inMultiSelectMode is false during a block drag (toSingleRange at :57031), so $checkMultiselectChange never fires; the harm was mid-drag $clickSelection/renderer.$isMousePressed clobbering. "Skip the whole deferred check while inVirtualSelectionMode" would over-correct: a stuck flag is a corruption symptom; the multi-select check (which already excludes it) still runs on focus.

2: Confirmed; the reset now restores session.$undoSelect.

3: Confirmed; doSetCode/applyChanges now reset when the detector flags corruption, exit otherwise. An unconditional reset fallback would tear down a live Alt+drag, so it's corruption-gated.

4: Ran the spec as requested -- it passes as written: the injected throw is recorded in window.rstudio.errors as a GWT JavaScriptException, so it does reach the uncaught-exception handler. The hardening is right anyway: injection is now proven by a window sentinel, and the drain only asserts no unexpected exceptions (the evaluate-driven $moveLines variant surfaces the throw through the evaluate, not the record).

5: Applied as suggested; verified $isFocused is set synchronously by textarea.focus(), including already-focused and backgrounded-window cases.

6: The detector now returns a reason string, logged on recovery. Kept Debug.log over Server.logException -- that path files client crashes; a recovered condition doesn't belong in crash monitoring. Happy to wire the dormant Server.log(WARNING) RPC if dailies visibility is wanted.

7: Confirmed; on failure the reset removes the exec rerouting handler explicitly, logs, and re-sets inMultiSelectMode ($onSingleSelect clears it as its first step, so leaving it untouched wasn't enough to keep the detector flagging).

8: Confirmed; inner catches now log with step context, outer catch is annotated as backstop.

9-13: All applied -- healthy 3-cursor selection survives tab switch (typing lands 3x), $moveLines guard covered via movelinesdown with rangeListAttached exposed, the corrupt shape is a real 3-cursor selection with a detached range list, focus-path repair has its own no-tab-switch test, and assertions use exact counts/values. 5/5 pass locally.

14-20: All comment fixes applied (per-function mixin header, named Ace-internal dependencies, javadoc pointer to the guard plus the unwrapped addRange/toSingleRange/$onRemoveRange paths, flag-mismatch test comment, ace_multiselect wording, scoped session.multiSelect claim, forEachSelection attribution in ace.ts).

21: Added a Debug.log when extra cursors are dropped; skipped the NEWS note (the #13605 entry already describes the recovery behavior).

22: Confirmed; failures logged and the marker count repaired after a failed removal. Detector left unchanged -- flagging cosmetic marker residue would trigger full resets.

23-24: Guarded $Debug logging added in both finally blocks (per repaired state) plus the detach-swallow rationale.

25: Leaving as-is -- the $entry wrap already reports the exception through the standard handler; user-facing breakpoint-failure UX is beyond this PR's scope.

kevinushey and others added 2 commits August 3, 2026 14:01
Pin the everyday multi-select behaviors that the multi_select_guard
wrappers must leave intact -- typing at keyboard-added cursors,
single-step undo of a multi-cursor edit, splitIntoLines, and moving
lines with multiple cursors -- driven through the real keyboard
shortcuts. Addresses #13605.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM!

@gtritchie
gtritchie merged commit db0cbef into main Aug 4, 2026
1 of 2 checks passed
@gtritchie
gtritchie deleted the bugfix/13605-multiselect-corruption branch August 4, 2026 16:28
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.

3 participants