From f9710c4ca0580ebbb7c02e6e46939cb9121581c4 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 07:21:00 +0800 Subject: [PATCH 1/6] Open generation-scoped webR session files in VS Code --- package.json | 40 +- src/extension.ts | 4 +- src/interactive/agent.ts | 78 ++++ src/interactive/backend.ts | 2 + src/interactive/backends/webr.ts | 17 + src/interactive/manager.ts | 228 ++++++++++- src/interactive/sessionPresentation.ts | 24 +- src/interactive/webRFiles.ts | 241 +++++++++++ src/languageService.ts | 114 +++++- src/session.ts | 7 +- src/test/node/interactiveCore.test.ts | 1 + src/test/node/interactiveWebR.test.ts | 257 ++++++++++++ src/test/node/webRFileSystem.test.ts | 175 ++++++++ src/test/suite/interactiveEditor.test.ts | 263 +++++++++++- src/test/suite/languageService.test.ts | 93 +++++ src/test/suite/webRSessionFiles.test.ts | 75 ++++ src/webr/console.ts | 22 + src/webr/fileHooks.ts | 34 ++ src/webr/fileSystemWorker.ts | 375 +++++++++++++++++ src/webr/filesystem.ts | 163 ++++++++ src/webr/sessionFiles.ts | 498 +++++++++++++++++++++++ website/docs/features/r-interactive.md | 7 +- 22 files changed, 2661 insertions(+), 57 deletions(-) create mode 100644 src/interactive/webRFiles.ts create mode 100644 src/test/node/webRFileSystem.test.ts create mode 100644 src/test/suite/webRSessionFiles.test.ts create mode 100644 src/webr/fileHooks.ts create mode 100644 src/webr/fileSystemWorker.ts create mode 100644 src/webr/filesystem.ts create mode 100644 src/webr/sessionFiles.ts diff --git a/package.json b/package.json index d6a1e8d0c..a66665245 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,8 @@ "onWebviewPanel:r.htmlViewer", "onLanguage:r", "onLanguage:rmd", - "onNotebook:r-interactive" + "onNotebook:r-interactive", + "onFileSystem:vscode-r-webr" ], "main": "./dist/extension", "browser": "./dist/web-extension.js", @@ -903,6 +904,12 @@ "icon": "$(plug)", "enablement": "!r.webExtension" }, + { + "command": "r.interactive.openSessionFile", + "title": "Open webR Session File…", + "category": "R", + "icon": "$(folder-opened)" + }, { "command": "r.interactive.open", "title": "Open Interactive Session", @@ -1541,6 +1548,11 @@ } ], "view/item/context": [ + { + "command": "r.interactive.openSessionFile", + "when": "view == rInteractiveSessions && viewItem == rInteractiveSession.webR", + "group": "session@0" + }, { "command": "r.workspaceViewer.view", "group": "inline", @@ -1628,67 +1640,67 @@ }, { "command": "r.interactive.cleanAssets", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "maintenance@1" }, { "command": "r.interactive.history", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@0" }, { "command": "r.interactive.plots", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@1" }, { "command": "r.interactive.cancelQueued", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@2" }, { "command": "r.interactive.input", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@3" }, { "command": "r.interactive.takeControl", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@4" }, { "command": "r.interactive.rename", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@5" }, { "command": "r.interactive.info", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@6" }, { "command": "r.interactive.export", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@7" }, { "command": "r.interactive.detach", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@8" }, { "command": "r.interactive.restart", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/", "group": "session@9" }, { "command": "r.interactive.stop", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession && !listMultiSelection", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/ && !listMultiSelection", "group": "session@10" }, { "command": "r.interactive.stopSelected", - "when": "view == rInteractiveSessions && viewItem == rInteractiveSession && listMultiSelection", + "when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/ && listMultiSelection", "group": "session@11" } ], diff --git a/src/extension.ts b/src/extension.ts index 59e5ee6cb..a2efbe4d8 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,6 +1,7 @@ 'use strict'; // interfaces, functions, etc. provided by vscode +import { WebRSessionFiles } from './webr/sessionFiles'; import * as vscode from 'vscode'; import * as os from 'os'; import path = require('path'); @@ -280,7 +281,8 @@ export async function activate( // initialize the package/help related functions globalRHelp = await rHelp.initializeHelp(context, rExtension); - context.subscriptions.push(new InteractiveManager(context)); + const sessionFiles = new WebRSessionFiles(); + context.subscriptions.push(new InteractiveManager(context, sessionFiles), sessionFiles); // register codelens and completion providers for r markdown and r files const codeLensProvider = new rmarkdown.RMarkdownCodeLensProvider(); diff --git a/src/interactive/agent.ts b/src/interactive/agent.ts index e16dabd1e..a743baeb5 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -1,3 +1,5 @@ +import { WebRFileError } from '../webr/filesystem'; +import { WebRFileRequests } from './webRFiles'; import * as net from 'net'; import * as fs from 'fs'; import * as path from 'path'; @@ -63,6 +65,10 @@ export class SessionAgent { // Retain the last successful write only while the backend is starting. private startupManifest: string | undefined = ''; private backend: SessionBackend; + private readonly fileRequests = new WebRFileRequests(); + private fileQueue = Promise.resolve(); + private fileOperations = 0; + private fileLeaseRevision = 0; private unsubscribe: () => void; private servers: net.Server[] = []; private frontendRequests = new Map(); @@ -399,6 +405,7 @@ export class SessionAgent { socket.on('close', () => { clearTimeout(authTimer); this.clients.delete(client); + this.fileRequests.disconnect(client); if (this.manifest.status === 'exited' && !this.clients.size && !this.stopped) { this.closeAfterExit(true); } @@ -457,6 +464,14 @@ export class SessionAgent { !other.socket.destroyed, ) ) { + if (this.lease?.client !== client.id || this.lease.until < Date.now()) { + this.fileLeaseRevision++; + for (const previous of this.clients) { + if (previous.id === this.lease?.client) { + this.fileRequests.disconnect(previous); + } + } + } this.lease = { client: client.id, until: Date.now() + 60000 }; result = true; } else { @@ -678,6 +693,66 @@ export class SessionAgent { result = await this.backend.inspect(request); break; } + case 'webRFiles': { + const files = this.backend.webRFiles; + if ( + !files || + !this.backendReady || + this.stopping || + this.stopped || + this.current || + this.fileOperations >= 32 + ) { + throw new WebRFileError( + 'Unavailable', + 'The webR session is busy, closed, or does not support files.', + ); + } + this.fileOperations++; + const leaseRevision = this.fileLeaseRevision; + const operation = this.fileQueue.then(() => { + if ( + !this.clients.has(client) || + !this.backendReady || + this.stopping || + this.stopped + ) { + throw new WebRFileError('Unavailable', 'The webR session is unavailable.'); + } + return this.fileRequests.handle(client, files, params, () => { + if (!this.clients.has(client)) { + throw new WebRFileError('Unavailable', 'The client disconnected.'); + } + if (leaseRevision !== this.fileLeaseRevision) { + throw new WebRFileError( + 'NoPermissions', + 'Control changed during the webR file operation.', + ); + } + try { + this.requireControl(client); + } catch { + throw new WebRFileError( + 'NoPermissions', + 'Take control of the session to change its files.', + ); + } + }); + }); + this.fileQueue = operation.then( + () => {}, + () => {}, + ); + try { + result = await operation; + } finally { + this.fileOperations--; + if (!this.fileOperations) { + void this.pump(); + } + } + break; + } case 'asset': { result = this.assets.read(String(params.id), 2 * 1024 * 1024).toString('base64'); break; @@ -733,6 +808,8 @@ export class SessionAgent { case 'detach': client.subscribed = false; if (this.lease?.client === client.id) { + this.fileLeaseRevision++; + this.fileRequests.disconnect(client); this.lease = undefined; } break; @@ -1075,6 +1152,7 @@ export class SessionAgent { this.dispatching || this.closingHandles || this.redispatchTimer || + this.fileOperations || this.current || this.manifest.status === 'exited' || this.manifest.status === 'unknown' diff --git a/src/interactive/backend.ts b/src/interactive/backend.ts index c286dd1d0..faebfd142 100644 --- a/src/interactive/backend.ts +++ b/src/interactive/backend.ts @@ -1,3 +1,4 @@ +import type { WebRFileAccess } from '../webr/filesystem'; import type { HtmlBundle } from './htmlBundle'; import type { AgentSettings, Submission } from './protocol'; @@ -92,6 +93,7 @@ export type BackendEvent = ( ) & { executionId?: string }; export interface SessionBackend { + readonly webRFiles?: WebRFileAccess; readonly ownership: BackendOwnership; readonly capabilities: BackendCapabilities; onEvent(listener: (event: BackendEvent) => void): () => void; diff --git a/src/interactive/backends/webr.ts b/src/interactive/backends/webr.ts index a4f527f84..3b9046324 100644 --- a/src/interactive/backends/webr.ts +++ b/src/interactive/backends/webr.ts @@ -1,3 +1,4 @@ +import { createWebRFileAccess, type WebRFileAccess } from '../../webr/filesystem'; import { webcrypto } from 'node:crypto'; import { DesktopWebRPackageStore } from '../webRPackageStore'; import { WebRConsole, WebRConsoleEvent } from '../../webr/console'; @@ -7,8 +8,10 @@ import type { AgentSettings, Submission } from '../protocol'; /** An R runtime managed by the session agent's Node process. */ export class WebRBackend implements SessionBackend { readonly ownership = 'managed' as const; + webRFiles?: WebRFileAccess; readonly capabilities = { streaming: true, + webRFiles: true, stdin: true, debugger: false, tables: true, @@ -25,6 +28,7 @@ export class WebRBackend implements SessionBackend { private readonly listeners = new Set<(event: BackendEvent) => void>(); private console?: WebRConsole; private current?: string; + private openFiles: { path: string; create: boolean }[] = []; private inputId = 0; private stopped = false; private readonly packages: DesktopWebRPackageStore; @@ -74,6 +78,7 @@ export class WebRBackend implements SessionBackend { await runtime.FS.mkdir('/project'); await runtime.FS.mount('NODEFS', { root: this.settings.directory }, '/project'); await runtime.evalRVoid('base::setwd("/project")'); + this.webRFiles = createWebRFileAccess(runtime); const rVersion = await runtime.evalRString('R.version.string'); await this.publishPackages(); if (!this.stopped) { @@ -127,6 +132,9 @@ export class WebRBackend implements SessionBackend { case 'stream': this.emit({ ...event, executionId }); break; + case 'openFile': + this.openFiles.push({ path: event.path, create: event.create }); + break; case 'input': this.emit({ type: 'input', @@ -181,6 +189,15 @@ export class WebRBackend implements SessionBackend { this.current = undefined; if (!this.stopped) { this.emit({ type: 'finished', executionId: submission.id, state }); + // File operations may now use the idle worker. + for (const params of this.openFiles.splice(0)) { + this.emit({ + type: 'notification', + executionId: submission.id, + method: 'webR/openFile', + params, + }); + } } }, (error: unknown) => { diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 2e9688076..4090edc50 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1,4 +1,6 @@ import { DesktopWebRPackageSource } from './webRPackageStore'; +import { AgentWebRFileAccess } from './webRFiles'; +import { WEBR_FILE_SCHEME, sessionFileOwner, WebRSessionFiles } from '../webr/sessionFiles'; import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; @@ -65,7 +67,13 @@ import { queryTablePage } from './tableQuery'; import { tableColumnAlignment, tableDisplayValue, tableSnapshotSummary } from './tableFormatting'; import { HistoryPage, searchHistory } from './history'; import { readExecutionRecordsAsync, readPreviousJournalAsync } from './journal'; -import { sessionAge, sessionPresentation, sessionProcessLabel } from './sessionPresentation'; +import { + sessionAge, + sessionPresentation, + sessionProcessLabel, + sessionProviderLabel, + sessionTitle, +} from './sessionPresentation'; import { STOP_REQUEST_TIMEOUT_MS, runningSessions, @@ -86,6 +94,7 @@ interface InteractiveView { controller: vscode.NotebookController; controllers: vscode.NotebookController[]; inputUri?: vscode.Uri; + fileRegistration?: vscode.Disposable; executions: Map< string, { task: vscode.NotebookCellExecution; started: boolean; startTime?: number } @@ -140,6 +149,7 @@ export class InteractiveManager private messages = vscode.notebooks.createRendererMessaging('r-interactive-renderer'); private serializer = new InteractiveSerializer(); private root: string; + private restoringConnections?: Promise; private closed = false; private clientId: string; private savedConnections: Map; @@ -161,7 +171,10 @@ export class InteractiveManager >(); private status = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 20); - constructor(private context: vscode.ExtensionContext) { + constructor( + private context: vscode.ExtensionContext, + private sessionFiles?: WebRSessionFiles, + ) { // A restart replaces the transcript, invalidating pending formatting edits. this.disposables.push( new InteractiveInputFeatures( @@ -173,6 +186,10 @@ export class InteractiveManager )?.model, ), ); + if (this.sessionFiles) { + this.sessionFiles.waitForReconnect = (id, generation) => + this.opening.get(`${id}:${generation}`) ?? this.restoringConnections; + } this.root = util.config().get('interactive.storagePath') || defaultStorage(); this.clientId = randomUUID(); // Native Interactive tabs restore their URI, but discard notebook metadata. @@ -275,6 +292,56 @@ export class InteractiveManager command('r.interactive.history', (value) => this.forView(value, (view) => this.history(view)), ); + command('r.interactive.openSessionFile', async (value, selectedPath) => { + const files = this.sessionFiles; + if (!files) { + throw new Error('The webR session filesystem is unavailable.'); + } + const file = + typeof selectedPath === 'string' + ? selectedPath + : typeof value === 'string' + ? value + : undefined; + let owner = typeof value === 'string' ? undefined : value; + if (!owner && this.active?.client.manifest.provider !== 'webr') { + this.refresh(); + const webR = await runningSessions( + this.manifests.filter((session) => session.provider === 'webr'), + ); + if (!webR.length) { + throw new Error('Start a webR Interactive session to open a session file.'); + } + owner = + webR.length === 1 + ? webR[0] + : ( + await vscode.window.showQuickPick( + webR.map((manifest) => ({ + label: manifest.label, + description: this.sessionChoiceDescription(manifest), + manifest, + })), + { title: 'Open webR Session File' }, + ) + )?.manifest; + if (!owner) { + return; + } + } + return this.forView(owner, (view) => { + const { id, generation, provider, capabilities } = view.client.manifest; + if (provider !== 'webr') { + throw new Error('Choose a webR Interactive session to open its files.'); + } + if (!capabilities.webRFiles) { + throw new Error( + 'Restart this webR session with a current agent to open its files.', + ); + } + return files.open(id, generation, file); + }); + }); command('r.interactive.plots', (value) => this.forView(value, (view) => this.plots(view))); command('r.interactive.cancelQueued', (value) => this.forView(value, (view) => this.cancelQueued(view)), @@ -352,6 +419,15 @@ export class InteractiveManager ); this.status.name = 'R Interactive session'; this.status.command = 'r.interactive.connect'; + this.disposables.push( + vscode.workspace.onDidOpenTextDocument((document) => { + const owner = sessionFileOwner(document.uri); + const view = owner && this.views.get(`${owner.id}:${owner.generation}`); + if (view && !view.disposed) { + session.bindSessionDocument(document.uri, view.target); + } + }), + ); this.disposables.push(this.status); const ageTimer = setInterval(() => { this.changes.fire(undefined); @@ -461,7 +537,11 @@ export class InteractiveManager ); setInteractiveExecutor(async (code, resource, source, offerTarget) => { const mode = util.config(resource).get('interactive.executionTarget', 'auto'); - if (mode === 'terminal' || (!this.routing && mode !== 'interactive' && !offerTarget)) { + const sessionFile = resource?.scheme === WEBR_FILE_SCHEME; + if ( + !sessionFile && + (mode === 'terminal' || (!this.routing && mode !== 'interactive' && !offerTarget)) + ) { return false; } try { @@ -472,6 +552,20 @@ export class InteractiveManager ? [...this.views.values()].find((item) => item.target === bound) : this.active : undefined; + if (sessionFile) { + const owner = resource && sessionFileOwner(resource); + view = owner ? this.views.get(`${owner.id}:${owner.generation}`) : undefined; + if ( + !view || + view.disposed || + !view.client.connected || + ['exited', 'stopping'].includes(view.client.manifest.status) + ) { + throw new Error( + 'This file belongs to a webR session generation that is no longer connected.', + ); + } + } if (view?.restarting) { throw new Error( 'R is restarting. Wait for the restart notice before running code.', @@ -514,7 +608,9 @@ export class InteractiveManager }); this.refresh(); if (util.config().get('interactive.restore', true)) { - void this.restoreConnections(); + this.restoringConnections = this.restoreConnections().finally(() => { + this.restoringConnections = undefined; + }); } } @@ -690,7 +786,7 @@ export class InteractiveManager : manifest.status === 'input' ? 'question' : 'terminal'; - this.status.text = `$(${icon}) R: ${manifest.label} · ${state}${queued ? ` · ${queued} queued` : ''}${view.client.connected && !view.client.control ? ' · observing' : ''}`; + this.status.text = `$(${icon}) ${sessionTitle(manifest)} · ${state}${queued ? ` · ${queued} queued` : ''}${view.client.connected && !view.client.control ? ' · observing' : ''}`; this.status.tooltip = `${ sessionPresentation( manifest, @@ -740,6 +836,14 @@ export class InteractiveManager const actions = [ { label: '$(plug) Switch Session…', command: 'r.interactive.connect' }, { label: '$(add) New Session…', command: 'r.interactive.new' }, + ...(view.client.manifest.provider === 'webr' + ? [ + { + label: '$(folder-opened) Session Files…', + command: 'r.interactive.openSessionFile', + }, + ] + : []), { label: 'Session', kind: vscode.QuickPickItemKind.Separator }, { label: '$(edit) Rename…', command: 'r.interactive.rename' }, { label: '$(info) Session Details', command: 'r.interactive.info' }, @@ -1126,12 +1230,13 @@ export class InteractiveManager ); const item = new vscode.TreeItem(manifest.label); item.id = `${manifest.id}:${manifest.generation}`; - item.description = `${presentation.state} · ${manifest.provider}`; + item.description = `${presentation.state} · ${sessionProviderLabel(manifest)}`; const age = sessionAge(manifest); if (age) { item.description += ` · ${age}`; } - item.contextValue = 'rInteractiveSession'; + item.contextValue = + manifest.provider === 'webr' ? 'rInteractiveSession.webR' : 'rInteractiveSession'; if (view?.client.connected && !view.client.control) { item.description += ' · observing'; } @@ -1504,7 +1609,7 @@ export class InteractiveManager private sessionChoiceDescription(manifest: SessionManifest): string { const age = sessionAge(manifest); - return `${manifest.status} · ${manifest.provider} · ${sessionProcessLabel(manifest)}${age ? ` · ${age}` : ''}`; + return `${manifest.status} · ${sessionProviderLabel(manifest)} · ${sessionProcessLabel(manifest)}${age ? ` · ${age}` : ''}`; } private async pick(): Promise { @@ -1600,7 +1705,7 @@ export class InteractiveManager const controller = vscode.notebooks.createNotebookController( `r-${manifest.id}-${manifest.generation}-${type}`, type, - `R: ${manifest.label}`, + sessionTitle(manifest), ); controller.supportedLanguages = ['r']; controller.supportsExecutionOrder = true; @@ -1661,7 +1766,7 @@ export class InteractiveManager { viewColumn: vscode.ViewColumn.Beside, preserveFocus: true }, existing?.uri ?? (savedUri ? vscode.Uri.parse(savedUri) : undefined), `${this.context.extension.id}/${native.id}`, - `R: ${manifest.label}`, + sessionTitle(manifest), ); if (!result?.notebookUri || !result.inputUri) { throw new Error('Interactive Window returned no document'); @@ -1720,6 +1825,7 @@ export class InteractiveManager hidden: new Set(), }; this.views.set(key, view); + this.attachFiles(view); controller.updateNotebookAffinity( notebook, vscode.NotebookControllerAffinity.Preferred, @@ -1798,6 +1904,57 @@ export class InteractiveManager } } + private attachFiles(view: InteractiveView): void { + view.fileRegistration?.dispose(); + const { id, generation, provider, directory, capabilities } = view.client.manifest; + if (!this.sessionFiles || provider !== 'webr' || !capabilities.webRFiles) { + return; + } + let projectUri = vscode.Uri.file(directory); + for (const folder of vscode.workspace.workspaceFolders ?? []) { + const relative = path.relative(folder.uri.fsPath, directory); + if ( + relative !== '..' && + !relative.startsWith('..' + path.sep) && + !path.isAbsolute(relative) + ) { + projectUri = vscode.Uri.joinPath( + folder.uri, + ...relative.split(path.sep).filter(Boolean), + ); + break; + } + } + view.fileRegistration = this.sessionFiles.add({ + id, + generation, + get label() { + return view.client.manifest.label; + }, + initialDirectory: '/', + projectUri, + files: () => { + if ( + view.disposed || + !view.client.connected || + view.client.manifest.generation !== generation + ) { + return Promise.reject( + new Error('Reconnect to the owning webR session to access its files.'), + ); + } + return Promise.resolve(new AgentWebRFileAccess(view.client)); + }, + onOpen: (uri) => session.bindSessionDocument(uri, view.target), + }); + for (const doc of vscode.workspace.textDocuments) { + const owner = sessionFileOwner(doc.uri); + if (owner?.id === id && owner.generation === generation) { + session.bindSessionDocument(doc.uri, view.target); + } + } + } + private updateLanguageEnvironment(target: session.Session, manifest: SessionManifest): void { if (manifest.provider === 'webr' && manifest.capabilities.webRPackageContext) { target.webRPackageSource ??= new DesktopWebRPackageSource( @@ -1922,7 +2079,11 @@ export class InteractiveManager snapshot: AgentSnapshot, preserveDrafts: boolean, ): Promise { - const previousCells = preserveDrafts ? view.notebook.getCells() : []; + const previousCells = preserveDrafts + ? view.notebook + .getCells() + .filter((cell) => !restoredCellMetadata(cell.metadata).rWebRFileNotice) + : []; for (const { task } of view.executions.values()) { task.end(undefined); } @@ -1960,6 +2121,9 @@ export class InteractiveManager } const cells: vscode.NotebookCellData[] = []; for (const model of [...view.history, view.model]) { + if (snapshot.manifest.provider === 'webr') { + cells.push(this.webRFileNotice(model.generation)); + } for (const cell of model.cells.values()) { if (!view.hidden.has(cell.record.id)) { const data = await this.cellData(view, cell); @@ -2171,6 +2335,10 @@ export class InteractiveManager return; } const changed = view.model.apply(event); + if (event.type === 'finished') { + this.sessionFiles?.refresh(view.client.manifest.id, view.client.manifest.generation); + } + this.updateStatus(); if (event.type === 'state') { view.client.manifest.status = event.data.status as SessionManifest['status']; @@ -2272,6 +2440,23 @@ export class InteractiveManager if (event.data.method === 'jdv/rowCount') { applyJdvRowCount(view.target.sessionId, params); } + if ( + event.data.method === 'webR/openFile' && + view.client.control && + typeof params.path === 'string' && + view.client.manifest.provider === 'webr' + ) { + // Opening an editor can request the file through the same agent. + // Release event delivery before serving that filesystem request. + void this.sessionFiles + ?.open( + view.client.manifest.id, + view.client.manifest.generation, + params.path, + params.create === true, + ) + .catch((error) => this.report(error)); + } if (event.data.method === 'help') { await session.showHelpNotification(params); } @@ -3350,6 +3535,16 @@ export class InteractiveManager } } + private webRFileNotice(generation: string): vscode.NotebookCellData { + const cell = new vscode.NotebookCellData( + vscode.NotebookCellKind.Markup, + '**webR files** · `/project` is the project directory on the R host. Files in `/home/web_user` and `/tmp` disappear when this session stops or restarts. Use **R: Open webR Session File…** to open a file in VS Code.', + 'markdown', + ); + cell.metadata = persistentCellMetadata({ rWebRFileNotice: generation }, 'markdown'); + return cell; + } + private noticeData( view: InteractiveView, state: 'stopped' | 'restarting' | 'restarted' | 'restartFailed', @@ -3558,6 +3753,7 @@ export class InteractiveManager const target = this.registerTarget(view.client); session.replaceSessionTransport(view.target, target); view.target = target; + this.attachFiles(view); this.listen(view, view.client); await view.client.connect(); const deadline = Date.now() + 30000; @@ -3597,6 +3793,15 @@ export class InteractiveManager ]); await vscode.workspace.applyEdit(edit); await this.queueNotice(view, 'restarted', generation); + if (manifest.provider === 'webr') { + const notice = new vscode.WorkspaceEdit(); + notice.set(view.notebook.uri, [ + vscode.NotebookEdit.insertCells(view.notebook.cellCount, [ + this.webRFileNotice(manifest.generation), + ]), + ]); + await vscode.workspace.applyEdit(notice); + } if (view.model.cells.size) { const cells = await Promise.all( [...view.model.cells.values()].map((cell) => this.cellData(view, cell)), @@ -3797,6 +4002,7 @@ export class InteractiveManager } private disposeView(view: InteractiveView, forget = true): void { + view.fileRegistration?.dispose(); if (view.disposed) { return; } diff --git a/src/interactive/sessionPresentation.ts b/src/interactive/sessionPresentation.ts index 2f8bbf927..1d810680d 100644 --- a/src/interactive/sessionPresentation.ts +++ b/src/interactive/sessionPresentation.ts @@ -23,6 +23,21 @@ export function sessionProcessLabel(manifest: SessionManifest, pending = 'starti : `PID ${manifest.rPid ?? pending}`; } +const providers = { + r: { short: 'plain', title: 'R', name: 'Plain R' }, + arf: { short: 'arf', title: 'arf', name: 'Headless arf' }, + 'arf-existing': { short: 'arf (attached)', title: 'arf (attached)', name: 'Attached arf' }, + webr: { short: 'webR', title: 'webR', name: 'webR' }, +}; + +export function sessionProviderLabel(manifest: Pick): string { + return providers[manifest.provider].title; +} + +export function sessionTitle(manifest: Pick): string { + return sessionProviderLabel(manifest) + ': ' + manifest.label; +} + /** Public session details; never include connection credentials. */ export function sessionPresentation( manifest: SessionManifest, @@ -40,19 +55,14 @@ export function sessionPresentation( : manifest.status === 'input' ? 'waiting for input' : manifest.status; - const provider = { - r: { short: 'plain', name: 'Plain R' }, - arf: { short: 'arf', name: 'Headless arf' }, - 'arf-existing': { short: 'arf (attached)', name: 'Attached arf' }, - webr: { short: 'webR', name: 'webR' }, - }[manifest.provider]; + const provider = providers[manifest.provider]; const version = manifest.rVersion?.match(/^R version (\S+)/)?.[1]; const supervision = manifest.supervision === 'detached' ? 'Independent process' : manifest.supervision; const age = sessionAge(manifest); return { state, - label: `R: ${manifest.label} · ${state}`, + label: `${sessionTitle(manifest)} · ${state}`, // Description is inline (and doubles as the native button tooltip); detail // gets a second picker row. Neither supports arbitrary multiline content. description: `${version ? `R ${version}` : 'R'} · ${provider.short} · ${sessionProcessLabel(manifest, 'pending')}${age ? ` · ${age}` : ''}${connected && !control ? ' · observing' : ''}`, diff --git a/src/interactive/webRFiles.ts b/src/interactive/webRFiles.ts new file mode 100644 index 000000000..1825e63fd --- /dev/null +++ b/src/interactive/webRFiles.ts @@ -0,0 +1,241 @@ +import { randomUUID } from 'node:crypto'; +import { + WEBR_FILE_CHUNK, + WEBR_FILE_LIMIT, + WebRFileError, + type WebRFileAccess, + type WebRFileErrorCode, + type WebRFileStat, + type WebRFileType, + type WebRFileWriteOptions, +} from '../webr/filesystem'; +import type { AgentClient } from './client'; + +export class AgentWebRFileAccess implements WebRFileAccess { + constructor(private readonly client: AgentClient) {} + + private async request(params: Record): Promise { + try { + return await this.client.request('webRFiles', params); + } catch (error) { + const text = error instanceof Error ? error.message : String(error); + const match = + /WebRFileError\[(FileNotFound|FileExists|FileNotADirectory|FileIsADirectory|NoPermissions|Unavailable|FileModifiedSince)\]: (.*)/s.exec( + text, + ); + throw new WebRFileError( + (match?.[1] as WebRFileErrorCode) ?? 'Unavailable', + match?.[2] ?? text, + ); + } + } + + stat(path: string): Promise { + return this.request({ action: 'stat', path }); + } + readDirectory(path: string): Promise<[string, WebRFileType][]> { + return this.request({ action: 'readDirectory', path }); + } + async readFile(path: string): Promise<{ bytes: Uint8Array; version: string }> { + const result = await this.request<{ data: string; version: string }>({ + action: 'readFile', + path, + }); + return { bytes: Buffer.from(result.data, 'base64'), version: result.version }; + } + async writeFile( + path: string, + bytes: Uint8Array, + options: WebRFileWriteOptions, + ): Promise { + if (bytes.byteLength > WEBR_FILE_LIMIT) { + throw new WebRFileError('Unavailable', 'webR files are limited to 16 MiB.'); + } + const token = await this.request({ + action: 'beginWrite', + path, + size: bytes.byteLength, + ...options, + }); + try { + for (let offset = 0; offset < bytes.length; offset += WEBR_FILE_CHUNK) { + const data = Buffer.from( + bytes.buffer, + bytes.byteOffset + offset, + Math.min(WEBR_FILE_CHUNK, bytes.length - offset), + ).toString('base64'); + await this.request({ action: 'writeChunk', token, offset, data }); + } + return await this.request({ action: 'commitWrite', token }); + } catch (error) { + await this.request({ action: 'abortWrite', token }).catch(() => {}); + throw error; + } + } + createDirectory(path: string): Promise { + return this.request({ action: 'createDirectory', path }); + } + delete(path: string, options: { recursive: boolean }): Promise { + return this.request({ action: 'delete', path, ...options }); + } + rename(path: string, to: string, options: { overwrite: boolean }): Promise { + return this.request({ action: 'rename', path, to, ...options }); + } +} + +interface Upload { + owner: object; + path: string; + options: WebRFileWriteOptions; + bytes: Buffer; + offset: number; + timer: NodeJS.Timeout; +} + +/** Upload buffers belong to one authenticated connection, and never alter a + * worker file until commit. Large reads use the agent's existing message pages. + */ +export class WebRFileRequests { + private readonly uploads = new Map(); + private bytes = 0; + + private remove(token: string): void { + const upload = this.uploads.get(token); + if (upload) { + this.uploads.delete(token); + clearTimeout(upload.timer); + this.bytes -= upload.bytes.length; + } + } + disconnect(owner: object): void { + for (const [token, upload] of this.uploads) { + if (upload.owner === owner) { + this.remove(token); + } + } + } + + async handle( + owner: object, + files: WebRFileAccess, + params: Record, + requireControl: () => void, + ): Promise { + const path = typeof params.path === 'string' ? params.path : ''; + switch (params.action) { + case 'stat': + return files.stat(path); + case 'readDirectory': + return files.readDirectory(path); + case 'readFile': { + const { bytes, version } = await files.readFile(path); + return { + data: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString( + 'base64', + ), + version, + }; + } + } + requireControl(); + switch (params.action) { + case 'createDirectory': + await files.createDirectory(path); + return true; + case 'delete': + if (typeof params.recursive !== 'boolean') { + throw new WebRFileError('Unavailable', 'Invalid delete options.'); + } + await files.delete(path, { recursive: params.recursive }); + return true; + case 'rename': + if (typeof params.to !== 'string' || typeof params.overwrite !== 'boolean') { + throw new WebRFileError('Unavailable', 'Invalid rename options.'); + } + await files.rename(path, params.to, { overwrite: params.overwrite }); + return true; + case 'beginWrite': { + const { size, create, overwrite, expected } = params; + if ( + !path || + typeof size !== 'number' || + !Number.isSafeInteger(size) || + size < 0 || + size > WEBR_FILE_LIMIT || + typeof create !== 'boolean' || + typeof overwrite !== 'boolean' || + (expected !== undefined && + (typeof expected !== 'string' || expected.length > 512)) + ) { + throw new WebRFileError( + 'Unavailable', + 'Invalid webR upload or file exceeds 16 MiB.', + ); + } + if (this.uploads.size >= 4 || this.bytes + size > 2 * WEBR_FILE_LIMIT) { + throw new WebRFileError('Unavailable', 'Too many webR uploads in progress.'); + } + const token = randomUUID(); + const bytes = Buffer.alloc(size); + const timer = setTimeout(() => this.remove(token), 30000); + timer.unref(); + this.uploads.set(token, { + owner, + path, + bytes, + offset: 0, + options: { create, overwrite, expected }, + timer, + }); + this.bytes += size; + return token; + } + case 'writeChunk': + case 'commitWrite': + case 'abortWrite': { + const token = typeof params.token === 'string' ? params.token : ''; + const upload = this.uploads.get(token); + if (!upload || upload.owner !== owner) { + throw new WebRFileError( + 'Unavailable', + 'The webR upload expired or belongs to another connection.', + ); + } + if (params.action === 'abortWrite') { + this.remove(token); + return true; + } + if (params.action === 'writeChunk') { + const { data, offset } = params; + if ( + offset !== upload.offset || + typeof data !== 'string' || + !data.length || + data.length > Math.ceil(WEBR_FILE_CHUNK / 3) * 4 + ) { + throw new WebRFileError('Unavailable', 'Invalid webR upload chunk.'); + } + const bytes = Buffer.from(data, 'base64'); + if ( + bytes.length > WEBR_FILE_CHUNK || + bytes.toString('base64') !== data || + upload.offset + bytes.length > upload.bytes.length + ) { + throw new WebRFileError('Unavailable', 'Invalid webR upload chunk.'); + } + bytes.copy(upload.bytes, upload.offset); + upload.offset += bytes.length; + upload.timer.refresh(); + return upload.offset; + } + if (upload.offset !== upload.bytes.length) { + throw new WebRFileError('Unavailable', 'The webR upload is incomplete.'); + } + this.remove(token); + return files.writeFile(upload.path, upload.bytes, upload.options, requireControl); + } + default: + throw new WebRFileError('Unavailable', 'Unknown webR file operation.'); + } + } +} diff --git a/src/languageService.ts b/src/languageService.ts index bb52ba9fa..526c5f025 100644 --- a/src/languageService.ts +++ b/src/languageService.ts @@ -42,6 +42,8 @@ import { CancellableLanguageClient } from './languageServerClient'; import { withRpcCancellation } from './nativeRpc'; import { prepareNodeWebR } from './webr/nodeRuntime'; import { resolveExecutable } from './interactive/executable'; +import { WEBR_FILE_SCHEME, sessionFileOwner } from './webr/sessionFiles'; +import { Message } from 'vscode-jsonrpc'; import { cachedWebRAssets } from './webr/assetCache'; import { createWebRLanguageSession } from './webr/languageSession'; import { createWebRMessageTransports } from './webr/messageTransports'; @@ -231,7 +233,8 @@ export class LanguageService implements Disposable { (filter) => 'scheme' in filter && (filter.scheme === 'vscode-notebook-cell' || - filter.scheme === 'vscode-interactive-input'), + filter.scheme === 'vscode-interactive-input' || + filter.scheme === WEBR_FILE_SCHEME), ); // An unrooted server resolves opaque document paths against cwd, which // makes languageserver discard cells when the session lives under /tmp. @@ -395,6 +398,7 @@ export class LanguageService implements Disposable { }, handleDiagnostics: (uri, diagnostics, next) => { const supportedSchemes = [ + WEBR_FILE_SCHEME, 'file', 'untitled', 'vscode-notebook-cell', @@ -471,6 +475,48 @@ export class LanguageService implements Disposable { : undefined, }); client.ownResource(() => session.close()); + if ( + target && + selector.some( + (filter) => 'scheme' in filter && filter.scheme === WEBR_FILE_SCHEME, + ) + ) { + // The VS Code selector matches a path. URI authority still distinguishes + // separate host sessions that happen to use the same generation string. + const worker = { + ...session, + dispatch(message: Message) { + if (Message.isRequest(message) || Message.isNotification(message)) { + const uri = ( + message.params as + | { textDocument?: { uri?: unknown } } + | undefined + )?.textDocument?.uri; + if (typeof uri === 'string') { + const owner = sessionFileOwner(Uri.parse(uri)); + if ( + !owner || + `${owner.id}:${owner.generation}` !== target.sessionId + ) { + return Promise.resolve( + Message.isRequest(message) + ? [ + { + jsonrpc: '2.0', + id: message.id, + result: null, + }, + ] + : [], + ); + } + } + } + return session.dispatch(message); + }, + }; + return createWebRMessageTransports(worker); + } return createWebRMessageTransports(session); }, clientOptions, @@ -520,7 +566,8 @@ export class LanguageService implements Disposable { const isR = virtualOnly ? (doc: TextDocument) => (doc.uri.scheme === 'vscode-interactive-input' || - doc.uri.scheme === 'vscode-notebook-cell') && + doc.uri.scheme === 'vscode-notebook-cell' || + doc.uri.scheme === WEBR_FILE_SCHEME) && (doc.languageId === 'r' || doc.languageId === 'rmd') : isOrdinaryRDocument; if (workspace.textDocuments.some(isR)) { @@ -583,6 +630,12 @@ export class LanguageService implements Disposable { switch (uri.scheme) { case 'untitled': return uri.scheme; + case WEBR_FILE_SCHEME: { + const owner = sessionFileOwner(uri); + return owner + ? `${WEBR_FILE_SCHEME}://${owner.id}/${owner.generation}` + : uri.toString(); + } case 'vscode-notebook-cell': return `vscode-notebook:${uri.fsPath}`; default: @@ -601,14 +654,20 @@ export class LanguageService implements Disposable { const didOpenTextDocument = async (document: TextDocument) => { if ( virtualOnly && - !['vscode-notebook-cell', 'vscode-interactive-input'].includes(document.uri.scheme) + !['vscode-notebook-cell', 'vscode-interactive-input', WEBR_FILE_SCHEME].includes( + document.uri.scheme, + ) ) { return; } if ( - !['file', 'untitled', 'vscode-notebook-cell', 'vscode-interactive-input'].includes( - document.uri.scheme, - ) + ![ + 'file', + 'untitled', + 'vscode-notebook-cell', + 'vscode-interactive-input', + WEBR_FILE_SCHEME, + ].includes(document.uri.scheme) ) { return; } @@ -619,7 +678,8 @@ export class LanguageService implements Disposable { const target = document.uri.scheme === 'vscode-interactive-input' || - document.uri.scheme === 'vscode-notebook-cell' + document.uri.scheme === 'vscode-notebook-cell' || + document.uri.scheme === WEBR_FILE_SCHEME ? boundSessionForDocument(document.uri) : undefined; const owner = target && { @@ -630,17 +690,33 @@ export class LanguageService implements Disposable { target ? Uri.file(target.workingDir) : document.uri, ); - if (document.uri.scheme === 'vscode-interactive-input') { + const sessionFile = document.uri.scheme === WEBR_FILE_SCHEME; + if (document.uri.scheme === 'vscode-interactive-input' || sessionFile) { + const file = sessionFileOwner(document.uri); + if ( + sessionFile && + (!file || + target?.interactiveProvider !== 'webr' || + target.sessionId !== `${file.id}:${file.generation}`) + ) { + return; + } // The same key as the queue and close use, which skip encoding. const key = this.getKey(document.uri); if (!this.checkClient(key)) { - const selector = [ - { - scheme: 'vscode-interactive-input', - language: 'r', - pattern: document.uri.fsPath, - }, - ]; + const selector = file + ? ['r', 'rmd'].map((language) => ({ + scheme: WEBR_FILE_SCHEME, + language, + pattern: `/${file.generation}/**`, + })) + : [ + { + scheme: 'vscode-interactive-input', + language: 'r', + pattern: document.uri.fsPath, + }, + ]; await this.startDocumentClient( key, selector, @@ -836,7 +912,13 @@ export class LanguageService implements Disposable { }; this.listeners.push( onDidBindSessionDocument((uri) => { - if (!['vscode-notebook-cell', 'vscode-interactive-input'].includes(uri.scheme)) { + if ( + ![ + 'vscode-notebook-cell', + 'vscode-interactive-input', + WEBR_FILE_SCHEME, + ].includes(uri.scheme) + ) { return; } const document = workspace.textDocuments.find( diff --git a/src/session.ts b/src/session.ts index 053572a97..2922ab3d6 100644 --- a/src/session.ts +++ b/src/session.ts @@ -3,6 +3,7 @@ import type { DesktopWebRPackageSource } from './interactive/webRPackageStore'; import { isDeepStrictEqual } from 'node:util'; +import { WEBR_FILE_SCHEME } from './webr/sessionFiles'; import * as fs from 'node:fs'; import * as fsp from 'node:fs/promises'; import { pathExists, readJson } from './fileSystem'; @@ -336,12 +337,14 @@ function retargetDocuments(previous: Session, next?: Session): void { if (owner !== previous) { continue; } - if (next) { + const uri = Uri.parse(key); + // A virtual file names its worker generation. A session restart cannot + // transfer that file or any unsaved editor contents to the replacement. + if (next && (uri.scheme !== WEBR_FILE_SCHEME || previous === next)) { documentSessions.set(key, next); } else { documentSessions.delete(key); } - const uri = Uri.parse(key); // All cells of a notebook use the same language client. changed.add( uri.scheme === 'vscode-notebook-cell' diff --git a/src/test/node/interactiveCore.test.ts b/src/test/node/interactiveCore.test.ts index a922ab1ef..12a6ba333 100644 --- a/src/test/node/interactiveCore.test.ts +++ b/src/test/node/interactiveCore.test.ts @@ -98,6 +98,7 @@ suite('Interactive session button', () => { true, true, ); + assert.strictEqual(presentation.label, 'webR: Analysis · idle'); assert.match(presentation.description, /webR · Agent PID 456/); assert.match(presentation.tooltip, /Provider: webR/); assert.match(presentation.tooltip, /Agent PID: 456/); diff --git a/src/test/node/interactiveWebR.test.ts b/src/test/node/interactiveWebR.test.ts index 46e3b04f7..50de74964 100644 --- a/src/test/node/interactiveWebR.test.ts +++ b/src/test/node/interactiveWebR.test.ts @@ -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 { AgentWebRFileAccess } from '../../interactive/webRFiles'; import { DesktopWebRPackageSource } from '../../interactive/webRPackageStore'; import type { AgentConfig, SessionEvent, SessionManifest } from '../../interactive/protocol'; @@ -123,6 +124,262 @@ suite('R Interactive webR provider', function () { .join(''); } + test('reads and saves a paged binary session file through a controlling agent connection', async () => { + const files = new AgentWebRFileAccess(client); + const directory = '/home/web_user/editor'; + const file = directory + '/sample.bin'; + await files.createDirectory(directory); + // Larger than a JSON-lines frame even before base64 encoding. + const bytes = new Uint8Array(4 * 1024 * 1024 + 31); + for (let index = 0; index < bytes.length; index++) { + bytes[index] = index % 251; + } + await files.writeFile(file, bytes, { create: true, overwrite: false }); + const read = await files.readFile(file); + assert.equal(Buffer.compare(read.bytes, bytes), 0); + assert.equal((await files.stat(file)).size, bytes.length); + assert.deepEqual(await files.readDirectory(directory), [['sample.bin', 'file']]); + const owner = await submit(`stopifnot(file.size("${file}") == ${bytes.length})`); + assert.equal((await wait(owner, 'finished')).data.state, 'success', output(owner)); + + const observer = new AgentClient(manifest); + try { + await observer.connect({ claim: false }); + assert.equal(observer.control, false); + const observed = new AgentWebRFileAccess(observer); + assert.equal(Buffer.compare((await observed.readFile(file)).bytes, bytes), 0); + await assert.rejects(observed.createDirectory(directory + '/observer'), { + code: 'NoPermissions', + }); + await assert.rejects(observed.delete(file, { recursive: false }), { + code: 'NoPermissions', + }); + await assert.rejects( + client.request('webRFiles', { + generation: randomUUID(), + action: 'readFile', + path: file, + }), + /generation/i, + ); + } finally { + observer.close(); + } + + // Desktop project files already have native editor URIs. + fs.writeFileSync(path.join(project, 'workspace.txt'), 'host contents'); + await assert.rejects(files.readFile('/project/workspace.txt'), { code: 'NoPermissions' }); + await assert.rejects( + files.writeFile('/project/workspace.txt', Uint8Array.of(0), { + create: false, + overwrite: true, + }), + { code: 'NoPermissions' }, + ); + assert.equal(fs.readFileSync(path.join(project, 'workspace.txt'), 'utf8'), 'host contents'); + const running = await submit('repeat {}'); + await wait(running, 'started'); + await assert.rejects(files.stat(file), { code: 'Unavailable' }); + await client.request('interrupt'); + assert.equal((await wait(running, 'finished')).data.state, 'interrupted'); + + const renamed = directory + '/renamed.bin'; + await files.rename(file, renamed, { overwrite: false }); + await files.delete(directory, { recursive: true }); + await assert.rejects(files.stat(renamed), { code: 'FileNotFound' }); + }); + + test('commits complete writes only for the same connection, controller and file version', async () => { + const files = new AgentWebRFileAccess(client); + const file = '/home/web_user/edits.bin'; + const before = await files.writeFile(file, Uint8Array.of(1), { + create: true, + overwrite: false, + }); + const begin = (expected: string) => + client.request('webRFiles', { + action: 'beginWrite', + path: file, + size: 3, + create: false, + overwrite: true, + expected, + }); + const append = (token: string) => + client.request('webRFiles', { + action: 'writeChunk', + token, + offset: 0, + data: Buffer.from([9, 8, 7]).toString('base64'), + }); + const commit = (token: string) => + client.request('webRFiles', { action: 'commitWrite', token }); + + await assert.rejects( + client.request('webRFiles', { + action: 'beginWrite', + path: file, + size: 16 * 1024 * 1024 + 1, + create: true, + overwrite: true, + }), + ); + const oversizedChunk = await client.request('webRFiles', { + action: 'beginWrite', + path: file, + size: 512 * 1024, + create: false, + overwrite: true, + expected: before, + }); + await assert.rejects( + client.request('webRFiles', { + action: 'writeChunk', + token: oversizedChunk, + offset: 0, + data: Buffer.alloc(256 * 1024 + 1).toString('base64'), + }), + ); + await client + .request('webRFiles', { action: 'abortWrite', token: oversizedChunk }) + .catch(() => {}); + assert.deepEqual(Array.from((await files.readFile(file)).bytes), [1]); + + const stale = await begin(before); + await append(stale); + const changed = await submit(`writeBin(as.raw(2), "${file}")`); + assert.equal((await wait(changed, 'finished')).data.state, 'success', output(changed)); + await assert.rejects(commit(stale), /FileModifiedSince/); + const actual = await files.readFile(file); + assert.deepEqual(Array.from(actual.bytes), [2]); + + const partial = await begin(actual.version); + await client.request('webRFiles', { + action: 'writeChunk', + token: partial, + offset: 0, + data: Buffer.from([9]).toString('base64'), + }); + await assert.rejects(commit(partial)); + assert.deepEqual(Array.from((await files.readFile(file)).bytes), [2]); + + const lost = await begin(actual.version); + await append(lost); + client.close(); + // Reuse the client ID and generation. A new socket cannot finish an old upload. + await client.connect({ claim: true }); + await assert.rejects(commit(lost)); + assert.deepEqual(Array.from((await files.readFile(file)).bytes), [2]); + + const lease = await begin(actual.version); + await append(lease); + const other = new AgentClient(manifest); + try { + await other.connect({ claim: false }); + assert.equal(await other.request('claim', { force: true }), true); + await assert.rejects(commit(lease), /control|observing|NoPermissions/i); + await assert.rejects( + other.request('webRFiles', { action: 'commitWrite', token: lease }), + ); + assert.deepEqual( + Array.from((await new AgentWebRFileAccess(other).readFile(file)).bytes), + [2], + ); + } finally { + other.close(); + } + }); + + test('file.edit opens a path relative to R and preserves an explicitly configured editor', async () => { + const directory = '/home/web_user/editing'; + const name = "résumé 'draft' #1.R"; + const literal = JSON.stringify(name); + const opened = await submit( + [ + `dir.create("${directory}"); setwd("${directory}")`, + `writeLines("value <- 1", ${literal})`, + `utils::file.edit(${literal})`, + 'cat("cell completed after file.edit")', + ].join('\n'), + ); + assert.equal((await wait(opened, 'finished')).data.state, 'success', output(opened)); + assert.match(output(opened), /cell completed after file.edit/); + await wait(opened, 'notification'); + const openEvents = () => + events.filter( + (event) => event.type === 'notification' && event.data.method === 'webR/openFile', + ); + assert.deepEqual( + openEvents().map((event) => (event.data.params as { path: string }).path), + [directory + '/' + name], + ); + + assert.equal((openEvents()[0].data.params as { create: boolean }).create, true); + const configure = await submit( + 'options(editor = function(file, title) { chosen_editor_file <<- file })', + ); + assert.equal((await wait(configure, 'finished')).data.state, 'success', output(configure)); + const custom = await submit( + `file.edit(${literal}); stopifnot(identical(chosen_editor_file, ${literal}))`, + ); + assert.equal((await wait(custom, 'finished')).data.state, 'success', output(custom)); + assert.equal(openEvents().length, 1); + }); + + test('opens readable text help and retains pager output after file.show removes its source', async () => { + const files = new AgentWebRFileAccess(client); + const openedPaths = (id: string) => + events + .filter( + (event) => + event.executionId === id && + event.type === 'notification' && + event.data.method === 'webR/openFile', + ) + .map((event) => (event.data.params as { path: string }).path); + const help = await submit('?mean'); + assert.equal((await wait(help, 'finished')).data.state, 'success', output(help)); + const helpEvent = await wait(help, 'notification'); + assert.equal((helpEvent.data.params as { create: boolean }).create, false); + const helpPages = openedPaths(help); + assert.equal(helpPages.length, 1); + assert.match(helpPages[0], /^\/tmp\/[^/]+\.txt$/); + assert.equal((await files.stat(helpPages[0])).readonly, true); + const page = new TextDecoder().decode((await files.readFile(helpPages[0])).bytes); + assert.match(page, /Arithmetic Mean/); + assert.ok( + !page.includes('\b'), + 'A text editor should not receive pager overstrike controls', + ); + + const path = '/home/web_user/pager source.txt'; + const source = JSON.stringify(path); + const show = await submit( + `writeLines(c("first", "second"), ${source}); file.show(${source}, title="File contents", delete.file=TRUE); stopifnot(!file.exists(${source}))`, + ); + assert.equal((await wait(show, 'finished')).data.state, 'success', output(show)); + const reportEvent = await wait(show, 'notification'); + assert.equal((reportEvent.data.params as { create: boolean }).create, false); + const reports = openedPaths(show); + assert.equal(reports.length, 1); + assert.notEqual(reports[0], path); + assert.equal( + new TextDecoder().decode((await files.readFile(reports[0])).bytes), + 'first\nsecond\n', + ); + await assert.rejects(files.stat(path), { code: 'FileNotFound' }); + + const configure = await submit( + 'options(pager = function(files, ...) { chosen_pager_lines <<- readLines(files[1]) })', + ); + assert.equal((await wait(configure, 'finished')).data.state, 'success', output(configure)); + const custom = await submit( + `writeLines("custom", ${source}); file.show(${source}); stopifnot(identical(chosen_pager_lines, "custom"))`, + ); + assert.equal((await wait(custom, 'finished')).data.state, 'success', output(custom)); + assert.deepEqual(openedPaths(custom), []); + }); + test('downloads a repository index with private host scratch files and the R project as its working directory', async () => { // This makes the upstream synchronous HTTP bridge fail in the launcher // directory even when a privileged runner could write to a read-only folder. diff --git a/src/test/node/webRFileSystem.test.ts b/src/test/node/webRFileSystem.test.ts new file mode 100644 index 000000000..247694bcf --- /dev/null +++ b/src/test/node/webRFileSystem.test.ts @@ -0,0 +1,175 @@ +import * as assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import * as fs from 'node:fs/promises'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import type { WebR } from 'webr'; +import { createWebRFileAccess } from '../../webr/filesystem'; +import { prepareNodeWebR } from '../../webr/nodeRuntime'; + +suite('webR virtual filesystem', function () { + this.timeout(60000); + let root: string; + let runtime: WebR; + let files: ReturnType; + let folder: string; + + suiteSetup(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'vscode-r-webr-files-')); + const baseUrl = await prepareNodeWebR(root, (directory) => + fs.cp(path.dirname(require.resolve('webr')), directory, { recursive: true }), + ); + const { WebR } = await import('webr'); + runtime = new WebR({ baseUrl, interactive: true }); + await runtime.init(); + files = createWebRFileAccess(runtime); + }); + setup(async () => { + folder = '/home/web_user/' + randomUUID(); + await runtime.FS.mkdir(folder); + }); + suiteTeardown(async () => { + runtime?.close(); + if (root) { + await fs.rm(root, { recursive: true, force: true }); + } + }); + + test('creates, reads, renames and deletes files visible to R', async () => { + const directory = folder + '/notes'; + const file = directory + "/résumé #1 ('draft').R"; + const contents = new TextEncoder().encode('résultat <- 42\n'); + await files.createDirectory(directory); + assert.equal((await files.stat(directory)).type, 'directory'); + await files.writeFile(file, contents, { create: true, overwrite: false }); + const info = await files.stat(file); + assert.equal(info.type, 'file'); + assert.equal(info.size, contents.length); + assert.ok(Number.isFinite(info.mtime)); + const read = await files.readFile(file); + assert.deepEqual(Array.from(read.bytes), Array.from(contents)); + assert.equal(typeof read.version, 'string'); + assert.equal( + await runtime.evalRString('readLines(file, encoding="UTF-8")', { env: { file } }), + 'résultat <- 42', + ); + assert.deepEqual(await files.readDirectory(directory), [["résumé #1 ('draft').R", 'file']]); + await assert.rejects(files.writeFile(file, contents, { create: true, overwrite: false }), { + code: 'FileExists', + }); + const renamed = directory + '/saved.R'; + await assert.rejects( + files.writeFile(renamed, contents, { create: false, overwrite: true }), + { code: 'FileNotFound' }, + ); + await files.rename(file, renamed, { overwrite: false }); + await assert.rejects(files.stat(file), { code: 'FileNotFound' }); + assert.deepEqual(Array.from((await files.readFile(renamed)).bytes), Array.from(contents)); + await runtime.evalRVoid('stopifnot(Sys.chmod(file, "0444"))', { env: { file: renamed } }); + assert.equal((await files.stat(renamed)).readonly, true); + await assert.rejects( + files.writeFile(renamed, contents, { create: false, overwrite: true }), + { code: 'NoPermissions' }, + ); + await assert.rejects(files.delete(directory, { recursive: false })); + const original = await runtime.evalRString('getwd()'); + await runtime.evalRVoid('setwd(path)', { env: { path: directory } }); + try { + await assert.rejects(files.delete(directory, { recursive: true })); + assert.deepEqual((await files.readFile(renamed)).bytes, contents); + } finally { + await runtime.evalRVoid('setwd(path)', { env: { path: original } }); + } + await files.delete(directory, { recursive: true }); + await assert.rejects(files.stat(renamed), { code: 'FileNotFound' }); + }); + + test('rejects a stale save even when R preserves the original size and modification time', async () => { + const file = folder + '/sample.bin'; + // R may rewrite data and restore its timestamp, as data-copying tools do. + const writeRBytes = (value: number) => + runtime.evalRVoid( + 'writeBin(as.raw(rep(value, 4)), file); stopifnot(Sys.setFileTime(file, as.POSIXct("2020-01-01", tz="UTC")))', + { env: { file, value } }, + ); + await writeRBytes(1); + const old = await files.readFile(file); + const before = await files.stat(file); + await writeRBytes(2); + const after = await files.stat(file); + assert.equal(after.size, before.size); + assert.equal(after.mtime, before.mtime); + const latest = await files.readFile(file); + assert.notEqual(latest.version, old.version); + await assert.rejects( + files.writeFile(file, Uint8Array.of(3), { + create: false, + overwrite: true, + expected: old.version, + }), + { code: 'FileModifiedSince' }, + ); + assert.deepEqual(Array.from((await files.readFile(file)).bytes), [2, 2, 2, 2]); + await files.writeFile(file, Uint8Array.of(3), { + create: false, + overwrite: true, + expected: latest.version, + }); + assert.deepEqual(Array.from((await files.readFile(file)).bytes), [3]); + }); + + test('reports an oversized file without transferring its contents', async () => { + const file = folder + '/oversized.bin'; + const bytes = 16 * 1024 * 1024 + 1; + await runtime.FS.writeFile(file, new Uint8Array(bytes)); + assert.equal((await files.stat(file)).size, bytes); + await assert.rejects(files.readFile(file), { code: 'Unavailable' }); + }); + + test('excludes host mounts, symlinks, devices and private session state', async () => { + const host = path.join(root, 'mount fixture'); + const mounted = folder + '/mounted'; + const virtual = folder + '/data.txt'; + await runtime.FS.writeFile(virtual, Uint8Array.of(17)); + await fs.mkdir(host); + await fs.writeFile(path.join(host, 'fixture.txt'), 'host fixture'); + await runtime.FS.mkdir(mounted); + await runtime.FS.mount('NODEFS', { root: host }, mounted); + const alias = folder + '/alias.txt'; + assert.equal( + await runtime.evalRBoolean('file.symlink(target, alias)', { + env: { target: virtual, alias }, + }), + true, + ); + const scratch = '/tmp/vscode-r-interactive'; + await runtime.FS.mkdir(scratch); + await runtime.FS.writeFile(scratch + '/marker', Uint8Array.of(19)); + const rootFolder = '/analysis-output'; + await runtime.FS.mkdir(rootFolder); + await runtime.FS.writeFile(rootFolder + '/result', Uint8Array.of(21)); + const roots = (await files.readDirectory('/')).map(([name]) => name); + assert.ok(roots.includes('analysis-output')); + assert.deepEqual(Array.from((await files.readFile(rootFolder + '/result')).bytes), [21]); + assert.ok(roots.includes('home')); + assert.ok(!roots.includes('dev') && !roots.includes('proc') && !roots.includes('project')); + assert.equal((await files.stat('/')).readonly, true); + await assert.rejects(files.readFile('/dev/null')); + await assert.rejects(files.stat('/proc/self')); + await assert.rejects(files.readFile(scratch + '/marker')); + await assert.rejects(files.readFile(alias)); + await assert.rejects(files.readFile(mounted + '/fixture.txt')); + await assert.rejects( + files.writeFile(mounted + '/fixture.txt', Uint8Array.of(0), { + create: false, + overwrite: true, + }), + ); + // A recursive operation must validate the whole directory before removing its first file. + await assert.rejects(files.delete(folder, { recursive: true })); + await assert.rejects(files.rename(folder, folder + '-moved', { overwrite: false })); + assert.equal(await fs.readFile(path.join(host, 'fixture.txt'), 'utf8'), 'host fixture'); + assert.deepEqual(Array.from(await runtime.FS.readFile(virtual)), [17]); + assert.deepEqual(Array.from(await runtime.FS.readFile(scratch + '/marker')), [19]); + }); +}); diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index 0709f4e41..d41e3cc76 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -25,6 +25,7 @@ import { AssetStorageStats, exportedAssetName, readAsset } from '../../interacti import { resolveExecutable } from '../../interactive/executable'; import { shellQuote } from '../../interactive/launcher'; import { prepareNodeWebR } from '../../webr/nodeRuntime'; +import type { WebRSessionFiles } from '../../webr/sessionFiles'; import { listenLocal, localEndpoint } from '../../interactive/transport'; import type { InteractiveManager } from '../../interactive/manager'; import type { GlobalEnvItem, WorkspaceDataProvider } from '../../workspaceViewer'; @@ -573,6 +574,13 @@ suite('Interactive VS Code integration', function () { assert.ok(manager, 'Interactive manager must be registered'); return manager; } + function registeredSessionFiles(context: vscode.ExtensionContext): WebRSessionFiles { + const provider = context.subscriptions.find( + (item) => 'open' in item && 'readDirectory' in item && 'writeFile' in item, + ); + assert.ok(provider, 'webR filesystem must be registered by activation'); + return provider as WebRSessionFiles; + } function recreateManager(context: vscode.ExtensionContext): void { const manager = interactiveManager(context); assert.ok(manager); @@ -581,7 +589,7 @@ suite('Interactive VS Code integration', function () { ).constructor; manager.dispose(); context.subscriptions.splice(context.subscriptions.indexOf(manager), 1); - context.subscriptions.push(new Manager(context)); + context.subscriptions.push(new Manager(context, registeredSessionFiles(context))); } function nodeOverride(name: string): { executable: string; log: string } { const node = resolveExecutable('node', root); @@ -1185,6 +1193,251 @@ suite('Interactive VS Code integration', function () { } } }); + test('opens and saves files in their owning webR session and rejects writes after restart', async function () { + this.timeout(90000); + const config = vscode.workspace.getConfiguration('r'); + const previous = config.inspect('interactive.supervision')?.globalValue; + const sandbox = sinon.createSandbox(); + const manager = interactiveManager(); + const ui = manager as unknown as { + status: vscode.StatusBarItem; + views: Map; + }; + const opened: SessionManifest[] = []; + const names = ['file owner A', 'file owner B']; + const file = '/tmp/owner-script.R'; + const navigated: string[] = []; + const errors = sandbox.stub(vscode.window, 'showErrorMessage').resolves(undefined); + sandbox + .stub(vscode.workspace, 'workspaceFolders') + .value([{ uri: vscode.Uri.file(root), name: 'mounted project', index: 0 }]); + sandbox.stub(vscode.window, 'showQuickPick').callsFake((async ( + items: unknown, + options: vscode.QuickPickOptions, + ) => { + const choices = (await items) as (vscode.QuickPickItem & { + value?: string; + path?: string; + })[]; + const provider = choices.find((item) => item.value === 'webr'); + if (provider) { + return provider; + } + assert.match(options.title ?? '', /webR/); + const target = options.title?.endsWith(' · /') ? '/tmp' : file; + navigated.push(target); + const choice = choices.find((item) => item.path === target); + assert.ok(choice, 'The file picker should offer ' + target); + return choice; + }) as never); + sandbox.stub(vscode.window, 'showInputBox').callsFake(() => Promise.resolve(names.shift())); + sandbox + .stub(vscode.window, 'showWarningMessage') + .callsFake(((_message: string, ...items: unknown[]) => + Promise.resolve( + items.includes('Restart Session') ? 'Restart Session' : 'Stop Session', + )) as never); + + async function start(label: string) { + await vscode.commands.executeCommand('r.interactive.new'); + manager.refresh(); + const manifest = manager.getChildren().find((m) => m.label === label); + assert.ok(manifest, JSON.stringify(errors.args)); + opened.push(manifest); + const notebook = vscode.workspace.notebookDocuments.find( + (n) => n.metadata.rSessionId === manifest.id, + ); + assert.ok(notebook); + return { manifest, notebook }; + } + async function finished( + notebook: vscode.NotebookDocument, + source: string, + ): Promise { + const find = () => + notebook.getCells().find((cell) => cell.document.getText() === source); + await until( + () => find()?.executionSummary?.success === true, + () => + 'webR source did not complete: ' + + JSON.stringify({ + source, + errors: errors.args, + cells: notebook + .getCells() + .map((c) => [c.document.getText(), c.executionSummary?.success]), + }), + ); + return find()!; + } + async function focus(document: vscode.TextDocument): Promise { + const editor = await vscode.window.showTextDocument(document, { + viewColumn: vscode.ViewColumn.Active, + preserveFocus: false, + preview: false, + }); + await until(() => vscode.window.activeTextEditor === editor); + } + async function replace(document: vscode.TextDocument, text: string): Promise { + const edit = new vscode.WorkspaceEdit(); + edit.replace( + document.uri, + new vscode.Range( + document.positionAt(0), + document.positionAt(document.getText().length), + ), + text, + ); + assert.ok(await vscode.workspace.applyEdit(edit)); + } + const sessionDocument = (manifest: SessionManifest) => + vscode.workspace.textDocuments.find( + (doc) => + doc.uri.scheme === 'vscode-r-webr' && + doc.uri.authority === manifest.id && + doc.uri.path === '/' + manifest.generation + file, + ); + try { + await config.update( + 'interactive.supervision', + 'detached', + vscode.ConfigurationTarget.Global, + ); + await prepareNodeWebR(root, (dir) => + fs.promises.cp(path.dirname(require.resolve('webr')), dir, { recursive: true }), + ); + const a = await start('file owner A'); + const view = [...ui.views.values()].find( + (item) => item.client.manifest.id === a.manifest.id, + ); + assert.ok(view); + await until( + () => + view.controller.label.startsWith('webR: file owner A') && + ui.status.text.includes('webR: file owner A'), + ); + assert.match(String(manager.getTreeItem(a.manifest).description), /webR/); + await until(() => + a.notebook.getCells().some((cell) => { + const text = cell.document.getText(); + return ( + cell.kind === vscode.NotebookCellKind.Markup && + text.includes('/project') && + text.includes('/tmp') && + text.includes('Open webR Session File') + ); + }), + ); + const makeA = + 'owner <- "A"; writeLines("initial_A <- TRUE", "/tmp/owner-script.R"); file.edit("/tmp/owner-script.R")'; + await vscode.commands.executeCommand('r.runSelection', makeA); + await finished(a.notebook, makeA); + await until( + () => !!sessionDocument(a.manifest), + () => 'file.edit() did not open the owner file: ' + JSON.stringify(errors.args), + ); + const docA = sessionDocument(a.manifest)!; + assert.match(docA.getText(), /initial_A/); + assert.strictEqual(docA.languageId, 'r'); + + const b = await start('file owner B'); + const makeB = 'owner <- "B"; writeLines("initial_B <- TRUE", "/tmp/owner-script.R")'; + await vscode.commands.executeCommand('r.runSelection', makeB); + await finished(b.notebook, makeB); + await vscode.commands.executeCommand('r.interactive.openSessionFile', b.manifest); + await until(() => !!sessionDocument(b.manifest)); + const docB = sessionDocument(b.manifest)!; + assert.match(docB.getText(), /initial_B/); + assert.notStrictEqual(docA.uri.toString(), docB.uri.toString()); + assert.deepStrictEqual(navigated, ['/tmp', file]); + + await focus(docA); + const saved = + 'stopifnot(owner == "A", any(grepl("saved_A", readLines("/tmp/owner-script.R")))); saved_A <- 21'; + await replace(docA, saved); + assert.ok(await docA.save()); + await vscode.commands.executeCommand('r.runSource'); + await finished(a.notebook, saved); + const unsaved = + 'stopifnot(owner == "A", saved_A == 21, !any(grepl("unsaved_A", readLines("/tmp/owner-script.R")))); unsaved_A <- saved_A * 2'; + await replace(docA, unsaved); + assert.ok(docA.isDirty); + await vscode.commands.executeCommand('r.runSource'); + await finished(a.notebook, unsaved); + assert.ok( + docA.isDirty, + 'Run Source should execute an unsaved editor buffer without implicitly saving it', + ); + assert.ok( + !b.notebook + .getCells() + .some((cell) => [saved, unsaved].includes(cell.document.getText())), + ); + assert.match( + Buffer.from(await vscode.workspace.fs.readFile(docB.uri)).toString(), + /initial_B/, + ); + // Save current content so closing the test tabs never needs a discard prompt. + assert.ok(await docA.save()); + + fs.writeFileSync(path.join(root, 'host-source.R'), 'host_file <- TRUE'); + await vscode.commands.executeCommand( + 'r.interactive.openSessionFile', + b.manifest, + '/project/host-source.R', + ); + await until( + () => + vscode.window.activeTextEditor?.document.uri.toString() === + vscode.Uri.file(path.join(root, 'host-source.R')).toString(), + ); + await vscode.commands.executeCommand('r.interactive.restart', a.manifest); + manager.refresh(); + const restarted = manager + .getChildren() + .find((m) => m.id === a.manifest.id && m.generation !== a.manifest.generation); + assert.ok(restarted, JSON.stringify(errors.args)); + opened[0] = restarted; + const replacement = [...ui.views.values()].find( + (item) => + item.client.manifest.id === restarted.id && + item.client.manifest.generation === restarted.generation, + ); + assert.ok(replacement); + const freshCode = 'writeLines("new_generation", "/tmp/owner-script.R")'; + await replacement.client.request('submit', { + submission: { id: randomUUID(), code: freshCode }, + }); + await finished(a.notebook, freshCode); + await assert.rejects( + Promise.resolve(vscode.workspace.fs.writeFile(docA.uri, Buffer.from('stale save'))), + ); + assert.match( + Buffer.from(await vscode.workspace.fs.readFile(docB.uri)).toString(), + /initial_B/, + ); + const freshUri = docA.uri.with({ path: '/' + restarted.generation + file }); + assert.match( + Buffer.from(await vscode.workspace.fs.readFile(freshUri)).toString(), + /new_generation/, + ); + assert.ok(errors.notCalled, JSON.stringify(errors.args)); + } finally { + try { + for (const manifest of opened.reverse()) { + await vscode.commands.executeCommand('r.interactive.stop', manifest); + await vscode.commands.executeCommand('r.interactive.detach', manifest); + } + } finally { + sandbox.restore(); + await config.update( + 'interactive.supervision', + previous, + vscode.ConfigurationTarget.Global, + ); + } + } + }); test('missing explicit tmux reports a recovery setting before installing or creating a session', async function () { if (process.platform === 'win32') { this.skip(); @@ -1612,7 +1865,7 @@ suite('Interactive VS Code integration', function () { test('the kernel button shows session identity, process details and live activity', async () => { const manifest = manifests[0]; await vscode.commands.executeCommand('r.interactive.open', manifest); - await until(() => controller.label === `R: ${manifest.label} · idle`); + await until(() => controller.label === `arf: ${manifest.label} · idle`); assert.ok(controller.description?.includes(`PID ${manifest.rPid ?? ''}`)); assert.ok(controller.detail?.includes(manifest.directory)); assert.match(controller.description ?? '', /^R \d/); @@ -1956,7 +2209,7 @@ suite('Interactive VS Code integration', function () { const created = sinon.spy(vscode.notebooks, 'createNotebookController'); const errors = sinon.stub(vscode.window, 'showErrorMessage').resolves(undefined); try { - const restoredManager = new Manager(context); + const restoredManager = new Manager(context, registeredSessionFiles(context)); context.subscriptions.push(restoredManager); await until(() => notebooks.every((notebook, i) => notebook.metadata.rSessionId === manifests[i].id), @@ -3257,7 +3510,7 @@ cat("\n")`; command, ...args, ); - if (args[3] === 'R: New session focus') { + if (args[3] === 'arf: New session focus') { // Emulate native models retained under a recycled numbered URI. const retained = new vscode.WorkspaceEdit(); retained.set(result.notebookUri, [ @@ -3310,7 +3563,7 @@ cat("\n")`; assert.strictEqual( vscode.window.tabGroups.all .flatMap((group) => group.tabs) - .filter((tab) => tab.label === 'R: New session focus').length, + .filter((tab) => tab.label === 'arf: New session focus').length, 1, 'Focusing the new native input must not open a duplicate tab in the previous editor group', ); diff --git a/src/test/suite/languageService.test.ts b/src/test/suite/languageService.test.ts index 01ce336d6..fb5b86aa1 100644 --- a/src/test/suite/languageService.test.ts +++ b/src/test/suite/languageService.test.ts @@ -16,6 +16,7 @@ import * as path from 'node:path'; import * as os from 'node:os'; import { extensionContext } from '../../extension'; import { LanguageService } from '../../languageService'; +import { sessionFileUri, WEBR_FILE_SCHEME } from '../../webr/sessionFiles'; import { connectTcpLanguageServer } from '../../languageServerTransport'; import { CancellableLanguageClient } from '../../languageServerClient'; import * as util from '../../util'; @@ -378,6 +379,98 @@ suite('Language service startup lifecycle', () => { }); suite('Language service for bound Interactive documents', () => { + test('isolates webR filesystem source clients per session generation and releases retired editors', async () => { + const sandbox = sinon.createSandbox(); + const config = vscode.workspace.getConfiguration; + sandbox.stub(vscode.workspace, 'getConfiguration').callsFake((...args) => { + const settings = config(...args); + return args[0] !== 'r' + ? settings + : ({ + ...settings, + get: (key: string, fallback?: unknown) => + key === 'lsp.runtime' + ? 'native' + : key === 'lsp.multiServer' + ? false + : settings.get(key, fallback), + } as vscode.WorkspaceConfiguration); + }); + mockExtensionContext(path.resolve(__dirname, '../../..'), sandbox); + sandbox.stub(util, 'getRpath').resolves(process.execPath); + sandbox.stub(vscode.workspace, 'getWorkspaceFolder').returns(undefined); + sandbox.stub(CancellableLanguageClient.prototype, 'start').resolves(); + sandbox.stub(CancellableLanguageClient.prototype, 'stop').resolves(); + sandbox.stub(CancellableLanguageClient.prototype, 'needsStop').returns(true); + const a = registerSessionTransport( + 'one:g1', + 'host', + os.tmpdir(), + () => Promise.resolve({}), + 'webr', + ); + const b = registerSessionTransport( + 'two:g2', + 'host', + os.tmpdir(), + () => Promise.resolve({}), + 'webr', + ); + const restarted = registerSessionTransport( + 'one:g3', + 'host', + os.tmpdir(), + () => Promise.resolve({}), + 'webr', + ); + const doc = (id: string, generation: string) => + ({ + uri: sessionFileUri(id, generation, '/tmp/analysis.R'), + languageId: 'r', + isClosed: false, + }) as vscode.TextDocument; + const first = doc('one', 'g1'), + second = doc('two', 'g2'); + sandbox.stub(vscode.workspace, 'textDocuments').get(() => [first, second]); + bindSessionDocument(first.uri, a); + bindSessionDocument(second.uri, b); + const service = new LanguageService(); + const state = service as unknown as { + startup: Promise; + clientUpdates: Map>; + clients: Map; + }; + const settle = async () => { + await state.startup; + while (state.clientUpdates.size) { + await Promise.all(state.clientUpdates.values()); + } + }; + const firstKey = WEBR_FILE_SCHEME + '://one/g1', + secondKey = WEBR_FILE_SCHEME + '://two/g2'; + try { + await settle(); + const peer = state.clients.get(secondKey); + assert.strictEqual(state.clients.get(firstKey)?.name, 'R Language Server (webR)'); + assert.strictEqual(peer?.name, 'R Language Server (webR)'); + assert.notStrictEqual(state.clients.get(firstKey), peer); + replaceSessionTransport(a, restarted); + await settle(); + assert.strictEqual(state.clients.has(firstKey), false); + assert.strictEqual(state.clients.get(secondKey), peer); + // Even an obsolete callback must never attach this URI to the replacement. + bindSessionDocument(first.uri, restarted); + await settle(); + assert.strictEqual(state.clients.has(firstKey), false); + } finally { + await service.dispose(); + unregisterSessionTransport(a); + unregisterSessionTransport(b); + unregisterSessionTransport(restarted); + sandbox.restore(); + } + }); + test('keeps an ordinary bound source in its own workspace with multiServer enabled', async () => { const sandbox = sinon.createSandbox(); const a = vscode.Uri.file(path.join(os.tmpdir(), 'workspace-a')); diff --git a/src/test/suite/webRSessionFiles.test.ts b/src/test/suite/webRSessionFiles.test.ts new file mode 100644 index 000000000..176559a30 --- /dev/null +++ b/src/test/suite/webRSessionFiles.test.ts @@ -0,0 +1,75 @@ +import * as assert from 'node:assert/strict'; +import * as sinon from 'sinon'; +import * as vscode from 'vscode'; +import type { WebRFileAccess } from '../../webr/filesystem'; +import { sessionFileOwner, sessionFileUri, WebRSessionFiles } from '../../webr/sessionFiles'; + +suite('webR session filesystem provider', () => { + test('identifies each generation and rejects traversal including backslashes', () => { + const uri = sessionFileUri('a', 'g1', '/tmp/50% #data.R'); + assert.deepEqual(sessionFileOwner(vscode.Uri.parse(uri.toString())), { + id: 'a', + generation: 'g1', + path: '/tmp/50% #data.R', + }); + assert.throws(() => sessionFileUri('a', 'g1', '/tmp/../project/a.R')); + assert.throws(() => sessionFileUri('a', 'g1', '/tmp/..\\secret')); + assert.equal(sessionFileOwner(uri.with({ query: 'unexpected' })), undefined); + }); + + test('keeps a dirty editor’s read revision on reconnect and refuses writes into a replacement generation', async () => { + const stubs = sinon.createSandbox(); + stubs + .stub(vscode.workspace, 'registerFileSystemProvider') + .returns(new vscode.Disposable(() => {})); + const uri = sessionFileUri('one', 'first', '/tmp/edit.R'); + const document = { uri, isDirty: true } as vscode.TextDocument; + stubs.stub(vscode.workspace, 'textDocuments').get(() => [document]); + const files = new WebRSessionFiles(); + let revision = '1'; + const write = stubs + .stub() + .callsFake((_path: string, _bytes: Uint8Array, opts: { expected?: string }) => { + if (opts.expected !== revision) { + return Promise.reject(new Error('WebRFileError[FileModifiedSince]: different')); + } + return Promise.resolve(++counter + ''); + }); + let counter = 0; + const access = { + readFile: () => Promise.resolve({ bytes: new Uint8Array([42]), version: revision }), + stat: () => + Promise.resolve({ type: 'file', size: 1, mtime: 0, ctime: 0, version: revision }), + writeFile: write, + } as unknown as WebRFileAccess; + const bind = (generation: string) => + files.add({ + id: 'one', + generation, + label: 'test', + initialDirectory: '/', + files: () => Promise.resolve(access), + }); + try { + const first = bind('first'); + assert.deepEqual(await files.readFile(uri), new Uint8Array([42])); + first.dispose(); + revision = '2'; + const same = bind('first'); + await assert.rejects( + files.writeFile(uri, new Uint8Array([7]), { create: true, overwrite: true }), + /changed in webR/, + ); + same.dispose(); + bind('second'); + await assert.rejects( + files.writeFile(uri, new Uint8Array([8]), { create: true, overwrite: true }), + /not connected/, + ); + sinon.assert.calledOnce(write); + } finally { + files.dispose(); + stubs.restore(); + } + }); +}); diff --git a/src/webr/console.ts b/src/webr/console.ts index 2d57be881..ff91931b7 100644 --- a/src/webr/console.ts +++ b/src/webr/console.ts @@ -2,6 +2,7 @@ import type { WebR } from 'webr'; import { WebRPackageCapture } from './packageCapture'; import type { WebRPackageContextEvent } from './packageContext'; import { consoleRunner } from './consoleRunner'; +import { installWebRFileHooks } from './fileHooks'; import { inspectWebRViewer, prepareWebRViewers } from './viewers'; import { checkHtmlSize, type HtmlBundle, validateHtmlBundle } from '../interactive/htmlBundle'; @@ -13,6 +14,7 @@ export type WebRConsoleEvent = | { type: 'started' } | { type: 'input'; prompt: string } | { type: 'plot'; png: Uint8Array } + | { type: 'openFile'; path: string; create: boolean } | { type: 'display'; data: Record } | { type: 'viewer'; method: 'dataview'; params: Record } | { type: 'widget'; files: Record }; @@ -25,6 +27,7 @@ interface Cell { outcome?: WebRConsoleResult; widgetBytes: number; widgetFiles: number; + openFiles?: Map; widgetError?: boolean; resolve(result: WebRConsoleResult): void; reject(error: Error): void; @@ -70,6 +73,7 @@ export class WebRConsole { await this.runtime.FS.mkdir(root); await prepareWebRViewers(this.runtime); await this.runtime.evalRVoid(consoleRunner); + await installWebRFileHooks(this.runtime); const initial = await this.packages.start(); if (initial) { this.onEvent(initial); @@ -285,6 +289,21 @@ export class WebRConsole { } break; } + case 'vscode-r-open-file': { + const data = message.data as { path?: unknown; create?: unknown } | undefined; + if ( + cell && + typeof data?.path === 'string' && + data.path.startsWith('/') && + data.path.length <= 4096 + ) { + cell.openFiles ??= new Map(); + if (cell.openFiles.size < 32) { + cell.openFiles.set(data.path, data.create === true); + } + } + break; + } case 'vscode-r-execution': { const marker = message.data as { id?: unknown; state?: unknown } | null; if (!cell || marker?.id !== cell.id) { @@ -358,6 +377,9 @@ export class WebRConsole { } } this.active = undefined; + for (const [path, create] of cell.openFiles ?? []) { + this.onEvent({ type: 'openFile', path, create }); + } cell.resolve(cell.outcome); } else if (cell.phase === 'submitted') { throw new Error('webR returned to the console before acknowledging the submission.'); diff --git a/src/webr/fileHooks.ts b/src/webr/fileHooks.ts new file mode 100644 index 000000000..d15c9f2c1 --- /dev/null +++ b/src/webr/fileHooks.ts @@ -0,0 +1,34 @@ +import type { WebR } from 'webr'; +import { fileSystemBootstrap } from './fileSystemWorker'; + +/** Base R accepts functions for both editor and pager. Install them once so users + * can override either option later, including an explicit editor= argument. */ +export async function installWebRFileHooks(runtime: WebR): Promise { + await runtime.evalRVoid('webr::eval_js(script)', { env: { script: fileSystemBootstrap } }); + await runtime.evalRVoid(String.raw` + base::local({ + send <- function(action, path, title = NULL, remove = FALSE) { + payload <- jsonlite::toJSON(list(action = action, path = path.expand(path), + cwd = getwd(), title = title, remove = isTRUE(remove)), auto_unbox = TRUE, null = "null") + encoded <- gsub("[[:space:]]", "", jsonlite::base64_enc(charToRaw(enc2utf8(as.character(payload))))) + webr::eval_js(paste0("globalThis.Module.vscodeRFileHook('", encoded, "')")) + invisible(NULL) + } + if (is.null(getOption("editor")) || identical(getOption("editor"), "vi")) { + options(editor = function(file, title) { + if (length(file) > 32L) stop("Open at most 32 files at once.") + for (path in file) send("editor", path) + invisible(NULL) + }) + } + if (is.null(getOption("pager")) || identical(getOption("pager"), file.path(R.home("bin"), "pager"))) { + options(pager = function(files, header, title, delete.file = FALSE) { + if (length(files) > 32L) stop("Open at most 32 pager files at once.") + for (path in files) send("pager", path, title, delete.file) + invisible(NULL) + }) + if (is.null(getOption("help_type"))) options(help_type = "text") + } + }, envir = base::new.env(parent = base::baseenv())) + `); +} diff --git a/src/webr/fileSystemWorker.ts b/src/webr/fileSystemWorker.ts new file mode 100644 index 000000000..f3ab990a0 --- /dev/null +++ b/src/webr/fileSystemWorker.ts @@ -0,0 +1,375 @@ +// This handler runs synchronously in the R worker. Emscripten resolves every +// operation against the primary memory filesystem before reading or changing it. +export const fileSystemBootstrap = String.raw`(() => { + const module = globalThis.Module; + if (module.vscodeRFileRequest) return null; + const fs = module.FS; + const memory = fs.root.mount.type; + const maximumFile = 16 * 1024 * 1024; + const chunk = 256 * 1024; + const protectedRoots = new Set([ + 'dev', + 'proc', + 'sys', + 'etc', + 'usr', + 'var', + 'bin', + 'sbin', + 'lib', + 'lib64', + 'root', + 'opt', + 'run', + 'boot', + 'language-library', + ]); + const decoder = new TextDecoder(); + let transfer; + let serial = 0; + const fail = (code, message) => { + throw Object.assign(new Error(message), { fileCode: code }); + }; + const missing = (e) => e.errno === 44; + function parts(path) { + if (typeof path !== 'string' || !path.startsWith('/') || path.length > 4096) + fail('NoPermissions', 'Use an absolute webR filesystem path.'); + const items = path === '/' ? [] : path.slice(1).split('/'); + if ( + items.length > 128 || + items.some( + (s) => !s || s === '.' || s === '..' || s.length > 255 || /[\\\x00-\x1f]/.test(s), + ) + ) + fail('NoPermissions', 'Invalid webR filesystem path.'); + if ( + protectedRoots.has(items[0]) || + (items[0] === 'home' && items[1] && items[1] !== 'web_user') || + items.some((s) => s.startsWith('.vscode-r-files-')) || + (items[0] === 'tmp' && + items.some((s) => s.startsWith('vscode-r-') || s.startsWith('vscode-view-'))) + ) + fail('NoPermissions', 'This webR runtime path is private.'); + return items; + } + function checked(node) { + if ( + node.mounted || + node.mount.type !== memory || + (!fs.isDir(node.mode) && !fs.isFile(node.mode)) + ) + fail( + 'NoPermissions', + 'Mounted filesystems, links and special files cannot be accessed here.', + ); + return node; + } + function lookup(path, optional = false) { + const items = parts(path); + let node = checked(fs.root); + for (let i = 0; i < items.length; i++) { + if (!fs.isDir(node.mode)) + fail('FileNotADirectory', 'A path component is not a directory.'); + try { + node = checked(fs.lookupNode(node, items[i])); + } catch (e) { + if (optional && i === items.length - 1 && missing(e)) return; + throw e; + } + } + return node; + } + function mutable(path) { + const items = parts(path); + if ( + !items.length || + path === '/home' || + path === '/home/web_user' || + path === '/tmp' || + path === '/workspace' + ) + fail('NoPermissions', 'The webR filesystem root cannot be replaced or removed.'); + } + function metadata(path, node) { + const s = node.node_ops.getattr(node); + const directory = fs.isDir(node.mode); + if (!directory && !fs.isFile(node.mode)) + fail('NoPermissions', 'Only regular files can be opened.'); + // Timestamps alone can repeat on rapid R writes. Include all accessible + // file bytes in the version used by conditional saves. + let a = 2166136261, + b = 5381; + if (!directory && s.size <= maximumFile) { + const bytes = fs.readFile(path); + for (const byte of bytes) { + a = Math.imul(a ^ byte, 16777619); + b = Math.imul(b, 33) ^ byte; + } + } + const mtime = +s.mtime, + ctime = +s.ctime; + return { + type: directory ? 'directory' : 'file', + size: s.size, + ctime, + mtime, + version: [node.id, s.mode, s.size, mtime, ctime, a >>> 0, b >>> 0].join(':'), + readonly: path === '/' || path === '/home' || (s.mode & 0o222) === 0, + }; + } + const to64 = (bytes) => { + let text = ''; + for (let i = 0; i < bytes.length; i += 16384) + text += String.fromCharCode(...bytes.subarray(i, i + 16384)); + return btoa(text); + }; + const asBytes = (text) => Uint8Array.from(atob(text), (letter) => letter.charCodeAt(0)); + const join = (path, name) => (path === '/' ? '' : path) + '/' + name; + function walk(path, nodes) { + if (nodes.length >= 10000) + fail('Unavailable', 'Directory operation exceeds 10,000 entries.'); + const node = lookup(path); + nodes.push([path, node]); + if (fs.isDir(node.mode)) + for (const name of fs.readdir(path)) { + if (name !== '.' && name !== '..') walk(join(path, name), nodes); + } + } + function perform(q) { + let node; + switch (q.action) { + case 'stat': + return metadata(q.path, lookup(q.path)); + case 'readDirectory': { + node = lookup(q.path); + if (!fs.isDir(node.mode)) fail('FileNotADirectory', 'Expected a directory.'); + const result = []; + for (const name of fs.readdir(q.path)) { + if (name === '.' || name === '..') continue; + try { + const child = lookup(join(q.path, name)); + result.push([name, fs.isDir(child.mode) ? 'directory' : 'file']); + } catch (e) { + if (e.fileCode !== 'NoPermissions') throw e; + } + if (result.length > 10000) + fail('Unavailable', 'Directory listing exceeds 10,000 entries.'); + } + return result; + } + case 'read': { + node = lookup(q.path); + if (fs.isDir(node.mode)) fail('FileIsADirectory', 'Expected a regular file.'); + const info = metadata(q.path, node); + if (info.size > maximumFile) + fail('Unavailable', 'webR files are limited to 16 MiB.'); + transfer = { bytes: fs.readFile(q.path), id: ++serial, kind: 'read' }; + return { size: info.size, version: info.version, id: transfer.id }; + } + case 'readChunk': + if (transfer?.id !== q.id || transfer.kind !== 'read') + fail('Unavailable', 'File read expired.'); + return to64(transfer.bytes.subarray(q.offset, q.offset + chunk)); + case 'begin': { + mutable(q.path); + lookup(q.path, true); + if (!Number.isSafeInteger(q.size) || q.size < 0 || q.size > maximumFile) + fail('Unavailable', 'webR files are limited to 16 MiB.'); + transfer = { + bytes: new Uint8Array(q.size), + id: ++serial, + kind: 'write', + offset: 0, + path: q.path, + options: q.options, + }; + return transfer.id; + } + case 'append': { + if (transfer?.id !== q.id || transfer.kind !== 'write') + fail('Unavailable', 'File upload expired.'); + const bytes = asBytes(q.data); + if ( + bytes.length > chunk || + q.offset !== transfer.offset || + q.offset + bytes.length > transfer.bytes.length + ) + fail('Unavailable', 'Invalid file upload chunk.'); + transfer.bytes.set(bytes, q.offset); + transfer.offset += bytes.length; + return null; + } + case 'commit': { + if ( + transfer?.id !== q.id || + transfer.kind !== 'write' || + transfer.offset !== transfer.bytes.length + ) + fail('Unavailable', 'Incomplete webR file upload.'); + const { path, bytes, options } = transfer; + node = lookup(path, true); + if (node && fs.isDir(node.mode)) fail('FileIsADirectory', 'Expected a file.'); + if ( + options.expected !== undefined && + (!node || options.expected !== metadata(path, node).version) + ) + fail( + 'FileModifiedSince', + 'The webR file changed. Reopen it or compare the current contents.', + ); + if (node && !options.overwrite) fail('FileExists', 'The file already exists.'); + if (!node && !options.create) fail('FileNotFound', 'The file does not exist.'); + if (node && (node.mode & 0o222) === 0) + fail('NoPermissions', 'The file is read-only.'); + const temporary = + path.slice(0, path.lastIndexOf('/') + 1) + + '.vscode-r-files-' + + (globalThis.crypto?.randomUUID?.() ?? ++serial + '-' + Date.now()); + // O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW. webR 0.6.1's Emscripten runtime + // does not implement the Node-style 'wx' string mode. + const fd = fs.open(temporary, 1 | 64 | 128 | 131072); + try { + try { + if (fs.write(fd, bytes, 0, bytes.length) !== bytes.length) + fail('Unavailable', 'Could not write the complete webR file.'); + } finally { + fs.close(fd); + } + fs.chmod(temporary, node ? node.mode & 0o777 : 0o666); + fs.rename(temporary, path); + } finally { + try { + fs.unlink(temporary); + } catch (e) { + if (!missing(e)) throw e; + } + } + transfer = undefined; + return metadata(path, lookup(path)).version; + } + case 'release': + if (transfer?.id === q.id) transfer = undefined; + return null; + case 'createDirectory': + node = lookup(q.path, true); + if (node) fail('FileExists', 'The path already exists.'); + fs.mkdir(q.path); + return null; + case 'delete': { + mutable(q.path); + node = lookup(q.path); + if (fs.isDir(node.mode) && q.recursive) { + const nodes = []; + walk(q.path, nodes); + // Check the R working directory and every parent's deletion + // permissions before removing any children. + for (const [, child] of nodes) { + const error = fs.mayDelete(child.parent, child.name, fs.isDir(child.mode)); + if (error) throw new fs.ErrnoError(error); + } + for (const [path, child] of nodes.reverse()) + fs.isDir(child.mode) ? fs.rmdir(path) : fs.unlink(path); + } else if (fs.isDir(node.mode)) fs.rmdir(q.path); + else fs.unlink(q.path); + return null; + } + case 'rename': { + mutable(q.path); + mutable(q.to); + node = lookup(q.path); + const destination = lookup(q.to, true); + if (q.path === q.to) return null; + if (q.to.startsWith(q.path + '/')) + fail('NoPermissions', 'A directory cannot be moved inside itself.'); + if (destination && !q.overwrite) fail('FileExists', 'The target already exists.'); + // A moved tree must not move mountpoints, special nodes or reserved scratch. + if (fs.isDir(node.mode)) walk(q.path, []); + fs.rename(q.path, q.to); + return null; + } + } + fail('Unavailable', 'Unknown webR file operation.'); + } + function absolute(cwd, path) { + if (typeof path !== 'string' || !path || typeof cwd !== 'string' || !cwd.startsWith('/')) + fail('NoPermissions', 'Invalid R editor path.'); + const fields = (path.startsWith('/') ? path : cwd + '/' + path).split('/'); + const normalized = []; + for (const field of fields) { + if (field === '..') normalized.pop(); + else if (field && field !== '.') normalized.push(field); + } + const result = '/' + normalized.join('/'); + parts(result); + return result; + } + module.vscodeRFileHook = (encoded) => { + const q = JSON.parse(decoder.decode(asBytes(encoded))); + let path = absolute(q.cwd, q.path); + if (q.action === 'pager') { + const original = lookup(path); + if (!fs.isFile(original.mode) || original.node_ops.getattr(original).size > 1024 * 1024) + fail('Unavailable', 'The webR pager accepts regular text files up to 1 MiB.'); + const text = decoder.decode(fs.readFile(path)).replace(/[^\n]\x08/g, ''); + const title = + String(q.title || 'R help') + .replace(/[^A-Za-z0-9_-]+/g, '-') + .slice(0, 64) + .replace(/^-+|-+$/g, '') || 'R-help'; + lookup('/tmp'); + const output = '/tmp/' + title + '-' + ++serial + '-' + Date.now() + '.txt'; + // Exclusive creation avoids following or replacing an existing name. + fs.writeFile(output, new TextEncoder().encode(text), { flags: 1 | 64 | 128 | 131072 }); + fs.chmod(output, 0o444); + if (q.remove === true) fs.unlink(path); + path = output; + } else if (q.action === 'editor') { + // A desktop /project path is opened by the owning native workspace, + // which performs its own containment check. Every other path is MEMFS. + let nativeProject = false; + if (path === '/project' || path.startsWith('/project/')) { + try { + const mount = fs.lookupNode(fs.root, 'project').mounted; + nativeProject = !!mount && mount.type === fs.filesystems.NODEFS; + } catch (e) { + if (!missing(e)) throw e; + } + } + if (!nativeProject) { + const node = lookup(path, true); + if (node && !fs.isFile(node.mode)) + fail('FileIsADirectory', 'Expected a regular file.'); + } + } else { + fail('Unavailable', 'Unknown webR editor operation.'); + } + module.webr.channel.write({ + type: 'vscode-r-open-file', + data: { path, create: q.action === 'editor' }, + }); + return null; + }; + module.vscodeRFileRequest = (encoded) => { + try { + return JSON.stringify({ value: perform(JSON.parse(decoder.decode(asBytes(encoded)))) }); + } catch (e) { + const fileError = { + 44: ['FileNotFound', 'The webR file does not exist.'], + 20: ['FileExists', 'The webR path already exists.'], + 54: ['FileNotADirectory', 'Expected a webR directory.'], + 31: ['FileIsADirectory', 'Expected a regular webR file.'], + 2: ['NoPermissions', 'Permission denied by webR.'], + 63: ['NoPermissions', 'Permission denied by webR.'], + 55: ['NoPermissions', 'The webR directory is not empty.'], + }[e.errno] ?? [ + 'Unavailable', + 'webR filesystem operation failed (' + (e.errno ?? 'unknown') + ').', + ]; + return JSON.stringify({ + error: e.fileCode ?? fileError[0], + message: e.fileCode ? e.message : fileError[1], + }); + } + }; + return null; +})()`; diff --git a/src/webr/filesystem.ts b/src/webr/filesystem.ts new file mode 100644 index 000000000..96511cdb8 --- /dev/null +++ b/src/webr/filesystem.ts @@ -0,0 +1,163 @@ +import type { WebR } from 'webr'; +import { fileSystemBootstrap } from './fileSystemWorker'; + +export const WEBR_FILE_LIMIT = 16 * 1024 * 1024; +export const WEBR_FILE_CHUNK = 256 * 1024; +export type WebRFileType = 'file' | 'directory'; +export interface WebRFileStat { + type: WebRFileType; + size: number; + ctime: number; + mtime: number; + version: string; + readonly?: boolean; +} +export interface WebRFileWriteOptions { + create: boolean; + overwrite: boolean; + expected?: string; +} +export interface WebRFileAccess { + stat(path: string): Promise; + readDirectory(path: string): Promise<[string, WebRFileType][]>; + readFile(path: string): Promise<{ bytes: Uint8Array; version: string }>; + writeFile( + path: string, + bytes: Uint8Array, + options: WebRFileWriteOptions, + beforeCommit?: () => void, + ): Promise; + createDirectory(path: string): Promise; + delete(path: string, options: { recursive: boolean }): Promise; + rename(from: string, to: string, options: { overwrite: boolean }): Promise; +} +export type WebRFileErrorCode = + | 'FileNotFound' + | 'FileExists' + | 'FileNotADirectory' + | 'FileIsADirectory' + | 'NoPermissions' + | 'Unavailable' + | 'FileModifiedSince'; +export class WebRFileError extends Error { + constructor( + readonly code: WebRFileErrorCode, + message: string, + ) { + super(`WebRFileError[${code}]: ${message}`); + this.name = 'WebRFileError'; + } +} + +function base64(bytes: Uint8Array): string { + let text = ''; + for (let i = 0; i < bytes.length; i += 16384) { + text += String.fromCharCode(...bytes.subarray(i, i + 16384)); + } + return btoa(text); +} + +type RunFileOperation = (operation: () => Promise) => Promise; + +/** All paths and file contents cross the R boundary as data. The fixed bridge + * runs its checks and each filesystem mutation synchronously in the worker. + */ +export function createWebRFileAccess( + runtime: WebR, + run: RunFileOperation = (operation) => operation(), +): WebRFileAccess { + let initialized = false; + let tail = Promise.resolve(); + const encoder = new TextEncoder(); + function schedule(operation: () => Promise): Promise { + const result = tail.then(() => + run(async () => { + if (!initialized) { + await runtime.evalRVoid('webr::eval_js(script)', { + env: { script: fileSystemBootstrap }, + }); + initialized = true; + } + return operation(); + }), + ); + tail = result.then( + () => {}, + () => {}, + ); + return result; + } + async function call(request: Record): Promise { + const encoded = base64(encoder.encode(JSON.stringify(request))); + const expression = 'globalThis.Module.vscodeRFileRequest("' + encoded + '")'; + const response = await runtime.evalRString('webr::eval_js(script)', { + env: { script: expression }, + }); + const result = JSON.parse(response) as + | { value: T } + | { error: WebRFileErrorCode; message: string }; + if ('error' in result) { + throw new WebRFileError(result.error, result.message); + } + return result.value; + } + return { + stat: (path) => schedule(() => call({ action: 'stat', path })), + readDirectory: (path) => schedule(() => call({ action: 'readDirectory', path })), + readFile: (path) => + schedule(async () => { + const { id, size, version } = await call<{ + id: number; + size: number; + version: string; + }>({ action: 'read', path }); + try { + const bytes = new Uint8Array(size); + for (let offset = 0; offset < size; offset += WEBR_FILE_CHUNK) { + const chunk = await call({ action: 'readChunk', id, offset }); + const raw = atob(chunk); + if (raw.length !== Math.min(WEBR_FILE_CHUNK, size - offset)) { + throw new WebRFileError('Unavailable', 'Incomplete webR file read.'); + } + for (let n = 0; n < raw.length; n++) { + bytes[offset + n] = raw.charCodeAt(n); + } + } + return { bytes, version }; + } finally { + await call({ action: 'release', id }).catch(() => {}); + } + }), + writeFile: (path, bytes, options, beforeCommit) => + schedule(async () => { + if (bytes.byteLength > WEBR_FILE_LIMIT) { + throw new WebRFileError('Unavailable', 'webR files are limited to 16 MiB.'); + } + const id = await call({ + action: 'begin', + path, + options, + size: bytes.byteLength, + }); + try { + for (let offset = 0; offset < bytes.length; offset += WEBR_FILE_CHUNK) { + await call({ + action: 'append', + id, + offset, + data: base64(bytes.subarray(offset, offset + WEBR_FILE_CHUNK)), + }); + } + beforeCommit?.(); + return await call({ action: 'commit', id }); + } finally { + await call({ action: 'release', id }).catch(() => {}); + } + }), + createDirectory: (path) => schedule(() => call({ action: 'createDirectory', path })), + delete: (path, options) => + schedule(() => call({ action: 'delete', path, recursive: options.recursive })), + rename: (path, to, options) => + schedule(() => call({ action: 'rename', path, to, overwrite: options.overwrite })), + }; +} diff --git a/src/webr/sessionFiles.ts b/src/webr/sessionFiles.ts new file mode 100644 index 000000000..ba3df7122 --- /dev/null +++ b/src/webr/sessionFiles.ts @@ -0,0 +1,498 @@ +import * as vscode from 'vscode'; +import type { WebRFileAccess, WebRFileStat } from './filesystem'; + +export const WEBR_FILE_SCHEME = 'vscode-r-webr'; +const identifier = /^[A-Za-z0-9_-]{1,100}$/; + +function validPath(path: string): boolean { + return ( + path === '/' || + (path.startsWith('/') && + !path.includes('\\') && + !path.includes('\0') && + path + .slice(1) + .split('/') + .every((part) => part && part !== '.' && part !== '..')) + ); +} + +export function sessionFileUri(id: string, generation: string, file: string): vscode.Uri { + if (!identifier.test(id) || !identifier.test(generation) || !validPath(file)) { + throw new Error('Invalid webR session file.'); + } + return vscode.Uri.from({ + scheme: WEBR_FILE_SCHEME, + authority: id, + path: '/' + generation + file, + }); +} + +export interface WebRFileOwner { + id: string; + generation: string; + path: string; +} +export function sessionFileOwner(uri: vscode.Uri): WebRFileOwner | undefined { + if ( + uri.scheme !== WEBR_FILE_SCHEME || + !identifier.test(uri.authority) || + uri.query || + uri.fragment + ) { + return; + } + const match = /^\/([^/]+)(\/.*)?$/.exec(uri.path); + if (!match || !identifier.test(match[1]) || !validPath(match[2] ?? '/')) { + return; + } + return { id: uri.authority, generation: match[1], path: match[2] ?? '/' }; +} + +export interface WebRFileSession { + id: string; + generation: string; + label: string; + files(): Promise; + initialDirectory: string; + /** The genuine host workspace URI mounted at /project in a desktop agent. */ + projectUri?: vscode.Uri; + onOpen?(uri: vscode.Uri): void; +} + +function key(id: string, generation: string): string { + return id + '/' + generation; +} +function child(directory: string, name: string): string { + return (directory === '/' ? '' : directory) + '/' + name; +} +function parent(file: string): string { + return file.slice(0, file.lastIndexOf('/')) || '/'; +} + +function fileError(error: unknown): Error { + if (error instanceof vscode.FileSystemError) { + return error; + } + const text = error instanceof Error ? error.message : String(error); + const match = /WebRFileError\[(\w+)\]: (.*)/s.exec(text); + if (match) { + switch (match[1]) { + case 'FileNotFound': + return vscode.FileSystemError.FileNotFound(match[2]); + case 'FileExists': + return vscode.FileSystemError.FileExists(match[2]); + case 'FileNotADirectory': + return vscode.FileSystemError.FileNotADirectory(match[2]); + case 'FileIsADirectory': + return vscode.FileSystemError.FileIsADirectory(match[2]); + case 'NoPermissions': + return vscode.FileSystemError.NoPermissions(match[2]); + case 'FileModifiedSince': + return vscode.FileSystemError.Unavailable( + 'The file changed in webR. Reopen or compare the current file before saving.', + ); + case 'Unavailable': + return vscode.FileSystemError.Unavailable(match[2]); + } + } + return vscode.FileSystemError.Unavailable(text); +} + +function fileType(type: 'file' | 'directory'): vscode.FileType { + return type === 'file' ? vscode.FileType.File : vscode.FileType.Directory; +} + +type Choice = vscode.QuickPickItem & { path?: string; action?: 'new' | 'path' }; + +/** One VS Code file system for all live worker generations in this extension host. */ +export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Disposable { + private readonly sessions = new Map(); + private readonly changed = new vscode.EventEmitter(); + readonly onDidChangeFile = this.changed.event; + private readonly versions = new Map(); + private readonly observed = new Map(); + private readonly watched = new Map(); + private readonly queued = new Map(); + private refreshing = false; + /** A desktop host can already be restoring this generation during editor reload. */ + waitForReconnect?: (id: string, generation: string) => Promise | undefined; + private readonly registration: vscode.Disposable; + private readonly closeListener: vscode.Disposable; + + constructor() { + this.registration = vscode.workspace.registerFileSystemProvider(WEBR_FILE_SCHEME, this, { + isCaseSensitive: true, + }); + this.closeListener = vscode.workspace.onDidCloseTextDocument((doc) => { + if (doc.uri.scheme === WEBR_FILE_SCHEME) { + this.versions.delete(doc.uri.toString()); + } + }); + } + + add(session: WebRFileSession): vscode.Disposable { + const identity = key(session.id, session.generation); + this.sessions.set(identity, session); + this.refresh(session.id, session.generation); + return new vscode.Disposable(() => { + if (this.sessions.get(identity) !== session) { + return; + } + this.sessions.delete(identity); + for (const uri of new Set([...this.versions.keys(), ...this.observed.keys()])) { + const owner = sessionFileOwner(vscode.Uri.parse(uri)); + if (owner && key(owner.id, owner.generation) === identity) { + // A dirty editor can reconnect to this generation. Its next + // save must still compare the original read revision. + if (!vscode.workspace.textDocuments.some((doc) => doc.uri.toString() === uri)) { + this.versions.delete(uri); + } + this.observed.delete(uri); + } + } + }); + } + + private session(owner: WebRFileOwner): WebRFileSession { + const session = this.sessions.get(key(owner.id, owner.generation)); + if (!session) { + throw vscode.FileSystemError.Unavailable( + 'This webR session generation is not connected. Reconnect to it to access its files.', + ); + } + return session; + } + + private async access( + uri: vscode.Uri, + action: (fs: WebRFileAccess, path: string) => Promise, + ): Promise { + const owner = sessionFileOwner(uri); + if (!owner) { + throw vscode.FileSystemError.FileNotFound(uri); + } + if (!this.sessions.has(key(owner.id, owner.generation))) { + await this.waitForReconnect?.(owner.id, owner.generation); + } + const session = this.session(owner); + try { + return await action(await session.files(), owner.path); + } catch (error) { + throw fileError(error); + } + } + + async stat(uri: vscode.Uri): Promise { + const result = await this.access(uri, (fs, path) => fs.stat(path)); + this.observed.set(uri.toString(), result.version); + return { + type: fileType(result.type), + size: result.size, + mtime: result.mtime, + ctime: result.ctime, + permissions: result.readonly ? vscode.FilePermission.Readonly : undefined, + }; + } + + async readDirectory(uri: vscode.Uri): Promise<[string, vscode.FileType][]> { + return (await this.access(uri, (fs, path) => fs.readDirectory(path))).map(([name, t]) => [ + name, + fileType(t), + ]); + } + + async readFile(uri: vscode.Uri): Promise { + const result = await this.access(uri, (fs, path) => fs.readFile(path)); + const id = uri.toString(); + const dirty = vscode.workspace.textDocuments.some( + (doc) => doc.isDirty && doc.uri.toString() === id, + ); + if (!dirty || !this.versions.has(id)) { + this.versions.set(id, result.version); + } + this.observed.set(id, result.version); + return result.bytes; + } + + async writeFile( + uri: vscode.Uri, + bytes: Uint8Array, + options: { create: boolean; overwrite: boolean }, + ): Promise { + const id = uri.toString(); + const before = this.versions.get(id); + const existed = before !== undefined || this.observed.has(id) || !options.create; + const version = await this.access(uri, (fs, path) => + fs.writeFile(path, bytes, { ...options, expected: before }), + ); + this.versions.set(id, version); + this.observed.set(id, version); + this.change(uri, existed ? vscode.FileChangeType.Changed : vscode.FileChangeType.Created); + } + + async createDirectory(uri: vscode.Uri): Promise { + await this.access(uri, (fs, path) => fs.createDirectory(path)); + this.change(uri, vscode.FileChangeType.Created); + } + + async delete(uri: vscode.Uri, options: { recursive: boolean }): Promise { + await this.access(uri, (fs, path) => fs.delete(path, options)); + this.versions.delete(uri.toString()); + this.observed.delete(uri.toString()); + this.change(uri, vscode.FileChangeType.Deleted); + } + + async rename(from: vscode.Uri, to: vscode.Uri, options: { overwrite: boolean }): Promise { + const source = sessionFileOwner(from), + dest = sessionFileOwner(to); + if (!source || !dest || source.id !== dest.id || source.generation !== dest.generation) { + throw vscode.FileSystemError.NoPermissions( + 'Rename is limited to one webR session generation.', + ); + } + await this.access(from, (fs, path) => fs.rename(path, dest.path, options)); + this.versions.delete(from.toString()); + this.observed.delete(from.toString()); + this.change(from, vscode.FileChangeType.Deleted); + this.change(to, vscode.FileChangeType.Created); + } + + private change(uri: vscode.Uri, type: vscode.FileChangeType): void { + const owner = sessionFileOwner(uri)!; + this.changed.fire([ + { uri, type }, + { + uri: sessionFileUri(owner.id, owner.generation, parent(owner.path)), + type: vscode.FileChangeType.Changed, + }, + ]); + } + + watch(uri: vscode.Uri): vscode.Disposable { + const id = uri.toString(), + entry = this.watched.get(id) ?? { uri, count: 0 }; + entry.count++; + this.watched.set(id, entry); + return new vscode.Disposable(() => { + if (--entry.count === 0) { + this.watched.delete(id); + this.observed.delete(id); + } + }); + } + + /** R can modify files without going through the provider. Check open files after a cell settles. */ + refresh(id: string, generation: string): void { + for (const uri of [ + ...vscode.workspace.textDocuments.map((d) => d.uri), + ...[...this.watched.values()].map((x) => x.uri), + ]) { + const owner = sessionFileOwner(uri); + if (owner?.id === id && owner.generation === generation) { + this.queued.set(uri.toString(), uri); + } + } + if (!this.refreshing && this.queued.size) { + void this.refreshFiles(); + } + } + + private async refreshFiles(): Promise { + this.refreshing = true; + try { + while (this.queued.size) { + const [id, uri] = this.queued.entries().next().value!; + this.queued.delete(id); + const previous = this.observed.get(id); + try { + const current = await this.access(uri, (fs, path) => fs.stat(path)); + this.observed.set(id, current.version); + if ( + previous !== current.version || + (current.type === 'directory' && this.watched.has(id)) + ) { + this.changed.fire([{ uri, type: vscode.FileChangeType.Changed }]); + } + } catch (error) { + if ( + error instanceof vscode.FileSystemError && + error.code === 'FileNotFound' && + previous + ) { + this.observed.delete(id); + this.changed.fire([{ uri, type: vscode.FileChangeType.Deleted }]); + } + } + } + } finally { + this.refreshing = false; + } + } + + async open(id?: string, generation?: string, path?: string, create = false): Promise { + if (!this.sessions.size) { + throw new Error('Start a webR Interactive session to open a session file.'); + } + const selected = + id && generation + ? this.session({ id, generation, path: '/' }) + : this.sessions.size === 1 + ? this.sessions.values().next().value + : ( + await vscode.window.showQuickPick( + [...this.sessions.values()].map((session) => ({ + label: session.label, + description: 'webR', + session, + })), + { title: 'Open webR Session File' }, + ) + )?.session; + if (!selected) { + return; + } + let file = path ?? selected.initialDirectory; + for (;;) { + const uri = sessionFileUri(selected.id, selected.generation, file); + if (selected.projectUri && (file === '/project' || file.startsWith('/project/'))) { + let target = selected.projectUri; + const segments = + file === '/project' ? [] : file.slice('/project/'.length).split('/'); + for (const [index, segment] of segments.entries()) { + target = vscode.Uri.joinPath(target, segment); + try { + if ( + (await vscode.workspace.fs.stat(target)).type & + vscode.FileType.SymbolicLink + ) { + throw vscode.FileSystemError.NoPermissions( + 'Open symbolic links through the host workspace.', + ); + } + } catch (error) { + if ( + !create || + index !== segments.length - 1 || + !(error instanceof vscode.FileSystemError) || + error.code !== 'FileNotFound' + ) { + throw error; + } + } + } + try { + if ((await vscode.workspace.fs.stat(target)).type & vscode.FileType.Directory) { + const choice = await vscode.window.showOpenDialog({ + defaultUri: target, + canSelectMany: false, + openLabel: 'Open Project File', + }); + if (!choice?.[0]) { + return; + } + target = choice[0]; + } + } catch (error) { + if ( + !create || + !(error instanceof vscode.FileSystemError) || + error.code !== 'FileNotFound' + ) { + throw error; + } + // Use normal editor creation for a new file on the actual host. + const newFile = new vscode.WorkspaceEdit(); + newFile.createFile(target, { ignoreIfExists: true }); + if (!(await vscode.workspace.applyEdit(newFile))) { + throw new Error('Could not create the project file.'); + } + } + await vscode.commands.executeCommand('vscode.open', target, { + preserveFocus: false, + }); + selected.onOpen?.(target); + return; + } + let stat: WebRFileStat; + try { + stat = await this.access(uri, (fs, p) => fs.stat(p)); + } catch (error) { + if ( + !create || + !(error instanceof vscode.FileSystemError) || + error.code !== 'FileNotFound' + ) { + throw error; + } + await this.writeFile(uri, new Uint8Array(), { create: true, overwrite: false }); + stat = { type: 'file', size: 0, mtime: 0, ctime: 0, version: '' }; + } + if (stat.type === 'file') { + await vscode.commands.executeCommand('vscode.open', uri, { preserveFocus: false }); + selected.onOpen?.(uri); + return; + } + const entries = await this.access(uri, (fs, p) => fs.readDirectory(p)); + const choices: Choice[] = []; + if (file !== '/') { + choices.push({ label: '$(arrow-up) ..', path: parent(file) }); + } + if (file === '/' && selected.projectUri) { + choices.push({ + label: '$(folder) project', + description: 'Mounted project on the R host', + path: '/project', + }); + } + for (const [name, type] of entries.sort(([a], [b]) => a.localeCompare(b))) { + if (file === '/' && name === 'project' && selected.projectUri) { + continue; + } + choices.push({ + label: `$(${type === 'directory' ? 'folder' : 'file'}) ${name}`, + path: child(file, name), + }); + } + if (!stat.readonly) { + choices.push({ label: '$(new-file) New file…', action: 'new' }); + } + choices.push({ label: '$(go-to-file) Open by path…', action: 'path' }); + const choice = await vscode.window.showQuickPick(choices, { + title: `webR: ${selected.label} · ${file}`, + placeHolder: 'Session files are lost when this webR generation stops.', + }); + if (!choice) { + return; + } + if (choice.path) { + file = choice.path; + create = false; + continue; + } + const value = await vscode.window.showInputBox({ + title: + choice.action === 'new' ? 'Create webR Session File' : 'Open webR Session File', + value: file === '/' ? '/' : file + '/', + validateInput: (input) => + validPath(input) ? undefined : 'Enter an absolute webR path.', + }); + if (value === undefined) { + return; + } + file = value; + create = choice.action === 'new'; + } + } + + dispose(): void { + this.registration.dispose(); + this.closeListener.dispose(); + this.changed.dispose(); + this.sessions.clear(); + this.watched.clear(); + this.queued.clear(); + this.versions.clear(); + this.observed.clear(); + } +} diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index 9e0d8f5f8..99fcb2e7a 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -15,6 +15,11 @@ For Remote SSH, install this extension **on the remote host**. The session agent Choose **webR** to run R in WebAssembly with no native R or arf installation. Relative paths such as `source("helpers.R")` and `read.csv("data.csv")` use the session’s project directory. Writes to that directory are visible on the host. Use `install.packages("ggplot2")` and then `library(ggplot2)`. The installer downloads compatible WebAssembly binaries and their runtime dependencies into the current session. For an alternative binary repository, pass its URL with `repos =`. webR-specific installation options are available through `webr::install()`. Static plots appear in the transcript. Workspace inspection and the native graphics devices described below are available with arf. [webR package installation](https://docs.r-wasm.org/webr/latest/packages.html) +**R: Open webR Session File…** opens the selected generation’s filesystem in VS Code. On desktop, **/project** opens the actual project on the R host, including a Remote SSH workspace. Files saved there remain on disk. Files in `/home/web_user` and `/tmp` live in the worker and are lost when that session stops or restarts. In VS Code for the Web, `/workspace` also lives in the worker. Use **Export File from webR…** to keep a browser result in the workspace. + +You can run `file.edit("/tmp/notes.R")`, edit the file in VS Code, save it, and then run `source("/tmp/notes.R")` in the same session. Virtual R editors use the owning session for Run Selection and language features. A tab from an earlier generation cannot overwrite a file in its replacement. Reopen the current file to compare if R has changed it since your last read. + + Choose **arf** to use an installed R and its project libraries. On the R host, install: - Native R and arf 0.7.2-rc.1 or later. The arf CLI is also used to list running arf sessions for adoption. @@ -97,7 +102,7 @@ New arf sessions save their resolved absolute executable path, so a later PATH c ### Session controls - **R: Open Interactive Session** opens the session picker when run from the Command Palette. The picker checks saved agents without taking control and shows live status, provider, PID, working directory, and a short session ID. Unavailable agents are omitted, while their saved history remains on disk. The picker also offers **New persistent R session**. Selecting a session in the tree opens that session directly. Cancelling the picker leaves existing sessions unchanged. -- The R session button in the Interactive toolbar shows the session name and live state. The kernel chooser uses a compact version/provider/PID description and a second line for the working directory, host, and supervision. VS Code also uses that short description as the button tooltip; it does not expose a separate tooltip or arbitrary multiline descriptions. The full R version, PID, directory, host, supervision, executable, session ID, and controlling/observing status remain available in the status-bar tooltip and **Session… → Session Details**. The presentation refreshes during startup, execution, disconnect, stop, and restart without changing the selected kernel. +- The session button and status bar identify the runtime directly, for example **webR: analysis · idle** or **arf: analysis · busy**. The Interactive Sessions tree also names the provider. The kernel chooser uses a compact version/provider/PID description and a second line for the working directory, host, and supervision. VS Code also uses that short description as the button tooltip; it does not expose a separate tooltip or arbitrary multiline descriptions. The full R version, PID, directory, host, supervision, executable, session ID, and controlling/observing status remain available in the status-bar tooltip and **Session… → Session Details**. The presentation refreshes during startup, execution, disconnect, stop, and restart without changing the selected kernel. - The status bar shows the selected session, activity, queued cell count, connection state, and observer status. Select it to switch sessions or answer a waiting R input prompt. Right-click a session in **Interactive Sessions** for actions on that specific session, including rename, interrupt, queued-work cancellation, detach, and restart. - The **Interactive Sessions** tooltip separates **Connection: Connected · controlling/observing** from process supervision. **Independent process** means R survives VS Code reload/exit; it does not mean the editor is disconnected. Unopened sessions show **Not open in this VS Code window**. Connection/control changes refresh the tooltip, including after reconnecting. - Session age appears in the session list, connection/stop pickers, and kernel description as **<1m**, **30m**, **1h**, or **1d**. It refreshes once a minute; the tooltip includes the start time. Age uses the persisted start of the current process generation, so reloading preserves it and restarting resets it. The recorded process exit time keeps a stopped session's lifetime fixed. From 80eb2c9155a9e8cd5b0a069cf65c220cb1cdb19f Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 07:09:25 +0800 Subject: [PATCH 2/6] Open browser webR session files in their owning notebook context --- package.json | 11 +-- src/test/web/webR.cjs | 91 ++++++++++++++++++++ src/web/extension.ts | 14 ++- src/web/interactive.ts | 171 +++++++++++++++++++++++++++++++++++-- src/web/languageService.ts | 52 ++++++++--- src/web/session.ts | 75 +++++++++++++--- 6 files changed, 379 insertions(+), 35 deletions(-) diff --git a/package.json b/package.json index a66665245..c2d0fdac8 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,7 @@ "id": "workspaceViewer", "title": "R", "icon": "./images/Rlogo.svg", - "when": "r.isActive" + "when": "r.isActive || r.webExtension" } ] }, @@ -71,7 +71,8 @@ "id": "workspaceViewer", "name": "Workspace", "icon": "./images/Rlogo.svg", - "contextualTitle": "R" + "contextualTitle": "R", + "when": "!r.webExtension" }, { "id": "rHelpPages", @@ -1737,17 +1738,17 @@ }, { "command": "r.interactive.connect", - "when": "view == rInteractiveSessions", + "when": "view == rInteractiveSessions && !r.webExtension", "group": "navigation@2" }, { "command": "r.interactive.refresh", - "when": "view == rInteractiveSessions", + "when": "view == rInteractiveSessions && !r.webExtension", "group": "navigation@3" }, { "command": "r.interactive.stopSelected", - "when": "view == rInteractiveSessions", + "when": "view == rInteractiveSessions && !r.webExtension", "group": "navigation@4" }, { diff --git a/src/test/web/webR.cjs b/src/test/web/webR.cjs index f37c1f429..6e642f279 100644 --- a/src/test/web/webR.cjs +++ b/src/test/web/webR.cjs @@ -190,6 +190,96 @@ async function notebookPackageCompletion() { console.log('Verified session-installed packages, attached exports, isolation and restart in browser completion.'); } +async function sessionFiles() { + async function newNotebook() { + await command('r.interactive.new'); + const doc = vscode.window.activeNotebookEditor?.notebook; + assert(doc?.notebookType === 'r-interactive','Expected an active webR notebook.'); + return doc; + } + async function open(path) { + await command('r.interactive.openSessionFile',path); + const document = vscode.window.activeTextEditor?.document; + assert(document?.uri.scheme === 'vscode-r-webr','Expected a real webR session document.'); + return document; + } + async function replace(document, contents) { + const change = new vscode.WorkspaceEdit(); + change.replace(document.uri,new vscode.Range(document.positionAt(0),document.positionAt(document.getText().length)),contents); + assert(await vscode.workspace.applyEdit(change) && await document.save(),'Could not save to the live webR filesystem.'); + } + const a = await newNotebook(); + const script = '/home/web_user/working file.R'; + await command('r.runCommand',[ + 'stopifnot(getwd() == "/workspace", path.expand("~") == "/home/web_user")', + 'writeLines("owner <- 3L", "/home/web_user/working file.R")', + 'writeLines("session text","/tmp/results.txt")', + 'writeLines("in workspace","/workspace/results.txt")', + ].join('\n')); + const fileA = await open(script); + assert(fileA.getText().trim() === 'owner <- 3L','Incorrect file from the first webR worker.'); + await replace(fileA,'owner <- 12L\n'); + await command('r.runCommand','cat(readLines("/home/web_user/working file.R"))'); + assert(stdout(a.cellAt(a.cellCount-1)).includes('owner <- 12L'),'R did not see the saved VS Code edit.'); + const tmp = await open('/tmp/results.txt'); + assert(tmp.getText().trim()==='session text','Opening a /tmp file changed the backend.'); + const cwd = await open('/workspace/results.txt'); + assert(cwd.getText().trim()==='in workspace','Opening a /workspace file changed the backend.'); + await vscode.window.showNotebookDocument(a); + await command('r.runCommand','file.edit("/tmp/edit-new.R")'); + await until(()=>vscode.window.activeTextEditor?.document.uri.scheme === 'vscode-r-webr' + && vscode.window.activeTextEditor.document.uri.path.endsWith('/tmp/edit-new.R'), 'file.edit did not open the session file.'); + const edited = vscode.window.activeTextEditor.document; + await replace(edited,'via_editor <- 20L\n'); + await command('r.runCommand','source("/tmp/edit-new.R"); via_editor'); + assert(stdout(a.cellAt(a.cellCount-1)).includes('20'), 'R did not see the new file created via file.edit().'); + await command('r.runCommand','?stats::lm'); + await until(async () => { + const help = vscode.window.activeTextEditor?.document; + if (help?.uri.scheme !== 'vscode-r-webr' || !help.uri.path.endsWith('.txt') || !help.getText().includes('Fitting Linear Models')) {return false;} + const stat = await vscode.workspace.fs.stat(help.uri); + return (stat.permissions & vscode.FilePermission.Readonly) !== 0; + },'The help pager did not open a read-only webR session document.'); + await vscode.window.showNotebookDocument(a); + await command('r.runCommand','install.packages("data.table")'); + const qualified = 'data.table::fr'; + await vscode.window.showTextDocument(fileA); + await replace(fileA,qualified+'\n'); + const hasFread = async (document, line = 0) => { + const r = await command('vscode.executeCompletionItemProvider',document.uri,new vscode.Position(line,qualified.length)); + return r?.items.some(item=>(typeof item.label==='string'?item.label:item.label.label)==='fread'); + }; + await until(()=>hasFread(fileA),'Session file did not use its notebook’s package context.'); + + const b = await newNotebook(); + await command('r.runCommand','writeLines(c("probe_in_b <- TRUE", "data.table::fr"),"/home/web_user/working file.R")'); + const fileB = await open(script); + assert(fileB.uri.toString() !== fileA.uri.toString(),'Two notebooks shared a session file identity.'); + await until(async()=>{ + const res=await command('vscode.executeDocumentSymbolProvider',fileB.uri); + return res?.some(symbol => symbol.name === 'probe_in_b'); + },'The second session file did not get a language service.'); + assert(!(await hasFread(fileB,1)),'The second worker received the first worker’s package completions.'); + + await vscode.window.showTextDocument(fileA); + await replace(fileA,'owner <- 21L\ncat(owner * 2)\n'); + const count=b.cellCount; + await command('r.runSource'); + assert(b.cellCount===count && stdout(a.cellAt(a.cellCount-1)).includes('42'),'Run Source submitted the old file to the most recent notebook.'); + await vscode.window.showNotebookDocument(a); + await command('r.interactive.restart'); + let rejected=false; + try { await vscode.workspace.fs.readFile(fileA.uri); } catch { rejected=true; } + assert(rejected,'Retired session file URI stayed readable.'); + rejected=false; + try { + await vscode.window.showTextDocument(fileA); + await command('r.runSelectionRetainCursor'); + } catch { rejected=true; } + assert(rejected && b.cellCount===count,'A stale file ran in another R session.'); + console.log('Verified live webR files, editing, package-aware language features and generation-safe execution.'); +} + exports.run = async () => { const files = testFiles(); try { @@ -301,6 +391,7 @@ exports.run = async () => { assert(stdout(reopened.cellAt(1)).includes('FALSE'), 'Reopening retained stale R state.'); await notebookLanguagePolicy(first, files); await notebookPackageCompletion(); + await sessionFiles(); 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 dcc94afdf..fe1c42c5f 100644 --- a/src/web/extension.ts +++ b/src/web/extension.ts @@ -19,7 +19,7 @@ export async function activate(context: vscode.ExtensionContext): Promise const runSource = async () => { const editor = vscode.window.activeTextEditor; if (editor) { - await interactive.submit(editor.document.getText()); + await interactive.submit(editor.document.getText(), editor.document.uri); } }; const runSelection = async (move: boolean) => { @@ -28,7 +28,7 @@ export async function activate(context: vscode.ExtensionContext): Promise if (!editor || !selection) { return; } - await interactive.submit(selection.selectedText); + await interactive.submit(selection.selectedText, editor.document.uri); if (move) { await moveAfterSelection(editor, selection); } @@ -45,6 +45,7 @@ export async function activate(context: vscode.ExtensionContext): Promise ) .map((range) => editor.document.getText(range)) .join('\n'), + editor.document.uri, ); } }, runSource); @@ -70,7 +71,14 @@ export async function activate(context: vscode.ExtensionContext): Promise 'r.goToNextChunk': goToNextChunk, 'r.selectCurrentChunk': selectCurrentChunk, 'r.interactive.new': () => interactive.open(true), - 'r.interactive.open': () => interactive.open(), + 'r.interactive.open': (doc?: vscode.NotebookDocument) => interactive.showSession(doc), + 'r.interactive.openSessionFile': ( + docOrPath?: vscode.NotebookDocument | string, + path?: string, + ) => + typeof docOrPath === 'string' + ? interactive.openFile(docOrPath) + : interactive.openFile(path, docOrPath), 'r.interactive.interrupt': () => interactive.interrupt(), 'r.interactive.stop': () => interactive.stop(), 'r.interactive.stopAll': () => interactive.stopAll(), diff --git a/src/web/interactive.ts b/src/web/interactive.ts index 738442903..b4a2c4f56 100644 --- a/src/web/interactive.ts +++ b/src/web/interactive.ts @@ -3,8 +3,15 @@ import { InteractiveSerializer } from '../interactive/notebook'; import { BrowserSession } from './session'; import type { WebRPackageSource } from '../webr/packageContext'; import { exportFile, importFiles } from './files'; +import { WEBR_FILE_SCHEME, WebRSessionFiles, sessionFileOwner } from '../webr/sessionFiles'; const notebookType = 'r-interactive'; +const filesystemDetail = + 'Files in /workspace, /home/web_user, and /tmp belong to this webR session. Use Import or Export to copy files between it and your VS Code workspace.'; + +function notebookLabel(doc: vscode.NotebookDocument): string { + return doc.uri.path.split('/').pop() || doc.uri.toString(); +} function openTabFor(uri: string): boolean { return vscode.window.tabGroups.all.some((group) => @@ -22,8 +29,21 @@ export class BrowserInteractive implements vscode.Disposable { 'R (webR)', ); private readonly sessions = new Map(); + private readonly files = new WebRSessionFiles(); + private readonly treeChanges = new vscode.EventEmitter(); + private readonly registrationsByNotebook = new Map< + vscode.NotebookDocument, + { id: string; generation: string; registration: vscode.Disposable } + >(); + private readonly notebookIds = new WeakMap(); + private readonly status = vscode.window.createStatusBarItem( + 'r.webR.session', + vscode.StatusBarAlignment.Left, + ); private readonly packageUpdates = new vscode.EventEmitter(); readonly onDidChangePackages = this.packageUpdates.event; + private readonly fileOwners = new vscode.EventEmitter(); + readonly onDidChangeFileOwners = this.fileOwners.event; private readonly registrations: vscode.Disposable[]; private last?: vscode.NotebookDocument; private opening?: Promise; @@ -33,6 +53,9 @@ export class BrowserInteractive implements vscode.Disposable { this.controller.supportedLanguages = ['r']; this.controller.supportsExecutionOrder = true; this.controller.description = 'webR (experimental) · R in this browser'; + this.controller.detail = filesystemDetail; + this.status.name = 'webR Interactive session'; + this.status.command = 'r.interactive.sessionActions'; this.controller.executeHandler = async (cells, doc) => { const session = this.session(doc); await session.run(async () => { @@ -46,6 +69,27 @@ export class BrowserInteractive implements vscode.Disposable { this.controller.interruptHandler = (doc) => this.interrupt(doc); const messages = vscode.notebooks.createRendererMessaging('r-interactive-renderer'); this.registrations = [ + this.files, + this.treeChanges, + this.fileOwners, + this.status, + vscode.window.onDidChangeActiveTextEditor(() => this.updatePresentation()), + vscode.workspace.onDidOpenNotebookDocument((doc) => { + if (doc.notebookType === notebookType) { + this.updatePresentation(); + } + }), + vscode.window.createTreeView('rInteractiveSessions', { + treeDataProvider: { + onDidChangeTreeData: this.treeChanges.event, + getChildren: () => + vscode.workspace.notebookDocuments.filter( + (doc) => + doc.notebookType === notebookType && openTabFor(doc.uri.toString()), + ), + getTreeItem: (doc) => this.treeItem(doc), + }, + }), this.packageUpdates, messages.onDidReceiveMessage(async ({ editor, message: raw }) => { const message = raw as Record | undefined; @@ -84,6 +128,7 @@ export class BrowserInteractive implements vscode.Disposable { if (editor?.notebook.notebookType === notebookType) { this.last = editor.notebook; } + this.updatePresentation(); }), vscode.workspace.onDidCloseNotebookDocument((doc) => this.forget(doc)), vscode.window.tabGroups.onDidChangeTabs((event) => { @@ -109,6 +154,38 @@ export class BrowserInteractive implements vscode.Disposable { } }), ]; + this.updatePresentation(); + } + + private treeItem(doc: vscode.NotebookDocument): vscode.TreeItem { + const item = new vscode.TreeItem(notebookLabel(doc)); + item.id = doc.uri.toString(); + item.iconPath = new vscode.ThemeIcon('notebook'); + item.description = `webR · ${this.sessions.get(doc)?.state ?? 'Ready to start'}`; + item.tooltip = `webR · ${notebookLabel(doc)}\n${filesystemDetail}`; + item.contextValue = 'rInteractiveSession.webR'; + item.command = { + command: 'r.interactive.open', + title: 'Open webR notebook', + arguments: [doc], + }; + return item; + } + + private updatePresentation(): void { + if (this.disposed) { + return; + } + this.treeChanges.fire(); + const doc = this.target(); + if (!doc) { + this.status.hide(); + return; + } + const state = this.sessions.get(doc)?.state ?? 'Ready to start'; + this.status.text = `$(notebook) webR: ${notebookLabel(doc)} · ${state}`; + this.status.tooltip = `${filesystemDetail}\nManage this webR session`; + this.status.show(); } private forget(doc: vscode.NotebookDocument): void { @@ -116,9 +193,14 @@ export class BrowserInteractive implements vscode.Disposable { if (this.last === doc) { this.last = undefined; } + this.updatePresentation(); } private target(): vscode.NotebookDocument | undefined { + const text = vscode.window.activeTextEditor?.document.uri; + if (text?.scheme === WEBR_FILE_SCHEME) { + return this.fileNotebook(text); + } const active = vscode.window.activeNotebookEditor?.notebook; return active?.notebookType === notebookType ? active @@ -128,6 +210,22 @@ export class BrowserInteractive implements vscode.Disposable { )); } + fileNotebook(uri: vscode.Uri): vscode.NotebookDocument | undefined { + const owner = sessionFileOwner(uri); + if (owner) { + for (const [doc, current] of this.registrationsByNotebook) { + if (current.id === owner.id && current.generation === owner.generation) { + return doc; + } + } + } + } + + fileSelector(doc: vscode.NotebookDocument): string | undefined { + const current = this.registrationsByNotebook.get(doc); + return current ? `**/${current.generation}/**` : undefined; + } + 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. @@ -151,10 +249,30 @@ export class BrowserInteractive implements vscode.Disposable { } let session = this.sessions.get(doc); if (!session) { - session = new BrowserSession(this.controller, this.context.extensionUri, doc, () => - this.packageUpdates.fire(doc), + const id = this.notebookIds.get(doc) ?? crypto.randomUUID(); + this.notebookIds.set(doc, id); + const generation = crypto.randomUUID(); + session = new BrowserSession( + this.controller, + this.context.extensionUri, + doc, + () => this.packageUpdates.fire(doc), + () => this.updatePresentation(), + () => this.files.refresh(id, generation), + (path, create) => this.files.open(id, generation, path, create), ); - this.sessions.set(doc, session); + const owner = session; + this.sessions.set(doc, owner); + const registration = this.files.add({ + id, + generation, + label: `webR · ${notebookLabel(doc)}`, + initialDirectory: '/workspace', + files: () => owner.fileAccess(), + }); + this.registrationsByNotebook.set(doc, { id, generation, registration }); + this.fileOwners.fire(); + this.updatePresentation(); } return session; } @@ -182,6 +300,7 @@ export class BrowserInteractive implements vscode.Disposable { extension: this.context.extension.id, notebookEditor: editor, }); + this.updatePresentation(); return doc; } @@ -204,11 +323,21 @@ export class BrowserInteractive implements vscode.Disposable { return this.opening; } - async submit(code: string): Promise { + async submit(code: string, source?: vscode.Uri): Promise { if (!code.trim()) { return; } - const doc = await this.open(false, true); + const fileOwner = + source && source.scheme === WEBR_FILE_SCHEME ? this.fileNotebook(source) : undefined; + if (source?.scheme === WEBR_FILE_SCHEME && !fileOwner) { + throw new Error( + 'This webR file belongs to a closed session. Open the file from a running webR session.', + ); + } + const doc = fileOwner ? await this.reveal(fileOwner, true) : await this.open(false, true); + if (fileOwner && source && this.fileNotebook(source) !== fileOwner) { + throw new Error('The webR session that owns this file has ended.'); + } const session = this.session(doc); await session.run(async () => { const index = doc.cellCount; @@ -233,6 +362,26 @@ export class BrowserInteractive implements vscode.Disposable { }); } + async showSession(doc?: vscode.NotebookDocument): Promise { + return doc?.notebookType === notebookType ? this.reveal(doc, false) : this.open(); + } + + async openFile(path?: string, doc?: vscode.NotebookDocument): Promise { + const source = vscode.window.activeTextEditor?.document.uri; + if (!doc && source?.scheme === WEBR_FILE_SCHEME && !this.fileNotebook(source)) { + throw new Error( + 'This file belongs to a closed webR session. Choose a running notebook to browse its files.', + ); + } + const target = + doc?.notebookType === notebookType + ? doc + : (this.target() ?? (await this.open(false, true))); + this.session(target); + const owner = this.registrationsByNotebook.get(target)!; + await this.files.open(owner.id, owner.generation, path); + } + async import(uris?: readonly vscode.Uri[]): Promise { const files = uris ?? @@ -286,8 +435,15 @@ export class BrowserInteractive implements vscode.Disposable { if (!doc) { return; } + const registered = this.registrationsByNotebook.get(doc); + if (registered) { + this.registrationsByNotebook.delete(doc); + registered.registration.dispose(); + this.fileOwners.fire(); + } this.sessions.get(doc)?.dispose(); this.sessions.delete(doc); + this.updatePresentation(); } stopAll(): void { @@ -298,6 +454,11 @@ export class BrowserInteractive implements vscode.Disposable { async actions(): Promise { const actions = [ + { + label: 'Open webR Session File…', + detail: filesystemDetail, + run: () => this.openFile(), + }, { label: 'Import files into webR…', run: () => this.import() }, { label: 'Export a file from webR…', run: () => this.export() }, { label: 'Interrupt calculation', run: () => this.interrupt() }, diff --git a/src/web/languageService.ts b/src/web/languageService.ts index b5c369ff6..0d90b65e7 100644 --- a/src/web/languageService.ts +++ b/src/web/languageService.ts @@ -13,6 +13,7 @@ import { createWebRMessageTransports } from '../webr/messageTransports'; import { cachedWebRAssets } from '../webr/assetCache'; import { WEBR_BASE_URL } from '../webr/runtime'; import type { BrowserInteractive } from './interactive'; +import { WEBR_FILE_SCHEME } from '../webr/sessionFiles'; /** The service provides one retry action for startup and worker failures. */ class WorkerLanguageClient extends LanguageClient { @@ -37,18 +38,32 @@ interface ClientSlot { } /** A notebook filter is matched against the owning notebook URI, not the cell URI. */ -function notebookSelector(notebook: vscode.NotebookDocument): DocumentFilter[] { +function notebookSelector(notebook: vscode.NotebookDocument, files?: string): DocumentFilter[] { const pattern = notebook.uri.fsPath.replace(/[?*{}[\]]/g, (char) => `[${char}]`); - return rLanguages.map((language) => ({ + const selectors: DocumentFilter[] = rLanguages.map((language) => ({ language, notebook: { notebookType: interactiveType, scheme: notebook.uri.scheme, pattern }, })); + if (files) { + selectors.push( + ...rLanguages.map((language) => ({ + language, + scheme: WEBR_FILE_SCHEME, + pattern: files, + })), + ); + } + return selectors; } /** The provider selector matches fsPath. Virtual notebooks can also differ only * in URI authority or query. Keep their text and requests in the owning worker. */ -function notebookSession(owner: vscode.Uri, session: WebRLanguageSession): WebRLanguageSession { +function notebookSession( + owner: vscode.NotebookDocument, + session: WebRLanguageSession, + interactive: BrowserInteractive, +): WebRLanguageSession { return { close: () => session.close(), refreshPackageContext: () => session.refreshPackageContext(), @@ -60,12 +75,14 @@ function notebookSession(owner: vscode.Uri, session: WebRLanguageSession): WebRL const params = message.params as { textDocument?: { uri?: unknown } } | undefined; if (typeof params?.textDocument?.uri === 'string') { const cell = vscode.Uri.parse(params.textDocument.uri); - if ( - cell.scheme !== 'vscode-notebook-cell' || - cell.authority !== owner.authority || - cell.path !== owner.path || - cell.query !== owner.query - ) { + const matches = + cell.scheme === WEBR_FILE_SCHEME + ? interactive.fileNotebook(cell) === owner + : cell.scheme === 'vscode-notebook-cell' && + cell.authority === owner.uri.authority && + cell.path === owner.uri.path && + cell.query === owner.uri.query; + if (!matches) { return Promise.resolve( Message.isRequest(message) ? [{ jsonrpc: '2.0', id: message.id, result: null }] @@ -92,6 +109,7 @@ export class BrowserLanguageService implements vscode.Disposable { private readonly interactive: BrowserInteractive, ) { this.listeners = [ + interactive.onDidChangeFileOwners(() => this.refresh()), interactive.onDidChangePackages((notebook) => { const slot = this.clients.get(notebook.uri.toString()); if (slot?.client.isRunning()) { @@ -141,8 +159,16 @@ export class BrowserLanguageService implements vscode.Disposable { const desired = new Map(); if (settings.get('lsp.enabled', true)) { const sources = new Set(); + const filesFor = new Set(); const otherNotebooks = new Set(); for (const doc of vscode.workspace.textDocuments) { + if (doc.uri.scheme === WEBR_FILE_SCHEME) { + const owner = this.interactive.fileNotebook(doc.uri); + if (owner && rLanguages.includes(doc.languageId)) { + filesFor.add(owner); + } + continue; + } if ( rLanguages.includes(doc.languageId) && doc.uri.scheme !== 'vscode-notebook-cell' @@ -152,6 +178,7 @@ export class BrowserLanguageService implements vscode.Disposable { } for (const notebook of vscode.workspace.notebookDocuments) { if ( + !filesFor.has(notebook) && !notebook .getCells() .some((cell) => rLanguages.includes(cell.document.languageId)) @@ -159,7 +186,10 @@ export class BrowserLanguageService implements vscode.Disposable { continue; } if (notebook.notebookType === interactiveType) { - desired.set(notebook.uri.toString(), notebookSelector(notebook)); + desired.set( + notebook.uri.toString(), + notebookSelector(notebook, this.interactive.fileSelector(notebook)), + ); } else { otherNotebooks.add(notebook.notebookType); } @@ -225,7 +255,7 @@ export class BrowserLanguageService implements vscode.Disposable { } current.session = session; return createWebRMessageTransports( - key === 'source' ? session : notebookSession(vscode.Uri.parse(key), session), + owner ? notebookSession(owner, session, this.interactive) : session, ); }, { diff --git a/src/web/session.ts b/src/web/session.ts index 7c9480706..86ffc637a 100644 --- a/src/web/session.ts +++ b/src/web/session.ts @@ -5,6 +5,7 @@ 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 { createWebRFileAccess, type WebRFileAccess } from '../webr/filesystem'; import { BrowserViewers } from './viewers'; import { webRWidgetHtml } from '../webr/widgetHtml'; @@ -25,7 +26,12 @@ interface ActiveCell { export class BrowserSession implements vscode.Disposable { private readonly supportsInterrupt = globalThis.crossOriginIsolated === true && typeof SharedArrayBuffer !== 'undefined'; - private worker?: { runtime: WebR; console: WebRConsole; ready: Promise }; + private worker?: { + runtime: WebR; + console: WebRConsole; + ready: Promise; + files: WebRFileAccess; + }; private current?: ActiveCell; private queue = Promise.resolve(); private executionOrder = 0; @@ -43,6 +49,9 @@ export class BrowserSession implements vscode.Disposable { extension: vscode.Uri, doc: vscode.NotebookDocument, private readonly packagesChanged: () => void, + private readonly stateChanged: () => void, + private readonly filesChanged: () => void, + private readonly openFile: (path: string, create: boolean) => Promise, ) { this.viewers = new BrowserViewers(extension, doc, (method, params) => this.run(async () => { @@ -55,6 +64,22 @@ export class BrowserSession implements vscode.Disposable { ); } + async fileAccess(): Promise { + const worker = this.getWorker(); + await worker.ready; + return worker.files; + } + + get state(): string { + if (this.closed || this.failed) { + return 'Stopped'; + } + if (this.current) { + return 'Running'; + } + return this.worker ? 'Ready' : 'Ready to start'; + } + get packageContext(): WebRPackageContext | undefined { return this.packages; } @@ -97,7 +122,6 @@ export class BrowserSession implements vscode.Disposable { if (!this.worker) { const runtime = new WebR({ baseUrl: WEBR_BASE_URL, - homedir: sessionDirectory, channelType: this.supportsInterrupt ? ChannelType.SharedArrayBuffer : ChannelType.PostMessage, @@ -115,17 +139,33 @@ export class BrowserSession implements vscode.Disposable { 'The webR worker ended. Restart the session to run more code.', { cause: error }, ); + this.stateChanged(); }, ); - const ready = session.start().catch((error: unknown) => { - session.close(); - if (this.worker?.console === session) { - this.clearPackages(); - this.worker = undefined; - } - throw error; - }); - this.worker = { runtime, console: session, ready }; + const ready = session + .start() + .then(async () => { + // The execution working directory is distinct from webR's retained + // /home/web_user. Both live in this worker's virtual filesystem. + await runtime.FS.mkdir(sessionDirectory); + await runtime.evalRVoid('base::setwd(directory)', { + env: { directory: sessionDirectory }, + }); + }) + .catch((error: unknown) => { + session.close(); + if (this.worker?.console === session) { + this.clearPackages(); + this.worker = undefined; + } + throw error; + }); + const files = createWebRFileAccess(runtime, (operation) => this.run(operation)); + this.worker = { runtime, console: session, ready, files }; + void ready.then( + () => this.stateChanged(), + () => this.stateChanged(), + ); } return this.worker; } @@ -171,6 +211,7 @@ export class BrowserSession implements vscode.Disposable { ), }; this.current = active; + this.stateChanged(); execution.executionOrder = ++this.executionOrder; execution.start(Date.now()); let success = false; @@ -208,11 +249,23 @@ export class BrowserSession implements vscode.Disposable { if (this.current === active) { this.current = undefined; execution.end(success, Date.now()); + this.filesChanged(); + this.stateChanged(); } } } private onEvent(event: WebRConsoleEvent): void { + if (event.type === 'openFile') { + if (!this.closed) { + void this.openFile(event.path, event.create).catch((error: unknown) => { + if (!this.closed) { + void vscode.window.showErrorMessage(String(error)); + } + }); + } + return; + } if (event.type === 'packageContext') { if (this.closed || this.failed) { return; From 7ee24b2e7ec4dca6181e933a42b28c6cf9c3baeb Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 07:40:16 +0800 Subject: [PATCH 3/6] Protect the active R directory and safely page mounted project files --- src/interactive/backends/webr.ts | 1 + src/test/node/interactiveWebR.test.ts | 41 +++++++ src/test/node/webRFileSystem.test.ts | 39 +++++++ src/webr/fileSystemWorker.ts | 153 +++++++++++++++++++++++--- 4 files changed, 216 insertions(+), 18 deletions(-) diff --git a/src/interactive/backends/webr.ts b/src/interactive/backends/webr.ts index 3b9046324..348e780bb 100644 --- a/src/interactive/backends/webr.ts +++ b/src/interactive/backends/webr.ts @@ -77,6 +77,7 @@ export class WebRBackend implements SessionBackend { await console.start(); await runtime.FS.mkdir('/project'); await runtime.FS.mount('NODEFS', { root: this.settings.directory }, '/project'); + await runtime.evalRVoid('webr::eval_js("globalThis.Module.vscodeRPinFileProject()")'); await runtime.evalRVoid('base::setwd("/project")'); this.webRFiles = createWebRFileAccess(runtime); const rVersion = await runtime.evalRString('R.version.string'); diff --git a/src/test/node/interactiveWebR.test.ts b/src/test/node/interactiveWebR.test.ts index 50de74964..fd1b2256d 100644 --- a/src/test/node/interactiveWebR.test.ts +++ b/src/test/node/interactiveWebR.test.ts @@ -380,6 +380,47 @@ suite('R Interactive webR provider', function () { assert.deepEqual(openedPaths(custom), []); }); + test('pages native project files into read-only snapshots while keeping generic file access isolated', async () => { + const files = new AgentWebRFileAccess(client); + const title = 'Project note'; + const name = "notes #1 ('demo').txt"; + const target = path.join(project, name); + fs.writeFileSync(target, 'first line\nsecond line\n'); + const page = await submit( + `file.show(${JSON.stringify(name)}, title=${JSON.stringify(title)}, delete.file=TRUE)`, + ); + assert.equal((await wait(page, 'finished')).data.state, 'success', output(page)); + const notification = await wait(page, 'notification'); + assert.equal(notification.data.method, 'webR/openFile'); + const params = notification.data.params as { path: string; create: boolean }; + assert.equal(params.create, false); + assert.match(params.path, /^\/tmp\/.+\.txt$/); + assert.equal((await files.stat(params.path)).readonly, true); + assert.equal( + new TextDecoder().decode((await files.readFile(params.path)).bytes), + 'first line\nsecond line\n', + ); + assert.equal(fs.existsSync(target), false); + fs.writeFileSync(target, 'retained'); + const keep = await submit(`file.show(${JSON.stringify(name)})`); + assert.equal((await wait(keep, 'finished')).data.state, 'success', output(keep)); + await wait(keep, 'notification'); + assert.equal(fs.readFileSync(target, 'utf8'), 'retained'); + await assert.rejects(files.readFile('/project/' + name), { code: 'NoPermissions' }); + + // A directory junction works without special symlink privileges on Windows. + const outside = path.join(root, 'outside-project'); + fs.mkdirSync(outside); + fs.writeFileSync(path.join(outside, 'example.txt'), 'unrelated'); + fs.symlinkSync(outside, path.join(project, 'linked'), 'junction'); + const link = await submit('file.show("linked/example.txt", delete.file=TRUE)'); + assert.equal((await wait(link, 'finished')).data.state, 'error'); + assert.equal(fs.readFileSync(path.join(outside, 'example.txt'), 'utf8'), 'unrelated'); + assert.ok( + !events.some((event) => event.executionId === link && event.type === 'notification'), + ); + }); + test('downloads a repository index with private host scratch files and the R project as its working directory', async () => { // This makes the upstream synchronous HTTP bridge fail in the launcher // directory even when a privileged runner could write to a read-only folder. diff --git a/src/test/node/webRFileSystem.test.ts b/src/test/node/webRFileSystem.test.ts index 247694bcf..c25d63902 100644 --- a/src/test/node/webRFileSystem.test.ts +++ b/src/test/node/webRFileSystem.test.ts @@ -84,6 +84,45 @@ suite('webR virtual filesystem', function () { await assert.rejects(files.stat(renamed), { code: 'FileNotFound' }); }); + test('protects the working directory and its ancestors during directory mutations', async () => { + const active = folder + '/active'; + const cwd = active + '/nested'; + const sibling = folder + '/act'; + await files.createDirectory(active); + await files.createDirectory(cwd); + await files.createDirectory(sibling); + const original = await runtime.evalRString('getwd()'); + await runtime.evalRVoid('setwd(path); writeLines("before", "original.txt")', { + env: { path: cwd }, + }); + try { + await assert.rejects(files.rename(active, folder + '/moved', { overwrite: false }), { + code: 'NoPermissions', + }); + await assert.rejects(files.rename(sibling, active, { overwrite: true }), { + code: 'NoPermissions', + }); + await assert.rejects(files.rename(sibling, cwd, { overwrite: true }), { + code: 'NoPermissions', + }); + await assert.rejects(files.delete(active, { recursive: true }), { + code: 'NoPermissions', + }); + assert.equal(await runtime.evalRString('getwd()'), cwd); + assert.equal(await runtime.evalRString('readLines("original.txt")'), 'before'); + await runtime.evalRVoid('writeLines("after", "relative.txt")'); + assert.equal( + new TextDecoder().decode((await files.readFile(cwd + '/relative.txt')).bytes), + 'after\n', + ); + await assert.rejects(files.stat(folder + '/moved'), { code: 'FileNotFound' }); + // A common name prefix is not an ancestor. + await files.rename(sibling, folder + '/sibling', { overwrite: false }); + } finally { + await runtime.evalRVoid('setwd(path)', { env: { path: original } }); + } + }); + test('rejects a stale save even when R preserves the original size and modification time', async () => { const file = folder + '/sample.bin'; // R may rewrite data and restore its timestamp, as data-copying tools do. diff --git a/src/webr/fileSystemWorker.ts b/src/webr/fileSystemWorker.ts index f3ab990a0..e65b397ce 100644 --- a/src/webr/fileSystemWorker.ts +++ b/src/webr/fileSystemWorker.ts @@ -90,6 +90,17 @@ export const fileSystemBootstrap = String.raw`(() => { ) fail('NoPermissions', 'The webR filesystem root cannot be replaced or removed.'); } + // Emscripten keeps cwd as a path string. Moving an ancestor would leave + // R resolving subsequent relative paths against the old, missing directory. + function protectWorkingDirectory(path) { + const cwd = fs.cwd(); + if (cwd === path || cwd.startsWith(path + '/')) { + fail( + 'NoPermissions', + 'Change the R working directory before moving or deleting its directory tree.', + ); + } + } function metadata(path, node) { const s = node.node_ops.getattr(node); const directory = fs.isDir(node.mode); @@ -258,11 +269,11 @@ export const fileSystemBootstrap = String.raw`(() => { case 'delete': { mutable(q.path); node = lookup(q.path); + if (fs.isDir(node.mode)) protectWorkingDirectory(q.path); if (fs.isDir(node.mode) && q.recursive) { const nodes = []; walk(q.path, nodes); - // Check the R working directory and every parent's deletion - // permissions before removing any children. + // Check every parent's deletion permissions before removing children. for (const [, child] of nodes) { const error = fs.mayDelete(child.parent, child.name, fs.isDir(child.mode)); if (error) throw new fs.ErrnoError(error); @@ -282,8 +293,12 @@ export const fileSystemBootstrap = String.raw`(() => { if (q.to.startsWith(q.path + '/')) fail('NoPermissions', 'A directory cannot be moved inside itself.'); if (destination && !q.overwrite) fail('FileExists', 'The target already exists.'); + if (destination && fs.isDir(destination.mode)) protectWorkingDirectory(q.to); // A moved tree must not move mountpoints, special nodes or reserved scratch. - if (fs.isDir(node.mode)) walk(q.path, []); + if (fs.isDir(node.mode)) { + protectWorkingDirectory(q.path); + walk(q.path, []); + } fs.rename(q.path, q.to); return null; } @@ -303,14 +318,125 @@ export const fileSystemBootstrap = String.raw`(() => { parts(result); return result; } + let project; + // The desktop backend calls this once, immediately after mounting its trusted + // project. A later NODEFS mount at the same virtual name cannot replace it. + module.vscodeRPinFileProject = () => { + if (project) return null; + const mount = fs.lookupNode(fs.root, 'project').mounted; + if (!mount || mount.type !== fs.filesystems.NODEFS) + throw Error('Expected the native project mount.'); + const builtin = (name) => + globalThis.process.getBuiltinModule?.(name) ?? + globalThis.process.mainModule.require(name); + const host = builtin('node:fs'), + paths = builtin('node:path'); + project = { mount, host, paths, root: host.realpathSync(mount.opts.root) }; + return null; + }; + function isProject(path) { + if (!project || (path !== '/project' && !path.startsWith('/project/'))) return false; + const mount = fs.lookupNode(fs.root, 'project').mounted; + if (mount !== project.mount || mount.type !== fs.filesystems.NODEFS) + fail('NoPermissions', 'The native project mount has changed.'); + return true; + } + function projectFile(path) { + const { mount, host, paths, root } = project; + if (host.realpathSync(mount.opts.root) !== root) + fail('NoPermissions', 'The native project directory has changed.'); + let node = mount.root, + native = root, + stat; + for (const name of parts(path).slice(1)) { + node = fs.lookupNode(node, name); + native = paths.join(native, name); + stat = host.lstatSync(native); + if ( + node.mounted || + node.mount !== mount || + stat.isSymbolicLink() || + (!stat.isDirectory() && !stat.isFile()) + ) + fail( + 'NoPermissions', + 'The pager requires a regular file inside the native project.', + ); + } + const relative = paths.relative(root, host.realpathSync(native)); + if ( + !stat?.isFile() || + !relative || + relative === '..' || + relative.startsWith('..' + paths.sep) || + paths.isAbsolute(relative) + ) + fail('NoPermissions', 'The pager requires a regular file inside the native project.'); + return { native, stat }; + } + function projectPage(path) { + const { host } = project; + const file = projectFile(path); + const fd = host.openSync( + file.native, + host.constants.O_RDONLY | (host.constants.O_NOFOLLOW ?? 0), + ); + try { + const opened = host.fstatSync(fd); + if ( + !opened.isFile() || + opened.size > 1024 * 1024 || + opened.dev !== file.stat.dev || + opened.ino !== file.stat.ino + ) + fail('Unavailable', 'The native project file changed or exceeds 1 MiB.'); + const bytes = new Uint8Array(opened.size + 1); + let size = 0; + while (size < bytes.length) { + const count = host.readSync(fd, bytes, size, bytes.length - size, null); + if (!count) break; + size += count; + } + if (size !== opened.size) + fail('Unavailable', 'The native project file changed while reading.'); + return { + bytes: bytes.subarray(0, size), + remove() { + const current = projectFile(path); + if ( + current.stat.dev !== opened.dev || + current.stat.ino !== opened.ino || + current.stat.size !== opened.size || + current.stat.mtimeMs !== opened.mtimeMs + ) + fail('Unavailable', 'The native project file changed before removal.'); + host.unlinkSync(current.native); + }, + }; + } finally { + host.closeSync(fd); + } + } module.vscodeRFileHook = (encoded) => { const q = JSON.parse(decoder.decode(asBytes(encoded))); let path = absolute(q.cwd, q.path); if (q.action === 'pager') { - const original = lookup(path); - if (!fs.isFile(original.mode) || original.node_ops.getattr(original).size > 1024 * 1024) - fail('Unavailable', 'The webR pager accepts regular text files up to 1 MiB.'); - const text = decoder.decode(fs.readFile(path)).replace(/[^\n]\x08/g, ''); + let bytes, remove; + if (isProject(path)) { + const page = projectPage(path); + bytes = page.bytes; + remove = page.remove; + } else { + const original = lookup(path); + if ( + !fs.isFile(original.mode) || + original.node_ops.getattr(original).size > 1024 * 1024 + ) + fail('Unavailable', 'The webR pager accepts regular text files up to 1 MiB.'); + bytes = fs.readFile(path); + remove = () => fs.unlink(path); + } + const text = decoder.decode(bytes).replace(/[^\n]\x08/g, ''); const title = String(q.title || 'R help') .replace(/[^A-Za-z0-9_-]+/g, '-') @@ -321,21 +447,12 @@ export const fileSystemBootstrap = String.raw`(() => { // Exclusive creation avoids following or replacing an existing name. fs.writeFile(output, new TextEncoder().encode(text), { flags: 1 | 64 | 128 | 131072 }); fs.chmod(output, 0o444); - if (q.remove === true) fs.unlink(path); + if (q.remove === true) remove(); path = output; } else if (q.action === 'editor') { // A desktop /project path is opened by the owning native workspace, // which performs its own containment check. Every other path is MEMFS. - let nativeProject = false; - if (path === '/project' || path.startsWith('/project/')) { - try { - const mount = fs.lookupNode(fs.root, 'project').mounted; - nativeProject = !!mount && mount.type === fs.filesystems.NODEFS; - } catch (e) { - if (!missing(e)) throw e; - } - } - if (!nativeProject) { + if (!isProject(path)) { const node = lookup(path, true); if (node && !fs.isFile(node.mode)) fail('FileIsADirectory', 'Expected a regular file.'); From 14f710af6f68362ad724d3cf4a8a05699cde9b80 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 07:42:45 +0800 Subject: [PATCH 4/6] Keep the original webR edit revision when a dirty file is restored --- src/extension.ts | 2 +- src/interactive/manager.ts | 1 + src/test/suite/webRSessionFiles.test.ts | 108 ++++++++++++++- src/webr/sessionFiles.ts | 174 +++++++++++++++++++++--- 4 files changed, 261 insertions(+), 24 deletions(-) diff --git a/src/extension.ts b/src/extension.ts index a2efbe4d8..efc7816ba 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -281,7 +281,7 @@ export async function activate( // initialize the package/help related functions globalRHelp = await rHelp.initializeHelp(context, rExtension); - const sessionFiles = new WebRSessionFiles(); + const sessionFiles = new WebRSessionFiles(context.workspaceState); context.subscriptions.push(new InteractiveManager(context, sessionFiles), sessionFiles); // register codelens and completion providers for r markdown and r files diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 4090edc50..de1574aa2 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -320,6 +320,7 @@ export class InteractiveManager webR.map((manifest) => ({ label: manifest.label, description: this.sessionChoiceDescription(manifest), + detail: manifest.directory + ' · ' + manifest.id.slice(0, 8), manifest, })), { title: 'Open webR Session File' }, diff --git a/src/test/suite/webRSessionFiles.test.ts b/src/test/suite/webRSessionFiles.test.ts index 176559a30..6e6a7d127 100644 --- a/src/test/suite/webRSessionFiles.test.ts +++ b/src/test/suite/webRSessionFiles.test.ts @@ -17,13 +17,118 @@ suite('webR session filesystem provider', () => { assert.equal(sessionFileOwner(uri.with({ query: 'unexpected' })), undefined); }); + test('a restored dirty backup keeps its original compare revision across provider disposal and rereads', async () => { + const stubs = sinon.createSandbox(), + data = new Map(); + const state = { + keys: () => [...data.keys()], + get: (key: string) => data.get(key), + update: (key: string, value: unknown) => { + data.set(key, value); + return Promise.resolve(); + }, + } as vscode.Memento; + stubs + .stub(vscode.workspace, 'registerFileSystemProvider') + .returns(new vscode.Disposable(() => {})); + const uri = sessionFileUri('one', 'first', '/tmp/edit.R'); + let dirty = false, + editorText = 'A', + bytes = 'A', + visible = true; + const document = { + uri, + get isDirty() { + return dirty; + }, + getText: () => editorText, + } as vscode.TextDocument; + stubs.stub(vscode.workspace, 'textDocuments').get(() => (visible ? [document] : [])); + const write = stubs + .stub() + .callsFake((_path: string, content: Uint8Array, opts: { expected?: string }) => { + if (opts.expected && opts.expected !== bytes) { + throw Error('WebRFileError[FileModifiedSince]: changed'); + } + bytes = new TextDecoder().decode(content); + return Promise.resolve(bytes); + }); + const access = { + readFile: () => + Promise.resolve({ bytes: new TextEncoder().encode(bytes), version: bytes }), + stat: () => + Promise.resolve({ type: 'file', size: 1, mtime: 0, ctime: 0, version: bytes }), + writeFile: write, + } as unknown as WebRFileAccess; + const provider = (memento?: vscode.Memento) => { + const files = new WebRSessionFiles(memento); + files.add({ + id: 'one', + generation: 'first', + label: 'test', + initialDirectory: '/', + files: () => Promise.resolve(access), + }); + return files; + }; + let files = provider(state); + try { + assert.equal(new TextDecoder().decode(await files.readFile(uri)), 'A'); + dirty = true; + editorText = 'X'; + files.dispose(); + bytes = 'B'; + files = provider(state); + // An unrelated fresh read sees B, including before VS Code exposes + // its restored document. Neither read describes X's last saved base. + visible = false; + await files.readFile(uri); + visible = true; + assert.equal(new TextDecoder().decode(await files.readFile(uri)), 'B'); + await assert.rejects( + files.writeFile(uri, new TextEncoder().encode('X'), { + create: true, + overwrite: true, + }), + /changed in webR/, + ); + assert.equal(bytes, 'B'); + assert.equal((write.firstCall.args[2] as { expected: string }).expected, 'A'); + files.dispose(); + files = provider(); + visible = false; + await files.readFile(uri); + visible = true; + await files.readFile(uri); + await assert.rejects( + files.writeFile(uri, new TextEncoder().encode('X'), { + create: true, + overwrite: true, + }), + /original editor revision is unavailable/, + ); + assert.equal(bytes, 'B'); + sinon.assert.calledOnce(write); + } finally { + files.dispose(); + stubs.restore(); + } + }); + test('keeps a dirty editor’s read revision on reconnect and refuses writes into a replacement generation', async () => { const stubs = sinon.createSandbox(); stubs .stub(vscode.workspace, 'registerFileSystemProvider') .returns(new vscode.Disposable(() => {})); const uri = sessionFileUri('one', 'first', '/tmp/edit.R'); - const document = { uri, isDirty: true } as vscode.TextDocument; + let dirty = false; + const document = { + uri, + get isDirty() { + return dirty; + }, + getText: () => '*', + } as vscode.TextDocument; stubs.stub(vscode.workspace, 'textDocuments').get(() => [document]); const files = new WebRSessionFiles(); let revision = '1'; @@ -53,6 +158,7 @@ suite('webR session filesystem provider', () => { try { const first = bind('first'); assert.deepEqual(await files.readFile(uri), new Uint8Array([42])); + dirty = true; first.dispose(); revision = '2'; const same = bind('first'); diff --git a/src/webr/sessionFiles.ts b/src/webr/sessionFiles.ts index ba3df7122..b224c272e 100644 --- a/src/webr/sessionFiles.ts +++ b/src/webr/sessionFiles.ts @@ -2,6 +2,7 @@ import * as vscode from 'vscode'; import type { WebRFileAccess, WebRFileStat } from './filesystem'; export const WEBR_FILE_SCHEME = 'vscode-r-webr'; +const baselineKey = 'r.webR.sessionFileBaselines.v1'; const identifier = /^[A-Za-z0-9_-]{1,100}$/; function validPath(path: string): boolean { @@ -57,6 +58,8 @@ export interface WebRFileSession { initialDirectory: string; /** The genuine host workspace URI mounted at /project in a desktop agent. */ projectUri?: vscode.Uri; + /** Owning notebook or project, for disambiguating similarly named sessions. */ + location?: vscode.Uri; onOpen?(uri: vscode.Uri): void; } @@ -110,7 +113,14 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo private readonly sessions = new Map(); private readonly changed = new vscode.EventEmitter(); readonly onDidChangeFile = this.changed.event; + // A read issued by the file service before a TextDocument opens may be a + // background read or part of restoring a dirty backup. It is provisional + // until a clean document opens with it, and never authorizes a dirty save. + private readonly pendingReads = new Map(); private readonly versions = new Map(); + private readonly recovered = new Set(); + private readonly pendingReloads = new Map(); + private savingState = Promise.resolve(); private readonly observed = new Map(); private readonly watched = new Map(); private readonly queued = new Map(); @@ -120,15 +130,109 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo private readonly registration: vscode.Disposable; private readonly closeListener: vscode.Disposable; - constructor() { + constructor(private readonly workspaceState?: vscode.Memento) { + const saved = workspaceState?.get(baselineKey); + if (Array.isArray(saved)) { + for (const entry of saved as unknown[]) { + if ( + !Array.isArray(entry) || + entry.length !== 2 || + typeof entry[0] !== 'string' || + typeof entry[1] !== 'string' + ) { + continue; + } + const [id, version] = entry as [string, string]; + if (sessionFileOwner(vscode.Uri.parse(id))) { + this.versions.set(id, version); + this.recovered.add(id); + } + } + } this.registration = vscode.workspace.registerFileSystemProvider(WEBR_FILE_SCHEME, this, { isCaseSensitive: true, }); - this.closeListener = vscode.workspace.onDidCloseTextDocument((doc) => { - if (doc.uri.scheme === WEBR_FILE_SCHEME) { - this.versions.delete(doc.uri.toString()); - } - }); + this.closeListener = vscode.Disposable.from( + vscode.workspace.onDidOpenTextDocument((doc) => { + if (doc.uri.scheme !== WEBR_FILE_SCHEME) { + return; + } + const id = doc.uri.toString(), + pending = this.pendingReads.get(id); + if (!doc.isDirty && pending !== undefined && !this.recovered.has(id)) { + void this.remember(id, pending); + } + }), + vscode.workspace.onDidChangeTextDocument(({ document, contentChanges }) => { + if (!contentChanges.length || document.uri.scheme !== WEBR_FILE_SCHEME) { + return; + } + const id = document.uri.toString(), + reload = this.pendingReloads.get(id); + if (reload) { + this.pendingReloads.delete(id); + if ( + !document.isDirty && + !this.recovered.has(id) && + document.getText() === reload.text + ) { + void this.remember(id, reload.version); + } + } + }), + vscode.workspace.onDidCloseTextDocument((doc) => { + if (doc.uri.scheme !== WEBR_FILE_SCHEME || doc.isDirty) { + return; + } + const id = doc.uri.toString(); + this.pendingReads.delete(id); + this.pendingReloads.delete(id); + this.recovered.delete(id); + void this.remember(id, undefined); + }), + ); + } + + /** Store only opaque revisions and generation-qualified URIs in this workspace. */ + private remember(id: string, version: string | undefined): Promise { + if (this.versions.get(id) === version) { + return this.savingState; + } + if (version === undefined) { + this.versions.delete(id); + } else { + this.versions.set(id, version); + } + if (!this.workspaceState) { + return Promise.resolve(); + } + const saved = [...this.versions]; + this.savingState = this.savingState + .then(async () => { + await this.workspaceState!.update(baselineKey, saved.length ? saved : undefined); + }) + .catch((error: unknown) => { + // The live editor still has its baseline. A restored dirty editor + // lacking a persisted version will fail closed. + console.error('Could not retain the webR session file revision', error); + }); + return this.savingState; + } + + private dirty(id: string): boolean { + return ( + vscode.workspace.textDocuments.some( + (doc) => doc.isDirty && doc.uri.toString() === id, + ) || + vscode.window.tabGroups.all.some((group) => + group.tabs.some( + (tab) => + tab.isDirty && + tab.input instanceof vscode.TabInputText && + tab.input.uri.toString() === id, + ), + ) + ); } add(session: WebRFileSession): vscode.Disposable { @@ -140,14 +244,11 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo return; } this.sessions.delete(identity); - for (const uri of new Set([...this.versions.keys(), ...this.observed.keys()])) { + // Disconnect and extension-host shutdown may both discard this + // registry before VS Code restores its unsaved document. + for (const uri of this.observed.keys()) { const owner = sessionFileOwner(vscode.Uri.parse(uri)); if (owner && key(owner.id, owner.generation) === identity) { - // A dirty editor can reconnect to this generation. Its next - // save must still compare the original read revision. - if (!vscode.workspace.textDocuments.some((doc) => doc.uri.toString() === uri)) { - this.versions.delete(uri); - } this.observed.delete(uri); } } @@ -205,11 +306,21 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo async readFile(uri: vscode.Uri): Promise { const result = await this.access(uri, (fs, path) => fs.readFile(path)); const id = uri.toString(); - const dirty = vscode.workspace.textDocuments.some( - (doc) => doc.isDirty && doc.uri.toString() === id, - ); - if (!dirty || !this.versions.has(id)) { - this.versions.set(id, result.version); + if (!this.dirty(id)) { + this.pendingReads.set(id, result.version); + const doc = vscode.workspace.textDocuments.find((item) => item.uri.toString() === id); + // A read by another consumer may see newer bytes than a clean + // editor has received. Never replace a recovered edit baseline. + if (doc && !this.recovered.has(id)) { + if (this.versions.get(id) !== result.version) { + const text = new TextDecoder().decode(result.bytes); + if (doc.getText() === text) { + await this.remember(id, result.version); + } else { + this.pendingReloads.set(id, { version: result.version, text }); + } + } + } } this.observed.set(id, result.version); return result.bytes; @@ -221,12 +332,21 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo options: { create: boolean; overwrite: boolean }, ): Promise { const id = uri.toString(); - const before = this.versions.get(id); + const original = this.versions.get(id); + const dirty = this.dirty(id); + if (dirty && original === undefined) { + throw vscode.FileSystemError.Unavailable( + 'Cannot safely overwrite this webR file because the original editor revision is unavailable. Compare with the current session file or use Save As to keep your edits.', + ); + } + const before = original ?? this.pendingReads.get(id); const existed = before !== undefined || this.observed.has(id) || !options.create; const version = await this.access(uri, (fs, path) => fs.writeFile(path, bytes, { ...options, expected: before }), ); - this.versions.set(id, version); + this.pendingReads.set(id, version); + this.recovered.delete(id); + await this.remember(id, version); this.observed.set(id, version); this.change(uri, existed ? vscode.FileChangeType.Changed : vscode.FileChangeType.Created); } @@ -238,7 +358,9 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo async delete(uri: vscode.Uri, options: { recursive: boolean }): Promise { await this.access(uri, (fs, path) => fs.delete(path, options)); - this.versions.delete(uri.toString()); + this.pendingReads.delete(uri.toString()); + this.recovered.delete(uri.toString()); + await this.remember(uri.toString(), undefined); this.observed.delete(uri.toString()); this.change(uri, vscode.FileChangeType.Deleted); } @@ -252,7 +374,9 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo ); } await this.access(from, (fs, path) => fs.rename(path, dest.path, options)); - this.versions.delete(from.toString()); + this.pendingReads.delete(from.toString()); + this.recovered.delete(from.toString()); + await this.remember(from.toString(), undefined); this.observed.delete(from.toString()); this.change(from, vscode.FileChangeType.Deleted); this.change(to, vscode.FileChangeType.Created); @@ -343,7 +467,10 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo await vscode.window.showQuickPick( [...this.sessions.values()].map((session) => ({ label: session.label, - description: 'webR', + description: 'webR · ' + session.id.slice(0, 8), + detail: + (session.projectUri ?? session.location)?.toString(true) ?? + 'Generation ' + session.generation.slice(0, 8), session, })), { title: 'Open webR Session File' }, @@ -492,6 +619,9 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo this.sessions.clear(); this.watched.clear(); this.queued.clear(); + this.pendingReads.clear(); + this.pendingReloads.clear(); + this.recovered.clear(); this.versions.clear(); this.observed.clear(); } From 90593afb79d4069499e3d2d5e9f92e5a8c745e4a Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 07:45:03 +0800 Subject: [PATCH 5/6] Retain edit baselines for browser session files as well --- src/web/interactive.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/web/interactive.ts b/src/web/interactive.ts index b4a2c4f56..5ce3695a3 100644 --- a/src/web/interactive.ts +++ b/src/web/interactive.ts @@ -29,7 +29,7 @@ export class BrowserInteractive implements vscode.Disposable { 'R (webR)', ); private readonly sessions = new Map(); - private readonly files = new WebRSessionFiles(); + private readonly files: WebRSessionFiles; private readonly treeChanges = new vscode.EventEmitter(); private readonly registrationsByNotebook = new Map< vscode.NotebookDocument, @@ -50,6 +50,7 @@ export class BrowserInteractive implements vscode.Disposable { private disposed = false; constructor(private readonly context: vscode.ExtensionContext) { + this.files = new WebRSessionFiles(context.workspaceState); this.controller.supportedLanguages = ['r']; this.controller.supportsExecutionOrder = true; this.controller.description = 'webR (experimental) · R in this browser'; From 4096b81bf562631b512441e11557405b606d7f58 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 07:46:33 +0800 Subject: [PATCH 6/6] Disambiguate browser notebooks in the session file picker --- src/web/interactive.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/web/interactive.ts b/src/web/interactive.ts index 5ce3695a3..f6a1e4184 100644 --- a/src/web/interactive.ts +++ b/src/web/interactive.ts @@ -267,7 +267,8 @@ export class BrowserInteractive implements vscode.Disposable { const registration = this.files.add({ id, generation, - label: `webR · ${notebookLabel(doc)}`, + label: notebookLabel(doc), + location: doc.uri, initialDirectory: '/workspace', files: () => owner.fileAccess(), });