From 9e6772c0b9c04fe9f80449afa05581b18b6eadcc Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sat, 28 Nov 2026 18:14:45 +0800 Subject: [PATCH 1/5] feat(web): run R Interactive and language features in browser workers --- .gitignore | 1 + CONTRIBUTING.md | 6 + esbuild.js | 17 +- package.json | 435 +++++++++++++++------- src/interactive/notebook.ts | 53 ++- src/rTerminal.ts | 27 +- src/rmarkdown/chunks.ts | 263 +++++++------ src/rmarkdown/index.ts | 12 +- src/selection.ts | 22 +- src/test/plot/plotCommands.test.ts | 1 + src/test/suite/chunks.test.ts | 3 +- src/test/web/webR.cjs | 131 +++++++ src/web/extension.ts | 90 +++++ src/web/files.ts | 47 +++ src/web/interactive.ts | 266 +++++++++++++ src/web/languageService.ts | 180 +++++++++ src/web/session.ts | 235 ++++++++++++ website/docs/features/language-service.md | 6 + website/docs/features/r-interactive.md | 10 + 19 files changed, 1489 insertions(+), 316 deletions(-) create mode 100644 src/test/web/webR.cjs create mode 100644 src/web/extension.ts create mode 100644 src/web/files.ts create mode 100644 src/web/interactive.ts create mode 100644 src/web/languageService.ts create mode 100644 src/web/session.ts diff --git a/.gitignore b/.gitignore index b9ae4d20a..ad66edaa1 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ node_modules *.vsix dist .vscode-test +.vscode-test-web/ *.temp *.tmp tmp.* diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1e18bfaaf..f1b811921 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -90,6 +90,12 @@ VS Code profile. This case uses an unavailable R executable and downloads the pinned webR assets. It checks Outline and Go to Definition across two unsaved R documents, then edits a declaration and checks the new symbol. +## Testing VS Code for the Web + +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. + +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 The VSIX includes the R-universe `wasm32-unknown-emscripten` languageserver diff --git a/esbuild.js b/esbuild.js index 6db33b0cc..c1a6eedd3 100644 --- a/esbuild.js +++ b/esbuild.js @@ -80,6 +80,21 @@ async function main() { logLevel: 'info', }); + const browserExtensionCtx = await esbuild.context({ + entryPoints: ['./src/web/extension.ts'], + outfile: 'dist/web-extension.js', + format: 'cjs', + platform: 'browser', + bundle: true, + // webR's Node entry imports worker_threads. The upstream browser + // distribution uses a Web Worker with the same JavaScript API. + alias: { webr: path.join(__dirname, 'node_modules/webr/dist/webr.js') }, + external: ['vscode'], + minify: production, + sourcemap: !production, + sourcesContent: false, + }); + // A session agent remains alive after the extension host exits. const agentCtx = await esbuild.context({ entryPoints: ['./src/interactive/agentMain.ts'], @@ -119,7 +134,7 @@ async function main() { logLevel: 'info', }); - const contexts = [extensionCtx, agentCtx, interactiveRendererCtx, webviewCtx]; + const contexts = [extensionCtx, browserExtensionCtx, agentCtx, interactiveRendererCtx, webviewCtx]; if (watch) { await Promise.all(contexts.map(context => context.watch())); console.log('Watching for changes...'); diff --git a/package.json b/package.json index 4b85b8522..1dbd2642e 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "onNotebook:r-interactive" ], "main": "./dist/extension", + "browser": "./dist/web-extension.js", "contributes": { "terminal": { "profiles": [ @@ -197,7 +198,8 @@ "command": "r.workspaceViewer.view", "title": "View", "icon": "$(open-preview)", - "category": "R Workspace Viewer" + "category": "R Workspace Viewer", + "enablement": "!r.webExtension" }, { "command": "r.workspaceViewer.clear", @@ -210,7 +212,8 @@ "command": "r.workspaceViewer.remove", "title": "Remove", "icon": "$(close)", - "category": "R Workspace Viewer" + "category": "R Workspace Viewer", + "enablement": "!r.webExtension" }, { "command": "r.workspaceViewer.save", @@ -223,40 +226,47 @@ "command": "r.workspaceViewer.load", "title": "Load workspace", "icon": "$(folder-opened)", - "category": "R Workspace Viewer" + "category": "R Workspace Viewer", + "enablement": "!r.webExtension" }, { "command": "r.workspaceViewer.package.showQuickPick", "title": "Show QuickPick", - "category": "R Workspace Viewer" + "category": "R Workspace Viewer", + "enablement": "!r.webExtension" }, { "command": "r.browser.refresh", "title": "Refresh", "icon": "$(refresh)", - "category": "R" + "category": "R", + "enablement": "!r.webExtension" }, { "command": "r.browser.openExternal", "title": "Open in external browser", "icon": "$(link-external)", - "category": "R" + "category": "R", + "enablement": "!r.webExtension" }, { "command": "r.showHelp", "title": "Show help", - "category": "R" + "category": "R", + "enablement": "!r.webExtension" }, { "command": "r.webview.find", "title": "R: Find in WebView", "icon": "$(search)", - "category": "R" + "category": "R", + "enablement": "!r.webExtension" }, { "command": "r.htmlViewer.restore", "title": "Restore HTML Viewer", - "category": "R" + "category": "R", + "enablement": "!r.webExtension" }, { "command": "r.htmlViewer.back", @@ -289,7 +299,8 @@ { "title": "Create R terminal", "category": "R", - "command": "r.createRTerm" + "command": "r.createRTerm", + "enablement": "!r.webExtension" }, { "title": "Run Source", @@ -301,22 +312,26 @@ "title": "Knit Rmd", "category": "R", "command": "r.knitRmd", - "icon": "$(run-below)" + "icon": "$(run-below)", + "enablement": "!r.webExtension" }, { "title": "Knit Rmd To PDF", "category": "R", - "command": "r.knitRmdToPdf" + "command": "r.knitRmdToPdf", + "enablement": "!r.webExtension" }, { "title": "Knit Rmd To HTML", "category": "R", - "command": "r.knitRmdToHtml" + "command": "r.knitRmdToHtml", + "enablement": "!r.webExtension" }, { "title": "Knit Rmd To All Formats", "category": "R", - "command": "r.knitRmdToAll" + "command": "r.knitRmdToAll", + "enablement": "!r.webExtension" }, { "title": "Run Source with Echo", @@ -331,112 +346,134 @@ { "title": "Show number of rows for selected object", "category": "R", - "command": "r.nrow" + "command": "r.nrow", + "enablement": "!r.webExtension" }, { "title": "Show length for a selected object", "category": "R", - "command": "r.length" + "command": "r.length", + "enablement": "!r.webExtension" }, { "title": "Show first part of a selected object", "category": "R", - "command": "r.head" + "command": "r.head", + "enablement": "!r.webExtension" }, { "title": "Show first part of a selected object (transposed)", "category": "R", - "command": "r.thead" + "command": "r.thead", + "enablement": "!r.webExtension" }, { "title": "Show names for a selected object", "category": "R", - "command": "r.names" + "command": "r.names", + "enablement": "!r.webExtension" }, { "title": "View selected object", "category": "R", - "command": "r.view" + "command": "r.view", + "enablement": "!r.webExtension" }, { "title": "Create gitignore", "category": "R", - "command": "r.createGitignore" + "command": "r.createGitignore", + "enablement": "!r.webExtension" }, { "title": "Create .lintr to the workspace", "category": "R", - "command": "r.createLintrConfig" + "command": "r.createLintrConfig", + "enablement": "!r.webExtension" }, { "title": "Preview Dataframe", "category": "R", - "command": "r.previewDataframe" + "command": "r.previewDataframe", + "enablement": "!r.webExtension" }, { "title": "Preview Environment", "category": "R", - "command": "r.previewEnvironment" + "command": "r.previewEnvironment", + "enablement": "!r.webExtension" }, { "title": "Load All", "category": "R Package", - "command": "r.loadAll" + "command": "r.loadAll", + "enablement": "!r.webExtension" }, { "title": "Build", "category": "R Package", - "command": "r.build" + "command": "r.build", + "enablement": "!r.webExtension" }, { "title": "Build Binary", "category": "R Package", - "command": "r.buildBinary" + "command": "r.buildBinary", + "enablement": "!r.webExtension" }, { "title": "Check", "category": "R Package", - "command": "r.check" + "command": "r.check", + "enablement": "!r.webExtension" }, { "title": "Document", "category": "R Package", - "command": "r.document" + "command": "r.document", + "enablement": "!r.webExtension" }, { "title": "Install", "category": "R Package", - "command": "r.install" + "command": "r.install", + "enablement": "!r.webExtension" }, { "title": "Test", "category": "R Package", - "command": "r.test" + "command": "r.test", + "enablement": "!r.webExtension" }, { "title": "Generate C/C++ Configuration", "category": "R Package", - "command": "r.generateCCppProperties" + "command": "r.generateCCppProperties", + "enablement": "!r.webExtension" }, { "title": "Activate R Session", "category": "R", - "command": "r.activateRSession" + "command": "r.activateRSession", + "enablement": "!r.webExtension" }, { "title": "Attach External R Session (Copy command)", "category": "R", - "command": "r.connectToSession" + "command": "r.connectToSession", + "enablement": "!r.webExtension" }, { "title": "Run Command With Selection or Word in Terminal", "category": "R", - "command": "r.runCommandWithSelectionOrWord" + "command": "r.runCommandWithSelectionOrWord", + "enablement": "!r.webExtension" }, { "title": "Run Command With Editor Path in Terminal", "category": "R", - "command": "r.runCommandWithEditorPath" + "command": "r.runCommandWithEditorPath", + "enablement": "!r.webExtension" }, { "title": "Run Command in Terminal", @@ -446,12 +483,14 @@ { "title": "Run from Beginning to Line", "category": "R", - "command": "r.runFromBeginningToLine" + "command": "r.runFromBeginningToLine", + "enablement": "!r.webExtension" }, { "title": "Run from Line to End", "category": "R", - "command": "r.runFromLineToEnd" + "command": "r.runFromLineToEnd", + "enablement": "!r.webExtension" }, { "title": "Run Selection/Line (Retain Cursor)", @@ -516,13 +555,15 @@ { "title": "New Draft", "category": "R Markdown", - "command": "r.rmarkdown.newDraft" + "command": "r.rmarkdown.newDraft", + "enablement": "!r.webExtension" }, { "title": "R Markdown (rmd)", "category": "R Markdown", "when": false, - "command": "r.rmarkdown.newFileDraft" + "command": "r.rmarkdown.newFileDraft", + "enablement": "!r.webExtension" }, { "title": "R Document (r)", @@ -534,60 +575,70 @@ "command": "r.rmarkdown.setKnitDirectory", "title": "Set Knit directory", "icon": "$(zap)", - "category": "R Markdown" + "category": "R Markdown", + "enablement": "!r.webExtension" }, { "command": "r.rmarkdown.showPreviewToSide", "title": "Open Preview to the Side", "icon": "$(open-preview)", - "category": "R Markdown" + "category": "R Markdown", + "enablement": "!r.webExtension" }, { "command": "r.rmarkdown.showPreview", "title": "Open Preview", "icon": "$(open-preview)", - "category": "R Markdown" + "category": "R Markdown", + "enablement": "!r.webExtension" }, { "command": "r.rmarkdown.preview.refresh", "title": "Refresh Preview", "icon": "$(refresh)", - "category": "R Markdown" + "category": "R Markdown", + "enablement": "!r.webExtension" }, { "command": "r.rmarkdown.preview.openExternal", "title": "Open in External Browser", "icon": "$(link-external)", - "category": "R Markdown" + "category": "R Markdown", + "enablement": "!r.webExtension" }, { "command": "r.rmarkdown.preview.showSource", "title": "Show Source", "icon": "$(go-to-file)", - "category": "R Markdown" + "category": "R Markdown", + "enablement": "!r.webExtension" }, { "title": "Toggle Style", "category": "R Markdown", "command": "r.rmarkdown.preview.toggleStyle", - "icon": "$(symbol-color)" + "icon": "$(symbol-color)", + "enablement": "!r.webExtension" }, { "title": "Enable Auto Refresh", "category": "R Markdown", "command": "r.rmarkdown.preview.enableAutoRefresh", - "icon": "$(sync)" + "icon": "$(sync)", + "enablement": "!r.webExtension" }, { "title": "Disable Auto Refresh", "category": "R Markdown", "command": "r.rmarkdown.preview.disableAutoRefresh", - "icon": "$(sync-ignored)" + "icon": "$(sync-ignored)", + "enablement": "!r.webExtension" }, { "title": "Launch RStudio Addin", "category": "R", - "command": "r.launchAddinPicker" + "command": "r.launchAddinPicker", + "enablement": "!r.webExtension" }, { "command": "r.helpPanel.back", @@ -614,143 +665,167 @@ "title": "Search Package Topics", "category": "R Help Panel", "command": "r.helpPanel.searchPackage", - "icon": "$(search)" + "icon": "$(search)", + "enablement": "!r.webExtension" }, { "title": "Open Topic in new Panel", "category": "R Help Panel", "command": "r.helpPanel.openInNewPanel", - "icon": "$(add)" + "icon": "$(add)", + "enablement": "!r.webExtension" }, { "title": "Clear Cached Files", "category": "R Help Panel", "command": "r.helpPanel.clearCache", - "icon": "$(refresh)" + "icon": "$(refresh)", + "enablement": "!r.webExtension" }, { "title": "Filter Packages", "category": "R Help Panel", "command": "r.helpPanel.filterPackages", - "icon": "$(filter)" + "icon": "$(filter)", + "enablement": "!r.webExtension" }, { "title": "Remove from favorites", "category": "R Help Panel", "command": "r.helpPanel.removeFromFavorites", - "icon": "$(star-full)" + "icon": "$(star-full)", + "enablement": "!r.webExtension" }, { "title": "Add to favorites", "category": "R Help Panel", "command": "r.helpPanel.addToFavorites", - "icon": "$(star-empty)" + "icon": "$(star-empty)", + "enablement": "!r.webExtension" }, { "title": "Show all packages", "category": "R Help Panel", "command": "r.helpPanel.showAllPackages", - "icon": "$(star-full)" + "icon": "$(star-full)", + "enablement": "!r.webExtension" }, { "title": "Show only favorites", "category": "R Help Panel", "command": "r.helpPanel.showOnlyFavorites", - "icon": "$(star-empty)" + "icon": "$(star-empty)", + "enablement": "!r.webExtension" }, { "title": "Remove Package", "category": "R Help Panel", "command": "r.helpPanel.removePackage", - "icon": "$(trash)" + "icon": "$(trash)", + "enablement": "!r.webExtension" }, { "title": "Update Installed Packages", "category": "R Help Panel", "command": "r.helpPanel.updateInstalledPackages", - "icon": "$(clone)" + "icon": "$(clone)", + "enablement": "!r.webExtension" }, { "title": "Update/reinstall Package", "category": "R Help Panel", "command": "r.helpPanel.updatePackage", - "icon": "$(cloud-download)" + "icon": "$(cloud-download)", + "enablement": "!r.webExtension" }, { "title": "Install multiple packages", "category": "R Help Panel", "command": "r.helpPanel.installPackages", - "icon": "$(expand-all)" + "icon": "$(expand-all)", + "enablement": "!r.webExtension" }, { "title": "Show QuickPick", "category": "R Help Panel", "command": "r.helpPanel.showQuickPick", - "icon": "$(zap)" + "icon": "$(zap)", + "enablement": "!r.webExtension" }, { "title": "Summarize Identical Topics", "category": "R Help Panel", "command": "r.helpPanel.summarizeTopics", - "icon": "$(fold)" + "icon": "$(fold)", + "enablement": "!r.webExtension" }, { "title": "Don't Summarize Identical Topics", "category": "R Help Panel", "command": "r.helpPanel.unsummarizeTopics", - "icon": "$(unfold)" + "icon": "$(unfold)", + "enablement": "!r.webExtension" }, { "title": "Open help for selection", "category": "R Help Panel", - "command": "r.helpPanel.openForSelection" + "command": "r.helpPanel.openForSelection", + "enablement": "!r.webExtension" }, { "title": "Open help for path", "category": "R Help Panel", - "command": "r.helpPanel.openForPath" + "command": "r.helpPanel.openForPath", + "enablement": "!r.webExtension" }, { "title": "Toggle Style", "category": "R Plot", "command": "r.plot.toggleStyle", - "icon": "$(symbol-color)" + "icon": "$(symbol-color)", + "enablement": "!r.webExtension" }, { "title": "Toggle Full Window Mode", "category": "R Plot", "command": "r.plot.toggleFullWindow", - "icon": "$(screen-full)" + "icon": "$(screen-full)", + "enablement": "!r.webExtension" }, { "title": "Toggle Preview Plot Layout", "category": "R Plot", "command": "r.plot.togglePreviewPlots", - "icon": "$(list-flat)" + "icon": "$(list-flat)", + "enablement": "!r.webExtension" }, { "title": "Export Plot", "category": "R Plot", "command": "r.plot.exportPlot", - "icon": "$(clone)" + "icon": "$(clone)", + "enablement": "!r.webExtension" }, { "title": "Close Plot", "category": "R Plot", "command": "r.plot.closePlot", - "icon": "$(trash)" + "icon": "$(trash)", + "enablement": "!r.webExtension" }, { "title": "Hide Plot", "category": "R Plot", "command": "r.plot.hidePlot", - "icon": "$(close)" + "icon": "$(close)", + "enablement": "!r.webExtension" }, { "title": "Restore Plots", "category": "R Plot", "command": "r.plot.resetPlots", - "icon": "$(discard)" + "icon": "$(discard)", + "enablement": "!r.webExtension" }, { "title": "Previous Plot", @@ -784,35 +859,40 @@ "title": "Zoom In", "category": "R Plot", "command": "r.plot.zoomIn", - "icon": "$(zoom-in)" + "icon": "$(zoom-in)", + "enablement": "!r.webExtension" }, { "title": "Zoom Out", "category": "R Plot", "command": "r.plot.zoomOut", - "icon": "$(zoom-out)" + "icon": "$(zoom-out)", + "enablement": "!r.webExtension" }, { "title": "Show Viewers", "category": "R Plot", "command": "r.plot.showViewers", - "icon": "$(versions)" + "icon": "$(versions)", + "enablement": "!r.webExtension" }, { "title": "Open Httpgd Url", "category": "R Plot", "command": "r.plot.openUrl", - "icon": "$(link)" + "icon": "$(link)", + "enablement": "!r.webExtension" }, { "title": "Open in External Browser", "category": "R Plot", "command": "r.plot.openExternal", - "icon": "$(link-external)" + "icon": "$(link-external)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.new", - "title": "New Persistent Interactive Session", + "title": "New Interactive Session", "category": "R", "icon": "$(add)" }, @@ -820,7 +900,8 @@ "command": "r.interactive.connect", "title": "Connect Interactive to Session", "category": "R", - "icon": "$(plug)" + "icon": "$(plug)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.open", @@ -831,7 +912,8 @@ "command": "r.interactive.refresh", "title": "Refresh Interactive Sessions", "category": "R", - "icon": "$(refresh)" + "icon": "$(refresh)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.interrupt", @@ -843,13 +925,15 @@ "command": "r.interactive.input", "title": "Reply to Interactive Input", "category": "R", - "icon": "$(comment)" + "icon": "$(comment)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.detach", "title": "Detach Interactive Session", "category": "R", - "icon": "$(debug-disconnect)" + "icon": "$(debug-disconnect)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.stop", @@ -862,7 +946,8 @@ "title": "Stop Selected Interactive Sessions…", "category": "R", "icon": "$(debug-stop)", - "shortTitle": "Stop Selected…" + "shortTitle": "Stop Selected…", + "enablement": "!r.webExtension" }, { "command": "r.interactive.stopAll", @@ -882,85 +967,99 @@ "command": "r.interactive.takeControl", "title": "Take Control of Interactive Session", "category": "R", - "icon": "$(key)" + "icon": "$(key)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.useTerminal", "title": "Use Terminal for R Execution", - "category": "R" + "category": "R", + "enablement": "!r.webExtension" }, { "command": "r.interactive.bindDocument", "title": "Bind Document to Interactive Session", - "category": "R" + "category": "R", + "enablement": "!r.webExtension" }, { "command": "r.interactive.export", "title": "Export Interactive History", "category": "R", - "icon": "$(export)" + "icon": "$(export)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.clear", "title": "Clear Completed Interactive Cells", "category": "R", "icon": "$(clear-all)", - "shortTitle": "Clear Completed" + "shortTitle": "Clear Completed", + "enablement": "!r.webExtension" }, { "command": "r.interactive.rename", "category": "R", "title": "Rename Interactive Session", - "icon": "$(edit)" + "icon": "$(edit)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.history", "category": "R", "title": "Search Interactive History", "icon": "$(history)", - "shortTitle": "History" + "shortTitle": "History", + "enablement": "!r.webExtension" }, { "command": "r.interactive.plots", "category": "R", "title": "Browse Interactive Plots", - "icon": "$(graph)" + "icon": "$(graph)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.cancelQueued", "category": "R", "title": "Cancel Queued Interactive Cells", - "icon": "$(close-all)" + "icon": "$(close-all)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.info", "category": "R", "title": "Show Interactive Session Details", - "icon": "$(info)" + "icon": "$(info)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.cleanAssets", "category": "R", "title": "Clean Up Interactive Assets", - "icon": "$(discard)" + "icon": "$(discard)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.reuseCell", "category": "R", "title": "Insert Cell Code into Interactive Input", - "icon": "$(insert)" + "icon": "$(insert)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.copyCell", "category": "R", "title": "Copy Cell Code", - "icon": "$(copy)" + "icon": "$(copy)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.source", "category": "R", "title": "Go to Interactive Cell Source", - "icon": "$(go-to-file)" + "icon": "$(go-to-file)", + "enablement": "!r.webExtension" }, { "command": "r.interactive.sessionActions", @@ -968,6 +1067,18 @@ "shortTitle": "Session…", "category": "R", "icon": "$(settings-gear)" + }, + { + "command": "r.webR.importFiles", + "title": "Import Files into webR…", + "category": "R", + "enablement": "r.webExtension" + }, + { + "command": "r.webR.exportFile", + "title": "Export File from webR…", + "category": "R", + "enablement": "r.webExtension" } ], "keybindings": [ @@ -1015,7 +1126,9 @@ }, { "command": "r.runSourcewithEcho", - "args": { "runChunkAtCursor": true }, + "args": { + "runChunkAtCursor": true + }, "key": "shift+Ctrl+enter", "mac": "shift+cmd+enter", "when": "editorTextFocus && editorLangId == 'r'" @@ -1228,6 +1341,14 @@ { "command": "r.interactive.source", "when": "false" + }, + { + "command": "r.webR.importFiles", + "when": "r.webExtension" + }, + { + "command": "r.webR.exportFile", + "when": "r.webExtension" } ], "editor/title/run": [ @@ -1236,7 +1357,7 @@ "command": "r.runSource" }, { - "when": "editorLangId == rmd && editorFocus", + "when": "!r.webExtension && editorLangId == rmd && editorFocus", "command": "r.knitRmd", "group": "navigation" } @@ -1264,32 +1385,32 @@ }, { "command": "r.rmarkdown.preview.openExternal", - "when": "resourceScheme =~ /webview/ && r.rmarkdown.preview.active", + "when": "!r.webExtension && resourceScheme =~ /webview/ && r.rmarkdown.preview.active", "group": "navigation@1" }, { "command": "r.rmarkdown.preview.showSource", - "when": "resourceScheme =~ /webview/ && r.rmarkdown.preview.active", + "when": "!r.webExtension && resourceScheme =~ /webview/ && r.rmarkdown.preview.active", "group": "navigation@2" }, { "command": "r.rmarkdown.preview.toggleStyle", - "when": "resourceScheme =~ /webview/ && r.rmarkdown.preview.active", + "when": "!r.webExtension && resourceScheme =~ /webview/ && r.rmarkdown.preview.active", "group": "navigation@3" }, { "command": "r.rmarkdown.preview.refresh", - "when": "resourceScheme =~ /webview/ && r.rmarkdown.preview.active", + "when": "!r.webExtension && resourceScheme =~ /webview/ && r.rmarkdown.preview.active", "group": "navigation@4" }, { "command": "r.rmarkdown.preview.enableAutoRefresh", - "when": "resourceScheme =~ /webview/ && r.rmarkdown.preview.active && !r.rmarkdown.preview.autoRefresh", + "when": "!r.webExtension && resourceScheme =~ /webview/ && r.rmarkdown.preview.active && !r.rmarkdown.preview.autoRefresh", "group": "navigation@5" }, { "command": "r.rmarkdown.preview.disableAutoRefresh", - "when": "resourceScheme =~ /webview/ && r.rmarkdown.preview.active && r.rmarkdown.preview.autoRefresh", + "when": "!r.webExtension && resourceScheme =~ /webview/ && r.rmarkdown.preview.active && r.rmarkdown.preview.autoRefresh", "group": "navigation@5" }, { @@ -1309,7 +1430,7 @@ }, { "command": "r.webview.find", - "when": "resourceScheme =~ /webview/ && r.helpPanel.active", + "when": "!r.webExtension && resourceScheme =~ /webview/ && r.helpPanel.active", "group": "navigation" }, { @@ -1395,28 +1516,28 @@ { "command": "r.rmarkdown.showPreviewToSide", "alt": "r.rmarkdown.showPreview", - "when": "editorLangId == rmd && editorFocus", + "when": "!r.webExtension && editorLangId == rmd && editorFocus", "group": "navigation" }, { "submenu": "r.knitCommands", - "when": "editorLangId == rmd && editorFocus", + "when": "!r.webExtension && editorLangId == rmd && editorFocus", "group": "@1" }, { "command": "r.rmarkdown.setKnitDirectory", - "when": "editorLangId == rmd && editorFocus", + "when": "!r.webExtension && editorLangId == rmd && editorFocus", "group": "@1" } ], "editor/context": [ { "command": "r.helpPanel.openForSelection", - "when": "resourceLangId == r" + "when": "!r.webExtension && resourceLangId == r" }, { "command": "r.helpPanel.openForSelection", - "when": "resourceLangId == rmd" + "when": "!r.webExtension && resourceLangId == rmd" } ], "view/item/context": [ @@ -1626,7 +1747,7 @@ "explorer/context": [ { "command": "r.rmarkdown.showPreview", - "when": "resourceLangId == rmd", + "when": "!r.webExtension && resourceLangId == rmd", "group": "navigation" } ], @@ -1647,7 +1768,8 @@ "file/newFile": [ { "group": "R", - "command": "r.rmarkdown.newFileDraft" + "command": "r.rmarkdown.newFileDraft", + "when": "!r.webExtension" }, { "group": "R", @@ -1667,29 +1789,29 @@ }, { "command": "r.interactive.history", - "when": "notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", + "when": "!r.webExtension && notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", "group": "navigation/transcript@1" }, { "command": "r.interactive.clear", - "when": "notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", + "when": "!r.webExtension && notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", "group": "navigation/transcript@2" } ], "notebook/cell/title": [ { "command": "r.interactive.reuseCell", - "when": "notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i && notebookCellType == code", + "when": "!r.webExtension && notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i && notebookCellType == code", "group": "inline/rInteractive@0" }, { "command": "r.interactive.copyCell", - "when": "notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i && notebookCellType == code", + "when": "!r.webExtension && notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i && notebookCellType == code", "group": "inline/rInteractive@1" }, { "command": "r.interactive.source", - "when": "notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i && notebookCellType == code", + "when": "!r.webExtension && notebookType == r-interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i && notebookCellType == code", "group": "inline/rInteractive@2" } ], @@ -1706,29 +1828,29 @@ }, { "command": "r.interactive.history", - "when": "notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", + "when": "!r.webExtension && notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", "group": "navigation/transcript@1" }, { "command": "r.interactive.clear", - "when": "notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", + "when": "!r.webExtension && notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", "group": "navigation/transcript@2" } ], "interactive/cell/title": [ { "command": "r.interactive.reuseCell", - "when": "notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", + "when": "!r.webExtension && notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", "group": "inline/rInteractive@0" }, { "command": "r.interactive.copyCell", - "when": "notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", + "when": "!r.webExtension && notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", "group": "inline/rInteractive@1" }, { "command": "r.interactive.source", - "when": "notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", + "when": "!r.webExtension && notebookType == interactive && notebookKernel =~ /^REditorSupport[.]r\\/r-/i", "group": "inline/rInteractive@2" } ] @@ -2406,7 +2528,9 @@ "markdownDescription": "Path to a custom CSS file to be used when `#r.plot.defaults.colorTheme#` is `vscode`. Replaces the default CSS overwrites!" }, "r.interactive.executionTarget": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "string", "enum": [ "auto", @@ -2417,7 +2541,9 @@ "description": "Execution target for R source commands. Auto uses the selected Interactive session or R terminal and offers a target chooser when none is available. Use Terminal for R Execution switches back to terminal routing." }, "r.interactive.supervision": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "string", "ignoreSync": true, "enum": [ @@ -2430,14 +2556,18 @@ "description": "Independent session supervision. Auto prefers tmux on Linux when available, otherwise uses a detached process; macOS and Windows use a detached process. Explicit tmux/systemd selections require their executables on the R host. Detached processes survive editor reload/exit, but host logout policies may stop them. Changes apply to new or restarted sessions." }, "r.interactive.nodePath": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "string", "ignoreSync": true, "default": "", "description": "Optional standalone Node.js 18+ executable on the R host for persistent session agents. Empty uses VS Code's runtime automatically (VS Code Server on remote hosts). Set an executable name on PATH or a path if the automatic runtime is unavailable in a compatible IDE; supports ~ and ${userHome}/${workspaceFolder}. Changes apply to new or restarted sessions." }, "r.interactive.arfPath": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "string", "scope": "machine-overridable", "ignoreSync": true, @@ -2445,14 +2575,18 @@ "description": "arf executable required for managed headless Interactive sessions and for listing running arf sessions to connect to, resolved on the R host. Listing uses the extension host's environment: if arf runs with a custom ARF_IPC_SESSIONS_DIR, set the same absolute path for the extension host. On a remote host, set this in the remote or folder settings; local user settings do not apply there. Use an executable name on PATH or a path (supports ~ and ${userHome}/${workspaceFolder}). The executable must be arf itself or a script that replaces itself with arf using exec; a launcher that starts arf as another process is not supported, and managed sessions refuse it. Ordinary R terminals do not require arf; if unavailable, the Interactive provider picker offers configuration." }, "r.interactive.storagePath": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "string", "ignoreSync": true, "default": "", "description": "Absolute, writable path on the R host for persistent Interactive sessions. Empty uses $XDG_STATE_HOME/vscode-r/interactive when set, otherwise ~/Library/Application Support/vscode-r/interactive on macOS or ~/.local/state/vscode-r/interactive on Linux. Windows uses %LOCALAPPDATA%/vscode-r/interactive and inherits its existing ACL. Securing a custom or shared storage location is your responsibility. Existing macOS registries at the Linux-style path are reused. Reload VS Code after changing this setting." }, "r.interactive.plotBackend": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "string", "ignoreSync": true, "enum": [ @@ -2464,21 +2598,33 @@ "description": "Interactive graphics provider. The jgd backend uses a separate R process with systemfonts to measure text while the editor is disconnected." }, "r.interactive.tableView": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "string", - "enum": ["table", "text"], - "enumDescriptions": ["Show a paged table preview.", "Show the table's ordinary R printout."], + "enum": [ + "table", + "text" + ], + "enumDescriptions": [ + "Show a paged table preview.", + "Show the table's ordinary R printout." + ], "default": "table", "description": "Default presentation for Interactive table outputs. Each output can switch between table and printed views without rerunning R. Printed snapshots require a session started with the current extension build." }, "r.interactive.restore": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "boolean", "default": true, "description": "Automatically reconnect the workspace’s Interactive sessions when R features are used." }, "r.interactive.historyLimit": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "integer", "minimum": 1, "maximum": 1000, @@ -2486,7 +2632,9 @@ "description": "Recent executions and plots restored in an Interactive window." }, "r.interactive.maxOutputSizeMiB": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "number", "ignoreSync": true, "minimum": 0.0625, @@ -2495,7 +2643,9 @@ "description": "Maximum retained console text output per execution, in MiB (1 MiB = 1,048,576 bytes). Excess output is drained and reported as truncated. Rich outputs have separate limits. Changes apply to new or restarted sessions." }, "r.interactive.maxJournalSizeMiB": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "number", "ignoreSync": true, "minimum": 8, @@ -2504,7 +2654,9 @@ "description": "Approximate retained output journal limit per R generation, in MiB (1 MiB = 1,048,576 bytes). Old output is removed when journal segments rotate, roughly every 4 MiB. Earlier generations and execution records are retained separately. Changes apply to new or restarted sessions." }, "r.interactive.maxAssetSizeMiB": { - "tags": ["experimental"], + "tags": [ + "experimental" + ], "type": "number", "ignoreSync": true, "default": 1024, @@ -2621,6 +2773,7 @@ "test": "pnpm run test:node && pnpm run test:extension", "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:activation": "node --test scripts/activation-environment.test.cjs && node scripts/test-activation.cjs", "lint": "oxlint src", "format": "oxfmt .", @@ -2692,6 +2845,10 @@ "r.interactive.arfPath", "r.interactive.storagePath" ] + }, + "virtualWorkspaces": { + "supported": "limited", + "description": "webR supports editing open R documents and running code in a browser session. Native R tools require a workspace extension host." } } } diff --git a/src/interactive/notebook.ts b/src/interactive/notebook.ts index dec3bfe06..a504082b0 100644 --- a/src/interactive/notebook.ts +++ b/src/interactive/notebook.ts @@ -1,5 +1,21 @@ import * as vscode from 'vscode'; +const encoder = new TextEncoder(); +const decoder = new TextDecoder('utf-8', { ignoreBOM: true }); + +function decodeBase64(encoded: string): Uint8Array { + return Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0)); +} + +function encodeBase64(bytes: Uint8Array): string { + // Spread in chunks so a large plot does not exceed the JS argument limit. + const parts: string[] = []; + for (let i = 0; i < bytes.length; i += 32768) { + parts.push(String.fromCharCode(...bytes.subarray(i, i + 32768))); + } + return btoa(parts.join('')); +} + interface SavedCell { kind: vscode.NotebookCellKind; value: string; @@ -69,7 +85,7 @@ export class InteractiveSerializer implements vscode.NotebookSerializer { { output_type: 'stream', name: stream.mime.endsWith('stderr') ? 'stderr' : 'stdout', - text: Buffer.from(stream.data).toString(), + text: decoder.decode(stream.data), }, ]; } @@ -77,7 +93,7 @@ export class InteractiveSerializer implements vscode.NotebookSerializer { (item) => item.mime === 'application/vnd.code.notebook.error', ); if (error) { - const value = JSON.parse(Buffer.from(error.data).toString()) as { + const value = JSON.parse(decoder.decode(error.data)) as { name: string; message: string; stack?: string; @@ -94,7 +110,7 @@ export class InteractiveSerializer implements vscode.NotebookSerializer { const custom = output.items.find((item) => item.mime === DISPLAY_MIME); const display = custom && - (JSON.parse(Buffer.from(custom.data).toString()) as + (JSON.parse(decoder.decode(custom.data)) as | Record | undefined); if (display?.kind === 'plot' && Array.isArray(display.pages)) { @@ -104,19 +120,16 @@ export class InteractiveSerializer implements vscode.NotebookSerializer { 'text/plain': `R plot ${index + 1} of ${(display.pages as unknown[]).length}`, }; if (typeof page.svgData === 'string') { - mime['image/svg+xml'] = Buffer.from( - page.svgData, - 'base64', - ).toString('utf8'); + mime['image/svg+xml'] = decoder.decode( + decodeBase64(page.svgData), + ); } else if ( typeof page.imageData === 'string' && typeof page.mime === 'string' ) { mime[page.mime] = page.mime === 'image/svg+xml' - ? Buffer.from(page.imageData, 'base64').toString( - 'utf8', - ) + ? decoder.decode(decodeBase64(page.imageData)) : page.imageData; } return { @@ -132,16 +145,16 @@ export class InteractiveSerializer implements vscode.NotebookSerializer { if (item.mime === DISPLAY_MIME) { continue; } - mime[item.mime] = Buffer.from(item.data).toString( - /^image\/(png|jpeg|gif)$/.test(item.mime) ? 'base64' : 'utf8', - ); + mime[item.mime] = /^image\/(png|jpeg|gif)$/.test(item.mime) + ? encodeBase64(item.data) + : decoder.decode(item.data); } return [{ output_type: 'display_data', data: mime, metadata: {} }]; }), } : {}), })); - return Buffer.from( + return encoder.encode( JSON.stringify( { nbformat: 4, @@ -162,7 +175,7 @@ export class InteractiveSerializer implements vscode.NotebookSerializer { if (!content.length) { return new vscode.NotebookData([]); } - const saved = JSON.parse(Buffer.from(content).toString('utf8')) as { + const saved = JSON.parse(decoder.decode(content)) as { version: number; metadata: Record; cells: SavedCell[]; @@ -180,7 +193,7 @@ export class InteractiveSerializer implements vscode.NotebookSerializer { output.items.map( (item) => new vscode.NotebookCellOutputItem( - Buffer.from(item.data, 'base64'), + decodeBase64(item.data), item.mime, ), ), @@ -206,7 +219,7 @@ export class InteractiveSerializer implements vscode.NotebookSerializer { items: output.items.map((item) => { let bytes = item.data; if (item.mime === DISPLAY_MIME) { - const display = JSON.parse(Buffer.from(bytes).toString('utf8')) as Record< + const display = JSON.parse(decoder.decode(bytes)) as Record< string, unknown >; @@ -220,13 +233,13 @@ export class InteractiveSerializer implements vscode.NotebookSerializer { delete page.url; page.connected = false; } - bytes = Buffer.from(JSON.stringify(display)); + bytes = encoder.encode(JSON.stringify(display)); } - return { mime: item.mime, data: Buffer.from(bytes).toString('base64') }; + return { mime: item.mime, data: encodeBase64(bytes) }; }), })), })); - return Buffer.from( + return encoder.encode( JSON.stringify({ version: 1, metadata: data.metadata ?? {}, cells }, null, 2), ); } diff --git a/src/rTerminal.ts b/src/rTerminal.ts index 2ec31d7a9..14c0217b6 100644 --- a/src/rTerminal.ts +++ b/src/rTerminal.ts @@ -11,7 +11,7 @@ import * as vscode from 'vscode'; import { extensionContext, globalPlotManager } from './extension'; import * as util from './util'; import * as selection from './selection'; -import { getSelection } from './selection'; +import { getSelection, moveAfterSelection } from './selection'; import { cleanupTerminalBinding, createSessionDiscoveryFile, @@ -599,29 +599,8 @@ export async function runSelectionInTerm(moveCursor: boolean, useRepl = true): P return; } } - // Cancellation must preserve both the selected code and its cursor position. - if (vscode.window.activeTextEditor !== textEditor) { - return; - } - if (moveCursor && selection.linesDownToMoveCursor > 0) { - if (!textEditor) { - return; - } - const lineCount = textEditor.document.lineCount; - if (selection.linesDownToMoveCursor + textEditor.selection.end.line === lineCount) { - const endPos = new vscode.Position( - lineCount, - textEditor.document.lineAt(lineCount - 1).text.length, - ); - await textEditor.edit((e) => e.insert(endPos, '\n')); - } - await vscode.commands.executeCommand('cursorMove', { - to: 'down', - value: selection.linesDownToMoveCursor, - }); - await vscode.commands.executeCommand('cursorMove', { - to: 'wrappedLineFirstNonWhitespaceCharacter', - }); + if (moveCursor && textEditor) { + await moveAfterSelection(textEditor, selection); } } diff --git a/src/rmarkdown/chunks.ts b/src/rmarkdown/chunks.ts index 283f3e602..d72de5258 100644 --- a/src/rmarkdown/chunks.ts +++ b/src/rmarkdown/chunks.ts @@ -1,6 +1,4 @@ import * as vscode from 'vscode'; -import { config } from '../util'; -import { runChunksInTerm, runSource } from '../rTerminal'; export function isRDocument(document: vscode.TextDocument) { return document.languageId === 'r'; @@ -240,158 +238,175 @@ export function isWithinChunk(chunk: RMarkdownChunk, line: number = _getStartLin return line >= chunk.startLine && line <= chunk.endLine; } -export async function runCurrentChunk( - chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine(), -): Promise { - const currentChunk = getCurrentChunk(chunks, line); - if (currentChunk) { - await runChunksInTerm([currentChunk.codeRange]); +export function createChunkCommands( + runChunksInTerm: (ranges: vscode.Range[]) => Promise, + runSource: (echo: boolean) => Promise, +) { + async function runCurrentChunk( + chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine(), + ): Promise { + const currentChunk = getCurrentChunk(chunks, line); + if (currentChunk) { + await runChunksInTerm([currentChunk.codeRange]); + } } -} -export function runSourceWithEcho(options?: { runChunkAtCursor?: boolean }): Promise { - const editor = vscode.window.activeTextEditor; - if (options?.runChunkAtCursor === true && editor && isRDocument(editor.document)) { - const line = editor.selection.active.line; - const chunk = getCurrentChunk(getChunks(editor.document), line); - if (chunk && isWithinChunk(chunk, line)) { - return runChunksInTerm([chunk.codeRange]); + function runSourceWithEcho(options?: { runChunkAtCursor?: boolean }): Promise { + const editor = vscode.window.activeTextEditor; + if (options?.runChunkAtCursor === true && editor && isRDocument(editor.document)) { + const line = editor.selection.active.line; + const chunk = getCurrentChunk(getChunks(editor.document), line); + if (chunk && isWithinChunk(chunk, line)) { + return runChunksInTerm([chunk.codeRange]); + } } + return runSource(true); } - return runSource(true); -} -export async function runCurrentChunkAndMove( - chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine(), -): Promise { - const currentChunk = getCurrentChunk(chunks, line); - if (currentChunk) { - await runChunksInTerm([currentChunk.codeRange]); - } - const nextChunk = getNextChunk(chunks, line); - if (nextChunk) { - void goToChunk(nextChunk); + async function runCurrentChunkAndMove( + chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine(), + ): Promise { + const currentChunk = getCurrentChunk(chunks, line); + if (currentChunk) { + await runChunksInTerm([currentChunk.codeRange]); + } + const nextChunk = getNextChunk(chunks, line); + if (nextChunk) { + void goToChunk(nextChunk); + } } -} -export async function runPreviousChunk( - chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine(), -): Promise { - const currentChunk = getCurrentChunk(chunks, line); - const previousChunk = getPreviousChunk(chunks, line); + async function runPreviousChunk( + chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine(), + ): Promise { + const currentChunk = getCurrentChunk(chunks, line); + const previousChunk = getPreviousChunk(chunks, line); - // Case: cursor is below the last chunk, run last chunk - if (currentChunk && line > currentChunk.endLine) { - await runChunksInTerm([currentChunk.codeRange]); - // Case: currentChunk is not the first chunk, so run previousChunk - } else if (previousChunk && previousChunk !== currentChunk) { - await runChunksInTerm([previousChunk.codeRange]); + // Case: cursor is below the last chunk, run last chunk + if (currentChunk && line > currentChunk.endLine) { + await runChunksInTerm([currentChunk.codeRange]); + // Case: currentChunk is not the first chunk, so run previousChunk + } else if (previousChunk && previousChunk !== currentChunk) { + await runChunksInTerm([previousChunk.codeRange]); + } } -} -export async function runNextChunk( - chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine(), -): Promise { - const currentChunk = getCurrentChunk(chunks, line); - const nextChunk = getNextChunk(chunks, line); + async function runNextChunk( + chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine(), + ): Promise { + const currentChunk = getCurrentChunk(chunks, line); + const nextChunk = getNextChunk(chunks, line); - // Case: currentChunk is not the last chunk, so run nextChunk - if (nextChunk && nextChunk !== currentChunk) { - await runChunksInTerm([nextChunk.codeRange]); + // Case: currentChunk is not the last chunk, so run nextChunk + if (nextChunk && nextChunk !== currentChunk) { + await runChunksInTerm([nextChunk.codeRange]); + } } -} -export async function runAboveChunks( - chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine(), -): Promise { - const currentChunk = getCurrentChunk(chunks, line); - const previousChunk = getPreviousChunk(chunks, line); - if (!currentChunk || !previousChunk) { - return; - } - const firstChunkId = 1; - const previousChunkId = previousChunk.id; + async function runAboveChunks( + chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine(), + ): Promise { + const currentChunk = getCurrentChunk(chunks, line); + const previousChunk = getPreviousChunk(chunks, line); + if (!currentChunk || !previousChunk) { + return; + } + const firstChunkId = 1; + const previousChunkId = previousChunk.id; - const codeRanges: vscode.Range[] = []; + const codeRanges: vscode.Range[] = []; - // Only do something if current chunk is not the first chunk - if (currentChunk.id > 1) { - for (let i = firstChunkId; i <= previousChunkId; i++) { - const chunk = chunks.find((e) => e.id === i); - if (chunk?.eval) { - codeRanges.push(chunk.codeRange); + // Only do something if current chunk is not the first chunk + if (currentChunk.id > 1) { + for (let i = firstChunkId; i <= previousChunkId; i++) { + const chunk = chunks.find((e) => e.id === i); + if (chunk?.eval) { + codeRanges.push(chunk.codeRange); + } } + await runChunksInTerm(codeRanges); } - await runChunksInTerm(codeRanges); } -} -export async function runBelowChunks( - chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine(), -): Promise { - const currentChunk = getCurrentChunk(chunks, line); - const nextChunk = getNextChunk(chunks, line); - if (!currentChunk || !nextChunk) { - return; - } - const nextChunkId = nextChunk.id; - const lastChunkId = chunks.length; + async function runBelowChunks( + chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine(), + ): Promise { + const currentChunk = getCurrentChunk(chunks, line); + const nextChunk = getNextChunk(chunks, line); + if (!currentChunk || !nextChunk) { + return; + } + const nextChunkId = nextChunk.id; + const lastChunkId = chunks.length; - const codeRanges: vscode.Range[] = []; + const codeRanges: vscode.Range[] = []; - // Only do something if current chunk is not the last chunk - if (currentChunk.id < lastChunkId) { - for (let i = nextChunkId; i <= lastChunkId; i++) { - const chunk = chunks.find((e) => e.id === i); - if (chunk?.eval) { - codeRanges.push(chunk.codeRange); + // Only do something if current chunk is not the last chunk + if (currentChunk.id < lastChunkId) { + for (let i = nextChunkId; i <= lastChunkId; i++) { + const chunk = chunks.find((e) => e.id === i); + if (chunk?.eval) { + codeRanges.push(chunk.codeRange); + } } + await runChunksInTerm(codeRanges); } - await runChunksInTerm(codeRanges); } -} -export async function runCurrentAndBelowChunks( - chunks: RMarkdownChunk[] = _getChunks(), - line: number = _getStartLine(), -): Promise { - const currentChunk = getCurrentChunk(chunks, line); - if (!currentChunk) { - return; - } - const currentChunkId = currentChunk.id; - const lastChunkId = chunks.length; + async function runCurrentAndBelowChunks( + chunks: RMarkdownChunk[] = _getChunks(), + line: number = _getStartLine(), + ): Promise { + const currentChunk = getCurrentChunk(chunks, line); + if (!currentChunk) { + return; + } + const currentChunkId = currentChunk.id; + const lastChunkId = chunks.length; - const codeRanges: vscode.Range[] = []; + const codeRanges: vscode.Range[] = []; - for (let i = currentChunkId; i <= lastChunkId; i++) { - const chunk = chunks.find((e) => e.id === i); - if (chunk) { - codeRanges.push(chunk.codeRange); + for (let i = currentChunkId; i <= lastChunkId; i++) { + const chunk = chunks.find((e) => e.id === i); + if (chunk) { + codeRanges.push(chunk.codeRange); + } } + await runChunksInTerm(codeRanges); } - await runChunksInTerm(codeRanges); -} -export async function runAllChunks(chunks: RMarkdownChunk[] = _getChunks()): Promise { - const firstChunkId = 1; - const lastChunkId = chunks.length; + async function runAllChunks(chunks: RMarkdownChunk[] = _getChunks()): Promise { + const firstChunkId = 1; + const lastChunkId = chunks.length; - const codeRanges: vscode.Range[] = []; + const codeRanges: vscode.Range[] = []; - for (let i = firstChunkId; i <= lastChunkId; i++) { - const chunk = chunks.find((e) => e.id === i); - if (chunk?.eval) { - codeRanges.push(chunk.codeRange); + for (let i = firstChunkId; i <= lastChunkId; i++) { + const chunk = chunks.find((e) => e.id === i); + if (chunk?.eval) { + codeRanges.push(chunk.codeRange); + } } + await runChunksInTerm(codeRanges); } - await runChunksInTerm(codeRanges); + + return { + runCurrentChunk, + runSourceWithEcho, + runCurrentChunkAndMove, + runPreviousChunk, + runNextChunk, + runAboveChunks, + runBelowChunks, + runCurrentAndBelowChunks, + runAllChunks, + }; } async function goToChunk(chunk: RMarkdownChunk) { @@ -448,7 +463,9 @@ export function getCodeLenses( chunks: RMarkdownChunk[], token: vscode.CancellationToken, ): vscode.CodeLens[] { - const enabledCodeLens = config().get('rmarkdown.enableCodeLens'); + const enabledCodeLens = vscode.workspace + .getConfiguration('r') + .get('rmarkdown.enableCodeLens'); if (enabledCodeLens === false) { return []; } @@ -531,7 +548,9 @@ export function getCodeLenses( // For default options, both options and sort order are based on options specified in package.json. // For user-specified options, both options and sort order are based on options specified in settings UI or settings.json. - const rmdCodeLensCommands: string[] = config().get('rmarkdown.codeLensCommands', []); + const rmdCodeLensCommands: string[] = vscode.workspace + .getConfiguration('r') + .get('rmarkdown.codeLensCommands', []); codeLenses = codeLenses .filter((e) => e.command && rmdCodeLensCommands.includes(e.command.command)) .sort(function (a, b) { diff --git a/src/rmarkdown/index.ts b/src/rmarkdown/index.ts index fdf2da540..90f40a9d0 100644 --- a/src/rmarkdown/index.ts +++ b/src/rmarkdown/index.ts @@ -1,6 +1,8 @@ import * as vscode from 'vscode'; import { config } from '../util'; +import { runChunksInTerm, runSource } from '../rTerminal'; import { + createChunkCommands, shouldDisplayChunkOptions, getChunks, getCurrentChunk, @@ -13,8 +15,9 @@ import { export { knitDir, RMarkdownKnitManager } from './knit'; export { RMarkdownPreviewManager } from './preview'; export { newDraft } from './draft'; -export { - getChunks, +export { getChunks, goToPreviousChunk, goToNextChunk, selectCurrentChunk } from './chunks'; + +export const { runCurrentChunk, runSourceWithEcho, runCurrentChunkAndMove, @@ -24,10 +27,7 @@ export { runBelowChunks, runCurrentAndBelowChunks, runAllChunks, - goToPreviousChunk, - goToNextChunk, - selectCurrentChunk, -} from './chunks'; +} = createChunkCommands(runChunksInTerm, runSource); export class RMarkdownCodeLensProvider implements vscode.CodeLensProvider { private _onDidChangeCodeLenses: vscode.EventEmitter = new vscode.EventEmitter(); diff --git a/src/selection.ts b/src/selection.ts index d171aec6c..15ec51ef7 100644 --- a/src/selection.ts +++ b/src/selection.ts @@ -1,9 +1,8 @@ 'use strict'; -import { Position, Range, window } from 'vscode'; +import { commands, Position, Range, TextEditor, window, workspace } from 'vscode'; import { LineCache } from './lineCache'; -import { config } from './util'; export function getWordOrSelection(): string | undefined { const textEditor = window.activeTextEditor; @@ -80,7 +79,7 @@ export function getSelection(): RSelection | undefined { let selectedText = currentDocument.getText(selection.range).trim(); - if (config().get('removeLeadingComments')) { + if (workspace.getConfiguration('r').get('removeLeadingComments')) { selectedText = removeLeadingComments(selectedText); } @@ -89,6 +88,23 @@ export function getSelection(): RSelection | undefined { return selection; } +/** Advance only the original editor after the submission has been accepted. */ +export async function moveAfterSelection(editor: TextEditor, selection: RSelection): Promise { + if (window.activeTextEditor !== editor || selection.linesDownToMoveCursor <= 0) { + return; + } + const lineCount = editor.document.lineCount; + if (selection.linesDownToMoveCursor + editor.selection.end.line === lineCount) { + const last = editor.document.lineAt(lineCount - 1).range.end; + await editor.edit((edit) => edit.insert(last, '\n')); + } + await commands.executeCommand('cursorMove', { + to: 'down', + value: selection.linesDownToMoveCursor, + }); + await commands.executeCommand('cursorMove', { to: 'wrappedLineFirstNonWhitespaceCharacter' }); +} + /** * Like vscode's Position class, but allows negative values. */ diff --git a/src/test/plot/plotCommands.test.ts b/src/test/plot/plotCommands.test.ts index cde69c62e..e9d41628b 100644 --- a/src/test/plot/plotCommands.test.ts +++ b/src/test/plot/plotCommands.test.ts @@ -59,6 +59,7 @@ suite('Contextual plot commands', () => { category: 'R Plot', command: 'r.plot.showViewers', icon: '$(versions)', + enablement: '!r.webExtension', }); assert.ok( !manifest.contributes.menus.commandPalette.some( diff --git a/src/test/suite/chunks.test.ts b/src/test/suite/chunks.test.ts index 851b891f5..88155ca06 100644 --- a/src/test/suite/chunks.test.ts +++ b/src/test/suite/chunks.test.ts @@ -2,7 +2,8 @@ import * as assert from 'assert'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; import * as executionTarget from '../../interactive/executionTarget'; -import { getChunks, getCurrentChunk, runSourceWithEcho } from '../../rmarkdown/chunks'; +import { getChunks, getCurrentChunk } from '../../rmarkdown/chunks'; +import { runSourceWithEcho } from '../../rmarkdown'; suite('R code chunk boundaries', () => { async function chunkCode(text: string, language = 'r') { diff --git a/src/test/web/webR.cjs b/src/test/web/webR.cjs new file mode 100644 index 000000000..f9753d8b6 --- /dev/null +++ b/src/test/web/webR.cjs @@ -0,0 +1,131 @@ +const vscode = require('vscode'); + +function assert(condition, message) { + if (!condition) {throw new Error(message);} +} + +async function until(check, message) { + const start = Date.now(); + while (Date.now() - start < 180000) { + const value = await check(); + if (value) {return value;} + await new Promise(resolve => setTimeout(resolve, 200)); + } + throw new Error(message); +} + +// No local paths or platform-specific process APIs are available in a web +// extension host. The provider also exercises read/write to a virtual repository. +function testFiles() { + const encoder = new TextEncoder(); + const files = new Map([ + ['/call.R', encoder.encode('result <- double_it(12)\n')], + ['/helper.R', encoder.encode('helper <- function(x) x + 2\n')], + ['/data.csv', encoder.encode('value\n3\n4\n')], + ]); + const changed = new vscode.EventEmitter(); + const provider = vscode.workspace.registerFileSystemProvider('r-webr-test', { + onDidChangeFile: changed.event, + watch: () => new vscode.Disposable(() => {}), + stat: uri => ({ type: vscode.FileType.File, ctime: 0, mtime: 0, size: files.get(uri.path)?.length ?? 0 }), + readDirectory: () => [], + createDirectory() {}, + delete(uri) { files.delete(uri.path); }, + rename() { throw vscode.FileSystemError.NoPermissions(); }, + readFile(uri) { + const contents = files.get(uri.path); + if (!contents) {throw vscode.FileSystemError.FileNotFound(uri);} + return contents; + }, + writeFile(uri, bytes) { + files.set(uri.path, bytes); + changed.fire([{type: vscode.FileChangeType.Changed, uri}]); + }, + }, { isCaseSensitive: true }); + return { + uri: name => vscode.Uri.from({scheme:'r-webr-test',path:'/'+name}), + dispose() { provider.dispose(); changed.dispose(); }, + }; +} + +async function editor(text, language = 'r') { + const document = await vscode.workspace.openTextDocument({language, content: text}); + return vscode.window.showTextDocument(document); +} + +const command = (id, ...args) => vscode.commands.executeCommand(id, ...args); +const items = cell => cell.outputs.flatMap(out => out.items); +const stdout = cell => items(cell).filter(i => i.mime.endsWith('.stdout')).map(i => new TextDecoder().decode(i.data)).join(''); + +exports.run = async () => { + const files = testFiles(); + try { + const first = (await editor('double_it <- function(x) x * 2\n')).document; + const other = await vscode.workspace.openTextDocument(files.uri('call.R')); + await vscode.window.showTextDocument(other); + await until(async () => { + const defs = await command('vscode.executeDefinitionProvider', other.uri, new vscode.Position(0,14)); + return defs?.some(location => (location.uri ?? location.targetUri).toString() === first.uri.toString() + && (location.range ?? location.targetSelectionRange).start.line === 0); + }, 'Definition did not resolve across the virtual and unsaved documents.'); + + await vscode.window.showTextDocument(first); + const edit = new vscode.WorkspaceEdit(); + edit.replace(first.uri, new vscode.Range(0,0,0,9),'triple_it'); + assert(await vscode.workspace.applyEdit(edit), 'Could not edit R document.'); + await until(async () => { + const symbols = await command('vscode.executeDocumentSymbolProvider', first.uri); + return symbols?.some(symbol => symbol.name === 'triple_it') && !symbols.some(symbol=>symbol.name==='double_it'); + }, 'Outline did not reflect the edit.'); + await command('r.runSource'); + const notebook = vscode.workspace.notebookDocuments.find(doc => doc.notebookType === 'r-interactive'); + assert(notebook?.cellCount === 1,'Run Source did not submit a cell.'); + + const second = await editor('triple_it(21)\nplot(1:3)\n'); + second.selection = new vscode.Selection(new vscode.Position(0,0),second.document.positionAt(second.document.getText().length)); + await command('r.runSelectionRetainCursor'); + assert(notebook.cellCount === 2 && stdout(notebook.cellAt(1)).includes('42'), 'Run Selection did not reuse the R session.'); + assert(items(notebook.cellAt(1)).some(item => item.mime === 'image/png' && item.data[0] === 137 && item.data[1] === 80), 'Missing PNG output.'); + + await command('r.webR.importFiles', [files.uri('helper.R'), files.uri('data.csv')]); + await editor('```{r}\nsource("helper.R")\nanswer <- helper(sum(read.csv("data.csv")$value))\nwriteLines(as.character(answer), "out.txt")\nanswer\n```\n','rmd'); + await command('r.runCurrentChunk'); + assert(stdout(notebook.cellAt(2)).includes('9'), 'Imports or Run Current Chunk failed.'); + await command('r.webR.exportFile','out.txt',files.uri('result.txt')); + assert(new TextDecoder().decode(await vscode.workspace.fs.readFile(files.uri('result.txt'))).trim()==='9','Incorrect exported result.'); + + if (globalThis.crossOriginIsolated && typeof SharedArrayBuffer !== 'undefined') { + const calculating = command('r.runCommand','cat("running\\n"); repeat { Sys.sleep(0.05) }'); + try { + await until(() => notebook.cellCount >= 4 && stdout(notebook.cellAt(3)).includes('running'), 'The long calculation did not start.'); + const outline = await command('vscode.executeDocumentSymbolProvider', first.uri); + assert(outline?.some(symbol => symbol.name === 'triple_it'), 'Language features unavailable while running R.'); + } finally { + await command('r.interactive.interrupt'); + } + await calculating; + await command('r.runCommand','answer'); + assert(stdout(notebook.cellAt(4)).includes('9'), 'Interrupt lost the R environment.'); + } + const savedUri = files.uri('transcript.rnb'); + const snapshot = new TextEncoder().encode(JSON.stringify({version:1,metadata:{},cells:[]})); + await vscode.workspace.fs.writeFile(savedUri,snapshot); + const saved = await vscode.workspace.openNotebookDocument(savedUri); + await vscode.window.showNotebookDocument(saved); + await command('r.runCommand','held_value <- 17; held_value'); + assert(stdout(saved.cellAt(0)).includes('17'), 'Saved notebook computation failed.'); + assert(await saved.save(),'Saving the .rnb transcript failed.'); + await command('workbench.action.closeActiveEditor'); + await until(() => !vscode.window.tabGroups.all.some(group => group.tabs.some(tab => + tab.input instanceof vscode.TabInputNotebook && tab.input.uri.toString() === savedUri.toString())), 'The saved notebook tab did not close.'); + const reopened = await vscode.workspace.openNotebookDocument(savedUri); + await vscode.window.showNotebookDocument(reopened); + assert(stdout(reopened.cellAt(0)).includes('17'), 'Saved notebook lost its transcript.'); + await command('r.runCommand','exists("held_value", inherits = FALSE)'); + assert(stdout(reopened.cellAt(1)).includes('FALSE'), 'Reopening retained stale R state.'); + console.log('Verified webR language features, R Interactive execution, files, and transcript reopening.'); + } finally { + await command('r.interactive.stopAll'); + files.dispose(); + } +}; diff --git a/src/web/extension.ts b/src/web/extension.ts new file mode 100644 index 000000000..d807cc287 --- /dev/null +++ b/src/web/extension.ts @@ -0,0 +1,90 @@ +import * as vscode from 'vscode'; +import { getSelection, moveAfterSelection } from '../selection'; +import { + createChunkCommands, + getChunks, + getCodeLenses, + goToNextChunk, + goToPreviousChunk, + selectCurrentChunk, +} from '../rmarkdown/chunks'; +import { BrowserInteractive } from './interactive'; +import { BrowserLanguageService } from './languageService'; + +export async function activate(context: vscode.ExtensionContext): Promise { + await vscode.commands.executeCommand('setContext', 'r.webExtension', true); + const interactive = new BrowserInteractive(context); + context.subscriptions.push(interactive, new BrowserLanguageService(context.globalStorageUri)); + + const runSource = async () => { + const editor = vscode.window.activeTextEditor; + if (editor) { + await interactive.submit(editor.document.getText()); + } + }; + const runSelection = async (move: boolean) => { + const editor = vscode.window.activeTextEditor; + const selection = getSelection(); + if (!editor || !selection) { + return; + } + await interactive.submit(selection.selectedText); + if (move) { + await moveAfterSelection(editor, selection); + } + }; + const chunks = createChunkCommands(async (ranges) => { + const editor = vscode.window.activeTextEditor; + if (editor) { + await interactive.submit( + ranges + .filter((range) => + getChunks(editor.document).some( + (chunk) => chunk.language === 'r' && chunk.codeRange.isEqual(range), + ), + ) + .map((range) => editor.document.getText(range)) + .join('\n'), + ); + } + }, runSource); + const commands = { + 'r.newFileDocument': async () => + vscode.window.showTextDocument( + await vscode.workspace.openTextDocument({ language: 'r' }), + ), + 'r.runSource': runSource, + 'r.runSourcewithEcho': chunks.runSourceWithEcho, + 'r.runSelection': () => runSelection(true), + 'r.runSelectionRetainCursor': () => runSelection(false), + 'r.runCommand': (code: string) => interactive.submit(code), + 'r.runCurrentChunk': chunks.runCurrentChunk, + 'r.runCurrentChunkAndMove': chunks.runCurrentChunkAndMove, + 'r.runPreviousChunk': chunks.runPreviousChunk, + 'r.runNextChunk': chunks.runNextChunk, + 'r.runAboveChunks': chunks.runAboveChunks, + 'r.runBelowChunks': chunks.runBelowChunks, + 'r.runCurrentAndBelowChunks': chunks.runCurrentAndBelowChunks, + 'r.runAllChunks': chunks.runAllChunks, + 'r.goToPreviousChunk': goToPreviousChunk, + 'r.goToNextChunk': goToNextChunk, + 'r.selectCurrentChunk': selectCurrentChunk, + 'r.interactive.new': () => interactive.open(true), + 'r.interactive.open': () => interactive.open(), + 'r.interactive.interrupt': () => interactive.interrupt(), + 'r.interactive.stop': () => interactive.stop(), + 'r.interactive.stopAll': () => interactive.stopAll(), + 'r.interactive.restart': () => interactive.stop(), + 'r.interactive.sessionActions': () => interactive.actions(), + 'r.webR.importFiles': (uris?: vscode.Uri[]) => interactive.import(uris), + 'r.webR.exportFile': (source?: string, uri?: vscode.Uri) => interactive.export(source, uri), + }; + for (const [id, handler] of Object.entries(commands)) { + context.subscriptions.push(vscode.commands.registerCommand(id, handler)); + } + context.subscriptions.push( + vscode.languages.registerCodeLensProvider([{ language: 'r' }, { language: 'rmd' }], { + provideCodeLenses: (doc, token) => getCodeLenses(getChunks(doc), token), + }), + ); +} diff --git a/src/web/files.ts b/src/web/files.ts new file mode 100644 index 000000000..d65a3fd05 --- /dev/null +++ b/src/web/files.ts @@ -0,0 +1,47 @@ +import * as vscode from 'vscode'; +import type { WebR } from 'webr'; + +// An imported helper and its data retain their relative paths in the session. +export const sessionDirectory = '/workspace'; + +function segments(path: string): string[] { + const parts = path.split('/'); + if ( + !path || + parts.some((p) => !p || p === '.' || p === '..' || p.includes('\\') || p.includes('\0')) + ) { + throw new Error('Use a relative path within the webR session directory.'); + } + return parts; +} + +export async function importFiles(runtime: WebR, files: readonly vscode.Uri[]): 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; + for (const part of parts.slice(0, -1)) { + directory += '/' + part; + if (!(await runtime.FS.analyzePath(directory)).exists) { + await runtime.FS.mkdir(directory); + } + } + const data = await vscode.workspace.fs.readFile(file); + await runtime.FS.writeFile(sessionDirectory + '/' + parts.join('/'), data); + } +} + +export async function exportFile( + runtime: WebR, + source: string, + destination: vscode.Uri, +): 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('/')); + await vscode.workspace.fs.writeFile(destination, data); +} diff --git a/src/web/interactive.ts b/src/web/interactive.ts new file mode 100644 index 000000000..c650093f6 --- /dev/null +++ b/src/web/interactive.ts @@ -0,0 +1,266 @@ +import * as vscode from 'vscode'; +import { InteractiveSerializer } from '../interactive/notebook'; +import { BrowserSession } from './session'; +import { exportFile, importFiles } from './files'; + +const notebookType = 'r-interactive'; + +function openTabFor(uri: string): boolean { + return vscode.window.tabGroups.all.some((group) => + group.tabs.some( + (tab) => + tab.input instanceof vscode.TabInputNotebook && tab.input.uri.toString() === uri, + ), + ); +} + +export class BrowserInteractive implements vscode.Disposable { + private readonly controller = vscode.notebooks.createNotebookController( + 'r-webr', + notebookType, + 'R (webR)', + ); + private readonly sessions = new Map(); + private readonly registrations: vscode.Disposable[]; + private last?: vscode.NotebookDocument; + private opening?: Promise; + private disposed = false; + + constructor(private readonly context: vscode.ExtensionContext) { + this.controller.supportedLanguages = ['r']; + this.controller.supportsExecutionOrder = true; + this.controller.description = 'R in this browser'; + this.controller.executeHandler = async (cells, doc) => { + const session = this.session(doc); + await session.run(async () => { + for (const cell of cells) { + if (!cell.document.isClosed) { + await session.evaluate(cell); + } + } + }); + }; + this.controller.interruptHandler = (doc) => this.interrupt(doc); + this.registrations = [ + this.controller, + vscode.workspace.registerNotebookSerializer(notebookType, new InteractiveSerializer(), { + transientOutputs: false, + }), + vscode.window.onDidChangeActiveNotebookEditor((editor) => { + if (editor?.notebook.notebookType === notebookType) { + this.last = editor.notebook; + } + }), + vscode.workspace.onDidCloseNotebookDocument((doc) => this.forget(doc)), + vscode.window.tabGroups.onDidChangeTabs((event) => { + // The web workbench can cache a notebook model after its last tab + // closes. Release its worker even when didCloseDocument is delayed. + for (const tab of event.closed) { + if ( + !(tab.input instanceof vscode.TabInputNotebook) || + tab.input.notebookType !== notebookType + ) { + continue; + } + const uri = tab.input.uri.toString(); + if (openTabFor(uri)) { + continue; + } + const doc = vscode.workspace.notebookDocuments.find( + (d) => d.uri.toString() === uri, + ); + if (doc) { + this.forget(doc); + } + } + }), + ]; + } + + private forget(doc: vscode.NotebookDocument): void { + this.stop(doc); + if (this.last === doc) { + this.last = undefined; + } + } + + private target(): vscode.NotebookDocument | undefined { + const active = vscode.window.activeNotebookEditor?.notebook; + return active?.notebookType === notebookType + ? active + : (this.last ?? + vscode.workspace.notebookDocuments.find( + (d) => d.notebookType === notebookType && openTabFor(d.uri.toString()), + )); + } + + private session(doc: vscode.NotebookDocument): BrowserSession { + if (this.disposed || doc.isClosed) { + throw new Error('The R Interactive notebook is closed.'); + } + let session = this.sessions.get(doc); + if (!session) { + session = new BrowserSession(this.controller); + this.sessions.set(doc, session); + } + return session; + } + + private async reveal(doc: vscode.NotebookDocument, preserveFocus: boolean) { + if (this.disposed || doc.isClosed) { + throw new Error('The R Interactive notebook is closed.'); + } + this.last = doc; + this.controller.updateNotebookAffinity(doc, vscode.NotebookControllerAffinity.Preferred); + const visible = vscode.window.visibleNotebookEditors.find( + (editor) => editor.notebook === doc, + ); + const editor = + visible && preserveFocus + ? visible + : await vscode.window.showNotebookDocument(doc, { + viewColumn: + visible?.viewColumn ?? + (preserveFocus ? vscode.ViewColumn.Beside : vscode.ViewColumn.Active), + preserveFocus, + }); + await vscode.commands.executeCommand('notebook.selectKernel', { + id: this.controller.id, + extension: this.context.extension.id, + notebookEditor: editor, + }); + return doc; + } + + open(create = false, preserveFocus = false): Promise { + if (this.opening) { + return this.opening; + } + const target = create ? undefined : this.target(); + this.opening = (async () => { + const doc = + target ?? + (await vscode.workspace.openNotebookDocument( + notebookType, + new vscode.NotebookData([]), + )); + return this.reveal(doc, preserveFocus); + })().finally(() => { + this.opening = undefined; + }); + return this.opening; + } + + async submit(code: string): Promise { + if (!code.trim()) { + return; + } + const doc = await this.open(false, true); + const session = this.session(doc); + await session.run(async () => { + const index = doc.cellCount; + const edit = new vscode.WorkspaceEdit(); + edit.set(doc.uri, [ + vscode.NotebookEdit.insertCells(index, [ + new vscode.NotebookCellData(vscode.NotebookCellKind.Code, code, 'r'), + ]), + ]); + if (!(await vscode.workspace.applyEdit(edit))) { + throw new Error('Could not add code to the R Interactive notebook.'); + } + // The user may edit or move cells while VS Code applies our edit. + const cell = index < doc.cellCount ? doc.cellAt(index) : undefined; + if ( + !cell || + cell.document.getText().replace(/\r\n/g, '\n') !== code.replace(/\r\n/g, '\n') + ) { + throw new Error('The submitted cell changed before it could run.'); + } + await session.evaluate(cell); + }); + } + + async import(uris?: readonly vscode.Uri[]): Promise { + const files = + uris ?? + (await vscode.window.showOpenDialog({ + canSelectMany: true, + openLabel: 'Import into webR', + defaultUri: vscode.workspace.workspaceFolders?.[0]?.uri, + })); + if (!files?.length) { + return; + } + const doc = await this.open(false, true); + await this.session(doc).files((runtime) => importFiles(runtime, files)); + } + + async export(source?: string, destination?: vscode.Uri): Promise { + const doc = this.target(); + if (!doc) { + return; + } + const name = + source ?? + (await vscode.window.showInputBox({ + prompt: 'File to export from the webR session directory', + placeHolder: 'results/model.csv', + })); + if (!name) { + return; + } + const folder = vscode.workspace.workspaceFolders?.[0]?.uri; + const target = + destination ?? + (await vscode.window.showSaveDialog({ + saveLabel: 'Export from webR', + defaultUri: folder + ? vscode.Uri.joinPath(folder, name.split('/').at(-1) || 'output') + : undefined, + })); + if (target) { + await this.session(doc).files((runtime) => exportFile(runtime, name, target)); + } + } + + async interrupt(doc = this.target()): Promise { + if (doc) { + await this.sessions.get(doc)?.interrupt(() => this.stop(doc)); + } + } + + stop(doc = this.target()): void { + if (!doc) { + return; + } + this.sessions.get(doc)?.dispose(); + this.sessions.delete(doc); + } + + stopAll(): void { + for (const doc of this.sessions.keys()) { + this.stop(doc); + } + } + + async actions(): Promise { + const actions = [ + { label: 'Import files into webR…', run: () => this.import() }, + { label: 'Export a file from webR…', run: () => this.export() }, + { label: 'Interrupt calculation', run: () => this.interrupt() }, + { label: 'Restart webR session', run: () => this.stop() }, + ]; + const selected = await vscode.window.showQuickPick(actions, { + title: 'R Interactive (webR)', + }); + await Promise.resolve(selected?.run()); + } + + dispose(): void { + this.disposed = true; + this.stopAll(); + for (const entry of this.registrations) { + entry.dispose(); + } + } +} diff --git a/src/web/languageService.ts b/src/web/languageService.ts new file mode 100644 index 000000000..e3a85d6d1 --- /dev/null +++ b/src/web/languageService.ts @@ -0,0 +1,180 @@ +import * as vscode from 'vscode'; +import { + CloseAction, + ErrorAction, + LanguageClient, + RevealOutputChannelOn, + State, +} from 'vscode-languageclient/browser'; +import { createWebRLanguageSession, type WebRLanguageSession } from '../webr/languageSession'; +import { createWebRMessageTransports } from '../webr/messageTransports'; +import { cachedWebRAssets } from '../webr/assetCache'; +import { WEBR_BASE_URL } from '../webr/runtime'; + +/** The service provides one retry action for startup and worker failures. */ +class WorkerLanguageClient extends LanguageClient { + override error( + message: string, + data?: unknown, + showNotification: boolean | 'force' = true, + ): void { + super.error(message, data, this.state === State.Running ? showNotification : false); + } +} + +export class BrowserLanguageService implements vscode.Disposable { + private readonly output = vscode.window.createOutputChannel('R Language Server', { log: true }); + private readonly listeners: vscode.Disposable[]; + private current?: { + client: LanguageClient; + abort: AbortController; + session?: WebRLanguageSession; + }; + private stopped = false; + private stopping = Promise.resolve(); + private nativePreferenceReported = false; + + constructor(private readonly storage: vscode.Uri) { + this.listeners = [ + vscode.workspace.onDidOpenTextDocument((doc) => { + if (doc.languageId === 'r' || doc.languageId === 'rmd') { + this.refresh(); + } + }), + vscode.workspace.onDidChangeConfiguration((change) => { + if ( + change.affectsConfiguration('r.lsp.enabled') || + change.affectsConfiguration('r.lsp.runtime') + ) { + this.refresh(); + } + }), + ]; + this.refresh(); + } + + private refresh(): void { + if (this.stopped) { + return; + } + const settings = vscode.workspace.getConfiguration('r'); + if ( + !settings.get('lsp.enabled', true) || + settings.get('lsp.runtime') === 'native' + ) { + this.stopClient(); + if ( + !this.nativePreferenceReported && + settings.get('lsp.runtime') === 'native' + ) { + this.nativePreferenceReported = true; + this.output.appendLine( + 'The browser has no native R executable. Set r.lsp.runtime to auto or webR to enable the R language server.', + ); + } + return; + } + this.nativePreferenceReported = false; + if ( + this.current || + !vscode.workspace.textDocuments.some((doc) => ['r', 'rmd'].includes(doc.languageId)) + ) { + return; + } + const abort = new AbortController(); + const client: LanguageClient = new WorkerLanguageClient( + 'r', + 'R Language Server', + async () => { + const session = await createWebRLanguageSession({ + baseUrl: WEBR_BASE_URL, + signal: abort.signal, + loadAsset: cachedWebRAssets(this.storage), + }); + if (abort.signal.aborted || this.current?.client !== client) { + session.close(); + throw new Error('The webR language service was stopped.'); + } + this.current.session = session; + return createWebRMessageTransports(session); + }, + { + documentSelector: [{ language: 'r' }, { language: 'rmd' }], + outputChannel: this.output, + revealOutputChannelOn: RevealOutputChannelOn.Never, + initializationFailedHandler: () => false, + errorHandler: { + error: () => ({ action: ErrorAction.Continue }), + closed: () => { + if (this.current?.client === client) { + // Allow the language client to unregister the disconnected providers first. + setTimeout( + () => + this.reportFailure( + client, + new Error('The webR worker disconnected.'), + ), + 0, + ); + } + return { action: CloseAction.DoNotRestart, handled: true }; + }, + }, + }, + ); + this.current = { client, abort }; + void this.stopping + .then(async () => { + if (this.current?.client === client) { + await client.start(); + } + }) + .catch((error) => this.reportFailure(client, error)); + } + + private reportFailure(client: LanguageClient, error: unknown): void { + if (this.current?.client !== client) { + return; + } + this.stopClient(); + this.output.appendLine(String(error)); + void vscode.window + .showErrorMessage( + `The webR language server could not continue: ${String(error)}`, + 'Retry', + ) + .then((action) => { + if (action === 'Retry') { + this.refresh(); + } + }); + } + + private stopClient(): void { + const current = this.current; + this.current = undefined; + if (current) { + if (current.client.state !== State.Running) { + current.abort.abort(); + current.session?.close(); + } + const disposing = current.client + .dispose() + .catch(() => {}) + .finally(() => { + current.session?.close(); + current.abort.abort(); + }); + this.stopping = Promise.all([this.stopping, disposing]).then(() => {}); + } + } + + dispose(): void { + this.stopped = true; + this.stopClient(); + for (const listener of this.listeners) { + listener.dispose(); + } + void this.stopping.then(() => this.output.dispose()); + } +} diff --git a/src/web/session.ts b/src/web/session.ts new file mode 100644 index 000000000..e702b8059 --- /dev/null +++ b/src/web/session.ts @@ -0,0 +1,235 @@ +import * as vscode from 'vscode'; +import { ChannelType, WebR } from 'webr'; +import { OutputQueue } from '../interactive/outputQueue'; +import { WebRConsole, type WebRConsoleEvent } from '../webr/console'; +import { WEBR_BASE_URL } from '../webr/runtime'; +import { sessionDirectory } from './files'; + +interface ActiveCell { + execution: vscode.NotebookCellExecution; + output: OutputQueue; + pending: ({ type: 'stdout' | 'stderr'; text: string } | { type: 'plot'; png: Uint8Array })[]; + remaining: number; + truncated: boolean; + outputError?: unknown; + input: vscode.CancellationTokenSource; +} + +export class BrowserSession implements vscode.Disposable { + private readonly supportsInterrupt = + globalThis.crossOriginIsolated === true && typeof SharedArrayBuffer !== 'undefined'; + private worker?: { runtime: WebR; console: WebRConsole; ready: Promise }; + private current?: ActiveCell; + private queue = Promise.resolve(); + private executionOrder = 0; + private failed?: Error; + private readonly outputLimit = + 1024 * 1024 * vscode.workspace.getConfiguration('r').get('interactive.maxOutputSizeMiB', 4); + private closed = false; + private readonly lifetime = new AbortController(); + + constructor(private readonly controller: vscode.NotebookController) {} + + // Queue file operations and submissions together. A stopped generation must + // never execute work against a replacement session or a closed worker. + run(operation: () => Promise): Promise { + const result = this.queue.then(() => { + if (this.closed) { + throw new Error('This webR session has ended.'); + } + if (this.failed) { + throw this.failed; + } + return operation(); + }); + this.queue = result.then( + () => {}, + () => {}, + ); + return result; + } + + private getWorker() { + if (this.closed) { + throw new Error('This webR session has ended.'); + } + if (!this.worker) { + const runtime = new WebR({ + baseUrl: WEBR_BASE_URL, + homedir: sessionDirectory, + channelType: this.supportsInterrupt + ? ChannelType.SharedArrayBuffer + : ChannelType.PostMessage, + }); + const session = new WebRConsole( + runtime, + (event) => this.onEvent(event), + this.supportsInterrupt, + (error) => { + this.failed = new Error( + 'The webR worker ended. Restart the session to run more code.', + { cause: error }, + ); + }, + ); + const ready = session.start().catch((error: unknown) => { + session.close(); + if (this.worker?.console === session) { + this.worker = undefined; + } + throw error; + }); + this.worker = { runtime, console: session, ready }; + } + return this.worker; + } + + async files(operation: (runtime: WebR) => Promise): Promise { + return this.run(async () => { + const worker = this.getWorker(); + await worker.ready; + return operation(worker.runtime); + }); + } + + async evaluate(cell: vscode.NotebookCell): Promise { + // start/clear even if loading fails so the error is visible in its cell. + const execution = this.controller.createNotebookCellExecution(cell); + const active: ActiveCell = { + execution, + pending: [], + remaining: this.outputLimit, + truncated: false, + input: new vscode.CancellationTokenSource(), + output: new OutputQueue( + async () => { + const outputs = active.pending.splice(0).map((value) => { + const item = + value.type === 'plot' + ? new vscode.NotebookCellOutputItem(value.png, 'image/png') + : value.type === 'stdout' + ? vscode.NotebookCellOutputItem.stdout(value.text) + : vscode.NotebookCellOutputItem.stderr(value.text); + return new vscode.NotebookCellOutput([item]); + }); + if (!this.closed && outputs.length) { + await execution.appendOutput(outputs); + } + }, + (error) => { + active.outputError = error; + }, + ), + }; + this.current = active; + execution.executionOrder = ++this.executionOrder; + execution.start(Date.now()); + let success = false; + try { + await execution.clearOutput(); + const worker = this.getWorker(); + await worker.ready; + if (this.closed) { + return; + } + const outcome = await worker.console.execute( + cell.document.getText(), + this.lifetime.signal, + ); + success = outcome === 'success'; + await active.output.flush(); + if (active.outputError) { + throw active.outputError; + } + } catch (error) { + await active.output.flush(); + if (!this.closed) { + await execution.appendOutput( + new vscode.NotebookCellOutput([ + vscode.NotebookCellOutputItem.error( + error instanceof Error ? error : new Error(String(error)), + ), + ]), + ); + } + } finally { + active.output.dispose(); + active.input.cancel(); + active.input.dispose(); + if (this.current === active) { + this.current = undefined; + execution.end(success, Date.now()); + } + } + } + + private onEvent(event: WebRConsoleEvent): void { + const active = this.current; + if (!active || this.closed) { + return; + } + if (event.type === 'input') { + const session = this.worker?.console; + void vscode.window + .showInputBox({ prompt: event.prompt, ignoreFocusOut: true }, active.input.token) + .then((value) => { + if (this.current === active && !this.closed) { + session?.replyInput(value ?? ''); + } + }); + } else if (event.type === 'plot') { + active.pending.push(event); + active.output.schedule('cell'); + } else if (event.type === 'stream' && !active.truncated) { + const bytes = new TextEncoder().encode(event.text); + let text = event.text; + if (bytes.length > active.remaining) { + text = new TextDecoder().decode(bytes.subarray(0, active.remaining), { + stream: true, + }); + active.truncated = true; + } + active.remaining -= Math.min(bytes.length, active.remaining); + const previous = active.pending.at(-1); + if (previous?.type === event.channel) { + previous.text += text; + } else { + active.pending.push({ type: event.channel, text }); + } + if (active.truncated) { + active.pending.push({ type: 'stderr', text: '\n[Console output truncated]\n' }); + } + active.output.schedule('cell'); + } + } + + async interrupt(restart: () => void): Promise { + if (!this.current) { + return; + } + if (this.supportsInterrupt) { + await this.worker?.console.interrupt(); + } else if ( + (await vscode.window.showWarningMessage( + 'This browser can stop the calculation by restarting webR. Restarting clears objects and imported files.', + 'Restart webR', + )) === 'Restart webR' && + !this.closed + ) { + restart(); + } + } + + dispose(): void { + this.closed = true; + if (this.current) { + this.current.input.cancel(); + this.current.output.dispose(); + this.current.execution.end(false, Date.now()); + this.current = undefined; + } + this.lifetime.abort(); + this.worker?.console.close(); + this.worker = undefined; + } +} diff --git a/website/docs/features/language-service.md b/website/docs/features/language-service.md index 2d7f8ef43..84017866d 100644 --- a/website/docs/features/language-service.md +++ b/website/docs/features/language-service.md @@ -242,3 +242,9 @@ decoration. Hovering over the decoration brings out a color picker popup that can be used to adjust the referenced color. ![Document color](https://user-images.githubusercontent.com/4662568/73992222-5f832980-4989-11ea-9593-a58e97df47b5.png) + +## VS Code for the Web + +Opening an R or R Markdown document in a trusted browser workspace starts the webR language server when `r.lsp.enabled` is enabled and `r.lsp.runtime` is `auto` or `webR`. Initial startup downloads the language server and its WebAssembly package library. Subsequent starts reuse cached package assets. + +Open buffers provide the source for Outline, completion, hover, signature help, and Go to Definition, including unsaved edits and navigation between open documents. Package-aware results reflect the worker’s package library. The browser language service operates independently of an Interactive notebook. Whole-project indexing and tools that launch a native executable require a workspace extension host with native R. diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index 92e1233f4..31677209c 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -262,3 +262,13 @@ Cleanup preserves distinct historical plots. Compression savings depend on the o ## Contributing The [architecture and backend contract](https://github.com/REditorSupport/vscode-R/blob/main/src/interactive/README.md), [test instructions](https://github.com/REditorSupport/vscode-R/blob/main/CONTRIBUTING.md#testing-r-interactive), and [analysis fixtures](https://github.com/REditorSupport/vscode-R/blob/main/src/test/examples/README.md) live with the source. + +## VS Code for the Web + +In a trusted browser workspace, **R: New Interactive Session** opens a notebook backed by webR. Use **Run Selection**, **Run Source**, or **Run Current Chunk** from an R or R Markdown editor. Each notebook has its own R environment. Text, warnings, errors, and PNG plots appear below the corresponding cell. The first run downloads the pinned webR runtime. Packages installed in a session need compatible WebAssembly builds. + +Use **R: Import Files into webR…** to copy scripts and data from the workspace into the session. Paths relative to their workspace folder are retained, so importing `helpers/fit.R` and `data/measurements.csv` allows `source("helpers/fit.R")` and `read.csv("data/measurements.csv")` in the notebook. In a multi-root workspace the folder name prefixes each imported path. Files created by R live in the session directory. **R: Export File from webR…** copies a selected result to a writable destination. Virtual workspaces backed by a read-only provider can still supply input files. + +Save an Interactive notebook as an `.rnb` file to keep its cells and outputs. Its live R objects and imported files belong to the browser worker and are released when the notebook closes, the page reloads, or the session restarts. On a cross-origin isolated host, **R: Interrupt Interactive Session** keeps the R environment. Console prompts such as `readline()` use the notebook input dialog. The PostMessage channel has limited input support and offers to restart the worker when interrupting a calculation. + +The browser language server runs in a separate worker and can serve open documents while code is running. [Browser language features](./language-service.md#vs-code-for-the-web) From 692f95f0b54e5ef4d0bd2746e35b83d871fc4510 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sat, 28 Nov 2026 19:23:53 +0800 Subject: [PATCH 2/5] Verify standard ggplot2 installation in a browser Interactive notebook --- src/test/web/webR.cjs | 9 +++++++++ website/docs/features/r-interactive.md | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/test/web/webR.cjs b/src/test/web/webR.cjs index f9753d8b6..3f0dd986f 100644 --- a/src/test/web/webR.cjs +++ b/src/test/web/webR.cjs @@ -107,6 +107,15 @@ exports.run = async () => { await command('r.runCommand','answer'); assert(stdout(notebook.cellAt(4)).includes('9'), 'Interrupt lost the R environment.'); } + const packageCell = notebook.cellCount; + await command('r.runCommand', [ + 'install.packages("ggplot2")', + 'library(ggplot2)', + 'ggplot(mtcars, aes(wt, mpg)) + geom_point()', + ].join('\n')); + assert(items(notebook.cellAt(packageCell)).some(item => item.mime === 'image/png' && item.data.length > 100), + 'Installing ggplot2 in a fresh browser session did not produce a plot.'); + const savedUri = files.uri('transcript.rnb'); const snapshot = new TextEncoder().encode(JSON.stringify({version:1,metadata:{},cells:[]})); await vscode.workspace.fs.writeFile(savedUri,snapshot); diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index 31677209c..ab49b7219 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -265,7 +265,7 @@ The [architecture and backend contract](https://github.com/REditorSupport/vscode ## VS Code for the Web -In a trusted browser workspace, **R: New Interactive Session** opens a notebook backed by webR. Use **Run Selection**, **Run Source**, or **Run Current Chunk** from an R or R Markdown editor. Each notebook has its own R environment. Text, warnings, errors, and PNG plots appear below the corresponding cell. The first run downloads the pinned webR runtime. Packages installed in a session need compatible WebAssembly builds. +In a trusted browser workspace, **R: New Interactive Session** opens a notebook backed by webR. Use **Run Selection**, **Run Source**, or **Run Current Chunk** from an R or R Markdown editor. Each notebook has its own R environment. Text, warnings, errors, and PNG plots appear below the corresponding cell. The first run downloads the pinned webR runtime. Install session packages with `install.packages("ggplot2")` and load them with `library(ggplot2)`. The repository must supply compatible WebAssembly binaries. Use **R: Import Files into webR…** to copy scripts and data from the workspace into the session. Paths relative to their workspace folder are retained, so importing `helpers/fit.R` and `data/measurements.csv` allows `source("helpers/fit.R")` and `read.csv("data/measurements.csv")` in the notebook. In a multi-root workspace the folder name prefixes each imported path. Files created by R live in the session directory. **R: Export File from webR…** copies a selected result to a writable destination. Virtual workspaces backed by a read-only provider can still supply input files. From c5a16e573ff94c269ccc5599f6a41d4fdd1a9dbd Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 08:23:59 +0800 Subject: [PATCH 3/5] Synchronize browser language settings and refresh open diagnostics --- src/test/web/webR.cjs | 16 ++++++++++++++++ src/web/languageService.ts | 1 + 2 files changed, 17 insertions(+) diff --git a/src/test/web/webR.cjs b/src/test/web/webR.cjs index 3f0dd986f..3dcef844d 100644 --- a/src/test/web/webR.cjs +++ b/src/test/web/webR.cjs @@ -69,6 +69,22 @@ exports.run = async () => { && (location.range ?? location.targetSelectionRange).start.line === 0); }, 'Definition did not resolve across the virtual and unsaved documents.'); + const settings = vscode.workspace.getConfiguration('r'); + const previousDiagnostics = settings.inspect('lsp.diagnostics')?.globalValue; + try { + const broken = (await editor('value <- )\n')).document; + const hasSyntaxError = () => vscode.languages.getDiagnostics(broken.uri) + .some(diagnostic => diagnostic.source === 'R' && diagnostic.severity === vscode.DiagnosticSeverity.Error); + await settings.update('lsp.diagnostics', true, vscode.ConfigurationTarget.Global); + await until(hasSyntaxError, 'The browser language server did not report the syntax error.'); + await settings.update('lsp.diagnostics', false, vscode.ConfigurationTarget.Global); + await until(() => !hasSyntaxError(), 'Disabling diagnostics did not clear the open document.'); + await settings.update('lsp.diagnostics', true, vscode.ConfigurationTarget.Global); + await until(hasSyntaxError, 'Enabling diagnostics did not recheck the open document.'); + } finally { + await settings.update('lsp.diagnostics', previousDiagnostics, vscode.ConfigurationTarget.Global); + } + await vscode.window.showTextDocument(first); const edit = new vscode.WorkspaceEdit(); edit.replace(first.uri, new vscode.Range(0,0,0,9),'triple_it'); diff --git a/src/web/languageService.ts b/src/web/languageService.ts index e3a85d6d1..83051a3b0 100644 --- a/src/web/languageService.ts +++ b/src/web/languageService.ts @@ -101,6 +101,7 @@ export class BrowserLanguageService implements vscode.Disposable { { documentSelector: [{ language: 'r' }, { language: 'rmd' }], outputChannel: this.output, + synchronize: { configurationSection: 'r.lsp' }, revealOutputChannelOn: RevealOutputChannelOn.Never, initializationFailedHandler: () => false, errorHandler: { From e83ff06233304a46bda496ba6e256145d447e881 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 08:30:54 +0800 Subject: [PATCH 4/5] Read the bundled Wasm language package from the browser extension --- src/web/extension.ts | 2 +- src/web/languageService.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/web/extension.ts b/src/web/extension.ts index d807cc287..12884940a 100644 --- a/src/web/extension.ts +++ b/src/web/extension.ts @@ -14,7 +14,7 @@ import { BrowserLanguageService } from './languageService'; export async function activate(context: vscode.ExtensionContext): Promise { await vscode.commands.executeCommand('setContext', 'r.webExtension', true); const interactive = new BrowserInteractive(context); - context.subscriptions.push(interactive, new BrowserLanguageService(context.globalStorageUri)); + context.subscriptions.push(interactive, new BrowserLanguageService(context)); const runSource = async () => { const editor = vscode.window.activeTextEditor; diff --git a/src/web/languageService.ts b/src/web/languageService.ts index 83051a3b0..4b3bf5013 100644 --- a/src/web/languageService.ts +++ b/src/web/languageService.ts @@ -34,7 +34,7 @@ export class BrowserLanguageService implements vscode.Disposable { private stopping = Promise.resolve(); private nativePreferenceReported = false; - constructor(private readonly storage: vscode.Uri) { + constructor(private readonly context: vscode.ExtensionContext) { this.listeners = [ vscode.workspace.onDidOpenTextDocument((doc) => { if (doc.languageId === 'r' || doc.languageId === 'rmd') { @@ -89,7 +89,7 @@ export class BrowserLanguageService implements vscode.Disposable { const session = await createWebRLanguageSession({ baseUrl: WEBR_BASE_URL, signal: abort.signal, - loadAsset: cachedWebRAssets(this.storage), + loadAsset: cachedWebRAssets(this.context), }); if (abort.signal.aborted || this.current?.client !== client) { session.close(); From 25ff9fd9e555b48c8381ff369fa3722489981eb7 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 09:07:25 +0800 Subject: [PATCH 5/5] Identify the experimental integration in browser workspace and kernel details --- package.json | 2 +- src/web/interactive.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 1dbd2642e..07a808fc6 100644 --- a/package.json +++ b/package.json @@ -2848,7 +2848,7 @@ }, "virtualWorkspaces": { "supported": "limited", - "description": "webR supports editing open R documents and running code in a browser session. Native R tools require a workspace extension host." + "description": "The experimental webR integration supports editing open R documents and running code in a browser session. Native R tools require a workspace extension host." } } } diff --git a/src/web/interactive.ts b/src/web/interactive.ts index c650093f6..6c65d7946 100644 --- a/src/web/interactive.ts +++ b/src/web/interactive.ts @@ -29,7 +29,7 @@ export class BrowserInteractive implements vscode.Disposable { constructor(private readonly context: vscode.ExtensionContext) { this.controller.supportedLanguages = ['r']; this.controller.supportsExecutionOrder = true; - this.controller.description = 'R in this browser'; + this.controller.description = 'webR (experimental) · R in this browser'; this.controller.executeHandler = async (cells, doc) => { const session = this.session(doc); await session.run(async () => {