Skip to content

preserve browser state across continuation prompts in the debugger - #17491

Merged
kevinushey merged 5 commits into
mainfrom
bugfix/debugger-continuation-fixup
May 1, 2026
Merged

kevinushey merged 5 commits into
mainfrom
bugfix/debugger-continuation-fixup

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Intent

Addresses #17481. Two related debugger regressions introduced by #17288, both surfacing as "the debug UI doesn't appear when the debugger is activated":

  1. Top-level breakpoints (e.g. via debugSource()) never showed the highlight or call stack at all.
  2. Multi-line input at the Browse[N]> prompt could clear the captured browser context, freezing the debug UI for the rest of the session.

Summary

Top-level breakpoints (isBrowseActive() excluded R_GlobalEnv)

isBrowseActive() in RSession.cpp required the captured browser env to be != R_GlobalEnv. For top-level debugging the script is evaluated in globalenv(), so the inject's parent.frame() correctly captures R_GlobalEnv — and the check then rejected the legitimate state. onConsolePrompt took its if (*pContextDepth == 0 && !s_browserActive) return; early-return path before firing kContextDepthChanged, so the client never saw the debug context.

The right invariant is "env was captured" (non-nil), not "env is non-globalenv". R_GlobalEnv is a perfectly valid captured env when debugging at the top level of a sourced script.

Multi-line input at the Browse prompt

Continuation prompts (+ ) share the hist == 1 path with fresh REPL prompts in RReadConsole, so they were calling setBrowserActive(false) between every line of a multi-line expression at the Browse prompt. That cleared the captured s_browserEnv and stuck the cached s_browserActive (SessionEnvironment side) at FALSE, which in turn could prevent onConsolePrompt from firing a fresh kContextDepthChanged after the multi-line eval finished (the change-detection conditions all read equal because nothing had legitimately changed during the continuation detour).

A continuation prompt does not change which REPL we're in (browser or top-level), so the cached state from the prior fresh prompt should be preserved. We now detect continuation prompts via getOption("continue") and skip the setAtTopLevelPrompt / setBrowserActive updates in that case. This also tightens the atTopLevelPrompt semantics from #17352: continuation-while-in-browser now correctly reads as not at top level.

Test plan

Manual:

  • Top-level: open a script (e.g. x <- 1; y <- 22; print(x + y)), set a breakpoint on line 2, run Source (or debugSource()). Confirm the debug highlight appears at line 2 and the debugger toolbar is enabled. Pre-fix this never worked.
  • Function-level + multi-line paste: f <- function() { browser(); 1 + 1 }; f(). At Browse[1]>, paste a multi-line local({ … }) block. Confirm the highlight and call stack remain visible across the paste, and that n continues to step correctly.
  • .rs.isBrowserActive() parity: at any Browse prompt (top-level or function-level), .rs.isBrowserActive() returns TRUE. Pre-fix it returned FALSE for top-level and could read FALSE mid-multi-line.

Automated coverage in test-automation-debugger.R:

  • Multi-line paste at Browse prompt asserts .rs.isBrowserActive() is TRUE mid-eval and .ace_executing-line survives the paste.
  • Top-level breakpoint via sourceActiveDocument asserts .ace_executing-line appears at the breakpoint line.

@kevinushey kevinushey added this to the Golden Wattle milestone Apr 29, 2026
@posit-snyk-bot

posit-snyk-bot commented Apr 29, 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.

isBrowseActive() in RSession.cpp excluded R_GlobalEnv as a valid
captured browser environment. For top-level debugging (debugSource()
of a script with breakpoints, or browser() at top level), the inject's
parent.frame() correctly captures R_GlobalEnv — so the !=R_GlobalEnv
clause then rejected the legitimate state, isBrowseActive() returned
FALSE, and onConsolePrompt's early-return path fired before any
kContextDepthChanged event reached the client. The debug highlight
and debugger toolbar therefore never appeared.

Test the right invariant — that the env was captured (non-nil) — rather
than excluding R_GlobalEnv specifically. R_GlobalEnv is a perfectly
valid captured env when debugging at the top level of a sourced script.

Adds a top-level breakpoint regression test that mirrors the reproducer
from #17481.

preserve browser state across continuation prompts in the debugger

Continuation prompts ("+ ") share the hist == 1 path with fresh REPL
prompts in RReadConsole, so they were calling setBrowserActive(false)
mid-parse on every line of a multi-line expression entered at the
Browse[N]> prompt. That cleared the captured browser environment,
flipped the cached browser-active flag to false, and could prevent the
client from receiving a kContextDepthChanged event when state didn't
appear to change after the multi-line eval — leaving the call stack
pane empty and the source-editor debug highlight stale.

Detect continuation prompts via getOption("continue") and skip the
setAtTopLevelPrompt / setBrowserActive updates in that case. The
underlying REPL (browser or top-level) hasn't changed across a
continuation, so the cached state should be preserved from the prior
fresh prompt.

Regression introduced by #17288.

replace em-dashes with ascii dashes in debugger test

handle nested debugger in test

still update top-level prompt flag at continuation prompts

The previous commit skipped both setAtTopLevelPrompt and setBrowserActive
at continuation prompts on the theory that the underlying REPL state had
not changed. But setAtTopLevelPrompt(false) is called right before each
line of input is returned to R (RStdCallbacks.cpp:440), so when R issued
the "+ " prompt for the next line of a multi-line expression, the flag
remained false instead of bouncing back to true.

NotebookQueue::process() bails out when isAtTopLevel() is false, so it
deferred the next line of any multi-line chunk expression and never
resumed -- leaving R hung at the "+ " prompt. This regressed the
"multiline expressions in chunks execute without hanging" automation
test.

Restore the atTopLevelPrompt update at continuation prompts, but key it
off browserContextActive() instead of the (always-false) `browsing` flag
derived from the prompt regex -- the "+ " prompt itself doesn't reveal
whether we're inside a browser. browserActive remains untouched at
continuation prompts, preserving the original fix for multi-line input
at Browse[N]>.
@kevinushey
kevinushey force-pushed the bugfix/debugger-continuation-fixup branch from d5c6f20 to 761fc76 Compare April 30, 2026 16:52
The waitUntil only checked element existence, so it could fire on a
transient highlight before the post-step events from the .doTrace
auto-step settled. Wait for the line number to match and add a brief
flush before asserting.
@gtritchie

Copy link
Copy Markdown
Member

Code Review

The fix logic is sound and well-reasoned. Three review passes (code quality, test coverage, comment accuracy) surfaced the following.


Critical (1)

Non-ASCII em-dash in RStdCallbacks.cpp will fail the linter test

The project's test-linter.R fails on non-ASCII characters in source files. Line 285 (// indicate top-level — R is waiting for input) contains a UTF-8 em-dash and is in the deleted hunk — confirm it is gone after the patch applies. The new comment block also uses em-dashes (mid-parse on a previous expression — the) — replace all of them with --.


Important (4)

1. NotebookQueue description in RStdCallbacks.cpp comment is inaccurate

The comment says "consumers like the RMarkdown notebook queue use this flag to advance to the next line of a multi-line chunk expression." NotebookQueue::process doesn't read atTopLevelPrompt — it checks the prompt string directly (prompt == "+ "). The actual consumer of isAtTopLevel() appears to be SessionChat.cpp. Suggested rewrite: "This flag is used by downstream components that need to distinguish REPL-idle state from mid-expression state; see isAtTopLevel() and its callers."

2. Sys.sleep(0.5) in both tests is a flakiness risk

The project provides .rs.waitUntil() to avoid time-based waits. Test 1 sleeps after sourceActiveDocument before running f() — this should poll for f being available or for the console prompt to return. Test 2 sleeps after the highlight appears to "let state settle" — the settledness condition is unspecified, which is fragile on slow CI.

3. activeLineEl$innerText == "3" assertion needs a comment

The breakpoint is placed on gutter child [[2L]] (line 2), but the assertion expects "3". If this is intentional (auto-step past .doTrace lands on line 3), it should be explicitly stated in the test — otherwise it reads as an off-by-one that could pass even if the highlight is on the wrong line.

4. No test for bare browser() at top level

Test 2 covers the isBrowseActive() fix via a debugSource() breakpoint, but debugSource() sets up its own environment. Calling browser() in a sourced script at the top level is a distinct path where parent.frame() is R_GlobalEnv and also triggers the bug. A regression could reintroduce the failure for bare top-level browser() without affecting debugSource().


Suggestions (3)

5. parent.frame() in isBrowseActive() comment is an R-side detail, not a C++ contract

If .rs.captureCurrentEnvironment() ever changes its capture strategy, the comment will be wrong. Consider phrasing in terms of the C++ call: "browserEnv() is set by rs_setCapturedBrowserEnv (called from .rs.captureCurrentEnvironment()) to the environment being debugged."

6. "brief window" in isBrowseActive() comment lacks timing precision

Adding one sentence would help: "This window spans from when setBrowserActive(true) is called in RReadConsole to when .rs.captureCurrentEnvironment() completes and setBrowserEnv() is called with a non-nil value."

7. No output assertion after exiting the top-level debugger

Test 2 verifies the highlight appears but not that the script completes and produces [1] 23 after stepping through. If the session hung, the test would still pass.


Strengths

  • Both fixes are logically correct: != R_NilValue properly guards "env captured" without excluding R_GlobalEnv, and gating setBrowserActive on the continuation-prompt check is the right place.
  • Test 1's .rs.waitUntil predicate that presses c when a nested debug at prompt appears is well-reasoned defensive handling.
  • Both tests clean up state completely.
  • The isBrowseActive() comment correctly documents why R_GlobalEnv must not be excluded — exactly the invariant a future maintainer might otherwise "fix" away.

@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.

Overall LGTM, AI review flagged some nitpicky things (and a real issue with em-dashes that needs to be addressed before merging).

kevinushey and others added 2 commits May 1, 2026 10:10
- replace utf-8 em-dashes with -- in RStdCallbacks.cpp
- fix inaccurate NotebookQueue reference in atTopLevelPrompt comment
- tighten isBrowseActive comment with C++-side capture details and
  precise window boundaries
- replace fixed Sys.sleep waits in tests with waitUntil predicates
  that poll for the actual condition (function defined, line number,
  console output) rather than time
- clarify that gutter children use 0-based indexing in BRAT, and that
  the breakpoint lands on the print() line
- assert "[1] 23" appears after the debugger exits so a hung session
  would fail the test
@kevinushey
kevinushey merged commit e8000a7 into main May 1, 2026
@kevinushey
kevinushey deleted the bugfix/debugger-continuation-fixup branch May 1, 2026 23:08
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