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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2662,8 +2662,8 @@
],
"capabilities": {
"untrustedWorkspaces": {
"supported": "limited",
"description": "R execution and persistent session connections require a trusted workspace.",
"supported": false,
"description": "Trust the workspace to enable R processes and session connections. R syntax highlighting is available in Restricted Mode.",
"restrictedConfigurations": [
"r.interactive.nodePath",
"r.interactive.arfPath",
Expand Down
77 changes: 66 additions & 11 deletions scripts/test-activation.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ 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',
'workspace', 'restricted-workspace', 'command', 'terminal-profile', 'task', 'r-notebook',
'interactive-create', 'interactive-restore',
'interactive-background-create', 'interactive-background-restore',
'terminal-persistent-reload',
Expand Down Expand Up @@ -101,18 +101,58 @@ function terminalLayoutState(logs, pid) {
return state;
}

// Count real launches synchronously so a slow R startup cannot hide an eager
// Help process. The two page requests share the server while its port is pending.
async function checkRDocumentActivation(vscode, extension, restricted) {
assert.equal(vscode.workspace.isTrusted, !restricted);
assert.ok(!extension?.isActive, 'R activated before opening the document');
const cp = require('node:child_process');
const originalSpawn = cp.spawn;
const rProcesses = [];
cp.spawn = function (command, args, ...options) {
if (/^(r|rterm|rscript)(\.exe)?$/i.test(path.basename(command))) {
rProcesses.push(args);
}
return originalSpawn.call(this, command, args, ...options);
};
try {
const document = await vscode.workspace.openTextDocument({ language: 'r', content: '1 + 1' });
await vscode.window.showTextDocument(document);
assert.ok(vscode.extensions.getExtension('REditorSupport.r-syntax'), 'R syntax is available');
if (restricted) {
await pause(2000);
assert.ok(!extension?.isActive, 'R runtime activated in Restricted Mode');
assert.deepEqual(rProcesses, []);
} else {
await until(() => extension.isActive, 'R document did not activate the extension');
assert.deepEqual(rProcesses, [], 'Opening a plain R file launched R with the LSP off');
const help = extension.exports.helpPanel;
const pages = await Promise.all(['mean', 'sum'].map((topic) =>
help.getHelpFileForPath(`library/base/html/${topic}.html`)));
assert.ok(pages.every((page) => page?.html), 'Both help pages loaded');
assert.equal(rProcesses.length, 1, 'Concurrent Help requests should share one R process');
assert.ok(rProcesses[0].some((arg) => path.basename(arg) === 'helpServer.R'));
}
} finally {
cp.spawn = originalSpawn;
}
}

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');
let terminalReload;
assert.ok(extension, 'The development extension must be available');
const restricted = testCase === 'restricted-workspace';
if (!restricted) { assert.ok(extension, 'The R 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') {
if (testCase === 'language-r' || restricted) {
await checkRDocumentActivation(vscode, extension, restricted);
} else 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');
Expand Down Expand Up @@ -141,12 +181,10 @@ exports.run = async (api) => {
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: '' });
const document = await vscode.workspace.openTextDocument({ language: 'rmd', content: '' });
await vscode.window.showTextDocument(document);
await until(() => extension.isActive, `${language} document did not activate R`);
await until(() => extension.isActive, 'R Markdown document did not activate R');
break;
}
case 'command':
Expand Down Expand Up @@ -341,7 +379,7 @@ exports.run = async (api) => {
throw new Error(`Unknown activation case: ${testCase}`);
}
}
const result = { case: testCase, vscode: vscode.version, active: extension.isActive, ...terminalReload };
const result = { case: testCase, vscode: vscode.version, active: extension?.isActive ?? false, ...terminalReload };
fs.writeFileSync(path.join(root, `${testCase}.json`), JSON.stringify(result));
console.log('Activation regression:', JSON.stringify(result));
};
Expand Down Expand Up @@ -373,6 +411,7 @@ async function main() {
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',
capabilities: { untrustedWorkspaces: { supported: true } },
}));
fs.writeFileSync(path.join(helper, 'index.cjs'), `
const vscode = require('vscode');
Expand All @@ -398,6 +437,17 @@ exports.activate = async () => {
{ stdio: 'inherit', shell: process.platform === 'win32' });
assert.equal(installed.status, 0, 'Could not install the R syntax dependency');
}
// VS Code force-enables development extensions. Both trust cases use the same
// installed runtime and syntax package. Let VS Code build the index for this
// directory; the shared extensions.json could already list only r-syntax.
const installedExtensions = path.join(root, 'installed-extensions');
if (selected.includes('language-r') || selected.includes('restricted-workspace')) {
const syntaxPackage = fs.readdirSync(extensions).find((name) => name.startsWith('reditorsupport.r-syntax-'));
assert.ok(syntaxPackage, 'The R syntax package must be installed');
fs.mkdirSync(installedExtensions);
fs.cpSync(path.join(extensions, syntaxPackage), path.join(installedExtensions, syntaxPackage), { recursive: true });
fs.symlinkSync(repository, path.join(installedExtensions, 'reditorsupport.r-' + require('../package.json').version), 'junction');
}
let success = false;
try {
const reports = [];
Expand All @@ -408,6 +458,8 @@ exports.activate = async () => {
const caseRoot = path.join(root, name);
const workspace = path.join(caseRoot, 'workspace');
const profile = path.join(caseRoot, 'profile');
const restricted = testCase === 'restricted-workspace';
const installedRuntime = restricted || testCase === 'language-r';
fs.mkdirSync(workspace, { recursive: true });
fs.mkdirSync(path.join(profile, 'User'), { recursive: true });
fs.writeFileSync(path.join(profile, 'User', 'settings.json'), JSON.stringify({
Expand All @@ -417,6 +469,8 @@ exports.activate = async () => {
'window.restoreWindows': 'all', 'terminal.integrated.enablePersistentSessions': persistentTerminal,
...(persistentTerminal ? { 'r.session.emulateRStudioAPI': false,
'r.consoleArgs': ['--no-save', '--no-restore', '--no-site-file'] } : {}),
...(restricted ? { 'security.workspace.trust.startupPrompt': 'never', 'r.lsp.enabled': true,
'r.sessionWatcher': true } : {}),
}));
fs.writeFileSync(path.join(workspace, 'index.js'), 'const unrelated = true;\n');
if (testCase === 'workspace') {
Expand Down Expand Up @@ -451,19 +505,20 @@ exports.activate = async () => {
}
const launchArgs = [
...(testCase === 'no-folder' ? [] : [workspace]),
'--user-data-dir', profile, '--extensions-dir', extensions,
'--user-data-dir', profile, '--extensions-dir', installedRuntime ? installedExtensions : extensions,
'--disable-renderer-backgrounding', '--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows',
// Pty host trace logs show whether reload-time input reached R.
...(persistentTerminal ? ['--log', 'trace'] : []),
];
const log = fs.createWriteStream(path.join(caseRoot, `${testCase}.log`));
try {
if (testCase.startsWith('interactive-') || persistentTerminal) {
if (testCase.startsWith('interactive-') || persistentTerminal || installedRuntime) {
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}`,
...(restricted ? [] : ['--disable-workspace-trust']),
...(installedRuntime ? [] : [`--extensionDevelopmentPath=${repository}`]),
`--extensionDevelopmentPath=${helper}`], { env: { ...process.env, ...env } });
const timer = setTimeout(() => { child.kill(); reject(new Error('Restore window timed out')); },
persistentTerminal ? 90000 : 45000);
Expand Down
26 changes: 18 additions & 8 deletions src/helpViewer/helpProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ type ChildProcessWithPort = DisposableProcess & {

// Class to forward help requests to a backgorund R instance that is running a help server
export class HelpProvider {
private cp: ChildProcessWithPort;
private cp?: ChildProcessWithPort;
private disposed = false;
private readonly rPath: string;
private readonly cwd?: string;
private readonly pkgListener?: () => void;
Expand All @@ -30,16 +31,23 @@ export class HelpProvider {
this.rPath = options.rPath || 'R';
this.cwd = options.cwd;
this.pkgListener = options.pkgListener;
this.cp = this.launchRHelpServer();
}

public async refresh(): Promise<void> {
this.cp.dispose();
this.cp = this.launchRHelpServer();
await this.cp.port;
this.cp?.dispose();
this.cp = undefined;
await this.start()?.port;
}

public launchRHelpServer(): ChildProcessWithPort {
// The server also watches installed packages for callers using cached Help metadata.
public start(): ChildProcessWithPort | undefined {
if (!this.disposed) {
this.cp ??= this.launchRHelpServer();
}
return this.cp;
}

private launchRHelpServer(): ChildProcessWithPort {
const lim = '---vsc---';
const portRegex = new RegExp(`.*${lim}(.*)${lim}.*`, 'ms');

Expand Down Expand Up @@ -108,7 +116,7 @@ export class HelpProvider {
public async getHelpFileFromRequestPath(
requestPath: string,
): Promise<undefined | rHelp.HelpFile> {
const port = await this.cp?.port;
const port = await this.start()?.port;
if (!port || typeof port !== 'number') {
return undefined;
}
Expand Down Expand Up @@ -145,7 +153,9 @@ export class HelpProvider {
}

dispose(): void {
this.cp.dispose();
this.disposed = true;
this.cp?.dispose();
this.cp = undefined;
}
}

Expand Down
8 changes: 7 additions & 1 deletion src/helpViewer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ export class RHelp implements api.HelpPanel, vscode.WebviewPanelSerializer<strin
readonly cwd?: string;

// Provides the content of help pages:
readonly helpProvider: HelpProvider;
private readonly helpProvider: HelpProvider;

// Provides a list of aliases:
readonly aliasProvider: AliasProvider;
Expand Down Expand Up @@ -501,8 +501,14 @@ export class RHelp implements api.HelpPanel, vscode.WebviewPanelSerializer<strin
return false;
}

// Cached aliases and package indexes still need invalidating when installed packages change.
public watchPackageChanges(): void {
this.helpProvider.start();
}

// helper function to get aliases from aliasprovider
private async getAllAliases(includePreview: boolean = false): Promise<Alias[] | undefined> {
this.watchPackageChanges();
const aliases = await doWithProgress(
() => this.aliasProvider.getAllAliases(),
vscode.ProgressLocation.Window,
Expand Down
1 change: 1 addition & 0 deletions src/helpViewer/packages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,7 @@ export class PackageManager {
// retrieve and parse an index file
// (either list of all packages, or documentation entries of a package)
private async getParsedIndexFile(path: string): Promise<IndexEntry[] | undefined> {
this.rHelp.watchPackageChanges();
let indexItems = this.getCachedIndexFile(path);

// only read and parse file if not cached yet
Expand Down
23 changes: 21 additions & 2 deletions src/test/suite/helpPackages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,15 @@ const index = (name: string): HelpFile => ({
html: `<table><tr><td><a href="${name}.html">${name}</a></td><td>Description</td></tr></table>`,
});

function manager(state: Memento, getHelpFileForPath: () => Promise<HelpFile | undefined>) {
function manager(
state: Memento,
getHelpFileForPath: () => Promise<HelpFile | undefined>,
watchPackageChanges: () => void = () => undefined,
) {
return new PackageManager({
rPath: 'R',
persistentState: state,
rHelp: { getHelpFileForPath } as unknown as RHelp,
rHelp: { getHelpFileForPath, watchPackageChanges } as unknown as RHelp,
});
}

Expand Down Expand Up @@ -79,6 +83,21 @@ suite('Help package state and index requests', () => {
assert.strictEqual(requests, 1);
});

test('reading a persisted package index starts watching for package changes', async () => {
const state = jsonState();
await manager(state, () => Promise.resolve(index('cached'))).getTopics('example');
let watching = false;
const packages = manager(
state,
() => assert.fail('Expected the cached index'),
() => {
watching = true;
},
);
assert.ok((await packages.getTopics('example'))?.some((topic) => topic.name === 'cached'));
assert.ok(watching);
});

test('clearing the cache prevents an older pending fetch from restoring stale topics', async () => {
let finish!: (file: HelpFile) => void;
const oldFile = new Promise<HelpFile>((resolve) => {
Expand Down
Loading