From 42c3922864dffaeef2519329c0348b4831fa73c7 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 18:49:39 +0800 Subject: [PATCH 1/4] Open portable .webrproj bundles as webR Interactive workspaces --- CONTRIBUTING.md | 2 + ThirdPartyNotices.txt | 80 ++++ package.json | 24 +- pnpm-lock.yaml | 12 + src/extension.ts | 9 +- src/interactive/agent.ts | 1 + src/interactive/backends/webr.ts | 76 +++- src/interactive/launcher.ts | 15 +- src/interactive/manager.ts | 202 ++++++-- src/interactive/projectHost.ts | 326 +++++++++++++ src/interactive/projectStorage.ts | 481 ++++++++++++++++++++ src/interactive/protocol.ts | 3 + src/languageService.ts | 100 ++-- src/test/node/interactiveWebR.test.ts | 73 +++ src/test/node/webRProjectArchive.test.ts | 108 +++++ src/test/node/webRProjectStorage.test.ts | 225 +++++++++ src/test/suite/webRProjectHost.test.ts | 22 + src/test/suite/webRProjectWorkspace.test.ts | 148 ++++++ src/test/web/webRProject.cjs | 162 +++++++ src/web/extension.ts | 20 +- src/web/files.ts | 13 +- src/web/interactive.ts | 178 +++++++- src/web/languageService.ts | 26 +- src/web/project.ts | 408 +++++++++++++++++ src/web/projectMirror.ts | 137 ++++++ src/web/session.ts | 45 +- src/webr/fileRevisions.ts | 175 +++++++ src/webr/projectArchive.ts | 205 +++++++++ src/webr/projectWorkspace.ts | 448 ++++++++++++++++++ src/webr/sessionFiles.ts | 174 ++----- website/docs/features/r-interactive.md | 4 + website/docs/features/webr.md | 37 ++ 32 files changed, 3671 insertions(+), 268 deletions(-) create mode 100644 src/interactive/projectHost.ts create mode 100644 src/interactive/projectStorage.ts create mode 100644 src/test/node/webRProjectArchive.test.ts create mode 100644 src/test/node/webRProjectStorage.test.ts create mode 100644 src/test/suite/webRProjectHost.test.ts create mode 100644 src/test/suite/webRProjectWorkspace.test.ts create mode 100644 src/test/web/webRProject.cjs create mode 100644 src/web/project.ts create mode 100644 src/web/projectMirror.ts create mode 100644 src/webr/fileRevisions.ts create mode 100644 src/webr/projectArchive.ts create mode 100644 src/webr/projectWorkspace.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3d6bea7e1..81616d7f1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -102,6 +102,8 @@ documents, then edits a declaration and checks the new symbol. Run `pnpm run test:web` for the headless Chromium suite. The test runner downloads VS Code for the Web, the R syntax extension, and Playwright's Chromium. The first R session fetches the pinned webR assets and package library over HTTPS. Linux CI images also need the Playwright browser system dependencies. To provision Chromium and its system dependencies explicitly for the tested runner, run `pnpm dlx playwright@1.65.1 install --with-deps chromium` before the suite. +Run `pnpm run test:web:project` to exercise the portable webR project workspace in Chromium. + The suite opens virtual and unsaved documents, runs editor commands, transfers files, exercises cancellation on a cross-origin isolated workbench, and reopens a saved Interactive transcript. Manually testing a browser development extension on `vscode.dev` can prompt for notebook trust when opening a notebook for the first time. ### Releasing the webR language service diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 3cfaf74ac..a42931550 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -125,3 +125,83 @@ Copyright (c) 2007, Nick Galbreath -- nickg [at] client9 [dot] com All rights reserved. http://code.google.com/p/stringencoders/ Released under the MIT license. + +webR project bundles +-------------------- + +@zip.js/zip.js 2.25.0 (https://github.com/gildas-lormeau/zip.js) +Bundled source files also credit Copyright (c) 2022, 2025, 2026 Gildas Lormeau. +BSD 3-Clause License + +Copyright (c) 2023, Gildas Lormeau + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +proper-lockfile 4.1.2 (https://github.com/moxystudio/node-proper-lockfile) +retry 0.12.0 (https://github.com/tim-kos/node-retry) +Copyright (c) 2011: +Tim Koschützki (tim@debuggable.com) +Felix Geisendörfer (felix@debuggable.com) +The MIT License (MIT) + +Copyright (c) 2018 Made With MOXY Lda + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +graceful-fs 4.2.11 (https://github.com/isaacs/node-graceful-fs) +signal-exit 3.0.7 (https://github.com/tapjs/signal-exit) +Copyright (c) 2015, Contributors (signal-exit) +The ISC License + +Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/package.json b/package.json index 2c0476c4c..228a36430 100644 --- a/package.json +++ b/package.json @@ -36,11 +36,20 @@ "onLanguage:r", "onLanguage:rmd", "onNotebook:r-interactive", - "onFileSystem:vscode-r-webr" + "onFileSystem:vscode-r-webr", + "onFileSystem:vscode-r-project" ], "main": "./dist/extension", "browser": "./dist/web-extension.js", "contributes": { + "customEditors": [ + { + "viewType": "r.webRProject", + "displayName": "webR Project", + "selector": [{ "filenamePattern": "*.webrproj" }], + "priority": "default" + } + ], "terminal": { "profiles": [ { @@ -902,6 +911,16 @@ "category": "R", "icon": "$(folder-opened)" }, + { + "command": "r.webR.newProject", + "title": "New webR Project…", + "category": "R" + }, + { + "command": "r.webR.openProject", + "title": "Open webR Project…", + "category": "R" + }, { "command": "r.interactive.open", "title": "Open Interactive Session", @@ -2773,6 +2792,7 @@ "test:node": "mocha \"out/test/node/**/*.test.js\" --config .mocharc.interactive.cjs", "test:extension": "vscode-test", "test:web": "pnpm run compile && pnpm --allow-build=@playwright/browser-chromium dlx @vscode/test-web@0.0.81 --browser chromium --headless --coi --quality stable --extensionId REditorSupport.r-syntax --extensionDevelopmentPath=. --extensionTestsPath=src/test/web/webR.cjs", + "test:web:project": "pnpm run compile && pnpm --allow-build=@playwright/browser-chromium dlx @vscode/test-web@0.0.81 --browser chromium --headless --coi --quality stable --extensionId REditorSupport.r-syntax --extensionDevelopmentPath=. --extensionTestsPath=src/test/web/webRProject.cjs", "test:activation": "node --test scripts/activation-environment.test.cjs && node scripts/test-activation.cjs", "lint": "oxlint src", "format": "oxfmt .", @@ -2816,11 +2836,13 @@ }, "dependencies": { "@vscode/codicons": "0.0.46-24", + "@zip.js/zip.js": "2.25.0", "ag-grid-community": "^36.3.0", "cheerio": "1.2.0", "ejs": "^7.0.2", "highlight.js": "^11.12.0", "js-yaml": "^5.5.0", + "proper-lockfile": "4.1.2", "tar": "7.5.24", "vscode-jsonrpc": "10.0.0", "vscode-languageclient": "^11.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dd2191639..1fc74c176 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: '@vscode/codicons': specifier: 0.0.46-24 version: 0.0.46-24 + '@zip.js/zip.js': + specifier: 2.25.0 + version: 2.25.0 ag-grid-community: specifier: ^36.3.0 version: 36.3.0 @@ -29,6 +32,9 @@ importers: js-yaml: specifier: ^5.5.0 version: 5.5.0 + proper-lockfile: + specifier: 4.1.2 + version: 4.1.2 tar: specifier: 7.5.24 version: 7.5.24 @@ -1427,6 +1433,10 @@ packages: '@xterm/xterm@5.5.0': resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==} + '@zip.js/zip.js@2.25.0': + resolution: {integrity: sha512-oNRqUuU1XFu6G5d7Z0jufJ9dS9WteO0xiU/PNxsUrb4itZCsSbn191jpJzU00Gmc6S680X3DPZeF5EV4zAEMAg==} + engines: {bun: '>=0.7.0', deno: '>=1.0.0', node: '>=18.0.0'} + ag-charts-types@14.3.0: resolution: {integrity: sha512-6VtzUYBKN5mFY24/Eye3RUn1AAq7s+/B4hEu83ZOK/Pjqx26tHq2MoxiXlBE8F7oQO0VpjV5rZZaw6wxSpMNJg==} @@ -3804,6 +3814,8 @@ snapshots: '@xterm/xterm@5.5.0': {} + '@zip.js/zip.js@2.25.0': {} + ag-charts-types@14.3.0: {} ag-grid-community@36.3.0: diff --git a/src/extension.ts b/src/extension.ts index 196a9b17a..f44584f14 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,4 +1,6 @@ 'use strict'; +import { registerWebRProjects } from './webr/projectWorkspace'; +import { createDesktopProjectHost } from './interactive/projectHost'; // interfaces, functions, etc. provided by vscode import { WebRSessionFiles } from './webr/sessionFiles'; @@ -273,7 +275,12 @@ export async function activate( // initialize the package/help related functions globalRHelp = await rHelp.initializeHelp(context, rExtension); const sessionFiles = new WebRSessionFiles(context.workspaceState); - context.subscriptions.push(new InteractiveManager(context, sessionFiles), sessionFiles); + const interactive = new InteractiveManager(context, sessionFiles); + context.subscriptions.push( + interactive, + sessionFiles, + registerWebRProjects(context, createDesktopProjectHost(context, interactive)), + ); // 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 7439d69f0..e857073dd 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -177,6 +177,7 @@ export class SessionAgent { label: config.label, host: os.hostname(), directory: config.directory, + projectBundle: config.projectBundle, endpoint: localEndpoint(this.runtime, 'control.sock'), token: randomBytes(32).toString('hex'), agentPid: process.pid, diff --git a/src/interactive/backends/webr.ts b/src/interactive/backends/webr.ts index 348e780bb..502b141a3 100644 --- a/src/interactive/backends/webr.ts +++ b/src/interactive/backends/webr.ts @@ -1,3 +1,5 @@ +import * as path from 'node:path'; +import { DesktopProjectStorage, ownProjectRuntime } from '../projectStorage'; import { createWebRFileAccess, type WebRFileAccess } from '../../webr/filesystem'; import { webcrypto } from 'node:crypto'; import { DesktopWebRPackageStore } from '../webRPackageStore'; @@ -34,6 +36,10 @@ export class WebRBackend implements SessionBackend { private readonly packages: DesktopWebRPackageStore; private webRPackageRevision?: number; private packageWarning?: string; + private project?: DesktopProjectStorage; + private releaseProject?: () => Promise; + private projectClosing?: Promise; + private projectWarning?: string; constructor( private readonly settings: AgentSettings, @@ -54,6 +60,28 @@ export class WebRBackend implements SessionBackend { } async start(): Promise { + if (this.settings.projectBundle) { + const storage = new DesktopProjectStorage( + this.settings.projectBundle, + path.dirname(this.settings.directory), + ); + this.releaseProject = await ownProjectRuntime(storage.bundle, (error) => { + this.releaseProject = undefined; + this.project = undefined; + this.emit({ + type: 'error', + message: 'Lost the webR project writer lock: ' + String(error), + }); + void this.stop(); + }).catch((error) => { + throw new Error( + 'Cannot acquire the webR project session. Reconnect to its existing session on this host or retry after its agent exits. ' + + String(error), + ); + }); + this.project = storage; + await storage.prepare(true); + } const { ChannelType, WebR } = await import('webr'); const runtime = new WebR({ baseUrl: this.baseUrl, @@ -187,9 +215,14 @@ export class WebRBackend implements SessionBackend { // The next editor request can see packages installed by this cell // as soon as its finished event is visible, including after reconnect. await this.publishPackages(); + const saved = await this.saveProject(submission.id); this.current = undefined; if (!this.stopped) { - this.emit({ type: 'finished', executionId: submission.id, state }); + this.emit({ + type: 'finished', + executionId: submission.id, + state: state === 'success' && !saved ? 'error' : state, + }); // File operations may now use the idle worker. for (const params of this.openFiles.splice(0)) { this.emit({ @@ -241,17 +274,54 @@ export class WebRBackend implements SessionBackend { await this.console?.interrupt(); } + private async saveProject(executionId?: string): Promise { + const project = this.project; + if (!project) { + return true; + } + try { + await project.checkpoint(); + this.projectWarning = undefined; + return true; + } catch (error) { + const reason = String(error); + const location = reason.includes(project.directory) + ? '' + : ' Working files: ' + project.directory; + const message = 'Could not save webR project. ' + reason + location; + if (executionId) { + this.emit({ type: 'stream', channel: 'stderr', text: message + '\n', executionId }); + } + if (message !== this.projectWarning) { + this.projectWarning = message; + if (!executionId) { + this.emit({ type: 'warning', message }); + } + process.stderr.write(message + '\n'); + } + return false; + } + } + private exit(): void { if (!this.stopped) { this.stopped = true; - this.emit({ type: 'exit' }); + if (this.releaseProject) { + const release = this.releaseProject; + this.projectClosing = this.saveProject().then(async () => { + await release().catch((error) => process.stderr.write(String(error) + '\n')); + this.emit({ type: 'exit' }); + }); + } else { + this.emit({ type: 'exit' }); + } } } stop(): Promise { this.console?.close(); this.exit(); - return Promise.resolve(); + return this.projectClosing ?? Promise.resolve(); } async dispose(): Promise { diff --git a/src/interactive/launcher.ts b/src/interactive/launcher.ts index e748f0a17..4ba19bf65 100644 --- a/src/interactive/launcher.ts +++ b/src/interactive/launcher.ts @@ -215,8 +215,10 @@ export async function launchAgent( runtime = hostNodeRuntime(), log: (text: string) => void = () => undefined, ): Promise { - const supervisor = prepareSupervisor(config.supervision, config.directory); - runtime = await prepareNodeRuntime(config.directory, runtime); + // Resolve and launch native infrastructure outside the mounted contents of a bundle. + const launchDirectory = config.projectBundle ? os.homedir() : config.directory; + const supervisor = prepareSupervisor(config.supervision, launchDirectory); + runtime = await prepareNodeRuntime(launchDirectory, runtime); const node = runtime.executable; ensureStorageDirectory(config.storage, path.dirname(config.storage)); const file = path.join(config.storage, 'config.json'); @@ -245,7 +247,7 @@ export async function launchAgent( file, ]; try { - await run(supervisor.executable, args, { env, cwd: config.directory, timeout: 10000 }); + await run(supervisor.executable, args, { env, cwd: launchDirectory, timeout: 10000 }); } catch (error) { // A failed command may already have started an agent. Falling back now // could create two R processes using the same session registry. @@ -265,7 +267,7 @@ export async function launchAgent( const child = spawn(node, [agent, file], { detached: true, windowsHide: true, - cwd: config.directory, + cwd: launchDirectory, env, stdio: ['ignore', descriptor, descriptor], }); @@ -296,7 +298,10 @@ export async function launchAgent( child.unref(); fs.closeSync(log); `; - await run(node, ['-e', bootstrap, agent, file], { env }); + await run(node, ['-e', bootstrap, agent, file], { + env, + ...(config.projectBundle && { cwd: launchDirectory }), + }); } const deadline = Date.now() + 30000; while (Date.now() < deadline) { diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 806635edc..291156a18 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1,9 +1,12 @@ +import { DesktopProjectStorage, withProjectLock } from './projectStorage'; +import { WEBR_PROJECT_SCHEME } from '../webr/projectWorkspace'; 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'; +import { homedir } from 'node:os'; import { randomUUID } from 'crypto'; import { AgentClient } from './client'; import { @@ -81,6 +84,12 @@ import { } from './sessionLifecycle'; import { InteractiveInputFeatures } from './inputFeatures'; +/** Project archives can include .vscode/settings.json. Native executables and agent + * storage for their automatically started session come from the host's user settings. */ +function hostSetting(name: string, fallback: string): string { + return vscode.workspace.getConfiguration('r').inspect(name)?.globalValue ?? fallback; +} + interface InteractiveView { client: AgentClient; target: session.Session; @@ -140,7 +149,11 @@ export class InteractiveManager private output = vscode.window.createOutputChannel('R Interactive'); private messages = vscode.notebooks.createRendererMessaging('r-interactive-renderer'); private serializer = new InteractiveSerializer(); - private root: string; + readonly root: string; + private readonly projects = new Map< + string, + { root: vscode.Uri; storage: DesktopProjectStorage } + >(); private restoringConnections?: Promise; private closed = false; private clientId: string; @@ -182,7 +195,13 @@ export class InteractiveManager this.sessionFiles.waitForReconnect = (id, generation) => this.opening.get(`${id}:${generation}`) ?? this.restoringConnections; } - this.root = util.config().get('interactive.storagePath') || defaultStorage(); + const projectWorkspace = vscode.workspace.workspaceFolders?.some( + (folder) => folder.uri.scheme === WEBR_PROJECT_SCHEME, + ); + const configuredStorage = projectWorkspace + ? hostSetting('interactive.storagePath', '') + : util.config().get('interactive.storagePath'); + this.root = configuredStorage || defaultStorage(); this.clientId = randomUUID(); // Native Interactive tabs restore their URI, but discard notebook metadata. // Keep that association outside the notebook, including while R is unreachable. @@ -415,7 +434,9 @@ export class InteractiveManager this.disposables.push( vscode.workspace.onDidOpenTextDocument((document) => { const owner = sessionFileOwner(document.uri); - const view = owner && this.views.get(`${owner.id}:${owner.generation}`); + const view = owner + ? this.views.get(`${owner.id}:${owner.generation}`) + : this.projectView(document.uri); if (view && !view.disposed) { session.bindSessionDocument(document.uri, view.target); } @@ -531,8 +552,10 @@ export class InteractiveManager setInteractiveExecutor(async (code, resource, source, offerTarget) => { const mode = util.config(resource).get('interactive.executionTarget', 'auto'); const sessionFile = resource?.scheme === WEBR_FILE_SCHEME; + const projectFile = resource?.scheme === WEBR_PROJECT_SCHEME; if ( !sessionFile && + !projectFile && (mode === 'terminal' || (!this.routing && mode !== 'interactive' && !offerTarget)) ) { return false; @@ -545,9 +568,11 @@ export class InteractiveManager ? [...this.views.values()].find((item) => item.target === bound) : this.active : undefined; - if (sessionFile) { + if (sessionFile || projectFile) { const owner = resource && sessionFileOwner(resource); - view = owner ? this.views.get(`${owner.id}:${owner.generation}`) : undefined; + view = owner + ? this.views.get(`${owner.id}:${owner.generation}`) + : resource && this.projectView(resource); if ( !view || view.disposed || @@ -1229,45 +1254,91 @@ export class InteractiveManager return item; } + private projectView(uri: vscode.Uri): InteractiveView | undefined { + const project = uri.scheme === WEBR_PROJECT_SCHEME && this.projects.get(uri.authority); + return project + ? [...this.views.values()].find( + (view) => + !view.disposed && + view.client.manifest.projectBundle === project.storage.bundle && + !['exited', 'stopping'].includes(view.client.manifest.status), + ) + : undefined; + } + + async openProject(storage: DesktopProjectStorage, root: vscode.Uri): Promise { + this.projects.set(root.authority, { root, storage }); + await withProjectLock(storage.bundle, 'open', async () => { + this.refresh(); + const [existing] = await runningSessions( + this.manifests.filter((m) => m.projectBundle === storage.bundle), + ); + if (existing) { + await this.open(existing); + } else { + await this.create(undefined, root, storage); + } + const view = this.projectView(root); + if (!view) { + throw new Error('Could not connect to the webR project session.'); + } + // A restored notebook can have been attached before the workspace provider was ready. + this.attachFiles(view); + }); + } + private async create( adoptable?: AdoptableArf, resource = vscode.window.activeTextEditor?.document.uri, + project?: DesktopProjectStorage, ): Promise { if (!vscode.workspace.isTrusted) { throw new Error('Trust this workspace before starting or controlling R'); } const adopt = adoptable?.session; const folder = this.sessionFolder(resource); - const directory = adopt?.cwd ?? defaultSessionDirectory(folder?.fsPath); - const arfCommand = this.arfCommand(folder ?? resource); + if (!adopt && !project && folder?.scheme === WEBR_PROJECT_SCHEME) { + const owner = this.projects.get(folder.authority); + if (!owner) { + throw new Error('The webR project is opening. Retry when it is ready.'); + } + await this.openProject(owner.storage, owner.root); + return this.projectView(owner.root); + } + const directory = + adopt?.cwd ?? project?.directory ?? defaultSessionDirectory(folder?.fsPath); + const arfCommand = project ? '' : this.arfCommand(folder ?? resource); // An adopted session keeps the listing that found it, which finds the // session again if its IPC restarts at another socket path, even if // another folder has become active since. const listing = adoptable?.listing; - let arfPath = listing ? listing.command : resolveArfExecutable(arfCommand, directory); + let arfPath = + listing?.command ?? (project ? undefined : resolveArfExecutable(arfCommand, directory)); const webR = { label: 'webR', detail: 'Experimental backend. Run R in WebAssembly using the project directory and a separate package library.', value: 'webr' as const, }; - const provider = adopt - ? 'arf-existing' - : await vscode.window.showQuickPick< - vscode.QuickPickItem & { value: 'arf' | 'webr' | 'configure' } - >( - arfPath - ? [{ label: 'arf', detail: arfPath, value: 'arf' as const }, webR] - : [ - webR, - { - label: '$(gear) Configure arf…', - description: 'Native R session', - detail: `Install arf on this host and set its path. Checked: ${arfCommand}`, - value: 'configure' as const, - }, - ], - { title: 'R Interactive session provider' }, - ); + const provider = project + ? 'webr' + : adopt + ? 'arf-existing' + : await vscode.window.showQuickPick< + vscode.QuickPickItem & { value: 'arf' | 'webr' | 'configure' } + >( + arfPath + ? [{ label: 'arf', detail: arfPath, value: 'arf' as const }, webR] + : [ + webR, + { + label: '$(gear) Configure arf…', + description: 'Native R session', + detail: `Install arf on this host and set its path. Checked: ${arfCommand}`, + value: 'configure' as const, + }, + ], + { title: 'R Interactive session provider' }, + ); if (!provider) { return; } @@ -1280,10 +1351,13 @@ export class InteractiveManager if (kind !== 'webr' && !rPath) { return; } - const label = await vscode.window.showInputBox({ - title: 'Session name', - value: adopt ? `arf ${adopt.pid}` : path.basename(directory), - }); + const label = project + ? path.basename(project.bundle, path.extname(project.bundle)).slice(0, 80) || + 'webR project' + : await vscode.window.showInputBox({ + title: 'Session name', + value: adopt ? `arf ${adopt.pid}` : path.basename(directory), + }); if (!label) { return; } @@ -1293,9 +1367,11 @@ export class InteractiveManager ) { return; } - const supervision = util.config(resource).get('interactive.supervision', 'auto'); - prepareSupervisor(supervision, directory); - const node = await this.nodeRuntime(directory, resource); + const supervision = project + ? hostSetting('interactive.supervision', 'auto') + : util.config(resource).get('interactive.supervision', 'auto'); + prepareSupervisor(supervision, project ? homedir() : directory); + const node = await this.nodeRuntime(directory, resource, !!project); return vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, @@ -1315,6 +1391,7 @@ export class InteractiveManager label, directory, storage: path.join(this.root, identity.id), + projectBundle: project?.bundle, provider: kind, ...(kind === 'webr' ? { backend: { kind, options: {} } } @@ -1409,7 +1486,14 @@ export class InteractiveManager private nodeRuntime( directory: string, resource = vscode.Uri.file(directory), + project = false, ): Promise { + if (project) { + const command = hostSetting('interactive.nodePath', '') + .replaceAll('${userHome}', homedir()) + .trim(); + return prepareNodeRuntime(homedir(), resolveNodeRuntime(command, homedir())); + } const command = util.substituteVariables( util.config(resource).get('interactive.nodePath', ''), resource, @@ -1465,7 +1549,11 @@ export class InteractiveManager const terminals: AdoptableArf[] = []; // Where `arf ipc list` runs and the configured arf path is resolved. const folder = this.sessionFolder(resource); - const directory = defaultSessionDirectory(folder?.fsPath); + const directory = defaultSessionDirectory( + folder?.scheme === WEBR_PROJECT_SCHEME + ? this.projects.get(folder.authority)?.storage.directory + : folder?.fsPath, + ); const arfCommand = this.arfCommand(folder ?? resource); // The registry that this listing reads, recorded for an adopted session. const registry = registryEnvironmentOf(process.env); @@ -1883,8 +1971,14 @@ export class InteractiveManager if (!this.sessionFiles || provider !== 'webr' || !capabilities.webRFiles) { return; } - let projectUri = vscode.Uri.file(directory); + const bundleRoot = [...this.projects.values()].find( + (project) => project.storage.bundle === view.client.manifest.projectBundle, + )?.root; + let projectUri = bundleRoot ?? vscode.Uri.file(directory); for (const folder of vscode.workspace.workspaceFolders ?? []) { + if (bundleRoot || folder.uri.scheme === WEBR_PROJECT_SCHEME) { + continue; + } const relative = path.relative(folder.uri.fsPath, directory); if ( relative !== '..' && @@ -1922,7 +2016,12 @@ export class InteractiveManager }); for (const doc of vscode.workspace.textDocuments) { const owner = sessionFileOwner(doc.uri); - if (owner?.id === id && owner.generation === generation) { + if ( + (owner?.id === id && owner.generation === generation) || + (bundleRoot && + doc.uri.scheme === WEBR_PROJECT_SCHEME && + doc.uri.authority === bundleRoot.authority) + ) { session.bindSessionDocument(doc.uri, view.target); } } @@ -2085,7 +2184,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)); + cells.push( + this.webRFileNotice(model.generation, view.client.manifest.projectBundle), + ); } for (const cell of model.cells.values()) { if (!view.hidden.has(cell.record.id)) { @@ -3390,10 +3491,12 @@ export class InteractiveManager } } - private webRFileNotice(generation: string): vscode.NotebookCellData { + private webRFileNotice(generation: string, bundle?: 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.', + bundle + ? '**webR project** · Explorer and R share `/project`. Editor saves and completed R cells update the .webrproj bundle. Files in `/home/web_user` and `/tmp` belong to this session.' + : '**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'); @@ -3507,11 +3610,20 @@ export class InteractiveManager ) as AgentConfig; // Re-evaluate auto and honor repaired settings; the saved config records // the actual supervisor of the old process, not the current preference. - config.supervision = util - .config(vscode.Uri.file(config.directory)) - .get('interactive.supervision', 'auto'); - prepareSupervisor(config.supervision, config.directory); - const node = await this.nodeRuntime(config.directory); + config.supervision = config.projectBundle + ? hostSetting('interactive.supervision', 'auto') + : util + .config(vscode.Uri.file(config.directory)) + .get('interactive.supervision', 'auto'); + prepareSupervisor( + config.supervision, + config.projectBundle ? homedir() : config.directory, + ); + const node = await this.nodeRuntime( + config.directory, + undefined, + !!config.projectBundle, + ); const backend = backendDescriptor(config); if ( backend.kind === 'sess' && @@ -3649,7 +3761,7 @@ export class InteractiveManager const notice = new vscode.WorkspaceEdit(); notice.set(view.notebook.uri, [ vscode.NotebookEdit.insertCells(view.notebook.cellCount, [ - this.webRFileNotice(manifest.generation), + this.webRFileNotice(manifest.generation, manifest.projectBundle), ]), ]); await vscode.workspace.applyEdit(notice); diff --git a/src/interactive/projectHost.ts b/src/interactive/projectHost.ts new file mode 100644 index 000000000..3fbb20c62 --- /dev/null +++ b/src/interactive/projectHost.ts @@ -0,0 +1,326 @@ +import { promises as fs } from 'node:fs'; +import * as path from 'node:path'; +import * as vscode from 'vscode'; +import { PROJECT_FILE_LIMIT, validateProjectPath } from '../webr/projectArchive'; +import type { + ProjectFileChange, + ProjectWriteOptions, + WebRProjectHost, + WebRProjectVolume, +} from '../webr/projectWorkspace'; +import { + DesktopProjectStorage, + remoteProjectScope, + readRegular, + sha256, + atomicFile, + assertProjectWritable, +} from './projectStorage'; +import type { InteractiveManager } from './manager'; + +function fileError(error: unknown): never { + switch ((error as NodeJS.ErrnoException).code) { + case 'ENOENT': + throw vscode.FileSystemError.FileNotFound(String(error)); + case 'EEXIST': + case 'ENOTEMPTY': + throw vscode.FileSystemError.FileExists(String(error)); + case 'EISDIR': + throw vscode.FileSystemError.FileIsADirectory(String(error)); + case 'ENOTDIR': + throw vscode.FileSystemError.FileNotADirectory(String(error)); + case 'EPERM': + case 'EACCES': + case 'ELOOP': + throw vscode.FileSystemError.NoPermissions(String(error)); + default: + throw error; + } +} + +class DesktopProjectVolume implements WebRProjectVolume { + private readonly changes = new vscode.EventEmitter(); + readonly onDidChange = this.changes.event; + private readonly watcher: vscode.FileSystemWatcher; + + constructor(readonly storage: DesktopProjectStorage) { + this.watcher = vscode.workspace.createFileSystemWatcher( + new vscode.RelativePattern(storage.directory, '**/*'), + ); + const report = (uri: vscode.Uri, type: vscode.FileChangeType) => { + const relative = path.relative(storage.directory, uri.fsPath).split(path.sep).join('/'); + if (!relative.startsWith('../') && !path.isAbsolute(relative)) { + this.changes.fire([{ path: relative, type }]); + } + }; + this.watcher.onDidChange((uri) => report(uri, vscode.FileChangeType.Changed)); + this.watcher.onDidCreate((uri) => report(uri, vscode.FileChangeType.Created)); + this.watcher.onDidDelete((uri) => report(uri, vscode.FileChangeType.Deleted)); + } + dispose() { + this.watcher.dispose(); + this.changes.dispose(); + } + + /** Validate every component on the actual checkout, since R can create symlinks after import. */ + private async target(name: string, create = false): Promise { + if (name) { + validateProjectPath(name); + } + let absolute = this.storage.directory; + for (const part of name ? name.split('/') : []) { + absolute = path.join(absolute, part); + try { + if ((await fs.lstat(absolute)).isSymbolicLink()) { + throw vscode.FileSystemError.NoPermissions('Project links cannot be followed.'); + } + } catch (error) { + if (create && (error as NodeJS.ErrnoException).code === 'ENOENT') { + continue; + } + fileError(error); + } + } + return absolute; + } + async stat(name: string): Promise { + try { + const st = await fs.lstat(await this.target(name)); + if (!st.isFile() && !st.isDirectory()) { + throw vscode.FileSystemError.NoPermissions('Unsupported project file: ' + name); + } + return { + type: st.isDirectory() ? vscode.FileType.Directory : vscode.FileType.File, + mtime: st.mtimeMs, + ctime: st.ctimeMs, + size: st.size, + permissions: + st.mode & 0o222 && (await fs.stat(this.storage.bundle)).mode & 0o222 + ? undefined + : vscode.FilePermission.Readonly, + }; + } catch (e) { + fileError(e); + } + } + async readDirectory(name: string): Promise<[string, vscode.FileType][]> { + try { + const entries = await fs.readdir(await this.target(name), { withFileTypes: true }); + return entries + .filter((e) => e.isDirectory() || e.isFile()) + .map((e) => [ + e.name, + e.isDirectory() ? vscode.FileType.Directory : vscode.FileType.File, + ]); + } catch (e) { + fileError(e); + } + } + async readFile(name: string): Promise { + try { + return await readRegular(await this.target(name), PROJECT_FILE_LIMIT); + } catch (e) { + fileError(e); + } + } + async writeFile(name: string, bytes: Uint8Array, options: ProjectWriteOptions): Promise { + if (bytes.byteLength > PROJECT_FILE_LIMIT) { + throw vscode.FileSystemError.Unavailable('File exceeds the .webrproj size limit.'); + } + await this.storage + .edit( + async () => { + const item = await this.target(name, true); + const stat = await fs.lstat(item).catch((e) => { + if ((e as NodeJS.ErrnoException).code !== 'ENOENT') { + throw e; + } + return undefined; + }); + if (stat?.isDirectory()) { + throw vscode.FileSystemError.FileIsADirectory(name); + } + const ensureExpected = async () => { + if (options.expected === undefined) { + return; + } + const current = await readRegular(item, PROJECT_FILE_LIMIT).catch( + (e: unknown) => { + if ((e as NodeJS.ErrnoException).code === 'ENOENT') { + return undefined; + } + throw e; + }, + ); + if (!current || sha256(current) !== options.expected) { + throw vscode.FileSystemError.Unavailable( + 'The project file changed. Compare or reopen it before saving.', + ); + } + }; + await ensureExpected(); + if (stat) { + await assertProjectWritable(item); + } + if (!stat && !options.create) { + throw vscode.FileSystemError.FileNotFound(name); + } + if (stat && !options.overwrite) { + throw vscode.FileSystemError.FileExists(name); + } + // Keep interrupted staging files outside the mounted project tree. + await atomicFile( + item, + bytes, + stat ? stat.mode & 0o777 : 0o600, + ensureExpected, + this.storage.cache, + ); + }, + (next) => { + next.set(name, bytes); + }, + ) + .catch(fileError); + } + async createDirectory(name: string): Promise { + await this.storage + .edit( + async () => { + const item = await this.target(name, true); + await fs.mkdir(item, { recursive: true, mode: 0o700 }); + }, + (next) => { + next.set(name, null); + }, + ) + .catch(fileError); + } + async delete(name: string, options: { recursive: boolean }): Promise { + if (!name) { + throw vscode.FileSystemError.NoPermissions('Cannot delete the project root.'); + } + await this.storage + .edit( + async () => { + const item = await this.target(name); + const st = await fs.lstat(item); + if (st.isDirectory() && !options.recursive) { + await fs.rmdir(item); + } else { + await fs.rm(item, { recursive: options.recursive }); + } + }, + (next) => { + for (const entry of next.keys()) { + if (entry === name || entry.startsWith(name + '/')) { + next.delete(entry); + } + } + }, + ) + .catch(fileError); + } + async rename(from: string, to: string, options: { overwrite: boolean }): Promise { + if (!from || !to || to.startsWith(from + '/') || from.startsWith(to + '/')) { + throw vscode.FileSystemError.NoPermissions('Invalid project move.'); + } + if (from === to) { + await this.target(from); + return; + } + await this.storage + .edit( + async () => { + const origin = await this.target(from), + target = await this.target(to, true); + if (!options.overwrite) { + try { + const existing = await fs.lstat(target); + const source = await fs.lstat(origin); + // A spelling-only rename on a case-insensitive host names the same entry. + if ( + from.normalize('NFC').toUpperCase() !== + to.normalize('NFC').toUpperCase() || + existing.dev !== source.dev || + existing.ino !== source.ino + ) { + throw vscode.FileSystemError.FileExists(to); + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error; + } + } + } + await fs.rename(origin, target); + }, + (next, working) => { + for (const name of next.keys()) { + if ( + name === from || + name.startsWith(from + '/') || + name === to || + name.startsWith(to + '/') + ) { + next.delete(name); + } + } + // Include the moved entry's actual contents, including new R-created descendants. + for (const [name, entry] of working) { + if (name === from || name.startsWith(from + '/')) { + next.set(to + name.slice(from.length), entry); + } + } + }, + ) + .catch(fileError); + } +} + +export function acceptsDesktopProjectSource( + uri: vscode.Uri, + remoteName: string | undefined, + hostUris: readonly vscode.Uri[], +): boolean { + if (uri.query || uri.fragment || !path.isAbsolute(uri.fsPath)) { + return false; + } + // Remote extension hosts receive their own backing files as file: and client-local files as vscode-local:. + if (uri.scheme === 'file') { + return true; + } + return ( + uri.scheme === 'vscode-remote' && + !!remoteName && + !!uri.authority && + hostUris.some( + (other) => other.scheme === 'vscode-remote' && other.authority === uri.authority, + ) + ); +} + +export function createDesktopProjectHost( + context: vscode.ExtensionContext, + manager: Pick, +): WebRProjectHost { + const remote = vscode.env.remoteName; + return { + ...(remote && { scope: () => remoteProjectScope(context.globalStorageUri.fsPath, remote) }), + accepts(uri) { + return acceptsDesktopProjectSource(uri, vscode.env.remoteName, [ + context.extensionUri, + context.globalStorageUri, + ...(vscode.workspace.workspaceFolders ?? []).map((folder) => folder.uri), + ]); + }, + async open(source) { + const storage = await DesktopProjectStorage.forBundle(source.fsPath, manager.root); + await storage.prepare(); + return new DesktopProjectVolume(storage); + }, + async start(_source, root, volume) { + await manager.openProject((volume as DesktopProjectVolume).storage, root); + }, + }; +} diff --git a/src/interactive/projectStorage.ts b/src/interactive/projectStorage.ts new file mode 100644 index 000000000..2ecbcb4a8 --- /dev/null +++ b/src/interactive/projectStorage.ts @@ -0,0 +1,481 @@ +import { constants as flags, promises as fs } from 'node:fs'; +import { createHash, randomUUID } from 'node:crypto'; +import * as path from 'node:path'; +import { hostname } from 'node:os'; +import { + decodeProject, + encodeProject, + PROJECT_ARCHIVE_LIMIT, + PROJECT_DATA_LIMIT, + PROJECT_ENTRY_LIMIT, + PROJECT_FILE_LIMIT, + type ProjectTree, + validateProjectPath, + validateProjectTree, +} from '../webr/projectArchive'; + +// proper-lockfile uses mkdir + heartbeat across processes, including remote filesystems. +// The detached agent and extension hosts must participate in the same lock protocol. +const { lock, check: isLocked } = require('proper-lockfile') as { + check(this: void, path: string, options: { realpath: false; stale: number }): Promise; + lock( + this: void, + path: string, + options: { + realpath: false; + stale: number; + retries: { + retries: number; + factor: number; + minTimeout: number; + maxTimeout: number; + }; + onCompromised: (error: Error) => void; + }, + ): Promise<() => Promise>; +}; + +export function sha256(bytes: Uint8Array | string): string { + return createHash('sha256').update(bytes).digest('hex'); +} +function missing(error: unknown): boolean { + return (error as NodeJS.ErrnoException).code === 'ENOENT'; +} + +const lockStaleMs = 15000; +function lockPath(file: string, purpose: string): string { + const name = '.vscode-r-webr-' + sha256(path.basename(file)).slice(0, 32) + '-' + purpose; + return path.join(path.dirname(file), name); +} +async function lease( + file: string, + purpose: string, + compromised: (error: Error) => void, + wait: boolean, +) { + // Each purpose must also have its own process-local key in proper-lockfile. + return lock(lockPath(file, purpose), { + realpath: false, + stale: lockStaleMs, + retries: { retries: wait ? 90 : 0, factor: 1.2, minTimeout: 35, maxTimeout: 350 }, + onCompromised: compromised, + }); +} + +/** The archive path is canonical on the R host and shared by aliases and VS Code profiles. */ +export async function withProjectLock( + file: string, + purpose: string, + callback: (check: () => void) => Promise, +): Promise { + let lost: Error | undefined; + const release = await lease( + file, + purpose, + (error) => { + lost = error; + }, + true, + ); + try { + return await callback(() => { + if (lost) { + throw lost; + } + }); + } finally { + if (!lost) { + await release(); + } + } +} + +export function ownProjectRuntime(file: string, compromised: (error: Error) => void) { + return lease(file, 'runtime', compromised, false); +} + +async function directoryExists(directory: string): Promise { + try { + const st = await fs.lstat(directory); + if (!st.isDirectory()) { + throw new Error('Invalid webR project working directory: ' + directory); + } + return true; + } catch (error) { + if (missing(error)) { + return false; + } + throw error; + } +} + +export async function assertProjectWritable(file: string): Promise { + if (!((await fs.stat(file)).mode & 0o222)) { + throw Object.assign(new Error('The file is read-only: ' + file), { code: 'EACCES' }); + } + await fs.access(file, flags.W_OK); +} + +async function syncDirectory(directory: string) { + // Windows permits FlushFileBuffers on files but not on directory handles opened by Node. + if (process.platform === 'win32') { + return; + } + const handle = await fs.open(directory, 'r'); + try { + await handle.sync(); + } finally { + await handle.close(); + } +} + +export async function atomicFile( + file: string, + bytes: Uint8Array | string, + mode: number, + beforeRename?: () => Promise, + temporaryDirectory = path.dirname(file), +) { + const temp = path.join(temporaryDirectory, '.webrproj-' + randomUUID() + '.tmp'); + const handle = await fs.open(temp, 'wx', mode); + try { + try { + await handle.writeFile(bytes); + await handle.sync(); + } finally { + await handle.close(); + } + await beforeRename?.(); + await fs.rename(temp, file); + await syncDirectory(path.dirname(file)); + } finally { + await fs.rm(temp, { force: true }); + } +} + +export async function readRegular(file: string, maxBytes: number): Promise { + const handle = await fs.open( + file, + flags.O_RDONLY | (flags.O_NOFOLLOW ?? 0) | (flags.O_NONBLOCK ?? 0), + ); + try { + const start = await handle.stat(); + if (!start.isFile() || start.size > maxBytes) { + throw new Error('Unsupported webR project file or size: ' + file); + } + const buffer = Buffer.alloc(start.size); + let offset = 0; + while (offset < buffer.byteLength) { + const { bytesRead } = await handle.read( + buffer, + offset, + buffer.byteLength - offset, + offset, + ); + if (!bytesRead) { + break; + } + offset += bytesRead; + } + const end = await handle.stat(); + if (offset !== start.size || start.size !== end.size || start.ctimeMs !== end.ctimeMs) { + throw new Error('The project file changed while it was being read. Retry: ' + file); + } + return buffer; + } finally { + await handle.close(); + } +} + +/** VS Code presents remote files to this extension host as file: URIs. Salt their + * workspace identities on the host before recording a trusted project locator. */ +export async function remoteProjectScope( + storage: string, + kind: string, + host = hostname(), +): Promise { + await fs.mkdir(storage, { recursive: true, mode: 0o700 }); + const file = path.join(storage, 'webr-project-host-id'); + async function read() { + try { + return (await readRegular(file, 64)).toString('utf8'); + } catch (error) { + if (missing(error)) { + return undefined; + } + throw error; + } + } + const id = + (await read()) ?? + (await withProjectLock(file, 'identity', async (check) => { + const existing = await read(); + if (existing !== undefined) { + return existing; + } + const created = randomUUID(); + check(); + await atomicFile(file, created, 0o600); + return created; + })); + if (!/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/.test(id)) { + throw new Error('Invalid webR project host identity: ' + file); + } + return sha256(JSON.stringify([kind, host, id])); +} + +async function snapshot(directory: string): Promise { + const tree: ProjectTree = new Map(); + let total = 0; + async function visit(parent: string) { + const folder = path.join(directory, parent); + if (!(await fs.lstat(folder)).isDirectory()) { + throw new Error('Invalid directory in the webR project: ' + folder); + } + const names = await fs.readdir(folder, { withFileTypes: true }); + for (const entry of names) { + const name = parent ? parent + '/' + entry.name : entry.name; + validateProjectPath(name); + if (tree.size >= PROJECT_ENTRY_LIMIT) { + throw new Error('Too many entries in the webR project.'); + } + const file = path.join(directory, name); + if (entry.isDirectory()) { + tree.set(name, null); + await visit(name); + } else if (entry.isFile()) { + const data = await readRegular( + file, + Math.min(PROJECT_FILE_LIMIT, PROJECT_DATA_LIMIT - total), + ); + total += data.byteLength; + tree.set(name, data); + } else { + throw new Error('The webR project contains a link or special file: ' + name); + } + } + } + await visit(''); + return tree; +} + +function fingerprint(tree: ProjectTree): string { + const hash = createHash('sha256'); + for (const name of [...tree.keys()].sort()) { + const bytes = tree.get(name)!; + hash.update(JSON.stringify([name, bytes?.byteLength ?? null])); + if (bytes) { + hash.update(bytes); + } + } + return hash.digest('hex'); +} + +interface Revision { + archive: string; + tree: string; +} + +/** Durable checkout shared by the desktop worker and its editors. Only user project files are mounted. */ +export class DesktopProjectStorage { + public readonly directory: string; + private readonly state: string; + + constructor( + readonly bundle: string, + readonly cache: string, + ) { + this.directory = path.join(cache, 'files'); + this.state = path.join(cache, 'revision.json'); + } + + static async forBundle(file: string, storage: string): Promise { + const bundle = await fs.realpath(file); + return new DesktopProjectStorage( + bundle, + path.join(storage, 'webr-projects', sha256(bundle)), + ); + } + + private readArchive() { + return readRegular(this.bundle, PROJECT_ARCHIVE_LIMIT); + } + private async revision(digest: string): Promise { + const saved = JSON.parse(await fs.readFile(this.state, 'utf8')) as Revision & { + next?: Revision; + }; + // A crash can leave the new archive on disk before its revision was finalized. + return saved.next?.archive === digest + ? saved.next + : { archive: saved.archive, tree: saved.tree }; + } + private async record(archive: string, tree: string) { + await atomicFile(this.state, JSON.stringify({ archive, tree }), 0o600); + } + private conflict(): Error { + return new Error( + 'The .webrproj file changed outside this session. Your working files are preserved in ' + + this.directory + + '. Stop the live session and reopen the project. If both copies changed, recover those files before replacing the archive.', + ); + } + + async prepare(startingRuntime = false): Promise { + await fs.mkdir(this.cache, { recursive: true, mode: 0o700 }); + await withProjectLock(this.bundle, 'save', async (check) => { + const archive = await this.readArchive(); + const digest = sha256(archive); + let state: Revision | undefined; + try { + state = await this.revision(digest); + } catch (error) { + if (!missing(error)) { + throw error; + } + } + const previous = path.join(this.cache, 'previous'); + // The backup closes the small crash window between renaming the old checkout and + // publishing its replacement. A missing entry inside a live tree must still fail. + let exists = await directoryExists(this.directory); + if ( + !startingRuntime && + (await isLocked(lockPath(this.bundle, 'runtime'), { + realpath: false, + stale: lockStaleMs, + })) + ) { + if (!exists || !state) { + throw new Error( + 'This bundle has a running webR session. Reconnect using its original session registry or stop it before opening a new checkout.', + ); + } + if (state.archive !== digest) { + throw this.conflict(); + } + // NODEFS still points at this physical tree. Its uncommitted files may + // belong to a cell that is running with no editor attached. + return; + } + if (!exists && (await directoryExists(previous))) { + await fs.rename(previous, this.directory); + exists = true; + } + const current = exists ? await snapshot(this.directory) : undefined; + if (current && state?.archive === digest) { + // A process may have died after changing the checkout but before checkpointing it. + const signature = fingerprint(current); + if (signature !== state.tree) { + await this.publish(current, signature, state, check); + } + return; + } + const incoming = await decodeProject(archive); + const signature = fingerprint(incoming); + if (current && fingerprint(current) === signature) { + await this.record(digest, signature); + return; + } + if (current && (!state || fingerprint(current) !== state.tree)) { + throw this.conflict(); + } + const staging = await fs.mkdtemp(path.join(this.cache, 'import-')); + try { + for (const [name, bytes] of incoming) { + const item = path.join(staging, name); + await fs.mkdir(bytes === null ? item : path.dirname(item), { + recursive: true, + mode: 0o700, + }); + if (bytes !== null) { + await fs.writeFile(item, bytes, { flag: 'wx', mode: 0o600 }); + } + } + check(); + await fs.rm(previous, { recursive: true, force: true }); + if (current) { + await fs.rename(this.directory, previous); + } + await fs.rename(staging, this.directory); + await this.record(digest, signature); + await fs.rm(previous, { recursive: true, force: true }); + } finally { + await fs.rm(staging, { recursive: true, force: true }); + } + }); + } + + private async publish( + tree: ProjectTree, + signature: string, + previous: Revision, + check: () => void, + ) { + const bytes = await encodeProject(tree); + const next: Revision = { archive: sha256(bytes), tree: signature }; + await assertProjectWritable(this.bundle); + const mode = (await fs.stat(this.bundle)).mode & 0o777; + await atomicFile(this.bundle, bytes, mode, async () => { + await assertProjectWritable(this.bundle); + if (sha256(await this.readArchive()) !== previous.archive) { + throw this.conflict(); + } + check(); + await atomicFile(this.state, JSON.stringify({ ...previous, next }), 0o600); + check(); + }); + await this.record(next.archive, next.tree); + } + + /** A cell checkpoint publishes the whole checkout. An editor operation publishes only the paths it + * changes, even while a detached calculation has other files half-written on disk. */ + checkpoint(): Promise { + return this.commit(); + } + + edit( + apply: () => Promise, + preview: (next: ProjectTree, working: ReadonlyMap) => void, + ): Promise { + return this.commit({ apply, preview }); + } + + private async commit(editor?: { + apply: () => Promise; + preview: (next: ProjectTree, working: ReadonlyMap) => void; + }): Promise { + await withProjectLock(this.bundle, 'save', async (check) => { + const original = await this.readArchive(); + const digest = sha256(original); + let state = await this.revision(digest); + let published: ProjectTree | undefined; + if (digest !== state.archive) { + published = await decodeProject(original); + const saved = fingerprint(published); + if (saved !== state.tree && saved !== fingerprint(await snapshot(this.directory))) { + throw this.conflict(); + } + await this.record(digest, saved); + state = { archive: digest, tree: saved }; + } + let tree: ProjectTree; + if (editor) { + await assertProjectWritable(this.bundle); + const working = await snapshot(this.directory); + const candidate = new Map(working); + editor.preview(candidate, working); + validateProjectTree(candidate); + published ??= await decodeProject(original); + editor.preview(published, working); + tree = validateProjectTree(published); + check(); + await editor.apply(); + } else { + tree = await snapshot(this.directory); + } + const signature = fingerprint(tree); + if (signature !== state.tree) { + await this.publish(tree, signature, state, check); + } + }); + } +} diff --git a/src/interactive/protocol.ts b/src/interactive/protocol.ts index 7f8876d73..c0b64aef0 100644 --- a/src/interactive/protocol.ts +++ b/src/interactive/protocol.ts @@ -20,6 +20,8 @@ export interface SessionIdentity { } export interface SessionManifest extends SessionIdentity { + /** Canonical bundle path on the R host, for an owned webR project. */ + projectBundle?: string; protocol: number; label: string; host: string; @@ -87,6 +89,7 @@ export interface AgentSnapshot { } export interface AgentSettings extends SessionIdentity { + projectBundle?: string; /** Completed processes whose transcripts precede this generation in the same window. */ previousGenerations?: string[]; label: string; diff --git a/src/languageService.ts b/src/languageService.ts index 6c80bed66..b4540433c 100644 --- a/src/languageService.ts +++ b/src/languageService.ts @@ -42,6 +42,7 @@ import { CancellableLanguageClient } from './languageServerClient'; import { withRpcCancellation } from './nativeRpc'; import { prepareNodeWebR } from './webr/nodeRuntime'; import { resolveExecutable } from './interactive/executable'; +import { WEBR_PROJECT_SCHEME } from './webr/projectWorkspace'; import { WEBR_FILE_SCHEME, sessionFileOwner } from './webr/sessionFiles'; import { Message } from 'vscode-jsonrpc'; import { cachedWebRAssets } from './webr/assetCache'; @@ -233,7 +234,8 @@ export class LanguageService implements Disposable { 'scheme' in filter && (filter.scheme === 'vscode-notebook-cell' || filter.scheme === 'vscode-interactive-input' || - filter.scheme === WEBR_FILE_SCHEME), + filter.scheme === WEBR_FILE_SCHEME || + filter.scheme === WEBR_PROJECT_SCHEME), ); // An unrooted server resolves opaque document paths against cwd, which // makes languageserver discard cells when the session lives under /tmp. @@ -395,6 +397,7 @@ export class LanguageService implements Disposable { handleDiagnostics: (uri, diagnostics, next) => { const supportedSchemes = [ WEBR_FILE_SCHEME, + WEBR_PROJECT_SCHEME, 'file', 'untitled', 'vscode-notebook-cell', @@ -474,7 +477,10 @@ export class LanguageService implements Disposable { if ( target && selector.some( - (filter) => 'scheme' in filter && filter.scheme === WEBR_FILE_SCHEME, + (filter) => + 'scheme' in filter && + (filter.scheme === WEBR_FILE_SCHEME || + filter.scheme === WEBR_PROJECT_SCHEME), ) ) { // The VS Code selector matches a path. URI authority still distinguishes @@ -489,11 +495,16 @@ export class LanguageService implements Disposable { | undefined )?.textDocument?.uri; if (typeof uri === 'string') { - const owner = sessionFileOwner(Uri.parse(uri)); - if ( - !owner || - `${owner.id}:${owner.generation}` !== target.sessionId - ) { + const documentUri = Uri.parse(uri); + const owner = sessionFileOwner(documentUri); + const matches = + documentUri.scheme === WEBR_PROJECT_SCHEME + ? documentUri.authority === + workspaceFolder?.uri.authority + : owner && + `${owner.id}:${owner.generation}` === + target.sessionId; + if (!matches) { return Promise.resolve( Message.isRequest(message) ? [ @@ -564,7 +575,8 @@ export class LanguageService implements Disposable { ? (doc: TextDocument) => (doc.uri.scheme === 'vscode-interactive-input' || doc.uri.scheme === 'vscode-notebook-cell' || - doc.uri.scheme === WEBR_FILE_SCHEME) && + doc.uri.scheme === WEBR_FILE_SCHEME || + doc.uri.scheme === WEBR_PROJECT_SCHEME) && (doc.languageId === 'r' || doc.languageId === 'rmd') : isOrdinaryRDocument; if (workspace.textDocuments.some(isR)) { @@ -606,6 +618,8 @@ export class LanguageService implements Disposable { switch (uri.scheme) { case 'untitled': return uri.scheme; + case WEBR_PROJECT_SCHEME: + return `${WEBR_PROJECT_SCHEME}://${uri.authority}`; case WEBR_FILE_SCHEME: { const owner = sessionFileOwner(uri); return owner @@ -630,9 +644,12 @@ export class LanguageService implements Disposable { const didOpenTextDocument = async (document: TextDocument) => { if ( virtualOnly && - !['vscode-notebook-cell', 'vscode-interactive-input', WEBR_FILE_SCHEME].includes( - document.uri.scheme, - ) + ![ + 'vscode-notebook-cell', + 'vscode-interactive-input', + WEBR_FILE_SCHEME, + WEBR_PROJECT_SCHEME, + ].includes(document.uri.scheme) ) { return; } @@ -643,6 +660,7 @@ export class LanguageService implements Disposable { 'vscode-notebook-cell', 'vscode-interactive-input', WEBR_FILE_SCHEME, + WEBR_PROJECT_SCHEME, ].includes(document.uri.scheme) ) { return; @@ -655,19 +673,27 @@ export class LanguageService implements Disposable { const target = document.uri.scheme === 'vscode-interactive-input' || document.uri.scheme === 'vscode-notebook-cell' || - document.uri.scheme === WEBR_FILE_SCHEME + document.uri.scheme === WEBR_FILE_SCHEME || + document.uri.scheme === WEBR_PROJECT_SCHEME ? boundSessionForDocument(document.uri) : undefined; const owner = target && { session: target, revision: target.languageEnvironmentRevision, }; + const projectFile = document.uri.scheme === WEBR_PROJECT_SCHEME; const folder = workspace.getWorkspaceFolder( - target ? Uri.file(target.workingDir) : document.uri, + target && !projectFile ? Uri.file(target.workingDir) : document.uri, ); const sessionFile = document.uri.scheme === WEBR_FILE_SCHEME; - if (document.uri.scheme === 'vscode-interactive-input' || sessionFile) { + if (document.uri.scheme === 'vscode-interactive-input' || sessionFile || projectFile) { + if ( + projectFile && + (!folder || target?.interactiveProvider !== 'webr' || target.processExited) + ) { + return; + } const file = sessionFileOwner(document.uri); if ( sessionFile && @@ -680,19 +706,26 @@ export class LanguageService implements Disposable { // The same key as the queue and close use, which skip encoding. const key = this.getKey(document.uri); if (!this.checkClient(key)) { - 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, - }, - ]; + const selector: DocumentFilter[] = + projectFile && folder + ? ['r', 'rmd'].map((language) => ({ + scheme: WEBR_PROJECT_SCHEME, + language, + pattern: { baseUri: folder.uri.toString(), pattern: '**/*' }, + })) + : file + ? ['r', 'rmd'].map((language) => ({ + scheme: WEBR_FILE_SCHEME, + language, + pattern: `/${file.generation}/**`, + })) + : [ + { + scheme: 'vscode-interactive-input', + language: 'r', + pattern: document.uri.fsPath, + }, + ]; const client = await this.createClient( selector, target?.workingDir ?? folder?.uri.fsPath ?? os.homedir(), @@ -904,6 +937,7 @@ export class LanguageService implements Disposable { 'vscode-notebook-cell', 'vscode-interactive-input', WEBR_FILE_SCHEME, + WEBR_PROJECT_SCHEME, ].includes(uri.scheme) ) { return; @@ -960,8 +994,16 @@ export class LanguageService implements Disposable { { scheme: 'untitled', language: 'rmd' }, ]; - const workspaceFolder = workspace.workspaceFolders?.[0]; - const cwd = workspaceFolder ? workspaceFolder.uri.fsPath : os.homedir(); + const roots = workspace.workspaceFolders; + if (roots?.[0]?.uri.scheme === WEBR_PROJECT_SCHEME) { + // A project can open only webR documents. Wait for an ordinary + // source editor before resolving or launching a native workspace server. + await this.waitForRDocument(this.startupCancellation.signal, false); + } + const workspaceFolder = roots?.find( + (folder) => folder.uri.scheme !== WEBR_PROJECT_SCHEME, + ); + const cwd = workspaceFolder?.uri.fsPath ?? os.homedir(); const client = await this.createClient( documentSelector, cwd, diff --git a/src/test/node/interactiveWebR.test.ts b/src/test/node/interactiveWebR.test.ts index fd1b2256d..abd1fa1da 100644 --- a/src/test/node/interactiveWebR.test.ts +++ b/src/test/node/interactiveWebR.test.ts @@ -8,6 +8,8 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import { readSessionManifest } from '../../interactive/launcher'; +import { DesktopProjectStorage } from '../../interactive/projectStorage'; +import { encodeProject, decodeProject } from '../../webr/projectArchive'; import { prepareNodeWebR } from '../../webr/nodeRuntime'; import { AgentClient } from '../../interactive/client'; import { AgentWebRFileAccess } from '../../interactive/webRFiles'; @@ -573,6 +575,77 @@ suite('R Interactive webR provider', function () { ); }); + test('commits project files written by a real webR agent after the editor disconnects', async () => { + const bundle = path.join(root, 'portable.webrproj'); + await fs.promises.writeFile( + bundle, + await encodeProject(new Map([['value.R', Buffer.from('41L')]])), + ); + const volume = await DesktopProjectStorage.forBundle(bundle, root); + await volume.prepare(); + client.close(); + manifest = await startAgent({ + ...config, + id: randomUUID(), + generation: randomUUID(), + storage: path.join(root, 'project-session'), + directory: volume.directory, + projectBundle: volume.bundle, + }); + assert.equal(manifest.projectBundle, volume.bundle); + await connect(); + const id = await submit( + 'writeLines("in progress","result.txt"); for(i in 1:500) { if(file.exists("continue")) break; Sys.sleep(0.025) }; stopifnot(file.exists("continue")); writeLines(as.character(source("value.R")$value + 1L), "result.txt")', + ); + await wait(id, 'started'); + client.close(); + for (let i = 0; i < 200 && !fs.existsSync(path.join(volume.directory, 'result.txt')); i++) { + await delay(25); + } + assert.equal( + await fs.promises.readFile(path.join(volume.directory, 'result.txt'), 'utf8'), + 'in progress\n', + ); + await volume.prepare(); // Explorer attaches while the original editor is closed and the cell is busy. + await volume.edit( + () => fs.promises.writeFile(path.join(volume.directory, 'editor.txt'), 'saved'), + (next) => { + next.set('editor.txt', Buffer.from('saved')); + }, + ); + const midCell = await decodeProject(await fs.promises.readFile(bundle)); + assert.ok(midCell.has('editor.txt')); + assert.ok( + !midCell.has('result.txt'), + 'A partial cell must not reach the portable archive on an editor save.', + ); + await fs.promises.writeFile(path.join(volume.directory, 'continue'), 'go'); + let result = ''; + for (let i = 0; i < 200 && result !== '42'; i++) { + const tree = await decodeProject(await fs.promises.readFile(bundle)); + result = Buffer.from(tree.get('result.txt') ?? []) + .toString() + .trim(); + if (result !== '42') { + await delay(30); + } + } + assert.equal(result, '42'); + await connect(); + await fs.promises.writeFile( + bundle, + await encodeProject(new Map([['outside', Buffer.from('keep')]])), + ); + const conflict = await submit('writeLines("recover this", "result.txt")'); + assert.equal((await wait(conflict, 'finished')).data.state, 'error'); + assert.match(output(conflict), /Could not save webR project/); + assert.equal( + await fs.promises.readFile(path.join(volume.directory, 'result.txt'), 'utf8'), + 'recover this\n', + ); + assert.ok((await decodeProject(await fs.promises.readFile(bundle))).has('outside')); + }); + test('mounts a project and retains R objects, files and PNG output across an editor reconnect', async () => { assert.equal(manifest.backend, 'webr'); assert.equal(manifest.rPath, undefined); diff --git a/src/test/node/webRProjectArchive.test.ts b/src/test/node/webRProjectArchive.test.ts new file mode 100644 index 000000000..51f1714f6 --- /dev/null +++ b/src/test/node/webRProjectArchive.test.ts @@ -0,0 +1,108 @@ +import * as assert from 'node:assert/strict'; +import { + type ZipWriterAddDataOptions, + ZipWriter, + Uint8ArrayReader, + Uint8ArrayWriter, +} from '@zip.js/zip.js/index-native.js'; +import { + decodeProject, + encodeProject, + PROJECT_FILE_LIMIT, + type ProjectTree, + validateProjectPath, +} from '../../webr/projectArchive'; + +const utf8 = (text: string) => new TextEncoder().encode(text); +const manifest = [ + 'manifest.json', + '{"format":1,"id":"demo-project","workingDirectory":"/project"}', +] as const; +type Member = readonly [string, string, ZipWriterAddDataOptions?]; + +async function zip(...members: Member[]): Promise> { + const writer = new ZipWriter(new Uint8ArrayWriter(), { useWebWorkers: false, level: 0 }); + for (const [name, text, options] of members) { + await writer.add(name, new Uint8ArrayReader(utf8(text)), options); + } + return writer.close(); +} + +suite('webR project ZIP format', () => { + test('round-trips empty folders and files, binary data, dotted and Unicode names', async () => { + const tree: ProjectTree = new Map(); + tree.set('深い', null); + tree.set('深い/📈.dat', new Uint8Array([0, 255, 42])); + tree.set('.Rprofile', utf8('message("project file")')); + tree.set('empty text', new Uint8Array()); + tree.set('empty directory', null); + tree.set('notes.txt', utf8('A line of text.\n'.repeat(512))); + const encoded = await encodeProject(tree); + assert.deepEqual(await decodeProject(encoded), tree); + assert.deepEqual(await encodeProject(new Map([...tree].reverse())), encoded); + assert.deepEqual(await decodeProject(await encodeProject(new Map())), new Map()); + }); + + test('accepts version 1 prototype metadata and infers directories missing from the ZIP', async () => { + const bytes = await zip(manifest, ['files/source/nested/fit.R', '42']); + const tree = await decodeProject(bytes); + assert.equal(tree.get('source'), null); + assert.equal(tree.get('source/nested'), null); + assert.deepEqual(tree.get('source/nested/fit.R'), utf8('42')); + }); + + test('rejects unreadable manifests, unknown entries and conflicting paths', async () => { + for (const members of [ + [['files/script.R', '42']], + [['manifest.json', 'invalid']], + [['manifest.json', '{"format":2}']], + [manifest, ['unknown.txt', '42']], + [manifest, ['files/A', '1'], ['files/a', '2']], + [manifest, ['files/caf\u00e9/x', '1'], ['files/cafe\u0301/y', '2']], + [manifest, ['files/one', '1'], ['files/one/two', '2']], + [manifest, ['files/link', 'target', { unixMode: 0o120777 }]], + ] satisfies Member[][]) { + await assert.rejects(decodeProject(await zip(...members))); + } + for (const path of [ + '/data', + '../outside', + 'nested/../data', + 'C:/temp', + 'a\\b', + 'a//b', + 'aux.txt', + 'dir/NUL', + 'tail.', + 'q?', + 'a\x00b', + ]) { + assert.throws(() => validateProjectPath(path), /Invalid webR project path/); + } + }); + + test('checks both the member CRC and declared expansion before returning file bytes', async () => { + const bytes = await zip(manifest, ['files/probe', 'distinct-content-marker']); + const content = Buffer.from(bytes).indexOf('distinct-content-marker'); + assert.notEqual(content, -1); + const corrupt = bytes.slice(); + corrupt[content] ^= 1; + await assert.rejects(decodeProject(corrupt), /crc|signature/i); + + const duplicate = await zip(manifest, ['files/twinA', 'one'], ['files/twinB', 'two']); + const changed = Buffer.from(duplicate); + const encodedB = Buffer.from('files/twinB'); + for (let i = changed.indexOf(encodedB); i >= 0; i = changed.indexOf(encodedB, i + 1)) { + changed[i + encodedB.length - 1] = 'A'.charCodeAt(0); + } + await assert.rejects(decodeProject(changed)); + + const nameIndex = Buffer.from(bytes).lastIndexOf('files/probe'); + // The fixed central directory header precedes the final name. + const header = nameIndex - 46; + const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + assert.equal(data.getUint32(header, true), 0x02014b50); + data.setUint32(header + 24, PROJECT_FILE_LIMIT + 1, true); + await assert.rejects(decodeProject(bytes), /64 MiB/); + }); +}); diff --git a/src/test/node/webRProjectStorage.test.ts b/src/test/node/webRProjectStorage.test.ts new file mode 100644 index 000000000..cea04bde2 --- /dev/null +++ b/src/test/node/webRProjectStorage.test.ts @@ -0,0 +1,225 @@ +import * as assert from 'node:assert/strict'; +import { promises as fs } from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { + DesktopProjectStorage, + remoteProjectScope, + ownProjectRuntime, + withProjectLock, +} from '../../interactive/projectStorage'; +import { encodeProject, decodeProject, type ProjectTree } from '../../webr/projectArchive'; + +suite('desktop webR project storage', function () { + let root: string; + let bundle: string; + let project: DesktopProjectStorage; + const start: ProjectTree = new Map([ + ['src', null], + ['src/fit.R', Buffer.from('1L')], + ]); + setup(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'webrproj-')); + bundle = path.join(root, 'Analysis.webrproj'); + await fs.writeFile(bundle, await encodeProject(start)); + project = await DesktopProjectStorage.forBundle(bundle, path.join(root, 'registry')); + await project.prepare(); + }); + teardown(async () => { + await fs.rm(root, { recursive: true, force: true }); + }); + const files = async () => decodeProject(await fs.readFile(bundle)); + + function editorSave(store: DesktopProjectStorage, name: string, text: string) { + const bytes = Buffer.from(text); + return store.edit( + () => fs.writeFile(path.join(store.directory, name), bytes), + (tree) => { + tree.set(name, bytes); + }, + ); + } + + test('remote source trust belongs to a stable host identity even with identical file URIs', async () => { + const sameHost = () => + remoteProjectScope(path.join(root, 'server-storage'), 'ssh-remote', 'host-a'); + const [a, b, c] = await Promise.all([sameHost(), sameHost(), sameHost()]); + assert.ok(/^[0-9a-f]{64}$/.test(a)); + assert.equal(a, b); + assert.equal(b, c); + assert.equal(await sameHost(), a); + assert.notEqual( + await remoteProjectScope(path.join(root, 'server-storage'), 'ssh-remote', 'host-b'), + a, + ); + assert.notEqual( + await remoteProjectScope(path.join(root, 'new-machine'), 'ssh-remote', 'host-a'), + a, + ); + }); + test('a second window retains the active checkout and declines an externally replaced archive', async () => { + const second = await DesktopProjectStorage.forBundle(bundle, path.join(root, 'registry')); + const release = await ownProjectRuntime(bundle, (error) => assert.fail(String(error))); + try { + await fs.writeFile(path.join(project.directory, 'work-in-progress'), 'half of a cell'); + await second.prepare(); + assert.ok(!(await files()).has('work-in-progress')); + const revision = path.join(project.cache, 'revision.json'); + const original = JSON.parse(await fs.readFile(revision, 'utf8')) as Record< + string, + unknown + >; + await editorSave(second, 'src/fit.R', 'updated'); + // Simulate process death just after renaming the editor's bundle but before + // finalizing the revision, while R has uncommitted changes on the checkout. + const saved: unknown = JSON.parse(await fs.readFile(revision, 'utf8')); + await fs.writeFile(revision, JSON.stringify({ ...original, next: saved })); + await second.prepare(); + await editorSave(second, 'other-editor', 'also saved'); + assert.ok(!(await files()).has('work-in-progress')); + assert.equal(Buffer.from((await files()).get('src/fit.R')!).toString(), 'updated'); + await fs.writeFile( + bundle, + await encodeProject(new Map([['external', Buffer.from('keep')]])), + ); + await assert.rejects(second.prepare(), /changed outside/); + assert.equal( + await fs.readFile(path.join(project.directory, 'work-in-progress'), 'utf8'), + 'half of a cell', + ); + assert.equal( + await fs.readFile(path.join(project.directory, 'src/fit.R'), 'utf8'), + 'updated', + ); + assert.deepEqual([...(await files()).keys()], ['external']); + } finally { + await release(); + } + }); + + test('a new window never swaps a clean directory beneath an active mount', async () => { + const release = await ownProjectRuntime(bundle, (error) => assert.fail(String(error))); + try { + await fs.writeFile( + bundle, + await encodeProject(new Map([['other.R', Buffer.from('2L')]])), + ); + await assert.rejects(project.prepare(), /changed outside/); + assert.deepEqual(await fs.readdir(project.directory), ['src']); + } finally { + await release(); + } + await project.prepare(); + assert.deepEqual(await fs.readdir(project.directory), ['other.R']); + }); + + test('publishes both editor and detached R writes and recovers an interrupted save', async () => { + await editorSave(project, 'src/fit.R', '2L'); + assert.equal(Buffer.from((await files()).get('src/fit.R')!).toString(), '2L'); + await fs.writeFile(path.join(project.directory, 'result.bin'), Buffer.from([0, 255])); + // Reopening recovers the on-disk checkout even when the agent never finished its cell. + await project.prepare(); + assert.deepEqual((await files()).get('result.bin'), new Uint8Array([0, 255])); + const fresh = await DesktopProjectStorage.forBundle( + bundle, + path.join(root, 'other-profile'), + ); + await fresh.prepare(); + assert.deepEqual( + await fs.readFile(path.join(fresh.directory, 'result.bin')), + Buffer.from([0, 255]), + ); + }); + + test('keeps independent external changes and preserves dirty files for recovery', async () => { + const revised = await encodeProject(new Map([['outside.R', Buffer.from('42')]])); + await fs.writeFile(bundle, revised); + await assert.rejects(editorSave(project, 'src/fit.R', 'unexpected'), /changed outside/); + assert.equal(await fs.readFile(path.join(project.directory, 'src/fit.R'), 'utf8'), '1L'); + await fs.writeFile(path.join(project.directory, 'src/fit.R'), 'my edits'); + await assert.rejects(project.prepare(), /working files are preserved/); + assert.deepEqual(await fs.readFile(bundle), Buffer.from(revised)); + assert.equal( + await fs.readFile(path.join(project.directory, 'src/fit.R'), 'utf8'), + 'my edits', + ); + }); + + test('rejects invalid candidate trees before mutating the checkout', async () => { + let edited = false; + await assert.rejects( + project.edit( + async () => { + edited = true; + await fs.writeFile(path.join(project.directory, 'alias'), 'unexpected'); + }, + (tree) => { + tree.set('SRC/alias', Buffer.from('bad')); + }, + ), + /conflicting/i, + ); + assert.equal(edited, false); + assert.deepEqual(await fs.readdir(project.directory), ['src']); + }); + + test('retains a read-only archive without replacing it via a writable parent', async () => { + await fs.chmod(bundle, 0o444); + try { + await assert.rejects(editorSave(project, 'src/fit.R', '2L'), /read-only/); + await fs.writeFile(path.join(project.directory, 'fromR'), 'preserved'); + await assert.rejects(project.checkpoint(), /read-only/); + assert.equal( + await fs.readFile(path.join(project.directory, 'src/fit.R'), 'utf8'), + '1L', + ); + assert.ok(!(await files()).has('fromR')); + } finally { + await fs.chmod(bundle, 0o600); + } + }); + + test('imports an externally updated archive over a clean checkout', async () => { + await fs.writeFile( + bundle, + await encodeProject( + new Map([ + ['empty', null], + ['new.R', Buffer.from('new')], + ]), + ), + ); + await project.prepare(); + assert.deepEqual((await fs.readdir(project.directory)).sort(), ['empty', 'new.R']); + assert.equal(await fs.readFile(path.join(project.directory, 'new.R'), 'utf8'), 'new'); + }); + + test('serializes writers; saving or opening does not release the independent session lock', async () => { + const release = await ownProjectRuntime(bundle, (error) => assert.fail(String(error))); + try { + await withProjectLock(bundle, 'open', () => project.prepare()); + const b = await DesktopProjectStorage.forBundle(bundle, path.join(root, 'registry')); + await Promise.all([editorSave(project, 'one', '1'), editorSave(b, 'two', '2')]); + assert.ok((await files()).has('one')); + assert.ok((await files()).has('two')); + await assert.rejects( + ownProjectRuntime(bundle, () => {}), + /lock/i, + ); + } finally { + await release(); + } + const again = await ownProjectRuntime(bundle, () => {}); + await again(); + }); + + test('recovers after replacing the archive before recording the new revision', async () => { + const revision = path.join(project.cache, 'revision.json'); + const old = await fs.readFile(revision); + await editorSave(project, 'fromR', 'x'); + await fs.writeFile(revision, old); + await editorSave(project, 'fromEditor', 'y'); + assert.ok((await files()).has('fromR')); + assert.ok((await files()).has('fromEditor')); + }); +}); diff --git a/src/test/suite/webRProjectHost.test.ts b/src/test/suite/webRProjectHost.test.ts new file mode 100644 index 000000000..78dc6003e --- /dev/null +++ b/src/test/suite/webRProjectHost.test.ts @@ -0,0 +1,22 @@ +import * as assert from 'node:assert/strict'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { Uri } from 'vscode'; +import { acceptsDesktopProjectSource } from '../../interactive/projectHost'; + +suite('webR project host files', () => { + test('accepts files on the extension host and isolates client files and other SSH authorities', () => { + const file = Uri.file(path.join(os.homedir(), 'Analysis.webrproj')); + const ours = file.with({ scheme: 'vscode-remote', authority: 'ssh-remote+ours' }); + const other = ours.with({ authority: 'ssh-remote+other' }); + assert.ok(acceptsDesktopProjectSource(file, undefined, [])); + // VS Code transforms incoming URIs for the remote extension host. + assert.ok(acceptsDesktopProjectSource(file, 'ssh-remote', [])); + assert.ok( + !acceptsDesktopProjectSource(file.with({ scheme: 'vscode-local' }), 'ssh-remote', []), + ); + assert.ok(acceptsDesktopProjectSource(ours, 'ssh-remote', [ours])); + assert.ok(!acceptsDesktopProjectSource(other, 'ssh-remote', [ours])); + assert.ok(!acceptsDesktopProjectSource(ours, undefined, [ours])); + }); +}); diff --git a/src/test/suite/webRProjectWorkspace.test.ts b/src/test/suite/webRProjectWorkspace.test.ts new file mode 100644 index 000000000..9beb22bde --- /dev/null +++ b/src/test/suite/webRProjectWorkspace.test.ts @@ -0,0 +1,148 @@ +import * as assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import * as sinon from 'sinon'; +import * as vscode from 'vscode'; +import { decodeProject, encodeProject } from '../../webr/projectArchive'; +import { + registerWebRProjects, + webRProjectRoot, + type WebRProjectVolume, +} from '../../webr/projectWorkspace'; + +suite('webR project workspace opener', () => { + const sandbox = sinon.createSandbox(); + let directory: string; + let registration: vscode.Disposable; + let files: vscode.FileSystemProvider; + let open: (file: vscode.Uri) => Promise; + let create: () => Promise; + let openFolder: sinon.SinonStub; + let openVolume: sinon.SinonStub; + let start: sinon.SinonStub; + let trust: sinon.SinonStub; + + setup(async () => { + directory = await mkdtemp(path.join(os.tmpdir(), 'webR project #')); + const disposable = new vscode.Disposable(() => {}); + trust = sandbox.stub(vscode.window, 'showWarningMessage'); + trust.resolves('Trust Project and Open'); + sandbox.stub(vscode.window, 'registerCustomEditorProvider').returns(disposable); + const fsRegistration = sandbox + .stub(vscode.workspace, 'registerFileSystemProvider') + .returns(disposable); + const commands = sandbox.stub(vscode.commands, 'registerCommand').returns(disposable); + openFolder = sandbox.stub(vscode.commands, 'executeCommand').resolves(); + const saved = new Map(); + const state = { + get: (key: string) => saved.get(key), + update: (key: string, v: unknown) => { + saved.set(key, v); + return Promise.resolve(); + }, + } as unknown as vscode.Memento; + openVolume = sandbox.stub().resolves({ + readDirectory: () => Promise.resolve([['fit.R', vscode.FileType.File]]), + } as Partial); + start = sandbox.stub().resolves(); + registration = registerWebRProjects( + { globalState: state, workspaceState: state } as vscode.ExtensionContext, + { + accepts: (uri) => uri.scheme === 'file', + open: openVolume, + start, + }, + ); + files = fsRegistration.firstCall.args[1]; + open = commands.getCalls().find((call) => call.args[0] === 'r.webR.openProject')!.args[1]; + create = commands.getCalls().find((call) => call.args[0] === 'r.webR.newProject')!.args[1]; + }); + teardown(async () => { + registration?.dispose(); + sandbox.restore(); + await rm(directory, { recursive: true, force: true }); + }); + + test('an openable project is located after a window change without launching R for a filesystem request', async () => { + const source = vscode.Uri.file(path.join(directory, 'Analysis #1.webrproj')); + await writeFile( + source.fsPath, + await encodeProject(new Map([['fit.R', new Uint8Array([42])]])), + ); + await open(source); + const root = await webRProjectRoot(source); + sinon.assert.calledOnceWithExactly(openFolder, 'vscode.openFolder', root, { + forceReuseWindow: true, + }); + sinon.assert.notCalled(openVolume); + assert.deepEqual(await files.readDirectory(root), [['fit.R', vscode.FileType.File]]); + sinon.assert.calledOnce(openVolume); + assert.deepEqual( + (openVolume.firstCall.args as vscode.Uri[]).map((uri) => uri.toString()), + [source.toString(), root.toString()], + ); + sinon.assert.notCalled(start); + await assert.rejects( + Promise.resolve(files.readDirectory(root.with({ path: '/unrelated' }))), + ); + await assert.rejects(Promise.resolve(files.delete(root, { recursive: true }))); + assert.notEqual( + root.authority, + (await webRProjectRoot(source.with({ path: '/another/Analysis #1.webrproj' }))) + .authority, + ); + }); + + test('reselecting a bundle locates an already-open workspace root in a fresh profile', async () => { + const source = vscode.Uri.file(path.join(directory, 'Work.webrproj')); + await writeFile(source.fsPath, await encodeProject(new Map())); + const root = await webRProjectRoot(source); + sandbox + .stub(vscode.workspace, 'workspaceFolders') + .get(() => [{ uri: root, name: 'Work', index: 0 }]); + sandbox.stub(vscode.workspace, 'isTrusted').get(() => true); + await assert.rejects(Promise.resolve(files.readDirectory(root)), /Reopen the original/); + await open(source); + sinon.assert.notCalled(openFolder); + sinon.assert.calledOnce(start); + assert.deepEqual(await files.readDirectory(root), [['fit.R', vscode.FileType.File]]); + }); + + test('a virtual root cannot expose an external project before the user trusts its source', async () => { + sandbox.stub(vscode.workspace, 'getWorkspaceFolder').returns(undefined); + sandbox + .stub(vscode.workspace, 'getConfiguration') + .callThrough() + .withArgs('security.workspace.trust') + .returns({ get: () => true } as unknown as vscode.WorkspaceConfiguration); + const source = vscode.Uri.file(path.join(directory, 'external.webrproj')); + await writeFile(source.fsPath, await encodeProject(new Map())); + const root = await webRProjectRoot(source); + trust.resolves(undefined); + await open(source); + sinon.assert.notCalled(openFolder); + await assert.rejects(Promise.resolve(files.readDirectory(root)), /Reopen the original/); + trust.resolves('Trust Project and Open'); + await open(source); + await open(source); + sinon.assert.calledTwice(trust); + sinon.assert.calledTwice(openFolder); + }); + + test('an invalid archive leaves the original workspace open; creating a new project preserves existing files', async () => { + const source = vscode.Uri.file(path.join(directory, 'original.webrproj')); + const original = Buffer.from('original bytes'); + await writeFile(source.fsPath, original); + await assert.rejects(open(source)); + const picker = sandbox.stub(vscode.window, 'showSaveDialog').resolves(source); + await assert.rejects(create()); + assert.deepEqual(await readFile(source.fsPath), original); + sinon.assert.notCalled(openFolder); + const fresh = vscode.Uri.file(path.join(directory, 'new project')); + picker.resolves(fresh); + await create(); + assert.equal((await decodeProject(await readFile(fresh.fsPath + '.webrproj'))).size, 0); + sinon.assert.calledOnce(openFolder); + }); +}); diff --git a/src/test/web/webRProject.cjs b/src/test/web/webRProject.cjs new file mode 100644 index 000000000..79727af63 --- /dev/null +++ b/src/test/web/webRProject.cjs @@ -0,0 +1,162 @@ +const vscode = require('vscode'); + +// An ordinary ZIP with a version-one manifest and files/tools/fit.R. +const fixture = 'UEsDBBQAAAAIAC+TfV05wx6vDgAAAAwAAAANAAAAbWFuaWZlc3QuanNvbqtWSssvyk0sUbIyrAUAUEsDBBQAAAAIAC+TfV2ZvLXxDwAAAA0AAAARAAAAZmlsZXMvdG9vbHMvZml0LlIrS8wpTVWw0VUwMfDhAgBQSwECFAMUAAAACAAvk31dOcMerw4AAAAMAAAADQAAAAAAAAAAAAAAgAEAAAAAbWFuaWZlc3QuanNvblBLAQIUAxQAAAAIAC+TfV2ZvLXxDwAAAA0AAAARAAAAAAAAAAAAAACAATkAAABmaWxlcy90b29scy9maXQuUlBLBQYAAAAAAgACAHoAAAB3AAAAAAA='; +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); +const fs = vscode.workspace.fs; +const command = (id, ...args) => vscode.commands.executeCommand(id, ...args); + +function assert(value, message) { + if (!value) {throw new Error(message);} +} + +async function until(check, message) { + const end = Date.now() + 100000; + do { + const result = await check(); + if (result) {return result;} + await new Promise(done => setTimeout(done, 100)); + } while (Date.now() < end); + throw new Error(message); +} + +function cellOutput(cell) { + return cell.outputs.flatMap(output => output.items).map(item => decoder.decode(item.data)).join(' '); +} + +async function addRoot(root, name) { + await new Promise((resolve, reject) => { + const listener = vscode.workspace.onDidChangeWorkspaceFolders(event => { + if (event.added.some(folder => folder.uri.toString() === root.toString())) { + listener.dispose(); + resolve(); + } + }); + const index = vscode.workspace.workspaceFolders?.length ?? 0; + if (!vscode.workspace.updateWorkspaceFolders(index, 0, {uri:root, name})) { + listener.dispose(); + reject(new Error('Could not attach workspace folder ' + name)); + } + }); +} + +// Use a saved multi-root workspace so the test extension remains active when +// opening a second project. A fresh profile can also attach a previously known +// root this way by selecting its original .webrproj through the command. +async function addProject(source) { + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(source.toString()))); + const authority = Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join(''); + const stem = source.path.split('/').at(-1).slice(0, -'.webrproj'.length); + const root = vscode.Uri.from({scheme: 'vscode-r-project', authority, path: '/' + stem}); + await addRoot(root, stem); + await command('r.webR.openProject', source); + const notebook = vscode.window.activeNotebookEditor?.notebook; + assert(notebook?.notebookType === 'r-interactive', 'Opening the bundle did not start its Interactive notebook.'); + const uri = name => vscode.Uri.joinPath(root, name); + const doc = await vscode.workspace.openTextDocument(uri('tools/fit.R')); + await vscode.window.showTextDocument(doc); + const run = async (code, success = true) => { + const position = notebook.cellCount; + await command('r.runCommand', code); + const cell = await until(() => notebook.cellCount > position && + typeof notebook.cellAt(position).executionSummary?.success === 'boolean' && notebook.cellAt(position), + 'The project cell did not complete: ' + code); + const text = cellOutput(cell); + assert(cell.executionSummary.success === success, 'Unexpected cell outcome for ' + code + ': ' + text); + return text; + }; + return {uri, doc, run, notebook}; +} + +async function activeCell(project, expression, action) { + const index = project.notebook.cellCount; + const running = project.run(expression, false); + // Surface a premature failure even if the cell never reached its marker. + await Promise.race([running, until(() => project.notebook.cellCount > index && + cellOutput(project.notebook.cellAt(index)).includes('running'), 'R did not reach its marker.')]); + try {await action();} + finally {await running;} +} + +exports.run = async () => { + // Files selected outside trusted folders prompt for project trust. Exercise + // the normal trusted-folder entry point in a private test directory. + const id = crypto.randomUUID(); + const folder = vscode.Uri.from({scheme:'vscode-userdata', path:'/User/webr-project-test-' + id}); + await fs.createDirectory(folder); + const index = vscode.workspace.workspaceFolders?.length ?? 0; + await addRoot(folder, 'project-bundles'); + const first = vscode.Uri.joinPath(folder,'first-' + id + '.webrproj'); + const second = vscode.Uri.joinPath(folder,'second-' + id + '.webrproj'); + const recovery = first.with({path: first.path + '.txt'}); + const original = Uint8Array.from(atob(fixture), char => char.charCodeAt(0)); + const settings = vscode.workspace.getConfiguration('r'); + const previousRuntime = settings.inspect('lsp.runtime')?.globalValue; + try { + await settings.update('lsp.runtime','native',vscode.ConfigurationTarget.Global); + await fs.writeFile(first, original); + const a = await addProject(first); + assert(a.doc.getText().trim() === 'value <- 40L', 'The bundle did not supply the project script.'); + const edit = new vscode.WorkspaceEdit(); + edit.replace(a.doc.uri, new vscode.Range(a.doc.positionAt(0), a.doc.positionAt(a.doc.getText().length)), 'value <- 42L\n'); + assert(await vscode.workspace.applyEdit(edit) && await a.doc.save(), 'Could not save in the project workspace.'); + + const out = await a.run('stopifnot(getwd() == "/project"); source("tools/fit.R"); session_marker <- TRUE; writeLines(as.character(value), "result.txt"); cat(value)'); + assert(out.includes('42') && decoder.decode(await fs.readFile(a.uri('result.txt'))).trim() === '42', + 'Explorer and R did not share project files.'); + await a.run('writeLines("saved", "before-error.txt"); stop("deliberate test error")', false); + assert(decoder.decode(await fs.readFile(a.uri('before-error.txt'))).trim() === 'saved', 'A failed cell lost its completed write.'); + if (globalThis.crossOriginIsolated) { + await activeCell(a, 'writeLines("saved", "before-interrupt.txt"); cat("running\\n"); repeat {Sys.sleep(0.05)}', + () => command('r.interactive.interrupt')); + assert(decoder.decode(await fs.readFile(a.uri('before-interrupt.txt'))).trim() === 'saved', 'Interrupt lost a completed R write.'); + } + + // Save the same path from Explorer while the R cell is running. + await activeCell(a, 'cat("running\\n"); Sys.sleep(1.5); writeLines("R copy", "same.txt")', + () => fs.writeFile(a.uri('same.txt'), encoder.encode('editor copy\n'))); + assert(decoder.decode(await fs.readFile(a.uri('same.txt'))).trim() === 'editor copy', 'R replaced the competing editor save.'); + await command('r.webR.exportFile', 'same.txt', recovery); + assert(decoder.decode(await fs.readFile(recovery)).trim() === 'R copy', 'R-side conflict recovery lost the unpublished data.'); + await a.run('writeLines("editor copy", "same.txt")'); + + // Pass only the archive bytes to a fresh project and worker. + await fs.writeFile(second, await fs.readFile(first)); + const b = await addProject(second); + assert(b.doc.getText().trim() === 'value <- 42L', 'Reopening the archive lost the editor save.'); + // Bound source files use their own worker even under a native setting. + const call = b.uri('caller.R'); + await fs.writeFile(call, encoder.encode('value + 1L\n')); + await vscode.workspace.openTextDocument(call); + await until(async () => { + const locations = await command('vscode.executeDefinitionProvider',call,new vscode.Position(0,2)); + return locations?.length === 1 && (locations[0].uri ?? locations[0].targetUri).toString() === b.doc.uri.toString(); + }, 'Go to Definition did not stay inside the owning project.'); + const fresh = await b.run('stopifnot(!exists("session_marker"), getwd() == "/project"); source("tools/fit.R"); cat(value, readLines("result.txt"), readLines("before-error.txt"))'); + assert(fresh.includes('42 42 saved'), 'The new worker read old project files: ' + fresh); + + await vscode.window.showTextDocument(a.doc); + assert((await a.run('cat(exists("session_marker"))')).includes('TRUE'), 'The source routed to a different project notebook.'); + await fs.writeFile(a.uri('nested.txt'), encoder.encode('data from A')); + await vscode.window.showTextDocument(b.doc); + await command('r.webR.importFiles', [a.uri('nested.txt')]); + const imported = vscode.workspace.asRelativePath(a.uri('nested.txt')); + assert(decoder.decode(await fs.readFile(b.uri(imported))) === 'data from A', 'The project import lost its relative path.'); + + await fs.writeFile(second, original); + let conflict; + try {await fs.writeFile(b.uri('conflict.txt'), encoder.encode('do not overwrite'));} + catch (error) {conflict = error;} + assert(conflict instanceof Error && /changed outside/.test(conflict.message), 'An external replacement must reject the stale writer.'); + const kept = await fs.readFile(second); + assert(kept.length === original.length && kept.every((v, i) => v === original[i]), 'The conflicting bundle was overwritten.'); + console.log('Verified shared browser projects, interrupt/error saves, concurrent edits, recovery, portable reopen and separate workers.'); + } finally { + await settings.update('lsp.runtime',previousRuntime,vscode.ConfigurationTarget.Global); + await command('r.interactive.stopAll'); + const count = (vscode.workspace.workspaceFolders?.length ?? 0) - index; + if (count > 0) {vscode.workspace.updateWorkspaceFolders(index, count);} + await fs.delete(folder,{recursive:true}).then(undefined,()=>{}); + } +}; diff --git a/src/web/extension.ts b/src/web/extension.ts index 7801d16e5..11184547d 100644 --- a/src/web/extension.ts +++ b/src/web/extension.ts @@ -11,11 +11,29 @@ import { } from '../rmarkdown/chunks'; import { BrowserInteractive } from './interactive'; import { BrowserLanguageService } from './languageService'; +import { BrowserProject, createBrowserProject } from './project'; +import { registerWebRProjects, WEBR_PROJECT_SCHEME } from '../webr/projectWorkspace'; +import { WEBR_FILE_SCHEME } from '../webr/sessionFiles'; export async function activate(context: vscode.ExtensionContext): Promise { await vscode.commands.executeCommand('setContext', 'r.webExtension', true); const interactive = new BrowserInteractive(context); - context.subscriptions.push(interactive, new BrowserLanguageService(context, interactive)); + context.subscriptions.push( + interactive, + new BrowserLanguageService(context, interactive), + registerWebRProjects(context, { + accepts: (source) => + ![ + WEBR_PROJECT_SCHEME, + WEBR_FILE_SCHEME, + 'untitled', + 'vscode-notebook-cell', + ].includes(source.scheme), + create: createBrowserProject, + open: (source, root) => BrowserProject.open(source, root), + start: (_source, _root, volume) => interactive.startProject(volume as BrowserProject), + }), + ); const runSource = async () => { const editor = vscode.window.activeTextEditor; diff --git a/src/web/files.ts b/src/web/files.ts index d65a3fd05..33d357f5d 100644 --- a/src/web/files.ts +++ b/src/web/files.ts @@ -15,14 +15,18 @@ function segments(path: string): string[] { return parts; } -export async function importFiles(runtime: WebR, files: readonly vscode.Uri[]): Promise { +export async function importFiles( + runtime: WebR, + files: readonly vscode.Uri[], + directoryRoot = sessionDirectory, +): Promise { for (const file of files) { const folder = vscode.workspace.getWorkspaceFolder(file); const relative = folder ? vscode.workspace.asRelativePath(file) : file.path.slice(file.path.lastIndexOf('/') + 1); const parts = segments(relative); - let directory = sessionDirectory; + let directory = directoryRoot; for (const part of parts.slice(0, -1)) { directory += '/' + part; if (!(await runtime.FS.analyzePath(directory)).exists) { @@ -30,7 +34,7 @@ export async function importFiles(runtime: WebR, files: readonly vscode.Uri[]): } } const data = await vscode.workspace.fs.readFile(file); - await runtime.FS.writeFile(sessionDirectory + '/' + parts.join('/'), data); + await runtime.FS.writeFile(directoryRoot + '/' + parts.join('/'), data); } } @@ -38,10 +42,11 @@ export async function exportFile( runtime: WebR, source: string, destination: vscode.Uri, + directoryRoot = sessionDirectory, ): Promise { if (vscode.workspace.fs.isWritableFileSystem(destination.scheme) === false) { throw new Error('Select a destination that permits writing files.'); } - const data = await runtime.FS.readFile(sessionDirectory + '/' + segments(source).join('/')); + const data = await runtime.FS.readFile(directoryRoot + '/' + segments(source).join('/')); await vscode.workspace.fs.writeFile(destination, data); } diff --git a/src/web/interactive.ts b/src/web/interactive.ts index f6a1e4184..9d1f16777 100644 --- a/src/web/interactive.ts +++ b/src/web/interactive.ts @@ -3,16 +3,15 @@ import { InteractiveSerializer } from '../interactive/notebook'; import { BrowserSession } from './session'; import type { WebRPackageSource } from '../webr/packageContext'; import { exportFile, importFiles } from './files'; +import { BrowserProject } from './project'; +import { projectDirectory } from './projectMirror'; +import { WEBR_PROJECT_SCHEME } from '../webr/projectWorkspace'; 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) => group.tabs.some( @@ -28,6 +27,9 @@ export class BrowserInteractive implements vscode.Disposable { notebookType, 'R (webR)', ); + private readonly projects = new Map(); + private readonly notebookProjects = new Map(); + private readonly openingProjects = new Map>(); private readonly sessions = new Map(); private readonly files: WebRSessionFiles; private readonly treeChanges = new vscode.EventEmitter(); @@ -158,12 +160,30 @@ export class BrowserInteractive implements vscode.Disposable { this.updatePresentation(); } + private notebookLabel(doc: vscode.NotebookDocument): string { + return ( + this.projectRoot(doc)?.path.slice(1) || + doc.uri.path.split('/').pop() || + doc.uri.toString() + ); + } + + private fileDetail(doc?: vscode.NotebookDocument): string { + const project = doc && this.notebookProjects.get(doc); + if (!project) { + return filesystemDetail; + } + return project.writable + ? 'Files in /project are saved in the .webrproj archive after each cell. Files elsewhere belong to this browser session.' + : 'This .webrproj is read-only. Export changes from /project to a writable destination before closing the browser session.'; + } + private treeItem(doc: vscode.NotebookDocument): vscode.TreeItem { - const item = new vscode.TreeItem(notebookLabel(doc)); + const item = new vscode.TreeItem(this.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.tooltip = `webR · ${this.notebookLabel(doc)}\n${this.fileDetail(doc)}`; item.contextValue = 'rInteractiveSession.webR'; item.command = { command: 'r.interactive.open', @@ -179,18 +199,21 @@ export class BrowserInteractive implements vscode.Disposable { } this.treeChanges.fire(); const doc = this.target(); + this.controller.detail = this.fileDetail(doc); 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.text = `$(notebook) webR: ${this.notebookLabel(doc)} · ${state}`; + this.status.tooltip = `${this.fileDetail(doc)}\nManage this webR session`; this.status.show(); } private forget(doc: vscode.NotebookDocument): void { this.stop(doc); + this.notebookProjects.delete(doc); + this.fileOwners.fire(); if (this.last === doc) { this.last = undefined; } @@ -199,7 +222,7 @@ export class BrowserInteractive implements vscode.Disposable { private target(): vscode.NotebookDocument | undefined { const text = vscode.window.activeTextEditor?.document.uri; - if (text?.scheme === WEBR_FILE_SCHEME) { + if (text?.scheme === WEBR_FILE_SCHEME || text?.scheme === WEBR_PROJECT_SCHEME) { return this.fileNotebook(text); } const active = vscode.window.activeNotebookEditor?.notebook; @@ -211,7 +234,30 @@ export class BrowserInteractive implements vscode.Disposable { )); } + private projectFor(uri: vscode.Uri): BrowserProject | undefined { + if (uri.scheme !== WEBR_PROJECT_SCHEME) { + return; + } + const project = this.projects.get(uri.authority); + if ( + project && + (uri.path === project.root.path || uri.path.startsWith(project.root.path + '/')) + ) { + return project; + } + } + + projectRoot(doc: vscode.NotebookDocument): vscode.Uri | undefined { + return this.notebookProjects.get(doc)?.root; + } + fileNotebook(uri: vscode.Uri): vscode.NotebookDocument | undefined { + if (uri.scheme === WEBR_PROJECT_SCHEME) { + const project = this.projectFor(uri); + return ( + project && [...this.notebookProjects].find(([, owner]) => owner === project)?.[0] + ); + } const owner = sessionFileOwner(uri); if (owner) { for (const [doc, current] of this.registrationsByNotebook) { @@ -260,16 +306,25 @@ export class BrowserInteractive implements vscode.Disposable { () => this.packageUpdates.fire(doc), () => this.updatePresentation(), () => this.files.refresh(id, generation), - (path, create) => this.files.open(id, generation, path, create), + (path, create) => { + const open = () => this.files.open(id, generation, path, create); + // A file created by the current R cell appears in Explorer when + // the cell settles. Queue its editor request behind that save. + return this.projectRoot(doc) && path.startsWith('/project/') + ? owner.run(open) + : open(); + }, + this.notebookProjects.get(doc), ); const owner = session; this.sessions.set(doc, owner); const registration = this.files.add({ id, generation, - label: notebookLabel(doc), + label: this.notebookLabel(doc), + projectUri: this.projectRoot(doc), location: doc.uri, - initialDirectory: '/workspace', + initialDirectory: this.projectRoot(doc) ? projectDirectory : '/workspace', files: () => owner.fileAccess(), }); this.registrationsByNotebook.set(doc, { id, generation, registration }); @@ -279,6 +334,68 @@ export class BrowserInteractive implements vscode.Disposable { return session; } + async startProject(project: BrowserProject): Promise { + this.projects.set(project.root.authority, project); + project.onRelease = () => { + if (this.projects.get(project.root.authority) !== project) { + return; + } + this.projects.delete(project.root.authority); + for (const [doc, owner] of this.notebookProjects) { + if (owner === project) { + this.forget(doc); + } + } + }; + const doc = await this.openProject(project, false); + await this.session(doc).fileAccess(); + } + + private openProject( + project: BrowserProject, + preserveFocus: boolean, + ): Promise { + const pending = this.openingProjects.get(project); + if (pending) { + return pending; + } + const open = (async () => { + let doc = this.fileNotebook(project.root); + if (!doc) { + const key = 'r.webR.projectNotebook.' + project.root.authority; + const saved = this.context.workspaceState.get(key); + if (saved && openTabFor(saved)) { + const restored = await vscode.workspace + .openNotebookDocument(vscode.Uri.parse(saved)) + .then( + (value) => value, + () => undefined, + ); + if ( + restored?.notebookType === notebookType && + restored.metadata.rWebRProject === project.root.toString() + ) { + doc = restored; + } + } + if (!doc) { + const data = new vscode.NotebookData([]); + data.metadata = { rWebRProject: project.root.toString() }; + doc = await vscode.workspace.openNotebookDocument(notebookType, data); + } + if (this.projects.get(project.root.authority) !== project) { + throw new Error('The webR project was closed.'); + } + this.notebookProjects.set(doc, project); + await this.context.workspaceState.update(key, doc.uri.toString()); + this.fileOwners.fire(); + } + return this.reveal(doc, preserveFocus); + })().finally(() => this.openingProjects.delete(project)); + this.openingProjects.set(project, open); + return open; + } + private async reveal(doc: vscode.NotebookDocument, preserveFocus: boolean) { if (this.disposed || doc.isClosed) { throw new Error('The R Interactive notebook is closed.'); @@ -296,6 +413,7 @@ export class BrowserInteractive implements vscode.Disposable { visible?.viewColumn ?? (preserveFocus ? vscode.ViewColumn.Beside : vscode.ViewColumn.Active), preserveFocus, + ...(this.projectRoot(doc) ? { preview: false } : {}), }); await vscode.commands.executeCommand('notebook.selectKernel', { id: this.controller.id, @@ -307,6 +425,11 @@ export class BrowserInteractive implements vscode.Disposable { } open(create = false, preserveFocus = false): Promise { + const active = vscode.window.activeTextEditor?.document.uri; + const project = !create && active && this.projectFor(active); + if (project) { + return this.openProject(project, preserveFocus); + } if (this.opening) { return this.opening; } @@ -336,7 +459,17 @@ export class BrowserInteractive implements vscode.Disposable { '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); + const project = source && this.projectFor(source); + if (source?.scheme === WEBR_PROJECT_SCHEME && !project) { + throw new Error( + 'Open the .webrproj workspace to run this file in its project session.', + ); + } + const doc = project + ? await this.openProject(project, true) + : 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.'); } @@ -396,7 +529,11 @@ export class BrowserInteractive implements vscode.Disposable { return; } const doc = await this.open(false, true); - await this.session(doc).files((runtime) => importFiles(runtime, files)); + await this.session(doc).files( + (runtime) => + importFiles(runtime, files, this.projectRoot(doc) ? projectDirectory : undefined), + true, + ); } async export(source?: string, destination?: vscode.Uri): Promise { @@ -423,7 +560,14 @@ export class BrowserInteractive implements vscode.Disposable { : undefined, })); if (target) { - await this.session(doc).files((runtime) => exportFile(runtime, name, target)); + await this.session(doc).files((runtime) => + exportFile( + runtime, + name, + target, + this.projectRoot(doc) ? projectDirectory : undefined, + ), + ); } } @@ -458,7 +602,7 @@ export class BrowserInteractive implements vscode.Disposable { const actions = [ { label: 'Open webR Session File…', - detail: filesystemDetail, + detail: this.fileDetail(this.target()), run: () => this.openFile(), }, { label: 'Import files into webR…', run: () => this.import() }, @@ -475,6 +619,8 @@ export class BrowserInteractive implements vscode.Disposable { dispose(): void { this.disposed = true; this.stopAll(); + this.projects.clear(); + this.notebookProjects.clear(); for (const entry of this.registrations) { entry.dispose(); } diff --git a/src/web/languageService.ts b/src/web/languageService.ts index 0d90b65e7..b011977c7 100644 --- a/src/web/languageService.ts +++ b/src/web/languageService.ts @@ -14,6 +14,7 @@ import { cachedWebRAssets } from '../webr/assetCache'; import { WEBR_BASE_URL } from '../webr/runtime'; import type { BrowserInteractive } from './interactive'; import { WEBR_FILE_SCHEME } from '../webr/sessionFiles'; +import { WEBR_PROJECT_SCHEME } from '../webr/projectWorkspace'; /** The service provides one retry action for startup and worker failures. */ class WorkerLanguageClient extends LanguageClient { @@ -38,7 +39,11 @@ interface ClientSlot { } /** A notebook filter is matched against the owning notebook URI, not the cell URI. */ -function notebookSelector(notebook: vscode.NotebookDocument, files?: string): DocumentFilter[] { +function notebookSelector( + notebook: vscode.NotebookDocument, + files?: string, + project?: vscode.Uri, +): DocumentFilter[] { const pattern = notebook.uri.fsPath.replace(/[?*{}[\]]/g, (char) => `[${char}]`); const selectors: DocumentFilter[] = rLanguages.map((language) => ({ language, @@ -53,6 +58,15 @@ function notebookSelector(notebook: vscode.NotebookDocument, files?: string): Do })), ); } + if (project) { + selectors.push( + ...rLanguages.map((language) => ({ + language, + scheme: WEBR_PROJECT_SCHEME, + pattern: { baseUri: project.toString(), pattern: '**/*' }, + })), + ); + } return selectors; } @@ -76,7 +90,7 @@ function notebookSession( if (typeof params?.textDocument?.uri === 'string') { const cell = vscode.Uri.parse(params.textDocument.uri); const matches = - cell.scheme === WEBR_FILE_SCHEME + cell.scheme === WEBR_FILE_SCHEME || cell.scheme === WEBR_PROJECT_SCHEME ? interactive.fileNotebook(cell) === owner : cell.scheme === 'vscode-notebook-cell' && cell.authority === owner.uri.authority && @@ -162,7 +176,7 @@ export class BrowserLanguageService implements vscode.Disposable { const filesFor = new Set(); const otherNotebooks = new Set(); for (const doc of vscode.workspace.textDocuments) { - if (doc.uri.scheme === WEBR_FILE_SCHEME) { + if (doc.uri.scheme === WEBR_FILE_SCHEME || doc.uri.scheme === WEBR_PROJECT_SCHEME) { const owner = this.interactive.fileNotebook(doc.uri); if (owner && rLanguages.includes(doc.languageId)) { filesFor.add(owner); @@ -188,7 +202,11 @@ export class BrowserLanguageService implements vscode.Disposable { if (notebook.notebookType === interactiveType) { desired.set( notebook.uri.toString(), - notebookSelector(notebook, this.interactive.fileSelector(notebook)), + notebookSelector( + notebook, + this.interactive.fileSelector(notebook), + this.interactive.projectRoot(notebook), + ), ); } else { otherNotebooks.add(notebook.notebookType); diff --git a/src/web/project.ts b/src/web/project.ts new file mode 100644 index 000000000..5a24b58d8 --- /dev/null +++ b/src/web/project.ts @@ -0,0 +1,408 @@ +import * as vscode from 'vscode'; +import { + decodeProject, + encodeProject, + PROJECT_ARCHIVE_LIMIT, + type ProjectTree, + validateProjectPath, +} from '../webr/projectArchive'; +import { createProjectFile, projectDigest, type WebRProjectVolume } from '../webr/projectWorkspace'; + +export function sameEntry( + a: Uint8Array | null | undefined, + b: Uint8Array | null | undefined, +): boolean { + return ( + a === b || + (a instanceof Uint8Array && + b instanceof Uint8Array && + a.length === b.length && + a.every((byte, index) => byte === b[index])) + ); +} + +function parent(path: string): string { + return path.slice(0, Math.max(0, path.lastIndexOf('/'))); +} + +function requireDirectory(tree: ProjectTree, path: string): void { + if (!path || tree.get(path) === null) { + return; + } + if (!tree.has(path)) { + throw vscode.FileSystemError.FileNotFound(path); + } + throw vscode.FileSystemError.FileNotADirectory(path); +} + +function remove(tree: ProjectTree, path: string, recursive: boolean): void { + const children = [...tree.keys()].filter((name) => name.startsWith(path + '/')); + if (!recursive && children.length) { + throw vscode.FileSystemError.NoPermissions('The directory is not empty.'); + } + children.forEach((name) => tree.delete(name)); + tree.delete(path); +} + +// Web extension hosts run in dedicated workers. A Web Lock serializes the last +// revision check and replacement across workbench tabs sharing the same storage. +interface BrowserLocks { + request(name: string, callback: () => Promise): Promise; +} +function locks(): BrowserLocks | undefined { + return (globalThis.navigator as Navigator & { locks?: BrowserLocks }).locks; +} + +export async function createBrowserProject(source: vscode.Uri, bytes: Uint8Array): Promise { + if (source.scheme !== 'file') { + return createProjectFile(source, bytes); + } + const lock = locks(); + if (!lock) { + throw vscode.FileSystemError.NoPermissions( + 'Creating browser projects requires a secure browser with Web Locks.', + ); + } + await lock.request('vscode-R.webrproj:' + source.toString(), async () => { + // The browser's save picker creates the selected file and grants a + // handle to it. A neighboring temp file need not be accessible. + try { + const target = await vscode.workspace.fs.stat(source); + if (target.type !== vscode.FileType.File || target.size !== 0) { + throw vscode.FileSystemError.FileExists('Choose a new or empty .webrproj file.'); + } + } catch (error) { + if (!(error instanceof vscode.FileSystemError) || error.code !== 'FileNotFound') { + throw error; + } + } + await vscode.workspace.fs.writeFile(source, bytes); + const saved = await vscode.workspace.fs.readFile(source); + if (!sameEntry(saved, bytes)) { + throw vscode.FileSystemError.Unavailable( + 'The browser could not verify the newly created .webrproj.', + ); + } + }); +} + +export class BrowserProject implements WebRProjectVolume { + private readonly changed = new vscode.EventEmitter< + { path: string; type: vscode.FileChangeType }[] + >(); + readonly onDidChange = this.changed.event; + private readonly mtimes = new Map(); + private revisionTime = Date.now(); + private queue = Promise.resolve(); + private disposed = false; + onRelease?: () => void; + + private constructor( + readonly source: vscode.Uri, + readonly root: vscode.Uri, + private contents: ProjectTree, + private digest: string, + private readonly readOnly: boolean, + ) {} + + static async open(source: vscode.Uri, root: vscode.Uri): Promise { + const stat = await vscode.workspace.fs.stat(source); + if (!(stat.type & vscode.FileType.File) || stat.size > PROJECT_ARCHIVE_LIMIT) { + throw vscode.FileSystemError.Unavailable('Select a supported .webrproj archive.'); + } + const bytes = await vscode.workspace.fs.readFile(source); + return new BrowserProject( + source, + root, + await decodeProject(bytes), + await projectDigest(bytes), + stat.permissions === vscode.FilePermission.Readonly || + vscode.workspace.fs.isWritableFileSystem(source.scheme) === false, + ); + } + + get writable(): boolean { + return !this.readOnly && !!locks(); + } + + // Each published snapshot is immutable for the entire lifetime of a cell. + get snapshot(): ReadonlyMap { + return this.contents; + } + + stat(path: string): Promise { + const entry = path ? this.contents.get(path) : null; + if (entry === undefined) { + throw vscode.FileSystemError.FileNotFound(path); + } + const mtime = this.mtimes.get(path) ?? 0; + return Promise.resolve({ + type: entry === null ? vscode.FileType.Directory : vscode.FileType.File, + ctime: 0, + mtime, + size: entry?.length ?? 0, + permissions: this.writable ? undefined : vscode.FilePermission.Readonly, + }); + } + + readDirectory(path: string): Promise<[string, vscode.FileType][]> { + requireDirectory(this.contents, path); + const children: [string, vscode.FileType][] = []; + for (const [name, value] of this.contents) { + if (parent(name) === path) { + children.push([ + name.slice(name.lastIndexOf('/') + 1), + value === null ? vscode.FileType.Directory : vscode.FileType.File, + ]); + } + } + return Promise.resolve(children); + } + + readFile(path: string): Promise { + const value = this.contents.get(path); + if (value === undefined) { + throw vscode.FileSystemError.FileNotFound(path); + } + if (value === null) { + throw vscode.FileSystemError.FileIsADirectory(path); + } + return Promise.resolve(value.slice()); + } + + writeFile( + path: string, + data: Uint8Array, + options: { create: boolean; overwrite: boolean; expected?: string }, + ): Promise { + return this.update(async (next) => { + validateProjectPath(path); + requireDirectory(next, parent(path)); + const old = next.get(path); + if (old === null) { + throw vscode.FileSystemError.FileIsADirectory(path); + } + if ( + options.expected !== undefined && + (old === undefined || (await projectDigest(old)) !== options.expected) + ) { + throw vscode.FileSystemError.Unavailable( + 'This project file changed since it was read. Reopen or compare it before saving.', + ); + } + if (old === undefined && !options.create) { + throw vscode.FileSystemError.FileNotFound(path); + } + if (old !== undefined && !options.overwrite) { + throw vscode.FileSystemError.FileExists(path); + } + next.set(path, data.slice()); + }); + } + + createDirectory(path: string): Promise { + return this.update((next) => { + validateProjectPath(path); + requireDirectory(next, parent(path)); + if (next.has(path) && next.get(path) !== null) { + throw vscode.FileSystemError.FileExists(path); + } + next.set(path, null); + }); + } + + delete(path: string, options: { recursive: boolean }): Promise { + return this.update((next) => { + validateProjectPath(path); + if (!next.has(path)) { + throw vscode.FileSystemError.FileNotFound(path); + } + remove(next, path, options.recursive); + }); + } + + rename(from: string, to: string, options: { overwrite: boolean }): Promise { + return this.update((next) => { + validateProjectPath(from); + validateProjectPath(to); + if (!next.has(from)) { + throw vscode.FileSystemError.FileNotFound(from); + } + if (from === to) { + return; + } + if (to.startsWith(from + '/') || from.startsWith(to + '/')) { + throw vscode.FileSystemError.NoPermissions('Overlapping project paths.'); + } + requireDirectory(next, parent(to)); + if (next.has(to)) { + if (!options.overwrite) { + throw vscode.FileSystemError.FileExists(to); + } + remove(next, to, false); + } + for (const [name, entry] of next) { + if (name === from || name.startsWith(from + '/')) { + next.delete(name); + next.set(to + name.slice(from.length), entry); + } + } + }); + } + + // Merge the cell's changes with edits saved while it was running. Conflicts + // leave the worker intact so the user can export its version. + async saveCell( + base: ReadonlyMap, + files: ProjectTree, + ): Promise { + const changed = [...new Set([...base.keys(), ...files.keys()])].filter( + (path) => !sameEntry(base.get(path), files.get(path)), + ); + if (!changed.length) { + return; + } + await this.update((next) => { + for (const path of changed) { + if ( + !sameEntry(next.get(path), base.get(path)) && + !sameEntry(next.get(path), files.get(path)) + ) { + throw vscode.FileSystemError.Unavailable( + 'Concurrent edits to ' + + path + + '. Export the R copy before restarting this webR session.', + ); + } + const entry = files.get(path); + if (entry === undefined) { + next.delete(path); + } else { + next.set(path, entry); + } + } + for (const path of next.keys()) { + requireDirectory(next, parent(path)); + } + }); + } + + private update(change: (next: ProjectTree) => Promise | void): Promise { + const result = this.queue.then(async () => { + if (this.disposed || !vscode.workspace.isTrusted) { + throw vscode.FileSystemError.NoPermissions( + 'Open the project in a trusted workspace.', + ); + } + if (this.readOnly) { + throw vscode.FileSystemError.NoPermissions( + 'The backing .webrproj is read-only. Use a writable copy to save changes.', + ); + } + const lock = locks(); + if (!lock) { + throw vscode.FileSystemError.NoPermissions( + 'Saving browser projects requires a secure browser with Web Locks.', + ); + } + await lock.request('vscode-R.webrproj:' + this.source.toString(), async () => { + const next = new Map(this.contents); + await change(next); + const events = [...new Set([...next.keys(), ...this.contents.keys()])] + .filter((path) => !sameEntry(next.get(path), this.contents.get(path))) + .map((path) => ({ + path, + type: !next.has(path) + ? vscode.FileChangeType.Deleted + : this.contents.has(path) + ? vscode.FileChangeType.Changed + : vscode.FileChangeType.Created, + })); + if (!events.length) { + await this.checkRevision(); + return; + } + const bytes = await encodeProject(next); + const digest = await projectDigest(bytes); + await this.replaceArchive(bytes, digest); + this.contents = next; + this.digest = digest; + this.revisionTime = Math.max(Date.now(), this.revisionTime + 1); + for (const { path } of events) { + this.mtimes.set(path, this.revisionTime); + this.mtimes.set(parent(path), this.revisionTime); + } + this.changed.fire(events); + }); + }); + this.queue = result.catch(() => {}); + return result; + } + + private async backingDigest(): Promise { + const stat = await vscode.workspace.fs.stat(this.source); + if (stat.size > PROJECT_ARCHIVE_LIMIT) { + return ''; + } + return projectDigest(await vscode.workspace.fs.readFile(this.source)); + } + + private async checkRevision(): Promise { + if (this.disposed) { + throw vscode.FileSystemError.Unavailable( + 'The project closed before the save finished.', + ); + } + if ((await this.backingDigest()) !== this.digest) { + throw vscode.FileSystemError.Unavailable( + 'The backing .webrproj changed outside this window. Export pending R files, save copies of dirty editors, then reload the window.', + ); + } + } + + private async replaceArchive(bytes: Uint8Array, digest: string): Promise { + if (this.source.scheme === 'file') { + // In the browser extension, VS Code's file: provider commits a + // FileSystemWritableFileStream on close(). Opening a single local + // file grants access to the file handle, but not to sibling files. + await this.checkRevision(); + await vscode.workspace.fs.writeFile(this.source, bytes); + return; + } + const temp = vscode.Uri.joinPath( + this.source, + '..', + '.webrproj-' + crypto.randomUUID() + '.tmp', + ); + let preserveTemp = false; + try { + await vscode.workspace.fs.writeFile(temp, bytes); + await this.checkRevision(); + try { + await vscode.workspace.fs.rename(temp, this.source, { overwrite: true }); + } catch (error) { + // Some providers replace the destination and then fail cleaning + // up the source. A committed archive is already safe to use. + if ((await this.backingDigest().catch(() => '')) !== digest) { + preserveTemp = true; + throw vscode.FileSystemError.Unavailable( + 'The provider could not replace this .webrproj. The complete pending archive was staged at ' + + temp.toString(true) + + '. ' + + String(error), + ); + } + } + } finally { + if (!preserveTemp) { + await vscode.workspace.fs.delete(temp).then(undefined, () => {}); + } + } + } + + dispose(): void { + this.disposed = true; + this.onRelease?.(); + this.changed.dispose(); + } +} diff --git a/src/web/projectMirror.ts b/src/web/projectMirror.ts new file mode 100644 index 000000000..1bf0c31f8 --- /dev/null +++ b/src/web/projectMirror.ts @@ -0,0 +1,137 @@ +import type { WebR } from 'webr'; +import { + PROJECT_DATA_LIMIT, + PROJECT_ENTRY_LIMIT, + PROJECT_FILE_LIMIT, + type ProjectTree, + validateProjectPath, +} from '../webr/projectArchive'; +import { BrowserProject, sameEntry } from './project'; + +export const projectDirectory = '/project'; + +// Consult physical MEMFS nodes: a link, mount or device must never turn a +// project save into a copy of some other part of the worker's filesystem. +const installInventory = `(() => { + const module = globalThis.Module, fs = module.FS; + const root = fs.lookupNode(fs.root, 'project'); + module.vscodeRProjectInventory = () => { + if (fs.lookupNode(fs.root, 'project') !== root || root.mounted) + throw Error('The mounted project directory was moved or replaced.'); + const result = []; + let total = 0; + function visit(directory, prefix) { + for (const name of fs.readdir('/project' + prefix)) { + if (name === '.' || name === '..') continue; + const node = fs.lookupNode(directory, name), path = prefix + '/' + name; + const dir = fs.isDir(node.mode); + if (node.mounted || node.mount !== root.mount || (!dir && !fs.isFile(node.mode))) + throw Error('Only regular files and directories can be saved in a webR project: ' + path); + const size = dir ? null : node.node_ops.getattr(node).size; + total += size || 0; + if (size > ${PROJECT_FILE_LIMIT} || total > ${PROJECT_DATA_LIMIT} || result.length >= ${PROJECT_ENTRY_LIMIT}) + throw Error('The webR project exceeds the project archive limits.'); + result.push([path.slice(1),size]); + if (dir) visit(node,path); + } + } + visit(root,''); + return JSON.stringify(result); + }; + return null; +})()`; + +type Snapshot = ReadonlyMap; + +/** One mirror belongs to exactly one R worker. The project volume outlives it. */ +export class ProjectMirror { + private applied: Snapshot = new Map(); + private pending = false; + + constructor(private readonly project: BrowserProject) {} + + async initialize(runtime: WebR): Promise { + await runtime.FS.mkdir(projectDirectory); + await runtime.evalRVoid('webr::eval_js(script)', { env: { script: installInventory } }); + await this.prepare(runtime); + } + + async prepare(runtime: WebR): Promise { + const next = this.project.snapshot; + // A failed save leaves the R copy available for correction or export. + // Do not silently replace it with the archive's last saved version. + if (this.pending || this.applied === next) { + return; + } + const previous = this.applied; + const removed = [...previous] + .filter( + ([path, old]) => !next.has(path) || (next.get(path) === null) !== (old === null), + ) + .sort(([a], [b]) => b.length - a.length); + if (removed.some(([, entry]) => entry === null)) { + const cwd = await runtime.evalRString('base::getwd()'); + if ( + removed.some( + ([path, entry]) => + entry === null && + (cwd === projectDirectory + '/' + path || + cwd.startsWith(projectDirectory + '/' + path + '/')), + ) + ) { + await runtime.evalRVoid('base::setwd("/project")'); + } + } + // Keep track of each successful operation. If a filesystem mutation + // fails partway, the next cell retries the rest of this revision. + const applied = new Map(previous); + this.applied = applied; + for (const [path, entry] of removed) { + const target = projectDirectory + '/' + path; + if (entry === null) { + await runtime.FS.rmdir(target); + } else { + await runtime.FS.unlink(target); + } + applied.delete(path); + } + for (const [path, entry] of [...next].sort(([a], [b]) => a.length - b.length)) { + if (sameEntry(applied.get(path), entry)) { + continue; + } + const target = projectDirectory + '/' + path; + if (entry === null) { + await runtime.FS.mkdir(target); + } else { + await runtime.FS.writeFile(target, entry.slice()); + } + applied.set(path, entry); + } + this.applied = next; + } + + async settle(runtime: WebR): Promise { + this.pending = true; + const files: ProjectTree = new Map(); + const raw = await runtime.evalRString( + 'webr::eval_js("globalThis.Module.vscodeRProjectInventory()")', + ); + const entries = JSON.parse(raw) as [string, number | null][]; + for (const [path, size] of entries) { + validateProjectPath(path); + if (size === null) { + files.set(path, null); + } else { + const bytes = await runtime.FS.readFile(projectDirectory + '/' + path); + if (bytes.length !== size) { + throw Error('A project file changed during the save: ' + path); + } + const previous = this.applied.get(path); + files.set(path, previous && sameEntry(previous, bytes) ? previous : bytes); + } + } + await this.project.saveCell(this.applied, files); + this.applied = files; + this.pending = false; + } +} diff --git a/src/web/session.ts b/src/web/session.ts index 86ffc637a..248949a4d 100644 --- a/src/web/session.ts +++ b/src/web/session.ts @@ -5,6 +5,8 @@ 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 type { BrowserProject } from './project'; +import { ProjectMirror, projectDirectory } from './projectMirror'; import { createWebRFileAccess, type WebRFileAccess } from '../webr/filesystem'; import { BrowserViewers } from './viewers'; import { webRWidgetHtml } from '../webr/widgetHtml'; @@ -31,6 +33,7 @@ export class BrowserSession implements vscode.Disposable { console: WebRConsole; ready: Promise; files: WebRFileAccess; + mirror?: ProjectMirror; }; private current?: ActiveCell; private queue = Promise.resolve(); @@ -52,6 +55,7 @@ export class BrowserSession implements vscode.Disposable { private readonly stateChanged: () => void, private readonly filesChanged: () => void, private readonly openFile: (path: string, create: boolean) => Promise, + private readonly project?: BrowserProject, ) { this.viewers = new BrowserViewers(extension, doc, (method, params) => this.run(async () => { @@ -142,14 +146,17 @@ export class BrowserSession implements vscode.Disposable { this.stateChanged(); }, ); + const mirror = this.project ? new ProjectMirror(this.project) : undefined; 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); + if (mirror) { + await mirror.initialize(runtime); + } else { + await runtime.FS.mkdir(sessionDirectory); + } await runtime.evalRVoid('base::setwd(directory)', { - env: { directory: sessionDirectory }, + env: { directory: mirror ? projectDirectory : sessionDirectory }, }); }) .catch((error: unknown) => { @@ -161,7 +168,7 @@ export class BrowserSession implements vscode.Disposable { throw error; }); const files = createWebRFileAccess(runtime, (operation) => this.run(operation)); - this.worker = { runtime, console: session, ready, files }; + this.worker = { runtime, console: session, ready, files, mirror }; void ready.then( () => this.stateChanged(), () => this.stateChanged(), @@ -170,10 +177,18 @@ export class BrowserSession implements vscode.Disposable { return this.worker; } - async files(operation: (runtime: WebR) => Promise): Promise { + async files(operation: (runtime: WebR) => Promise, editing = false): Promise { return this.run(async () => { const worker = this.getWorker(); await worker.ready; + await worker.mirror?.prepare(worker.runtime); + if (editing) { + try { + return await operation(worker.runtime); + } finally { + await worker.mirror?.settle(worker.runtime); + } + } return operation(worker.runtime); }); } @@ -222,16 +237,24 @@ export class BrowserSession implements vscode.Disposable { if (this.closed) { return; } - const outcome = await worker.console.execute( - cell.document.getText(), - this.lifetime.signal, - ); - success = outcome === 'success'; + await worker.mirror?.prepare(worker.runtime); + try { + const outcome = await worker.console.execute( + cell.document.getText(), + this.lifetime.signal, + ); + success = outcome === 'success'; + } finally { + if (!this.closed && !this.failed) { + await worker.mirror?.settle(worker.runtime); + } + } await active.output.flush(); if (active.outputError) { throw active.outputError; } } catch (error) { + success = false; await active.output.flush(); if (!this.closed) { await execution.appendOutput( diff --git a/src/webr/fileRevisions.ts b/src/webr/fileRevisions.ts new file mode 100644 index 000000000..5bead34e9 --- /dev/null +++ b/src/webr/fileRevisions.ts @@ -0,0 +1,175 @@ +import * as vscode from 'vscode'; + +/** Retain the revision a text editor actually saw, including across hot exit. */ +export class WebRFileRevisions implements vscode.Disposable { + // 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 closeListener: vscode.Disposable; + + constructor( + private readonly workspaceState: vscode.Memento | undefined, + private readonly stateKey: string, + accepts: (uri: vscode.Uri) => boolean, + ) { + const saved = workspaceState?.get(this.stateKey); + 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 (accepts(vscode.Uri.parse(id))) { + this.versions.set(id, version); + this.recovered.add(id); + } + } + } + this.closeListener = vscode.Disposable.from( + vscode.workspace.onDidOpenTextDocument((doc) => { + if (!accepts(doc.uri)) { + 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 || !accepts(document.uri)) { + 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 (!accepts(doc.uri) || 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 file 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(this.stateKey, 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 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, + ), + ) + ); + } + + async read(uri: vscode.Uri, bytes: Uint8Array, version: string): Promise { + const id = uri.toString(); + if (!this.dirty(id)) { + this.pendingReads.set(id, 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) !== version) { + const text = new TextDecoder().decode(bytes); + if (doc.getText() === text) { + await this.remember(id, version); + } else { + this.pendingReloads.set(id, { version, text }); + } + } + } + } + } + + expected(uri: vscode.Uri): string | undefined { + const id = uri.toString(); + 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 file or use Save As to keep your edits.', + ); + } + return original ?? this.pendingReads.get(id); + } + + async wrote(uri: vscode.Uri, version: string): Promise { + const id = uri.toString(); + this.pendingReads.set(id, version); + this.recovered.delete(id); + await this.remember(id, version); + } + + async forget(uri: vscode.Uri): Promise { + const id = uri.toString(); + this.pendingReads.delete(id); + this.pendingReloads.delete(id); + this.recovered.delete(id); + await this.remember(id, undefined); + } + + dispose(): void { + this.closeListener.dispose(); + this.pendingReads.clear(); + this.pendingReloads.clear(); + this.recovered.clear(); + this.versions.clear(); + } +} diff --git a/src/webr/projectArchive.ts b/src/webr/projectArchive.ts new file mode 100644 index 000000000..cf1fcc661 --- /dev/null +++ b/src/webr/projectArchive.ts @@ -0,0 +1,205 @@ +import { + type FileEntry, + Uint8ArrayReader, + Uint8ArrayWriter, + ZipReader, + ZipWriter, +} from '@zip.js/zip.js/index-native.js'; + +/** Paths are relative to the project root. A null value represents a directory. */ +export type ProjectTree = Map; +export const PROJECT_ARCHIVE_LIMIT = 160 * 1024 * 1024; +export const PROJECT_DATA_LIMIT = 128 * 1024 * 1024; +export const PROJECT_FILE_LIMIT = 64 * 1024 * 1024; +export const PROJECT_ENTRY_LIMIT = 10_000; +const manifestLimit = 64 * 1024; +const encoder = new TextEncoder(); +// File names must round-trip on Windows and through a UTF-8 ZIP directory. +// oxlint-disable-next-line no-control-regex +const invalidCharacters = /[<>:"\\|?*\u0000-\u001f\u007f\ud800-\udfff]/u; +const deviceName = /^(?:con|prn|aux|nul|conin\$|conout\$|(?:com|lpt)[1-9¹²³]) *(?:\.|$)/i; + +export function validateProjectPath(path: string): void { + if (path.length > 4096 || encoder.encode(path).length > 4096) { + throw new Error('The webR project path exceeds 4096 UTF-8 bytes.'); + } + for (const part of path.split('/')) { + if ( + !part || + part.endsWith('.') || + part.endsWith(' ') || + invalidCharacters.test(part) || + deviceName.test(part) || + encoder.encode(part).length > 255 + ) { + throw new Error(`Invalid webR project path: ${JSON.stringify(path)}.`); + } + } +} + +/** Some ZIP writers omit parent directories. Record them and detect file/directory + * and spelling collisions before a case-insensitive host materializes the tree. */ +class ProjectPaths { + readonly entries = new Map(); + private readonly spellings = new Set(); + + add(path: string, value: T | null): void { + validateProjectPath(path); + // Once an exact directory is known, all its ancestors were checked when + // we added it. Siblings in a deep tree need not retrace the whole path. + let name = path; + let entry = value; + while (true) { + if (entry === null && this.entries.get(name) === null) { + return; + } + const spelling = name.normalize('NFC').toUpperCase(); + if (this.spellings.has(spelling)) { + throw new Error(`Conflicting webR project path: ${name}.`); + } + if (this.entries.size >= PROJECT_ENTRY_LIMIT) { + throw new Error('The webR project exceeds 10,000 files and directories.'); + } + this.spellings.add(spelling); + this.entries.set(name, entry); + const slash = name.lastIndexOf('/'); + if (slash < 0) { + return; + } + name = name.slice(0, slash); + entry = null; + } + } +} + +function includeFile(total: number, size: number): number { + if (!Number.isSafeInteger(size) || size < 0 || size > PROJECT_FILE_LIMIT) { + throw new Error('A webR project file exceeds 64 MiB or has an invalid size.'); + } + if (total + size > PROJECT_DATA_LIMIT) { + throw new Error('The webR project exceeds 128 MiB of uncompressed files.'); + } + return total + size; +} + +export async function decodeProject(bytes: Uint8Array): Promise { + if (bytes.length > PROJECT_ARCHIVE_LIMIT) { + throw new Error('The webR project archive exceeds 160 MiB.'); + } + const reader = new ZipReader(new Uint8ArrayReader(bytes), { + useWebWorkers: false, + strictness: 'strict', + checkSignature: true, + }); + try { + let manifest: FileEntry | undefined; + const paths = new ProjectPaths(); + let total = 0; + let members = 0; + for await (const entry of reader.getEntriesGenerator()) { + // Bound ZIP records too, including duplicate directory entries that + // would otherwise collapse to a single path in the project tree. + if (++members > PROJECT_ENTRY_LIMIT + 2) { + throw new Error('The webR project contains too many ZIP entries.'); + } + const type = (entry.externalFileAttributes >>> 16) & 0o170000; + if ( + entry.encrypted || + entry.symlink || + (type !== 0 && type !== (entry.directory ? 0o040000 : 0o100000)) || + (entry.directory && entry.uncompressedSize !== 0) || + (entry.compressionMethod !== 0 && entry.compressionMethod !== 8) + ) { + throw new Error(`Unsupported webR project ZIP entry: ${entry.filename}.`); + } + if (entry.filename === 'manifest.json' && !entry.directory) { + if (entry.uncompressedSize > manifestLimit) { + throw new Error('The webR project manifest exceeds 64 KiB.'); + } + manifest = entry; + continue; + } + if (entry.directory && entry.filename === 'files/') { + continue; + } + if (!entry.filename.startsWith('files/')) { + throw new Error(`Unexpected webR project ZIP entry: ${entry.filename}.`); + } + const path = entry.filename.slice('files/'.length); + if (entry.directory) { + paths.add(path.replace(/\/$/, ''), null); + } else { + total = includeFile(total, entry.uncompressedSize); + paths.add(path, entry); + } + } + if (!manifest) { + throw new Error('Missing webR project manifest.json.'); + } + const metadata: unknown = JSON.parse( + new TextDecoder('utf-8', { fatal: true }).decode( + await manifest.getData(new Uint8ArrayWriter()), + ), + ); + if ( + !metadata || + typeof metadata !== 'object' || + !('format' in metadata) || + metadata.format !== 1 + ) { + throw new Error('Unsupported webR project format. Expected format 1.'); + } + // Extract sequentially after checking declared sizes and the entire path tree. + // zip.js checks the number of bytes produced by the decompressor and the CRC. + const tree: ProjectTree = new Map(); + for (const [path, entry] of paths.entries) { + tree.set(path, entry ? await entry.getData(new Uint8ArrayWriter()) : null); + } + return tree; + } finally { + await reader.close(); + } +} + +/** Validate a proposed filesystem mutation before changing the live checkout. + * The returned map includes inferred directories and shares the original byte arrays. */ +export function validateProjectTree(tree: ProjectTree): ProjectTree { + const paths = new ProjectPaths(); + let total = 0; + for (const [path, bytes] of tree) { + total = includeFile(total, bytes?.length ?? 0); + paths.add(path, bytes); + } + return paths.entries; +} + +export async function encodeProject(tree: ProjectTree): Promise> { + const entries = validateProjectTree(tree); + // ProjectTree carries no filesystem timestamps. Keep the bytes stable across + // unchanged saves, independent of entry insertion order or local time zone. + const writer = new ZipWriter(new Uint8ArrayWriter(), { + useWebWorkers: false, + extendedTimestamp: false, + lastModDate: new Date(1980, 0, 1), + zip64: false, + }); + await writer.add('manifest.json', new Uint8ArrayReader(encoder.encode('{"format":1}\n')), { + level: 0, + }); + await writer.add('files/', undefined, { directory: true }); + for (const path of [...entries.keys()].sort()) { + const data = entries.get(path); + if (data) { + await writer.add('files/' + path, new Uint8ArrayReader(data), { + level: data.length < 256 ? 0 : 6, + }); + } else { + await writer.add('files/' + path + '/', undefined, { directory: true }); + } + } + const archive = await writer.close(); + if (archive.length > PROJECT_ARCHIVE_LIMIT) { + throw new Error('The webR project archive exceeds 160 MiB.'); + } + return archive; +} diff --git a/src/webr/projectWorkspace.ts b/src/webr/projectWorkspace.ts new file mode 100644 index 000000000..50e769309 --- /dev/null +++ b/src/webr/projectWorkspace.ts @@ -0,0 +1,448 @@ +import * as vscode from 'vscode'; +import { + decodeProject, + encodeProject, + PROJECT_ARCHIVE_LIMIT, + validateProjectPath, +} from './projectArchive'; +import { WebRFileRevisions } from './fileRevisions'; + +export const WEBR_PROJECT_SCHEME = 'vscode-r-project'; +const editorId = 'r.webRProject'; +const extension = '.webrproj'; +const sourceKey = 'r.webR.projectSource.v1.'; +const filters = { 'webR projects': ['webrproj'] }; + +export type ProjectWriteOptions = { create: boolean; overwrite: boolean; expected?: string }; +export type ProjectFileChange = { path: string; type: vscode.FileChangeType }; + +/** Paths within a volume are relative to its root. The root itself is ''. */ +export interface WebRProjectVolume { + stat(path: string): PromiseLike; + readDirectory(path: string): PromiseLike<[string, vscode.FileType][]>; + readFile(path: string): PromiseLike; + writeFile(path: string, bytes: Uint8Array, options: ProjectWriteOptions): PromiseLike; + createDirectory(path: string): PromiseLike; + delete(path: string, options: { recursive: boolean }): PromiseLike; + rename(from: string, to: string, options: { overwrite: boolean }): PromiseLike; + onDidChange?: vscode.Event; + dispose?(): void; +} + +export interface WebRProjectHost { + accepts(source: vscode.Uri): boolean; + /** Disambiguate agent-side file URIs from different remote machines. */ + scope?(): Promise; + /** Browser native save pickers can grant access to just the selected file. */ + create?(source: vscode.Uri, bytes: Uint8Array): Promise; + /** Explorer can resolve files before any execution session has started. */ + open(source: vscode.Uri, root: vscode.Uri): Promise; + start(source: vscode.Uri, root: vscode.Uri, volume: WebRProjectVolume): Promise; +} + +/** Publish a complete new bundle without overwriting an existing project. */ +export async function createProjectFile(source: vscode.Uri, bytes: Uint8Array): Promise { + const temp = vscode.Uri.joinPath(source, '..', '.webrproj-' + crypto.randomUUID() + '.tmp'); + try { + await vscode.workspace.fs.writeFile(temp, bytes); + await vscode.workspace.fs.rename(temp, source, { overwrite: false }); + } finally { + await vscode.workspace.fs.delete(temp).then(undefined, () => {}); + } +} + +export async function projectDigest(bytes: Uint8Array): Promise { + const data = + bytes.buffer instanceof ArrayBuffer + ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) + : new Uint8Array(bytes); + const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', data)); + return Array.from(hash, (n) => n.toString(16).padStart(2, '0')).join(''); +} + +export async function webRProjectRoot(source: vscode.Uri, scope?: string): Promise { + const filename = source.path.slice(source.path.lastIndexOf('/') + 1); + const stem = filename.slice(0, -extension.length); + const name = !stem || stem === '.' || stem === '..' ? 'webR project' : stem; + return vscode.Uri.from({ + scheme: WEBR_PROJECT_SCHEME, + authority: await projectDigest( + new TextEncoder().encode( + scope ? JSON.stringify([scope, source.toString()]) : source.toString(), + ), + ), + path: '/' + name, + }); +} + +function split(uri: vscode.Uri): { root: vscode.Uri; path: string } { + if ( + uri.scheme !== WEBR_PROJECT_SCHEME || + !/^[0-9a-f]{64}$/.test(uri.authority) || + !uri.path.startsWith('/') || + uri.query || + uri.fragment + ) { + throw vscode.FileSystemError.FileNotFound(uri); + } + const [, name, ...parts] = uri.path.split('/'); + const path = parts.join('/'); + if (!name) { + throw vscode.FileSystemError.FileNotFound(uri); + } + if (path) { + validateProjectPath(path); + } + return { root: uri.with({ path: '/' + name }), path }; +} + +interface OpenVolume { + volume: WebRProjectVolume; + source: vscode.Uri; + listener?: vscode.Disposable; +} + +/** Maps each stable workspace URI back to the bundle the user actually opened. */ +class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { + private readonly changes = new vscode.EventEmitter(); + readonly onDidChangeFile = this.changes.event; + private readonly volumes = new Map>(); + private readonly starting = new Map>(); + private readonly revisions: WebRFileRevisions; + private readonly subscriptions: vscode.Disposable[] = []; + private closed = false; + + constructor( + private readonly context: vscode.ExtensionContext, + private readonly host: WebRProjectHost, + ) { + this.revisions = new WebRFileRevisions( + context.workspaceState, + 'r.webR.projectFileBaselines.v1', + (uri) => uri.scheme === WEBR_PROJECT_SCHEME, + ); + this.subscriptions.push( + vscode.workspace.registerFileSystemProvider(WEBR_PROJECT_SCHEME, this, { + isCaseSensitive: true, + }), + vscode.window.registerCustomEditorProvider(editorId, { + openCustomDocument: (uri: vscode.Uri) => ({ uri, dispose() {} }), + resolveCustomEditor: async ( + document: vscode.CustomDocument, + panel: vscode.WebviewPanel, + ) => { + try { + await this.openProject(document.uri, panel); + } catch (error) { + panel.dispose(); + void vscode.window.showErrorMessage(String(error)); + } + }, + }), + vscode.commands.registerCommand('r.webR.openProject', async (uri?: vscode.Uri) => { + const source = + uri ?? + ( + await vscode.window.showOpenDialog({ + filters, + defaultUri: this.backingDirectory(), + canSelectMany: false, + canSelectFiles: true, + openLabel: 'Open webR Project', + }) + )?.[0]; + if (source) { + await this.openProject(source); + } + }), + vscode.commands.registerCommand('r.webR.newProject', async () => { + const parent = + this.backingDirectory() ?? vscode.workspace.workspaceFolders?.[0]?.uri; + const browserFilePicker = + vscode.env.uiKind === vscode.UIKind.Web && !vscode.env.remoteName; + const file = await vscode.window.showSaveDialog({ + filters, + defaultUri: parent + ? vscode.Uri.joinPath(parent, 'Untitled.webrproj') + : browserFilePicker + ? vscode.Uri.file('/Untitled.webrproj') + : undefined, + saveLabel: 'Create webR Project', + }); + if (!file) { + return; + } + if ( + browserFilePicker && + file.scheme === 'file' && + !file.path.toLowerCase().endsWith(extension) + ) { + throw new Error( + 'Choose a filename ending in .webrproj in the browser save dialog.', + ); + } + const source = file.path.toLowerCase().endsWith(extension) + ? file + : file.with({ path: file.path + extension }); + this.checkSource(source); + const bytes = await encodeProject(new Map()); + if (host.create) { + await host.create(source, bytes); + } else { + await createProjectFile(source, bytes); + } + await this.openProject(source, undefined, true); + }), + vscode.workspace.onDidGrantWorkspaceTrust(() => this.startRoots()), + vscode.workspace.onDidChangeWorkspaceFolders((event) => this.startRoots(event.added)), + ); + this.startRoots(); + } + + /** From a bundle root, the picker should offer its host directory for the next bundle. */ + private backingDirectory(): vscode.Uri | undefined { + const folder = vscode.workspace.workspaceFolders?.find( + (f) => f.uri.scheme === WEBR_PROJECT_SCHEME, + ); + const stored = + folder && this.context.globalState.get(sourceKey + folder.uri.authority); + return stored ? vscode.Uri.joinPath(vscode.Uri.parse(stored, true), '..') : undefined; + } + + private checkSource(uri: vscode.Uri): void { + if ( + uri.scheme === WEBR_PROJECT_SCHEME || + uri.scheme === 'vscode-r-webr' || + !uri.path.toLowerCase().endsWith(extension) || + !this.host.accepts(uri) + ) { + throw vscode.FileSystemError.Unavailable( + 'Choose a .webrproj file on a filesystem accessible to this VS Code host.', + ); + } + } + + private async openProject( + source: vscode.Uri, + panel?: vscode.WebviewPanel, + created = false, + ): Promise { + this.checkSource(source); + const root = await webRProjectRoot(source, await this.host.scope?.()); + // Reject invalid input before replacing the current workspace. Do not take a + // writer lock or start an R process in this outgoing extension host. + const stat = await vscode.workspace.fs.stat(source); + if (!(stat.type & vscode.FileType.File) || stat.size > PROJECT_ARCHIVE_LIMIT) { + throw new Error('This file is not a supported webR project archive.'); + } + await decodeProject(await vscode.workspace.fs.readFile(source)); + // VS Code can implicitly trust virtual filesystems. Establish trust in + // the original file before exposing its workspace settings to extensions. + const known = + this.context.globalState.get(sourceKey + root.authority) === source.toString(); + const insideTrustedFolder = + vscode.workspace.isTrusted && !!vscode.workspace.getWorkspaceFolder(source); + if ( + !created && + !known && + !insideTrustedFolder && + vscode.workspace.getConfiguration('security.workspace.trust').get('enabled', true) + ) { + const allow = 'Trust Project and Open'; + const choice = await vscode.window.showWarningMessage( + `Do you trust the authors of ${source.path.slice(source.path.lastIndexOf('/') + 1)}?`, + { + modal: true, + detail: 'Opening this file as a workspace applies its workspace settings, activates extensions, and starts R Interactive.', + }, + allow, + ); + if (choice !== allow) { + panel?.dispose(); + return; + } + } + await this.context.globalState.update(sourceKey + root.authority, source.toString()); + // Closing the launcher prevents restoring its old tab from navigating again. + panel?.dispose(); + if ( + vscode.workspace.workspaceFolders?.some( + (folder) => folder.uri.toString() === root.toString(), + ) + ) { + await this.start(root); + return; + } + await vscode.commands.executeCommand('vscode.openFolder', root, { forceReuseWindow: true }); + } + + private startRoots( + folders: readonly vscode.WorkspaceFolder[] = vscode.workspace.workspaceFolders ?? [], + ): void { + for (const { uri } of folders) { + if (uri.scheme === WEBR_PROJECT_SCHEME && vscode.workspace.isTrusted) { + void this.start(uri).catch((error) => { + if (!this.closed) { + void vscode.window.showErrorMessage( + `Cannot start the webR project. ${String(error)}`, + ); + } + }); + } + } + } + + private start(uri: vscode.Uri): Promise { + if (!vscode.workspace.isTrusted) { + return Promise.reject(new Error('Trust this workspace before starting R Interactive.')); + } + const { root } = split(uri); + let pending = this.starting.get(root.authority); + if (!pending) { + pending = this.volume(root) + .then(({ source, volume }) => { + if (!this.closed) { + return this.host.start(source, root, volume); + } + }) + .finally(() => this.starting.delete(root.authority)); + this.starting.set(root.authority, pending); + } + return pending; + } + + private volume(root: vscode.Uri): Promise { + const id = root.toString(); + let pending = this.volumes.get(id); + if (!pending) { + pending = this.load(root).catch((error) => { + this.volumes.delete(id); + throw error; + }); + this.volumes.set(id, pending); + } + return pending; + } + + private async load(root: vscode.Uri): Promise { + const stored = this.context.globalState.get(sourceKey + root.authority); + if (!stored) { + throw vscode.FileSystemError.Unavailable( + 'Reopen the original .webrproj file to locate this project.', + ); + } + const source = vscode.Uri.parse(stored, true); + this.checkSource(source); + if ( + (await webRProjectRoot(source, await this.host.scope?.())).toString() !== + root.toString() + ) { + throw vscode.FileSystemError.FileNotFound(root); + } + const volume = await this.host.open(source, root); + const listener = volume.onDidChange?.((items) => { + this.changes.fire( + items.map(({ type, path }) => ({ + type, + uri: path ? vscode.Uri.joinPath(root, path) : root, + })), + ); + }); + return { source, volume, listener }; + } + + private async target(uri: vscode.Uri, mutation = false) { + const { root, path } = split(uri); + if (mutation && (!path || !vscode.workspace.isTrusted)) { + throw vscode.FileSystemError.NoPermissions(uri); + } + return { volume: (await this.volume(root)).volume, path }; + } + + watch(): vscode.Disposable { + return new vscode.Disposable(() => {}); + } + async stat(uri: vscode.Uri) { + const { volume, path } = await this.target(uri); + return volume.stat(path); + } + async readDirectory(uri: vscode.Uri) { + const { volume, path } = await this.target(uri); + return volume.readDirectory(path); + } + async readFile(uri: vscode.Uri) { + const { volume, path } = await this.target(uri); + const bytes = await volume.readFile(path); + await this.revisions.read(uri, bytes, await projectDigest(bytes)); + return bytes; + } + private changed(uri: vscode.Uri, type: vscode.FileChangeType): void { + this.changes.fire([ + { uri, type }, + { uri: vscode.Uri.joinPath(uri, '..'), type: vscode.FileChangeType.Changed }, + ]); + } + async writeFile( + uri: vscode.Uri, + bytes: Uint8Array, + options: { create: boolean; overwrite: boolean }, + ) { + const { volume, path } = await this.target(uri, true); + const expected = this.revisions.expected(uri); + await volume.writeFile(path, bytes, { ...options, expected }); + await this.revisions.wrote(uri, await projectDigest(bytes)); + this.changed( + uri, + options.create && !options.overwrite + ? vscode.FileChangeType.Created + : vscode.FileChangeType.Changed, + ); + } + async createDirectory(uri: vscode.Uri) { + const { volume, path } = await this.target(uri, true); + await volume.createDirectory(path); + this.changed(uri, vscode.FileChangeType.Created); + } + async delete(uri: vscode.Uri, options: { recursive: boolean }) { + const { volume, path } = await this.target(uri, true); + await volume.delete(path, options); + await this.revisions.forget(uri); + this.changed(uri, vscode.FileChangeType.Deleted); + } + async rename(from: vscode.Uri, to: vscode.Uri, options: { overwrite: boolean }) { + const { root, path } = split(to); + if (!path || root.toString() !== split(from).root.toString()) { + throw vscode.FileSystemError.NoPermissions(to); + } + const source = await this.target(from, true); + await source.volume.rename(source.path, path, options); + await this.revisions.forget(from); + this.changed(from, vscode.FileChangeType.Deleted); + this.changed(to, vscode.FileChangeType.Created); + } + dispose(): void { + this.closed = true; + for (const item of this.subscriptions) { + item.dispose(); + } + for (const pending of this.volumes.values()) { + void pending.then( + ({ volume, listener }) => { + listener?.dispose(); + volume.dispose?.(); + }, + () => {}, + ); + } + this.volumes.clear(); + this.revisions.dispose(); + this.changes.dispose(); + } +} + +export function registerWebRProjects( + context: vscode.ExtensionContext, + host: WebRProjectHost, +): vscode.Disposable { + return new ProjectWorkspace(context, host); +} diff --git a/src/webr/sessionFiles.ts b/src/webr/sessionFiles.ts index b224c272e..ce35eadc3 100644 --- a/src/webr/sessionFiles.ts +++ b/src/webr/sessionFiles.ts @@ -1,4 +1,5 @@ import * as vscode from 'vscode'; +import { WebRFileRevisions } from './fileRevisions'; import type { WebRFileAccess, WebRFileStat } from './filesystem'; export const WEBR_FILE_SCHEME = 'vscode-r-webr'; @@ -113,14 +114,7 @@ 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 revisions: WebRFileRevisions; private readonly observed = new Map(); private readonly watched = new Map(); private readonly queued = new Map(); @@ -128,111 +122,16 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo /** 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(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); - } - } - } + constructor(workspaceState?: vscode.Memento) { + this.revisions = new WebRFileRevisions( + workspaceState, + baselineKey, + (uri) => !!sessionFileOwner(uri), + ); this.registration = vscode.workspace.registerFileSystemProvider(WEBR_FILE_SCHEME, this, { isCaseSensitive: true, }); - 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 { @@ -268,6 +167,7 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo private async access( uri: vscode.Uri, action: (fs: WebRFileAccess, path: string) => Promise, + destination?: string, ): Promise { const owner = sessionFileOwner(uri); if (!owner) { @@ -277,6 +177,16 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo await this.waitForReconnect?.(owner.id, owner.generation); } const session = this.session(owner); + if ( + session.projectUri && + [owner.path, destination].some( + (path) => path === '/project' || path?.startsWith('/project/'), + ) + ) { + throw vscode.FileSystemError.NoPermissions( + 'Open this file through the owning project workspace.', + ); + } try { return await action(await session.files(), owner.path); } catch (error) { @@ -306,22 +216,7 @@ 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(); - 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 }); - } - } - } - } + await this.revisions.read(uri, result.bytes, result.version); this.observed.set(id, result.version); return result.bytes; } @@ -332,21 +227,12 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo options: { create: boolean; overwrite: boolean }, ): Promise { const id = uri.toString(); - 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 before = this.revisions.expected(uri); 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.pendingReads.set(id, version); - this.recovered.delete(id); - await this.remember(id, version); + await this.revisions.wrote(uri, version); this.observed.set(id, version); this.change(uri, existed ? vscode.FileChangeType.Changed : vscode.FileChangeType.Created); } @@ -358,9 +244,7 @@ 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.pendingReads.delete(uri.toString()); - this.recovered.delete(uri.toString()); - await this.remember(uri.toString(), undefined); + await this.revisions.forget(uri); this.observed.delete(uri.toString()); this.change(uri, vscode.FileChangeType.Deleted); } @@ -373,10 +257,8 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo 'Rename is limited to one webR session generation.', ); } - await this.access(from, (fs, path) => fs.rename(path, dest.path, options)); - this.pendingReads.delete(from.toString()); - this.recovered.delete(from.toString()); - await this.remember(from.toString(), undefined); + await this.access(from, (fs, path) => fs.rename(path, dest.path, options), dest.path); + await this.revisions.forget(from); this.observed.delete(from.toString()); this.change(from, vscode.FileChangeType.Deleted); this.change(to, vscode.FileChangeType.Created); @@ -614,15 +496,11 @@ export class WebRSessionFiles implements vscode.FileSystemProvider, vscode.Dispo dispose(): void { this.registration.dispose(); - this.closeListener.dispose(); + this.revisions.dispose(); this.changed.dispose(); this.sessions.clear(); this.watched.clear(); this.queued.clear(); - this.pendingReads.clear(); - this.pendingReloads.clear(); - this.recovered.clear(); - this.versions.clear(); this.observed.clear(); } } diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index 44ed7671b..b06673e6d 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -21,6 +21,10 @@ Choose **webR** to run R in WebAssembly with no native R or arf installation. Re 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. +Use **R: New webR Project…** to keep scripts, data and results together in one +`.webrproj` file. Opening the file starts an Explorer workspace and a project +Interactive session whose working directory is `/project`. [Portable webR projects](./webr.md#portable-webr-projects) + Choose **arf** to use an installed R and its project libraries. On the R host, install: diff --git a/website/docs/features/webr.md b/website/docs/features/webr.md index 0d0b95779..e3566f313 100644 --- a/website/docs/features/webr.md +++ b/website/docs/features/webr.md @@ -27,6 +27,43 @@ installed on that server. ## Files and session lifetime +### Portable webR projects + +Use **R: New webR Project…** to create a `.webrproj` file. To reopen one, use +**File → Open File…** or **R: Open webR Project…**. VS Code opens the project as +an Explorer workspace and starts its webR Interactive session once the workspace +is trusted. With Workspace Trust enabled, opening a bundle from outside a trusted +workspace asks whether you trust its authors before its workspace settings take +effect. Reopening on the same R host can reconnect to the existing session. +If VS Code first displays a binary editor, choose **Reopen Editor With… → webR Project**. + +Create `fit.R` in Explorer, save it, then run `source("fit.R")` in Interactive. +The R working directory is `/project`. For example, +`write.csv(mtcars, "cars.csv", row.names = FALSE)` adds `cars.csv` to the +project. Editor saves and R file changes from completed cells go back into the +bundle. On desktop the session agent can finish a cell and save its files after +VS Code closes. In the browser, wait for the cell to finish before closing the tab. + +To move a project, copy the saved `.webrproj` file. Its version-one ZIP format +has a `manifest.json` containing `{"format":1}` and a `files/` directory with +the project contents. To carry an R object with the project, save it explicitly, +for example with `saveRDS(model, "model.rds")`, then load it with `readRDS()` in +the next session. The R heap, worker-local package library, and files under +`/tmp` or `/home/web_user` belong to the running session. + +On desktop and Remote SSH, save the bundle on the R host. In browser-only VS Code, +choose a backing filesystem that the browser can reopen and write. A read-only +repository can supply a project to inspect. Saving requires a writable copy and +a browser with Web Locks. If another program replaces the bundle, vscode-R reports +the conflict and preserves the other version. On desktop the error identifies +the working directory where you can recover changes. In the browser, export the +R copy or use **Save As…** for an unsaved editor before reloading the window. + +Projects support ordinary files and directories with portable names, up to +10,000 entries, 64 MiB per file, and 128 MiB of uncompressed file data. + +### Session files + - **Desktop and Remote.** The session's initial `/project` directory mounts the selected host project. R can source a helper or write a CSV there directly. **Open webR Session File…** opens project files in the host workspace. Worker-local files such as those in `/tmp` use the owning session and generation. Closing and reconnecting to a supervised session retains its objects and files. Stop or restart ends that runtime. - **Browser.** The session starts in `/workspace`. **Import Files into webR…** copies selected workspace files into that directory. **Export File from webR…** copies a result to a writable workspace destination. Use **Open webR Session File…** in Session Actions or the session tree to edit a live worker file. Its source commands target the owning notebook. Closing the notebook, reloading the page, or restarting ends access to that generation. - **History.** Desktop sessions have a durable journal and asset store, session naming and binding, queued-cell cancellation, history search, plot browsing, export and cleanup commands. Browser notebooks support New, Open, Manage, Interrupt, Restart, Stop and Stop All. Save an `.rnb` notebook to retain cells and outputs across reloads. Reopening creates a fresh R environment. From 49dfbd88e6345439499599a960ab0715711dd033 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 19:25:43 +0800 Subject: [PATCH 2/4] Keep webR hovers independent of the host R help index --- src/completions.ts | 13 ++++++++ src/helpViewer/index.ts | 19 +++++++----- src/test/suite/completions.test.ts | 50 ++++++++++++++++++++++++++++++ src/test/suite/helpPanel.test.ts | 30 +++++++++++++++++- 4 files changed, 103 insertions(+), 9 deletions(-) diff --git a/src/completions.ts b/src/completions.ts index d093a57cb..d0ff27d36 100644 --- a/src/completions.ts +++ b/src/completions.ts @@ -8,6 +8,8 @@ import { globalRHelp } from './extension'; import { config } from './util'; import { getChunks } from './rmarkdown'; import { CompletionItemKind } from 'vscode-languageclient'; +import { WEBR_FILE_SCHEME } from './webr/sessionFiles'; +import { WEBR_PROJECT_SCHEME } from './webr/projectWorkspace'; // Get with names(roxygen2:::default_tags()) const roxygenTagCompletionItems = [ @@ -230,6 +232,17 @@ export class HelpLinkHoverProvider implements vscode.HoverProvider { ) { return null; } + // The webR language worker supplies help from its own package library. + // Looking up a native Help-panel link here also starts a host R process. + const scheme = document.uri.scheme; + if ( + scheme === WEBR_PROJECT_SCHEME || + scheme === WEBR_FILE_SCHEME || + ((scheme === 'vscode-interactive-input' || scheme === 'vscode-notebook-cell') && + session.boundSessionForDocument(document.uri)?.interactiveProvider === 'webr') + ) { + return null; + } if (document.languageId === 'rmd') { const chunks = getChunks(document); diff --git a/src/helpViewer/index.ts b/src/helpViewer/index.ts index 33e2ffa34..3d1a6c3e0 100644 --- a/src/helpViewer/index.ts +++ b/src/helpViewer/index.ts @@ -44,17 +44,20 @@ export async function initializeHelp( // set context value to indicate that the help related tree-view should be shown void vscode.commands.executeCommand('setContext', 'r.helpViewer.show', true); - // get the "vanilla" R path from config - const rPath = await getRpath(false, undefined, false); + // A native child can only use a directory on its extension host. In a + // pure virtual workspace, leave its cwd unset just as in an empty window. + const folder = vscode.workspace.workspaceFolders?.find( + ({ uri }) => + uri.scheme === 'file' || + (uri.scheme === 'vscode-remote' && + context.extensionUri.scheme === uri.scheme && + uri.authority === context.extensionUri.authority), + ); + const rPath = await getRpath(false, folder?.uri, false); if (!rPath) { return undefined; } - // get the current working directory from vscode - const cwd = vscode.workspace.workspaceFolders?.length - ? vscode.workspace.workspaceFolders[0].uri.fsPath - : undefined; - // get the Memento for storing cached help files (or create a dummy for this session) const cacheConfig = config().get<'None' | 'Workspace' | 'Global'>('helpPanel.cacheIndexFiles'); const persistentState = @@ -72,7 +75,7 @@ export async function initializeHelp( indexTemplatePath: context.asAbsolutePath('./dist/webviews/help/00Index.ejs'), rdToHtmlScriptFile: context.asAbsolutePath('./R/help/rdToHtml.R'), rPath: rPath, - cwd: cwd, + cwd: folder?.uri.fsPath, persistentState: persistentState, }; diff --git a/src/test/suite/completions.test.ts b/src/test/suite/completions.test.ts index 7017334f6..c54fde457 100644 --- a/src/test/suite/completions.test.ts +++ b/src/test/suite/completions.test.ts @@ -24,6 +24,56 @@ suite('Help link hover', () => { }); teardown(() => sandbox.restore()); + test('webR project sources, session files and bound notebook inputs never request native help aliases', async () => { + const provider = new HelpLinkHoverProvider(); + const source = await vscode.workspace.openTextDocument({ + language: 'r', + content: + 'm <- lm(mpg ~ ., data = mtcars)\nsummary(m)\npar(mfrow = c(2, 2), mar = c(3, 3, 2, 2))\nplot(m)', + }); + const binding = sandbox.stub(session, 'boundSessionForDocument'); + for (const scheme of [ + 'vscode-r-project', + 'vscode-r-webr', + 'vscode-interactive-input', + 'vscode-notebook-cell', + ]) { + const uri = vscode.Uri.from({ scheme, path: '/analysis.R' }); + if (scheme === 'vscode-interactive-input' || scheme === 'vscode-notebook-cell') { + binding.withArgs(uri).returns({ interactiveProvider: 'webr' } as session.Session); + } + const doc = Object.create(source, { uri: { value: uri } }) as vscode.TextDocument; + for (const [line, col] of [ + [0, 6], + [1, 2], + [2, 1], + [3, 2], + ]) { + assert.strictEqual( + await provider.provideHover(doc, new vscode.Position(line, col)), + null, + ); + } + } + sinon.assert.notCalled(aliases); + aliases.resolves([{ package: 'stats', name: 'lm', alias: 'lm' }]); + const nativeInput = vscode.Uri.from({ + scheme: 'vscode-interactive-input', + path: '/native.R', + }); + binding.withArgs(nativeInput).returns({ interactiveProvider: 'arf' } as session.Session); + const input = Object.create(source, { uri: { value: nativeInput } }) as vscode.TextDocument; + for (const doc of [source, input]) { + const hover = await provider.provideHover(doc, new vscode.Position(0, 6)); + assert.ok(hover); + assert.match( + (hover.contents[0] as vscode.MarkdownString).value, + /stats::lm.*command:r\.helpPanel\.openForPath/, + ); + } + assert.deepEqual(aliases.args, [['lm'], ['lm']]); + }); + test('punctuation does not look up the entire document as a help alias', async () => { const document = await vscode.workspace.openTextDocument({ language: 'r', diff --git a/src/test/suite/helpPanel.test.ts b/src/test/suite/helpPanel.test.ts index 6b50ef79f..2fea57b73 100644 --- a/src/test/suite/helpPanel.test.ts +++ b/src/test/suite/helpPanel.test.ts @@ -3,11 +3,39 @@ import * as sinon from 'sinon'; import * as vscode from 'vscode'; import * as path from 'path'; import { HelpPanel } from '../../helpViewer/panel'; -import type { HelpFile, RHelp } from '../../helpViewer'; +import { initializeHelp, type HelpFile, type RHelp } from '../../helpViewer'; import * as util from '../../util'; import { trackModuleTimers, type ModuleTimerTracker } from '../common/fakeTimers'; import { mockExtensionContext } from '../common/mockvscode'; +suite('Native Help runtime', () => { + test('selects the host workspace for native Help even when a virtual project is first', async () => { + const sandbox = sinon.createSandbox(); + try { + const native = vscode.Uri.file(path.resolve('native-project')); + const virtual = vscode.Uri.from({ + scheme: 'vscode-r-project', + authority: 'analysis.webrproj', + path: '/project-id/Analysis', + }); + const folders = sandbox.stub(vscode.workspace, 'workspaceFolders'); + const resolveR = sandbox.stub(util, 'getRpath').resolves(undefined); + sandbox.stub(vscode.commands, 'executeCommand').resolves(); + const context = { extensionUri: vscode.Uri.file(__dirname) } as vscode.ExtensionContext; + const api = {} as Parameters[1]; + folders.get(() => [{ uri: virtual }, { uri: native }]); + await initializeHelp(context, api); + sinon.assert.calledOnceWithExactly(resolveR, false, native, false); + resolveR.resetHistory(); + folders.get(() => [{ uri: virtual }]); + await initializeHelp(context, api); + sinon.assert.calledOnceWithExactly(resolveR, false, undefined, false); + } finally { + sandbox.restore(); + } + }); +}); + suite('Help panel navigation', () => { let sandbox: sinon.SinonSandbox; let panel: vscode.WebviewPanel; From 1b3134356c28e9598950770e92659ced9748d7ca Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 19:25:43 +0800 Subject: [PATCH 3/4] Name webR workspaces and default their terminals to the project filesystem --- package.json | 16 + src/interactive/manager.ts | 21 +- src/interactive/projectHost.ts | 3 +- src/languageService.ts | 8 +- src/test/suite/webRProjectTerminal.test.ts | 194 ++++++ src/test/suite/webRProjectWorkspace.test.ts | 112 +++- src/test/web/webRProject.cjs | 16 +- src/web/extension.ts | 1 + src/web/interactive.ts | 21 +- src/webr/projectTerminal.ts | 627 ++++++++++++++++++++ src/webr/projectWorkspace.ts | 240 ++++++-- website/docs/features/webr.md | 18 + 12 files changed, 1206 insertions(+), 71 deletions(-) create mode 100644 src/test/suite/webRProjectTerminal.test.ts create mode 100644 src/webr/projectTerminal.ts diff --git a/package.json b/package.json index 228a36430..0093c0faa 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,11 @@ { "title": "R Terminal", "id": "r.terminal-profile" + }, + { + "title": "webR Project Terminal", + "id": "r.webr-project-terminal", + "icon": "terminal" } ] }, @@ -921,6 +926,12 @@ "title": "Open webR Project…", "category": "R" }, + { + "command": "r.webR.projectTerminal", + "title": "Open webR Project Terminal", + "category": "R", + "enablement": "r.hasWebRProject" + }, { "command": "r.interactive.open", "title": "Open Interactive Session", @@ -1100,6 +1111,11 @@ } ], "keybindings": [ + { + "command": "r.webR.projectTerminal", + "key": "ctrl+shift+`", + "when": "isWeb && !terminalProcessSupported && virtualWorkspace == vscode-r-project && workspaceFolderCount == 1" + }, { "command": "r.runSelection", "key": "Ctrl+enter", diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 291156a18..bf3576d95 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1,5 +1,5 @@ import { DesktopProjectStorage, withProjectLock } from './projectStorage'; -import { WEBR_PROJECT_SCHEME } from '../webr/projectWorkspace'; +import { WEBR_PROJECT_SCHEME, webRProjectKey } from '../webr/projectWorkspace'; import { DesktopWebRPackageSource } from './webRPackageStore'; import { AgentWebRFileAccess } from './webRFiles'; import { WEBR_FILE_SCHEME, sessionFileOwner, WebRSessionFiles } from '../webr/sessionFiles'; @@ -1255,7 +1255,8 @@ export class InteractiveManager } private projectView(uri: vscode.Uri): InteractiveView | undefined { - const project = uri.scheme === WEBR_PROJECT_SCHEME && this.projects.get(uri.authority); + const project = + uri.scheme === WEBR_PROJECT_SCHEME && this.projects.get(webRProjectKey(uri)); return project ? [...this.views.values()].find( (view) => @@ -1266,8 +1267,16 @@ export class InteractiveManager : undefined; } + projectTerminalSession(root: vscode.Uri): { id: string; generation: string } | undefined { + const view = this.projectView(root); + if (view?.client.connected) { + const { id, generation } = view.client.manifest; + return { id, generation }; + } + } + async openProject(storage: DesktopProjectStorage, root: vscode.Uri): Promise { - this.projects.set(root.authority, { root, storage }); + this.projects.set(root.toString(), { root, storage }); await withProjectLock(storage.bundle, 'open', async () => { this.refresh(); const [existing] = await runningSessions( @@ -1298,7 +1307,7 @@ export class InteractiveManager const adopt = adoptable?.session; const folder = this.sessionFolder(resource); if (!adopt && !project && folder?.scheme === WEBR_PROJECT_SCHEME) { - const owner = this.projects.get(folder.authority); + const owner = this.projects.get(webRProjectKey(folder)); if (!owner) { throw new Error('The webR project is opening. Retry when it is ready.'); } @@ -1551,7 +1560,7 @@ export class InteractiveManager const folder = this.sessionFolder(resource); const directory = defaultSessionDirectory( folder?.scheme === WEBR_PROJECT_SCHEME - ? this.projects.get(folder.authority)?.storage.directory + ? this.projects.get(webRProjectKey(folder))?.storage.directory : folder?.fsPath, ); const arfCommand = this.arfCommand(folder ?? resource); @@ -2020,7 +2029,7 @@ export class InteractiveManager (owner?.id === id && owner.generation === generation) || (bundleRoot && doc.uri.scheme === WEBR_PROJECT_SCHEME && - doc.uri.authority === bundleRoot.authority) + webRProjectKey(doc.uri) === bundleRoot.toString()) ) { session.bindSessionDocument(doc.uri, view.target); } diff --git a/src/interactive/projectHost.ts b/src/interactive/projectHost.ts index 3fbb20c62..c9494b1de 100644 --- a/src/interactive/projectHost.ts +++ b/src/interactive/projectHost.ts @@ -302,7 +302,7 @@ export function acceptsDesktopProjectSource( export function createDesktopProjectHost( context: vscode.ExtensionContext, - manager: Pick, + manager: Pick, ): WebRProjectHost { const remote = vscode.env.remoteName; return { @@ -322,5 +322,6 @@ export function createDesktopProjectHost( async start(_source, root, volume) { await manager.openProject((volume as DesktopProjectVolume).storage, root); }, + terminalSession: (root) => manager.projectTerminalSession(root), }; } diff --git a/src/languageService.ts b/src/languageService.ts index b4540433c..99b1b852e 100644 --- a/src/languageService.ts +++ b/src/languageService.ts @@ -42,7 +42,7 @@ import { CancellableLanguageClient } from './languageServerClient'; import { withRpcCancellation } from './nativeRpc'; import { prepareNodeWebR } from './webr/nodeRuntime'; import { resolveExecutable } from './interactive/executable'; -import { WEBR_PROJECT_SCHEME } from './webr/projectWorkspace'; +import { WEBR_PROJECT_SCHEME, webRProjectKey } from './webr/projectWorkspace'; import { WEBR_FILE_SCHEME, sessionFileOwner } from './webr/sessionFiles'; import { Message } from 'vscode-jsonrpc'; import { cachedWebRAssets } from './webr/assetCache'; @@ -499,8 +499,8 @@ export class LanguageService implements Disposable { const owner = sessionFileOwner(documentUri); const matches = documentUri.scheme === WEBR_PROJECT_SCHEME - ? documentUri.authority === - workspaceFolder?.uri.authority + ? webRProjectKey(documentUri) === + workspaceFolder?.uri.toString() : owner && `${owner.id}:${owner.generation}` === target.sessionId; @@ -619,7 +619,7 @@ export class LanguageService implements Disposable { case 'untitled': return uri.scheme; case WEBR_PROJECT_SCHEME: - return `${WEBR_PROJECT_SCHEME}://${uri.authority}`; + return webRProjectKey(uri) || uri.toString(); case WEBR_FILE_SCHEME: { const owner = sessionFileOwner(uri); return owner diff --git a/src/test/suite/webRProjectTerminal.test.ts b/src/test/suite/webRProjectTerminal.test.ts new file mode 100644 index 000000000..d5e797173 --- /dev/null +++ b/src/test/suite/webRProjectTerminal.test.ts @@ -0,0 +1,194 @@ +import * as assert from 'node:assert/strict'; +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import * as sinon from 'sinon'; +import * as vscode from 'vscode'; +import { + registerWebRProjectTerminal, + WEBR_PROJECT_TERMINAL_COMMAND, + WEBR_PROJECT_TERMINAL_PROFILE, + type WebRProjectTerminalTarget, +} from '../../webr/projectTerminal'; + +suite('webR project terminal', () => { + const sandbox = sinon.createSandbox(); + let temp: string; + let project: string; + let worker: string; + let resolve: sinon.SinonStub<[], Promise>; + let profile: vscode.TerminalProfileProvider; + let open: () => Promise; + let registration: vscode.Disposable; + let pty: vscode.Pseudoterminal | undefined; + let cancellation: vscode.CancellationTokenSource; + + setup(async () => { + temp = await mkdtemp(path.join(os.tmpdir(), 'webR terminal ')); + project = path.join(temp, 'saved project'); + worker = path.join(temp, 'worker'); + await Promise.all([ + mkdir(project), + mkdir(path.join(worker, 'tmp'), { recursive: true }), + mkdir(path.join(worker, 'home', 'web_user'), { recursive: true }), + ]); + const target: WebRProjectTerminalTarget = { + name: 'Analysis.webrproj', + resource: (input) => { + assert.ok(input.startsWith('/') && !input.split('/').includes('..')); + if (input === '/project' || input.startsWith('/project/')) { + return vscode.Uri.file(path.join(project, input.slice('/project'.length))); + } + return vscode.Uri.file(path.join(worker, input)); + }, + }; + resolve = sandbox + .stub<[], Promise>() + .resolves(target); + const disposable = new vscode.Disposable(() => {}); + const registerProfile = sandbox + .stub(vscode.window, 'registerTerminalProfileProvider') + .returns(disposable); + const registerCommand = sandbox + .stub(vscode.commands, 'registerCommand') + .returns(disposable); + registration = registerWebRProjectTerminal(resolve); + assert.equal(registerProfile.firstCall.args[0], WEBR_PROJECT_TERMINAL_PROFILE); + profile = registerProfile.firstCall.args[1]; + assert.equal(registerCommand.firstCall.args[0], WEBR_PROJECT_TERMINAL_COMMAND); + open = registerCommand.firstCall.args[1]; + cancellation = new vscode.CancellationTokenSource(); + }); + + teardown(async () => { + pty?.close(); + pty = undefined; + cancellation.dispose(); + registration.dispose(); + sandbox.restore(); + await rm(temp, { recursive: true, force: true }); + }); + + async function terminal() { + const selected = await profile.provideTerminalProfile(cancellation.token); + assert.ok(selected && 'pty' in selected.options); + assert.equal(selected.options.name, 'webR: Analysis.webrproj'); + assert.equal(selected.options.isTransient, true); + pty = selected.options.pty; + pty.open(undefined); + const current = pty; + return (line: string) => + new Promise((done, reject) => { + let entered = false, + text = ''; + const timer = setTimeout(() => { + listener.dispose(); + reject(new Error('No terminal prompt after ' + line)); + }, 5000); + const listener = current.onDidWrite((event) => { + if (!entered) { + if (event === '\r\n') { + entered = true; + } + } else if (event.startsWith('webR:') && event.endsWith('$ ')) { + clearTimeout(timer); + listener.dispose(); + done(text); + } else { + text += event; + } + }); + current.handleInput!(line + '\r'); + }); + } + test('routes quoted paths and durable changes to the project and absolute paths to the worker', async () => { + const send = await terminal(); + assert.equal(await send('pwd'), '/project\r\n'); + assert.equal(await send('mkdir -p "tool scripts/nested"'), ''); + assert.equal(await send("cd 'tool scripts'"), ''); + assert.equal(await send('pwd'), '/project/tool scripts\r\n'); + assert.equal(await send("echo 'R & webR' > nested/測試.R"), ''); + assert.equal(await send('echo second >> nested/測試.R'), ''); + assert.equal(await send('cat nested/測試.R'), 'R & webR\r\nsecond\r\n'); + assert.equal(await send('cp nested/測試.R /tmp/copy.R'), ''); + assert.equal( + await readFile(path.join(worker, 'tmp', 'copy.R'), 'utf8'), + 'R & webR\nsecond\n', + ); + assert.equal(await send('mv nested/測試.R moved.R'), ''); + assert.equal(await send('rmdir nested'), ''); + assert.equal(await send('ls'), 'moved.R\r\n'); + assert.equal(await send('rm moved.R'), ''); + assert.deepEqual( + await vscode.workspace.fs.readDirectory( + vscode.Uri.file(path.join(project, 'tool scripts')), + ), + [], + ); + assert.equal(await send('cd /'), ''); + assert.equal(await send('ls'), 'home/\r\nproject/\r\ntmp/\r\n'); + assert.equal(await send('cd'), ''); + assert.equal(await send('pwd'), '/home/web_user\r\n'); + sinon.assert.calledOnce(resolve); + }); + + test('rejects unsupported shell syntax and displays control bytes as text', async () => { + const send = await terminal(); + assert.match(await send('help'), /webR filesystem commands/); + assert.match(await send('echo unsafe; touch marker'), /command chaining/); + assert.match(await send('bash'), /Unknown webR filesystem command: bash/); + assert.match(await send('echo "unterminated'), /Unclosed quote/); + assert.match(await send('echo 1 > file extra'), /output|followed by/); + assert.equal(await send('ls'), ''); + await writeFile(path.join(project, 'control.txt'), 'before\x1b]0;fake title\x07after\n'); + assert.equal(await send('cat control.txt'), 'before\\x1b]0;fake title\\x07after\r\n'); + assert.equal(await send('echo "two words" > "a b"'), ''); + assert.equal(await send('cat a\\ b'), 'two words\r\n'); + await send('echo old'); + assert.equal(await send('\x1b[A'), 'old\r\n'); + }); + + test('cross-mount copies preserve bytes and failed copies and moves retain both filesystems', async () => { + const send = await terminal(); + const payload = Buffer.from([0, 127, 128, 255]); + await writeFile(path.join(worker, 'tmp', 'raw'), payload); + assert.equal(await send('cp /tmp/raw .'), ''); + assert.deepEqual(await readFile(path.join(project, 'raw')), payload); + assert.match(await send('mv raw /tmp/moved'), /between mounted filesystems/); + assert.deepEqual(await readFile(path.join(project, 'raw')), payload); + await assert.rejects(readFile(path.join(worker, 'tmp', 'moved')), { code: 'ENOENT' }); + + await mkdir(path.join(project, 'dst', 'raw'), { recursive: true }); + await writeFile(path.join(project, 'dst', 'raw', 'keep'), 'preserve'); + assert.match(await send('cp raw dst'), /Cannot replace/); + assert.match(await send('mv raw dst'), /Cannot replace/); + await mkdir(path.join(project, 'src', 'raw'), { recursive: true }); + assert.match(await send('mv src/raw dst'), /not empty/); + assert.equal(await readFile(path.join(project, 'dst', 'raw', 'keep'), 'utf8'), 'preserve'); + assert.equal(await send('cd /tmp'), ''); + assert.match(await send('rm -r /project'), /filesystem root/); + assert.match(await send('mv /project /tmp/saved'), /filesystem root/); + }); + + test('requires existing parents, validates redirection before mutations, and accepts separate ls flags', async () => { + const send = await terminal(); + assert.notEqual(await send('touch missing/a'), ''); + assert.notEqual(await send('echo text > missing/b'), ''); + assert.equal(await send('ls'), ''); + assert.equal(await send('mkdir target'), ''); + assert.match(await send('touch should-not-be-created > target'), /directory/); + assert.equal(await send('ls'), 'target/\r\n'); + assert.equal(await send('echo hello > .hidden'), ''); + assert.match(await send('ls -l -a'), /\b6 \.hidden\r\n/); + }); + + test('a cancelled profile and a missing webR workspace never launch a native shell', async () => { + const create = sandbox.stub(vscode.window, 'createTerminal'); + cancellation.cancel(); + assert.equal(await profile.provideTerminalProfile(cancellation.token), undefined); + sinon.assert.notCalled(resolve); + resolve.resolves(undefined); + await assert.rejects(open(), /Open a .webrproj/); + sinon.assert.notCalled(create); + }); +}); diff --git a/src/test/suite/webRProjectWorkspace.test.ts b/src/test/suite/webRProjectWorkspace.test.ts index 9beb22bde..811dea14c 100644 --- a/src/test/suite/webRProjectWorkspace.test.ts +++ b/src/test/suite/webRProjectWorkspace.test.ts @@ -7,6 +7,8 @@ import * as vscode from 'vscode'; import { decodeProject, encodeProject } from '../../webr/projectArchive'; import { registerWebRProjects, + webRProjectAddress, + webRProjectKey, webRProjectRoot, type WebRProjectVolume, } from '../../webr/projectWorkspace'; @@ -14,6 +16,7 @@ import { suite('webR project workspace opener', () => { const sandbox = sinon.createSandbox(); let directory: string; + let saved: Map; let registration: vscode.Disposable; let files: vscode.FileSystemProvider; let open: (file: vscode.Uri) => Promise; @@ -29,12 +32,16 @@ suite('webR project workspace opener', () => { trust = sandbox.stub(vscode.window, 'showWarningMessage'); trust.resolves('Trust Project and Open'); sandbox.stub(vscode.window, 'registerCustomEditorProvider').returns(disposable); + sandbox.stub(vscode.window, 'registerTerminalProfileProvider').returns(disposable); const fsRegistration = sandbox .stub(vscode.workspace, 'registerFileSystemProvider') .returns(disposable); const commands = sandbox.stub(vscode.commands, 'registerCommand').returns(disposable); - openFolder = sandbox.stub(vscode.commands, 'executeCommand').resolves(); - const saved = new Map(); + openFolder = sandbox + .stub(vscode.commands, 'executeCommand') + .resolves() + .withArgs('vscode.openFolder'); + saved = new Map(); const state = { get: (key: string) => saved.get(key), update: (key: string, v: unknown) => { @@ -47,11 +54,16 @@ suite('webR project workspace opener', () => { } as Partial); start = sandbox.stub().resolves(); registration = registerWebRProjects( - { globalState: state, workspaceState: state } as vscode.ExtensionContext, + { + globalState: state, + workspaceState: state, + globalStorageUri: vscode.Uri.file(path.join(directory, 'storage')), + } as vscode.ExtensionContext, { accepts: (uri) => uri.scheme === 'file', open: openVolume, start, + terminalSession: () => undefined, }, ); files = fsRegistration.firstCall.args[1]; @@ -72,9 +84,31 @@ suite('webR project workspace opener', () => { ); await open(source); const root = await webRProjectRoot(source); - sinon.assert.calledOnceWithExactly(openFolder, 'vscode.openFolder', root, { - forceReuseWindow: true, + sinon.assert.calledOnce(openFolder); + const [command, descriptor, options] = openFolder.firstCall.args as [ + string, + vscode.Uri, + unknown, + ]; + assert.equal(command, 'vscode.openFolder'); + assert.deepEqual(options, { forceReuseWindow: true }); + assert.ok(descriptor.fsPath.endsWith('.code-workspace')); + const layout = JSON.parse(await readFile(descriptor.fsPath, 'utf8')) as { + folders: { uri: string }[]; + settings: Record; + }; + assert.equal(layout.folders.length, 1); + assert.equal(vscode.Uri.parse(layout.folders[0].uri).toString(), root.toString()); + assert.equal(vscode.Uri.parse(layout.folders[0].uri).authority, 'Analysis #1.webrproj'); + assert.deepEqual(layout.settings, { + 'terminal.integrated.defaultProfile.linux': 'webR Project Terminal', + 'terminal.integrated.defaultProfile.osx': 'webR Project Terminal', + 'terminal.integrated.defaultProfile.windows': 'webR Project Terminal', }); + layout.settings['terminal.integrated.defaultProfile.osx'] = 'zsh'; + await writeFile(descriptor.fsPath, JSON.stringify(layout)); + await open(source); + assert.deepEqual(JSON.parse(await readFile(descriptor.fsPath, 'utf8')), layout); sinon.assert.notCalled(openVolume); assert.deepEqual(await files.readDirectory(root), [['fit.R', vscode.FileType.File]]); sinon.assert.calledOnce(openVolume); @@ -87,11 +121,71 @@ suite('webR project workspace opener', () => { Promise.resolve(files.readDirectory(root.with({ path: '/unrelated' }))), ); await assert.rejects(Promise.resolve(files.delete(root, { recursive: true }))); - assert.notEqual( - root.authority, - (await webRProjectRoot(source.with({ path: '/another/Analysis #1.webrproj' }))) - .authority, + assert.equal(root.authority, 'Analysis #1.webrproj'); + const other = await webRProjectRoot(source.with({ path: '/another/Analysis #1.webrproj' })); + assert.equal(other.authority, root.authority); + assert.notEqual(webRProjectKey(root), webRProjectKey(other)); + assert.equal( + webRProjectKey(vscode.Uri.joinPath(root, 'sub', 'fit.R')), + webRProjectKey(root), + ); + await assert.rejects(Promise.resolve(files.readDirectory(other)), /Reopen the original/); + }); + + test('existing workspaces and their children resolve using the original trusted source ID', async () => { + const source = vscode.Uri.file(path.join(directory, 'Results.webrproj')); + const named = await webRProjectRoot(source); + const { id } = webRProjectAddress(named)!; + const old = named.with({ authority: id, path: '/Results' }); + // These are the only locator and root values saved by the previous VSIX. + saved.set('r.webR.projectSource.v1.' + id, source.toString()); + await files.readDirectory(vscode.Uri.joinPath(old, 'sub')); + sinon.assert.calledOnce(openVolume); + assert.equal((openVolume.firstCall.args[0] as vscode.Uri).toString(), source.toString()); + assert.equal(webRProjectAddress(old)?.id, id); + assert.equal( + webRProjectAddress(vscode.Uri.joinPath(old, 'sub', 'fit.R'))?.path, + 'sub/fit.R', ); + await assert.rejects(Promise.resolve(files.readDirectory(old.with({ path: '/unknown' })))); + await assert.rejects( + Promise.resolve(files.readDirectory(named.with({ authority: 'other.webrproj' }))), + ); + }); + + test('reselecting an original-format root in a saved multi-root workspace retains the other folders', async () => { + const source = vscode.Uri.file(path.join(directory, 'Results.webrproj')); + await writeFile(source.fsPath, await encodeProject(new Map())); + const named = await webRProjectRoot(source); + const old = named.with({ authority: webRProjectAddress(named)!.id, path: '/Results' }); + sandbox.stub(vscode.workspace, 'workspaceFolders').get(() => [ + { uri: old, name: 'Results', index: 0 }, + { uri: vscode.Uri.file(directory), name: 'data', index: 1 }, + ]); + sandbox + .stub(vscode.workspace, 'workspaceFile') + .get(() => vscode.Uri.file(path.join(directory, 'data.code-workspace'))); + sandbox.stub(vscode.workspace, 'isTrusted').get(() => true); + await open(source); + sinon.assert.notCalled(openFolder); + sinon.assert.calledOnce(start); + assert.equal((start.firstCall.args[1] as vscode.Uri).toString(), old.toString()); + }); + + test('project labels keep readable filenames and isolate equal paths on separate R hosts', async () => { + const filename = 'Résumé @50% #1.WEBRPROJ'; + const source = vscode.Uri.from({ scheme: 'file', path: '/shared/' + filename }); + const a = await webRProjectRoot(source, 'host A'); + const b = await webRProjectRoot(source, 'host B'); + assert.equal(a.authority, filename); + assert.equal(b.authority, filename); + assert.notEqual(webRProjectAddress(a)?.id, webRProjectAddress(b)?.id); + const restored = vscode.Uri.parse(a.toString()); + assert.equal(webRProjectKey(restored), webRProjectKey(a)); + assert.equal(webRProjectAddress(restored)?.path, ''); + assert.equal(restored.path.split('/').at(-1), 'Résumé @50% #1'); + const special = await webRProjectRoot(source.with({ path: '/shared/r:$(bug)#1.webrproj' })); + assert.equal(webRProjectKey(vscode.Uri.parse(special.toString())), webRProjectKey(special)); }); test('reselecting a bundle locates an already-open workspace root in a fresh profile', async () => { diff --git a/src/test/web/webRProject.cjs b/src/test/web/webRProject.cjs index 79727af63..270117b30 100644 --- a/src/test/web/webRProject.cjs +++ b/src/test/web/webRProject.cjs @@ -46,9 +46,10 @@ async function addRoot(root, name) { // root this way by selecting its original .webrproj through the command. async function addProject(source) { const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(source.toString()))); - const authority = Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join(''); - const stem = source.path.split('/').at(-1).slice(0, -'.webrproj'.length); - const root = vscode.Uri.from({scheme: 'vscode-r-project', authority, path: '/' + stem}); + const id = Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join(''); + const filename = source.path.split('/').at(-1); + const stem = filename.slice(0, -'.webrproj'.length); + const root = vscode.Uri.from({scheme: 'vscode-r-project', authority: filename, path: '/' + id + '/' + stem}); await addRoot(root, stem); await command('r.webR.openProject', source); const notebook = vscode.window.activeNotebookEditor?.notebook; @@ -87,8 +88,13 @@ exports.run = async () => { await fs.createDirectory(folder); const index = vscode.workspace.workspaceFolders?.length ?? 0; await addRoot(folder, 'project-bundles'); - const first = vscode.Uri.joinPath(folder,'first-' + id + '.webrproj'); - const second = vscode.Uri.joinPath(folder,'second-' + id + '.webrproj'); + const copy = vscode.Uri.joinPath(folder, 'copy'); + await fs.createDirectory(copy); + // The status indicator shows the same filename for both roots; every file + // operation, execution request and language service must still use its own project. + const filename = 'Analysis #1.webrproj'; + const first = vscode.Uri.joinPath(folder, filename); + const second = vscode.Uri.joinPath(copy, filename); const recovery = first.with({path: first.path + '.txt'}); const original = Uint8Array.from(atob(fixture), char => char.charCodeAt(0)); const settings = vscode.workspace.getConfiguration('r'); diff --git a/src/web/extension.ts b/src/web/extension.ts index 11184547d..3925fe52a 100644 --- a/src/web/extension.ts +++ b/src/web/extension.ts @@ -32,6 +32,7 @@ export async function activate(context: vscode.ExtensionContext): Promise create: createBrowserProject, open: (source, root) => BrowserProject.open(source, root), start: (_source, _root, volume) => interactive.startProject(volume as BrowserProject), + terminalSession: (root) => interactive.projectTerminalSession(root), }), ); diff --git a/src/web/interactive.ts b/src/web/interactive.ts index 9d1f16777..f4f4711c8 100644 --- a/src/web/interactive.ts +++ b/src/web/interactive.ts @@ -5,7 +5,7 @@ import type { WebRPackageSource } from '../webr/packageContext'; import { exportFile, importFiles } from './files'; import { BrowserProject } from './project'; import { projectDirectory } from './projectMirror'; -import { WEBR_PROJECT_SCHEME } from '../webr/projectWorkspace'; +import { WEBR_PROJECT_SCHEME, webRProjectAddress, webRProjectKey } from '../webr/projectWorkspace'; import { WEBR_FILE_SCHEME, WebRSessionFiles, sessionFileOwner } from '../webr/sessionFiles'; const notebookType = 'r-interactive'; @@ -162,7 +162,7 @@ export class BrowserInteractive implements vscode.Disposable { private notebookLabel(doc: vscode.NotebookDocument): string { return ( - this.projectRoot(doc)?.path.slice(1) || + this.projectRoot(doc)?.path.split('/').pop() || doc.uri.path.split('/').pop() || doc.uri.toString() ); @@ -238,7 +238,7 @@ export class BrowserInteractive implements vscode.Disposable { if (uri.scheme !== WEBR_PROJECT_SCHEME) { return; } - const project = this.projects.get(uri.authority); + const project = this.projects.get(webRProjectKey(uri)); if ( project && (uri.path === project.root.path || uri.path.startsWith(project.root.path + '/')) @@ -268,6 +268,11 @@ export class BrowserInteractive implements vscode.Disposable { } } + projectTerminalSession(root: vscode.Uri): { id: string; generation: string } | undefined { + const doc = this.fileNotebook(root); + return doc && this.registrationsByNotebook.get(doc); + } + fileSelector(doc: vscode.NotebookDocument): string | undefined { const current = this.registrationsByNotebook.get(doc); return current ? `**/${current.generation}/**` : undefined; @@ -335,12 +340,12 @@ export class BrowserInteractive implements vscode.Disposable { } async startProject(project: BrowserProject): Promise { - this.projects.set(project.root.authority, project); + this.projects.set(project.root.toString(), project); project.onRelease = () => { - if (this.projects.get(project.root.authority) !== project) { + if (this.projects.get(project.root.toString()) !== project) { return; } - this.projects.delete(project.root.authority); + this.projects.delete(project.root.toString()); for (const [doc, owner] of this.notebookProjects) { if (owner === project) { this.forget(doc); @@ -362,7 +367,7 @@ export class BrowserInteractive implements vscode.Disposable { const open = (async () => { let doc = this.fileNotebook(project.root); if (!doc) { - const key = 'r.webR.projectNotebook.' + project.root.authority; + const key = 'r.webR.projectNotebook.' + webRProjectAddress(project.root)!.id; const saved = this.context.workspaceState.get(key); if (saved && openTabFor(saved)) { const restored = await vscode.workspace @@ -383,7 +388,7 @@ export class BrowserInteractive implements vscode.Disposable { data.metadata = { rWebRProject: project.root.toString() }; doc = await vscode.workspace.openNotebookDocument(notebookType, data); } - if (this.projects.get(project.root.authority) !== project) { + if (this.projects.get(project.root.toString()) !== project) { throw new Error('The webR project was closed.'); } this.notebookProjects.set(doc, project); diff --git a/src/webr/projectTerminal.ts b/src/webr/projectTerminal.ts new file mode 100644 index 000000000..1a86f1738 --- /dev/null +++ b/src/webr/projectTerminal.ts @@ -0,0 +1,627 @@ +import * as vscode from 'vscode'; + +export const WEBR_PROJECT_TERMINAL_PROFILE = 'r.webr-project-terminal'; +export const WEBR_PROJECT_TERMINAL_COMMAND = 'r.webR.projectTerminal'; + +export interface WebRProjectTerminalTarget { + name: string; + /** Resolve an absolute POSIX path within the captured project/session. */ + resource(path: string): vscode.Uri; +} + +const home = '/home/web_user'; +const help = + [ + 'webR filesystem commands', + ' pwd Print the current directory', + ' cd [DIR] Change directory (~ is your webR home)', + ' ls [-al] [PATH] List files (-a includes dotfiles, -l shows sizes)', + ' cat FILE... Print UTF-8 text', + ' echo [TEXT...] Print text', + ' touch FILE Create an empty file if it is missing', + ' mkdir [-p] DIR Create a directory', + ' cp SOURCE DEST Copy a file', + ' mv SOURCE DEST Rename or move within the same filesystem', + ' rm [-r] PATH Remove a file or directory tree', + ' rmdir DIR Remove an empty directory', + ' clear, help, exit', + 'Quote spaces with single or double quotes. Use > to write output or >> to append.', + 'Use R Interactive to evaluate R code. This terminal runs the commands listed above.', + ].join('\n') + '\n'; + +type Redirect = { path: string; append: boolean }; + +/** Parse the supported syntax without invoking a shell or evaluating the input as R code. */ +function parse(line: string): { args: string[]; redirect?: Redirect } { + const args: string[] = []; + let word = '', + started = false, + quote = '', + redirectAt = -1, + append = false; + const finish = () => { + if (started) { + args.push(word); + } + word = ''; + started = false; + }; + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (quote && ch === quote) { + quote = ''; + } else if (ch === '\\' && quote !== "'") { + if (i + 1 === line.length) { + throw new Error('Incomplete escape at end of command.'); + } + started = true; + if (quote && !['"', '\\'].includes(line[i + 1])) { + word += ch; + } else { + word += line[++i]; + } + } else if (quote) { + word += ch; + } else if (ch === '"' || ch === "'") { + started = true; + quote = ch; + } else if (/\s/.test(ch)) { + finish(); + } else if (ch === '>') { + finish(); + if (redirectAt !== -1) { + throw new Error('Use one output redirection at the end of the command.'); + } + redirectAt = args.length; + append = line[i + 1] === '>'; + if (append) { + i++; + } + } else if ('|;&<`'.includes(ch) || (ch === '$' && line[i + 1] === '(')) { + throw new Error( + 'Pipes, command chaining and shell substitution are unavailable. Type help for supported commands.', + ); + } else { + word += + !started && ch === '~' && (!line[i + 1] || /[\s/]/.test(line[i + 1])) ? home : ch; + started = true; + } + } + if (quote) { + throw new Error('Unclosed quote.'); + } + finish(); + if (redirectAt === -1) { + return { args }; + } + if (!redirectAt || args.length !== redirectAt + 1 || !args[redirectAt]) { + throw new Error('Expected a command followed by > FILE or >> FILE.'); + } + return { args: args.slice(0, redirectAt), redirect: { path: args[redirectAt], append } }; +} + +function absolute(cwd: string, name: string): string { + if (!name) { + throw new Error('Expected a path.'); + } + const parts = (name.startsWith('/') ? name : cwd + '/' + name).split('/'); + const result: string[] = []; + for (const part of parts) { + if (part === '..') { + result.pop(); + } else if (part && part !== '.') { + result.push(part); + } + } + return '/' + result.join('/'); +} + +async function stat(uri: vscode.Uri): Promise { + try { + return await vscode.workspace.fs.stat(uri); + } catch (error) { + if (error instanceof vscode.FileSystemError && error.code === 'FileNotFound') { + return; + } + throw error; + } +} + +/** Keep control bytes in R files and filenames from becoming terminal instructions. */ +function display(text: string): string { + return text + .replace(/\r\n?/g, '\n') + .replace( + // oxlint-disable-next-line no-control-regex + /[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, + (ch) => '\\x' + ch.charCodeAt(0).toString(16).padStart(2, '0'), + ) + .replace(/\n/g, '\r\n'); +} + +class ProjectTerminal implements vscode.Pseudoterminal { + private readonly written = new vscode.EventEmitter(); + private readonly ended = new vscode.EventEmitter(); + readonly onDidWrite = this.written.event; + readonly onDidClose = this.ended.event; + private cwd = '/project'; + private line: string[] = []; + private cursor = 0; + private readonly history: string[] = []; + private historyIndex = 0; + private draft = ''; + private closed = false; + private queue = Promise.resolve(); + + constructor(private readonly target: WebRProjectTerminalTarget) {} + + private get prompt(): string { + return 'webR:' + display(this.cwd) + '$ '; + } + + open(): void { + this.written.fire('webR project filesystem. Type help for commands.\r\n' + this.prompt); + } + close(): void { + this.closed = true; + this.written.dispose(); + this.ended.dispose(); + } + handleInput(input: string): void { + this.queue = this.queue + .then(() => this.input(input)) + .catch((error: unknown) => { + if (!this.closed) { + this.written.fire(display(String(error)) + '\r\n' + this.prompt); + } + }); + } + private redraw(): void { + const before = this.line.slice(0, this.cursor).join(''), + after = this.line.slice(this.cursor).join(''); + // Save/restore the cursor around the suffix so wide and combining characters + // do not require guessing their terminal cell width. + this.written.fire('\r\x1b[2K' + this.prompt + before + '\x1b7' + after + '\x1b8'); + } + private recall(direction: number): void { + if (this.historyIndex === this.history.length) { + this.draft = this.line.join(''); + } + this.historyIndex = Math.max( + 0, + Math.min(this.history.length, this.historyIndex + direction), + ); + this.line = Array.from(this.history[this.historyIndex] ?? this.draft); + this.cursor = this.line.length; + this.redraw(); + } + private async input(data: string): Promise { + // xterm sends arrows as CSI sequences and may send a complete pasted line + // in one event. Serialize admissions so pasted commands see the preceding cwd. + // oxlint-disable-next-line no-control-regex + const keys = data.match(/\x1b\[[0-9;]*[A-Za-z~]|\r\n|[\s\S]/gu) ?? []; + for (const key of keys) { + if (this.closed) { + return; + } + switch (key) { + case '\r': + case '\n': + case '\r\n': { + const command = this.line.join(''); + this.written.fire('\r\n'); + this.line = []; + this.cursor = 0; + this.draft = ''; + if (command.trim()) { + if (this.history.at(-1) !== command) { + this.history.push(command); + } + if (this.history.length > 100) { + this.history.shift(); + } + await this.execute(command); + } + this.historyIndex = this.history.length; + if (!this.closed) { + this.written.fire(this.prompt); + } + break; + } + case '\x03': + this.line = []; + this.cursor = 0; + this.historyIndex = this.history.length; + this.written.fire('^C\r\n' + this.prompt); + break; + case '\x04': + if (!this.line.length) { + this.exit(); + } + break; + case '\x0c': + this.written.fire('\x1b[2J\x1b[H'); + this.redraw(); + break; + case '\x1b[A': + this.recall(-1); + break; + case '\x1b[B': + this.recall(1); + break; + case '\x1b[D': + this.cursor = Math.max(0, this.cursor - 1); + this.redraw(); + break; + case '\x1b[C': + this.cursor = Math.min(this.line.length, this.cursor + 1); + this.redraw(); + break; + case '\x01': + case '\x1b[H': + this.cursor = 0; + this.redraw(); + break; + case '\x05': + case '\x1b[F': + this.cursor = this.line.length; + this.redraw(); + break; + case '\b': + case '\x7f': + if (this.cursor) { + this.line.splice(--this.cursor, 1); + this.redraw(); + } + break; + case '\x1b[3~': + this.line.splice(this.cursor, 1); + this.redraw(); + break; + case '\t': + this.line.splice(this.cursor++, 0, ' '); + this.redraw(); + break; + default: + if ( + key.length && + key.codePointAt(0)! >= 32 && + !key.startsWith('\x1b') && + !(key.charCodeAt(0) >= 127 && key.charCodeAt(0) <= 159) + ) { + const atEnd = this.cursor === this.line.length; + this.line.splice(this.cursor++, 0, key); + if (atEnd) { + this.written.fire(key); + } else { + this.redraw(); + } + } + } + } + } + private exit(): void { + this.ended.fire(0); + this.close(); + } + private uri(path: string): vscode.Uri { + return this.target.resource(absolute(this.cwd, path)); + } + + /** The VS Code file service can create parents implicitly; these commands require one. */ + private async requireParent(path: string): Promise { + const parent = absolute(path, '..'); + if ( + !( + (await vscode.workspace.fs.stat(this.target.resource(parent))).type & + vscode.FileType.Directory + ) + ) { + throw new Error('Not a directory: ' + parent); + } + } + private async execute(line: string): Promise { + try { + const { args, redirect } = parse(line); + if (!args.length) { + return; + } + const path = redirect && absolute(this.cwd, redirect.path); + if (path) { + await this.requireParent(path); + if ( + ((await stat(this.target.resource(path)))?.type ?? 0) & + vscode.FileType.Directory + ) { + throw new Error('Cannot redirect output to a directory: ' + path); + } + if (this.closed) { + return; + } + } + const result = await this.command(args[0], args.slice(1)); + if (redirect && path && !this.closed) { + const destination = this.target.resource(path); + let bytes: Uint8Array = new TextEncoder().encode(result); + if (redirect.append && (await stat(destination))) { + const previous = await vscode.workspace.fs.readFile(destination); + const combined = new Uint8Array(previous.length + bytes.length); + combined.set(previous); + combined.set(bytes, previous.length); + bytes = combined; + } + if (!this.closed) { + await vscode.workspace.fs.writeFile(destination, bytes); + } + } else if (result && !this.closed) { + this.written.fire(display(result) + (result.endsWith('\n') ? '' : '\r\n')); + } + } catch (error) { + if (!this.closed) { + this.written.fire( + display(error instanceof Error ? error.message : String(error)) + '\r\n', + ); + } + } + } + private async command(name: string, args: string[]): Promise { + const files = vscode.workspace.fs; + const usage = (condition: boolean, syntax: string) => { + if (!condition) { + throw new Error('Usage: ' + syntax); + } + }; + switch (name) { + case 'help': + usage(!args.length, 'help'); + return help; + case 'pwd': + usage(!args.length, 'pwd'); + return this.cwd + '\n'; + case 'echo': + return args.join(' ') + '\n'; + case 'clear': + usage(!args.length, 'clear'); + this.written.fire('\x1b[2J\x1b[H'); + return ''; + case 'exit': + usage(!args.length, 'exit'); + this.exit(); + return ''; + case 'cd': { + usage(args.length <= 1, 'cd [DIR]'); + const dir = absolute(this.cwd, args[0] ?? home); + const entry = await files.stat(this.target.resource(dir)); + if (!(entry.type & vscode.FileType.Directory)) { + throw new Error('Not a directory: ' + dir); + } + this.cwd = dir; + return ''; + } + case 'ls': { + let flags = ''; + while (args[0]?.startsWith('-')) { + const option = args.shift()!; + if (option === '--') { + break; + } + usage(/^-[al]+$/.test(option), 'ls [-al] [PATH]'); + flags += option; + } + usage(args.length <= 1, 'ls [-al] [PATH]'); + const path = absolute(this.cwd, args[0] ?? '.'); + const uri = this.target.resource(path); + const info = await files.stat(uri); + const directory = !!(info.type & vscode.FileType.Directory); + const entries: [string, vscode.FileType][] = directory + ? await files.readDirectory(uri) + : [[path.split('/').pop()!, info.type]]; + // The session file provider hides host mounts. The terminal routes + // /project through the owning, durable workspace provider. + if (path === '/' && !entries.some(([entry]) => entry === 'project')) { + entries.push(['project', vscode.FileType.Directory]); + } + const rows = []; + for (const [entry, type] of entries.sort(([a], [b]) => a.localeCompare(b))) { + if (this.closed) { + return ''; + } + if (directory && entry.startsWith('.') && !flags.includes('a')) { + continue; + } + const details = flags.includes('l') + ? directory + ? await files.stat(this.target.resource(absolute(path, entry))) + : info + : undefined; + rows.push( + (details ? String(details.size).padStart(8) + ' ' : '') + + entry + + (type & vscode.FileType.Directory ? '/' : ''), + ); + } + return rows.length ? rows.join('\n') + '\n' : ''; + } + case 'cat': { + usage(!!args.length, 'cat FILE...'); + const texts = []; + for (const file of args) { + if (this.closed) { + return ''; + } + const bytes = await files.readFile(this.uri(file)); + try { + texts.push(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + } catch { + throw new Error('Cannot print a binary file: ' + file); + } + } + return texts.join(''); + } + case 'touch': { + usage(args.length === 1, 'touch FILE'); + const path = absolute(this.cwd, args[0]), + uri = this.target.resource(path), + existing = await stat(uri); + if (!existing) { + await this.requireParent(path); + await files.writeFile(uri, new Uint8Array()); + } else if (existing.type & vscode.FileType.Directory) { + throw new Error('Expected a file: ' + args[0]); + } + return ''; + } + case 'mkdir': { + const parents = args[0] === '-p'; + if (parents) { + args.shift(); + } + usage(args.length === 1, 'mkdir [-p] DIR'); + const dir = absolute(this.cwd, args[0]), + uri = this.target.resource(dir); + if (parents) { + let current = '/'; + for (const part of dir.split('/').filter(Boolean)) { + current = absolute(current, part); + const location = this.target.resource(current); + const existing = await stat(location); + if (!existing) { + await files.createDirectory(location); + } else if (!(existing.type & vscode.FileType.Directory)) { + throw new Error('Not a directory: ' + current); + } + } + } else { + if (await stat(uri)) { + throw new Error('Already exists: ' + dir); + } + await this.requireParent(dir); + await files.createDirectory(uri); + } + return ''; + } + case 'cp': + case 'mv': { + usage(args.length === 2, name + ' SOURCE DEST'); + const source = absolute(this.cwd, args[0]), + src = this.target.resource(source); + if (source === '/' || (name === 'mv' && source === '/project')) { + throw new Error('Cannot move or copy a filesystem root.'); + } + const sourceIsDir = !!((await files.stat(src)).type & vscode.FileType.Directory); + if (name === 'cp' && sourceIsDir) { + throw new Error('cp requires a source file.'); + } + let dest = absolute(this.cwd, args[1]), + dst = this.target.resource(dest); + let existing = await stat(dst); + if (existing && existing.type & vscode.FileType.Directory) { + dest = absolute(dest, source.split('/').pop()!); + dst = this.target.resource(dest); + existing = await stat(dst); + } + if (source === dest || dest.startsWith(source + '/')) { + throw new Error('Destination is the source or lies inside it.'); + } + if (existing && !!(existing.type & vscode.FileType.Directory) !== sourceIsDir) { + throw new Error( + 'Cannot replace a file with a directory or a directory with a file.', + ); + } + await this.requireParent(dest); + if (name === 'mv') { + if (this.cwd === source || this.cwd.startsWith(source + '/')) { + throw new Error('Change directories before moving the current directory.'); + } + if ( + source.startsWith('/project/') !== dest.startsWith('/project/') || + src.scheme !== dst.scheme || + src.authority !== dst.authority + ) { + throw new Error( + 'Use cp then rm to move files between mounted filesystems.', + ); + } + if (existing && sourceIsDir && (await files.readDirectory(dst)).length) { + throw new Error('Directory is not empty: ' + dest); + } + await files.rename(src, dst, { overwrite: true }); + } else { + const bytes = await files.readFile(src); + if (!this.closed) { + await files.writeFile(dst, bytes); + } + } + return ''; + } + case 'rm': + case 'rmdir': { + const recursive = name === 'rm' && args[0] === '-r'; + if (recursive) { + args.shift(); + } + usage(args.length === 1, name + (name === 'rm' ? ' [-r] PATH' : ' DIR')); + const path = absolute(this.cwd, args[0]), + uri = this.target.resource(path); + if (path === '/' || path === '/project') { + throw new Error('Cannot remove a filesystem root.'); + } + if (this.cwd === path || this.cwd.startsWith(path + '/')) { + throw new Error('Change directories before removing the current directory.'); + } + const dir = !!((await files.stat(uri)).type & vscode.FileType.Directory); + if (dir && name === 'rm' && !recursive) { + throw new Error( + 'Use rmdir for an empty directory or rm -r for a directory tree.', + ); + } + if (!dir && name === 'rmdir') { + throw new Error('Not a directory: ' + path); + } + await files.delete(uri, { recursive, useTrash: false }); + return ''; + } + default: + throw new Error( + 'Unknown webR filesystem command: ' + + name + + '. Type help for supported commands.', + ); + } + } +} + +export function registerWebRProjectTerminal( + resolve: () => Promise, +): vscode.Disposable { + const options = async (): Promise => { + const target = await resolve(); + if (!target) { + throw new Error('Open a .webrproj workspace to use its webR project terminal.'); + } + return { + name: 'webR: ' + target.name, + pty: new ProjectTerminal(target), + isTransient: true, + }; + }; + return vscode.Disposable.from( + vscode.window.registerTerminalProfileProvider(WEBR_PROJECT_TERMINAL_PROFILE, { + provideTerminalProfile: async (token) => { + if (token.isCancellationRequested) { + return; + } + const profile = await options(); + if (token.isCancellationRequested) { + profile.pty.close(); + return; + } + return new vscode.TerminalProfile(profile); + }, + }), + vscode.commands.registerCommand(WEBR_PROJECT_TERMINAL_COMMAND, async () => { + const term = vscode.window.createTerminal(await options()); + term.show(); + }), + ); +} diff --git a/src/webr/projectWorkspace.ts b/src/webr/projectWorkspace.ts index 50e769309..74dc7f9b8 100644 --- a/src/webr/projectWorkspace.ts +++ b/src/webr/projectWorkspace.ts @@ -6,11 +6,14 @@ import { validateProjectPath, } from './projectArchive'; import { WebRFileRevisions } from './fileRevisions'; +import { registerWebRProjectTerminal, type WebRProjectTerminalTarget } from './projectTerminal'; +import { sessionFileUri } from './sessionFiles'; export const WEBR_PROJECT_SCHEME = 'vscode-r-project'; const editorId = 'r.webRProject'; const extension = '.webrproj'; const sourceKey = 'r.webR.projectSource.v1.'; +const digestPattern = /^[0-9a-f]{64}$/; const filters = { 'webR projects': ['webrproj'] }; export type ProjectWriteOptions = { create: boolean; overwrite: boolean; expected?: string }; @@ -38,6 +41,7 @@ export interface WebRProjectHost { /** Explorer can resolve files before any execution session has started. */ open(source: vscode.Uri, root: vscode.Uri): Promise; start(source: vscode.Uri, root: vscode.Uri, volume: WebRProjectVolume): Promise; + terminalSession(root: vscode.Uri): { id: string; generation: string } | undefined; } /** Publish a complete new bundle without overwriting an existing project. */ @@ -64,36 +68,82 @@ export async function webRProjectRoot(source: vscode.Uri, scope?: string): Promi const filename = source.path.slice(source.path.lastIndexOf('/') + 1); const stem = filename.slice(0, -extension.length); const name = !stem || stem === '.' || stem === '..' ? 'webR project' : stem; + const id = await projectDigest( + new TextEncoder().encode( + scope ? JSON.stringify([scope, source.toString()]) : source.toString(), + ), + ); + // VS Code uses the authority verbatim as the native virtual-workspace indicator. + // A colon starts an unescaped URI port, so escape it in POSIX bundle names. + // Escape literal codicon tokens so they render as filename text in the status bar. + const label = filename + // oxlint-disable-next-line no-control-regex + .replace(/[:\u0000-\u001f\u007f]/g, encodeURIComponent) + .replace(/\$\([a-z0-9-]+(?:~[a-z]+)?\)/gi, (token) => '\\' + token); return vscode.Uri.from({ scheme: WEBR_PROJECT_SCHEME, - authority: await projectDigest( - new TextEncoder().encode( - scope ? JSON.stringify([scope, source.toString()]) : source.toString(), - ), - ), - path: '/' + name, + authority: label, + path: '/' + id + '/' + name, }); } -function split(uri: vscode.Uri): { root: vscode.Uri; path: string } { +/** Read both filename-labelled roots and the original SHA-authority URI format. */ +export function webRProjectAddress( + uri: vscode.Uri, +): { id: string; root: vscode.Uri; path: string } | undefined { if ( uri.scheme !== WEBR_PROJECT_SCHEME || - !/^[0-9a-f]{64}$/.test(uri.authority) || - !uri.path.startsWith('/') || uri.query || - uri.fragment + uri.fragment || + !uri.path.startsWith('/') ) { - throw vscode.FileSystemError.FileNotFound(uri); + return; + } + const parts = uri.path.slice(1).split('/'); + const legacy = digestPattern.test(uri.authority); + const id = legacy ? uri.authority : parts.shift(); + const name = parts.shift(); + if ( + !id || + !digestPattern.test(id) || + !name || + (!legacy && !uri.authority.toLowerCase().endsWith(extension)) + ) { + return; } - const [, name, ...parts] = uri.path.split('/'); - const path = parts.join('/'); - if (!name) { + const root = uri.with({ path: legacy ? '/' + name : '/' + id + '/' + name }); + return { id, root, path: parts.join('/') }; +} + +export function webRProjectKey(uri: vscode.Uri): string { + return webRProjectAddress(uri)?.root.toString() ?? ''; +} + +function legacyWebRProjectRoot(named: vscode.Uri): vscode.Uri { + const [, id, name] = named.path.split('/'); + return named.with({ authority: id, path: '/' + name }); +} + +/** Keep a user's saved multi-root workspace intact when they relocate a legacy bundle. */ +export function existingWebRProjectRoot(named: vscode.Uri): vscode.Uri | undefined { + const folders = vscode.workspace.workspaceFolders; + const current = folders?.find((folder) => folder.uri.toString() === named.toString()); + if (current || !vscode.workspace.workspaceFile) { + return current?.uri; + } + const legacy = legacyWebRProjectRoot(named).toString(); + return folders?.find((folder) => folder.uri.toString() === legacy)?.uri; +} + +function split(uri: vscode.Uri) { + const address = webRProjectAddress(uri); + if (!address) { throw vscode.FileSystemError.FileNotFound(uri); } - if (path) { - validateProjectPath(path); + if (address.path) { + validateProjectPath(address.path); } - return { root: uri.with({ path: '/' + name }), path }; + return address; } interface OpenVolume { @@ -102,6 +152,54 @@ interface OpenVolume { listener?: vscode.Disposable; } +/** VS Code selects contributed default profiles from workspace settings. Keep + * these local to the window, including when the source bundle is read-only. */ +async function projectWorkspaceFile(storage: vscode.Uri, root: vscode.Uri): Promise { + const { id } = split(root); + const folder = vscode.Uri.joinPath(storage, 'project-workspaces', id); + // The backing provider may run on a different OS from the source. Use a + // bounded, portable basename for the private workbench descriptor. + const stem = root.path.split('/').at(-1)!; + // oxlint-disable-next-line no-control-regex + const title = Array.from(stem.replace(/[<>:"/\\|?*\u0000-\u001f\u007f]/g, '_')) + .slice(0, 48) + .join(''); + const file = vscode.Uri.joinPath(folder, 'webR - ' + title + '.code-workspace'); + try { + await vscode.workspace.fs.stat(file); + return file; // Preserve any workspace preferences edited since the first open. + } catch (error) { + if (!(error instanceof vscode.FileSystemError && error.code === 'FileNotFound')) { + throw error; + } + } + // Uri.toString() folds hostnames to lowercase. Store the original filename + // explicitly so opening or restoring this workspace preserves its label. + const folderUri = + root.scheme + + '://' + + encodeURIComponent(root.authority) + + root.path.split('/').map(encodeURIComponent).join('/'); + const settings: Record = {}; + for (const platform of ['linux', 'osx', 'windows']) { + settings['terminal.integrated.defaultProfile.' + platform] = 'webR Project Terminal'; + if (vscode.env.uiKind === vscode.UIKind.Web && !vscode.env.remoteName) { + // The extension's native R terminal is available only on a process host. + settings['terminal.integrated.profiles.' + platform] = { 'R Terminal': null }; + } + } + const json = JSON.stringify({ folders: [{ uri: folderUri }], settings }, null, 2) + '\n'; + await vscode.workspace.fs.createDirectory(folder); + try { + await createProjectFile(file, new TextEncoder().encode(json)); + } catch (error) { + if (!(error instanceof vscode.FileSystemError && error.code === 'FileExists')) { + throw error; + } + } + return file; +} + /** Maps each stable workspace URI back to the bundle the user actually opened. */ class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { private readonly changes = new vscode.EventEmitter(); @@ -122,6 +220,7 @@ class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { (uri) => uri.scheme === WEBR_PROJECT_SCHEME, ); this.subscriptions.push( + registerWebRProjectTerminal(() => this.terminal()), vscode.workspace.registerFileSystemProvider(WEBR_PROJECT_SCHEME, this, { isCaseSensitive: true, }), @@ -204,8 +303,8 @@ class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { const folder = vscode.workspace.workspaceFolders?.find( (f) => f.uri.scheme === WEBR_PROJECT_SCHEME, ); - const stored = - folder && this.context.globalState.get(sourceKey + folder.uri.authority); + const id = folder && webRProjectAddress(folder.uri)?.id; + const stored = id && this.context.globalState.get(sourceKey + id); return stored ? vscode.Uri.joinPath(vscode.Uri.parse(stored, true), '..') : undefined; } @@ -238,8 +337,8 @@ class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { await decodeProject(await vscode.workspace.fs.readFile(source)); // VS Code can implicitly trust virtual filesystems. Establish trust in // the original file before exposing its workspace settings to extensions. - const known = - this.context.globalState.get(sourceKey + root.authority) === source.toString(); + const key = sourceKey + split(root).id; + const known = this.context.globalState.get(key) === source.toString(); const insideTrustedFolder = vscode.workspace.isTrusted && !!vscode.workspace.getWorkspaceFolder(source); if ( @@ -262,23 +361,84 @@ class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { return; } } - await this.context.globalState.update(sourceKey + root.authority, source.toString()); + await this.context.globalState.update(key, source.toString()); // Closing the launcher prevents restoring its old tab from navigating again. panel?.dispose(); - if ( - vscode.workspace.workspaceFolders?.some( - (folder) => folder.uri.toString() === root.toString(), - ) - ) { - await this.start(root); + const existing = existingWebRProjectRoot(root); + if (existing) { + await this.start(existing); return; } - await vscode.commands.executeCommand('vscode.openFolder', root, { forceReuseWindow: true }); + const file = await projectWorkspaceFile(this.context.globalStorageUri, root); + await vscode.commands.executeCommand('vscode.openFolder', file, { forceReuseWindow: true }); + } + + private async terminal(): Promise { + const projects = vscode.workspace.workspaceFolders?.filter( + (f) => f.uri.scheme === WEBR_PROJECT_SCHEME, + ); + if (!projects?.length) { + return; + } + const active = vscode.window.activeTextEditor?.document.uri; + const current = active && vscode.workspace.getWorkspaceFolder(active); + const folder = + projects.find((f) => f.uri.toString() === current?.uri.toString()) ?? + (projects.length === 1 + ? projects[0] + : ( + await vscode.window.showQuickPick( + projects.map((f) => { + const source = this.context.globalState.get( + sourceKey + split(f.uri).id, + ); + return { + label: f.name, + detail: source + ? vscode.Uri.parse(source) + .with({ query: '', fragment: '' }) + .toString(true) + : f.uri.toString(true), + folder: f, + }; + }), + { title: 'Select a webR Project for the Terminal' }, + ) + )?.folder); + if (!folder) { + throw new vscode.CancellationError(); + } + const { root } = split(folder.uri); + let owner = this.host.terminalSession(root); + if (!owner) { + await this.start(root); + owner = this.host.terminalSession(root); + } + if (!owner) { + throw new Error('Reconnect to the webR project session to open its terminal.'); + } + const { id, generation } = owner; + const { source } = await this.volume(root); + return { + name: source.path.slice(source.path.lastIndexOf('/') + 1), + resource: (path) => + path === '/project' + ? root + : path.startsWith('/project/') + ? vscode.Uri.joinPath(root, path.slice('/project/'.length)) + : sessionFileUri(id, generation, path), + }; } private startRoots( folders: readonly vscode.WorkspaceFolder[] = vscode.workspace.workspaceFolders ?? [], ): void { + void vscode.commands.executeCommand( + 'setContext', + 'r.hasWebRProject', + vscode.workspace.workspaceFolders?.some((f) => f.uri.scheme === WEBR_PROJECT_SCHEME) ?? + false, + ); for (const { uri } of folders) { if (uri.scheme === WEBR_PROJECT_SCHEME && vscode.workspace.isTrusted) { void this.start(uri).catch((error) => { @@ -296,8 +456,12 @@ class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { if (!vscode.workspace.isTrusted) { return Promise.reject(new Error('Trust this workspace before starting R Interactive.')); } - const { root } = split(uri); - let pending = this.starting.get(root.authority); + const root = webRProjectAddress(uri)?.root; + if (!root) { + return Promise.reject(vscode.FileSystemError.FileNotFound(uri)); + } + const key = root.toString(); + let pending = this.starting.get(key); if (!pending) { pending = this.volume(root) .then(({ source, volume }) => { @@ -305,8 +469,8 @@ class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { return this.host.start(source, root, volume); } }) - .finally(() => this.starting.delete(root.authority)); - this.starting.set(root.authority, pending); + .finally(() => this.starting.delete(key)); + this.starting.set(key, pending); } return pending; } @@ -325,7 +489,8 @@ class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { } private async load(root: vscode.Uri): Promise { - const stored = this.context.globalState.get(sourceKey + root.authority); + const { id } = split(root); + const stored = this.context.globalState.get(sourceKey + id); if (!stored) { throw vscode.FileSystemError.Unavailable( 'Reopen the original .webrproj file to locate this project.', @@ -333,10 +498,9 @@ class ProjectWorkspace implements vscode.FileSystemProvider, vscode.Disposable { } const source = vscode.Uri.parse(stored, true); this.checkSource(source); - if ( - (await webRProjectRoot(source, await this.host.scope?.())).toString() !== - root.toString() - ) { + const named = await webRProjectRoot(source, await this.host.scope?.()); + const expected = digestPattern.test(root.authority) ? legacyWebRProjectRoot(named) : named; + if (expected.toString() !== root.toString()) { throw vscode.FileSystemError.FileNotFound(root); } const volume = await this.host.open(source, root); diff --git a/website/docs/features/webr.md b/website/docs/features/webr.md index e3566f313..84b91e1fc 100644 --- a/website/docs/features/webr.md +++ b/website/docs/features/webr.md @@ -36,6 +36,9 @@ is trusted. With Workspace Trust enabled, opening a bundle from outside a truste workspace asks whether you trust its authors before its workspace settings take effect. Reopening on the same R host can reconnect to the existing session. If VS Code first displays a binary editor, choose **Reopen Editor With… → webR Project**. +The virtual-workspace indicator shows the bundle filename, for example +`Sales Report.webrproj`. Hover over a shortened label to see its full name. +In a Remote SSH window, VS Code uses that indicator for the SSH connection. Create `fit.R` in Explorer, save it, then run `source("fit.R")` in Interactive. The R working directory is `/project`. For example, @@ -44,6 +47,21 @@ project. Editor saves and R file changes from completed cells go back into the bundle. On desktop the session agent can finish a cell and save its files after VS Code closes. In the browser, wait for the cell to finish before closing the tab. +**Terminal → New Terminal** uses the **webR Project Terminal** profile, starting +in `/project`. Browser-only VS Code opens a profile picker from this menu; +select **webR Project Terminal** or use **R: Open webR Project Terminal** directly. +Use `ls` to see the same files as Explorer. For example, after +`writeLines("ready", "/tmp/status.txt")` in R Interactive, `cat /tmp/status.txt` +prints `ready` in the terminal. `cp /tmp/status.txt /project/status.txt` saves a +copy in the bundle. Type `help` for the available filesystem commands. Use +R Interactive for R expressions and select a host shell from the terminal +profile dropdown for programs such as Git or Bash. + +vscode-R keeps the terminal default in its local VS Code workspace file. If +you already had the project open with an older build, reopen the `.webrproj` +file to use the new label and terminal default. In a custom multi-root +workspace, choose **R: Open webR Project Terminal** for a particular project. + To move a project, copy the saved `.webrproj` file. Its version-one ZIP format has a `manifest.json` containing `{"format":1}` and a `files/` directory with the project contents. To carry an R object with the project, save it explicitly, From 685cc942dfcf709315c5c2b5115a885d4b05aab4 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 19:32:33 +0800 Subject: [PATCH 4/4] Document terminal profile discovery on older VS Code --- website/docs/features/webr.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/website/docs/features/webr.md b/website/docs/features/webr.md index 84b91e1fc..b71fe2cba 100644 --- a/website/docs/features/webr.md +++ b/website/docs/features/webr.md @@ -50,6 +50,9 @@ VS Code closes. In the browser, wait for the cell to finish before closing the t **Terminal → New Terminal** uses the **webR Project Terminal** profile, starting in `/project`. Browser-only VS Code opens a profile picker from this menu; select **webR Project Terminal** or use **R: Open webR Project Terminal** directly. +On VS Code 1.101, the first terminal in a fresh profile can open the host shell +while VS Code discovers contributed profiles. **R: Open webR Project Terminal** +opens the filesystem terminal directly in that case. Use `ls` to see the same files as Explorer. For example, after `writeLines("ready", "/tmp/status.txt")` in R Interactive, `cat /tmp/status.txt` prints `ready` in the terminal. `cp /tmp/status.txt /project/status.txt` saves a