Skip to content

expand ~ in savehistory() / loadhistory() paths with path.expand() - #19685

Merged
kevinushey merged 4 commits into
mainfrom
bugfix/19684-history-tilde-path
Nov 19, 2026
Merged

kevinushey merged 4 commits into
mainfrom
bugfix/19684-history-tilde-path

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

On Windows with R 4.1 and earlier, savehistory() and loadhistory() didn't save or load the history file when given a path starting with ~ and the R home directory contained a non-ASCII character such as é. Neither showed an error.

Fixes #19684.

Approach

On Windows, RStudio replaces utils::savehistory() and utils::loadhistory() with .rs.savehistory() and .rs.loadhistory(), which call rs_saveHistory and rs_loadHistory in RSession.cpp. Those passed the path through R_ExpandFileName(r::sexp::asString(...)). Since #19640, asString() returns UTF-8. On Windows, though, R_ExpandFileName() expands ~ by prepending the home directory as getenv() returns it, which is in the native code page. FilePath then decoded the mixed string as UTF-8 and named a directory that doesn't exist. rs_saveHistory discards the write error, and rs_loadHistory only logs it, so nothing reached the user.

The wrappers now expand ~ in R with path.expand(), and the C++ side takes the expanded path as given. path.expand() marks the result's encoding, so asString() converts it to UTF-8 correctly whatever the native encoding. Relative paths and paths without ~ behave as before.

Before #19640 the whole string was native, so any non-ASCII history path failed. #19640 fixed paths that don't start with ~, and this fixes the rest.

The POSIX loadhistory() / savehistory() callbacks (doHistoryFileOperation() in RStdCallbacks.cpp) aren't affected. They read the path as native, which is what R_ExpandFileName() expects, and FilePath on POSIX uses the bytes as they are.

Automated Tests

New src/cpp/tests/testthat/test-history.R (--scope r --filter history) covers the split where the wrappers expand ~ and the C++ side doesn't. .rs.savehistory("~/<temp name>") should write the file under path.expand("~"), and .rs.loadhistory("~/<temp name>") should load it, checked by saving the history to a temp file and reading it back. The load test changes the session's history, so it skips unless RSTUDIO_TESTS_HELPER is set, as the rstudio-tests runners do. With path.expand() removed from the wrappers, both tests fail.

They don't reproduce #19684: that needs Windows, R < 4.2 and a non-ASCII home directory, and R caches the home directory for the life of the process. Verified manually instead:

  • Windows VM (R 3.6.3, code page 1252), using rsession from a CI installer that includes mark file paths passed to R as utf-8 #19640, with R_USER set to a directory named Crème. savehistory("~/hist.Rhistory") wrote no file at all, and loadhistory() on the same path logged system error 2 (The system cannot find the file specified) from rs_loadHistory. Calling the same C++ functions with path.expand(file), as the wrappers now do, wrote the file into Crème and loaded it back without error. (In that build R_ExpandFileName() leaves an already-expanded path unchanged, so this exercises the fixed behavior.)
  • macOS, using this branch's rsession with HOME set to a directory named Crème. .rs.savehistory("~/...") and .rs.loadhistory("~/...") work, and a relative path still saves into the working directory.
  • The R testthat suite passes locally (macOS, R 4.6.1).

QA Notes

Needs Windows with R 4.1 or earlier and an R home directory containing a non-ASCII character that the system code page can represent (e.g. é on an English-language system). Setting the R_USER environment variable to such a directory before starting RStudio is enough.

  1. In the Console, run a few commands, then savehistory("~/test.Rhistory").
  2. file.exists("~/test.Rhistory") should be TRUE, and the file should contain those commands.
  3. loadhistory("~/test.Rhistory") should restore them (check with the Up arrow in the Console).

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 (n/a: no UI)
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

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

Passed Failed Skipped Flaky
5747 0 254 2
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1438 0 49 0
✅ desktop-macos 1444 0 43 1
✅ desktop-windows 1432 0 60 1
✅ server-linux 1381 0 54 0
✅ setup 48 0 32 0

View report online


All platforms - commit 0c14ee484a09e776a932b659b9500582db869bc7 - Run #2376

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

The path.expand() approach looks right. In R 4.1.3's do_pathexpand, UTF-8 input goes through R_ExpandFileNameUTF8 and other input is expanded natively, and asString() converts either result to UTF-8 correctly. The inline comments are about the error handling around the fix and a test.

One more that isn't on a changed line:

The same encoding mismatch is in other callers. r::util::expandFileName (src/cpp/r/RUtil.cpp:180) and one direct R_ExpandFileName call still pass UTF-8 strings to R_ExpandFileName, so on Windows with R < 4.2 and a non-ASCII R_USER they build the same mixed-encoding path:

  • initializePaths() (src/cpp/session/modules/SessionFiles.cpp:1955) runs Rf_translateCharUTF8 then R_ExpandFileName. RStudio's list.files() / list.dirs() replacements use it, and SessionPatches.R:64 enables them by default on R < 4.2. So list.files("~") is affected in exactly the setup from #19684.
  • r::sexp::extract(SEXP, FilePath*) (src/cpp/r/RSexp.cpp:1173) extracts as UTF-8, then expands.
  • rs_browseURL for bare file paths (src/cpp/r/session/RSession.cpp:175).

Making expandFileName handle the encoding (UTF-8 to native, expand, back to UTF-8) would fix all of these, and the history functions could use it as well. That may be better as a separate issue than in this PR.

std::string file = R_ExpandFileName(r::sexp::asString(sFile).c_str());
consoleHistory().saveToFile(FilePath(file), false /* atomic */);
FilePath file(r::sexp::asString(sFile));
consoleHistory().saveToFile(file, false /* atomic */);

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 still drops the error from saveToFile(), so on Windows a failed savehistory() stays silent, which is what kept #19684 hidden. It predates this PR, but the same thing happens for any other write failure, such as a directory that doesn't exist or isn't writable.

On POSIX, RStudio's Rsavehistory goes through doHistoryFileOperation() (RStdCallbacks.cpp:146), which raises the error in R (RStdCallbacks.cpp:160), and R's own savehistory() fails with "problem in saving the history file". Raising an R error here would make Windows match.

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.

This is #19687, fixed in #19689: rs_saveHistory and rs_loadHistory now raise an R error with the same message the POSIX callbacks give. I kept it out of this PR so this one stays on the ~ expansion. The two PRs conflict on these lines; whichever merges second keeps this PR's FilePath file(...) line inside #19689's try.

FilePath file(r::sexp::asString(sFile));
Error error = consoleHistory().loadFromFile(file, true);
if (error)
LOG_ERROR(error);

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.

Same for load errors, with one more effect. ConsoleHistory::loadFromFile() clears historyBuffer_ before it finds the file is missing (RConsoleHistory.cpp:154), and consoleHistoryReset() runs only on success. So on Windows loadhistory("typo.Rhistory") empties the server-side history with no message, while the Console's Up arrow still offers the old commands. With "Always save history" on, quitting then writes the empty history to .Rhistory (RStdCallbacks.cpp:793).

R's own loadhistory() also clears first, so the clear itself is expected. What's missing is the error, and a reset event so the client matches the server. POSIX Rloadhistory (RStdCallbacks.cpp:666) raises the error but also skips the reset.

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.

The missing error is #19689, as above. The clearing is #19686, fixed in #19688: loadFromFile() reads into a separate buffer and swaps it in only once the read succeeds, and a missing file with verifyFile set returns the error before touching the history. A failed load now leaves the server's history as it was, so the client's list still matches and no reset event is needed. The reset after a successful load is unchanged. That covers POSIX Rloadhistory too.

Comment thread src/cpp/r/R/Tools.R
.rs.addFunction("savehistory", function(file = ".Rhistory")
{
invisible(.Call("rs_saveHistory", file, PACKAGE = "(embedding)"))
invisible(.Call("rs_saveHistory", path.expand(file), PACKAGE = "(embedding)"))

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.

Could this get a testthat test? It wouldn't reproduce #19684, as the description says, but it would cover the new split where these wrappers expand ~ and the C++ side doesn't. FilePath's string constructor doesn't expand ~, so if path.expand() were dropped later, "~/x" would be treated as a relative path and nothing would catch it. No existing test calls savehistory or loadhistory.

Something like .rs.savehistory("~/<temp name>") followed by expect_true(file.exists(path.expand(...))), with cleanup, would work on any platform.

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 202a3a9. test-history.R checks that .rs.savehistory("~/<temp name>") writes the file under path.expand("~"). It also checks that .rs.loadhistory("~/<temp name>") loads that file, by saving the history to a temp file and reading it back. The load test changes the session's history, so it skips outside the rstudio-tests runner, as #19689's tests do. With path.expand() removed from the wrappers, both tests fail. #19689 adds a file with the same name, so whichever merges second keeps both sets of tests.

@kevinushey

Copy link
Copy Markdown
Collaborator Author

Agreed on the other R_ExpandFileName callers. Filed as #19724, which proposes fixing r::util::expandFileName() to handle UTF-8 and pointing initializePaths() at it.

@kevinushey
kevinushey requested a review from gtritchie November 18, 2026 22:04

@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 new test covers the ~ expansion, and the rest is tracked in #19688, #19689 and #19724.

Jenkins failed on 202a3a9 with "This commit cannot be built", and GitHub shows the branch as conflicting with main. Could you merge main in and let CI pass before merging?

@kevinushey
kevinushey merged commit b7ebf96 into main Nov 19, 2026
45 checks passed
@kevinushey
kevinushey deleted the bugfix/19684-history-tilde-path branch November 19, 2026 15:29
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.

savehistory() / loadhistory() mis-decode "~" paths on Windows R < 4.2 when the home directory is non-ASCII

2 participants