diff --git a/R/languageServer.R b/R/languageServer.R index 013bb7319..4cf76b16c 100644 --- a/R/languageServer.R +++ b/R/languageServer.R @@ -7,6 +7,13 @@ if (nzchar(add_lib_paths)) { .libPaths(.paths) } +# A native Interactive session's package resolution order precedes the +# language-server process defaults, including a different default user library. +session_lib_paths <- Sys.getenv("VSCR_LSP_SESSION_LIB_PATHS") +if (nzchar(session_lib_paths)) { + .paths <- c(strsplit(session_lib_paths, "\n", fixed = TRUE)[[1L]], .paths) +} + use_renv_lib_path <- Sys.getenv("VSCR_USE_RENV_LIB_PATH") use_renv_lib_path <- if (nzchar(use_renv_lib_path)) as.logical(use_renv_lib_path) else FALSE if (use_renv_lib_path) { diff --git a/package.json b/package.json index 07a808fc6..a1baed9ef 100644 --- a/package.json +++ b/package.json @@ -1969,7 +1969,7 @@ ], "default": "auto", "scope": "resource", - "description": "Select the language server runtime. The webR integration is experimental. Its implementation and behavior may change substantially between releases." + "description": "Select the language server runtime for source editors. R Interactive inputs and cells follow their session provider. The webR integration is experimental. Its implementation and behavior may change substantially between releases." }, "r.lsp.enabled": { "type": "boolean", diff --git a/sess/R/interactive.R b/sess/R/interactive.R index 1c06367e4..902ec60b8 100644 --- a/sess/R/interactive.R +++ b/sess/R/interactive.R @@ -255,7 +255,7 @@ interactive_start <- function(config, managed = FALSE) { list( pid = Sys.getpid(), version = R.version.string, - rPath = file.path(R.home("bin"), "R"), + rPath = file.path(R.home("bin"), if (.Platform$OS.type == "windows") "R.exe" else "R"), libraryPaths = as.list(.libPaths()), sessionId = .session_id(), nativeConsole = FALSE diff --git a/src/interactive/executable.ts b/src/interactive/executable.ts index 0da7eac63..15be63a42 100644 --- a/src/interactive/executable.ts +++ b/src/interactive/executable.ts @@ -35,7 +35,15 @@ export function resolveExecutable( }; if (command.includes('/') || command.includes('\\')) { const file = path.resolve(directory, command); - return executable(file) ? file : undefined; + if (executable(file)) { + return file; + } + // Earlier Interactive sessions report R.home("bin")/R on Windows. + // Resolve the sibling executable so reconnection uses that exact R installation. + if (process.platform === 'win32' && !path.extname(file) && executable(file + '.exe')) { + return file + '.exe'; + } + return undefined; } // Resolve relative PATH entries against the session's cwd, as spawn does. const searchPath = pathValue diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 9282de1c3..86e6697ed 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1813,8 +1813,7 @@ export class InteractiveManager target.pid = String(manifest.rPid ?? ''); target.rVer = manifest.rVersion ?? ''; target.processExited = manifest.status === 'exited'; - target.rPath = manifest.rPath; - target.libraryPaths = manifest.libraryPaths; + session.updateSessionLanguageEnvironment(target, manifest.rPath, manifest.libraryPaths); target.label = manifest.label; target.execute = async (code) => { const view = [...this.views.values()].find((item) => item.target === target); @@ -1924,8 +1923,11 @@ export class InteractiveManager view.target.pid = String(snapshot.manifest.rPid ?? ''); view.target.rVer = snapshot.manifest.rVersion ?? ''; view.target.processExited = snapshot.manifest.status === 'exited'; - view.target.rPath = snapshot.manifest.rPath; - view.target.libraryPaths = snapshot.manifest.libraryPaths; + session.updateSessionLanguageEnvironment( + view.target, + snapshot.manifest.rPath, + snapshot.manifest.libraryPaths, + ); view.base = snapshot.manifest.assetBase ? ( await vscode.env.asExternalUri(vscode.Uri.parse(snapshot.manifest.assetBase)) @@ -2178,12 +2180,15 @@ export class InteractiveManager } if (typeof event.data.rPath === 'string') { view.client.manifest.rPath = event.data.rPath; - view.target.rPath = event.data.rPath; } if (Array.isArray(event.data.libraryPaths)) { view.client.manifest.libraryPaths = event.data.libraryPaths.map(String); - view.target.libraryPaths = view.client.manifest.libraryPaths; } + session.updateSessionLanguageEnvironment( + view.target, + view.client.manifest.rPath, + view.client.manifest.libraryPaths, + ); if (typeof event.data.runtimeSessionId === 'string') { view.client.manifest.runtimeSessionId = event.data.runtimeSessionId; } @@ -3564,8 +3569,11 @@ export class InteractiveManager target.pid = String(snapshot.manifest.rPid ?? ''); target.rVer = snapshot.manifest.rVersion ?? ''; target.processExited = snapshot.manifest.status === 'exited'; - target.rPath = snapshot.manifest.rPath; - target.libraryPaths = snapshot.manifest.libraryPaths; + session.updateSessionLanguageEnvironment( + target, + snapshot.manifest.rPath, + snapshot.manifest.libraryPaths, + ); view.prompts.clear(); if (snapshot.workspace) { target.workspaceData = snapshot.workspace as unknown as session.WorkspaceData; diff --git a/src/languageService.ts b/src/languageService.ts index c131d32d6..0f9946474 100644 --- a/src/languageService.ts +++ b/src/languageService.ts @@ -41,10 +41,18 @@ import { connectTcpLanguageServer } from './languageServerTransport'; import { CancellableLanguageClient } from './languageServerClient'; import { withRpcCancellation } from './nativeRpc'; import { prepareNodeWebR } from './webr/nodeRuntime'; +import { resolveExecutable } from './interactive/executable'; import { cachedWebRAssets } from './webr/assetCache'; import { createWebRLanguageSession } from './webr/languageSession'; import { createWebRMessageTransports } from './webr/messageTransports'; +function isOrdinaryRDocument(document: TextDocument): boolean { + return ( + (document.uri.scheme === 'file' || document.uri.scheme === 'untitled') && + (document.languageId === 'r' || document.languageId === 'rmd') + ); +} + export class LanguageService implements Disposable { private readonly clients: Map = new Map(); private readonly initSet: Set = new Set(); @@ -53,6 +61,7 @@ export class LanguageService implements Disposable { private readonly sessionSignatures = new SessionSignatureHelpProvider(); private readonly clientUpdates = new Map>(); private readonly listeners: Disposable[] = []; + private documentListenersStarted = false; private startup: Promise; private readonly startupCancellation = new AbortController(); private readonly startingClients = new Set(); @@ -78,7 +87,7 @@ export class LanguageService implements Disposable { return; } const nextDocument = workspace.onDidOpenTextDocument((doc) => { - if (doc.languageId === 'r' || doc.languageId === 'rmd') { + if (isOrdinaryRDocument(doc)) { nextDocument.dispose(); this.startup = this.startWithRetry(); } @@ -242,22 +251,38 @@ export class LanguageService implements Disposable { const resourceConfig = config(resource); const debug = this.config.get('lsp.debug'); const useRenvLibPath = this.config.get('useRenvLibPath') ?? false; - const policy = resourceConfig.get('lsp.runtime', 'auto'); - // Interactive input/cell clients follow their bound runtime in auto mode. - // Ordinary source files keep their shared workspace language server. - const rPath = - policy === 'webR' || (policy === 'auto' && target?.interactiveProvider === 'webr') - ? '' - : target?.rPath || - (await withRpcCancellation( - () => getRpath(false, resource, policy === 'native'), - this.startupCancellation.signal, - )) || - ''; + const provider = virtualOnly ? target?.interactiveProvider : undefined; + const policy = provider + ? provider === 'webr' + ? 'webR' + : 'native' + : resourceConfig.get('lsp.runtime', 'auto'); + let rPath = ''; + if (policy !== 'webR') { + rPath = + (provider && target?.rPath + ? resolveExecutable(target.rPath, cwd) + : await withRpcCancellation( + () => + getRpath( + false, + resource, + policy === 'native' && + !provider && + workspace.textDocuments.some(isOrdinaryRDocument), + ), + this.startupCancellation.signal, + )) ?? ''; + } if (this.disposed) { throw new Error('The R language service is shutting down.'); } if (!rPath && policy === 'native') { + if (provider) { + throw new Error( + `Cannot start the R language server for the ${provider} Interactive session: native R executable ${target?.rPath ?? 'not found'}.`, + ); + } this.outputChannel.appendLine( `Skipping the R language server in ${cwd} because no R executable was found.`, ); @@ -271,7 +296,8 @@ export class LanguageService implements Disposable { env.VSCR_LSP_DEBUG = debug ? 'TRUE' : 'FALSE'; env.VSCR_LSP_VIRTUAL_DOCUMENTS = virtualOnly ? 'TRUE' : 'FALSE'; env.VSCR_LSP_SYNTHETIC_WORKSPACE = syntheticWorkspace ? 'TRUE' : 'FALSE'; - env.VSCR_LIB_PATHS = target?.libraryPaths?.join('\n') ?? getRLibPaths(); + env.VSCR_LIB_PATHS = target?.libraryPaths ? '' : getRLibPaths(); + env.VSCR_LSP_SESSION_LIB_PATHS = target?.libraryPaths?.join('\n') ?? ''; env.VSCR_USE_RENV_LIB_PATH = useRenvLibPath ? 'TRUE' : 'FALSE'; const lang = this.config.get('lsp.lang'); @@ -427,7 +453,7 @@ export class LanguageService implements Disposable { 'r', 'R Language Server (webR)', async () => { - await this.waitForRDocument(client.startupSignal); + await this.waitForRDocument(client.startupSignal, virtualOnly); const baseUrl = await withRpcCancellation( () => prepareNodeWebR(extensionContext.globalStorageUri.fsPath), client.startupSignal, @@ -484,8 +510,15 @@ export class LanguageService implements Disposable { } } - private async waitForRDocument(signal: AbortSignal): Promise { - const isR = (doc: TextDocument) => doc.languageId === 'r' || doc.languageId === 'rmd'; + private async waitForRDocument(signal: AbortSignal, virtualOnly: boolean): Promise { + // A native Interactive notebook must not wake a separate desktop webR + // worker merely because webR was selected for ordinary source files. + const isR = virtualOnly + ? (doc: TextDocument) => + (doc.uri.scheme === 'vscode-interactive-input' || + doc.uri.scheme === 'vscode-notebook-cell') && + (doc.languageId === 'r' || doc.languageId === 'rmd') + : isOrdinaryRDocument; if (workspace.textDocuments.some(isR)) { return; } @@ -554,7 +587,13 @@ export class LanguageService implements Disposable { } private startMultiLanguageService(virtualOnly = false): void { - const clientTargets = new Map(); + if (this.documentListenersStarted) { + return; + } + this.documentListenersStarted = true; + // Record the owner used to start each virtual client. A queued ordinary + // open may reuse that client after the document has acquired a new owner. + const clientTargets = new Map(); const didOpenTextDocument = async (document: TextDocument) => { if ( virtualOnly && @@ -574,7 +613,15 @@ export class LanguageService implements Disposable { return; } - const target = boundSessionForDocument(document.uri); + const target = + document.uri.scheme === 'vscode-interactive-input' || + document.uri.scheme === 'vscode-notebook-cell' + ? boundSessionForDocument(document.uri) + : undefined; + const owner = target && { + session: target, + revision: target.languageEnvironmentRevision, + }; const folder = workspace.getWorkspaceFolder( target ? Uri.file(target.workingDir) : document.uri, ); @@ -598,8 +645,8 @@ export class LanguageService implements Disposable { folder?.uri ?? document.uri, target, ); - if (this.clients.has(key)) { - clientTargets.set(key, target); + if (owner && this.clients.has(key)) { + clientTargets.set(key, owner); } } return; @@ -625,8 +672,8 @@ export class LanguageService implements Disposable { folder?.uri ?? document.uri, target, ); - if (this.clients.has(key)) { - clientTargets.set(key, target); + if (owner && this.clients.has(key)) { + clientTargets.set(key, owner); } } return; @@ -761,16 +808,20 @@ export class LanguageService implements Disposable { const target = boundSessionForDocument(document.uri); // Rebinding retained cells can report the same notebook owner // repeatedly. Restart its shared server only once per owner. - if (restart && clientTargets.get(key) !== target) { + const owner = clientTargets.get(key); + if ( + restart && + (owner?.session !== target || + owner?.revision !== target?.languageEnvironmentRevision) + ) { const client = this.clients.get(key); this.clients.delete(key); + clientTargets.delete(key); this.initSet.delete(key); if (client) { await this.stopClient(client); } } - // A reused client still belongs to its original owner. Only - // creating the client above establishes a new binding. await didOpenTextDocument(document); } catch (error) { this.outputChannel.appendLine( @@ -826,6 +877,9 @@ export class LanguageService implements Disposable { if (useMultiServer) { this.startMultiLanguageService(); } else { + // A workspace runtime can be unavailable or take time to download. + // Bound Interactive clients already know which runtime they need. + this.startMultiLanguageService(true); const documentSelector: DocumentFilter[] = [ { scheme: 'file', language: 'r' }, { scheme: 'file', language: 'rmd' }, @@ -848,7 +902,6 @@ export class LanguageService implements Disposable { if (client) { this.clients.set('global', client); } - this.startMultiLanguageService(true); } } diff --git a/src/session.ts b/src/session.ts index 30a79d92c..d547327aa 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1,5 +1,6 @@ 'use strict'; +import { isDeepStrictEqual } from 'node:util'; import * as fs from 'node:fs'; import * as fsp from 'node:fs/promises'; import { pathExists, readJson } from './fileSystem'; @@ -133,6 +134,7 @@ export class Session { public rPath?: string; public libraryPaths?: string[]; public interactiveProvider?: ProviderKind; + public languageEnvironmentRevision = 0; public requester?: (data: Record) => Promise; public connectionId?: string; public attachmentId?: string; @@ -309,6 +311,21 @@ export function unbindSessionDocument(uri: Uri): void { } } +/** Restart bound virtual clients if the runtime reports a new executable or library order. */ +export function updateSessionLanguageEnvironment( + target: Session, + rPath: string | undefined, + libraryPaths: string[] | undefined, +): void { + if (target.rPath === rPath && isDeepStrictEqual(target.libraryPaths, libraryPaths)) { + return; + } + target.rPath = rPath; + target.libraryPaths = libraryPaths; + target.languageEnvironmentRevision++; + retargetDocuments(target, target); +} + /** Let per-notebook language clients reselect their runtime after restart or detach. */ function retargetDocuments(previous: Session, next?: Session): void { const changed = new Set(); diff --git a/src/test/node/interactiveRuntime.test.ts b/src/test/node/interactiveRuntime.test.ts index 5d49e18ae..b82755832 100644 --- a/src/test/node/interactiveRuntime.test.ts +++ b/src/test/node/interactiveRuntime.test.ts @@ -296,6 +296,12 @@ suite('Interactive real R runtime', function () { } }); + test('reports the executable of the running R installation in its ready metadata', () => { + const executable = client.manifest.rPath; + assert.ok(executable && path.isAbsolute(executable)); + assert.ok(fs.statSync(executable).isFile(), executable); + }); + test('evaluates CRLF editor code while retaining its original text in history', async () => { const code = 'crlf_value <- 41\r\ncrlf_value + 1\r\n'; const id = await submit(code); diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index befe6639e..ea46d88e1 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -2298,6 +2298,9 @@ suite('Interactive VS Code integration', function () { ); const end = document.positionAt(document.getText().length); editor.selection = new vscode.Selection(end, end); + // The type command targets keyboard focus, which may have moved + // while the client registered its formatting provider. + await vscode.commands.executeCommand('interactive.input.focus'); await vscode.commands.executeCommand('type', { text: ch }); await until( () => document.getText() === expected, diff --git a/src/test/suite/languageService.test.ts b/src/test/suite/languageService.test.ts index f34a4b779..5bd7d7499 100644 --- a/src/test/suite/languageService.test.ts +++ b/src/test/suite/languageService.test.ts @@ -21,6 +21,7 @@ import { CancellableLanguageClient } from '../../languageServerClient'; import * as util from '../../util'; import { bindSessionDocument, + updateSessionLanguageEnvironment, registerSessionTransport, replaceSessionTransport, unregisterSessionTransport, @@ -129,7 +130,7 @@ suite('Language service startup lifecycle', () => { const service = new LanguageService(); await service.dispose(); sinon.assert.calledWithMatch(appendLine, 'Failed to start language server:'); - sinon.assert.notCalled(register); + sinon.assert.calledOnceWithExactly(register, true); }); test('disposal waits for every client when one stop fails', async () => { @@ -185,7 +186,7 @@ suite('Language service startup lifecycle', () => { finish({ stop } as unknown as LanguageClient); await disposal; sinon.assert.calledOnce(stop); - sinon.assert.notCalled(register); + sinon.assert.calledOnceWithExactly(register, true); }); test('disposal cancels TCP startup while R remains alive without connecting', async () => { @@ -212,7 +213,7 @@ suite('Language service startup lifecycle', () => { await listening; await service.dispose(); sinon.assert.calledOnce(disposeChild); - sinon.assert.notCalled(register); + sinon.assert.calledOnceWithExactly(register, true); }); test('a missing package still prompts for installation without stopping a starting client', () => { @@ -377,8 +378,156 @@ suite('Language service startup lifecycle', () => { }); suite('Language service for bound Interactive documents', () => { + test('keeps an ordinary bound source in its own workspace with multiServer enabled', async () => { + const sandbox = sinon.createSandbox(); + const a = vscode.Uri.file(path.join(os.tmpdir(), 'workspace-a')); + const b = vscode.Uri.file(path.join(os.tmpdir(), 'workspace-b')); + const source = { + uri: vscode.Uri.joinPath(a, 'helper.R'), + languageId: 'r', + isClosed: false, + } as vscode.TextDocument; + sandbox.stub(vscode.workspace, 'getConfiguration').returns({ + get: (key: string) => key === 'lsp.multiServer', + } as unknown as vscode.WorkspaceConfiguration); + sandbox.stub(vscode.workspace, 'textDocuments').get(() => [source]); + sandbox.stub(vscode.workspace, 'getWorkspaceFolder').callsFake((uri) => { + const root = uri.fsPath.startsWith(a.fsPath) ? a : b; + return { uri: root, name: path.basename(root.fsPath), index: 0 }; + }); + const target = registerSessionTransport( + 'cross-folder-run', + 'host', + b.fsPath, + () => Promise.resolve({}), + 'webr', + ); + bindSessionDocument(source.uri, target); + const start = sandbox + .stub( + LanguageService.prototype as unknown as { + createClient: ( + selector: unknown[], + cwd: string, + folder: vscode.WorkspaceFolder, + ) => Promise; + }, + 'createClient', + ) + .resolves({ stop: () => Promise.resolve() } as LanguageClient); + const service = new LanguageService(); + try { + const state = service as unknown as { + startup: Promise; + clientUpdates: Map>; + }; + await state.startup; + await Promise.all(state.clientUpdates.values()); + sinon.assert.calledOnce(start); + assert.strictEqual(start.firstCall.args[1], a.fsPath); + assert.strictEqual(start.firstCall.args[2].uri.toString(), a.toString()); + } finally { + await service.dispose(); + unregisterSessionTransport(target); + sandbox.restore(); + } + }); + + test('defers the ordinary webR download until a source editor opens', async () => { + const sandbox = sinon.createSandbox(); + const opened = new vscode.EventEmitter(); + const controller = new AbortController(); + const cell = { + uri: vscode.Uri.parse('vscode-notebook-cell:/one#cell'), + languageId: 'r', + } as vscode.TextDocument; + sandbox.stub(vscode.workspace, 'textDocuments').get(() => [cell]); + sandbox.stub(vscode.workspace, 'onDidOpenTextDocument').callsFake(opened.event); + const gate = LanguageService.prototype as unknown as { + waitForRDocument(signal: AbortSignal, virtualOnly: boolean): Promise; + }; + let sourceReady = false; + const source = gate.waitForRDocument(controller.signal, false).then(() => { + sourceReady = true; + }); + try { + // The notebook side is ready immediately despite a waiting ordinary client. + await gate.waitForRDocument(controller.signal, true); + opened.fire(cell); + await Promise.resolve(); + assert.strictEqual(sourceReady, false); + opened.fire({ + uri: vscode.Uri.file('/source.R'), + languageId: 'r', + } as vscode.TextDocument); + await source; + assert.strictEqual(sourceReady, true); + } finally { + controller.abort(); + opened.dispose(); + sandbox.restore(); + } + }); + + test('starts a bound webR input even when the ordinary native source client cannot start', async () => { + const sandbox = sinon.createSandbox(); + const input = { + uri: vscode.Uri.parse('vscode-interactive-input:/session-only'), + languageId: 'r', + isClosed: false, + } as vscode.TextDocument; + const config = vscode.workspace.getConfiguration; + sandbox.stub(vscode.workspace, 'getConfiguration').callsFake((...args) => { + const settings = config(...args); + return args[0] !== 'r' + ? settings + : ({ + ...settings, + get: (key: string, fallback?: unknown) => + key === 'lsp.runtime' + ? 'native' + : key === 'lsp.multiServer' + ? false + : settings.get(key, fallback), + } as vscode.WorkspaceConfiguration); + }); + mockExtensionContext(path.resolve(__dirname, '../../..'), sandbox); + sandbox.stub(vscode.workspace, 'textDocuments').get(() => [input]); + sandbox.stub(vscode.workspace, 'getWorkspaceFolder').returns(undefined); + sandbox.stub(util, 'getRpath').resolves(undefined); + sandbox.stub(CancellableLanguageClient.prototype, 'start').resolves(); + sandbox.stub(CancellableLanguageClient.prototype, 'stop').resolves(); + const target = registerSessionTransport( + 'wasm-only', + 'host', + os.tmpdir(), + () => Promise.resolve({}), + 'webr', + ); + bindSessionDocument(input.uri, target); + const service = new LanguageService(); + try { + const state = service as unknown as { + startup: Promise; + clientUpdates: Map>; + clients: Map; + }; + await state.startup; + await Promise.all(state.clientUpdates.values()); + assert.strictEqual(state.clients.has('global'), false); + assert.strictEqual( + state.clients.get(input.uri.toString(true))?.name, + 'R Language Server (webR)', + ); + } finally { + await service.dispose(); + unregisterSessionTransport(target); + sandbox.restore(); + } + }); + for (const policy of ['auto', 'native', 'webR']) { - test(`uses the configured runtime across binding, restart, and detach (${policy})`, async () => { + test(`uses the session runtime for Interactive and the configured runtime for ordinary sources (${policy})`, async () => { const sandbox = sinon.createSandbox(); const tester = (scheme: string, path: string, fragment?: string) => ({ @@ -389,7 +538,8 @@ suite('Language service for bound Interactive documents', () => { const source = tester('file', '/test/script.R'); const notebook = tester('vscode-notebook-cell', '/test/Interactive.rnb', 'cell1'); const prompt = tester('vscode-interactive-input', '/test/Interactive.input'); - const docs = [source, notebook, prompt]; + const nativePrompt = tester('vscode-interactive-input', '/test/Other.input'); + const docs = [source, notebook, prompt, nativePrompt]; const opened = new vscode.EventEmitter(); sandbox.stub(vscode.workspace, 'onDidOpenTextDocument').callsFake(opened.event); const getConfiguration = vscode.workspace.getConfiguration; @@ -415,16 +565,31 @@ suite('Language service for bound Interactive documents', () => { sandbox.stub(vscode.workspace, 'createFileSystemWatcher').returns({ dispose() {}, } as vscode.FileSystemWatcher); - sandbox.stub(util, 'getRpath').resolves(process.execPath); + sandbox.stub(vscode.workspace, 'getWorkspaceFolder').returns(undefined); + const findR = sandbox.stub(util, 'getRpath').resolves(process.execPath); // Only transport startup is stubbed: createClient must select the real // client type/providers using the same document events as an editor. const start = sandbox.stub(CancellableLanguageClient.prototype, 'start').resolves(); sandbox.stub(CancellableLanguageClient.prototype, 'needsStop').returns(true); sandbox.stub(CancellableLanguageClient.prototype, 'stop').resolves(); const session = (id: string, provider: 'webr' | 'arf') => - registerSessionTransport(id, 'host', '/test', () => Promise.resolve({}), provider); + registerSessionTransport( + id, + 'host', + path.join(os.tmpdir(), id), + () => Promise.resolve({}), + provider, + ); const wasm = session('lsp-test-webr', 'webr'); const native = session('lsp-test-arf', 'arf'); + // Older Windows sessions already on disk omitted .exe in their ready metadata. + const reportedPath = + process.platform === 'win32' + ? process.execPath.replace(/\.exe$/i, '') + : process.execPath; + updateSessionLanguageEnvironment(native, reportedPath, [ + path.join(os.tmpdir(), 'first-library'), + ]); const languageService = new LanguageService(); const state = languageService as unknown as { startup: Promise; @@ -450,20 +615,29 @@ suite('Language service for bound Interactive documents', () => { const project = state.clients.get('global'); check(policy === 'webR'); const unboundPrompt = state.clients.get(prompt.uri.toString(true)); - // An ordinary open update can run after the input acquires its owner. + // Queue ordinary open updates before the editor reports its binding. + // Both updates run after the owner changes and reuse an existing client. opened.fire(notebook); opened.fire(prompt); bindSessionDocument(source.uri, wasm); bindSessionDocument(notebook.uri.with({ fragment: '' }), wasm); bindSessionDocument(prompt.uri, wasm); + bindSessionDocument(nativePrompt.uri, native); await settle(); - check(policy !== 'native'); - const boundPrompt = state.clients.get(prompt.uri.toString(true)); - assert.notStrictEqual(boundPrompt, unboundPrompt); + check(true); + const nativeKey = nativePrompt.uri.toString(true); + const nativeClient = state.clients.get(nativeKey); + assert.strictEqual(nativeClient?.name, 'R Language Server'); assert.strictEqual( - boundPrompt?.clientOptions.workspaceFolder?.uri.fsPath, + nativeClient.clientOptions.workspaceFolder?.uri.fsPath, + vscode.Uri.file(native.workingDir).fsPath, + ); + assert.strictEqual( + state.clients.get(prompt.uri.toString(true))?.clientOptions.workspaceFolder?.uri + .fsPath, vscode.Uri.file(wasm.workingDir).fsPath, ); + assert.notStrictEqual(state.clients.get(prompt.uri.toString(true)), unboundPrompt); assert.strictEqual(state.clients.get('global'), project); const count = start.callCount; bindSessionDocument(notebook.uri, wasm); @@ -475,18 +649,42 @@ suite('Language service for bound Interactive documents', () => { ); replaceSessionTransport(wasm, native); await settle(); - check(policy === 'webR'); + check(false); + const nativeKeyAfterRestart = prompt.uri.toString(true); + const oldClient = state.clients.get(nativeKeyAfterRestart); + updateSessionLanguageEnvironment(native, process.execPath, [ + path.join(os.tmpdir(), 'changed-library'), + ]); + await settle(); + assert.notStrictEqual(state.clients.get(nativeKeyAfterRestart), oldClient); + const callsAfterMetadata = start.callCount; + updateSessionLanguageEnvironment(native, process.execPath, [ + path.join(os.tmpdir(), 'changed-library'), + ]); + await settle(); + assert.strictEqual(start.callCount, callsAfterMetadata); + // Never silently analyze this session with the workspace's R or webR. + const finds = findR.callCount; + updateSessionLanguageEnvironment( + native, + path.join(os.tmpdir(), 'unavailable-session-R'), + [], + ); + await settle(); + assert.strictEqual(state.clients.has(nativeKeyAfterRestart), false); + assert.strictEqual(findR.callCount, finds); + assert.strictEqual(state.clients.get('global'), project); replaceSessionTransport(native, wasm); await settle(); - check(policy !== 'native'); + check(true); unregisterSessionTransport(wasm); await settle(); check(policy === 'webR'); } finally { await languageService.dispose(); + opened.dispose(); unregisterSessionTransport(wasm); unregisterSessionTransport(native); - opened.dispose(); sandbox.restore(); } }); diff --git a/src/test/web/webR.cjs b/src/test/web/webR.cjs index 3dcef844d..23ec2cd5f 100644 --- a/src/test/web/webR.cjs +++ b/src/test/web/webR.cjs @@ -57,6 +57,65 @@ const command = (id, ...args) => vscode.commands.executeCommand(id, ...args); const items = cell => cell.outputs.flatMap(out => out.items); const stdout = cell => items(cell).filter(i => i.mime.endsWith('.stdout')).map(i => new TextDecoder().decode(i.data)).join(''); +async function notebookLanguagePolicy(source, files) { + const settings = vscode.workspace.getConfiguration('r'); + const previousRuntime = settings.inspect('lsp.runtime')?.globalValue; + const previousEnabled = settings.inspect('lsp.enabled')?.globalValue; + const global = vscode.ConfigurationTarget.Global; + const hasSymbol = async (document, name) => { + const symbols = await command('vscode.executeDocumentSymbolProvider', document.uri); + return symbols?.some(symbol => symbol.name === name); + }; + const definitions = async (document, line) => + (await command('vscode.executeDefinitionProvider', document.uri, new vscode.Position(line, 3))) ?? []; + + async function openNotebook(unique) { + // VS Code's document selectors see the same path for both virtual repositories. + const uri = files.uri('analysis[1].rnb').with({ authority: unique }); + const cell = value => ({ kind: vscode.NotebookCellKind.Code, language: 'r', value, outputs: [] }); + const transcript = { + version: 1, + metadata: {}, + cells: [ + cell(`session_fn <- function(x) x\n${unique} <- function(x) x + 1`), + cell('session_fn(42)\nonly_in_b(0)\ntriple_it(3)'), + ], + }; + await vscode.workspace.fs.writeFile(uri, new TextEncoder().encode(JSON.stringify(transcript))); + const notebook = await vscode.workspace.openNotebookDocument(uri); + await vscode.window.showNotebookDocument(notebook); + return notebook; + } + + try { + await settings.update('lsp.runtime', 'native', global); + const a = await openNotebook('only_in_a'); + const b = await openNotebook('only_in_b'); + for (const book of [a, b]) { + const declaration = book.cellAt(0).document; + const call = book.cellAt(1).document; + await until(async () => { + const results = await definitions(call, 0); + return results.length === 1 && + (results[0].uri ?? results[0].targetUri).toString() === declaration.uri.toString(); + }, 'Definition did not resolve within ' + book.uri.toString()); + } + assert(!(await hasSymbol(source, 'triple_it')), 'An ordinary browser source received webR under native mode.'); + assert((await definitions(a.cellAt(1).document, 1)).length === 0, 'Another notebook supplied a local definition.'); + + await settings.update('lsp.runtime', 'auto', global); + await until(() => hasSymbol(source, 'triple_it'), 'Ordinary source language features did not resume.'); + assert((await definitions(a.cellAt(1).document, 2)).length === 0, 'A standalone source supplied a notebook definition.'); + + await settings.update('lsp.enabled', false, global); + await until(async () => !(await hasSymbol(a.cellAt(0).document, 'session_fn')) && + !(await hasSymbol(source, 'triple_it')), 'Disabling the language service left providers registered.'); + } finally { + await settings.update('lsp.runtime', previousRuntime, global); + await settings.update('lsp.enabled', previousEnabled, global); + } +} + exports.run = async () => { const files = testFiles(); try { @@ -148,6 +207,7 @@ exports.run = async () => { assert(stdout(reopened.cellAt(0)).includes('17'), 'Saved notebook lost its transcript.'); await command('r.runCommand','exists("held_value", inherits = FALSE)'); assert(stdout(reopened.cellAt(1)).includes('FALSE'), 'Reopening retained stale R state.'); + await notebookLanguagePolicy(first, files); console.log('Verified webR language features, R Interactive execution, files, and transcript reopening.'); } finally { await command('r.interactive.stopAll'); diff --git a/src/web/languageService.ts b/src/web/languageService.ts index 4b3bf5013..78cda191b 100644 --- a/src/web/languageService.ts +++ b/src/web/languageService.ts @@ -1,6 +1,8 @@ import * as vscode from 'vscode'; +import { Message } from 'vscode-jsonrpc'; import { CloseAction, + type DocumentFilter, ErrorAction, LanguageClient, RevealOutputChannelOn, @@ -22,14 +24,59 @@ class WorkerLanguageClient extends LanguageClient { } } +const interactiveType = 'r-interactive'; +const rLanguages = ['r', 'rmd']; + +interface ClientSlot { + client: LanguageClient; + abort: AbortController; + selector: string; + session?: WebRLanguageSession; +} + +/** A notebook filter is matched against the owning notebook URI, not the cell URI. */ +function notebookSelector(notebook: vscode.NotebookDocument): DocumentFilter[] { + const pattern = notebook.uri.fsPath.replace(/[?*{}[\]]/g, (char) => `[${char}]`); + return rLanguages.map((language) => ({ + language, + notebook: { notebookType: interactiveType, scheme: notebook.uri.scheme, pattern }, + })); +} + +/** The provider selector matches fsPath. Virtual notebooks can also differ only + * in URI authority or query. Keep their text and requests in the owning worker. + */ +function notebookSession(owner: vscode.Uri, session: WebRLanguageSession): WebRLanguageSession { + return { + close: () => session.close(), + dispatch(message) { + if (Message.isRequest(message) || Message.isNotification(message)) { + const params = message.params as { textDocument?: { uri?: unknown } } | undefined; + if (typeof params?.textDocument?.uri === 'string') { + const cell = vscode.Uri.parse(params.textDocument.uri); + if ( + cell.scheme !== 'vscode-notebook-cell' || + cell.authority !== owner.authority || + cell.path !== owner.path || + cell.query !== owner.query + ) { + return Promise.resolve( + Message.isRequest(message) + ? [{ jsonrpc: '2.0', id: message.id, result: null }] + : [], + ); + } + } + } + return session.dispatch(message); + }, + }; +} + export class BrowserLanguageService implements vscode.Disposable { private readonly output = vscode.window.createOutputChannel('R Language Server', { log: true }); private readonly listeners: vscode.Disposable[]; - private current?: { - client: LanguageClient; - abort: AbortController; - session?: WebRLanguageSession; - }; + private readonly clients = new Map(); private stopped = false; private stopping = Promise.resolve(); private nativePreferenceReported = false; @@ -37,7 +84,21 @@ export class BrowserLanguageService implements vscode.Disposable { constructor(private readonly context: vscode.ExtensionContext) { this.listeners = [ vscode.workspace.onDidOpenTextDocument((doc) => { - if (doc.languageId === 'r' || doc.languageId === 'rmd') { + if (rLanguages.includes(doc.languageId)) { + this.refresh(); + } + }), + vscode.workspace.onDidCloseTextDocument((doc) => { + if (rLanguages.includes(doc.languageId)) { + this.refresh(); + } + }), + vscode.workspace.onDidOpenNotebookDocument(() => this.refresh()), + vscode.workspace.onDidCloseNotebookDocument((doc) => + this.stopClient(doc.uri.toString()), + ), + vscode.workspace.onDidChangeNotebookDocument((event) => { + if (event.contentChanges.length) { this.refresh(); } }), @@ -58,32 +119,72 @@ export class BrowserLanguageService implements vscode.Disposable { return; } const settings = vscode.workspace.getConfiguration('r'); - if ( - !settings.get('lsp.enabled', true) || - settings.get('lsp.runtime') === 'native' - ) { - this.stopClient(); - if ( - !this.nativePreferenceReported && - settings.get('lsp.runtime') === 'native' - ) { - this.nativePreferenceReported = true; - this.output.appendLine( - 'The browser has no native R executable. Set r.lsp.runtime to auto or webR to enable the R language server.', - ); + const desired = new Map(); + if (settings.get('lsp.enabled', true)) { + const sources = new Set(); + const otherNotebooks = new Set(); + for (const doc of vscode.workspace.textDocuments) { + if ( + rLanguages.includes(doc.languageId) && + doc.uri.scheme !== 'vscode-notebook-cell' + ) { + sources.add(doc.uri.scheme); + } + } + for (const notebook of vscode.workspace.notebookDocuments) { + if ( + !notebook + .getCells() + .some((cell) => rLanguages.includes(cell.document.languageId)) + ) { + continue; + } + if (notebook.notebookType === interactiveType) { + desired.set(notebook.uri.toString(), notebookSelector(notebook)); + } else { + otherNotebooks.add(notebook.notebookType); + } + } + if (settings.get('lsp.runtime') === 'native') { + if (!this.nativePreferenceReported && (sources.size || otherNotebooks.size)) { + this.nativePreferenceReported = true; + this.output.appendLine( + 'R Interactive notebooks use webR. Set r.lsp.runtime to auto or webR to enable language features for other R documents in the browser.', + ); + } + } else { + this.nativePreferenceReported = false; + if (sources.size || otherNotebooks.size) { + // Keep one project client across ordinary virtual files and untitled editors. + // Notebook cells have their own selectors, so an Interactive session cannot + // leak its symbols into source completions or another session. + const selector: DocumentFilter[] = []; + for (const scheme of [...sources].sort()) { + selector.push(...rLanguages.map((language) => ({ language, scheme }))); + } + for (const notebook of [...otherNotebooks].sort()) { + selector.push(...rLanguages.map((language) => ({ language, notebook }))); + } + desired.set('source', selector); + } } - return; } - this.nativePreferenceReported = false; - if ( - this.current || - !vscode.workspace.textDocuments.some((doc) => ['r', 'rmd'].includes(doc.languageId)) - ) { - return; + for (const [key, active] of this.clients) { + if (JSON.stringify(desired.get(key)) !== active.selector) { + this.stopClient(key); + } + } + for (const [key, selector] of desired) { + if (!this.clients.has(key)) { + this.startClient(key, selector); + } } + } + + private startClient(key: string, selector: DocumentFilter[]): void { const abort = new AbortController(); const client: LanguageClient = new WorkerLanguageClient( - 'r', + key === 'source' ? 'r' : 'r:' + key, 'R Language Server', async () => { const session = await createWebRLanguageSession({ @@ -91,15 +192,18 @@ export class BrowserLanguageService implements vscode.Disposable { signal: abort.signal, loadAsset: cachedWebRAssets(this.context), }); - if (abort.signal.aborted || this.current?.client !== client) { + const current = this.clients.get(key); + if (abort.signal.aborted || current?.client !== client) { session.close(); throw new Error('The webR language service was stopped.'); } - this.current.session = session; - return createWebRMessageTransports(session); + current.session = session; + return createWebRMessageTransports( + key === 'source' ? session : notebookSession(vscode.Uri.parse(key), session), + ); }, { - documentSelector: [{ language: 'r' }, { language: 'rmd' }], + documentSelector: selector, outputChannel: this.output, synchronize: { configurationSection: 'r.lsp' }, revealOutputChannelOn: RevealOutputChannelOn.Never, @@ -107,11 +211,11 @@ export class BrowserLanguageService implements vscode.Disposable { errorHandler: { error: () => ({ action: ErrorAction.Continue }), closed: () => { - if (this.current?.client === client) { - // Allow the language client to unregister the disconnected providers first. + if (this.clients.get(key)?.client === client) { setTimeout( () => this.reportFailure( + key, client, new Error('The webR worker disconnected.'), ), @@ -123,21 +227,21 @@ export class BrowserLanguageService implements vscode.Disposable { }, }, ); - this.current = { client, abort }; + this.clients.set(key, { client, abort, selector: JSON.stringify(selector) }); void this.stopping .then(async () => { - if (this.current?.client === client) { + if (this.clients.get(key)?.client === client) { await client.start(); } }) - .catch((error) => this.reportFailure(client, error)); + .catch((error) => this.reportFailure(key, client, error)); } - private reportFailure(client: LanguageClient, error: unknown): void { - if (this.current?.client !== client) { + private reportFailure(key: string, client: LanguageClient, error: unknown): void { + if (this.clients.get(key)?.client !== client) { return; } - this.stopClient(); + this.stopClient(key); this.output.appendLine(String(error)); void vscode.window .showErrorMessage( @@ -151,28 +255,31 @@ export class BrowserLanguageService implements vscode.Disposable { }); } - private stopClient(): void { - const current = this.current; - this.current = undefined; - if (current) { - if (current.client.state !== State.Running) { - current.abort.abort(); - current.session?.close(); - } - const disposing = current.client - .dispose() - .catch(() => {}) - .finally(() => { - current.session?.close(); - current.abort.abort(); - }); - this.stopping = Promise.all([this.stopping, disposing]).then(() => {}); + private stopClient(key: string): void { + const current = this.clients.get(key); + if (!current) { + return; } + this.clients.delete(key); + if (current.client.state !== State.Running) { + current.abort.abort(); + current.session?.close(); + } + const disposing = current.client + .dispose() + .catch(() => {}) + .finally(() => { + current.session?.close(); + current.abort.abort(); + }); + this.stopping = Promise.all([this.stopping, disposing]).then(() => {}); } dispose(): void { this.stopped = true; - this.stopClient(); + for (const key of this.clients.keys()) { + this.stopClient(key); + } for (const listener of this.listeners) { listener.dispose(); } diff --git a/website/docs/features/language-service.md b/website/docs/features/language-service.md index 84017866d..6ec60caf0 100644 --- a/website/docs/features/language-service.md +++ b/website/docs/features/language-service.md @@ -5,24 +5,36 @@ vscode-R’s webR integration is **experimental**. Its implementation and behavior may change substantially between releases, including when `auto` selects webR. -With `r.lsp.runtime` set to `auto`, vscode-R uses your configured R installation -when available. If it cannot find R, it starts the WebAssembly build of R -(webR) in a separate worker when you open an R document. Use `webR` to choose -this runtime explicitly or `native` to require a native installation. -`r.lsp.enabled` controls both runtimes. Reload the window after changing the -runtime setting. With the default `r.lsp.multiServer = false`, open files share -one server and the first workspace folder supplies its runtime preference. With -`r.lsp.multiServer = true`, each workspace folder uses its own preference. If an initialized webR worker -stops, choose **Retry** to reopen the current documents with a new worker. - -The VSIX includes the Wasm languageserver package. The first webR session -downloads its pinned runtime, supporting packages and development R modules. -Downloads are cached in extension storage. The -language worker analyzes the open editor buffers locally, including unsaved -changes. Cross-file navigation and rename cover open documents in the same -workspace. Package information reflects the packages installed in the worker. -The native server can additionally index closed files and use your project's R -library. +For R and R Markdown source editors, `r.lsp.runtime` selects the workspace +language server. On desktop, `auto` uses the configured native R installation +when available and otherwise starts webR. Choose `native` to require native R +or `webR` to use WebAssembly. Reload the window after changing this setting. + +With the default `r.lsp.multiServer = false`, ordinary sources share one server +and the first workspace folder supplies its runtime preference. With +`r.lsp.multiServer = true`, each workspace folder uses its own preference. +If an initialized webR language worker stops, choose **Retry** to reopen the +current documents with a new worker. + +**R Interactive inputs and cells follow their execution session.** An arf +session uses a native language server with the session's R executable, working +directory and reported library paths. A webR session uses a dedicated webR +language worker. This also applies when the workspace setting selects the other +runtime. For example, with `r.lsp.runtime` set to `native`, sending a selection +from `analysis.R` to a webR session leaves the source editor on native R and the +Interactive notebook on webR. If native R is unavailable, the webR notebook +can still provide language features. Set `r.lsp.enabled` to `false` to disable +the language service for both source editors and Interactive documents. + +The VSIX includes the Wasm languageserver package. The first webR language +session downloads its pinned runtime, supporting packages and development R +modules. Subsequent starts reuse cached assets. The worker analyzes +open editor buffers locally, including unsaved changes. Cross-file navigation +and rename cover open documents served by the same language client. Package +completion and signatures reflect the language worker's library. Installing +a package in an Interactive webR session changes that session's execution +library only. Native R can additionally index closed files and use the +project's R library. When renaming a project-level symbol with webR, review the edits in VS Code. The preview covers open files in the same workspace folder. Closed files can @@ -245,6 +257,14 @@ can be used to adjust the referenced color. ## VS Code for the Web -Opening an R or R Markdown document in a trusted browser workspace starts the webR language server when `r.lsp.enabled` is enabled and `r.lsp.runtime` is `auto` or `webR`. Initial startup downloads the language server and its WebAssembly package library. Subsequent starts reuse cached package assets. - -Open buffers provide the source for Outline, completion, hover, signature help, and Go to Definition, including unsaved edits and navigation between open documents. Package-aware results reflect the worker’s package library. The browser language service operates independently of an Interactive notebook. Whole-project indexing and tools that launch a native executable require a workspace extension host with native R. +In a trusted browser workspace, opening an R or R Markdown source document +starts the webR language server when `r.lsp.runtime` is `auto` or `webR`. +Choosing `native` leaves ordinary browser source editors without a language +server. Cells in a webR Interactive notebook use webR regardless of that +workspace preference. `r.lsp.enabled` controls both. + +The browser language worker provides Outline, completion, hover, signature +help and Go to Definition for open buffers, including unsaved edits. It can +serve requests while Interactive code is running. Package-aware results use +its own language-service library. Whole-project indexing and tools that launch +a native executable require a workspace extension host with native R. diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index ab49b7219..adc55ddeb 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -131,7 +131,8 @@ External terminal output observed through the arf console bridge is retained in ### Language features -- Separate language-server processes serve virtual documents with the session's R executable, library paths, and working directory. Cell and input diagnostics lint the live text with lintr's disk cache disabled, because virtual documents have no corresponding R source file. Blank or whitespace-only Interactive prompts clear diagnostics and ignore late lint replies; nonempty code and source files still receive normal diagnostics. Unsaved notebook cells also use a pathless language-server URI so namespace linters do not try to read a nonexistent file; diagnostics still map to the original cell. Source-file language servers retain the user's cache setting. Live completion and hover use the owning session with short timeouts. With `r.lsp.runtime` set to `auto`, webR Interactive inputs and cells use the webR language server even if native R is installed. Explicit `native` and `webR` preferences apply to these editors. Ordinary source files keep the workspace language server when routed to an Interactive session. +- **Inputs and cells use the session’s runtime.** A native arf session supplies its R executable, working directory and reported library paths. A webR session uses a separate webR language worker with its own package library. This choice follows the session even when `r.lsp.runtime` selects a different runtime for source files. Running a source file or selection in an Interactive session preserves that editor’s workspace language server. `r.lsp.enabled` enables or disables both. [Language server runtime](./language-service.md#language-server-runtime) +- Native cell and input diagnostics lint the live text with lintr’s disk cache disabled. Blank Interactive prompts clear diagnostics and ignore late lint replies. Unsaved notebook cells use a pathless language-server URI so namespace linters can analyze the buffer without a corresponding file. Source-file language servers retain the user’s cache setting. Live completion and hover use the owning session when it supports object inspection. - Custom `.lintr` linter lists in cells and inputs require the [pathless-document settings fix in `languageserver`](https://github.com/REditorSupport/languageserver/pull/782). `languageserver` 0.3.20 selects default linters for these documents, even when source files use your configured rules. Updating the extension alone does not fix that package behavior. - Function hovers and parameter hints can use the owning session's cached function metadata, including while R is busy. After executing `fun1 <- function(x, y) x + y`, hovering over `fun1` shows its formals, and typing `fun1(` or `fun1(1, ` shows and highlights the corresponding parameter. Hints handle defaults, named arguments, `...`, nested expressions, and quoted names. Source-local definitions and package signatures from languageserver take priority. Session hints are a fallback for simple function names in source documents, notebook cells, and Interactive inputs; they do not evaluate code. Different sessions can define the same name with different signatures. @@ -271,4 +272,4 @@ Use **R: Import Files into webR…** to copy scripts and data from the workspace Save an Interactive notebook as an `.rnb` file to keep its cells and outputs. Its live R objects and imported files belong to the browser worker and are released when the notebook closes, the page reloads, or the session restarts. On a cross-origin isolated host, **R: Interrupt Interactive Session** keeps the R environment. Console prompts such as `readline()` use the notebook input dialog. The PostMessage channel has limited input support and offers to restart the worker when interrupting a calculation. -The browser language server runs in a separate worker and can serve open documents while code is running. [Browser language features](./language-service.md#vs-code-for-the-web) +Browser Interactive cells use a separate webR language worker even when the workspace language-server setting is `native`. The worker can answer requests while code is running, and package completions use its own package library. [Browser language features](./language-service.md#vs-code-for-the-web)