From cea6b0c0d50dc8c8890de696229c95bf8eee23aa Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Tue, 17 Nov 2026 01:10:51 +0800 Subject: [PATCH 1/4] fix: activate vscode-R only for R features --- package.json | 6 ++---- website/docs/features/r-interactive.md | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index ee442d263..175d4ce8e 100644 --- a/package.json +++ b/package.json @@ -35,9 +35,7 @@ "onWebviewPanel:r.htmlViewer", "onLanguage:r", "onLanguage:rmd", - "onNotebook:r-interactive", - "onNotebook:interactive", - "onStartupFinished" + "onNotebook:r-interactive" ], "main": "./dist/extension", "contributes": { @@ -2457,7 +2455,7 @@ "tags": ["experimental"], "type": "boolean", "default": true, - "description": "Reconnect the workspace’s Interactive sessions when VS Code reopens." + "description": "Automatically reconnect the workspace’s Interactive sessions when R features are used." }, "r.interactive.historyLimit": { "tags": ["experimental"], diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index 361f58042..a50b45cea 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -194,7 +194,7 @@ If session creation reports `EACCES`, the storage directory or an ancestor is no Each session stores a manifest, immutable assets, and one journal directory per process generation. Private Unix sockets and credentials live in a mode-0700 runtime directory. The extension discovers existing agents after a reload and reconstructs the recent transcript. Asset URLs are regenerated through VS Code's remote forwarding support. -With `r.interactive.restore` enabled (the default), reopening the same workspace reconnects its saved sessions, even when no R source file is open. Native Interactive tabs are matched by their saved URI, since VS Code does not retain their notebook metadata across reload. This restores the existing views without opening duplicate empty tabs. A failed reconnect preserves the saved association for a later retry. Sessions remain discoverable through **R: Open Interactive Session** from another workspace or when automatic restoration is disabled. Closing a view or choosing **Disconnect** removes its automatic-restoration entry while leaving R alive. +With `r.interactive.restore` enabled (the default), saved sessions reconnect when you open an R workspace, display a saved R Interactive tab, or use an R command. In an unrelated workspace with no visible R tab, reconnection waits until you use R. Native Interactive tabs are matched by their saved URI, since VS Code does not retain their notebook metadata across reload. This restores the existing views without opening duplicate empty tabs. A failed reconnect preserves the saved association for a later retry. Sessions remain discoverable through **R: Open Interactive Session** from another workspace or when automatic restoration is disabled. Closing a view or choosing **Disconnect** removes its automatic-restoration entry while leaving R alive. Admission and completion records are flushed to disk. Ordinary output is buffered by the OS, so a machine crash can lose recent output. The execution ledger prevents automatic duplicate evaluation; it does not make arbitrary R code transactional. If the agent dies during a request, the outcome can remain unknown. R process death loses in-memory objects even when its transcript survives. From 4de4ae3de87d77f8c02557f0f0ecf736c2055ba8 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Tue, 17 Nov 2026 01:15:02 +0800 Subject: [PATCH 2/4] test: cover on-demand activation and native Interactive restoration --- .github/workflows/main.yml | 7 + CONTRIBUTING.md | 10 ++ package.json | 1 + scripts/test-activation.cjs | 308 ++++++++++++++++++++++++++++++++++++ 4 files changed, 326 insertions(+) create mode 100644 scripts/test-activation.cjs diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 7dcfe7db1..12c46bceb 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -110,6 +110,12 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: ./.github/actions/setup-test-tools - uses: ./.github/actions/prepare-test-runtime + - name: Test on-demand activation (Linux) + if: runner.os == 'Linux' + run: xvfb-run -a pnpm run test:activation + - name: Test on-demand activation + if: runner.os != 'Linux' + run: pnpm run test:activation - name: Run plot lifecycle extension tests (Linux) if: runner.os == 'Linux' run: xvfb-run -a pnpm run test:extension --label plot-lifecycle @@ -128,6 +134,7 @@ jobs: with: name: extension-test-logs-${{ runner.os }} path: | + .vscode-test/activation/*.log .vscode-test/user-data/**/logs/**/exthost/exthost.log .vscode-test/user-data/**/logs/**/exthost/output_logging_*/*.log retention-days: 7 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 987614d34..4e80af132 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -116,6 +116,16 @@ in Node/Mocha, then runs the extension-host suites. supervision. After preparing once with `pnpm run pretest`, use `pnpm run test:node` and `pnpm run test:extension` to rerun either layer without rebuilding. +Run `pnpm run test:activation` after compiling to check activation in fresh +VS Code windows. It verifies that unrelated workspaces and Python Interactive +windows keep vscode-R inactive, and that R files, commands, terminal profiles, +tasks, notebooks, and restored native R Interactive inputs activate it. Each +case uses temporary profiles without the normal suite's forced activation. +`VSCR_ACTIVATION_VSCODE` selects an existing VS Code executable; otherwise the +runner downloads current stable. `VSCR_ACTIVATION_CASES` selects a comma-separated +subset of cases from `scripts/test-activation.cjs`. On headless Linux, use +`xvfb-run -a pnpm run test:activation`. + To debug extension-host tests, select **Extension Tests** in Run and Debug and press **F5**. The pre-launch task runs `pnpm run pretest`, and the debugger then asks which `.vscode-test.mjs` configuration to run (`provider-tests`, diff --git a/package.json b/package.json index 175d4ce8e..4258ae059 100644 --- a/package.json +++ b/package.json @@ -2601,6 +2601,7 @@ "test": "pnpm run test:node && pnpm run test:extension", "test:node": "mocha \"out/test/node/**/*.test.js\" --config .mocharc.interactive.cjs", "test:extension": "vscode-test", + "test:activation": "node scripts/test-activation.cjs", "lint": "oxlint src", "format": "oxfmt .", "format:check": "oxfmt --check .", diff --git a/scripts/test-activation.cjs b/scripts/test-activation.cjs new file mode 100644 index 000000000..bc9b6687c --- /dev/null +++ b/scripts/test-activation.cjs @@ -0,0 +1,308 @@ +// Run after `pnpm run compile`. Every case gets a fresh extension host and +// profile; this runner never calls extension.activate() or extensionSetup. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const repository = path.resolve(__dirname, '..'); +const cases = [ + 'no-folder', 'non-r', 'non-r-interactive', 'language-r', 'language-rmd', + 'workspace', 'command', 'terminal-profile', 'task', 'r-notebook', + 'interactive-create', 'interactive-restore', + 'interactive-background-create', 'interactive-background-restore', +]; +const pause = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); + +async function until(predicate, message) { + const deadline = Date.now() + 15000; + while (!predicate()) { + assert.ok(Date.now() < deadline, message); + await pause(50); + } +} + +async function within(promise, message) { + let timer; + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(message)), 20000); + }), + ]); + } finally { clearTimeout(timer); } +} + +exports.run = async (api) => { + const vscode = api?.extensions ? api : require('vscode'); + const testCase = process.env.VSCR_ACTIVATION_CASE; + const root = process.env.VSCR_ACTIVATION_ROOT; + const extension = vscode.extensions.getExtension('REditorSupport.r'); + assert.ok(extension, 'The development extension must be available'); + // Give delayed startup activation and workspace searches time to run. The + // normal suite's forced global activation would hide this regression. + await pause(3000); + + if (testCase === 'workspace') { + await until(() => extension.isActive, 'R workspace marker did not activate the extension'); + } else if (testCase === 'interactive-restore') { + await until(() => extension.isActive, 'Restored R Interactive input did not activate R'); + const input = vscode.workspace.textDocuments.find((document) => + document.uri.scheme === 'vscode-interactive-input' && document.languageId === 'r'); + assert.ok(input, 'The empty R Interactive input must retain its language after reopening'); + assert.equal(input.getText(), ''); + assert.ok(!vscode.workspace.textDocuments.some((document) => + ['file', 'untitled'].includes(document.uri.scheme) && document.languageId === 'r'), + 'Restoration must activate without a separate R source document'); + } else { + // VS Code may resolve configured R tasks during startup. That workspace + // is already R-related; verify its actual provider below either way. + if (testCase !== 'task') { + assert.equal(extension.isActive, false, `${testCase}: R activated before an R trigger`); + } + switch (testCase) { + case 'no-folder': + assert.equal(vscode.workspace.workspaceFolders, undefined); + break; + case 'non-r': { + const document = await vscode.workspace.openTextDocument( + vscode.Uri.file(path.join(root, 'workspace', 'index.js'))); + await vscode.window.showTextDocument(document); + await pause(2000); + assert.equal(extension.isActive, false, 'JavaScript editing activated R'); + break; + } + case 'language-r': + case 'language-rmd': { + const language = testCase.slice('language-'.length); + const document = await vscode.workspace.openTextDocument({ language, content: '' }); + await vscode.window.showTextDocument(document); + await until(() => extension.isActive, `${language} document did not activate R`); + break; + } + case 'command': + // A command that does not itself open an R document proves the + // contributed command's activation route works independently. + await within(vscode.commands.executeCommand('r.browser.refresh'), 'R command timed out'); + assert.equal(extension.isActive, true, 'Contributed R command did not activate R'); + break; + case 'terminal-profile': { + await within(vscode.commands.executeCommand('workbench.action.terminal.newWithProfile', + { config: { extensionIdentifier: 'REditorSupport.r', id: 'r.terminal-profile', title: 'R Terminal' } }), + 'R Terminal profile timed out'); + await until(() => extension.isActive, 'R Terminal profile did not activate R'); + await until(() => vscode.window.terminals.length > 0, 'R Terminal was not created'); + vscode.window.terminals.forEach((terminal) => terminal.dispose()); + break; + } + case 'task': { + const tasks = await within(vscode.tasks.fetchTasks({ type: 'R' }), 'R task resolution timed out'); + assert.ok(tasks.some((task) => task.name === 'Activation task' && task.execution), + 'The contributed R task must be resolved without opening R source'); + assert.equal(extension.isActive, true, 'R task resolution did not activate R'); + break; + } + case 'r-notebook': { + const notebook = await within(vscode.workspace.openNotebookDocument( + vscode.Uri.file(path.join(root, 'notebook.rnb'))), 'R notebook opening timed out'); + await vscode.window.showNotebookDocument(notebook); + assert.equal(notebook.notebookType, 'r-interactive'); + assert.equal(extension.isActive, true, 'R notebook did not activate R'); + break; + } + case 'interactive-background-restore': { + const uri = vscode.Uri.parse(fs.readFileSync(path.join(root, 'interactive-uri'), 'utf8')); + assert.ok(vscode.window.tabGroups.all.some((group) => + group.tabs.some((tab) => tab.label === 'Activation test')), + 'The original background Interactive tab must have been restored'); + await within(vscode.commands.executeCommand('interactive.open', + { preserveFocus: false }, uri), 'Restored background Interactive tab timed out'); + await until(() => extension.isActive, 'Opening restored background R input did not activate R'); + assert.ok(vscode.workspace.textDocuments.some((document) => + document.uri.scheme === 'vscode-interactive-input' && document.languageId === 'r'), + 'Background Interactive input must retain R language'); + break; + } + case 'non-r-interactive': + case 'interactive-create': + case 'interactive-background-create': { + const opened = await within(vscode.commands.executeCommand('interactive.open', + { preserveFocus: false }, undefined, undefined, 'Activation test'), + 'Native Interactive window timed out'); + assert.ok(opened?.inputUri, 'Native Interactive must expose its input URI'); + let input = await vscode.workspace.openTextDocument(opened.inputUri); + input = await vscode.languages.setTextDocumentLanguage(input, 'python'); + await pause(2000); + assert.equal(extension.isActive, false, 'Python native Interactive activated R'); + if (testCase !== 'non-r-interactive') { + const controller = vscode.notebooks.createNotebookController( + 'activation-r', 'interactive', 'Activation R'); + controller.supportedLanguages = ['r']; + await vscode.commands.executeCommand('notebook.selectKernel', { + id: controller.id, extension: 'vscode-r-tests.activation-fixture', + notebookEditor: { notebookUri: opened.notebookUri }, + }); + input = await vscode.languages.setTextDocumentLanguage(input, 'r'); + await vscode.commands.executeCommand('interactive.input.focus'); + await until(() => extension.isActive, 'R native Interactive input did not activate R'); + assert.equal(input.getText(), ''); + const notebook = await vscode.workspace.openNotebookDocument(opened.notebookUri); + assert.equal(notebook.cellCount, 0, 'Restore fixture must have no R transcript cells'); + fs.writeFileSync(path.join(root, 'interactive-uri'), opened.notebookUri.toString()); + if (testCase === 'interactive-background-create') { + await vscode.window.showTextDocument(await vscode.workspace.openTextDocument( + vscode.Uri.file(path.join(root, 'workspace', 'index.js')))); + } + // Keep this native tab open. The next fully exited editor + // reuses only this profile and restores the empty R input. + await pause(1000); + } + break; + } + default: + throw new Error(`Unknown activation case: ${testCase}`); + } + } + const result = { case: testCase, vscode: vscode.version, active: extension.isActive }; + fs.writeFileSync(path.join(root, `${testCase}.json`), JSON.stringify(result)); + console.log('Activation regression:', JSON.stringify(result)); +}; + +async function main() { + const { downloadAndUnzipVSCode, resolveCliArgsFromVSCodeExecutablePath, runTests } = require('@vscode/test-electron'); + const { spawnSync } = require('node:child_process'); + 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-']) { + 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`)); + } + } + // macOS's long per-user TMPDIR can exceed the Unix socket path limit. + const root = fs.mkdtempSync(path.join(process.platform === 'darwin' ? '/tmp' : os.tmpdir(), 'r-act-')); + const extensions = path.join(root, 'extensions'); + fs.mkdirSync(extensions); + // Extension test mode uses in-memory editor storage. Restoration needs + // ordinary development windows and a helper that exits after assertions. + const helper = path.join(root, 'helper'); + fs.mkdirSync(helper); + fs.writeFileSync(path.join(helper, 'package.json'), JSON.stringify({ + name: 'activation-fixture', publisher: 'vscode-r-tests', version: '1.0.0', + engines: { vscode: '^1.101.0' }, activationEvents: ['onStartupFinished'], main: 'index.cjs', + })); + fs.writeFileSync(path.join(helper, 'index.cjs'), ` +const vscode = require('vscode'); +exports.activate = async () => { + try { await require(${JSON.stringify(__filename)}).run(vscode); } + catch (error) { require('node:fs').writeFileSync(require('node:path').join(process.env.VSCR_ACTIVATION_ROOT, + process.env.VSCR_ACTIVATION_CASE + '.error'), error.stack || String(error)); } + finally { await vscode.commands.executeCommand('workbench.action.quit'); } +}; +`); + // Reuse the cached syntax dependency when available; clean CI installs only + // that dependency into this run's isolated extension directory. + const cached = path.join(repository, '.vscode-test', 'extensions'); + const syntax = fs.existsSync(cached) && fs.readdirSync(cached).find((name) => + name.startsWith('reditorsupport.r-syntax-')); + if (syntax) { + fs.cpSync(path.join(cached, syntax), path.join(extensions, syntax), { recursive: true }); + } else { + const [cli, ...args] = resolveCliArgsFromVSCodeExecutablePath(executable, { reuseMachineInstall: true }); + const installed = spawnSync(cli, [...args, '--user-data-dir', path.join(root, 'install-profile'), '--extensions-dir', extensions, + '--install-extension', 'REditorSupport.r-syntax'], + { stdio: 'inherit', shell: process.platform === 'win32' }); + assert.equal(installed.status, 0, 'Could not install the R syntax dependency'); + } + let success = false; + try { + const reports = []; + for (const testCase of selected) { + const name = testCase.startsWith('interactive-background-') ? 'restore-background' + : testCase.startsWith('interactive-') ? 'restore' : 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': false, 'r.plot.backend': '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': false, + })); + fs.writeFileSync(path.join(workspace, 'index.js'), 'const unrelated = true;\n'); + if (testCase === 'workspace') { + fs.mkdirSync(path.join(workspace, 'nested'), { recursive: true }); + fs.writeFileSync(path.join(workspace, 'nested', 'sample.R'), '1 + 1\n'); + } + if (testCase === 'task') { + fs.mkdirSync(path.join(workspace, '.vscode')); + fs.writeFileSync(path.join(workspace, '.vscode', 'tasks.json'), JSON.stringify({ + version: '2.0.0', tasks: [{ type: 'R', label: 'Activation task', code: ['1 + 1'] }], + })); + } + if (testCase === 'r-notebook') { + fs.writeFileSync(path.join(caseRoot, 'notebook.rnb'), JSON.stringify({ version: 1, metadata: {}, cells: [] })); + } + const env = { VSCR_ACTIVATION_CASE: testCase, VSCR_ACTIVATION_ROOT: caseRoot, + ELECTRON_RUN_AS_NODE: '' }; + const launchArgs = [ + ...(testCase === 'no-folder' ? [] : [workspace]), + '--user-data-dir', profile, '--extensions-dir', extensions, + '--disable-renderer-backgrounding', '--disable-background-timer-throttling', + '--disable-backgrounding-occluded-windows', + ]; + const log = fs.createWriteStream(path.join(caseRoot, `${testCase}.log`)); + try { + if (testCase.startsWith('interactive-')) { + await new Promise((resolve, reject) => { + const child = require('node:child_process').spawn(executable, [...launchArgs, + '--no-sandbox', '--disable-gpu-sandbox', '--skip-welcome', '--skip-release-notes', '--disable-updates', + '--disable-workspace-trust', `--extensionDevelopmentPath=${repository}`, + `--extensionDevelopmentPath=${helper}`], { env: { ...process.env, ...env } }); + const timer = setTimeout(() => { child.kill(); reject(new Error('Restore window timed out')); }, 45000); + child.stdout.on('data', (data) => log.write(data)); + child.stderr.on('data', (data) => log.write(data)); + child.once('error', (error) => { clearTimeout(timer); reject(error); }); + child.once('exit', (code) => { + clearTimeout(timer); + if (code === 0) { resolve(); } + else { reject(new Error(`Restore window exited ${code}`)); } + }); + }); + const errorFile = path.join(caseRoot, `${testCase}.error`); + assert.ok(!fs.existsSync(errorFile), fs.existsSync(errorFile) && fs.readFileSync(errorFile, 'utf8')); + } else { + await runTests({ vscodeExecutablePath: executable, extensionDevelopmentPath: repository, + extensionTestsPath: __filename, extensionTestsEnv: env, launchArgs, stdout: log, stderr: log }); + } + } finally { await new Promise((resolve) => log.end(resolve)); } + reports.push(JSON.parse(fs.readFileSync(path.join(caseRoot, `${testCase}.json`), 'utf8'))); + } + console.log(JSON.stringify(reports, null, 2)); + success = true; + } finally { + if (success) { fs.rmSync(root, { recursive: true, force: true }); } + else { + const artifacts = path.join(repository, '.vscode-test', 'activation'); + fs.mkdirSync(artifacts, { recursive: true }); + for (const directory of fs.readdirSync(root, { withFileTypes: true })) { + if (!directory.isDirectory()) { continue; } + for (const file of fs.readdirSync(path.join(root, directory.name))) { + if (file.endsWith('.log')) { + fs.copyFileSync(path.join(root, directory.name, file), + path.join(artifacts, `${directory.name}-${file}`)); + } + } + } + console.error('Retained activation test profiles:', root, 'and logs:', artifacts); + } + } +} + +if (require.main === module) { + main().catch((error) => { console.error(error); process.exitCode = 1; }); +} From a0cc73527510bae46a66ac657e618776918ce916 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Tue, 17 Nov 2026 01:27:55 +0800 Subject: [PATCH 3/4] test: fix Windows activation launch and parallel setup timing --- R/tests/attach_sess.R | 24 +++++++++++++++------- package.json | 2 +- scripts/activation-environment.test.cjs | 27 +++++++++++++++++++++++++ scripts/test-activation.cjs | 14 +++++++++++-- 4 files changed, 57 insertions(+), 10 deletions(-) create mode 100644 scripts/activation-environment.test.cjs diff --git a/R/tests/attach_sess.R b/R/tests/attach_sess.R index 65466d2c8..b0db4c94b 100644 --- a/R/tests/attach_sess.R +++ b/R/tests/attach_sess.R @@ -51,6 +51,9 @@ writeLines( ) runner <- file.path(root, "run-case.R") +# Match production: the follower waits through the owner's consent, install and load. +# Source installation can take more than a minute on Windows runners. +parallel_setup_timeout <- 300 writeLines( c( "args <- commandArgs(TRUE)", @@ -370,9 +373,7 @@ writeLines( "} else if (mode %in% c('parallel_approve', 'parallel_decline', 'parallel_third',", " 'parallel_failure', 'parallel_retry')) {", " timeout <- 10", - # The follower budget covers the owner's whole source install, which can - # take well over 20 seconds on Windows runners. - " parallel_setup_timeout <- 60", + sprintf(" parallel_setup_timeout <- %d", parallel_setup_timeout), " if (mode == 'parallel_approve') {", " result <- attach_sess(timeout=timeout, setup_timeout=parallel_setup_timeout)", " stopifnot(identical(result, TRUE), 'sess' %in% loadedNamespaces())", @@ -466,7 +467,11 @@ r_binary <- file.path(R.home("bin"), if (.Platform$OS.type == "windows") "R.exe" r_literal <- function(value) encodeString(value, quote = "\"") read_child_logs <- function(paths) { read_log <- function(path) { - tryCatch(readLines(path, warn = FALSE), error = function(e) paste("could not read", path)) + # Windows can deny reads while a child still has its redirected stream open. + suppressWarnings(tryCatch( + readLines(path, warn = FALSE), + error = function(e) paste("could not read", path) + )) } c(read_log(paths$stdout), read_log(paths$stderr)) } @@ -898,16 +903,17 @@ start_parallel_child <- function(case_root, mode, role, result_file, install_hel wait_for_child <- function(paths, description) { # Must exceed the parallel follower's setup budget so its own diagnostic wins. - deadline <- Sys.time() + 90 + deadline <- Sys.time() + parallel_setup_timeout + 30 while (!file.exists(paths$result) && Sys.time() < deadline) { Sys.sleep(0.01) } - child_output <- read_child_logs(paths) if (!file.exists(paths$result)) { + child_output <- read_child_logs(paths) stop(paste(description, "timed out; child output:", paste(child_output, collapse = "\n"))) } result <- readLines(paths$result, warn = FALSE) if (!identical(result, "ok")) { + child_output <- read_child_logs(paths) stop(paste( description, "failed:", @@ -977,7 +983,11 @@ run_parallel_setup <- function(approve) { wait_for_file(follower_observed, 10, "follower observation of the held setup lock") if (approve) { - wait_for_file(description_visible, 60, "installed package metadata while owner holds lock") + wait_for_file( + description_visible, + parallel_setup_timeout - 30, + "installed package metadata while owner holds lock" + ) stopifnot(dir.exists(lock_path), file.exists(file.path(managed_library, "sess", "DESCRIPTION"))) stopifnot(!file.exists(load_log), !file.exists(ready_path)) file.create(install_release) diff --git a/package.json b/package.json index 4258ae059..8dee1d0db 100644 --- a/package.json +++ b/package.json @@ -2601,7 +2601,7 @@ "test": "pnpm run test:node && pnpm run test:extension", "test:node": "mocha \"out/test/node/**/*.test.js\" --config .mocharc.interactive.cjs", "test:extension": "vscode-test", - "test:activation": "node scripts/test-activation.cjs", + "test:activation": "node --test scripts/activation-environment.test.cjs && node scripts/test-activation.cjs", "lint": "oxlint src", "format": "oxfmt .", "format:check": "oxfmt --check .", diff --git a/scripts/activation-environment.test.cjs b/scripts/activation-environment.test.cjs new file mode 100644 index 000000000..8bdf90789 --- /dev/null +++ b/scripts/activation-environment.test.cjs @@ -0,0 +1,27 @@ +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +const { test } = require('node:test'); +const { clearElectronNodeMode } = require('./test-activation.cjs'); + +function childEnvironment(environment) { + const child = spawnSync(process.execPath, ['-e', ` + const flags = Object.keys(process.env).filter(key => key.toUpperCase() === 'ELECTRON_RUN_AS_NODE'); + process.stdout.write(JSON.stringify({ flags, marker: process.env.VSCR_ACTIVATION_MARKER })); + `], { env: environment, encoding: 'utf8' }); + assert.equal(child.status, 0, child.stderr); + return JSON.parse(child.stdout); +} + +test('an empty Electron Node-mode flag is still present in a spawned process', () => { + const environment = { ...process.env, ELECTRON_RUN_AS_NODE: '' }; + assert.equal(childEnvironment(environment).flags.length, 1); +}); + +test('activation launches remove inherited Electron Node mode and preserve other settings', () => { + for (const value of ['', '1']) { + const environment = { ...process.env, ELECTRON_RUN_AS_NODE: value, + electron_run_as_node: value, Electron_Run_As_Node: value, VSCR_ACTIVATION_MARKER: 'preserved' }; + clearElectronNodeMode(environment); + assert.deepEqual(childEnvironment(environment), { flags: [], marker: 'preserved' }); + } +}); diff --git a/scripts/test-activation.cjs b/scripts/test-activation.cjs index bc9b6687c..4acc7e2e2 100644 --- a/scripts/test-activation.cjs +++ b/scripts/test-activation.cjs @@ -14,6 +14,13 @@ const cases = [ ]; const pause = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); +function clearElectronNodeMode(environment) { + for (const key of Object.keys(environment)) { + if (key.toUpperCase() === 'ELECTRON_RUN_AS_NODE') { delete environment[key]; } + } +} +exports.clearElectronNodeMode = clearElectronNodeMode; + async function until(predicate, message) { const deadline = Date.now() + 15000; while (!predicate()) { @@ -170,6 +177,10 @@ exports.run = async (api) => { }; async function main() { + // Electron on Windows enters Node mode even when this variable is empty. + // runTests merges process.env itself, so remove it from our environment + // before either the test runner or ordinary restore windows inherit it. + clearElectronNodeMode(process.env); const { downloadAndUnzipVSCode, resolveCliArgsFromVSCodeExecutablePath, runTests } = require('@vscode/test-electron'); const { spawnSync } = require('node:child_process'); const executable = process.env.VSCR_ACTIVATION_VSCODE || await downloadAndUnzipVSCode(); @@ -247,8 +258,7 @@ exports.activate = async () => { if (testCase === 'r-notebook') { fs.writeFileSync(path.join(caseRoot, 'notebook.rnb'), JSON.stringify({ version: 1, metadata: {}, cells: [] })); } - const env = { VSCR_ACTIVATION_CASE: testCase, VSCR_ACTIVATION_ROOT: caseRoot, - ELECTRON_RUN_AS_NODE: '' }; + const env = { VSCR_ACTIVATION_CASE: testCase, VSCR_ACTIVATION_ROOT: caseRoot }; const launchArgs = [ ...(testCase === 'no-folder' ? [] : [workspace]), '--user-data-dir', profile, '--extensions-dir', extensions, From 9dfb20e28deaba14293f2923e90b6866d5c135b4 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Tue, 17 Nov 2026 07:20:33 +0800 Subject: [PATCH 4/4] test: verify persistent terminal reconnection after reload --- CONTRIBUTING.md | 8 ++- scripts/test-activation.cjs | 85 +++++++++++++++++++++--- website/docs/features/r-terminals.md | 10 ++- website/docs/features/session-watcher.md | 10 ++- 4 files changed, 99 insertions(+), 14 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4e80af132..00bca4111 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -119,8 +119,12 @@ and `pnpm run test:extension` to rerun either layer without rebuilding. Run `pnpm run test:activation` after compiling to check activation in fresh VS Code windows. It verifies that unrelated workspaces and Python Interactive windows keep vscode-R inactive, and that R files, commands, terminal profiles, -tasks, notebooks, and restored native R Interactive inputs activate it. Each -case uses temporary profiles without the normal suite's forced activation. +tasks, notebooks, and restored native R Interactive inputs activate it. It also +checks that a persistent R terminal retains its process and workspace across a +window reload, then reconnects after explicit R activation. This case needs R +and the `sess` Imports installed, and installs the bundled package into a +temporary library. Each case uses temporary profiles without the normal suite's +forced activation. `VSCR_ACTIVATION_VSCODE` selects an existing VS Code executable; otherwise the runner downloads current stable. `VSCR_ACTIVATION_CASES` selects a comma-separated subset of cases from `scripts/test-activation.cjs`. On headless Linux, use diff --git a/scripts/test-activation.cjs b/scripts/test-activation.cjs index 4acc7e2e2..56453bfe1 100644 --- a/scripts/test-activation.cjs +++ b/scripts/test-activation.cjs @@ -11,6 +11,7 @@ const cases = [ 'workspace', 'command', 'terminal-profile', 'task', 'r-notebook', 'interactive-create', 'interactive-restore', 'interactive-background-create', 'interactive-background-restore', + 'terminal-persistent-reload', ]; const pause = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); @@ -46,6 +47,7 @@ exports.run = async (api) => { const testCase = process.env.VSCR_ACTIVATION_CASE; const root = process.env.VSCR_ACTIVATION_ROOT; const extension = vscode.extensions.getExtension('REditorSupport.r'); + let terminalReload; assert.ok(extension, 'The development extension must be available'); // Give delayed startup activation and workspace searches time to run. The // normal suite's forced global activation would hide this regression. @@ -103,6 +105,52 @@ exports.run = async (api) => { vscode.window.terminals.forEach((terminal) => terminal.dispose()); break; } + case 'terminal-persistent-reload': { + const phaseFile = path.join(root, 'terminal-reload-state.json'); + const reloading = fs.existsSync(phaseFile); + if (!reloading) { + await within(vscode.commands.executeCommand('workbench.action.terminal.newWithProfile', + { config: { extensionIdentifier: 'REditorSupport.r', id: 'r.terminal-profile', title: 'R Terminal' } }), + 'Persistent R Terminal creation timed out'); + } + await until(() => vscode.window.terminals.length > 0, 'Persistent R Terminal was not restored'); + const terminal = vscode.window.terminals[0]; + const terminalPid = await within(terminal.processId, 'Restored terminal PID was not available'); + const stateFile = path.join(root, reloading ? 'terminal-after' : 'terminal-before'); + const rFile = JSON.stringify(stateFile.replace(/\\/g, '/')); + const rTemporary = JSON.stringify(`${stateFile}.pending`.replace(/\\/g, '/')); + terminal.sendText(`${reloading ? '' : '.vscode_r_activation_marker <- 42; '}` + + `writeLines(c(as.character(Sys.getpid()), get('.session_id', asNamespace('sess'))(), ` + + `as.character(.vscode_r_activation_marker)), ${rTemporary}); ` + + `stopifnot(file.rename(${rTemporary}, ${rFile}))`); + await until(() => fs.existsSync(stateFile), 'R terminal did not report its retained state'); + const [pid, sessionId, marker] = fs.readFileSync(stateFile, 'utf8').trim().split(/\r?\n/); + assert.equal(marker, '42', 'Window reload must retain the R workspace'); + if (!reloading) { + await until(() => extension.exports.session.getSessionReference(sessionId), + 'Initial R terminal sess attachment did not complete'); + fs.writeFileSync(phaseFile, JSON.stringify({ terminalPid, pid, sessionId, + connectionId: extension.exports.session.getSessionReference(sessionId).connectionId })); + return 'reload'; + } + const previous = JSON.parse(fs.readFileSync(phaseFile, 'utf8')); + assert.equal(terminalPid, previous.terminalPid, 'Window reload must retain the terminal process'); + assert.equal(pid, previous.pid, 'Window reload must retain the same R process'); + assert.equal(sessionId, previous.sessionId, 'The retained R process must keep its sess identity'); + assert.equal(extension.isActive, false, 'Restored terminal waits for explicit R activation'); + assert.ok(!vscode.workspace.textDocuments.some((document) => ['r', 'rmd'].includes(document.languageId)), + 'The restored terminal must not rely on an R source document'); + terminal.show(); + await until(() => vscode.window.activeTerminal === terminal, 'Restored R terminal did not receive focus'); + await within(vscode.commands.executeCommand('r.activateRSession'), 'Restored R terminal activation timed out'); + await until(() => extension.exports.session.getSessionReference(sessionId), + 'Explicit activation did not reconnect the retained R terminal'); + assert.notEqual(extension.exports.session.getSessionReference(sessionId).connectionId, previous.connectionId); + terminalReload = { terminalPid, rPid: Number(pid), retainedWorkspace: true, + inactiveAfterReload: true, reconnected: true }; + terminal.dispose(); + break; + } case 'task': { const tasks = await within(vscode.tasks.fetchTasks({ type: 'R' }), 'R task resolution timed out'); assert.ok(tasks.some((task) => task.name === 'Activation task' && task.execution), @@ -171,7 +219,7 @@ exports.run = async (api) => { throw new Error(`Unknown activation case: ${testCase}`); } } - const result = { case: testCase, vscode: vscode.version, active: extension.isActive }; + const result = { case: testCase, vscode: vscode.version, active: extension.isActive, ...terminalReload }; fs.writeFileSync(path.join(root, `${testCase}.json`), JSON.stringify(result)); console.log('Activation regression:', JSON.stringify(result)); }; @@ -207,10 +255,11 @@ async function main() { fs.writeFileSync(path.join(helper, 'index.cjs'), ` const vscode = require('vscode'); exports.activate = async () => { - try { await require(${JSON.stringify(__filename)}).run(vscode); } + let reload = false; + try { reload = await require(${JSON.stringify(__filename)}).run(vscode) === 'reload'; } catch (error) { require('node:fs').writeFileSync(require('node:path').join(process.env.VSCR_ACTIVATION_ROOT, process.env.VSCR_ACTIVATION_CASE + '.error'), error.stack || String(error)); } - finally { await vscode.commands.executeCommand('workbench.action.quit'); } + finally { await vscode.commands.executeCommand(reload ? 'workbench.action.reloadWindow' : 'workbench.action.quit'); } }; `); // Reuse the cached syntax dependency when available; clean CI installs only @@ -231,6 +280,7 @@ exports.activate = async () => { try { const reports = []; for (const testCase of selected) { + const persistentTerminal = testCase === 'terminal-persistent-reload'; const name = testCase.startsWith('interactive-background-') ? 'restore-background' : testCase.startsWith('interactive-') ? 'restore' : testCase; const caseRoot = path.join(root, name); @@ -239,10 +289,12 @@ exports.activate = async () => { 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': false, 'r.plot.backend': 'native', + 'r.lsp.enabled': false, 'r.sessionWatcher': persistentTerminal, 'r.plot.backend': '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': false, + 'window.restoreWindows': 'all', 'terminal.integrated.enablePersistentSessions': persistentTerminal, + ...(persistentTerminal ? { 'r.session.emulateRStudioAPI': false, + 'r.consoleArgs': ['--no-save', '--no-restore', '--no-site-file'] } : {}), })); fs.writeFileSync(path.join(workspace, 'index.js'), 'const unrelated = true;\n'); if (testCase === 'workspace') { @@ -259,6 +311,22 @@ exports.activate = async () => { fs.writeFileSync(path.join(caseRoot, 'notebook.rnb'), JSON.stringify({ version: 1, metadata: {}, cells: [] })); } const env = { VSCR_ACTIVATION_CASE: testCase, VSCR_ACTIVATION_ROOT: caseRoot }; + if (persistentTerminal) { + 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.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}`); + env.R_LIBS_USER = [library, ...fs.readFileSync(librariesFile, 'utf8').trim().split(/\r?\n/)].join(path.delimiter); + env.R_PROFILE_USER = emptyProfile; + } const launchArgs = [ ...(testCase === 'no-folder' ? [] : [workspace]), '--user-data-dir', profile, '--extensions-dir', extensions, @@ -267,17 +335,18 @@ exports.activate = async () => { ]; const log = fs.createWriteStream(path.join(caseRoot, `${testCase}.log`)); try { - if (testCase.startsWith('interactive-')) { + if (testCase.startsWith('interactive-') || persistentTerminal) { await new Promise((resolve, reject) => { const child = require('node:child_process').spawn(executable, [...launchArgs, '--no-sandbox', '--disable-gpu-sandbox', '--skip-welcome', '--skip-release-notes', '--disable-updates', '--disable-workspace-trust', `--extensionDevelopmentPath=${repository}`, `--extensionDevelopmentPath=${helper}`], { env: { ...process.env, ...env } }); - const timer = setTimeout(() => { child.kill(); reject(new Error('Restore window timed out')); }, 45000); + const timer = setTimeout(() => { child.kill(); reject(new Error('Restore window timed out')); }, + persistentTerminal ? 90000 : 45000); child.stdout.on('data', (data) => log.write(data)); child.stderr.on('data', (data) => log.write(data)); child.once('error', (error) => { clearTimeout(timer); reject(error); }); - child.once('exit', (code) => { + child.once('close', (code) => { clearTimeout(timer); if (code === 0) { resolve(); } else { reject(new Error(`Restore window exited ${code}`)); } diff --git a/website/docs/features/r-terminals.md b/website/docs/features/r-terminals.md index e7742c1bc..7292fedf7 100644 --- a/website/docs/features/r-terminals.md +++ b/website/docs/features/r-terminals.md @@ -17,8 +17,14 @@ For an alternative R console, see [arf](https://github.com/eitsupi/arf). If the R session watcher is enabled, then it will attach to the R session whenever a new R terminal is created. The status of the session watcher is shown -in the status bar like below. Managed terminals reconnect automatically after a -VS Code window reload. +in the status bar like below. + +Managed terminals reconnect automatically after a VS Code window reload once +vscode-R activates. VS Code can restore an existing terminal without activating +vscode-R. In a workspace with no R files or visible R Interactive tab, +reconnection waits until you use R. Open an R file, or focus the restored R +terminal and run **R: Activate R Session**, to reconnect it. This reconnects the +R process preserved across the window reload without restarting it. ![R session status bar item](/images/r-status-bar-item.png) diff --git a/website/docs/features/session-watcher.md b/website/docs/features/session-watcher.md index fd7edc100..be5172cd8 100644 --- a/website/docs/features/session-watcher.md +++ b/website/docs/features/session-watcher.md @@ -12,8 +12,14 @@ session automatically and shows the attached R process in the status bar. vscode-R 3.0.0 uses the bundled `sess` R package for this connection. If the package is missing or older than the extension, vscode-R asks whether it may -install or update the bundled version. Managed terminals can reconnect after a -VS Code window reload. +install or update the bundled version. Managed terminals reconnect after a +VS Code window reload once vscode-R activates. + +VS Code can restore an existing terminal while vscode-R remains inactive. In a +workspace with no R files or visible R Interactive tab, reconnection waits until +you use R. Open an R file, or focus the restored R terminal and run +**R: Activate R Session**, to reconnect it. The R process preserved across the +window reload is not restarted by reconnection. ## External and self-managed R sessions