Skip to content
Open
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
7 changes: 7 additions & 0 deletions R/languageServer.R
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion sess/R/interactive.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion src/interactive/executable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 16 additions & 8 deletions src/interactive/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand Down
107 changes: 80 additions & 27 deletions src/languageService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, LanguageClient> = new Map();
private readonly initSet: Set<string> = new Set();
Expand All @@ -53,6 +61,7 @@ export class LanguageService implements Disposable {
private readonly sessionSignatures = new SessionSignatureHelpProvider();
private readonly clientUpdates = new Map<string, Promise<void>>();
private readonly listeners: Disposable[] = [];
private documentListenersStarted = false;
private startup: Promise<void>;
private readonly startupCancellation = new AbortController();
private readonly startingClients = new Set<CancellableLanguageClient>();
Expand All @@ -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();
}
Expand Down Expand Up @@ -242,22 +251,38 @@ export class LanguageService implements Disposable {
const resourceConfig = config(resource);
const debug = this.config.get<boolean>('lsp.debug');
const useRenvLibPath = this.config.get<boolean>('useRenvLibPath') ?? false;
const policy = resourceConfig.get<string>('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<string>('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.`,
);
Expand All @@ -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<string>('lsp.lang');
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -484,8 +510,15 @@ export class LanguageService implements Disposable {
}
}

private async waitForRDocument(signal: AbortSignal): Promise<void> {
const isR = (doc: TextDocument) => doc.languageId === 'r' || doc.languageId === 'rmd';
private async waitForRDocument(signal: AbortSignal, virtualOnly: boolean): Promise<void> {
// 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;
}
Expand Down Expand Up @@ -554,7 +587,13 @@ export class LanguageService implements Disposable {
}

private startMultiLanguageService(virtualOnly = false): void {
const clientTargets = new Map<string, Session | undefined>();
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<string, { session: Session; revision: number }>();
const didOpenTextDocument = async (document: TextDocument) => {
if (
virtualOnly &&
Expand All @@ -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,
);
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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' },
Expand All @@ -848,7 +902,6 @@ export class LanguageService implements Disposable {
if (client) {
this.clients.set('global', client);
}
this.startMultiLanguageService(true);
}
}

Expand Down
17 changes: 17 additions & 0 deletions src/session.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -133,6 +134,7 @@ export class Session {
public rPath?: string;
public libraryPaths?: string[];
public interactiveProvider?: ProviderKind;
public languageEnvironmentRevision = 0;
public requester?: (data: Record<string, unknown>) => Promise<unknown>;
public connectionId?: string;
public attachmentId?: string;
Expand Down Expand Up @@ -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<string>();
Expand Down
6 changes: 6 additions & 0 deletions src/test/node/interactiveRuntime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions src/test/suite/interactiveEditor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading