Skip to content

keep a rig user-mode install from becoming the default R outside RStudio - #19230

Merged
kevinushey merged 11 commits into
mainfrom
bugfix/rig-user-install-side-effects
Oct 26, 2026
Merged

kevinushey merged 11 commits into
mainfrom
bugfix/rig-user-install-side-effects

Conversation

@kevinushey

@kevinushey kevinushey commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #19229.

When the project R-version warning bar installs a missing R, it runs rig add <version> --user. If no rig user-mode default exists yet, rig also makes the new R the default outside RStudio: it creates ~/.local/bin/R and Rscript quick links and rig's Current link; on macOS it installs and loads a LaunchAgent (io.r-lib.rig.rstudio-which-r) that runs launchctl setenv RSTUDIO_WHICH_R <new R> at every login; and it appends . "$HOME/.local/bin/rigenv" to the shell startup files whenever ~/.local/bin is not ahead of /usr/local/bin on its PATH. The LaunchAgent in particular outlives RStudio and changes which R Desktop uses for every launch from the Dock, and overrides a user's own launchctl setenv RSTUDIO_WHICH_R. rig 0.11.0 has no opt-out for any of this.

This PR:

  • runs rig with $HOME/.local/bin first on its PATH, so it never edits the shell startup files;
  • before rig add, records which of rig's default-R files exist (Current/current, R, Rscript, and on macOS the LaunchAgent plist) and the RSTUDIO_WHICH_R launchd holds; once rig exits, removes the files the install created, unloads the agent and puts launchd's RSTUDIO_WHICH_R back (restored to the previous value, or unset). Files that existed before are left alone, so a user who already uses rig in user mode is unaffected. What was removed is noted in the install job's output.
  • leaves Windows as is: rig's user-mode default there (R.exe shims and registry entries) is not undone yet, and Windows switches are persisted by design anyway.
  • creates rig's user-mode quick-link directory (~/.local/bin, as reported by rig system dirs --user) before running rig add. rig 0.11.0 fails outright with "No such file or directory" when that directory does not exist yet (rig fails with "No such file or directory" in user mode on macOS when ~/.local/bin does not exist r-lib/rig#491, fixed upstream in treat a missing binary dir as having no aliases on macos r-lib/rig#492), which is the state of a fresh macOS account, so the install feature could not work there.
  • drops a stale duplicate of the Switch R version automatically when switching between RStudio projects that use renv #12622 NEWS entry (from before rig was bundled).

Upstream, r-lib/rig#490 adds rig add --no-default. Once a bundled rig has it, RStudio can pass the flag; the cleanup here stays harmless either way.

No NEWS entry: the feature is unreleased.

Tests:

  • new testthat cases in test-rig.R cover the snapshot/restore (pre-existing links kept, dangling links, agent unload plus env restore and unset, the non-macOS layout). rstudio-tests --scope r --filter rig: 98 pass; --filter linter: 84 pass.
  • a new desktop e2e test, "installs a missing R without making it the default R outside RStudio", opens a project whose lockfile asks for an R series not on the machine, takes the "Install R x and switch" offer, waits for the session to come back under the new R, and then checks the sandbox home: R is installed under rig's user-mode root, and none of rig's Current, R, Rscript links or the LaunchAgent exist, the shell startup files are unchanged, and launchd's RSTUDIO_WHICH_R and job list are as before. It downloads a build of R, so it is opt-in: PW_ALLOW_R_INSTALL=1. The test does not create ~/.local/bin itself, so it also covers the directory creation above (without it, rig 0.11.0 fails the install). Verified on this Mac via test:desktop-dev (23s), and that it fails with the cleanup disabled (it then lists exactly those four files).

rig add --user makes the first R it installs the user-mode default: R and
Rscript quick links in ~/.local/bin, rig's Current link, and on macOS a
login LaunchAgent that sets RSTUDIO_WHICH_R for every GUI application. It
also appends to the shell startup files unless ~/.local/bin precedes
/usr/local/bin on its PATH. None of that should happen for an R installed
from the project R-version warning bar: run rig with ~/.local/bin first on
PATH, and remove the default-R files the install created once it exits,
restoring launchd's RSTUDIO_WHICH_R. Files that existed before are kept.

Also drops a stale duplicate of the #12622 NEWS entry.

Addresses #19229
@kevinushey kevinushey added this to the 2026.11 (Montauk Daisy) milestone Oct 22, 2026
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

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

Passed Failed Skipped Flaky
4362 0 217 2
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 14 0
✅ desktop-linux 1092 0 43 0
✅ desktop-macos 1096 0 38 2
✅ desktop-windows 1091 0 50 0
✅ server-linux 1045 0 44 0
✅ setup 36 0 28 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 db33882e2e70476f3307dba87998d4ef35a6fafb - Run #1710

… stays off

Opt-in (PW_ALLOW_R_INSTALL=1), as it downloads and installs a build of R
into the sandbox home. Creates rig's quick-link directory first: rig 0.11.0
fails outright in a home without one.

Addresses #19229
rig 0.11.0 fails outright with "No such file or directory" when ~/.local/bin does not exist yet (r-lib/rig#491), as on a fresh macOS account, so the warning-bar install could not work there. The e2e no longer creates the directory itself.

Addresses #19229.

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

Two correctness gaps in the cleanup, plus test and cleanup items:

  • The snapshot is in-memory only, and rig sets the default before the slow pak step, so quitting mid-install leaves the LaunchAgent in place (SessionRig.R:215).
  • Files that existed before the install are left alone even when rig rewrites them (dangling Current after rig rm of the default), so RSTUDIO_WHICH_R is not restored (SessionRig.R:195).
  • Restore failures are ignored but still logged as removed (SessionRig.R:211).
  • The e2e test has no launchd cleanup if it fails (renv_r_version_switch.test.ts:313), and userInstallBegin/End have no unit tests (test-rig.R:377).
  • Three nits (Windows env copy, expect.poll, an extra rig spawn).

rig behavior is cited from the v0.11.0 source.

unname(created)
})

.rs.setVar("rig.installState", new.env(parent = emptyenv()))

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.

The snapshot lives only in this environment, and RInstallJob has no shutdown handling, so if the session exits while rig add is running the restore never happens.

The window is wide: in rig 0.11.0, rig add sets the default (set_default_if_none, which creates Current, the R/Rscript links and the LaunchAgent and runs launchctl load) before it downloads and installs pak (system_add_pak). If the user quits RStudio during the pak step, exitWithParent kills rig, finish() never runs, and the LaunchAgent keeps setting RSTUDIO_WHICH_R to the new R at every login, which is #19229 again.

Persisting the snapshot (e.g. under the session's scratch/state dir) and restoring it at shutdown or the next startup, or restoring from a shutdown hook, would close this.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 5ffec95. The snapshot is now saved under the user scratch dir, with the session pid. At shutdown the job stops rig and restores through the normal exit path (bounded to a second, since onShutdown runs before the session's child cleanup). If rig outlives that, or the session dies outright, the next session restores from the file once the recording session is gone.

Comment thread src/cpp/session/modules/SessionRig.R Outdated
.rs.addFunction("rig.userDefaultRestore", function(snapshot, launchctl = .rs.rig.launchctl)
{
paths <- snapshot$paths
created <- paths[!snapshot$existed & .rs.rig.pathExists(paths)]

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.

existed records only whether each path is present, not what it points at, so files rig rewrites are kept as they are after the install.

Concrete case: rig decides whether a default is set with read_version_link, which uses Path::exists() and so treats a dangling Current as "no default". A user with rig user-mode R 4.3 (default) and 4.4 runs rig rm 4.3: Current now dangles, and the LaunchAgent plist stays, because rig only removes it when no versions are left. If RStudio then installs 4.2, rig repoints Current, rewrites the plist to 4.2 and loads it. Both paths "existed", so nothing is restored and launchctl is never called. 4.2 becomes the GUI default R at every login.

Snapshotting link targets, the plist contents and comparing the launchctl getenv RSTUDIO_WHICH_R value before and after (rather than keying the launchd restore off plist creation) would cover this.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 5ffec95. The snapshot records link targets, plist bytes and the agent's loaded state. A repointed Current goes back to its old target, a rewritten plist is written back and reloaded if it was loaded before, and RSTUDIO_WHICH_R is reset whenever the value changed. Your rig rm scenario is the new "links rig repoints and an agent it rewrites are put back" test.

Comment thread src/cpp/session/modules/SessionRig.R Outdated
}

# the links go, not what they point at
file.remove(created)

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.

The result of file.remove() is ignored, and .rs.rig.launchctl turns every failure into "", but unname(created) is still returned as removed. If launchctl unload/unsetenv fails, or a remove hits a permission error, nothing is logged, and the job output still says "Removed the default R setup rig added outside RStudio: ..." for files that are still there or a variable that is still set. Returning only what was actually removed, and logging the launchctl failures, would make this diagnosable.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 5ffec95. launchctl failures and failed removals come back as separate messages in the job log, and only what was actually removed or restored is reported as such.

// links, shell startup-file edits, and on macOS a login LaunchAgent that
// sets RSTUDIO_WHICH_R), which RStudio undoes (#19229). This downloads and
// installs a build of R, so it runs only when asked to.
test("installs a missing R without making it the default R outside RStudio", async ({

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.

launchd is per-user, not per-HOME, so rig's launchctl load of the sandbox-home agent goes into the developer's real GUI domain (rig installs the agent whenever /Applications/RStudio.app exists). If a cleanup regression fails the final assertions, which is what this test exists to catch, nothing undoes it: afterAll only switches R back. The agent stays loaded and RSTUDIO_WHICH_R points into the sandbox dir, which is then deleted, so RStudio launched from the Dock targets a missing R until logout. A finally/afterAll that unloads the agent and restores whichRBefore would make a failing run safe.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 4265d15. A finally boots the agent out of the GUI domain if the run loaded it, and puts RSTUDIO_WHICH_R back to its pre-test value.


})

test_that("a user-mode install leaves rig's default R setup as it was", {

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.

These cover userDefaultPaths/Snapshot/Restore and ensureBinaryDir, but not rig.userInstallBegin/rig.userInstallEnd: the state reset, the Windows early return, rig system dirs failing, and userInstallEnd with no snapshot. A regression where Begin stops recording the snapshot would pass --scope r --filter rig and only show up in the opt-in e2e test. userInstallBegin takes rig, so a stub script that prints the dirs JSON would be enough to drive it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added in 5ffec95, with a stub rig script and a fake launchd: Begin/End round trip, save failure, rig failing, End with nothing pending, and startup recovery.

Comment thread src/cpp/session/modules/SessionRig.cpp Outdated
LOG_ERROR(beginError);

core::system::Options environment;
core::system::environment(&environment);

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.

Nit: the environment is copied and passed explicitly on every platform but only changed inside #ifndef _WIN32. Moving the copy and options.environment = environment into that block would leave Windows exactly as before.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 5ffec95.

// under the new R; a failed installation is reported in the warning bar
const failure = page.getByText(`Installation of R ${target} failed`);
const deadline = Date.now() + 600000;
for (;;) {

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.

Nit: the other tests in this file use expect.poll. expect.poll(async () => { if (await failure.count()) throw new Error(await failure.first().innerText()); return (await getVersion(page).catch(() => ({ r: "" }))).r; }, { timeout: 600000, intervals: [5000] }).toBe(target!) would replace the hand-written loop, deadline and sleep.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 4265d15.

if (.rs.platform.isWindows)
return(invisible(FALSE))

dirs <- .rs.rig.json(rig, c("system", "dirs", "--user"))

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.

Nit: this adds a synchronous rig system dirs --user spawn on the main thread in the install RPC path, on top of the rig --version call(s) in .rs.rig.find. That is small next to the install itself; caching the dirs alongside the rig.find result would avoid it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I'd leave this one. It is a single short spawn before a multi-minute download, rig.find is not cached either, and the dirs can change if rig is reconfigured between installs.

…failures

rig sets the default before its slow pak step, and on macOS a child does not die with the session, so the snapshot now also lives in the user scratch dir: a session exiting mid-install stops rig and undoes what it added, and a snapshot left behind (crash, kill) is undone by the next session once the session that took it is gone.

The snapshot records link targets, the agent's contents and whether launchd had it loaded, so a repointed 'Current' or a rewritten agent (rig treats a dangling 'Current' as 'no default') is put back too, and RSTUDIO_WHICH_R is restored whenever it changed. Removal and launchctl failures are reported in the job log rather than counted as done.
…erything is undone

The snapshot records rig's pid once it runs, so a later session leaves it alone while that rig lives on (on macOS it outlives a crashed session). A session refuses to install while another live session's snapshot exists, and undoes a dead session's leftover before taking its own snapshot, so leftovers do not pass for setup to keep. The snapshot stays on disk while any step failed, for a later try. A failed snapshot now aborts the install rather than running it un-undoable. restoreMessages returns character() rather than NULL for the C++ extractor, and the lifecycle test no longer indexes the LaunchAgent path on Linux.
…napshot atomically

A leftover snapshot that cannot be fully undone now blocks further installs (a fresh snapshot would take the leftovers for setup to keep). A snapshot that cannot be saved aborts the install, since nothing could undo it. The snapshot is written to a staged file and renamed into place. The agent's loaded state is reconciled on its own, so a load that failed is retried next time. The permission scenario moves to its own test with the root skip.
…hen rig's agent is already loaded

A rewritten LaunchAgent whose unload fails is left as rig wrote it, so a later try still sees it as rewritten and unloads it first. The e2e install test skips when an agent of rig's label is already loaded for the user: the sandbox plist shares that label, so rig would kickstart the real one and the cleanup would unload it.
…xtures

Unloading needs the plist, so one rig created is kept while the unload fails, for the next try. The agent tests write their fixtures with writeBin so the byte comparisons hold on Windows too.
@kevinushey
kevinushey requested a review from gtritchie October 23, 2026 23:32

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

Thanks for the rework. The earlier points are addressed: the persisted snapshot with shutdown and startup recovery, content-based restore of repointed links and the rewritten agent, failures reported and retried, the e2e finally cleanup, the new lifecycle tests, the Windows env copy, and expect.poll.

Two new points in the reworked cleanup:

  • A leftover snapshot that can't be fully undone blocks all later installs, with no hint that deleting the snapshot file clears it (SessionRig.R:429).
  • Minor: the shutdown hook's processSupervisor().wait() waits on every supervised child, not just rig (SessionRig.cpp:99).

Comment thread src/cpp/session/modules/SessionRig.R Outdated
if (length(notes) == 0L)
stop("another RStudio session is still installing R")

stop(paste(c("an earlier installation's changes are not all undone yet:", notes), collapse = "\n"))

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.

A leftover snapshot that can never be fully undone blocks every later install, and nothing tells the user how to get out of it.

I reproduced this by running this file's snapshot/restore functions in plain R. The setup: current was already dangling (after rig rm of the default version), rig repointed it to the new R, the session crashed, and the user then removed ~/.local/share/rig by hand. From then on:

  • every userInstallRecover fails with "could not restore the link .../rig/r/current", because the file.symlink() at line 327 has no parent directory, and the snapshot is kept;
  • every userInstallBegin stops here with "an earlier installation's changes are not all undone yet: ...", which the job reports as "could not record rig's default R setup: ...".

Neither message mentions rig-install-snapshot.rds in the user scratch dir, so the user can't install R from RStudio again unless they find and delete that file. The trigger is narrow, but the dead end is permanent. Naming the file (and that deleting it clears the block) in this message would be enough. Alternatively, a step whose target directory no longer exists could be treated as moot rather than failed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good catch, thanks for the repro. Fixed in db33882, both ways: a relink whose directory is gone since is treated as moot (nothing of rig's is left there, and recreating the directory for a dangling link would not restore anything), and the refusal now names the snapshot file and says that deleting it clears the block, for any other leftover that can never be undone. Test added for the removed-directory case, plus an assertion that the message names the file.

Comment thread src/cpp/session/modules/SessionRig.cpp Outdated
return;

stopped_ = true;
module_context::processSupervisor().wait(

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.

Minor: wait() polls until the supervisor has no children at all (while (poll()), and poll() returns !children.empty() in Process.cpp), not just until rig exits.

rig::initialize is registered before assistant::initialize and chat::initialize (SessionMain.cpp:761 vs 791/792), and onShutdown slots run in the order they were connected, so this handler runs while the Copilot agent and the chat backend are still supervised children. When an install is running at shutdown, this therefore always takes the full second even if rig exits after the first poll. It also runs those children's callbacks before their own modules have marked themselves as shutting down.

The cost is small (the assistant and chat handlers have their own bounded waits), but polling until !processRunning_ or a deadline would stop as soon as rig exits:

boost::posix_time::ptime deadline = boost::get_system_time() + boost::posix_time::seconds(1);
while (processRunning_ && boost::get_system_time() < deadline)
{
   module_context::processSupervisor().poll();
   boost::this_thread::sleep(boost::posix_time::milliseconds(10));
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed; db33882 polls directly until processRunning_ clears (up to a second, in 10ms steps) instead of wait(), so the hook returns as soon as rig exits.

…refusal

A repointed link whose directory the user has since removed can never be
put back, and the snapshot it kept then refused every later install with
no way out. Such a link is now treated as nothing left to undo, and the
refusal names the snapshot file so that any other leftover that will never
be undone can be cleared by hand.

The shutdown hook polls the process supervisor until rig exits (or a
second passes) instead of waiting for every supervised child to go.

Addresses #19229
@kevinushey
kevinushey requested a review from gtritchie October 26, 2026 16:05

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

Both follow-up findings are fixed in db33882:

  • A leftover snapshot that can't be undone no longer blocks installs for good: a repointed link whose directory was removed is skipped, and the refusal now names the snapshot file to delete. The reproduction from my last review now recovers and clears the snapshot.
  • The shutdown hook now polls until rig exits, for at most about a second, instead of waiting for every supervised child.

The snapshot/restore tests in test-rig.R, including the new one, pass when run against this branch's SessionRig.R.

@kevinushey
kevinushey merged commit d0ab541 into main Oct 26, 2026
44 checks passed
@kevinushey
kevinushey deleted the bugfix/rig-user-install-side-effects branch October 26, 2026 17:48
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.

Installing R via rig from the project R-version warning makes it the default R outside RStudio

2 participants