diff --git a/package.json b/package.json index a1baed9ef..d6a1e8d0c 100644 --- a/package.json +++ b/package.json @@ -2826,6 +2826,7 @@ "tar": "7.5.24", "vscode-jsonrpc": "10.0.0", "vscode-languageclient": "^11.0.0", + "vscode-languageserver-textdocument": "1.0.16", "webr": "0.6.1", "winreg": "^1.2.5", "ws": "^8.23.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 18a16a662..34750f181 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -41,6 +41,9 @@ importers: vscode-languageclient: specifier: ^11.0.0 version: 11.0.0 + vscode-languageserver-textdocument: + specifier: 1.0.16 + version: 1.0.16 webr: specifier: 0.6.1 version: 0.6.1 diff --git a/src/interactive/agent.ts b/src/interactive/agent.ts index cb10ae555..e16dabd1e 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -319,6 +319,7 @@ export class SessionAgent { ended: this.manifest.ended, rPath: this.manifest.rPath, libraryPaths: this.manifest.libraryPaths, + webRPackageRevision: this.manifest.webRPackageRevision, runtimeSessionId: this.manifest.runtimeSessionId, capabilities: this.manifest.capabilities, }); diff --git a/src/interactive/backend.ts b/src/interactive/backend.ts index 5158a75cf..c286dd1d0 100644 --- a/src/interactive/backend.ts +++ b/src/interactive/backend.ts @@ -9,6 +9,7 @@ export interface RuntimeMetadata { runtimeSessionId?: string; rPath?: string; libraryPaths?: string[]; + webRPackageRevision?: number; } export const INSPECTION_METHODS = [ 'workspace', diff --git a/src/interactive/backends/webr.ts b/src/interactive/backends/webr.ts index 5719c1783..a4f527f84 100644 --- a/src/interactive/backends/webr.ts +++ b/src/interactive/backends/webr.ts @@ -1,3 +1,5 @@ +import { webcrypto } from 'node:crypto'; +import { DesktopWebRPackageStore } from '../webRPackageStore'; import { WebRConsole, WebRConsoleEvent } from '../../webr/console'; import { BackendEvent, DispatchNotSentError, InspectionRequest, SessionBackend } from '../backend'; import type { AgentSettings, Submission } from '../protocol'; @@ -11,6 +13,7 @@ export class WebRBackend implements SessionBackend { debugger: false, tables: true, viewerInspection: true, + webRPackageContext: true, html: true, inspection: false, inspectionDeadline: false, @@ -24,11 +27,16 @@ export class WebRBackend implements SessionBackend { private current?: string; private inputId = 0; private stopped = false; + private readonly packages: DesktopWebRPackageStore; + private webRPackageRevision?: number; + private packageWarning?: string; constructor( private readonly settings: AgentSettings, private readonly baseUrl: string, - ) {} + ) { + this.packages = new DesktopWebRPackageStore(settings.storage, settings.generation); + } onEvent(listener: (event: BackendEvent) => void): () => void { this.listeners.add(listener); @@ -58,6 +66,7 @@ export class WebRBackend implements SessionBackend { } this.exit(); }, + webcrypto as Pick, ); this.console = console; try { @@ -66,11 +75,12 @@ export class WebRBackend implements SessionBackend { await runtime.FS.mount('NODEFS', { root: this.settings.directory }, '/project'); await runtime.evalRVoid('base::setwd("/project")'); const rVersion = await runtime.evalRString('R.version.string'); + await this.publishPackages(); if (!this.stopped) { this.emit({ type: 'ready', capabilities: this.capabilities, - metadata: { rVersion }, + metadata: { rVersion, webRPackageRevision: this.webRPackageRevision }, }); } } catch (error) { @@ -79,12 +89,40 @@ export class WebRBackend implements SessionBackend { } } + private async publishPackages(): Promise { + try { + const revision = await this.packages.publish(); + if (revision !== undefined && !this.stopped) { + this.webRPackageRevision = revision; + this.emit({ type: 'metadata', metadata: { webRPackageRevision: revision } }); + } + this.packageWarning = undefined; + } catch (error) { + this.reportPackageWarning(error); + } + } + + private reportPackageWarning(error: unknown): void { + const message = 'Could not publish webR package information: ' + String(error); + if (!this.stopped && message !== this.packageWarning) { + this.packageWarning = message; + this.emit({ type: 'warning', message }); + } + } + private receive(event: WebRConsoleEvent): void { if (this.stopped) { return; } const executionId = this.current; switch (event.type) { + case 'packageContext': + try { + this.packages.stage(event.context, event.archives); + } catch (error) { + this.reportPackageWarning(error); + } + break; case 'started': case 'stream': this.emit({ ...event, executionId }); @@ -136,7 +174,10 @@ export class WebRBackend implements SessionBackend { resolve(); }) .then( - (state) => { + async (state) => { + // The next editor request can see packages installed by this cell + // as soon as its finished event is visible, including after reconnect. + await this.publishPackages(); this.current = undefined; if (!this.stopped) { this.emit({ type: 'finished', executionId: submission.id, state }); diff --git a/src/interactive/client.ts b/src/interactive/client.ts index 833767ad5..125cfbaec 100644 --- a/src/interactive/client.ts +++ b/src/interactive/client.ts @@ -217,6 +217,9 @@ export class AgentClient extends EventEmitter { if (typeof data.runtimeSessionId === 'string') { this.manifest.runtimeSessionId = data.runtimeSessionId; } + if (typeof data.webRPackageRevision === 'number') { + this.manifest.webRPackageRevision = data.webRPackageRevision; + } if (Array.isArray(data.libraryPaths)) { this.manifest.libraryPaths = data.libraryPaths.map(String); } diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 86e6697ed..2e9688076 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1,9 +1,11 @@ +import { DesktopWebRPackageSource } from './webRPackageStore'; import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; import { randomUUID } from 'crypto'; import { AgentClient } from './client'; import { + identifier, AgentConfig, AgentSnapshot, DEFAULT_MAX_ASSET_BYTES, @@ -1796,6 +1798,17 @@ export class InteractiveManager } } + private updateLanguageEnvironment(target: session.Session, manifest: SessionManifest): void { + if (manifest.provider === 'webr' && manifest.capabilities.webRPackageContext) { + target.webRPackageSource ??= new DesktopWebRPackageSource( + path.join(this.root, identifier(manifest.id)), + manifest.generation, + ); + target.webRPackageSource.update(manifest.webRPackageRevision); + } + session.updateSessionLanguageEnvironment(target, manifest.rPath, manifest.libraryPaths); + } + private registerTarget(client: AgentClient): session.Session { const manifest = client.manifest; const target = session.registerSessionTransport( @@ -1813,7 +1826,7 @@ export class InteractiveManager target.pid = String(manifest.rPid ?? ''); target.rVer = manifest.rVersion ?? ''; target.processExited = manifest.status === 'exited'; - session.updateSessionLanguageEnvironment(target, manifest.rPath, manifest.libraryPaths); + this.updateLanguageEnvironment(target, manifest); target.label = manifest.label; target.execute = async (code) => { const view = [...this.views.values()].find((item) => item.target === target); @@ -1923,11 +1936,7 @@ export class InteractiveManager view.target.pid = String(snapshot.manifest.rPid ?? ''); view.target.rVer = snapshot.manifest.rVersion ?? ''; view.target.processExited = snapshot.manifest.status === 'exited'; - session.updateSessionLanguageEnvironment( - view.target, - snapshot.manifest.rPath, - snapshot.manifest.libraryPaths, - ); + this.updateLanguageEnvironment(view.target, snapshot.manifest); view.base = snapshot.manifest.assetBase ? ( await vscode.env.asExternalUri(vscode.Uri.parse(snapshot.manifest.assetBase)) @@ -2184,11 +2193,7 @@ export class InteractiveManager if (Array.isArray(event.data.libraryPaths)) { view.client.manifest.libraryPaths = event.data.libraryPaths.map(String); } - session.updateSessionLanguageEnvironment( - view.target, - view.client.manifest.rPath, - view.client.manifest.libraryPaths, - ); + this.updateLanguageEnvironment(view.target, view.client.manifest); if (typeof event.data.runtimeSessionId === 'string') { view.client.manifest.runtimeSessionId = event.data.runtimeSessionId; } @@ -3569,11 +3574,7 @@ export class InteractiveManager target.pid = String(snapshot.manifest.rPid ?? ''); target.rVer = snapshot.manifest.rVersion ?? ''; target.processExited = snapshot.manifest.status === 'exited'; - session.updateSessionLanguageEnvironment( - target, - snapshot.manifest.rPath, - snapshot.manifest.libraryPaths, - ); + this.updateLanguageEnvironment(target, snapshot.manifest); view.prompts.clear(); if (snapshot.workspace) { target.workspaceData = snapshot.workspace as unknown as session.WorkspaceData; diff --git a/src/interactive/protocol.ts b/src/interactive/protocol.ts index 8bddb5310..7f8876d73 100644 --- a/src/interactive/protocol.ts +++ b/src/interactive/protocol.ts @@ -42,6 +42,8 @@ export interface SessionManifest extends SessionIdentity { runtimeSessionId?: string; rPath?: string; libraryPaths?: string[]; + /** Revision of the package snapshot stored by this webR generation. */ + webRPackageRevision?: number; } export interface SourceLocation { diff --git a/src/interactive/webRPackageStore.ts b/src/interactive/webRPackageStore.ts new file mode 100644 index 000000000..6b613829d --- /dev/null +++ b/src/interactive/webRPackageStore.ts @@ -0,0 +1,223 @@ +import { createHash, randomUUID } from 'node:crypto'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { + isArchiveDigest, + isPackageName, + type WebRPackageContext, + type WebRPackageSource, +} from '../webr/packageContext'; +import { atomicJson } from './journal'; +import { identifier } from './protocol'; + +function directory(storage: string, generation: string): string { + return path.join(storage, identifier(generation), 'webr-packages'); +} + +function verifiedContext(value: unknown): WebRPackageContext { + const context = value as Partial | null; + if ( + !context || + typeof context.libraryId !== 'string' || + !context.libraryId || + !Number.isSafeInteger(context.revision) || + (context.revision as number) < 0 || + !Array.isArray(context.attached) || + !context.attached.every(isPackageName) || + !Array.isArray(context.packages) || + !context.packages.every( + (pkg) => + pkg && + isPackageName(pkg.name) && + typeof pkg.version === 'string' && + (pkg.archive === undefined || isArchiveDigest(pkg.archive)) && + (pkg.unavailable === undefined || + (pkg.unavailable === true && pkg.archive === undefined)), + ) + ) { + throw new Error('Invalid webR session package context.'); + } + return context as WebRPackageContext; +} + +function sha256(bytes: Uint8Array): string { + return createHash('sha256').update(bytes).digest('hex'); +} + +function archives(context: WebRPackageContext): Set { + return new Set(context.packages.flatMap((pkg) => (pkg.archive ? [pkg.archive] : []))); +} + +/** Single writer inside the session agent. Publish metadata only after all its bytes are durable. */ +export class DesktopWebRPackageStore { + private readonly root: string; + private readonly written = new Set(); + private readonly pending = new Map>(); + private committed?: WebRPackageContext; + private latest?: WebRPackageContext; + + constructor(storage: string, generation: string) { + this.root = directory(storage, generation); + } + + stage(context: WebRPackageContext, delta: Map>): void { + verifiedContext(context); + if ( + this.committed && + (this.committed.libraryId !== context.libraryId || + this.committed.revision > context.revision) + ) { + throw new Error('Obsolete webR session package context.'); + } + if (this.committed?.revision === context.revision) { + return; + } + const required = archives(context); + for (const key of this.pending.keys()) { + if (!required.has(key)) { + this.pending.delete(key); + } + } + for (const [key, bytes] of delta) { + if (required.has(key) && !this.written.has(key)) { + this.pending.set(key, bytes); + } + } + this.latest = context; + } + + /** Retry an interrupted disk write at the next idle boundary, even if packages did not change. */ + async publish(): Promise { + const context = this.latest; + if (!context) { + return; + } + const required = archives(context); + await fs.promises.mkdir(this.root, { recursive: true, mode: 0o700 }); + for (const digest of required) { + if (this.written.has(digest)) { + continue; + } + const bytes = this.pending.get(digest); + if (!bytes || sha256(bytes) !== digest) { + throw new Error('Missing or invalid webR session package archive.'); + } + const temporary = path.join(this.root, randomUUID() + '.partial'); + try { + const file = await fs.promises.open(temporary, 'wx', 0o600); + try { + await file.writeFile(bytes); + await file.sync(); + } finally { + await file.close(); + } + await fs.promises.rename(temporary, path.join(this.root, digest + '.gz')); + } finally { + await fs.promises.rm(temporary, { force: true }); + } + this.written.add(digest); + this.pending.delete(digest); + } + atomicJson(path.join(this.root, 'context.json'), context); + this.committed = context; + if (this.latest === context) { + this.latest = undefined; + } + return context.revision; + } +} + +function readContext(file: string): unknown { + const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0)); + try { + if (!fs.fstatSync(fd).isFile()) { + throw new Error('Invalid webR session package metadata.'); + } + return JSON.parse(fs.readFileSync(fd, 'utf8')) as unknown; + } catch (error) { + // A malformed file's contents may appear in the default JSON parser error. + if (error instanceof SyntaxError) { + throw new Error('Invalid webR session package metadata.'); + } + throw error; + } finally { + fs.closeSync(fd); + } +} + +/** Read-only package source for one authenticated agent generation. No archive bytes cross its control socket. */ +export class DesktopWebRPackageSource implements WebRPackageSource { + private readonly root: string; + private advertised?: number; + private context?: WebRPackageContext; + private allowed = new Set(); + + constructor( + private readonly storage: string, + private readonly generation: string, + private readonly latestRevision?: () => number | undefined, + ) { + this.root = directory(storage, generation); + } + + /** Pin membership to the snapshot last requested by this particular language worker. */ + forWorker(): WebRPackageSource { + return new DesktopWebRPackageSource(this.storage, this.generation, () => this.advertised); + } + + update(revision: number | undefined): void { + if ( + revision !== undefined && + Number.isSafeInteger(revision) && + revision >= 0 && + (this.advertised === undefined || revision > this.advertised) + ) { + this.advertised = revision; + } + } + + current(): WebRPackageContext | undefined { + if (this.latestRevision) { + this.update(this.latestRevision()); + } + if (this.advertised === undefined) { + return undefined; + } + if (!this.context || this.context.revision < this.advertised) { + const context = verifiedContext(readContext(path.join(this.root, 'context.json'))); + if ( + context.revision < this.advertised || + (this.context && this.context.libraryId !== context.libraryId) + ) { + throw new Error('The webR session package context changed.'); + } + this.context = context; + this.allowed = archives(context); + } + return this.context; + } + + async readArchive(digest: string): Promise> { + if (!isArchiveDigest(digest) || !this.allowed.has(digest)) { + throw new Error('Unknown webR session package archive.'); + } + const file = await fs.promises.open( + path.join(this.root, digest + '.gz'), + fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0), + ); + try { + if (!(await file.stat()).isFile()) { + throw new Error('Invalid webR session package archive.'); + } + const bytes = await file.readFile(); + if (sha256(bytes) !== digest) { + throw new Error('Invalid checksum for a webR session package.'); + } + return bytes.buffer instanceof ArrayBuffer + ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) + : Uint8Array.from(bytes); + } finally { + await file.close(); + } + } +} diff --git a/src/languageService.ts b/src/languageService.ts index 0f9946474..bb52ba9fa 100644 --- a/src/languageService.ts +++ b/src/languageService.ts @@ -465,6 +465,10 @@ export class LanguageService implements Disposable { baseUrl, signal: client.startupSignal, loadAsset: cachedWebRAssets(extensionContext), + packageSource: + provider === 'webr' + ? target?.webRPackageSource?.forWorker() + : undefined, }); client.ownResource(() => session.close()); return createWebRMessageTransports(session); diff --git a/src/session.ts b/src/session.ts index d547327aa..053572a97 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1,5 +1,7 @@ 'use strict'; +import type { DesktopWebRPackageSource } from './interactive/webRPackageStore'; + import { isDeepStrictEqual } from 'node:util'; import * as fs from 'node:fs'; import * as fsp from 'node:fs/promises'; @@ -135,6 +137,7 @@ export class Session { public libraryPaths?: string[]; public interactiveProvider?: ProviderKind; public languageEnvironmentRevision = 0; + public webRPackageSource?: DesktopWebRPackageSource; public requester?: (data: Record) => Promise; public connectionId?: string; public attachmentId?: string; diff --git a/src/test/node/interactiveWebR.test.ts b/src/test/node/interactiveWebR.test.ts index 9562681be..46e3b04f7 100644 --- a/src/test/node/interactiveWebR.test.ts +++ b/src/test/node/interactiveWebR.test.ts @@ -1,6 +1,6 @@ import * as assert from 'node:assert/strict'; import { spawn, type ChildProcess } from 'node:child_process'; -import { randomUUID } from 'node:crypto'; +import { createHash, randomUUID } from 'node:crypto'; import { once } from 'node:events'; import * as fs from 'node:fs'; import { createServer } from 'node:http'; @@ -10,6 +10,7 @@ import { setTimeout as delay } from 'node:timers/promises'; import { readSessionManifest } from '../../interactive/launcher'; import { prepareNodeWebR } from '../../webr/nodeRuntime'; import { AgentClient } from '../../interactive/client'; +import { DesktopWebRPackageSource } from '../../interactive/webRPackageStore'; import type { AgentConfig, SessionEvent, SessionManifest } from '../../interactive/protocol'; suite('R Interactive webR provider', function () { @@ -17,20 +18,21 @@ suite('R Interactive webR provider', function () { let root: string; let project: string; let launchDirectory: string; - let agent: ChildProcess; - let closed: Promise; + let config: AgentConfig; + let workers: { child: ChildProcess; closed: Promise }[]; let client: AgentClient; let manifest: SessionManifest; let events: SessionEvent[]; setup(async () => { + workers = []; root = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-r-webr-')); project = path.join(root, 'my project'); fs.mkdirSync(project); const baseUrl = await prepareNodeWebR(root, (directory) => fs.promises.cp(path.dirname(require.resolve('webr')), directory, { recursive: true }), ); - const config: AgentConfig = { + config = { id: randomUUID(), generation: randomUUID(), label: 'webR test', @@ -50,10 +52,15 @@ suite('R Interactive webR provider', function () { // Exercise the same process entry point as a managed Interactive agent. launchDirectory = path.join(root, 'launcher'); fs.mkdirSync(launchDirectory); + manifest = await startAgent(config); + await connect(); + }); + + async function startAgent(config: AgentConfig): Promise { fs.mkdirSync(config.storage, { mode: 0o700 }); const configFile = path.join(config.storage, 'config.json'); fs.writeFileSync(configFile, JSON.stringify(config)); - agent = spawn( + const child = spawn( process.execPath, [require.resolve('../../interactive/agentMain'), configFile], { @@ -61,26 +68,26 @@ suite('R Interactive webR provider', function () { stdio: 'inherit', }, ); - closed = once(agent, 'close'); + workers.push({ child, closed: once(child, 'close') }); for (let i = 0; i < 500; i++) { const ready = readSessionManifest(config.storage, config.id, config.generation); if (ready?.status === 'idle') { - manifest = ready; - await connect(); - return; + return ready; } - if (ready?.startupError || agent.exitCode !== null || agent.signalCode !== null) { + if (ready?.startupError || child.exitCode !== null || child.signalCode !== null) { throw new Error(ready?.startupError ?? 'webR agent exited during startup'); } await delay(20); } throw new Error('webR agent did not become ready'); - }); + } teardown(async () => { client?.close(); - agent?.kill(); - await closed; + for (const worker of workers) { + worker.child.kill(); + } + await Promise.all(workers.map((worker) => worker.closed)); fs.rmSync(root, { recursive: true, force: true }); }); @@ -359,10 +366,9 @@ suite('R Interactive webR provider', function () { assert.equal((await client.snapshot()).manifest.status, 'exited'); }); - test('installs packages from the configured Wasm repository without replacing library or require', async () => { + async function withPackageRepository(operation: () => Promise): Promise { // Serve a tiny binary fixture through the ordinary package index and tarball paths. - const http = await import('node:http'); - const server = http.createServer((request, response) => { + const server = createServer((request, response) => { const name = request.url?.split('/').at(-1); if (name === 'PACKAGES.rds' || name === 'vscoderfixture_1.0.0.tgz') { response.end(fs.readFileSync(path.join(project, name))); @@ -377,22 +383,159 @@ suite('R Interactive webR provider', function () { try { const address = server.address(); assert.ok(address && typeof address === 'object'); - const id = await submit(`local({ + const fixture = await submit(`local({ pkg <- "vscoderfixture" dir.create(file.path(pkg, "Meta"), recursive = TRUE) meta <- readRDS(system.file("Meta", "package.rds", package = "datasets")) meta$DESCRIPTION[c("Package", "Version")] <- c(pkg, "1.0.0") write.dcf(as.data.frame(as.list(meta$DESCRIPTION)), file.path(pkg, "DESCRIPTION")) saveRDS(meta, file.path(pkg, "Meta", "package.rds")) - writeLines(character(), file.path(pkg, "NAMESPACE")) + dir.create(file.path(pkg, "R")) + writeLines(c( + "fixture_add <- function(fixture_amount = 17L) fixture_amount + 1L", + ".onLoad <- function(...) if (isTRUE(getOption('vscoderfixture.track'))) writeLines('loaded', 'fixture-loaded')" + ), file.path(pkg, "R", pkg)) + writeLines("export(fixture_add)", file.path(pkg, "NAMESPACE")) utils::tar("vscoderfixture_1.0.0.tgz", pkg, tar = "internal", compression = "gzip") index <- as.matrix(data.frame(Package = pkg, Version = "1.0.0", Depends = NA_character_, Imports = NA_character_, LinkingTo = NA_character_, row.names = pkg)) saveRDS(index, "PACKAGES.rds") + options(webr_pkg_repos = "http://127.0.0.1:${address.port}") + })`); + assert.equal((await wait(fixture, 'finished')).data.state, 'success', output(fixture)); + await operation(); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } + } + + test('publishes installed and attached package state from the owning webR generation', async () => { + const name = 'vscoderfixture'; + const source = new DesktopWebRPackageSource(config.storage, manifest.generation); + async function current() { + const revision = (await client.snapshot()).manifest.webRPackageRevision; + assert.notEqual(revision, undefined); + source.update(revision); + const context = source.current(); + assert.ok(context); + assert.equal(context.revision, revision); + return context; + } + await withPackageRepository(async () => { + // Package discovery must leave user code and namespace loading hooks untouched. + const installed = await submit(` + previous_libs <- .libPaths() + session_lib <- tempfile() + dir.create(session_lib) + .libPaths(c(session_lib, previous_libs)) + options(vscoderfixture.track = TRUE) + install.packages("vscoderfixture", quiet = TRUE) + stopifnot(!("vscoderfixture" %in% loadedNamespaces())) + `); + assert.equal( + (await wait(installed, 'finished')).data.state, + 'success', + output(installed), + ); + const available = await current(); + const pkg = available.packages.find((item) => item.name === name); + assert.ok(pkg); + assert.equal(pkg.version, '1.0.0'); + const digest = pkg.archive; + assert.ok(digest); + assert.ok(!available.attached.includes(name)); + assert.ok(!fs.existsSync(path.join(project, 'fixture-loaded'))); + const unchanged = await submit('invisible(42L)'); + assert.equal((await wait(unchanged, 'finished')).data.state, 'success'); + assert.equal((await current()).revision, available.revision); + + const archive = await source.readArchive(digest); + assert.equal(createHash('sha256').update(archive).digest('hex'), digest); + fs.writeFileSync(path.join(project, 'unrelated.txt'), 'user project file'); + await assert.rejects(async () => + source.readArchive(path.join(project, 'unrelated.txt')), + ); + await assert.rejects(async () => source.readArchive('0'.repeat(64))); + + const loaded = await submit('library(vscoderfixture); stopifnot(fixture_add() == 18L)'); + assert.equal((await wait(loaded, 'finished')).data.state, 'success', output(loaded)); + const attached = await current(); + assert.ok(attached.attached.includes(name)); + assert.equal(attached.packages.find((item) => item.name === name)?.archive, digest); + assert.ok(attached.revision > available.revision); + assert.equal( + fs.readFileSync(path.join(project, 'fixture-loaded'), 'utf8').trim(), + 'loaded', + ); + + // Restore an editor connection and package reader without re-executing the cell. + client.close(); + await connect(); + const restored = new DesktopWebRPackageSource(config.storage, manifest.generation); + restored.update((await client.snapshot()).manifest.webRPackageRevision); + assert.deepEqual(restored.current(), attached); + assert.deepEqual(await restored.readArchive(digest), archive); + + const secondConfig = { + ...config, + id: randomUUID(), + generation: randomUUID(), + storage: path.join(root, 'peer'), + }; + const second = await startAgent(secondConfig); + const peer = new AgentClient(second); + try { + await peer.connect({ claim: true }); + const peerSource = new DesktopWebRPackageSource( + secondConfig.storage, + second.generation, + ); + peerSource.update((await peer.snapshot()).manifest.webRPackageRevision); + const peerContext = peerSource.current(); + assert.ok(!peerContext?.packages.some((item) => item.name === name)); + assert.ok(!peerContext?.attached.includes(name)); + await assert.rejects(async () => peerSource.readArchive(digest)); + const wrongGeneration = new DesktopWebRPackageSource( + config.storage, + second.generation, + ); + await assert.rejects(async () => { + wrongGeneration.update(attached.revision); + wrongGeneration.current(); + return wrongGeneration.readArchive(digest); + }); + } finally { + peer.close(); + } + + const detached = await submit( + 'detach("package:vscoderfixture", unload = TRUE); stopifnot(!("package:vscoderfixture" %in% search()))', + ); + assert.equal( + (await wait(detached, 'finished')).data.state, + 'success', + output(detached), + ); + const retained = await current(); + assert.ok(retained.packages.some((item) => item.name === name)); + assert.ok(!retained.attached.includes(name)); + assert.ok(retained.revision > attached.revision); + + const removed = await submit('.libPaths(previous_libs)'); + assert.equal((await wait(removed, 'finished')).data.state, 'success', output(removed)); + assert.ok(!(await current()).packages.some((item) => item.name === name)); + await assert.rejects(async () => source.readArchive(digest)); + }); + }); + + test('installs packages from the configured Wasm repository without replacing library or require', async () => { + await withPackageRepository(async () => { + const id = await submit(`local({ + pkg <- "vscoderfixture" lib <- tempfile() dir.create(lib) - options(webr_pkg_repos = "http://127.0.0.1:${address.port}") install.packages(pkgs = pkg, lib, quiet = TRUE) stopifnot(identical(library, base::library), identical(require, base::require), identical(requireNamespace, base::requireNamespace)) @@ -406,9 +549,6 @@ suite('R Interactive webR provider', function () { output(absent), /Could not install missingfixture from the webR binary repositories/, ); - } finally { - server.closeAllConnections(); - await new Promise((resolve) => server.close(() => resolve())); - } + }); }); }); diff --git a/src/test/node/webRDocumentReplay.test.ts b/src/test/node/webRDocumentReplay.test.ts new file mode 100644 index 000000000..68aeec0e4 --- /dev/null +++ b/src/test/node/webRDocumentReplay.test.ts @@ -0,0 +1,92 @@ +import * as assert from 'node:assert/strict'; +import type { Message } from 'vscode-jsonrpc'; +import { LanguageDocuments } from '../../webr/languageDocuments'; + +suite('webR package context document replay', () => { + test('restores only open buffers with their latest versions and UTF-16 changes', async () => { + const state = new LanguageDocuments(); + const open = (uri: string, text: string) => ({ + jsonrpc: '2.0', + method: 'textDocument/didOpen', + params: { textDocument: { uri, text, languageId: 'r', version: 1 } }, + }); + const init = { jsonrpc: '2.0', id: 0, method: 'initialize', params: { rootUri: null } }; + const ready = { jsonrpc: '2.0', method: 'initialized', params: {} }; + const config = { + jsonrpc: '2.0', + method: 'workspace/didChangeConfiguration', + params: { settings: { diagnostics: false } }, + }; + const uri = 'untitled:unsaved'; + const change = (version: number, text: string) => ({ + jsonrpc: '2.0', + method: 'textDocument/didChange', + params: { + textDocument: { uri, version }, + contentChanges: [ + { + range: { start: { line: 0, character: 2 }, end: { line: 0, character: 3 } }, + text, + }, + ], + }, + }); + for (const message of [ + init, + ready, + config, + open(uri, '😀x\r\ny'), + open('untitled:closed', 'discarded'), + change(3, 'edited'), + change(2, 'stale'), + { + jsonrpc: '2.0', + method: 'textDocument/didClose', + params: { textDocument: { uri: 'untitled:closed' } }, + }, + ]) { + state.record(message); + } + const sent: Message[] = []; + await state.replay((message) => { + sent.push(message); + return Promise.resolve([]); + }); + const expected = open(uri, '😀edited\r\ny'); + expected.params.textDocument.version = 3; + assert.deepEqual(sent, [init, ready, config, expected]); + }); + test('restores the current workspace folders after a package worker replacement', async () => { + const state = new LanguageDocuments(); + const a = { name: 'old', uri: 'file:///old' }; + const b = { name: 'new', uri: 'file:///new' }; + state.record({ + jsonrpc: '2.0', + id: 3, + method: 'initialize', + params: { rootUri: a.uri, capabilities: {} }, + } as Message); + const change = (added: (typeof a)[], removed: (typeof a)[]) => + state.record({ + jsonrpc: '2.0', + method: 'workspace/didChangeWorkspaceFolders', + params: { event: { added, removed } }, + } as Message); + const read = async () => { + const sent: Message[] = []; + await state.replay((message) => { + sent.push(message); + return Promise.resolve([]); + }); + return ( + sent[0] as Message & { + params: { rootUri: string | null; workspaceFolders: (typeof a)[] }; + } + ).params; + }; + change([b], [a]); + assert.deepEqual(await read(), { rootUri: b.uri, workspaceFolders: [b], capabilities: {} }); + change([], [b]); + assert.deepEqual(await read(), { rootUri: null, workspaceFolders: [], capabilities: {} }); + }); +}); diff --git a/src/test/node/webRPackageBuild.test.ts b/src/test/node/webRPackageBuild.test.ts new file mode 100644 index 000000000..2748431b7 --- /dev/null +++ b/src/test/node/webRPackageBuild.test.ts @@ -0,0 +1,69 @@ +import * as assert from 'node:assert/strict'; +import { cp, mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { gunzipSync, gzipSync } from 'node:zlib'; +import type { WebR } from 'webr'; +import { prepareNodeWebR } from '../../webr/nodeRuntime'; +import { packageDigest } from '../../webr/packageContext'; +import { + capturePackageImage, + packageImageBootstrap, + privatePackageDigest, + sessionPackageDigest, +} from '../../webr/packageImage'; +import { prepareWebRViewers } from '../../webr/viewers'; + +suite('webR private namespace build identity', function () { + this.timeout(30000); + test('uses exact installed file contents across library paths, compression levels and same-version rebuilds', async () => { + const root = await mkdtemp(path.join(tmpdir(), 'r-namespace-')); + let runtime: WebR | undefined; + try { + const baseUrl = await prepareNodeWebR(root, (stage) => + cp(path.dirname(require.resolve('webr')), stage, { recursive: true }), + ); + const { WebR: Runtime } = await import('webr'); + runtime = new Runtime({ baseUrl, interactive: false }); + await runtime.init(); + await runtime.FS.mkdir('/tmp/vscode-r-interactive'); + await prepareWebRViewers(runtime); + await runtime.evalRVoid('webr::eval_js(script)', { + env: { script: packageImageBootstrap }, + }); + await runtime.evalRVoid(` + dir.create("/installed") + stopifnot(file.copy(getNamespaceInfo(asNamespace("jsonlite"),"path"), "/installed", recursive=TRUE)) + `); + const pkg = { + name: 'jsonlite', + version: 'same', + path: '/installed/jsonlite', + stamp: '', + }; + const expected = await privatePackageDigest(runtime, pkg.name); + const original = await capturePackageImage(runtime, pkg); + const zip = new Uint8Array(gzipSync(gunzipSync(original), { level: 1 })); + const id = await packageDigest(zip, globalThis.crypto); + assert.equal(await sessionPackageDigest(zip, id), expected); + await assert.rejects( + sessionPackageDigest(zip, '0'.repeat(64)), + /Invalid webR session package image/, + ); + await runtime.evalRVoid( + 'writeLines("export(altered)", "/installed/jsonlite/NAMESPACE")', + ); + const rebuilt = await capturePackageImage(runtime, pkg); + assert.notEqual( + await sessionPackageDigest( + rebuilt, + await packageDigest(rebuilt, globalThis.crypto), + ), + expected, + ); + } finally { + runtime?.close(); + await rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/src/test/node/webRPackageImage.test.ts b/src/test/node/webRPackageImage.test.ts new file mode 100644 index 000000000..189500141 --- /dev/null +++ b/src/test/node/webRPackageImage.test.ts @@ -0,0 +1,139 @@ +import * as assert from 'node:assert/strict'; +import { webcrypto } from 'node:crypto'; +import * as path from 'node:path'; +import type { WebR } from 'webr'; +import { + capturePackageImage, + mountPackageImage, + packageImageBootstrap, +} from '../../webr/packageImage'; +import { packageDigest } from '../../webr/packageContext'; +import { WebRPackageCapture } from '../../webr/packageCapture'; +import { prepareWebRViewers } from '../../webr/viewers'; +import { prepareNodeWebR } from '../../webr/nodeRuntime'; +import { cp, mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; + +suite('webR read-only package images', function () { + this.timeout(30000); + test('shares the exact bytes independently of later edits, with validated paths and digest', async () => { + const root = await mkdtemp(path.join(tmpdir(), 'r-image-')); + let runtime: WebR | undefined; + try { + const baseUrl = await prepareNodeWebR(root, (stage) => + cp(path.dirname(require.resolve('webr')), stage, { recursive: true }), + ); + const { WebR: Runtime } = await import('webr'); + runtime = new Runtime({ baseUrl, interactive: false }); + await runtime.init(); + await runtime.evalRVoid('webr::eval_js(script)', { + env: { script: packageImageBootstrap }, + }); + await runtime.evalRVoid(` + dir.create("/tmp/vscode-r-interactive") + dir.create("/session-library") + dir.create("/tmp/fixture/Meta", recursive=TRUE) + writeLines("Package: fixture","/tmp/fixture/DESCRIPTION") + saveRDS("metadata","/tmp/fixture/Meta/package.rds") + writeBin(as.raw(0:255),"/tmp/fixture/snapshot") + `); + const pkg = { name: 'fixture', version: '1.0', path: '/tmp/fixture', stamp: 'fixture' }; + const bytes = await capturePackageImage(runtime, pkg); + const archive = await packageDigest(bytes, webcrypto as Pick); + await assert.rejects( + mountPackageImage(runtime, { ...pkg, archive: '0'.repeat(64) }, bytes), + /invalid/i, + ); + await assert.rejects( + mountPackageImage(runtime, { ...pkg, name: '../outside', archive }, bytes), + /invalid/i, + ); + await runtime.evalRVoid('unlink("/tmp/fixture", recursive=TRUE)'); + await mountPackageImage(runtime, { ...pkg, archive }, bytes); + assert.deepEqual( + Array.from(await runtime.FS.readFile('/session-library/fixture/snapshot')), + Array.from({ length: 256 }, (_, i) => i), + ); + // Official webR package installs use a WORKERFS image. Its child + // nodes may lack .mount even though they belong to this package. + const mounted = await capturePackageImage(runtime, { + ...pkg, + path: '/session-library/fixture', + }); + assert.equal( + await packageDigest(mounted, webcrypto as Pick), + archive, + ); + await assert.rejects( + runtime.FS.writeFile('/session-library/fixture/snapshot', new Uint8Array([0])), + ); + } finally { + runtime?.close(); + await rm(root, { recursive: true, force: true }); + } + }); + test('keeps unrelated packages visible and detects same-version in-place rebuilds', async () => { + const root = await mkdtemp(path.join(tmpdir(), 'r-catalogue-')); + let runtime: WebR | undefined; + try { + const baseUrl = await prepareNodeWebR(root, (stage) => + cp(path.dirname(require.resolve('webr')), stage, { recursive: true }), + ); + const { WebR: Runtime } = await import('webr'); + runtime = new Runtime({ baseUrl, interactive: false }); + await runtime.init(); + await runtime.FS.mkdir('/tmp/vscode-r-interactive'); + await prepareWebRViewers(runtime); + const warnings: string[] = []; + const capture = new WebRPackageCapture( + runtime, + webcrypto as Pick, + (message) => warnings.push(message), + ); + await capture.start(); + await runtime.evalRVoid(` + dir.create("/testlib") + for (pkg in c("workingfixture","linkedfixture")) { + path <- file.path("/testlib", pkg) + dir.create(file.path(path, "Meta"), recursive=TRUE) + writeLines(c(paste("Package:", pkg), "Version: 1.0"), file.path(path,"DESCRIPTION")) + saveRDS(list(), file.path(path,"Meta","package.rds")) + writeLines("export(original)", file.path(path,"NAMESPACE")) + } + writeLines("outside", "/tmp/outside") + stopifnot(file.symlink("/tmp/outside","/testlib/linkedfixture/extra")) + .libPaths(c("/testlib", .libPaths())) + `); + const first = await capture.capture(); + const original = first?.context.packages.find( + (p) => p.name === 'workingfixture', + )?.archive; + assert.ok(original); + assert.equal( + first?.context.packages.find((p) => p.name === 'linkedfixture')?.unavailable, + true, + ); + assert.equal(first?.archives.size, 1); + assert.match(warnings[0], /linkedfixture/); + await runtime.evalRVoid( + 'writeLines("export(replacement)", "/testlib/workingfixture/NAMESPACE")', + ); + const changed = await capture.capture(); + const replacement = changed?.context.packages.find( + (p) => p.name === 'workingfixture', + )?.archive; + assert.ok(replacement && replacement !== original); + await runtime.evalRVoid('unlink("/testlib/workingfixture", recursive=TRUE)'); + const removed = await capture.capture(); + assert.ok(removed); + assert.equal( + removed.context.packages.some((p) => p.name === 'workingfixture'), + false, + ); + assert.equal(warnings.length, 1); + } finally { + runtime?.close(); + await rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/src/test/node/webRPackageStore.test.ts b/src/test/node/webRPackageStore.test.ts new file mode 100644 index 000000000..cbdf09ccc --- /dev/null +++ b/src/test/node/webRPackageStore.test.ts @@ -0,0 +1,68 @@ +import * as assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import * as fs from 'node:fs/promises'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { + DesktopWebRPackageSource, + DesktopWebRPackageStore, +} from '../../interactive/webRPackageStore'; +import type { WebRPackageContext } from '../../webr/packageContext'; + +suite('private desktop webR package snapshots', () => { + test('publishes only complete verified revisions and pins each worker to its own last observation', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'r-package-snapshot-')); + try { + const store = new DesktopWebRPackageStore(root, 'generation-a'); + const source = new DesktopWebRPackageSource(root, 'generation-a'); + const first = source.forWorker(), + second = source.forWorker(); + const bytes = new TextEncoder().encode('test package image'); + const digest = createHash('sha256').update(bytes).digest('hex'); + const initial: WebRPackageContext = { + libraryId: 'library', + revision: 1, + packages: [], + attached: [], + }; + store.stage(initial, new Map()); + await store.publish(); + source.update(1); + assert.deepEqual(first.current(), initial); + + const installed = { + ...initial, + revision: 2, + packages: [{ name: 'fixture', version: '1.0', archive: digest }], + }; + store.stage(installed, new Map([[digest, new Uint8Array([99])]])); + await assert.rejects(store.publish(), /invalid.*archive/i); + assert.deepEqual(second.current(), initial); + store.stage(installed, new Map([[digest, bytes]])); + await store.publish(); + source.update(2); + assert.deepEqual(first.current(), installed); + assert.deepEqual(await first.readArchive(digest), bytes); + + const removed = { ...initial, revision: 3 }; + store.stage(removed, new Map()); + await store.publish(); + source.update(3); + assert.deepEqual(second.current(), removed); + await assert.rejects(second.readArchive(digest), /unknown/i); + // A worker may still be asynchronously opening the previous revision. + assert.deepEqual(await first.readArchive(digest), bytes); + const content = path.join(root, 'generation-a', 'webr-packages', digest + '.gz'); + await fs.writeFile(content, 'unrelated contents'); + await assert.rejects(first.readArchive(digest), /checksum/i); + assert.deepEqual(first.current(), removed); + await assert.rejects(first.readArchive(digest), /unknown/i); + assert.throws( + () => new DesktopWebRPackageSource(root, '../another-session'), + /identifier/i, + ); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/src/test/suite/languageService.test.ts b/src/test/suite/languageService.test.ts index 5bd7d7499..01ce336d6 100644 --- a/src/test/suite/languageService.test.ts +++ b/src/test/suite/languageService.test.ts @@ -754,6 +754,7 @@ suite('Language service initialization cancellation', () => { : instance; return Promise.resolve([{ jsonrpc: '2.0', id: message.id, result }]); }, + refreshPackageContext: () => Promise.resolve(), close() {}, }); }); diff --git a/src/test/web/webR.cjs b/src/test/web/webR.cjs index 9c1890e20..f37c1f429 100644 --- a/src/test/web/webR.cjs +++ b/src/test/web/webR.cjs @@ -116,6 +116,80 @@ async function notebookLanguagePolicy(source, files) { } } +async function notebookPackageCompletion() { + // This document and the execution notebook use distinct language workers. + // All three completion checks come from normal VS Code commands, including + // while another cell blocks the execution worker. + const text = 'probe_ready <- TRUE\ndata.table::fr\nlibrary(data.t)\nsetDTthre'; + const probes = [ + {line:1, column:'data.table::fr'.length, label:'fread'}, + {line:2, column:'library(data.t'.length, label:'data.table'}, + {line:3, column:'setDTthre'.length, label:'setDTthreads'}, + ]; + const labels = async (document, context) => { + const result = await command('vscode.executeCompletionItemProvider', document.uri, new vscode.Position(context.line,context.column)); + return result?.items.map(item => typeof item.label === 'string' ? item.label : item.label.label) ?? []; + }; + const available = async doc => Promise.all(probes.map(async item => (await labels(doc,item)).includes(item.label))); + const scope = async (doc, expected) => { + await until(async () => { + const outline = await command('vscode.executeDocumentSymbolProvider', doc.uri); + if (!outline?.some(symbol=>symbol.name==='probe_ready')) {return false;} + const actual = await available(doc); + return actual.every((value,index) => value === expected[index]); + }, 'Incorrect package completions for '+doc.uri.toString()+', expected '+expected.join('/')); + }; + async function notebook() { + await command('r.interactive.new'); + const book = vscode.window.activeNotebookEditor?.notebook; + assert(book?.notebookType === 'r-interactive','No active webR notebook'); + const change = new vscode.WorkspaceEdit(); + change.set(book.uri,[vscode.NotebookEdit.insertCells(0,[ + new vscode.NotebookCellData(vscode.NotebookCellKind.Code,text,'r'), + ])]); + assert(await vscode.workspace.applyEdit(change),'Could not add completion probe to notebook'); + return book; + } + const a = await notebook(); + const input = a.cellAt(0).document; + await scope(input, [false,false,false]); + await command('r.runCommand','install.packages("data.table")'); + await scope(input, [true,true,false]); + // Use a computed package name. Static parsing of this cell alone cannot + // infer which package was put on the evaluation session's search path. + await command('r.runCommand','pkg <- paste("data", "table", sep="."); library(pkg, character.only=TRUE)'); + await scope(input,[true,true,true]); + await command('r.runCommand', 'detach(paste0("package:", pkg), character.only=TRUE)'); + await scope(input,[true,true,false]); + await command('r.runCommand','library(pkg, character.only=TRUE)'); + await scope(input,[true,true,true]); + + const b = await notebook(); + await scope(b.cellAt(0).document,[false,false,false]); + const project = (await editor(text)).document; + await scope(project,[false,false,false]); + + await vscode.window.showNotebookDocument(a); + if (globalThis.crossOriginIsolated && typeof SharedArrayBuffer !== 'undefined') { + const index = a.cellCount; + const busy = command('r.runCommand','cat("busy\\n"); repeat { Sys.sleep(0.05) }'); + try { + await until(()=>a.cellCount>index && stdout(a.cellAt(index)).includes('busy'),'Calculation did not start'); + const response = await Promise.race([ + available(input), + new Promise((_,reject)=>setTimeout(()=>reject(new Error('Completion waited on the execution worker')),8000)), + ]); + assert(response.every(Boolean),'Lost runtime package completions during calculation.'); + } finally { + await command('r.interactive.interrupt'); + await busy; + } + } + await command('r.interactive.restart'); + await scope(input,[false,false,false]); + console.log('Verified session-installed packages, attached exports, isolation and restart in browser completion.'); +} + exports.run = async () => { const files = testFiles(); try { @@ -226,6 +300,7 @@ exports.run = async () => { 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); + await notebookPackageCompletion(); console.log('Verified webR language features, R Interactive execution, files, and transcript reopening.'); } finally { await command('r.interactive.stopAll'); diff --git a/src/web/extension.ts b/src/web/extension.ts index 12884940a..dcc94afdf 100644 --- a/src/web/extension.ts +++ b/src/web/extension.ts @@ -14,7 +14,7 @@ import { BrowserLanguageService } from './languageService'; export async function activate(context: vscode.ExtensionContext): Promise { await vscode.commands.executeCommand('setContext', 'r.webExtension', true); const interactive = new BrowserInteractive(context); - context.subscriptions.push(interactive, new BrowserLanguageService(context)); + context.subscriptions.push(interactive, new BrowserLanguageService(context, interactive)); const runSource = async () => { const editor = vscode.window.activeTextEditor; diff --git a/src/web/interactive.ts b/src/web/interactive.ts index a3ddbcada..738442903 100644 --- a/src/web/interactive.ts +++ b/src/web/interactive.ts @@ -1,6 +1,7 @@ import * as vscode from 'vscode'; import { InteractiveSerializer } from '../interactive/notebook'; import { BrowserSession } from './session'; +import type { WebRPackageSource } from '../webr/packageContext'; import { exportFile, importFiles } from './files'; const notebookType = 'r-interactive'; @@ -21,6 +22,8 @@ export class BrowserInteractive implements vscode.Disposable { 'R (webR)', ); private readonly sessions = new Map(); + private readonly packageUpdates = new vscode.EventEmitter(); + readonly onDidChangePackages = this.packageUpdates.event; private readonly registrations: vscode.Disposable[]; private last?: vscode.NotebookDocument; private opening?: Promise; @@ -43,6 +46,7 @@ export class BrowserInteractive implements vscode.Disposable { this.controller.interruptHandler = (doc) => this.interrupt(doc); const messages = vscode.notebooks.createRendererMessaging('r-interactive-renderer'); this.registrations = [ + this.packageUpdates, messages.onDidReceiveMessage(async ({ editor, message: raw }) => { const message = raw as Record | undefined; if ( @@ -124,13 +128,32 @@ export class BrowserInteractive implements vscode.Disposable { )); } + packageSource(doc: vscode.NotebookDocument): WebRPackageSource { + // Resolve on every call: the language client may start before R does or + // remain open while the notebook replaces its execution worker. + return { + current: () => this.sessions.get(doc)?.packageContext, + readArchive: (digest) => { + const bytes = this.sessions.get(doc)?.readPackageArchive(digest); + if (!bytes) { + return Promise.reject( + new Error('The webR package is no longer available in this session.'), + ); + } + return Promise.resolve(bytes); + }, + }; + } + private session(doc: vscode.NotebookDocument): BrowserSession { if (this.disposed || doc.isClosed) { throw new Error('The R Interactive notebook is closed.'); } let session = this.sessions.get(doc); if (!session) { - session = new BrowserSession(this.controller, this.context.extensionUri, doc); + session = new BrowserSession(this.controller, this.context.extensionUri, doc, () => + this.packageUpdates.fire(doc), + ); this.sessions.set(doc, session); } return session; diff --git a/src/web/languageService.ts b/src/web/languageService.ts index 78cda191b..b5c369ff6 100644 --- a/src/web/languageService.ts +++ b/src/web/languageService.ts @@ -12,6 +12,7 @@ import { createWebRLanguageSession, type WebRLanguageSession } from '../webr/lan import { createWebRMessageTransports } from '../webr/messageTransports'; import { cachedWebRAssets } from '../webr/assetCache'; import { WEBR_BASE_URL } from '../webr/runtime'; +import type { BrowserInteractive } from './interactive'; /** The service provides one retry action for startup and worker failures. */ class WorkerLanguageClient extends LanguageClient { @@ -26,6 +27,7 @@ class WorkerLanguageClient extends LanguageClient { const interactiveType = 'r-interactive'; const rLanguages = ['r', 'rmd']; +const packageContextChanged = '$/webR/packageContextChanged'; interface ClientSlot { client: LanguageClient; @@ -49,7 +51,11 @@ function notebookSelector(notebook: vscode.NotebookDocument): DocumentFilter[] { function notebookSession(owner: vscode.Uri, session: WebRLanguageSession): WebRLanguageSession { return { close: () => session.close(), + refreshPackageContext: () => session.refreshPackageContext(), dispatch(message) { + if (Message.isNotification(message) && message.method === packageContextChanged) { + return session.refreshPackageContext().then(() => []); + } if (Message.isRequest(message) || Message.isNotification(message)) { const params = message.params as { textDocument?: { uri?: unknown } } | undefined; if (typeof params?.textDocument?.uri === 'string') { @@ -81,8 +87,21 @@ export class BrowserLanguageService implements vscode.Disposable { private stopping = Promise.resolve(); private nativePreferenceReported = false; - constructor(private readonly context: vscode.ExtensionContext) { + constructor( + private readonly context: vscode.ExtensionContext, + private readonly interactive: BrowserInteractive, + ) { this.listeners = [ + interactive.onDidChangePackages((notebook) => { + const slot = this.clients.get(notebook.uri.toString()); + if (slot?.client.isRunning()) { + void slot.client.sendNotification(packageContextChanged).catch((error) => { + if (this.clients.get(notebook.uri.toString()) === slot) { + this.output.appendLine(String(error)); + } + }); + } + }), vscode.workspace.onDidOpenTextDocument((doc) => { if (rLanguages.includes(doc.languageId)) { this.refresh(); @@ -187,10 +206,17 @@ export class BrowserLanguageService implements vscode.Disposable { key === 'source' ? 'r' : 'r:' + key, 'R Language Server', async () => { + const owner = + key === 'source' + ? undefined + : vscode.workspace.notebookDocuments.find( + (doc) => doc.uri.toString() === key, + ); const session = await createWebRLanguageSession({ baseUrl: WEBR_BASE_URL, signal: abort.signal, loadAsset: cachedWebRAssets(this.context), + packageSource: owner ? this.interactive.packageSource(owner) : undefined, }); const current = this.clients.get(key); if (abort.signal.aborted || current?.client !== client) { diff --git a/src/web/session.ts b/src/web/session.ts index 62eb8c7a7..7c9480706 100644 --- a/src/web/session.ts +++ b/src/web/session.ts @@ -3,6 +3,7 @@ import { ChannelType, WebR } from 'webr'; import { OutputQueue } from '../interactive/outputQueue'; import { WebRConsole, type WebRConsoleEvent } from '../webr/console'; import { WEBR_BASE_URL } from '../webr/runtime'; +import type { WebRPackageContext } from '../webr/packageContext'; import { sessionDirectory } from './files'; import { BrowserViewers } from './viewers'; import { webRWidgetHtml } from '../webr/widgetHtml'; @@ -32,6 +33,8 @@ export class BrowserSession implements vscode.Disposable { private readonly outputLimit = 1024 * 1024 * vscode.workspace.getConfiguration('r').get('interactive.maxOutputSizeMiB', 4); private closed = false; + private packageArchives = new Map>(); + private packages?: WebRPackageContext; private readonly lifetime = new AbortController(); readonly viewers: BrowserViewers; @@ -39,6 +42,7 @@ export class BrowserSession implements vscode.Disposable { private readonly controller: vscode.NotebookController, extension: vscode.Uri, doc: vscode.NotebookDocument, + private readonly packagesChanged: () => void, ) { this.viewers = new BrowserViewers(extension, doc, (method, params) => this.run(async () => { @@ -51,6 +55,22 @@ export class BrowserSession implements vscode.Disposable { ); } + get packageContext(): WebRPackageContext | undefined { + return this.packages; + } + + readPackageArchive(digest: string): Uint8Array | undefined { + return this.packageArchives.get(digest); + } + + private clearPackages(): void { + this.packageArchives.clear(); + if (this.packages) { + this.packages = undefined; + this.packagesChanged(); + } + } + // Queue file operations and submissions together. A stopped generation must // never execute work against a replacement session or a closed worker. run(operation: () => Promise): Promise { @@ -87,6 +107,10 @@ export class BrowserSession implements vscode.Disposable { (event) => this.onEvent(event), this.supportsInterrupt, (error) => { + if (this.closed || this.worker?.console !== session) { + return; + } + this.clearPackages(); this.failed = new Error( 'The webR worker ended. Restart the session to run more code.', { cause: error }, @@ -96,6 +120,7 @@ export class BrowserSession implements vscode.Disposable { const ready = session.start().catch((error: unknown) => { session.close(); if (this.worker?.console === session) { + this.clearPackages(); this.worker = undefined; } throw error; @@ -188,6 +213,29 @@ export class BrowserSession implements vscode.Disposable { } private onEvent(event: WebRConsoleEvent): void { + if (event.type === 'packageContext') { + if (this.closed || this.failed) { + return; + } + // Publish the inventory and its immutable bytes together. A language + // request can read this snapshot even while the next R cell is busy. + const retained = new Map>(); + for (const { archive } of event.context.packages) { + if (!archive) { + continue; + } + const bytes = event.archives.get(archive) ?? this.packageArchives.get(archive); + if (!bytes) { + // Keep the last complete generation if an incomplete delta arrives. + return; + } + retained.set(archive, bytes); + } + this.packageArchives = retained; + this.packages = event.context; + this.packagesChanged(); + return; + } if (event.type === 'viewer' && !this.closed) { const p = event.params; const view = vscode.workspace @@ -284,6 +332,7 @@ export class BrowserSession implements vscode.Disposable { dispose(): void { this.closed = true; + this.clearPackages(); if (this.current) { this.current.input.cancel(); this.current.output.dispose(); diff --git a/src/webr/console.ts b/src/webr/console.ts index baac33e1b..2d57be881 100644 --- a/src/webr/console.ts +++ b/src/webr/console.ts @@ -1,4 +1,6 @@ import type { WebR } from 'webr'; +import { WebRPackageCapture } from './packageCapture'; +import type { WebRPackageContextEvent } from './packageContext'; import { consoleRunner } from './consoleRunner'; import { inspectWebRViewer, prepareWebRViewers } from './viewers'; import { checkHtmlSize, type HtmlBundle, validateHtmlBundle } from '../interactive/htmlBundle'; @@ -6,6 +8,7 @@ import { checkHtmlSize, type HtmlBundle, validateHtmlBundle } from '../interacti export type WebRConsoleResult = 'success' | 'error' | 'interrupted'; export type WebRConsoleEvent = + | WebRPackageContextEvent | { type: 'stream'; channel: 'stdout' | 'stderr'; text: string } | { type: 'started' } | { type: 'input'; prompt: string } @@ -35,13 +38,22 @@ export class WebRConsole { private active?: Cell; private sequence = 0; private closed = false; + private readonly packages: WebRPackageCapture; + private packageError?: string; constructor( private readonly runtime: WebR, private readonly onEvent: (event: WebRConsoleEvent) => void, private readonly supportsInterrupt: boolean, private readonly onExit?: (error?: Error) => void, - ) {} + crypto: Pick = globalThis.crypto, + ) { + this.packages = new WebRPackageCapture(runtime, crypto, (message) => { + if (!this.closed) { + this.onEvent({ type: 'stream', channel: 'stderr', text: message + '\n' }); + } + }); + } async start(): Promise { await this.runtime.init(); @@ -58,6 +70,10 @@ export class WebRConsole { await this.runtime.FS.mkdir(root); await prepareWebRViewers(this.runtime); await this.runtime.evalRVoid(consoleRunner); + const initial = await this.packages.start(); + if (initial) { + this.onEvent(initial); + } void this.pump().catch((error) => this.end(error instanceof Error ? error : new Error(String(error))), ); @@ -326,6 +342,21 @@ export class WebRConsole { 'base::unlink(' + JSON.stringify(cell.directory) + ', recursive = TRUE)', ); } + try { + const update = await this.packages.capture(); + if (update) { + this.onEvent(update); + } + this.packageError = undefined; + } catch (error) { + const message = + 'Could not synchronize webR packages with the language server: ' + + String(error); + if (!this.closed && this.packageError !== message) { + this.packageError = message; + this.onEvent({ type: 'stream', channel: 'stderr', text: message + '\n' }); + } + } this.active = undefined; cell.resolve(cell.outcome); } else if (cell.phase === 'submitted') { diff --git a/src/webr/languageDocuments.ts b/src/webr/languageDocuments.ts new file mode 100644 index 000000000..b9d81db8d --- /dev/null +++ b/src/webr/languageDocuments.ts @@ -0,0 +1,121 @@ +import { + TextDocument, + type TextDocumentContentChangeEvent, +} from 'vscode-languageserver-textdocument'; +import { Message, type NotificationMessage, type RequestMessage } from 'vscode-jsonrpc'; + +/** Only the current open buffers and initialization settings survive analysis worker replacement. */ +export class LanguageDocuments { + private initialize?: RequestMessage; + private initialized?: NotificationMessage; + private configuration?: NotificationMessage; + private readonly documents = new Map(); + + clear(): void { + this.initialize = this.initialized = this.configuration = undefined; + this.documents.clear(); + } + + record(message: Message): void { + if (Message.isRequest(message) && message.method === 'initialize') { + this.initialize = message; + return; + } + if (!Message.isNotification(message)) { + return; + } + if (message.method === 'initialized') { + this.initialized = message; + return; + } + if (message.method === 'workspace/didChangeWorkspaceFolders' && this.initialize) { + type Folder = { uri: string; name: string }; + const params = this.initialize.params as { + workspaceFolders?: Folder[] | null; + rootUri?: string | null; + }; + const { event } = message.params as { event: { added: Folder[]; removed: Folder[] } }; + const initial = + params.workspaceFolders ?? + (params.rootUri ? [{ uri: params.rootUri, name: params.rootUri }] : []); + const folders = new Map(initial.map((folder) => [folder.uri, folder])); + for (const folder of event.removed) { + folders.delete(folder.uri); + } + for (const folder of event.added) { + folders.set(folder.uri, folder); + } + // Reinitialize with the current roots, including an explicitly empty + // workspace. Replaying an old root can mix symbols from unrelated folders. + this.initialize = { + ...this.initialize, + params: { + ...params, + workspaceFolders: [...folders.values()], + rootUri: folders.keys().next().value ?? null, + }, + }; + return; + } + if (message.method === 'workspace/didChangeConfiguration') { + this.configuration = message; + return; + } + const params = message.params as + | { + textDocument?: { uri: string; languageId: string; version: number; text: string }; + contentChanges?: TextDocumentContentChangeEvent[]; + text?: string; + } + | undefined; + const item = params?.textDocument; + if (!item) { + return; + } + const doc = this.documents.get(item.uri); + switch (message.method) { + case 'textDocument/didOpen': + this.documents.set( + item.uri, + TextDocument.create(item.uri, item.languageId, item.version, item.text), + ); + break; + case 'textDocument/didChange': + if (doc && item.version > doc.version && params?.contentChanges) { + TextDocument.update(doc, params.contentChanges, item.version); + } + break; + case 'textDocument/didSave': + if (doc && typeof params?.text === 'string') { + TextDocument.update(doc, [{ text: params.text }], doc.version); + } + break; + case 'textDocument/didClose': + this.documents.delete(item.uri); + break; + } + } + + async replay(dispatch: (message: Message) => Promise): Promise { + for (const message of [this.initialize, this.initialized, this.configuration]) { + if (message) { + await dispatch(message); + } + } + for (const doc of this.documents.values()) { + const open: NotificationMessage = { + jsonrpc: '2.0', + method: 'textDocument/didOpen', + params: { + textDocument: { + uri: doc.uri, + languageId: doc.languageId, + version: doc.version, + text: doc.getText(), + }, + }, + }; + await dispatch(open); + } + } +} diff --git a/src/webr/languageSession.ts b/src/webr/languageSession.ts index 78c80dc45..1630a2c94 100644 --- a/src/webr/languageSession.ts +++ b/src/webr/languageSession.ts @@ -1,85 +1,366 @@ import { WebR } from 'webr'; -import type { Message } from 'vscode-jsonrpc'; +import { Message } from 'vscode-jsonrpc'; import { downloadWebRAsset, type LoadWebRAsset } from './assets'; +import { LanguageDocuments } from './languageDocuments'; +import { + mountPackageImage, + packageImageBootstrap, + privatePackageDigest, + sessionPackageDigest, +} from './packageImage'; +import type { WebRPackageContext, WebRPackageSource, WebRSessionPackage } from './packageContext'; import packages from './packages.json'; import serverModules from './serverModules.json'; +const toolPackages = packages.map((asset) => asset.name); + export interface WebRLanguageSession { dispatch(message: Message): Promise; + refreshPackageContext(): Promise; close(): void; } -/** A language worker has its own package library and never shares the user's evaluation session. */ -export async function createWebRLanguageSession(options: { +interface LanguageSessionOptions { baseUrl: string; signal?: AbortSignal; loadAsset?: LoadWebRAsset; -}): Promise { - const { signal, loadAsset = downloadWebRAsset } = options; + packageSource?: WebRPackageSource; +} + +async function sendToWorker(runtime: WebR, message: Message): Promise { + const json = await runtime.evalRString( + 'as.character(jsonlite::toJSON(dispatch_lsp(packet), auto_unbox = FALSE))', + { env: { packet: JSON.stringify(message) } }, + ); + return (JSON.parse(json) as string[]).map((reply) => JSON.parse(reply) as Message); +} + +/** Run code analysis independently, sharing only an immutable view of the owning console's packages. */ +export async function createWebRLanguageSession( + options: LanguageSessionOptions, +): Promise { + const { signal, loadAsset = downloadWebRAsset, packageSource } = options; signal?.throwIfAborted(); - const runtime = new WebR({ baseUrl: options.baseUrl, interactive: false }); const lifetime = new AbortController(); - const close = () => { - if (!lifetime.signal.aborted) { - lifetime.abort(); + const owned = new Set(); + const documents = new LanguageDocuments(); + // A user package with another build of a pinned namespace cannot be loaded + // alongside it. Its name remains visible, with metadata marked unavailable. + const reserved = new Set(toolPackages); + const privateDigests = new Map(); + // Keep at most one comparison per reserved name, including across worker + // replacement. The verified compressed digest identifies the session image. + const comparisons = new Map(); + const digestWorkers = new WeakSet(); + + async function unavailablePackages( + runtime: WebR, + context: WebRPackageContext, + ): Promise { + const missing: string[] = []; + for (const pkg of context.packages) { + if (pkg.unavailable) { + missing.push(pkg.name); + continue; + } + if (!pkg.archive || !reserved.has(pkg.name) || !packageSource) { + continue; + } + let result = comparisons.get(pkg.name); + if (result?.archive !== pkg.archive) { + let expected = privateDigests.get(pkg.name); + if (expected === undefined) { + if (!digestWorkers.has(runtime)) { + await runtime.evalRVoid('webr::eval_js(script)', { + env: { script: packageImageBootstrap }, + }); + digestWorkers.add(runtime); + } + // The distribution can contain lazy data or unsupported links. + // If its canonical image is unavailable, only this namespace is hidden. + expected = await privatePackageDigest(runtime, pkg.name).catch(() => null); + lifetime.signal.throwIfAborted(); + privateDigests.set(pkg.name, expected); + } + const matches = + expected !== null && + (await sessionPackageDigest( + await packageSource.readArchive(pkg.archive), + pkg.archive, + )) === expected; + result = { archive: pkg.archive, matches }; + comparisons.set(pkg.name, result); + } + if (!result.matches) { + missing.push(pkg.name); + } + } + return missing; + } + + let queue = Promise.resolve(); + let shutdown = false; + function release(runtime: WebR) { + if (owned.delete(runtime)) { runtime.close(); } - }; - signal?.addEventListener('abort', close, { once: true }); - try { - await runtime.init(); - await runtime.FS.mkdir('/language-library'); - // Keep peak memory bounded while downloading packages concurrently. - for (let first = 0; first < packages.length; first += 4) { - const batch = await Promise.all( - packages.slice(first, first + 4).map(async (asset) => ({ - bytes: await loadAsset(asset, lifetime.signal), - })), - ); - for (const { bytes } of batch) { - await runtime.FS.writeFile('/tmp/pkg.tgz', bytes); - await runtime.evalRVoid( - 'utils::untar("/tmp/pkg.tgz", exdir = "/language-library", tar = "internal")', - ); + } + function close() { + lifetime.abort(); + documents.clear(); + for (const runtime of owned) { + release(runtime); + } + } + + async function unmount(runtime: WebR, paths: string[]) { + for (const path of paths) { + await runtime.FS.unmount(path); + await runtime.FS.rmdir(path); + } + } + + async function mount(runtime: WebR, entries: WebRSessionPackage[]): Promise { + const added: string[] = []; + try { + for (const pkg of entries) { + if (!pkg.archive || !packageSource || pkg.unavailable || reserved.has(pkg.name)) { + continue; + } + lifetime.signal.throwIfAborted(); + await mountPackageImage(runtime, pkg, await packageSource.readArchive(pkg.archive)); + added.push('/session-library/' + pkg.name); } + } catch (error) { + await unmount(runtime, added); + throw error; + } + return added; + } + + async function setContext(runtime: WebR, context: WebRPackageContext | undefined) { + if (!packageSource) { + return; } - await runtime.FS.unlink('/tmp/pkg.tgz'); - await runtime.evalRVoid('.libPaths(c("/language-library", .libPaths()))'); - if ( - await runtime.evalRBoolean('"run_embedded" %in% getNamespaceExports("languageserver")') - ) { - await runtime.evalRVoid('server_api <- asNamespace("languageserver")'); + if (context) { + const unavailable = await unavailablePackages(runtime, context); + await runtime.evalRVoid( + 'assign("session_context", lapply(jsonlite::fromJSON(context), as.character), envir=.GlobalEnv)', + { + env: { + context: JSON.stringify({ + installed: context.packages.map((pkg) => pkg.name), + attached: context.attached, + unavailable, + revision: context.libraryId + ':' + context.revision, + }), + }, + }, + ); } else { - // Compatibility for the pinned 0.3.22 Wasm build, which predates run_embedded(). await runtime.evalRVoid( - 'server_api <- new.env(parent = asNamespace("languageserver"))', + 'session_context <- list(installed=.packages(all.available=TRUE, lib.loc=.Library), attached=.packages())', ); - for (const asset of serverModules) { - await runtime.FS.writeFile( - '/tmp/server.R', - await loadAsset(asset, lifetime.signal), + } + } + + async function startWorker(context: WebRPackageContext | undefined): Promise { + lifetime.signal.throwIfAborted(); + const runtime = new WebR({ baseUrl: options.baseUrl, interactive: false }); + owned.add(runtime); + try { + await runtime.init(); + await runtime.FS.mkdir('/language-library'); + // Bound peak memory while preparing language tooling. Each package is checksum verified. + for (let first = 0; first < packages.length; first += 4) { + const batch = await Promise.all( + packages + .slice(first, first + 4) + .map((asset) => loadAsset(asset, lifetime.signal)), ); - await runtime.evalRVoid('sys.source("/tmp/server.R", envir = server_api)'); + for (const bytes of batch) { + await runtime.FS.writeFile('/tmp/pkg.tgz', bytes); + await runtime.evalRVoid( + 'utils::untar("/tmp/pkg.tgz", exdir="/language-library", tar="internal")', + ); + } } - } - await runtime.evalRVoid('dispatch_lsp <- server_api$run_embedded()'); - signal?.throwIfAborted(); - return { - async dispatch(message) { - const json = await runtime.evalRString( - 'as.character(jsonlite::toJSON(dispatch_lsp(packet), auto_unbox = FALSE))', - { - env: { packet: JSON.stringify(message) }, - }, + await runtime.FS.unlink('/tmp/pkg.tgz'); + await runtime.evalRVoid('.libPaths(c("/language-library", .libPaths()))'); + if (packageSource) { + // Additional dependencies such as jsonlite and withr can first be + // used after initialization. Resolve them all against our pinned + // library while the user's package images are still invisible. + await runtime.evalRVoid( + 'invisible(lapply(names, loadNamespace, lib.loc="/language-library"))', + { env: { names: toolPackages } }, + ); + const loaded = await runtime.evalRString( + 'paste(loadedNamespaces(), collapse="\\n")', + ); + for (const name of loaded.split('\n')) { + reserved.add(name); + } + } + await runtime.FS.mkdir('/session-library'); + await mount(runtime, context?.packages ?? []); + await runtime.evalRVoid('.libPaths(c("/session-library", .libPaths()))'); + // Prefer an integrated, compatible published API. The current pinned Wasm binary + // predates it, so development builds pair its providers with verified upstream modules. + const exported = await runtime.evalRBoolean( + '"run_embedded" %in% getNamespaceExports(loadNamespace("languageserver", lib.loc="/language-library"))' + + ' && "package_context" %in% names(formals(languageserver::run_embedded))', + ); + if (exported) { + await runtime.evalRVoid('server_api <- asNamespace("languageserver")'); + } else { + await runtime.evalRVoid( + 'server_api <- new.env(parent=asNamespace("languageserver"))', ); - return (JSON.parse(json) as string[]).map((reply) => JSON.parse(reply) as Message); - }, - close, - }; + for (const asset of serverModules) { + await runtime.FS.writeFile( + '/tmp/server.R', + await loadAsset(asset, lifetime.signal), + ); + await runtime.evalRVoid('sys.source("/tmp/server.R", envir=server_api)'); + } + } + await setContext(runtime, context); + const argumentsR = packageSource ? 'package_context=function() session_context' : ''; + await runtime.evalRVoid('dispatch_lsp <- server_api$run_embedded(' + argumentsR + ')'); + lifetime.signal.throwIfAborted(); + return runtime; + } catch (error) { + release(runtime); + throw error; + } + } + + signal?.addEventListener('abort', close, { once: true }); + let applied = packageSource?.current(); + let runtime: WebR; + try { + try { + runtime = await startWorker(applied); + } catch (error) { + const latest = packageSource?.current(); + if ( + lifetime.signal.aborted || + (latest?.libraryId === applied?.libraryId && latest?.revision === applied?.revision) + ) { + throw error; + } + applied = latest; + runtime = await startWorker(applied); + } } catch (error) { close(); throw error; } finally { signal?.removeEventListener('abort', close); } + + async function applyContext(next: WebRPackageContext | undefined): Promise { + if (applied?.libraryId === next?.libraryId && applied?.revision === next?.revision) { + return; + } + const old = new Map(applied?.packages.map((p) => [p.name, p.archive])); + const current = new Map(next?.packages.map((p) => [p.name, p.archive])); + const additions = + next?.packages.filter( + (p) => p.archive && !p.unavailable && !reserved.has(p.name) && !old.has(p.name), + ) ?? []; + // R caches loaded namespace DLLs. Replacing/removing their files underneath a + // live worker can leave stale functions. Start the replacement before retiring it. + const replaced = + applied && + (applied.libraryId !== next?.libraryId || + applied.packages.some( + (p) => !current.has(p.name) || current.get(p.name) !== p.archive, + )); + const loadedAddition = + additions.length && + (await runtime.evalRBoolean( + 'any(unlist(names, use.names=FALSE) %in% loadedNamespaces())', + { env: { names: additions.map((p) => p.name) } }, + )); + if (replaced || loadedAddition) { + const replacement = await startWorker(next); + try { + await documents.replay((message) => sendToWorker(replacement, message)); + } catch (error) { + release(replacement); + throw error; + } + release(runtime); + runtime = replacement; + } else { + const added = await mount(runtime, additions); + try { + await setContext(runtime, next); + } catch (error) { + await unmount(runtime, added); + throw error; + } + } + applied = next; + } + async function synchronize(): Promise { + lifetime.signal.throwIfAborted(); + if (!packageSource || shutdown) { + return; + } + const requested = packageSource.current(); + try { + await applyContext(requested); + } catch (error) { + // A restart or removal can retire an image while the worker is mounting + // a previous catalogue. The old worker remains usable until a swap succeeds. + lifetime.signal.throwIfAborted(); + const latest = packageSource.current(); + if ( + latest?.libraryId === requested?.libraryId && + latest?.revision === requested?.revision + ) { + throw error; + } + await applyContext(latest); + } + } + + function serialized(operation: () => Promise): Promise { + const result = queue.then(operation); + queue = result.then( + () => undefined, + () => undefined, + ); + return result; + } + return { + dispatch(message) { + return serialized(async () => { + lifetime.signal.throwIfAborted(); + const method = 'method' in message ? message.method : undefined; + if (method === 'shutdown' || method === 'exit') { + shutdown = true; + } + if (method === '$/webR/packageContextChanged') { + await synchronize(); + return []; + } + // Ingest edits into the current worker before any potentially slow library + // update. The next request sees the new catalogue and the latest document. + if (Message.isRequest(message)) { + await synchronize(); + } + const result = await sendToWorker(runtime, message); + if (packageSource) { + documents.record(message); + } + return result; + }); + }, + refreshPackageContext: () => serialized(synchronize), + close, + }; } diff --git a/src/webr/messageTransports.ts b/src/webr/messageTransports.ts index c3295c644..5a9489ad2 100644 --- a/src/webr/messageTransports.ts +++ b/src/webr/messageTransports.ts @@ -3,7 +3,9 @@ import type { DataCallback, MessageReader, MessageWriter } from 'vscode-jsonrpc' import type { WebRLanguageSession } from './languageSession'; /** The same decoded JSON-RPC transport is used by the browser and Node language clients. */ -export function createWebRMessageTransports(session: WebRLanguageSession): { +export function createWebRMessageTransports( + session: Pick, +): { reader: MessageReader; writer: MessageWriter; } { diff --git a/src/webr/packageCapture.ts b/src/webr/packageCapture.ts new file mode 100644 index 000000000..b1798ed40 --- /dev/null +++ b/src/webr/packageCapture.ts @@ -0,0 +1,108 @@ +import type { WebR } from 'webr'; +import { + packageDigest, + type WebRPackageContextEvent, + type WebRSessionPackage, +} from './packageContext'; +import { + capturePackageImage, + packageImageBootstrap, + readExecutionLibrary, + type PackageLocation, +} from './packageImage'; + +/** Publish at a settled console boundary so editor requests never have to interrupt R. */ +export class WebRPackageCapture { + private readonly libraryId: string; + private readonly bundled = new Map(); + private published = new Map(); + private previous?: string; + private catalogue?: string; + private failures = new Map(); + private retryAt = 0; + private revision = 0; + + constructor( + private readonly runtime: WebR, + private readonly crypto: Pick, + private readonly warn?: (message: string) => void, + ) { + this.libraryId = crypto.randomUUID(); + } + + async start(): Promise { + await this.runtime.evalRVoid('webr::eval_js(script)', { + env: { script: packageImageBootstrap }, + }); + const state = await readExecutionLibrary(this.runtime); + for (const pkg of state.packages) { + this.bundled.set(pkg.name, this.identity(pkg)); + } + return this.capture(state); + } + + private identity(pkg: PackageLocation): string { + return JSON.stringify([pkg.path, pkg.version, pkg.stamp]); + } + + async capture( + state?: Awaited>, + ): Promise { + const { packages, attached } = state ?? (await readExecutionLibrary(this.runtime)); + const signature = JSON.stringify([packages, attached]); + if (signature === this.previous && (!this.failures.size || Date.now() < this.retryAt)) { + return; + } + const next = new Map(); + const archives = new Map>(); + const visible: WebRSessionPackage[] = []; + const failures = new Map(); + for (const pkg of packages) { + const identity = this.identity(pkg); + const entry: WebRSessionPackage = { name: pkg.name, version: pkg.version }; + if (this.bundled.get(pkg.name) !== identity) { + const old = this.published.get(pkg.name); + if (old?.identity === identity && old.archive) { + entry.archive = old.archive; + } else { + try { + const bytes = await capturePackageImage(this.runtime, pkg); + entry.archive = await packageDigest(bytes, this.crypto); + archives.set(entry.archive, bytes); + } catch (error) { + // A nonportable package must not conceal unrelated installs or removals. + entry.unavailable = true; + const message = String(error); + failures.set(pkg.name, message); + if (this.failures.get(pkg.name) !== message) { + this.warn?.( + `Cannot share the files of ${pkg.name} with the language server: ${message}`, + ); + } + } + } + } + visible.push(entry); + next.set(pkg.name, { identity, archive: entry.archive }); + } + this.published = next; + this.previous = signature; + this.failures = failures; + this.retryAt = Date.now() + 5000; + const catalogue = JSON.stringify([visible, attached]); + if (catalogue === this.catalogue) { + return; + } + this.catalogue = catalogue; + return { + type: 'packageContext', + context: { + libraryId: this.libraryId, + revision: ++this.revision, + packages: visible, + attached, + }, + archives, + }; + } +} diff --git a/src/webr/packageContext.ts b/src/webr/packageContext.ts new file mode 100644 index 000000000..79e4f98f3 --- /dev/null +++ b/src/webr/packageContext.ts @@ -0,0 +1,43 @@ +export interface WebRSessionPackage { + name: string; + version: string; + /** Digest of the immutable installed package image. Omitted for bundled R packages. */ + archive?: string; + /** Present on the search path, but its bytes could not be shared. */ + unavailable?: true; +} + +export interface WebRPackageContext { + libraryId: string; + revision: number; + packages: WebRSessionPackage[]; + /** First match wins, as in R's search(). */ + attached: string[]; +} + +export interface WebRPackageSource { + current(): WebRPackageContext | undefined; + readArchive(digest: string): Promise>; +} + +export type WebRPackageContextEvent = { + type: 'packageContext'; + context: WebRPackageContext; + archives: Map>; +}; + +export function isPackageName(name: unknown): name is string { + return typeof name === 'string' && /^[A-Za-z][A-Za-z0-9.]*$/.test(name); +} + +export function isArchiveDigest(digest: unknown): digest is string { + return typeof digest === 'string' && /^[a-f0-9]{64}$/.test(digest); +} + +export async function packageDigest( + bytes: Uint8Array, + crypto: Pick, +): Promise { + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); + return Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join(''); +} diff --git a/src/webr/packageImage.ts b/src/webr/packageImage.ts new file mode 100644 index 000000000..f7140e07a --- /dev/null +++ b/src/webr/packageImage.ts @@ -0,0 +1,265 @@ +import type { WebR } from 'webr'; +import { + isArchiveDigest, + isPackageName, + packageDigest, + type WebRSessionPackage, +} from './packageContext'; + +/** + * This helper runs synchronously inside R's Wasm worker. Inspect the effective + * library order, including packages installed as read-only WORKERFS images. + * Keep installed code and its data together; never traverse a link outside a package. + */ +export const packageImageBootstrap = String.raw`(() => { + const fs = globalThis.Module.FS; + const encoder = new TextEncoder(); + let descriptions = new Map(); + let bundled; + const packageName = /^[A-Za-z][A-Za-z0-9.]*$/; + function fileStamp(path) { + const stat = fs.stat(path); + return [stat.ino, stat.size, stat.mtime.getTime(), stat.ctime.getTime()].join(':'); + } + function packageStamp(path, name) { + const root = fs.stat(path); + const fields = [root.ino, fileStamp(path + '/DESCRIPTION'), fileStamp(path + '/Meta/package.rds')]; + if (bundled && bundled.get(path) !== root.ino) { + fields.push(fileStamp(path)); + // Detect in-place rebuilds of the same version, even when DESCRIPTION is preserved. + for (const relative of ['NAMESPACE', 'Meta/nsInfo.rds', 'R/' + name + '.rdx', + 'R/' + name + '.rdb', 'help/' + name + '.rdx', 'help/' + name + '.rdb', 'libs/' + name + '.so']) { + try { fields.push(fileStamp(path + '/' + relative)); } catch { fields.push(''); } + } + } + return fields.join(':'); + } + globalThis.Module.vscodeRPackageList = (paths, attached) => { + const found = new Map(); + const next = new Map(); + for (const lib of paths) { + for (const name of fs.readdir(lib)) { + if (!packageName.test(name) || found.has(name)) continue; + const path = lib.replace(/\/$/, '') + '/' + name; + let signature; + try { + signature = packageStamp(path, name); + } catch { + continue; // Lock directories and other incomplete installations. + } + let info = descriptions.get(path); + if (info?.stamp !== signature) { + const dcf = fs.readFile(path + '/DESCRIPTION', {encoding: 'utf8'}); + if (dcf.match(/^Package:[ \t]*(.+)$/m)?.[1].trim() !== name) continue; + const version = dcf.match(/^Version:[ \t]*(.+)$/m)?.[1].trim(); + if (!version) continue; + // Reading can materialize lazy files in the bundled distribution. + fs.readFile(path + '/Meta/package.rds'); + info = {name, version, path, stamp: packageStamp(path, name)}; + } + found.set(name, info); // First match in .libPaths() wins. + next.set(path, info); + } + } + if (!bundled) bundled = new Map([...next.keys()].map(path => [path, fs.stat(path).ino])); + descriptions = next; + const packages = [...found.values()].sort((a,b) => a.name < b.name ? -1 : 1); + return JSON.stringify({packages, attached}); + }; + globalThis.Module.vscodeRWritePackageImage = (root, target) => { + const rootNode = fs.lookupPath(root, {follow: true}).node; + const base = fs.getPath(rootNode); + const entries = []; + // WORKERFS constructs children before Emscripten assigns the mount to + // its root. A child's own .mount can be absent. Walk resolved inode + // parents: foreign submounts end at their own self-parented root. + function belongsToPackage(node) { + while (node !== rootNode && node.parent !== node) node = node.parent; + return node === rootNode; + } + // Duplicate an internal linked file under its visible relative name. A link + // outside this package would copy data the user did not install as part of it. + const directories = [{absolute: base, prefix: '', parents: new Set([base])}]; + while (directories.length) { + const {absolute, prefix, parents} = directories.pop(); + for (const name of fs.readdir(absolute)) { + if (name === '.' || name === '..') continue; + const relative = prefix + name; + const node = fs.lookupPath(absolute + '/' + name, {follow: true}).node; + const path = fs.getPath(node); + if (!belongsToPackage(node)) { + throw Error('Cannot share a link or mount outside the installed R package: ' + relative); + } + if (fs.isDir(node.mode)) { + if (parents.has(path)) throw Error('Cyclic package directory: ' + relative); + directories.push({absolute: path, prefix: relative + '/', parents: new Set([...parents, path])}); + } else if (fs.isFile(node.mode)) { + entries.push({relative, path, size: fs.stat(path).size}); + } else { + throw Error('Cannot share a special file in an R package: ' + relative); + } + } + } + entries.sort((a,b) => a.relative < b.relative ? -1 : 1); + const header = encoder.encode(JSON.stringify(entries.map(e => [e.relative, e.size]))); + const bytes = new Uint8Array(4 + header.length + entries.reduce((n,e) => n + e.size, 0)); + new DataView(bytes.buffer).setUint32(0, header.length, true); + bytes.set(header, 4); + let offset = 4 + header.length; + for (const {relative, path, size} of entries) { + const data = fs.readFile(path); + if (data.length !== size) throw Error('R package changed while being shared: ' + relative); + bytes.set(data, offset); + offset += size; + } + fs.writeFile(target, bytes, {canOwn: true}); + return null; + }; + return null; +})()`; + +export interface PackageLocation extends WebRSessionPackage { + path: string; + stamp: string; +} + +export async function readExecutionLibrary( + runtime: WebR, +): Promise<{ packages: PackageLocation[]; attached: string[] }> { + const result = + await runtime.evalRString(`webr::eval_js(paste0("globalThis.Module.vscodeRPackageList(", + jsonlite::toJSON(base::.libPaths()), ",", jsonlite::toJSON(base::.packages()), ")"))`); + return JSON.parse(result) as { packages: PackageLocation[]; attached: string[] }; +} + +/** The image excludes mtimes and compression headers. It contains sorted relative + * names, exact lengths, and every regular file byte in the installed directory. */ +async function readCanonicalPackage( + runtime: WebR, + path: string, + target: string, +): Promise> { + const script = `globalThis.Module.vscodeRWritePackageImage(${JSON.stringify(path)},${JSON.stringify(target)})`; + try { + await runtime.evalRVoid('webr::eval_js(script)', { env: { script } }); + return new Uint8Array(await runtime.FS.readFile(target)); + } finally { + await runtime.FS.unlink(target).catch(() => undefined); + } +} + +export async function capturePackageImage( + runtime: WebR, + pkg: PackageLocation, +): Promise> { + const bytes = await readCanonicalPackage( + runtime, + pkg.path, + '/tmp/vscode-r-interactive/package-image', + ); + return new Uint8Array( + await new Response( + new Blob([bytes]).stream().pipeThrough(new CompressionStream('gzip')), + ).arrayBuffer(), + ); +} + +/** Compare the private loaded namespace to a session image without loading its code. */ +export async function privatePackageDigest(runtime: WebR, name: string): Promise { + const path = await runtime.evalRString('getNamespaceInfo(asNamespace(name), "path")', { + env: { name }, + }); + const bytes = await readCanonicalPackage(runtime, path, '/tmp/vscode-r-private-package-image'); + return packageDigest(bytes, globalThis.crypto); +} + +/** Verify the transport digest before decompressing any session data. */ +async function decodePackageImage( + bytes: Uint8Array, + archive: string, +): Promise> { + if (!isArchiveDigest(archive) || (await packageDigest(bytes, globalThis.crypto)) !== archive) { + throw new Error('Invalid webR session package image.'); + } + return new Uint8Array( + await new Response( + new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip')), + ).arrayBuffer(), + ); +} + +export async function sessionPackageDigest( + bytes: Uint8Array, + archive: string, +): Promise { + return packageDigest(await decodePackageImage(bytes, archive), globalThis.crypto); +} + +/** Mount a checked, read-only copy of the exact package directory that R installed. */ +export async function mountPackageImage( + runtime: WebR, + pkg: WebRSessionPackage, + bytes: Uint8Array, +): Promise { + if (!isPackageName(pkg.name) || !pkg.archive) { + throw new Error('Invalid webR session package image.'); + } + const raw = await decodePackageImage(bytes, pkg.archive); + const length = new DataView(raw.buffer).getUint32(0, true); + const startOfData = 4 + length; + if (startOfData > raw.length) { + throw new Error('Truncated webR package index.'); + } + const entries: unknown = JSON.parse( + new TextDecoder('utf-8', { fatal: true }).decode(raw.subarray(4, startOfData)), + ); + if (!Array.isArray(entries)) { + throw new Error('Invalid webR package index.'); + } + const files = []; + const seen = new Set(); + let offset = 0; + for (const entry of entries as unknown[]) { + if (!Array.isArray(entry) || entry.length !== 2) { + throw new Error('Invalid webR package entry.'); + } + const [file, size] = entry as unknown[]; + if ( + typeof file !== 'string' || + file.includes('\\') || + file.includes('\0') || + file + .split('/') + .some((part) => !part || part === '.' || part === '..' || part === '__proto__') || + typeof size !== 'number' || + !Number.isSafeInteger(size) || + size < 0 || + offset + size > raw.length - startOfData || + seen.has(file) + ) { + throw new Error('Invalid path or range in webR package image.'); + } + seen.add(file); + files.push({ filename: '/' + file, start: offset, end: offset + size }); + offset += size; + } + if ( + offset !== raw.length - startOfData || + !seen.has('DESCRIPTION') || + !seen.has('Meta/package.rds') + ) { + throw new Error('Incomplete webR session package image.'); + } + const path = '/session-library/' + pkg.name; + await runtime.FS.mkdir(path); + try { + await runtime.FS.mount( + 'WORKERFS', + { packages: [{ metadata: { files }, blob: raw.subarray(startOfData) }] }, + path, + ); + } catch (error) { + await runtime.FS.rmdir(path); + throw error; + } +} diff --git a/src/webr/serverModules.json b/src/webr/serverModules.json index 66d4d7bb3..50da46232 100644 --- a/src/webr/serverModules.json +++ b/src/webr/serverModules.json @@ -1,37 +1,37 @@ [ { "name": "workspace.R", - "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/8afd6768773640648f92cc083425c6b17ad44f23/R/workspace.R", - "sha256": "35c0e4b2220e4976b296333cce14f0c1d1f1c860f45f0d5788acdcdd264bfb1e" + "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/d6d6faf42d0c16a417ea5621b236657aade9db2a/R/workspace.R", + "sha256": "1b625bc4a110807241083bec33fd23bd4994f24c4370d1cc1743b0b112745fda" }, { "name": "source-path-completion.R", - "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/8afd6768773640648f92cc083425c6b17ad44f23/R/source-path-completion.R", + "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/d6d6faf42d0c16a417ea5621b236657aade9db2a/R/source-path-completion.R", "sha256": "0c8864a76fc6ac4518b535fede6b3ccbbf8d68fa479565ca3111eeb880c575dd" }, { "name": "completion.R", - "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/8afd6768773640648f92cc083425c6b17ad44f23/R/completion.R", - "sha256": "63f644dae9cd6e8f4ea9a4baf89cad2ae517ebf2913f8f421c3d3fc97126f4d5" + "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/d6d6faf42d0c16a417ea5621b236657aade9db2a/R/completion.R", + "sha256": "057ab1ad73740cdebacc90b3afde15102d942edef32470e61acaae6fa4b1c974" }, { "name": "definition.R", - "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/8afd6768773640648f92cc083425c6b17ad44f23/R/definition.R", + "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/d6d6faf42d0c16a417ea5621b236657aade9db2a/R/definition.R", "sha256": "47f0adcb30954398c2027f78fa764c01dfe7f8f6a678dabd23a5359ea736846d" }, { "name": "glue-provider.R", - "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/8afd6768773640648f92cc083425c6b17ad44f23/R/glue-provider.R", + "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/d6d6faf42d0c16a417ea5621b236657aade9db2a/R/glue-provider.R", "sha256": "66f320e73289151bc9da9557246c0217b0153a54ac57b86cb86f5d000c83eb41" }, { "name": "backend-styler.R", - "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/8afd6768773640648f92cc083425c6b17ad44f23/R/backend-styler.R", + "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/d6d6faf42d0c16a417ea5621b236657aade9db2a/R/backend-styler.R", "sha256": "1f7c0a999e645662a7c1f700d840d5b42d19dd67a5ca861d7ee2a8f2369d5f5e" }, { "name": "embedded.R", - "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/8afd6768773640648f92cc083425c6b17ad44f23/R/embedded.R", - "sha256": "3c42f013ca3a9b075b47b26f48869760e26e0a6cb44071ac5f870166f6c3e1d2" + "url": "https://raw.githubusercontent.com/REditorSupport/languageserver/d6d6faf42d0c16a417ea5621b236657aade9db2a/R/embedded.R", + "sha256": "18cc000b2804cbee771c5cf03480baccb277e63f58909b3bb301c999260ff627" } ] diff --git a/website/docs/features/language-service.md b/website/docs/features/language-service.md index 6ec60caf0..93387ac22 100644 --- a/website/docs/features/language-service.md +++ b/website/docs/features/language-service.md @@ -31,10 +31,19 @@ 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. +completion, help and signatures for a bound webR notebook use read-only images +of its execution session’s installed packages. After `install.packages("data.table")`, +`library(data.t…)` and `data.table::` offer that package and its exports. +`library(data.table)` adds its attached names to unqualified completion. +The package context refreshes after a cell settles and stays available while the +next cell is busy. Each session has its own library and search order. Ordinary +source files keep the workspace context. The language worker keeps its own pinned +tooling and bootstrap namespaces. When a session uses the same installed build, its normal metadata is available. +If the session uses different contents under one of those names, or its files +cannot be mirrored, its name still completes in +`library()`. Package hover explains why namespace metadata is unavailable for +that build. The execution and analysis workers keep separate R objects. 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 @@ -265,6 +274,6 @@ 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 +serve requests while Interactive code is running. Bound notebooks share the +installed-package context of their own execution worker. 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 e704a80b1..9e0d8f5f8 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -131,7 +131,7 @@ External terminal output observed through the arf console bridge is retained in ### Language features -- **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) +- **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 language worker that reads the same installed package versions and follows the console’s attachment order after each completed cell. 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.