Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 80 additions & 18 deletions scripts/test-activation.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const cases = [
'workspace', 'command', 'terminal-profile', 'task', 'r-notebook',
'interactive-create', 'interactive-restore',
'interactive-background-create', 'interactive-background-restore',
'terminal-persistent-reload',
'terminal-persistent-reload', 'terminal-revive-create', 'terminal-revive-restore',
];
const pause = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));

Expand All @@ -22,9 +22,9 @@ function clearElectronNodeMode(environment) {
}
exports.clearElectronNodeMode = clearElectronNodeMode;

async function until(predicate, message) {
const deadline = Date.now() + 15000;
while (!predicate()) {
async function until(predicate, message, timeout = 15000) {
const deadline = Date.now() + timeout;
while (!(await predicate())) {
assert.ok(Date.now() < deadline, message);
await pause(50);
}
Expand Down Expand Up @@ -164,6 +164,63 @@ exports.run = async (api) => {
vscode.window.terminals.forEach((terminal) => terminal.dispose());
break;
}
case 'terminal-revive-create':
case 'terminal-revive-restore': {
const creating = testCase === 'terminal-revive-create';
const previousFile = path.join(root, 'terminal-before-quit.json');
if (creating) {
await within(vscode.commands.executeCommand('r.createRTerm'), 'Could not create R terminal');
}
const previous = creating ? undefined : JSON.parse(fs.readFileSync(previousFile, 'utf8'));
const name = previous?.name ?? 'R Interactive';
await until(() => vscode.window.terminals.some((term) => term.name === name),
'The R terminal was missing from the restored window');
const terminal = vscode.window.terminals.find((term) => term.name === name);
const terminalPid = await within(terminal.processId, 'Missing terminal PID');
const stateFile = path.join(root, testCase + '-state');
const rPath = (value) => JSON.stringify(value.replace(/\\/g, '/'));
const deadline = Date.now() + 30000;
while (!fs.existsSync(stateFile)) {
assert.ok(Date.now() < deadline, 'R terminal did not report its startup state');
terminal.sendText(`writeLines(c(Sys.getpid(), sess:::.session_id(), Sys.getenv('SESS_DISCOVERY_FILE')), ` +
`${rPath(stateFile + '.pending')}); invisible(file.rename(${rPath(stateFile + '.pending')}, ${rPath(stateFile)}))`);
for (let i = 0; i < 20 && !fs.existsSync(stateFile); ++i) { await pause(100); }
}
const [pid, sessionId, discovery] = fs.readFileSync(stateFile, 'utf8').trim().split(/\r?\n/);
if (creating) {
await until(() => extension.exports.session.getSessionReference(sessionId), 'Initial sess attachment failed');
const logs = path.join(root, 'profile', 'logs');
await until(() => terminalLayoutState(logs, terminalPid).saved, 'R terminal layout was not saved');
fs.writeFileSync(previousFile, JSON.stringify({ name: terminal.name, pid, sessionId }));
} else {
assert.notEqual(pid, previous.pid, 'A full restart must create a new R process');
assert.notEqual(sessionId, previous.sessionId);
// The new R process has already tried the saved endpoint. Exercise
// recovery even if its stale discovery record is removed before activation.
const sessionsDir = path.join(root, 'profile', 'User', 'globalStorage', 'reditorsupport.r', 'sessions');
assert.equal(path.relative(sessionsDir, path.dirname(discovery)), '');
fs.rmSync(discovery, { force: true });
const document = await vscode.workspace.openTextDocument({ language: 'r', content: 'revived' });
await vscode.window.showTextDocument(document);
await until(() => extension.isActive, 'R file did not activate vscode-R');
await until(() => extension.exports.session.getSessionReference(sessionId),
`Revived R terminal ${terminalPid} did not attach R process ${pid} through ${discovery}`);
terminal.sendText('revivedTable <- data.frame(x = 1)');
// The connection is public before the native process lookup selects
// its Workspace. Wait for the editor's session completion to observe
// the object created in this R process.
await until(async () => {
const completions = await vscode.commands.executeCommand('vscode.executeCompletionItemProvider',
document.uri, new vscode.Position(0, 7));
return completions.items.some((item) => item.label === 'revivedTable' && item.detail === '[session]');
}, 'The refreshed Workspace did not contain the revived session object', 30000);
terminal.sendText('View(revivedTable); plot(1)');
const hasTab = (label) => vscode.window.tabGroups.all.some((group) => group.tabs.some((tab) => tab.label === label));
await until(() => hasTab('revivedTable') && hasTab('R Plot'), 'Data and plot viewers did not open after revival');
terminal.dispose();
}
break;
}
case 'terminal-persistent-reload': {
const phaseFile = path.join(root, 'terminal-reload-state.json');
const reloading = fs.existsSync(phaseFile);
Expand Down Expand Up @@ -356,7 +413,7 @@ async function main() {
const executable = process.env.VSCR_ACTIVATION_VSCODE || await downloadAndUnzipVSCode();
const selected = process.env.VSCR_ACTIVATION_CASES?.split(',') || cases;
selected.forEach((testCase) => assert.ok(cases.includes(testCase), `Unknown case: ${testCase}`));
for (const prefix of ['interactive-', 'interactive-background-']) {
for (const prefix of ['interactive-', 'interactive-background-', 'terminal-revive-']) {
if (selected.includes(`${prefix}restore`)) {
assert.ok(selected.includes(`${prefix}create`), 'Restore requires its create stage in the same run');
assert.ok(selected.indexOf(`${prefix}create`) < selected.indexOf(`${prefix}restore`));
Expand Down Expand Up @@ -402,19 +459,21 @@ exports.activate = async () => {
try {
const reports = [];
for (const testCase of selected) {
const persistentTerminal = testCase === 'terminal-persistent-reload';
const revive = testCase.startsWith('terminal-revive-');
const persistentTerminal = testCase === 'terminal-persistent-reload' || revive;
const name = testCase.startsWith('interactive-background-') ? 'restore-background'
: testCase.startsWith('interactive-') ? 'restore' : testCase;
: testCase.startsWith('interactive-') ? 'restore' : revive ? 'terminal-revive' : testCase;
const caseRoot = path.join(root, name);
const workspace = path.join(caseRoot, 'workspace');
const profile = path.join(caseRoot, 'profile');
fs.mkdirSync(workspace, { recursive: true });
fs.mkdirSync(path.join(profile, 'User'), { recursive: true });
fs.writeFileSync(path.join(profile, 'User', 'settings.json'), JSON.stringify({
'r.lsp.enabled': false, 'r.sessionWatcher': persistentTerminal, 'r.plot.backend': 'native',
'r.lsp.enabled': false, 'r.sessionWatcher': persistentTerminal, 'r.plot.backend': revive ? 'standard' : 'native',
'r.interactive.restore': false, 'r.interactive.storagePath': path.join(caseRoot, 'sessions'),
'update.mode': 'none', 'extensions.autoUpdate': false, 'workbench.startupEditor': 'none',
'window.restoreWindows': 'all', 'terminal.integrated.enablePersistentSessions': persistentTerminal,
...(revive ? { 'terminal.integrated.persistentSessionReviveProcess': 'onExitAndWindowClose' } : {}),
...(persistentTerminal ? { 'r.session.emulateRStudioAPI': false,
'r.consoleArgs': ['--no-save', '--no-restore', '--no-site-file'] } : {}),
}));
Expand All @@ -437,15 +496,17 @@ exports.activate = async () => {
const library = path.join(caseRoot, 'r-library');
const librariesFile = path.join(caseRoot, 'r-library-paths');
const emptyProfile = path.join(caseRoot, 'empty-profile');
fs.mkdirSync(library);
fs.mkdirSync(library, { recursive: true });
fs.writeFileSync(emptyProfile, '');
const rString = (value) => JSON.stringify(value.replace(/\\/g, '/'));
const setup = spawnSync('Rscript', ['--vanilla', '-e',
`writeLines(.libPaths(), ${rString(librariesFile)}); ` +
`install.packages(${rString(path.join(repository, 'dist', 'resources', 'sess'))}, ` +
`lib=${rString(library)}, repos=NULL, type='source')`],
{ encoding: 'utf8', timeout: 300000 });
assert.equal(setup.status, 0, `Could not prepare isolated terminal sess: ${setup.stderr}`);
if (!fs.existsSync(librariesFile)) {
const setup = spawnSync('Rscript', ['--vanilla', '-e',
`writeLines(.libPaths(), ${rString(librariesFile)}); ` +
`install.packages(${rString(path.join(repository, 'dist', 'resources', 'sess'))}, ` +
`lib=${rString(library)}, repos=NULL, type='source')`],
{ encoding: 'utf8', timeout: 300000 });
assert.equal(setup.status, 0, `Could not prepare isolated terminal sess: ${setup.stderr}`);
}
env.R_LIBS_USER = [library, ...fs.readFileSync(librariesFile, 'utf8').trim().split(/\r?\n/)].join(path.delimiter);
env.R_PROFILE_USER = emptyProfile;
}
Expand Down Expand Up @@ -495,20 +556,21 @@ exports.activate = async () => {
for (const directory of fs.readdirSync(root, { withFileTypes: true })) {
if (!directory.isDirectory()) { continue; }
const caseRoot = path.join(root, directory.name);
if (directory.name === 'terminal-persistent-reload') {
const terminalCase = directory.name === 'terminal-persistent-reload' || directory.name === 'terminal-revive';
if (terminalCase) {
fs.mkdirSync(path.join(artifacts, directory.name), { recursive: true });
}
for (const file of fs.readdirSync(caseRoot, { withFileTypes: true })) {
if (file.name.endsWith('.log')) {
fs.copyFileSync(path.join(caseRoot, file.name),
path.join(artifacts, `${directory.name}-${file.name}`));
} else if (directory.name === 'terminal-persistent-reload' && file.isFile()) {
} else if (terminalCase && file.isFile()) {
// Phase and probe files show how far each window got.
fs.copyFileSync(path.join(caseRoot, file.name),
path.join(artifacts, directory.name, file.name));
}
}
if (directory.name === 'terminal-persistent-reload') {
if (terminalCase) {
const logs = path.join(caseRoot, 'profile', 'logs');
if (fs.existsSync(logs)) {
fs.cpSync(logs, path.join(artifacts, directory.name, 'logs'), { recursive: true });
Expand Down
106 changes: 77 additions & 29 deletions sess/R/server.R
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
#' @details
#' When SESS_DISCOVERY_FILE describes the connected endpoint, an unexpected disconnect waits for a
#' replacement endpoint in that file and reconnects with the same runtime options and session
#' identity. The optional discovery jgdSocket string updates JGD_SOCKET when the resolved backend
#' includes jgd and `allow_jgd` is `TRUE`; an empty string clears it, and an omitted field leaves it
#' unchanged. Set `options(sess.quiet = TRUE)` to suppress the successful connection message.
#' identity. A managed R terminal that starts before its editor is ready retries its first discovery
#' connection in the background. A new R process gets its own workspace and session identity. The
#' optional discovery jgdSocket string updates JGD_SOCKET when the resolved backend includes jgd and
#' `allow_jgd` is `TRUE`; an empty string clears it, and an omitted field leaves it unchanged. Set
#' `options(sess.quiet = TRUE)` to suppress the successful connection message.
#' @export
connect <- function(
endpoint = NULL,
Expand Down Expand Up @@ -69,21 +71,27 @@ connect <- function(

.sess_env$latest_plot_path <- file.path(.sess_env$tempdir, "sess_plot.png")

endpoint <- .resolve_endpoint(endpoint)
if (!nzchar(endpoint)) {
warning("[sess] Connection info not available. Cannot connect to VS Code.")
return(invisible(FALSE))
}

discovery_file <- Sys.getenv("SESS_DISCOVERY_FILE")
registration <- getOption("vscodeR.terminalStartup")
managed_startup <- is.null(endpoint) &&
!nzchar(Sys.getenv("SESS_ENDPOINT")) &&
nzchar(discovery_file) &&
is.list(registration) &&
identical(registration$pid, Sys.getpid()) &&
identical(registration$file, paste0(discovery_file, ".startup")) &&
is.function(registration$run)
# Only follow discovery if it describes this connection, including explicit
# endpoints from the generated attach script. Never redirect an unrelated client.
discovery <- if (nzchar(discovery_file)) .read_discovery(discovery_file) else NULL
if (!is.null(discovery) && identical(discovery$endpoint, endpoint)) {
endpoint <- if (managed_startup) discovery$endpoint %||% "" else .resolve_endpoint(endpoint)
if (managed_startup || (!is.null(discovery) && identical(discovery$endpoint, endpoint))) {
.configure_discovery_jgd(discovery, allow_jgd && plot_backend %in% c("auto", "jgd"))
.sess_env$reconnect <- list(
path = discovery_file,
endpoint = endpoint,
# The first handshake can lose its socket during the attach write or poll.
# Until startup succeeds, even the same endpoint is eligible for retry.
endpoint = if (managed_startup) NULL else endpoint,
startup_run = if (managed_startup) registration$run,
options = list(
use_rstudioapi = use_rstudioapi,
plot_backend = plot_backend,
Expand All @@ -94,6 +102,21 @@ connect <- function(
)
}

retry_startup <- function() {
if (managed_startup) {
message("[sess] Waiting for VS Code to accept the terminal connection.")
.schedule_reconnect(.sess_env$reconnect)
}
invisible(FALSE)
}
if (!nzchar(endpoint)) {
if (!managed_startup) {
warning("[sess] Connection info not available. Cannot connect to VS Code.")
}
return(retry_startup())
}
discovery_endpoint <- endpoint

# processx uses the \\?\pipe\ namespace on Windows.
# Normalize \\.\pipe\* paths from Node.js to improve compatibility.
if (.Platform$OS.type == "windows") {
Expand All @@ -106,7 +129,7 @@ connect <- function(
# and the console does not redraw it. Startup and console calls to connect()
# are followed by the frontend's own prompt.
print_async_msg <- function(msg) {
redraw <- isTRUE(.sess_env$reconnecting) && interactive()
redraw <- !is.null(.sess_env$reconnecting) && interactive()
prompt <- if (redraw) getOption("prompt") else ""
cat(sprintf("\r%s\n\n%s", msg, prompt))
}
Expand All @@ -115,12 +138,14 @@ connect <- function(
con <- tryCatch(
processx::conn_connect_unix_socket(endpoint, encoding = ""),
error = function(e) {
print_async_msg(sprintf("[sess] Failed to connect to IPC endpoint: %s", e$message))
if (!managed_startup && !identical(.sess_env$reconnecting, "startup")) {
print_async_msg(sprintf("[sess] Failed to connect to IPC endpoint: %s", e$message))
}
NULL
}
)
if (is.null(con)) {
return(FALSE)
return(retry_startup())
}

.sess_env$con <- con
Expand All @@ -138,15 +163,12 @@ connect <- function(

# Start the polling loop
poll_connection(.sess_env$transport_generation)
TRUE
}

connected <- do_connect()

if (is.na(use_rstudioapi)) {
use_rstudioapi <- TRUE
}
if (isTRUE(connected) && !is.null(.sess_env$con)) {
if (is.null(.sess_env$con)) {
return(FALSE)
}
if (is.na(use_rstudioapi)) {
use_rstudioapi <- TRUE
}
tryCatch(
runtime_start(
use_rstudioapi = use_rstudioapi,
Expand Down Expand Up @@ -180,9 +202,18 @@ connect <- function(
.sess_env$runtime_start_phase <- NULL
}
)
if (!is.null(.sess_env$con) && managed_startup) {
.sess_env$reconnect$endpoint <- discovery_endpoint
.sess_env$reconnect$startup_run <- NULL
}
invisible(!is.null(.sess_env$con))
}

invisible(isTRUE(connected) && !is.null(.sess_env$con))
if (managed_startup && !identical(registration$endpoint, discovery_endpoint)) {
# The editor replaced discovery before the revived profile reached sess.
# Publish readiness for the actual endpoint, superseding the saved attempt.
return(.reconnect_with_startup(discovery_endpoint, do_connect))
}
do_connect()
}

# Resolve the direct argument, environment variables, then discovery data.
Expand Down Expand Up @@ -343,7 +374,8 @@ connect <- function(
.schedule_reconnect <- function(
settings,
generation = .sess_env$transport_generation,
schedule = later::later
schedule = later::later,
delay = 1
) {
if (is.null(settings)) {
return(invisible(NULL))
Expand All @@ -359,8 +391,22 @@ connect <- function(
) {
return(invisible(NULL))
}
registration <- getOption("vscodeR.terminalStartup")
if (
is.null(settings$endpoint) &&
(!is.list(registration) ||
!identical(registration$pid, pid) ||
!identical(registration$file, paste0(settings$path, ".startup")) ||
!identical(registration$run, settings$startup_run))
) {
return(invisible(NULL))
}
discovery <- .read_discovery(settings$path)
endpoint <- discovery$endpoint
if (is.null(endpoint) && is.null(settings$endpoint)) {
# Wake an editor which started after the discovery file disappeared.
.reconnect_with_startup(registration$endpoint, function() FALSE)
}
if (
is.character(endpoint) &&
length(endpoint) == 1L &&
Expand All @@ -377,7 +423,7 @@ connect <- function(
discovery,
isTRUE(allow_jgd) && settings$options$plot_backend %in% c("auto", "jgd")
)
.sess_env$reconnecting <- TRUE
.sess_env$reconnecting <- if (is.null(settings$endpoint)) "startup" else TRUE
tryCatch(
.reconnect_with_startup(
endpoint,
Expand All @@ -390,16 +436,18 @@ connect <- function(
)
if (!is.null(.sess_env$con)) {
settings$endpoint <- endpoint
settings$startup_run <- NULL
.sess_env$reconnect <- settings
return(invisible(NULL))
}
# An attach write/poll failure may itself have queued a retry. Cancel it
# before scheduling our retry so there is only one pending chain.
.transport_disconnect(silent = TRUE, preserve_plots = TRUE)
}
.schedule_reconnect(settings, .sess_env$transport_generation, schedule)
next_delay <- if (is.null(settings$endpoint)) min(delay * 2, 8) else 1
.schedule_reconnect(settings, .sess_env$transport_generation, schedule, next_delay)
},
1
delay
)
invisible(NULL)
}
Expand Down
Loading
Loading