Skip to content

reduce reliance on R_GlobalContext in debugger - #17288

Merged
kevinushey merged 31 commits into
mainfrom
feature/r-global-context
Apr 2, 2026
Merged

kevinushey merged 31 commits into
mainfrom
feature/r-global-context

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Summary

  • Replace the legacy RCntxt infrastructure (which overlaid an internal R struct on R_GlobalContext) with targeted, minimal uses of the context stack
  • Reimplement callFramesAsJson in R using sys.frame() / sys.nframe() / sys.call() (public R API) instead of walking RCNTXT directly
  • Reimplement getFunctionContext in R using sys.frame(), with the browser context's cloenv passed from a small C++ helper (browserContextEnv())
  • Consolidate remaining context stack access into RContext.cpp with a file-local struct, reducing the surface area that depends on R internals

The remaining uses of R_GlobalContext are limited to simple boolean queries (isTopLevelContext, hasFunctionContext, hasBrowserContext, inActiveBrowseContext, inDebugHiddenContext) and browserContextEnv().

Test plan

  • Verify basic debugging: step, continue, and quit work correctly
  • Verify stepping into nested functions positions the debugger correctly (debugging-cmd-enter.R)
  • Verify promise forcing steps through the promise code, not the callee body (debugging-14306.R)
  • Verify environment pane updates correctly when navigating the call stack
  • Run debugging-*.R test scripts in src/cpp/tests/debugger/

…inery

Add RContext.hpp, a lightweight header that depends only on the stable
{nextcontext, callflag} prefix of the RCNTXT struct. Migrate call sites
that only need callflag checks (busy detection, top-level checks,
browser context detection) to use it instead of the full RCntxt class.

Replace the C++ rs_chatCallStackFunctions() with R-side
lapply(seq_len(sys.nframe()), sys.function), and replace
rs_dumpContexts() with a direct call to sys.status().

The remaining RCntxt usage in SessionEnvironment.cpp (debugger call
frame introspection) is left for a follow-up.
Move the debugger call frame introspection from C++ (walking the RCNTXT
linked list) to R using sys.call/sys.function/sys.frame/sys.parents.

The new .rs.callFrames() R function builds the same frame descriptor
list that the old C++ callFramesAsJson() produced, using only public R
APIs for most of the work. The browser environment is tracked as a
global (s_browserEnv) set from onConsolePrompt, to handle the promise
forcing case where the browser's environment doesn't correspond to any
sys.frame() visible from R.

Use R_GetCurrentSrcref(NA_INTEGER) (public R API) instead of accessing
the RCNTXT srcref field directly for debug stepping line detection.

Also update functionIsOutOfSync() to accept the CallFrameResult struct
instead of an RCntxt object.
Pass R_GetCurrentSrcref(NA_INTEGER) from C++ into .rs.callFrames so
the innermost frame can use the evaluator's runtime srcref (the current
stepping position), which is not accessible from R's sys.*() functions.

Track the browser environment as a global (s_browserEnv) set from
onConsolePrompt, and expose it via rs_getBrowserEnv so the R function
can correctly identify the browsed frame during promise forcing.

Also fix the Phase 3 iteration order to go inner-to-outer
(rev(seq_len(nframe))), matching the old C++ RCNTXT convention where
depth 1 is the innermost function context.
Replace the shared RCntxt object used for change detection with a plain
SEXP environment pointer. Reimplement getFunctionContext and
inDebugHiddenContext as R helpers (.rs.getFunctionContext,
.rs.inDebugHiddenContext).

SessionEnvironment.cpp no longer includes RCntxt.hpp or RCntxtUtils.hpp.
The only remaining context access is via RContext.hpp (the lightweight
{nextcontext, callflag} walker for inActiveBrowseContext).

Also fix two bugs from the prior commit:
- Phase 1 envSrcrefMap now iterates inner-to-outer (rev(seq_len(nframe)))
  so first-match-wins selects the innermost srcref
- lastDebugLine is now propagated back from R to C++ via the return value
  instead of dead code mutating a local R list copy
All context introspection now uses either the lightweight RContext.hpp
(for signal-safe callflag checks) or R-side sys.*() functions (for full
frame introspection). The version-dispatched RCntxt class hierarchy,
its five RCNTXT_* struct definitions, and supporting files are no longer
referenced and can be removed.

Addresses review feedback: clean up dead code, fix copyright years,
add clarifying comment on evaldepth equivalence.
Extend the RContext struct to include the stable prefix of RCNTXT
through cloenv, enabling direct context stack walks for browser
detection and debug-hidden checks without the old RCntxt class.

These must run in C++ (not R) because onConsolePrompt is called from
the R console read callback, where sys.*() functions don't see the
browser's call stack.

Also rename contextStack() to globalContext() and use R_NO_REMAP
to avoid Rinternals.h macro conflicts with C++ standard headers.
Replace the C++ context stack walk in getFunctionContext with a call
to the R-side .rs.getFunctionContext(), which uses sys.frame() /
sys.nframe() (public R API) instead of walking RCNTXT directly.

The browser context's cloenv is passed from C++ via a new
browserContextEnv() helper, since browserText() / do_sysbrowser
are unreliable when called through R_tryEval (R_ToplevelExec
resets R_ToplevelContext, hiding the CTXT_BROWSER context).

Also fix Rf_asLogical check in inDebugHiddenContext to compare
against TRUE explicitly, avoiding NA_LOGICAL being treated as
truthy.
@kevinushey kevinushey added this to the Globemaster Allium milestone Mar 25, 2026
@posit-snyk-bot

posit-snyk-bot commented Mar 25, 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.

gtritchie added a commit that referenced this pull request Mar 25, 2026
Enable dark theme styling for the New Connection Wizard and all its
sub-pages (snippet, Shiny, ODBC install/pre-install).

GWT changes:
- Call setThemeAware(true) in NewConnectionWizard constructor
- Add dark CSS overrides for wizardBodyPanel border, warning panels,
  code viewer, and ODBC console areas
- Remove newConnectionWizardBackground sprite in dark mode (all
  connection pages override getWizardPageBackgroundStyle with this
  custom sprite, which was not covered by the base Wizard.css dark
  override)
- Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css

Shiny iframe dark mode (Spark Connection, etc.):
- Inject dark-mode CSS into the Shiny mini-UI iframe for labels,
  form controls, and select option elements
- In Server, use native JSNI to inject styles into the same-origin
  iframe document
- In Desktop, add an Electron bridge method (injectShinyDialogCss)
  that uses WebFrameMain.executeJavaScript() to inject CSS into
  cross-origin iframes, matching the Shiny dialog frame by its full
  URL (origin + pathname)
gtritchie added a commit that referenced this pull request Mar 25, 2026
Enable dark theme styling for the New Connection Wizard and all its
sub-pages (snippet, Shiny, ODBC install/pre-install).

GWT changes:
- Call setThemeAware(true) in NewConnectionWizard constructor
- Add dark CSS overrides for wizardBodyPanel border, warning panels,
  code viewer, and ODBC console areas
- Remove newConnectionWizardBackground sprite in dark mode (all
  connection pages override getWizardPageBackgroundStyle with this
  custom sprite, which was not covered by the base Wizard.css dark
  override)
- Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css

Shiny iframe dark mode (Spark Connection, etc.):
- Inject dark-mode CSS into the Shiny mini-UI iframe for labels,
  form controls, and select option elements
- In Server, use native JSNI to inject styles into the same-origin
  iframe document
- In Desktop, add an Electron bridge method (injectShinyDialogCss)
  that uses WebFrameMain.executeJavaScript() to inject CSS into
  cross-origin iframes, matching the Shiny dialog frame by its full
  URL (origin + pathname)
gtritchie added a commit that referenced this pull request Mar 25, 2026
Enable dark theme styling for the New Connection Wizard and all its
sub-pages (snippet, Shiny, ODBC install/pre-install).

GWT changes:
- Call setThemeAware(true) in NewConnectionWizard constructor
- Add dark CSS overrides for wizardBodyPanel border, warning panels,
  code viewer, and ODBC console areas
- Remove newConnectionWizardBackground sprite in dark mode (all
  connection pages override getWizardPageBackgroundStyle with this
  custom sprite, which was not covered by the base Wizard.css dark
  override)
- Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css

Shiny iframe dark mode (Spark Connection, etc.):
- Inject dark-mode CSS into the Shiny mini-UI iframe for labels,
  form controls, and select option elements
- In Server, use native JSNI to inject styles into the same-origin
  iframe document
- In Desktop, add an Electron bridge method (injectShinyDialogCss)
  that uses WebFrameMain.executeJavaScript() to inject CSS into
  cross-origin iframes, matching the Shiny dialog frame by its full
  URL (origin + pathname)
gtritchie added a commit that referenced this pull request Mar 25, 2026
Enable dark theme styling for the New Connection Wizard and all its
sub-pages (snippet, Shiny, ODBC install/pre-install).

GWT changes:
- Call setThemeAware(true) in NewConnectionWizard constructor
- Add dark CSS overrides for wizardBodyPanel border, warning panels,
  code viewer, and ODBC console areas
- Remove newConnectionWizardBackground sprite in dark mode (all
  connection pages override getWizardPageBackgroundStyle with this
  custom sprite, which was not covered by the base Wizard.css dark
  override)
- Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css

Shiny iframe dark mode (Spark Connection, etc.):
- Inject dark-mode CSS into the Shiny mini-UI iframe for labels,
  form controls, and select option elements
- In Server, use native JSNI to inject styles into the same-origin
  iframe document
- In Desktop, add an Electron bridge method (injectShinyDialogCss)
  that uses WebFrameMain.executeJavaScript() to inject CSS into
  cross-origin iframes, matching the Shiny dialog frame by its full
  URL (origin + pathname)
gtritchie added a commit that referenced this pull request Mar 26, 2026
Enable dark theme styling for the New Connection Wizard and all its
sub-pages (snippet, Shiny, ODBC install/pre-install).

GWT changes:
- Call setThemeAware(true) in NewConnectionWizard constructor
- Add dark CSS overrides for wizardBodyPanel border, warning panels,
  code viewer, and ODBC console areas
- Remove newConnectionWizardBackground sprite in dark mode (all
  connection pages override getWizardPageBackgroundStyle with this
  custom sprite, which was not covered by the base Wizard.css dark
  override)
- Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css

Shiny iframe dark mode (Spark Connection, etc.):
- Inject dark-mode CSS into the Shiny mini-UI iframe for labels,
  form controls, and select option elements
- In Server, use native JSNI to inject styles into the same-origin
  iframe document
- In Desktop, add an Electron bridge method (injectShinyDialogCss)
  that uses WebFrameMain.executeJavaScript() to inject CSS into
  cross-origin iframes, matching the Shiny dialog frame by its full
  URL (origin + pathname)
@kevinushey
kevinushey marked this pull request as ready for review March 30, 2026 18:15
gtritchie

This comment was marked as resolved.

R only added special NA_INTEGER handling to R_GetCurrentSrcref in
R 4.5. On older versions, NA_INTEGER is treated as a large negative
skip value and always returns R_NilValue, causing the debug source
highlight to break during stepping.
…t/hasBrowserContext

- isBusy() now uses !isTopLevelContext() so it correctly reports busy
  for non-function contexts like top-level for loops
- isTopLevelContext() now checks nextcontext == nullptr to distinguish
  the real top-level from R_ToplevelExec contexts
- browserContextActive() is now prompt-based (Browse[N]>) instead of
  walking R_GlobalContext
- Remove hasFunctionContext() and hasBrowserContext() (no remaining
  callers)

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

PR Review: reduce reliance on R_GlobalContext in debugger

Reviewed +908/-1448 across 24 files. Well-structured refactoring that consolidates all R_GlobalContext access into a single file behind a narrow API, replacing version-fragile struct overlays with R's public sys.*() API. Net deletion of ~540 lines.


Critical (2)

1. s_browserEnv is not GC-protected
src/cpp/session/modules/environment/SessionEnvironment.cpp

The static SEXP s_browserEnv is assigned from environmentTop without R_PreserveObject, but read from R via .Call("rs_getBrowserEnv"). If the browser context is unwound between assignment and use, GC could collect it. By contrast, pCurrentEnv in the same file correctly uses preserve/release.

// Suggested fix:
if (s_browserEnv != R_NilValue)
   R_ReleaseObject(s_browserEnv);
s_browserEnv = environmentTop;
if (s_browserEnv != R_NilValue)
   R_PreserveObject(s_browserEnv);

2. No bounds check on VECTOR_ELT in getFunctionContext()
src/cpp/r/RContext.cpp:110-111

int foundDepth = r::sexp::asInteger(VECTOR_ELT(resultSEXP, 0));
SEXP foundEnv = VECTOR_ELT(resultSEXP, 1);

If .rs.getFunctionContext() returns something other than a 2-element VECSXP (due to a bug or unexpected R state), this will crash. No type/length validation on resultSEXP. Also, the Error from the R call is silently discarded without LOG_ERROR.


Important (5)

3. rs_getBrowserEnv() misleading null check
SessionEnvironment.cpp

return s_browserEnv ? s_browserEnv : R_NilValue;

s_browserEnv is initialized to R_NilValue (a valid non-null SEXP pointer), so the C boolean test always evaluates true. The ternary fallback is dead code. Simplify to return s_browserEnv;.

4. isBusy() semantic broadening
src/cpp/r/session/RBusy.cpp

Old code checked callflag & CTXT_FUNCTION (any function on stack). New code checks !isTopLevelContext() (any context at all, including loops, ccode, browser). This broadens what's considered "busy." If intentional, worth a comment; if not, consider preserving the old CTXT_FUNCTION check.

5. boost::regex_match can throw in RReadConsole
src/cpp/r/session/RStdCallbacks.cpp:277-278

static const boost::regex reBrowsePrompt("Browse\\[\\d+\\]> ");
setBrowserActive(boost::regex_match(prompt, reBrowsePrompt));

boost::regex_match can throw boost::regex_error. No try-catch, and this runs inside RReadConsole. An exception could terminate the session.

6. Unchecked getNamedListSEXP inner calls in callFramesFromR()
SessionEnvironment.cpp

Four getNamedListSEXP calls inside the context extraction block silently discard their Error return values. If the R function changes its return structure, these failures would be invisible. At minimum, add LOG_ERROR.

7. R-side tryCatch swallows errors silently
SessionEnvironment.R (.rs.callFrames)

At least 5 places use tryCatch(..., error = function(e) "") with zero logging. Bugs in helpers like .rs.functionNameFromCall, .rs.sourceFileFromRef, .rs.simulateSourceRefs would produce blank/zero values indistinguishable from legitimately absent data. The old C++ code had LOG_ERROR on some of these paths.


Suggestions (5)

8. chat.hasTrustedCaller now includes its own frame
src/cpp/session/modules/SessionChat.R:293 — Old .Call returned only callfun from CTXT_FUNCTION contexts. New lapply(seq_len(sys.nframe()), sys.function) includes .rs.chat.hasTrustedCaller itself. Verify the trusted caller check doesn't match .rs. internal functions.

9. .rs.callFrames docstring doesn't match return value
The @return documents flat components (context_callfun, context_cloenv, src_context_callfun, src_context_call). Actual return is nested (context is a list with sub-elements, src_context is a list with sub-elements, and lastDebugLine is undocumented).

10. rs_dumpContexts() silently discards error — Add LOG_ERROR.

11. RContext struct "stable prefix" comment — Worth explaining why these fields are stable (same order across R 3.2-4.4+) and what R version range this is validated for. Aids future maintainers when a new R version ships.

12. CMake libgit2 timestamp workaround — Orthogonal to this PR's purpose. Consider splitting into a separate commit for cleaner history.


Strengths

  • Major reduction in R-internal dependency surface — deletes 5 header/source files maintaining version-specific RCNTXT struct layouts
  • Clean encapsulation — all R_GlobalContext access behind a narrow API in one file
  • Good use of stable R public APIs (sys.frame(), sys.nframe(), sys.call(), R_GetCurrentSrcref())
  • High-quality comments in key areas: context type flag binary literals, browser env promise-forcing rationale, browserEnv param explaining R_ToplevelExec behavior
  • inActiveBrowseContext() rename improves precision
  • Defensive null check in SessionBreakpoints.R

Instead of walking R_GlobalContext to find the browser context's
environment, inject .rs.captureCurrentEnvironment() into the browser
REPL. R evaluates this in the browser's rho, so parent.frame()
correctly returns the environment being debugged -- even during
promise forcing where the browser env doesn't correspond to any
sys.frame() visible from R.

Also adds dumpContexts() for debugging/testing the context stack,
and rs_setCapturedBrowserEnv .Call method for the R-to-C++ bridge.
inActiveBrowseContext() now checks browserContextActive() (prompt-based)
and browserEnv() != R_GlobalEnv (captured via REPL injection) instead
of walking the C context stack.
…textEnv

inDebugHiddenContext() now calls .rs.inDebugHiddenContext() in R
instead of walking the C context stack. The R version also correctly
handles S4 trace wrappers via .rs.originalFunction().

browserContextEnv() has no remaining callers (getFunctionContext now
uses the browser env captured via the injected REPL command) and is
removed.

The only remaining globalContext() uses are isTopLevelContext() (needs
async-signal safety) and dumpContexts() (diagnostic tool).
… tracking

isTopLevelContext() now uses atDefaultPrompt() (set from RReadConsole
when hist==1 and the prompt matches the default) combined with
!r::exec::isExecuting() (tracks internal R code execution).

This removes the last production use of R_GlobalContext. Only the
dumpContexts() diagnostic tool still accesses the C context stack.
RContext.cpp no longer accesses R_GlobalContext or the RCNTXT struct
directly. Remove the internal struct definition, context type flags,
globalContext() accessor, contextTypeName() helper, and dumpContexts()
diagnostic function. Revert rs_dumpContexts to use sys.status().
…xt result

- Use PreservedSEXP for s_browserEnv in both SessionEnvironment.cpp
  and RSession.cpp to ensure proper R_PreserveObject/R_ReleaseObject
  lifecycle
- Add type/length validation on the VECTOR_ELT calls in
  getFunctionContext() to guard against malformed R results
- Add LOG_ERROR to unchecked getNamedListSEXP calls in callFramesFromR
- Add LOG_ERROR to rs_dumpContexts
- Use regex_utils::match instead of boost::regex_match for browse
  prompt detection (catches exceptions instead of propagating)
- Document isBusy() semantic broadening
- Exclude own frame in .rs.chat.hasTrustedCaller
Move isTopLevelContext, inActiveBrowseContext, getFunctionContext, and
inDebugHiddenContext from the r::context namespace (RContext.cpp) to
r::session (RSession.cpp). These functions now operate entirely on
tracked session state and R-side calls, so r::session is their natural
home.

Rename for clarity:
- isTopLevelContext -> isAtTopLevel
- inActiveBrowseContext -> isBrowseActive

Delete RContext.cpp and RContext.hpp — no longer needed.
@gtritchie

Copy link
Copy Markdown
Member

Review #210 /Users/gary/alt/rstudio 6ccb5be..ac1f205

Review Findings

  • Severity: High; Location: src/cpp/session/modules/environment/SessionEnvironment.cpp:476; Problem: callFramesFromR() stores raw SEXP pointers from resultSEXP into CallFrameResult, but those objects are no longer protected once the local Protect goes out of scope. Callers then pass cfResult.originalCallfun, cfResult.callFunSourceRefs, cfResult.srcContextCallfun, etc. into later R API calls that can trigger GC, so this can turn into use-after-GC and intermittent debugger/environment failures. Fix: Preserve the extracted SEXPs (or the whole resultSEXP) for as long as CallFrameResult is used, and release them only after the caller is done.

  • Severity: Medium; Location: src/cpp/r/session/RStdCallbacks.cpp:291; Problem: browser state is now derived entirely from whether the current prompt string matches Browse[n]> . That loses the fact that a browser context is still active when code run from the browser opens another console prompt (readline(), scan(), etc.), so browserContextActive()/isBrowseActive() become false even though the debugger is still on the stack. Existing consumers such as quit handling, notebook scheduling, and environment/debug state can then behave as if debugging has ended. Fix: Keep browser-active state tied to the actual browser context lifetime, not just the current prompt text, or at minimum avoid clearing it until the browser frame is known to be gone.

  • Severity: Low; Location: src/cpp/r/session/RStdCallbacks.cpp:311; Problem: the injected .rs.captureCurrentEnvironment() command is copied into buf without checking buflen, unlike the normal console-input path. If R ever supplies a smaller read buffer here, this is an out-of-bounds write. Fix: apply the same length check/truncation logic used for normal console input before writing the injected command.

Summary

This change replaces direct RCNTXT walking with R-level call-stack inspection and prompt-tracked browser state, plus a CMake workaround to avoid needless libgit2 rebuilds.

- pass caller's Protect into callFramesFromR() so returned SEXPs
  stay protected for the lifetime of their use
- only update browser state on REPL prompts (hist == 1) so that
  readline()/scan() inside the browser don't clear debug state
- simplify capture-env injection flag logic and rename to
  s_captureInjected for clarity
- remove redundant environmentTop assignment in onConsolePrompt
@kevinushey
kevinushey merged commit f016ddb into main Apr 2, 2026
8 checks passed
@kevinushey
kevinushey deleted the feature/r-global-context branch April 2, 2026 23:36
kevinushey added a commit that referenced this pull request Apr 29, 2026
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.
kevinushey added a commit that referenced this pull request Apr 30, 2026
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 added a commit that referenced this pull request May 1, 2026
…17491)

* debugger fixes

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

* harden top-level breakpoint test against transient highlight state

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.

* line number is 3, even though 0-based index is 2

* address pr review feedback for debugger continuation fixup

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