Skip to content

check working directory changes made by assistant-run code - #19795

Merged
kevinushey merged 12 commits into
mainfrom
bugfix/chat-guardrails-working-directory
Nov 25, 2026
Merged

kevinushey merged 12 commits into
mainfrom
bugfix/chat-guardrails-working-directory

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Two changes to the checks applied to R code that Posit Assistant runs:

  • The checks now cover setwd(). The working directory is one of the locations such code may edit files in, so the check on where it can move belongs with the checks on where it can write.
  • unlink(NULL) no longer fails while the checks are active.

Fixes #19794.

Approach

Working directory. setwd() gets a preflight hook like the other checked functions. Code called directly by Posit Assistant can move within the allowed locations (the project, tempdir(), library paths, and so on), and back into the directory the user was in. Anything else is refused with the usual "agent file operations were blocked" message.

  • The user's directory is recorded when the checks are activated, and kept while the working directory is still where the previous evaluation left it, so that moving into a subdirectory in one evaluation and back in a later one works when no project is open. A setwd() from the Console between evaluations replaces the recorded directory.
  • Files are checked against that recorded directory, not the live working directory. A move the check doesn't see (withr::with_dir(), source(chdir = TRUE), package code) changes where code runs, but not where it may edit files.
  • The check looks at the function that called setwd(), not at the rest of the call stack. A call made by a package's own code, or by RStudio's own R code, is not checked: knitr, rmarkdown and RStudio's project lookup, among others, change directory as part of their normal operation. A function that Posit Assistant's code passes to a package is still checked.
  • source(), sys.source() and compiler::loadcmp() (for chdir = TRUE), tools::checkMD5sums(), and the srcfile helpers open.srcfile() and utils:::.normalizePath() (which read a parsed file from the directory it was parsed in), are not checked either. Each restores the previous directory on exit. A setwd() call inside a sourced script is checked like any other. Base functions that write in the directory they change into, such as tools::buildVignette(), are left to the check.

unlink(NULL). The check passed its argument to Sys.glob(), which rejects NULL. It now coerces the argument first, as unlink() itself does, and checks and deletes that same coerced vector.

Known limits. Code that a package or source(chdir = TRUE) has moved outside the allowed locations can only move back into them, and can't edit files where it is. So rmarkdown::render() of a document outside the allowed locations is now refused, as NEWS notes. The recorded user directory is not kept across a session suspend and resume.

The header comment in SessionChat.R also gains a sentence on what the checks do not cover.

Automated Tests

New tests in src/cpp/tests/testthat/test-chat-guardrails.R cover moving outside and within the allowed locations, across evaluations (including one that ends in an error), after the user changes directory, from package code and RStudio's project lookup, from a function passed to package code, through source(chdir = TRUE) / sys.source(), from inside a sourced script, through a srcfile lookup, compiler::loadcmp() and tools::checkMD5sums(), file edits after a move the check doesn't see (withr::with_dir(), source(chdir = TRUE)), and the arguments setwd() rejects itself, plus unlink() of NULL and of a factor.

QA Notes

With a project open, ask Posit Assistant to run each of these:

  • setwd(".."): refused, and the working directory is unchanged.
  • old <- setwd(tempdir()); setwd(old): succeeds.
  • unlink(NULL): succeeds silently.
  • withr::with_dir("..", writeLines("x", "notes.txt")): refused at writeLines(), and no file is created.
  • Rendering an R Markdown document in the project with rmarkdown::render(): works as before.
  • Rendering one in a folder outside the project (and outside tempdir()): refused.

Documentation

None needed.

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests (ran the chat, chat-guardrails and linter R test files locally; relying on CI for the rest)

The working directory is one of the roots that code run by Posit Assistant may edit files within, so the file checks now also cover setwd(): such code can move within the allowed roots, and back to the directory the user chose. Package code, source(chdir = TRUE) and srcfile lookups are not affected.

Also fixes unlink(NULL) raising an error while the checks are active.
@kevinushey kevinushey added this to the 2026.12 (Parrot Balsam) milestone Nov 23, 2026
@kevinushey
kevinushey requested a review from gtritchie November 23, 2026 22:16
The package exemption now looks at the function calling setwd() rather than the whole stack, so a function the agent passes to a package is checked. The user's directory is also matched exactly, as a filesystem root is never treated as containing other paths, and a source() reference taken before the checks were activated is recognized.
RStudio's R helpers change directory temporarily (e.g. to find a project file), and are no more agent code than a package's are. Also has unlink() validate and delete the same coerced vector.
Also tests the setwd() check through safeEval and through the project lookup helper.
Also records the user's directory in resolved form, and tightens the unlink() and project lookup tests.

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

Requesting changes for the withr::with_dir() gap in chat.validateWorkingDirectory. The other comments are smaller.

.rs.addFunction("chat.validateWorkingDirectory", function(action, dir, caller)
{
# hasTrustedCallerImpl contributes the chat.safeFunctions allowlist
exempt <-

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.

withr::with_dir() and withr::local_dir() still let assistant code put the working directory anywhere. They call setwd() from a withr function, so isTrustedFunction(caller) exempts the move. While that directory is the working directory it's an allowed root (chat.allowedRoots() includes getwd()), so hooked writes there pass:

withr::with_dir("~/other-project", writeLines("x", "notes.txt"))

withr::local_dir() at the top level of the evaluated code goes further: its restore is deferred on the global environment, so the directory stays, and remains a root in later evaluations. Assistant-generated code reaches for withr often, so this isn't only a deliberate-misuse case.

One option: check edits against the working directory as of activation (or the last checked setwd()) rather than the live getwd(), so an exempt move changes where code runs without widening where it may write.

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, and source(chdir = TRUE) had the same gap. Took your suggestion in 31a74c2. chat.allowedRoots() now uses the directory recorded at activation instead of the live getwd(). A move the setwd() check exempts changes where code runs, but doesn't make the new directory editable. withr::with_dir(outside, writeLines("x", "notes.txt")) is now refused at writeLines(). A checked setwd() can only land within the roots, so no separate record of the last checked move is needed.

On withr::local_dir(): with withr 3.x it doesn't outlast the expression under safeEval(). eval(expr, globalenv()) puts a frame on the stack whose environment is the global env, so withr attaches the restore to that frame rather than deferring it globally. Within the expression it's the same gap as with_dir(), which is covered now.

Side effect, now in NEWS: rmarkdown::render() of a document outside the allowed locations is refused. It used to pass because render's own setwd() made the document's folder a root.

Comment thread src/cpp/session/modules/SessionChat.R Outdated
# on exit: source() and sys.source() for 'chdir = TRUE', and the srcfile
# helpers, which read a parsed file from the directory it was parsed in.
.rs.setVar("chat.workingDirectoryCallers", list(
base = c("source", "sys.source", "open.srcfile"),

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.

source(chdir = TRUE) and sys.source(chdir = TRUE) make the sourced file's directory an allowed edit root while the script runs, wherever that is. The test source(chdir = TRUE) can change the working directory shows the script seeing getwd() as the outside directory, so relative writes in the script (saveRDS(x, "cache.rds"), unlink("output", recursive = TRUE)) land there unchecked. If that's intended, worth saying so in this comment; otherwise the fix suggested for withr would cover it too.

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.

Not intended. The same change covers it (31a74c2). Writes in the sourced script are checked against the recorded directory, so a relative saveRDS() or writeLines() in a script sourced with chdir = TRUE from outside the roots is refused. See the new test "a directory change that isn't checked doesn't widen where files may be edited".

# into a directory on its caller's behalf and restores the previous one
# on exit: source() and sys.source() for 'chdir = TRUE', and the srcfile
# helpers, which read a parsed file from the directory it was parsed in.
.rs.setVar("chat.workingDirectoryCallers", list(

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 few other base-package functions call setwd() directly and restore it on exit, but aren't listed here, and base namespaces aren't trusted, so they're now refused for a directory outside the roots: compiler::loadcmp(file, chdir = TRUE) (the same pattern as source(chdir = TRUE)), tools::checkMD5sums(), tools::buildVignette() / buildVignettes(), and utils:::untar2() (which untar() uses for the internal tar). Refusing untar() into an outside directory is arguably right, but loadcmp() and checkMD5sums() only read there. Worth adding loadcmp at least, or noting that the list is deliberately limited to these.

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 compiler::loadcmp() and tools::checkMD5sums() in 31a74c2. Exempting them is safe now that an exempt move no longer makes the directory editable. I left buildVignette()/buildVignettes() and untar2() checked on purpose: they write in the directory they change into, and some of that writing (pandoc's, for vignettes) is out of the hooks' sight. The comment on chat.workingDirectoryCallers now says this. isWorkingDirectoryCaller() also skips namespaces that aren't loaded rather than loading them.

.rs.chat.umaskMasksWorldRead()

# likewise, note where the user is before agent code can move
.rs.chat.recordUserWorkingDirectory()

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.

This runs after the reentrancy guard at line 752. If restoreBindings() fails to restore any binding, chat.bindingsInjected stays TRUE (line 1077), so every later activation returns early and the user's directory is never recorded again. After a Console setwd("~/projB"), assistant code doing setwd("sub"); setwd("..") is then refused on the way back. Recording before the guard would avoid that.

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 don't think this happens as described. For the setwd() check to refuse a later move, base::setwd must still be hooked, which means its own restore failed, and restoring a base binding doesn't fail in practice. The realistic failure is an fs binding, e.g. requireNamespace("fs") failing after fs was unloaded and removed. In that case setwd() is restored along with every other base hook, and injectBindings() returns early on every later activation. The guardrails are then off for the rest of the session, and a stale recorded directory doesn't matter. That stuck flag is on main already; I'd rather fix it in its own issue (have injectBindings() re-hook what was restored) than move the record above the guard. Moving it would also let a nested activation record a directory agent code had moved to as the user's choice.


setwd = function()
{
.rs.chat.validateWorkingDirectory("setwd", dir, sys.function(sys.parent()))

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.

setwd("") and setwd(NA) now fail with "One or more agent file operations were blocked" instead of R's own error ("cannot change working directory" / "character argument expected"): chat.normalizePath() turns both into "", which is never within a root. An agent running setwd(Sys.getenv("PROJ_DIR")) with the variable unset would read that as the move being forbidden. Returning early from chat.validateWorkingDirectory() unless dir is a single non-empty, non-NA string would let setwd() report 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.

Agreed, fixed in 31a74c2 with one change. setwd() moves to the first element of a longer vector (setwd(c("sub", "x")) moves to sub). An early return for anything but a single string would let setwd(c(outside, ".")) through unchecked. The check now returns early only for arguments setwd() rejects itself (not character, empty, or a first element that is NA or ""), and checks the first element otherwise. The tests compare the guarded error with plain setwd()'s error for "", NA_character_, NA and character().

Comment thread NEWS.md
- ([#19661](https://github.com/rstudio/rstudio/issues/19661)): RStudio Desktop can now switch to another installed version of R on macOS and Linux as well as Windows, from Tools > Global Options > General or Session > Switch R Version, restarting only the R session rather than RStudio. The version of R switched to, including from the renv R version notice in the Console, is kept for later launches; it takes precedence over `RSTUDIO_WHICH_R` until that variable changes (as it does when rig's default R changes), and is forgotten then. If the chosen R can't be used at startup, RStudio starts with the default R and asks whether to keep the choice (on Windows, the Choose R dialog is shown, as before), and if a session fails to start with the chosen R, the error page offers to go back to the previous or the default version of R.

### Fixed
- ([#19794](https://github.com/rstudio/rstudio/issues/19794)): Fixed an issue where `unlink(NULL)` failed with "invalid 'path' argument" in R code run by Posit Assistant. Packages that make this call while cleaning up, such as rmarkdown when rendering fails early, reported that error in place of the original one.

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 setwd() check changes the released guardrails (they shipped in 2026.04.0), so it needs a NEWS entry of its own; this one covers only unlink(NULL). From .claude/CLAUDE.md: "When fixing a bug or adding a new feature, add an entry to the appropriate section (### New, ### Fixed, etc.) of NEWS.md."

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, added in 51bf37c. It cites this PR, since the setwd() part has no issue of its own. It also covers the effect on rendering documents outside the allowed locations.

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

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

Passed Failed Skipped Flaky
5823 0 254 3
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1456 0 49 1
✅ desktop-macos 1463 0 43 1
✅ desktop-windows 1452 0 60 0
✅ server-linux 1400 0 54 1
✅ setup 48 0 32 0

View report online


All platforms - commit ae120267b3b715b637ac49ff7f7d41af9e25e0d1 - Run #2516

Edits were checked against the live working directory, so a move that
the setwd() check exempts (package code such as withr::with_dir(), or
source(chdir = TRUE)) made the new directory editable. They're now
checked against the directory recorded at activation.

With that, compiler::loadcmp() and tools::checkMD5sums() can change
directory like source() does, and arguments setwd() rejects are left
for it to report rather than reported as a blocked move.

@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. The changes address the review, and I agree with leaving the restore-failure case to its own issue.

@kevinushey
kevinushey merged commit ba4b4f0 into main Nov 25, 2026
1 of 5 checks passed
@kevinushey
kevinushey deleted the bugfix/chat-guardrails-working-directory branch November 25, 2026 18:17
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.

unlink(NULL) fails in R code run by Posit Assistant

2 participants