diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f1b811921..3d6bea7e1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -82,6 +82,14 @@ Interactive session. Run the source/bootstrap checks with `pnpm run test:sess-source`, or just the base-R identity checks with `pnpm run test:sess-identity`. +## Updating the webR viewer dependency + +The data and list viewers use a private copy of jsonlite's Wasm namespace so +they can open before a user installs any packages. When updating the jsonlite +entry in `src/webr/packages.json`, run `python3 scripts/update-webr-viewer-jsonlite.py` +and commit the regenerated archive. The script verifies the upstream digest. +A local copy of the upstream archive can be passed as its first argument. + ## Testing the webR language service After compiling the extension, set `VSCR_ACTIVATION_CASES=webr-language` and run diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 6b6b1ff30..3cfaf74ac 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -65,3 +65,63 @@ authors. The distribution's licensing terms are included in dist/resources/webr-LICENSE.md. Runtime binaries and additional R packages are retrieved from their upstream distributions when the user starts webR. https://github.com/r-wasm/webr/tree/v0.6.1 + +jsonlite Wasm viewer runtime +--------------------------- + +The viewer runtime includes a reduced copy of the jsonlite Wasm package. +The source distribution is https://cran.r-project.org/package=jsonlite. +The Wasm binary and checksum are pinned in src/webr/packages.json. + +Copyright 2020 Jeroen Ooms. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +YAJL +Copyright (c) 2007-2014, Lloyd Hilaiel +Copyright (c) 2010-2011, Florian Forster + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Base64 encoding/decoding (RFC1341) +Copyright (c) 2005, Jouni Malinen + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License version 2 as +published by the Free Software Foundation. + +Alternatively, this software may be distributed under the terms of BSD +license. + +See README and COPYING for more details. + +Copyright (c) 2007, Nick Galbreath -- nickg [at] client9 [dot] com +All rights reserved. +http://code.google.com/p/stringencoders/ +Released under the MIT license. diff --git a/esbuild.js b/esbuild.js index c1a6eedd3..36210486d 100644 --- a/esbuild.js +++ b/esbuild.js @@ -30,6 +30,14 @@ function copyResources() { } } fs.copyFileSync(path.join(__dirname, 'node_modules/webr/LICENSE.md'), path.join(destDir, 'webr-LICENSE.md')); + const viewerLibrary = fs.readFileSync(path.join(__dirname, 'src/webr/resources/viewer-jsonlite.tgz')); + fs.writeFileSync(path.join(destDir, 'webr-viewer-jsonlite.json'), JSON.stringify(viewerLibrary.toString('base64'))); + // The detached agent and the browser extension embed the same R viewer + // helpers as sess. The Node test build reads the generated resource directly. + const viewerSource = ['dispatch.R', 'handlers.R', 'inspection_call.R', 'interactive_viewers.R'] + .map(file => fs.readFileSync(path.join(__dirname, 'sess', 'R', file), 'utf8')) + .join('\n'); + fs.writeFileSync(path.join(destDir, 'webr-viewers.json'), JSON.stringify(viewerSource)); console.log('Resources copied.'); } diff --git a/scripts/update-webr-viewer-jsonlite.py b/scripts/update-webr-viewer-jsonlite.py new file mode 100644 index 000000000..939b7e5b1 --- /dev/null +++ b/scripts/update-webr-viewer-jsonlite.py @@ -0,0 +1,40 @@ +"""Regenerate the small offline viewer dependency from vscode-R's pinned webR package.""" +import argparse +import gzip +import hashlib +import io +import json +from pathlib import Path +import tarfile +from urllib.request import urlopen + +root = Path(__file__).resolve().parents[1] +packages = json.loads((root / "src/webr/packages.json").read_text()) +package = next(entry for entry in packages if entry["name"] == "jsonlite") +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("archive", nargs="?", type=Path, help="use a local copy of the official archive") +args = parser.parse_args() +if args.archive: + original = args.archive.read_bytes() +else: + with urlopen(package["url"], timeout=60) as response: + original = response.read() +if hashlib.sha256(original).hexdigest() != package["sha256"]: + raise SystemExit("The archive does not match src/webr/packages.json") + +# Preserve the namespace, lazy-load databases and compiled Wasm routines. +# Package help, examples and vignettes are available from the full distribution. +metadata = {"jsonlite/DESCRIPTION", "jsonlite/LICENSE", "jsonlite/NAMESPACE"} +directories = ("jsonlite/Meta/", "jsonlite/R/", "jsonlite/libs/") +out = root / "src/webr/resources/viewer-jsonlite.tgz" +with tarfile.open(fileobj=io.BytesIO(original), mode="r:gz") as source, out.open("wb") as stream: + with gzip.GzipFile(filename="", fileobj=stream, mode="wb", mtime=0) as compressed: + with tarfile.open(fileobj=compressed, mode="w", format=tarfile.USTAR_FORMAT) as target: + for member in sorted(source.getmembers(), key=lambda entry: entry.name): + if member.name not in metadata and not member.name.startswith(directories): + continue + if member.isfile(): + entry = tarfile.TarInfo(member.name) + entry.size = member.size + target.addfile(entry, source.extractfile(member)) +print(out) diff --git a/sess/R/hooks.R b/sess/R/hooks.R index c62a9d9cf..82a53b1dd 100644 --- a/sess/R/hooks.R +++ b/sess/R/hooks.R @@ -110,112 +110,6 @@ runtime_start <- function( .runtime_set_field("dataview_registry", new.env(parent = emptyenv())) } - show_dataview <- function(x, title = deparse(substitute(x))) { - # Capture the root before forcing x so View(x$a) shares the viewer for x. - original_expression <- substitute(x) - expression <- original_expression - while ( - is.call(expression) && - is.symbol(expression[[1L]]) && - as.character(expression[[1L]]) %in% c("$", "[[", "@") - ) { - expression <- expression[[2L]] - } - owner <- .sess_env$view_owner - if (is.null(owner) && missing(title) && is.symbol(expression)) { - owner <- as.character(expression) - } - force(title) - # Resolve the variable behind View() before x is forced, so jdv can - # follow it. The lookup starts at the caller, never at this function's frame. - tracked_binding <- .jdv_track_binding(original_expression, parent.frame()) - - view_type <- if (dataview_is_table(x)) { - "table" - } else if (listview_supported(x)) { - "list" - } else { - "object" - } - title_key <- paste(as.character(title), collapse = "\n") - if ( - (view_type %in% c("table", "list") || .jdv_is_arrow(x)) && - .jdv_show(x, title_key, tracked_binding) - ) { - return(invisible(NULL)) - } - # Explicit View() in Interactive should open the normal data viewer when - # jdv is available. Inline rich output remains the fallback when it is not. - if ( - is.null(.sess_env$view_owner) && - isTRUE(.sess_env$interactive_connected) && - .interactive_rich_value(x) - ) { - return(invisible(NULL)) - } - owner <- owner %||% title_key - registry_key <- paste0(view_type, ":", owner) - dataview_registry <- .sess_env$dataview_registry - view_id <- if ( - nzchar(title_key) && exists(registry_key, envir = dataview_registry, inherits = FALSE) - ) { - get(registry_key, envir = dataview_registry, inherits = FALSE) - } else { - id <- dataview_new_id() - if (nzchar(title_key)) { - assign(registry_key, id, envir = dataview_registry) - } - id - } - - if (view_type == "table") { - registration <- dataview_register(x, view_id = view_id) - - notify_client( - "dataview", - list( - title = title, - source = "table", - type = "json", - view_id = registration$view_id, - state_generation = registration$state_generation - ) - ) - } else if (view_type == "list") { - context <- .sess_env$listview_context - if (is.null(context) && missing(title)) { - context <- listview_expression_context(original_expression, parent.frame(), owner, x) - } - root <- if (is.null(context)) listview_state(x, title_key, owner) else context$root - navigation <- if (is.null(context)) { - listview_navigation(listview_location(root)) - } else { - context$navigation - } - root <- dataview_set_state(view_id, root) - notify_client( - "dataview", - list( - title = title, - source = view_type, - type = "json", - view_id = view_id, - state_generation = root$state_generation, - navigation = navigation - ) - ) - } else { - code <- if (is.primitive(x)) utils::capture.output(print(x)) else deparse(x) - file_path <- .sess_env$dataviews[[view_id]]$file %||% - tempfile(tmpdir = .sess_env$tempdir, fileext = ".R") - writeLines(code, file_path) - .sess_env$dataviews[[view_id]] <- list(type = "object", file = file_path) - notify_client( - "dataview", - list(title = title, file = file_path, source = "object", type = "R") - ) - } - } .runtime_rebind("View", show_dataview, ns = "utils") # 2. Browser & Webview Options diff --git a/sess/R/interactive.R b/sess/R/interactive.R index 902ec60b8..d09bb3b5d 100644 --- a/sess/R/interactive.R +++ b/sess/R/interactive.R @@ -452,55 +452,6 @@ interactive_execute <- function(id, code, source = NULL) { } } -.interactive_table_text <- function(value) { - file <- tempfile("table-print-") - on.exit(unlink(file)) - tryCatch( - { - # Use the class printer and current R options. A file bounds the amount we - # retain in memory even when a custom printer produces a very large table. - # Binary output keeps notebook newlines portable on Windows too. - connection <- file(file, open = "wb") - tryCatch(utils::capture.output(print(value), file = connection), finally = close(connection)) - limit <- 256L * 1024L - text <- readChar(file, nchars = limit, useBytes = TRUE) - if (!length(text)) { - text <- "" - } - text <- iconv(text, to = "UTF-8", sub = "") - if (file.info(file)$size > limit) { - text <- paste0(text, "\n[Printed preview truncated at 256 KiB]\n") - } - list(printedText = text) - }, - error = function(e) list(printError = conditionMessage(e)) - ) -} - -.interactive_table_snapshot <- function(value) { - source_rows <- nrow(value) - # Bound work before copying or invoking a class printer. Bounding the printed - # bytes afterwards does not prevent a printer from scanning billions of rows. - limit <- max(1L, min(1000L, floor(100000 / max(1L, ncol(value))))) - truncated <- source_rows > limit - # Row subsetting already allocates independent data.table columns. Calling - # copy() afterwards also duplicates attributes and objects inside list cells. - snapshot <- dataview_slice(value, seq_len(min(source_rows, limit))) - if (is.data.frame(snapshot)) { - for (position in seq_len(ncol(snapshot))) { - column <- snapshot[[position]] - if (is.list(column) && is.null(dim(column)) && !inherits(column, "POSIXlt")) { - snapshot[[position]] <- lapply(column, dataview_cell_preview) - } else if (is.character(column)) { - snapshot[[position]] <- dataview_preview_text(column) - } - } - } else if (is.character(snapshot)) { - snapshot[] <- dataview_preview_text(snapshot) - } - list(value = snapshot, source_rows = source_rows, truncated = truncated) -} - # jdv handles back the inline table and list previews ------------------------ # # Each table or list output holds one registry-free jdv handle (no viewer slot, @@ -684,96 +635,7 @@ handle_jdv_open_viewer <- function(params) { } .interactive_rich_value <- function(value) { - if (dataview_is_table(value)) { - snapshot <- .interactive_table_snapshot(value) - printed <- .interactive_table_text(snapshot$value) - if (snapshot$truncated && !is.null(printed$printedText)) { - note <- sprintf( - "\n[Snapshot: first %s of %s rows. Open Data viewer for the full table.]\n", - format(nrow(snapshot$value), big.mark = ",", scientific = FALSE, trim = TRUE), - format(snapshot$source_rows, big.mark = ",", scientific = FALSE, trim = TRUE) - ) - printed$printedText <- paste0(printed$printedText, note) - } - preview <- if (is.data.frame(value) || is.matrix(value)) { - .interactive_handle_preview( - value, - "table", - c(list(sourceRows = snapshot$source_rows), printed) - ) - } - if (!is.null(preview)) { - .interactive_event("display", c(list(kind = "table"), preview)) - return(TRUE) - } - registration <- dataview_register(snapshot$value) - metadata <- handle_dataview_init(list(view_id = registration$view_id)) - preview <- handle_dataview_page(list( - view_id = registration$view_id, - startRow = 0L, - endRow = 20L, - formatNumbers = TRUE, - sortModel = list(), - filterModel = list() - )) - full_view <- NULL - if (snapshot$truncated) { - # Retain the full object without copying it. The cell remains a snapshot; - # the expanded viewer can reflect later reference edits to this object. - full_view <- dataview_register(value, live = TRUE)$view_id - } - .interactive_event( - "display", - c( - list( - kind = "table", - viewId = registration$view_id, - fullViewId = full_view, - sourceRows = snapshot$source_rows, - columns = metadata$columns, - rows = preview$rows, - formattedColumns = preview$formattedColumns, - totalRows = metadata$totalRows - ), - printed - ) - ) - return(TRUE) - } - if (is.list(value) && !is.object(value)) { - preview <- .interactive_handle_preview(value, "list") - if (!is.null(preview)) { - .interactive_event( - "display", - c( - list( - kind = "list", - handleId = preview$handleId, - descriptor = preview$descriptor, - page = preview$page - ), - .interactive_table_text(value) - ) - ) - return(TRUE) - } - view_id <- dataview_new_id() - # Nested panels reuse the root's owner; separate cell results must stay independent. - root <- listview_state(value, "List", paste0("interactive:", view_id)) - dataview_set_state(view_id, root) - preview <- get_workspace_children(view_id = view_id) - .interactive_event( - "display", - c( - list( - kind = "list", - viewId = view_id, - navigation = listview_navigation(listview_location(root)) - ), - preview, - .interactive_table_text(value) - ) - ) + if (.interactive_viewer_value(value, .interactive_handle_preview)) { return(TRUE) } if (inherits(value, "htmlwidget") && requireNamespace("htmlwidgets", quietly = TRUE)) { diff --git a/sess/R/interactive_viewers.R b/sess/R/interactive_viewers.R new file mode 100644 index 000000000..972655a0b --- /dev/null +++ b/sess/R/interactive_viewers.R @@ -0,0 +1,245 @@ +# Interactive table and list displays shared by the native and webR runtimes. +.interactive_table_text <- function(value) { + file <- tempfile("table-print-") + on.exit(unlink(file)) + tryCatch( + { + # Use the class printer and current R options. A file bounds the amount we + # retain in memory even when a custom printer produces a very large table. + # Binary output keeps notebook newlines portable on Windows too. + connection <- file(file, open = "wb") + tryCatch(utils::capture.output(print(value), file = connection), finally = close(connection)) + limit <- 256L * 1024L + text <- readChar(file, nchars = limit, useBytes = TRUE) + if (!length(text)) { + text <- "" + } + text <- iconv(text, to = "UTF-8", sub = "") + if (file.info(file)$size > limit) { + text <- paste0(text, "\n[Printed preview truncated at 256 KiB]\n") + } + list(printedText = text) + }, + error = function(e) list(printError = conditionMessage(e)) + ) +} + +.interactive_table_snapshot <- function(value) { + source_rows <- nrow(value) + # Bound work before copying or invoking a class printer. Bounding the printed + # bytes afterwards does not prevent a printer from scanning billions of rows. + limit <- max(1L, min(1000L, floor(100000 / max(1L, ncol(value))))) + truncated <- source_rows > limit + # Row subsetting already allocates independent data.table columns. Calling + # copy() afterwards also duplicates attributes and objects inside list cells. + snapshot <- dataview_slice(value, seq_len(min(source_rows, limit))) + if (is.data.frame(snapshot)) { + for (position in seq_len(ncol(snapshot))) { + column <- snapshot[[position]] + if (is.list(column) && is.null(dim(column)) && !inherits(column, "POSIXlt")) { + snapshot[[position]] <- lapply(column, dataview_cell_preview) + } else if (is.character(column)) { + snapshot[[position]] <- dataview_preview_text(column) + } + } + } else if (is.character(snapshot)) { + snapshot[] <- dataview_preview_text(snapshot) + } + list(value = snapshot, source_rows = source_rows, truncated = truncated) +} + +.interactive_viewer_value <- function(value, handle_preview = function(...) NULL) { + if (dataview_is_table(value)) { + snapshot <- .interactive_table_snapshot(value) + printed <- .interactive_table_text(snapshot$value) + if (snapshot$truncated && !is.null(printed$printedText)) { + note <- sprintf( + "\n[Snapshot: first %s of %s rows. Open Data viewer for the full table.]\n", + format(nrow(snapshot$value), big.mark = ",", scientific = FALSE, trim = TRUE), + format(snapshot$source_rows, big.mark = ",", scientific = FALSE, trim = TRUE) + ) + printed$printedText <- paste0(printed$printedText, note) + } + preview <- if (is.data.frame(value) || is.matrix(value)) { + handle_preview(value, "table", c(list(sourceRows = snapshot$source_rows), printed)) + } + if (!is.null(preview)) { + .interactive_event("display", c(list(kind = "table"), preview)) + return(TRUE) + } + registration <- dataview_register(snapshot$value) + metadata <- handle_dataview_init(list(view_id = registration$view_id)) + preview <- handle_dataview_page(list( + view_id = registration$view_id, + startRow = 0L, + endRow = 20L, + formatNumbers = TRUE, + sortModel = list(), + filterModel = list() + )) + full_view <- NULL + if (snapshot$truncated) { + # Retain the full object without copying it. The cell remains a snapshot; + # the expanded viewer can reflect later reference edits to this object. + full_view <- dataview_register(value, live = TRUE)$view_id + } + .interactive_event( + "display", + c( + list( + kind = "table", + viewId = registration$view_id, + fullViewId = full_view, + sourceRows = snapshot$source_rows, + columns = metadata$columns, + rows = preview$rows, + formattedColumns = preview$formattedColumns, + totalRows = metadata$totalRows + ), + printed + ) + ) + return(TRUE) + } + if (is.list(value) && !is.object(value)) { + preview <- handle_preview(value, "list") + if (!is.null(preview)) { + .interactive_event( + "display", + c( + list( + kind = "list", + handleId = preview$handleId, + descriptor = preview$descriptor, + page = preview$page + ), + .interactive_table_text(value) + ) + ) + return(TRUE) + } + view_id <- dataview_new_id() + # Nested panels reuse the root's owner; separate cell results must stay independent. + root <- listview_state(value, "List", paste0("interactive:", view_id)) + dataview_set_state(view_id, root) + preview <- get_workspace_children(view_id = view_id) + .interactive_event( + "display", + c( + list( + kind = "list", + viewId = view_id, + navigation = listview_navigation(listview_location(root)) + ), + preview, + .interactive_table_text(value) + ) + ) + return(TRUE) + } + FALSE +} + +show_dataview <- function(x, title = deparse(substitute(x))) { + # Capture the root before forcing x so View(x$a) shares the viewer for x. + original_expression <- substitute(x) + expression <- original_expression + while ( + is.call(expression) && + is.symbol(expression[[1L]]) && + as.character(expression[[1L]]) %in% c("$", "[[", "@") + ) { + expression <- expression[[2L]] + } + owner <- .sess_env$view_owner + if (is.null(owner) && missing(title) && is.symbol(expression)) { + owner <- as.character(expression) + } + force(title) + # Resolve the variable behind View() before x is forced, so jdv can + # follow it. The lookup starts at the caller, never at this function's frame. + tracked_binding <- .jdv_track_binding(original_expression, parent.frame()) + + view_type <- if (dataview_is_table(x)) { + "table" + } else if (listview_supported(x)) { + "list" + } else { + "object" + } + title_key <- paste(as.character(title), collapse = "\n") + if ( + (view_type %in% c("table", "list") || .jdv_is_arrow(x)) && + .jdv_show(x, title_key, tracked_binding) + ) { + return(invisible(NULL)) + } + # Explicit View() in Interactive should open the normal data viewer when + # jdv is available. Inline rich output remains the fallback when it is not. + if ( + is.null(.sess_env$view_owner) && + isTRUE(.sess_env$interactive_connected) && + .interactive_rich_value(x) + ) { + return(invisible(NULL)) + } + owner <- owner %||% title_key + registry_key <- paste0(view_type, ":", owner) + dataview_registry <- .sess_env$dataview_registry + view_id <- if ( + nzchar(title_key) && exists(registry_key, envir = dataview_registry, inherits = FALSE) + ) { + get(registry_key, envir = dataview_registry, inherits = FALSE) + } else { + id <- dataview_new_id() + if (nzchar(title_key)) { + assign(registry_key, id, envir = dataview_registry) + } + id + } + + if (view_type == "table") { + registration <- dataview_register(x, view_id = view_id) + + notify_client( + "dataview", + list( + title = title, + source = "table", + type = "json", + view_id = registration$view_id, + state_generation = registration$state_generation + ) + ) + } else if (view_type == "list") { + context <- .sess_env$listview_context + if (is.null(context) && missing(title)) { + context <- listview_expression_context(original_expression, parent.frame(), owner, x) + } + root <- if (is.null(context)) listview_state(x, title_key, owner) else context$root + navigation <- if (is.null(context)) { + listview_navigation(listview_location(root)) + } else { + context$navigation + } + root <- dataview_set_state(view_id, root) + notify_client( + "dataview", + list( + title = title, + source = view_type, + type = "json", + view_id = view_id, + state_generation = root$state_generation, + navigation = navigation + ) + ) + } else { + code <- if (is.primitive(x)) utils::capture.output(print(x)) else deparse(x) + file_path <- .sess_env$dataviews[[view_id]]$file %||% + tempfile(tmpdir = .sess_env$tempdir, fileext = ".R") + writeLines(code, file_path) + .sess_env$dataviews[[view_id]] <- list(type = "object", file = file_path) + notify_client("dataview", list(title = title, file = file_path, source = "object", type = "R")) + } +} diff --git a/src/interactive/agent.ts b/src/interactive/agent.ts index 0123057d3..cb10ae555 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -15,6 +15,7 @@ import { SessionBackend, StopRefusedError, inspectionMethod, + isViewerInspection, } from './backend'; import { AGENT_PROTOCOL, @@ -638,17 +639,25 @@ export class SessionAgent { this.state('busy'); break; case 'inspect': { - if (this.backend.capabilities.inspection === false) { + const request = { + method: inspectionMethod(params.method), + params: object(params.params ?? {}), + timeout: 5000, + }; + if ( + this.backend.capabilities.inspection === false && + !(this.backend.capabilities.viewerInspection && isViewerInspection(request)) + ) { throw new Error('This runtime does not support inspection'); } - if (params.method === 'workspace') { + if (request.method === 'workspace') { if (!this.current) { await this.refreshWorkspace(); } result = this.workspace ?? {}; break; } - const method = inspectionMethod(params.method); + const { method } = request; // Opening a viewer and closing a handle change what every client // of the session sees, while reading a page does not. if (method === 'jdv_open_viewer' || method === 'jdv_handle_close') { @@ -657,7 +666,7 @@ export class SessionAgent { if (this.current) { // A cleared output must not keep its value alive. R releases // the handle once it is idle, before the next cell runs. - const handle = object(params.params ?? {}).handle_id; + const handle = request.params.handle_id; if (method === 'jdv_handle_close' && typeof handle === 'string') { this.pendingHandleCloses.set(handle, 0); result = true; @@ -665,11 +674,7 @@ export class SessionAgent { } throw new Error('R is busy; cached data remains available. Retry when idle.'); } - result = await this.backend.inspect({ - method, - params: object(params.params ?? {}), - timeout: 5000, - }); + result = await this.backend.inspect(request); break; } case 'asset': { @@ -756,7 +761,7 @@ export class SessionAgent { this.handleBackendEvent(event); } catch (error) { // Storage failures must never stop draining runtime output. - if (event.type === 'display') { + if (event.type === 'display' || event.type === 'widget') { const key = event.executionId ?? 'session'; if (this.retentionWarnings.has(key)) { return; @@ -831,6 +836,12 @@ export class SessionAgent { this.event('input', this.input, executionId); this.state('input'); break; + case 'widget': + this.display( + { kind: 'html', asset: this.assets.importHtmlFiles(event.files) }, + executionId, + ); + break; case 'display': this.display(event.data, executionId); break; diff --git a/src/interactive/assets.ts b/src/interactive/assets.ts index f92445c7d..21e967ce6 100644 --- a/src/interactive/assets.ts +++ b/src/interactive/assets.ts @@ -1,3 +1,4 @@ +import { type HtmlBundle, validateHtmlBundle, checkHtmlSize } from './htmlBundle'; import * as fs from 'fs'; import * as path from 'path'; import * as http from 'http'; @@ -179,9 +180,7 @@ export class AssetStore { return; } total += stat.size; - if (total > 64 * 1024 * 1024 || entries.length >= 5000) { - throw new Error('HTML bundle exceeds the 64 MiB / 5000 file limit'); - } + checkHtmlSize(entries.length + 1, total); const bytes = fs.readFileSync(absolute); entries.push({ relative: path.relative(root, absolute), bytes }); if (!/\.(html?|css)$/i.test(absolute)) { @@ -218,6 +217,20 @@ export class AssetStore { } }; collect(fs.realpathSync(file)); + return this.storeHtml(entries, path.basename(file), total); + } + + importHtmlFiles(files: HtmlBundle): string { + const total = validateHtmlBundle(files); + const entries = Object.entries(files).map(([relative, bytes]) => ({ relative, bytes })); + return this.storeHtml(entries, 'index.html', total); + } + + private storeHtml( + entries: { relative: string; bytes: Uint8Array }[], + entry: string, + total: number, + ): string { entries.sort((a, b) => a.relative.localeCompare(b.relative)); const hash = createHash('sha256'); for (const entry of entries) { @@ -233,7 +246,7 @@ export class AssetStore { for (const entry of entries) { const target = path.join(temporary, entry.relative); fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 }); - fs.writeFileSync(target, entry.bytes, { mode: 0o600 }); + fs.writeFileSync(target, entry.bytes, { mode: 0o600, flag: 'wx' }); } fs.renameSync(temporary, destination); this.bytes += total; @@ -242,7 +255,7 @@ export class AssetStore { throw error; } } - return `${id}/${path.basename(file)}`; + return `${id}/${entry}`; } resolve(id: string): string { diff --git a/src/interactive/backend.ts b/src/interactive/backend.ts index 6e2283cf8..5158a75cf 100644 --- a/src/interactive/backend.ts +++ b/src/interactive/backend.ts @@ -1,3 +1,4 @@ +import type { HtmlBundle } from './htmlBundle'; import type { AgentSettings, Submission } from './protocol'; export type BackendOwnership = 'managed' | 'adopted'; @@ -39,6 +40,22 @@ export interface InspectionRequest { */ timeout?: number; } +/** Live controls attached to a retained table or list never take an R expression. */ +export function isViewerInspection(request: InspectionRequest): boolean { + return ( + typeof request.params.view_id === 'string' && + request.params.view_id.length > 0 && + [ + 'dataview_init', + 'dataview_page', + 'dataview_dispose', + 'workspace_children', + 'listview_navigate', + 'listview_view', + ].includes(request.method) + ); +} + export interface InputReply { value: string; } @@ -61,6 +78,7 @@ export type BackendEvent = ( | { type: 'finished'; state: 'success' | 'error' | 'interrupted' } | { type: 'stream'; text: string; channel: string; external?: boolean } | { type: 'condition' | 'input' | 'display'; data: Record } + | { type: 'widget'; files: HtmlBundle } | { type: 'workspaceChanged' } | { type: 'notification' | 'viewer'; method: string; params: Record } | { type: 'clientRequest'; id: string; method: string; params: unknown } diff --git a/src/interactive/backends/webr.ts b/src/interactive/backends/webr.ts index 67011e709..5719c1783 100644 --- a/src/interactive/backends/webr.ts +++ b/src/interactive/backends/webr.ts @@ -1,5 +1,5 @@ import { WebRConsole, WebRConsoleEvent } from '../../webr/console'; -import { BackendEvent, DispatchNotSentError, SessionBackend } from '../backend'; +import { BackendEvent, DispatchNotSentError, InspectionRequest, SessionBackend } from '../backend'; import type { AgentSettings, Submission } from '../protocol'; /** An R runtime managed by the session agent's Node process. */ @@ -9,8 +9,9 @@ export class WebRBackend implements SessionBackend { streaming: true, stdin: true, debugger: false, - tables: false, - html: false, + tables: true, + viewerInspection: true, + html: true, inspection: false, inspectionDeadline: false, interrupt: true, @@ -95,6 +96,13 @@ export class WebRBackend implements SessionBackend { data: { inputId: ++this.inputId, prompt: event.prompt }, }); break; + case 'display': + case 'viewer': + this.emit({ ...event, executionId }); + break; + case 'widget': + this.emit({ type: 'widget', files: event.files, executionId }); + break; case 'plot': this.emit({ type: 'display', @@ -150,8 +158,11 @@ export class WebRBackend implements SessionBackend { }); } - inspect(): Promise { - return Promise.reject(new Error('Object inspection is unavailable for webR Interactive.')); + inspect(request: InspectionRequest): Promise { + if (!this.console || this.stopped) { + return Promise.reject(new Error('webR session is closed.')); + } + return this.console.inspect(request.method, request.params); } replyInput(reply: { value: string }): Promise { diff --git a/src/interactive/htmlBundle.ts b/src/interactive/htmlBundle.ts new file mode 100644 index 000000000..f99a5ead3 --- /dev/null +++ b/src/interactive/htmlBundle.ts @@ -0,0 +1,45 @@ +/** A generated HTML document and its package-owned assets, relative to index.html. */ +export type HtmlBundle = Record; + +export const maxHtmlBytes = 64 * 1024 * 1024; +export const maxHtmlFiles = 5000; + +export function checkHtmlPath(relative: string): void { + const parts = relative.split('/'); + if ( + parts.some( + (part) => + !part || + part === '.' || + part === '..' || + // eslint-disable-next-line no-control-regex -- widget assets must be valid portable file names + /[\\:<>"|?*\x00-\x1f]|[. ]$/.test(part) || + /^(?:con|aux|nul|prn|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part), + ) + ) { + throw new Error('Invalid path in HTML widget bundle'); + } +} + +export function checkHtmlSize(files: number, bytes: number): void { + if (files > maxHtmlFiles || !Number.isSafeInteger(bytes) || bytes < 0 || bytes > maxHtmlBytes) { + throw new Error('HTML bundle exceeds the 64 MiB / 5000 file limit'); + } +} + +export function validateHtmlBundle(files: HtmlBundle): number { + if (!Object.hasOwn(files, 'index.html')) { + throw new Error('HTML widget has no index.html'); + } + const entries = Object.entries(files); + let total = 0; + for (const [name, bytes] of entries) { + checkHtmlPath(name); + if (!(bytes instanceof Uint8Array)) { + throw new Error('Invalid HTML widget asset'); + } + total += bytes.length; + checkHtmlSize(entries.length, total); + } + return total; +} diff --git a/src/interactive/renderer.ts b/src/interactive/renderer.ts index 8f01b35f5..3085f2c55 100644 --- a/src/interactive/renderer.ts +++ b/src/interactive/renderer.ts @@ -241,7 +241,10 @@ export function activate(context: RendererContext): { }, 'Text', ); - toolbar.prepend(open, toggle); + toolbar.prepend(toggle); + if (!data.panel) { + toolbar.prepend(open); + } showView(); state.dispose = () => { state.table?.dispose(); @@ -347,7 +350,10 @@ export function activate(context: RendererContext): { }, 'Text', ); - toolbar.append(open, toggle, reset); + if (!data.panel) { + toolbar.append(open); + } + toolbar.append(toggle, reset); status.textContent = connectionHint(data); showView(); state.dispose = () => { @@ -508,7 +514,9 @@ export function activate(context: RendererContext): { iframe.srcdoc = String(data.text); } element.append(iframe); - toolbar.append(button('Open viewer', 'open', () => send(item, data, 'open'))); + if (!data.inlineOnly) { + toolbar.append(button('Open viewer', 'open', () => send(item, data, 'open'))); + } } else if (data.kind === 'url') { const label = document.createElement('span'); label.textContent = typeof data.url === 'string' ? data.url : ''; diff --git a/src/test/node/interactiveWebR.test.ts b/src/test/node/interactiveWebR.test.ts index 3efe96896..9562681be 100644 --- a/src/test/node/interactiveWebR.test.ts +++ b/src/test/node/interactiveWebR.test.ts @@ -96,7 +96,7 @@ suite('R Interactive webR provider', function () { await client.request('submit', { submission: { id, code } }); return id; } - async function wait(id: string, type: string): Promise { + async function wait(id: string | undefined, type: string): Promise { for (let i = 0; i < 500; i++) { const event = events.find((item) => item.executionId === id && item.type === type); if (event) { @@ -106,6 +106,9 @@ suite('R Interactive webR provider', function () { } throw new Error('Missing ' + type + ' for ' + id + ': ' + JSON.stringify(events.slice(-6))); } + function inspect(method: string, params: Record): Promise { + return client.request('inspect', { method, params }); + } function output(id: string): string { return events .filter((event) => event.type === 'stream' && event.executionId === id) @@ -140,6 +143,131 @@ suite('R Interactive webR provider', function () { } }); + test('shows native table and list outputs with live paging and nested navigation', async () => { + assert.equal(manifest.capabilities.tables, true); + assert.equal(manifest.capabilities.inspection, false); + const id = await submit( + [ + 'lst <- list(first = 1, nested = list(frame = mtcars), last = "end")', + 'View(mtcars)', + 'mtcars', + 'View(lst)', + 'lst', + ].join('\n'), + ); + assert.equal((await wait(id, 'finished')).data.state, 'success', output(id)); + const displays = events + .filter((e) => e.executionId === id && e.type === 'display') + .map((e) => e.data); + assert.deepEqual( + displays.map((d) => d.kind), + ['table', 'table', 'list', 'list'], + ); + const [table, , list] = displays; + assert.equal(table.totalRows, 32); + assert.equal((table.rows as unknown[]).length, 20); + const preview = table.rows as Record[]; + assert.equal(preview[0]['0'], 'Mazda RX4'); + assert.equal(preview[0]['1'], 21); + assert.equal(typeof table.printedText, 'string'); + + type TablePage = { totalRows: number; rows: Record[] }; + const meta = await inspect<{ + totalRows: number; + columns: { field: string; headerName: string }[]; + }>('dataview_init', { view_id: table.viewId }); + assert.equal(meta.totalRows, 32); + assert.deepEqual( + meta.columns.slice(1, 3).map((col) => col.headerName), + ['mpg', 'cyl'], + ); + const sorted = await inspect('dataview_page', { + view_id: table.viewId, + startRow: 0, + endRow: 2, + sortModel: [{ colId: '1', sort: 'desc' }], + }); + assert.deepEqual( + sorted.rows.map((row) => row['0']), + ['Toyota Corolla', 'Fiat 128'], + ); + const last = await inspect('dataview_page', { + view_id: table.viewId, + startRow: 31, + endRow: 32, + }); + assert.equal(last.rows[0]['0'], 'Volvo 142E'); + assert.deepEqual( + (list.children as { label: string }[]).map((x) => x.label), + ['$ first', '$ nested', '$ last'], + ); + const nav = await inspect<{ title: string; breadcrumbs: unknown[] }>('listview_navigate', { + view_id: list.viewId, + path: [2], + }); + assert.equal(nav.title, 'List$nested'); + assert.equal(nav.breadcrumbs.length, 2); + const items = await inspect<{ children: { label: string }[] }>('workspace_children', { + view_id: list.viewId, + path: [2], + start: 1, + }); + assert.deepEqual( + items.children.map((x) => x.label), + ['$ frame'], + ); + assert.equal( + await inspect('listview_view', { view_id: list.viewId, path: [2], index: 1 }), + true, + ); + const panel = await wait(undefined, 'viewer'); + assert.equal(panel.data.method, 'dataview'); + const params = panel.data.params as { source: string; title: string; view_id: string }; + assert.equal(params.source, 'table'); + assert.equal(params.title, 'List$nested$frame'); + const nested = await inspect('dataview_page', { + view_id: params.view_id, + startRow: 31, + endRow: 32, + }); + assert.equal(nested.rows[0]['0'], 'Volvo 142E'); + await assert.rejects(inspect('workspace', {}), /inspection/); + await assert.rejects(inspect('workspace_children', { name: 'mtcars' }), /inspection/); + }); + + test('bounds retained previews and uses handles for remaining table and list rows', async () => { + const id = await submit('data.frame(x = seq_len(2000))\nas.list(seq_len(502))'); + assert.equal((await wait(id, 'finished')).data.state, 'success', output(id)); + const [table, list] = events + .filter((e) => e.type === 'display' && e.executionId === id) + .map((e) => e.data); + assert.equal(table.sourceRows, 2000); + assert.equal(table.totalRows, 1000); + assert.equal((table.rows as unknown[]).length, 20); + assert.notEqual(table.fullViewId, table.viewId); + const full = await inspect<{ rows: Record[] }>('dataview_page', { + view_id: table.fullViewId, + startRow: 1999, + endRow: 2000, + }); + assert.equal(full.rows[0]['1'], 2000); + assert.equal((list.children as unknown[]).length, 500); + assert.equal(list.next_start, 501); + const rest = await inspect<{ children: { index: number }[] }>('workspace_children', { + view_id: list.viewId, + path: [], + start: 501, + }); + assert.deepEqual( + rest.children.map((item) => item.index), + [501, 502], + ); + await assert.rejects( + inspect('dataview_page', { view_id: table.fullViewId, startRow: 0, endRow: 1000000 }), + /page|rows/i, + ); + }); + test('mounts a project and retains R objects, files and PNG output across an editor reconnect', async () => { assert.equal(manifest.backend, 'webr'); assert.equal(manifest.rPath, undefined); @@ -171,6 +299,37 @@ suite('R Interactive webR provider', function () { assert.equal(fs.readFileSync(path.join(project, 'slope.txt'), 'utf8').trim(), '2'); }); + test('delivers widgets, tables, text fragments and nested input in expression order', async () => { + // Exercise the HTML transport without downloading an optional widget package in CI. + const id = await submit( + [ + 'folder <- tempfile(); dir.create(folder); writeLines("

widget

", file.path(folder, "index.html"))', + 'emit <- environment(getOption("vscodeR.webR.execute"))$send_widget', + 'cat("prefix"); emit(folder, 1L); data.frame(x = 1:2); cat("next"); emit(folder, 1L)', + 'reply <- readline("value? "); cat(paste("answer", reply))', + ].join('\n'), + ); + const prompt = await wait(id, 'input'); + const seen = events + .filter((item) => item.executionId === id) + .flatMap((item) => { + if (item.type === 'input') { + return ['input']; + } + if (item.type === 'display') { + return [String(item.data.kind)]; + } + if (item.type === 'stream' && ['prefix', 'next'].includes(String(item.data.text))) { + return [String(item.data.text)]; + } + return []; + }); + assert.deepEqual(seen, ['prefix', 'html', 'table', 'next', 'html', 'input']); + await client.request('input', { id: prompt.data.inputId, executionId: id, value: 'ok' }); + assert.equal((await wait(id, 'finished')).data.state, 'success'); + assert.match(output(id), /answer ok/); + }); + test('reports cell errors, answers nested prompts, and interrupts a busy or waiting cell without losing R state', async () => { const bad = await submit('stop("sample error")'); assert.equal((await wait(bad, 'finished')).data.state, 'error'); diff --git a/src/test/node/interactiveWebRWidget.test.ts b/src/test/node/interactiveWebRWidget.test.ts new file mode 100644 index 000000000..e0e3114ca --- /dev/null +++ b/src/test/node/interactiveWebRWidget.test.ts @@ -0,0 +1,119 @@ +import * as assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { load } from 'cheerio/slim'; +import { AssetStore } from '../../interactive/assets'; +import { maxHtmlBytes, validateHtmlBundle, type HtmlBundle } from '../../interactive/htmlBundle'; +import { prepareNodeWebR } from '../../webr/nodeRuntime'; +import { webRWidgetHtml } from '../../webr/widgetHtml'; +import { widgetRunner } from '../../webr/widget'; + +const encode = (text: string) => new TextEncoder().encode(text); +const fixture = (): HtmlBundle => ({ + 'index.html': encode( + '' + + '' + + '', + ), + 'libs/widget.js': encode('globalThis.widget = "";'), + 'libs/style/main.css': encode('.widget { background-image: url("../../img/plot.png"); }'), + 'img/plot.png': Uint8Array.of(0, 1, 2, 255), +}); + +suite('webR HTML widgets', () => { + test('retains the generated bundle as an ordinary desktop HTML asset', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'webr-widget-')); + try { + const store = new AssetStore(directory); + const files = fixture(); + const asset = store.importHtmlFiles(files); + assert.match(asset, /^[a-f0-9]{64}\/index\.html$/); + assert.deepEqual(store.read(asset), Buffer.from(files['index.html'])); + assert.deepEqual( + store.read(asset.replace('index.html', 'libs/widget.js')), + Buffer.from(files['libs/widget.js']), + ); + assert.equal(store.importHtmlFiles(files), asset); + assert.throws( + () => store.importHtmlFiles({ ...files, '../outside': encode('denied') }), + /Invalid path/, + ); + assert.throws( + () => validateHtmlBundle({ ...files, 'a\\..\\outside': encode('denied') }), + /Invalid path/, + ); + assert.throws(() => validateHtmlBundle({ 'file.js': encode('x') }), /index.html/); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); + + test('embeds local JS, CSS and its relative binary references without executing them', () => { + const html = webRWidgetHtml(fixture()); + const $ = load(html); + assert.equal($('script[src]').length, 0); + assert.equal($('script').first().text(), 'globalThis.widget = "<\\/script>";'); + assert.equal($('script[type="application/json"]').text(), '{"value":2}'); + assert.equal($('link[href]').length, 0); + assert.equal($('style').attr('media'), 'screen'); + assert.match($('style').text(), /data:image\/png;base64,AAEC\/w==/); + assert.equal($('img').attr('src'), 'data:image/png;base64,AAEC/w=='); + }); + + test('the host independently bounds retained worker output', () => { + const files = fixture(); + const piece = new Uint8Array(1024 * 1024); + for (let i = 0; i < maxHtmlBytes / piece.length; ++i) { + files['asset-' + i] = piece; + } + assert.throws(() => validateHtmlBundle(files), /64 MiB/); + }); + + test('worker capture rejects mounted or linked content and enforces its per-cell budget before sending', async function () { + this.timeout(30000); + const { WebR } = await import('webr'); + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'webr-widget # ')); + const project = path.join(root, 'project'); + let closeWorker: (() => void) | undefined; + const call = `function(dir, id = 1L) webr::eval_js(paste0("globalThis.Module.vscodeRWidget(", + encodeString(dir, quote='"'), ",", id, ")"))`; + try { + const baseUrl = await prepareNodeWebR(root, (stage) => + fs.promises.cp(path.dirname(require.resolve('webr')), stage, { recursive: true }), + ); + const runtime = new WebR({ baseUrl }); + closeWorker = () => runtime.close(); + fs.mkdirSync(project); + fs.writeFileSync(path.join(project, 'private.R'), 'project data'); + await runtime.init(); + await runtime.FS.mkdir('/project'); + await runtime.FS.mount('NODEFS', { root: project }, '/project'); + // Only the transport is needed by this dependency-free worker fixture. + await runtime.evalRVoid(widgetRunner); + await runtime.evalRVoid( + 'dir.create("/widget"); writeLines("

widget

", "/widget/index.html"); file.symlink("/project/private.R", "/widget/data.R")', + ); + const send = (directory: string) => + runtime.evalRString('(' + call + ')(dir)', { env: { dir: directory } }); + assert.match(await send('/widget'), /symlink/); + await runtime.evalRVoid( + 'unlink("/widget/data.R"); file.symlink("/project", "/widget/subdir")', + ); + assert.match(await send('/widget'), /symlink/); + await runtime.evalRVoid('unlink("/widget/subdir"); file.symlink("/project", "/alias")'); + assert.match(await send('/alias'), /Invalid widget directory/); + assert.match(await send('/project'), /Invalid widget directory/); + await runtime.evalRVoid( + 'for (i in 1:2500) file.create(file.path("/widget", as.character(i)))', + ); + // 2501 files fit once. A second send exceeds the aggregate cell budget. + assert.equal(await runtime.evalRBoolean('!nzchar((' + call + ')("/widget"))'), true); + assert.match(await send('/widget'), /5000 file limit/); + assert.equal(await runtime.evalRBoolean('!nzchar((' + call + ')("/widget",2L))'), true); + } finally { + closeWorker?.(); + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index ea46d88e1..0709f4e41 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -1033,6 +1033,7 @@ suite('Interactive VS Code integration', function () { }) as never); sandbox.stub(vscode.window, 'showInputBox').resolves(label); let manifest: SessionManifest | undefined; + const viewerPanels: vscode.WebviewPanel[] = []; try { for (const [key, value] of Object.entries(overrides)) { await config.update(key, value, vscode.ConfigurationTarget.Global); @@ -1106,8 +1107,69 @@ suite('Interactive VS Code integration', function () { Buffer.from(png.data).subarray(0, 8).toString('hex'), '89504e470d0a1a0a', ); + + // Exercise both View() and the controls of the notebook renderer. + const examples = 'View(mtcars); lst <- list(nested = list(answer = 42)); View(lst)'; + await vscode.commands.executeCommand('r.runSelection', examples); + const viewerCell = () => + notebook.getCells().find((item) => item.document.getText() === examples); + await until(() => viewerCell()?.executionSummary?.success === true); + const displays = viewerCell()! + .outputs.flatMap((output) => output.items) + .filter((item) => item.mime === DISPLAY_MIME) + .map( + (item) => + JSON.parse(Buffer.from(item.data).toString()) as Record, + ); + assert.deepStrictEqual( + displays.map((item) => item.kind), + ['table', 'list'], + ); + assert.strictEqual( + (displays[0].rows as Record[])[0]['0'], + 'Mazda RX4', + ); + assert.strictEqual((displays[1].children as { label: string }[])[0].label, '$ nested'); + await vscode.commands.executeCommand( + 'interactive.open', + { preserveFocus: false }, + notebook.uri, + ); + const owner = vscode.window.visibleNotebookEditors.find( + (item) => item.notebook === notebook, + ); + assert.ok(owner); + const actions = manager as unknown as { + rendererMessage( + editor: vscode.NotebookEditor, + message: Record, + ): Promise; + }; + const createPanel = vscode.window.createWebviewPanel; + sandbox + .stub(vscode.window, 'createWebviewPanel') + .callsFake((type, title, column, options) => { + const panel = createPanel(type, title, column, options); + if (type === 'dataview') { + viewerPanels.push(panel); + } + return panel; + }); + for (const display of displays) { + await actions.rendererMessage(owner, { + action: display.kind, + generation: display.generation, + displayId: display.displayId, + }); + } + assert.strictEqual(viewerPanels.length, 2, JSON.stringify(errors.args)); + assert.match(viewerPanels[0].title, /table/i); + assert.match(viewerPanels[1].title, /list/i); } finally { try { + for (const panel of viewerPanels) { + panel.dispose(); + } if (manifest) { sandbox .stub(vscode.window, 'showWarningMessage') diff --git a/src/test/web/webR.cjs b/src/test/web/webR.cjs index 23ec2cd5f..9c1890e20 100644 --- a/src/test/web/webR.cjs +++ b/src/test/web/webR.cjs @@ -191,6 +191,24 @@ exports.run = async () => { 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 rich = cell => items(cell) + .filter(item => item.mime === 'application/vnd.vscode-r.display+json') + .map(item => JSON.parse(new TextDecoder().decode(item.data))); + await command('r.runCommand', 'obj <- list(nest=list(text="hello", rows=mtcars)); View(mtcars); View(obj); mtcars; obj'); + const previews = rich(notebook.cellAt(notebook.cellCount - 1)); + assert(previews.map(p => p.kind).join(',') === 'table,list,table,list', 'View and bare objects must render in evaluation order.'); + assert(previews[0].rows.length === 20 && previews[0].sourceRows === 32 && + previews[1].children[0].has_children, 'Expected a paged table and an expandable list.'); + + await command('r.runCommand', [ + 'install.packages(c("plotly", "gapminder"))', + 'library(plotly); library(gapminder)', + 'p <- gapminder |> filter(year == 1977) |> ggplot(aes(gdpPercap, lifeExp, size=pop, color=continent)) + geom_point() + theme_bw()', + 'ggplotly(p)', + ].join('\n')); + const widget = rich(notebook.cellAt(notebook.cellCount - 1)).find(p => p.kind === 'htmlText'); + assert(widget?.text.includes('html-widget') && widget.text.includes('plotly'), 'A live Plotly widget should retain its JavaScript and data.'); + 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/src/web/interactive.ts b/src/web/interactive.ts index 6c65d7946..a3ddbcada 100644 --- a/src/web/interactive.ts +++ b/src/web/interactive.ts @@ -41,7 +41,37 @@ export class BrowserInteractive implements vscode.Disposable { }); }; this.controller.interruptHandler = (doc) => this.interrupt(doc); + const messages = vscode.notebooks.createRendererMessaging('r-interactive-renderer'); this.registrations = [ + messages.onDidReceiveMessage(async ({ editor, message: raw }) => { + const message = raw as Record | undefined; + if ( + !message || + typeof message !== 'object' || + !['table', 'page', 'list', 'listPage', 'listNavigate', 'listItem'].includes( + String(message.action), + ) + ) { + return; + } + const session = this.sessions.get(editor.notebook); + const reply = { + outputId: message.outputId, + action: message.action, + requestId: message.requestId, + }; + try { + if (!session) { + throw new Error( + 'This webR session has ended. Run the cell again for live controls.', + ); + } + const result = await session.viewers.rendererMessage(message); + await messages.postMessage({ ...reply, result }, editor); + } catch (error) { + await messages.postMessage({ ...reply, error: String(error) }, editor); + } + }), this.controller, vscode.workspace.registerNotebookSerializer(notebookType, new InteractiveSerializer(), { transientOutputs: false, @@ -100,7 +130,7 @@ export class BrowserInteractive implements vscode.Disposable { } let session = this.sessions.get(doc); if (!session) { - session = new BrowserSession(this.controller); + session = new BrowserSession(this.controller, this.context.extensionUri, doc); this.sessions.set(doc, session); } return session; diff --git a/src/web/session.ts b/src/web/session.ts index e702b8059..62eb8c7a7 100644 --- a/src/web/session.ts +++ b/src/web/session.ts @@ -4,11 +4,17 @@ import { OutputQueue } from '../interactive/outputQueue'; import { WebRConsole, type WebRConsoleEvent } from '../webr/console'; import { WEBR_BASE_URL } from '../webr/runtime'; import { sessionDirectory } from './files'; +import { BrowserViewers } from './viewers'; +import { webRWidgetHtml } from '../webr/widgetHtml'; interface ActiveCell { execution: vscode.NotebookCellExecution; output: OutputQueue; - pending: ({ type: 'stdout' | 'stderr'; text: string } | { type: 'plot'; png: Uint8Array })[]; + pending: ( + | { type: 'stdout' | 'stderr'; text: string } + | { type: 'plot'; png: Uint8Array } + | { type: 'rich'; output: vscode.NotebookCellOutput } + )[]; remaining: number; truncated: boolean; outputError?: unknown; @@ -28,7 +34,22 @@ export class BrowserSession implements vscode.Disposable { private closed = false; private readonly lifetime = new AbortController(); - constructor(private readonly controller: vscode.NotebookController) {} + readonly viewers: BrowserViewers; + constructor( + private readonly controller: vscode.NotebookController, + extension: vscode.Uri, + doc: vscode.NotebookDocument, + ) { + this.viewers = new BrowserViewers(extension, doc, (method, params) => + this.run(async () => { + const worker = this.worker; + if (!worker) { + throw new Error('This webR viewer is no longer connected.'); + } + return worker.console.inspect(method, params); + }), + ); + } // Queue file operations and submissions together. A stopped generation must // never execute work against a replacement session or a closed worker. @@ -104,6 +125,9 @@ export class BrowserSession implements vscode.Disposable { output: new OutputQueue( async () => { const outputs = active.pending.splice(0).map((value) => { + if (value.type === 'rich') { + return value.output; + } const item = value.type === 'plot' ? new vscode.NotebookCellOutputItem(value.png, 'image/png') @@ -164,6 +188,30 @@ export class BrowserSession implements vscode.Disposable { } private onEvent(event: WebRConsoleEvent): void { + if (event.type === 'viewer' && !this.closed) { + const p = event.params; + const view = vscode.workspace + .getConfiguration('r') + .get>('session.viewers.viewColumn')?.view; + if ( + view !== 'Disable' && + typeof p.view_id === 'string' && + (p.source === 'table' || p.source === 'list') + ) { + void this.viewers + .openValue( + p.source, + p.view_id, + typeof p.title === 'string' ? p.title : 'R Viewer', + ) + .catch((error: unknown) => { + if (!this.closed) { + void vscode.window.showErrorMessage(String(error)); + } + }); + } + return; + } const active = this.current; if (!active || this.closed) { return; @@ -177,6 +225,20 @@ export class BrowserSession implements vscode.Disposable { session?.replyInput(value ?? ''); } }); + } else if (event.type === 'display' || event.type === 'widget') { + try { + const data = + event.type === 'display' + ? event.data + : { kind: 'htmlText', text: webRWidgetHtml(event.files) }; + active.pending.push({ type: 'rich', output: this.viewers.output(data) }); + } catch (error) { + active.pending.push({ + type: 'stderr', + text: `Unable to display webR output: ${String(error)}\n`, + }); + } + active.output.schedule('cell'); } else if (event.type === 'plot') { active.pending.push(event); active.output.schedule('cell'); @@ -228,6 +290,7 @@ export class BrowserSession implements vscode.Disposable { this.current.execution.end(false, Date.now()); this.current = undefined; } + this.viewers.dispose(); this.lifetime.abort(); this.worker?.console.close(); this.worker = undefined; diff --git a/src/web/viewers.ts b/src/web/viewers.ts new file mode 100644 index 000000000..8ce80d40c --- /dev/null +++ b/src/web/viewers.ts @@ -0,0 +1,233 @@ +import * as vscode from 'vscode'; +import { DISPLAY_MIME } from '../interactive/notebook'; +import { queryTablePage } from '../interactive/tableQuery'; + +type Data = Record; +type Inspect = (method: string, params: Data) => Promise; + +function object(value: unknown): Data { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error('Invalid R viewer response.'); + } + return value as Data; +} +function entryPath(value: unknown): number[] { + const path = value ?? []; + if (!Array.isArray(path) || !path.every((index) => Number.isSafeInteger(index) && index > 0)) { + throw new Error('Invalid R list path.'); + } + return path as number[]; +} + +/** A saved cell carries its preview. Only its owning worker can service live requests. */ +export class BrowserViewers implements vscode.Disposable { + private readonly generation = crypto.randomUUID(); + private readonly panels = new Set(); + private closed = false; + + constructor( + private readonly extension: vscode.Uri, + private readonly doc: vscode.NotebookDocument, + private readonly inspect: Inspect, + ) {} + + public output(source: Data): vscode.NotebookCellOutput { + const displayId = crypto.randomUUID(); + const data = { + ...source, + displayId, + generation: this.generation, + connected: true, + ...(source.kind === 'htmlText' ? { inlineOnly: true } : {}), + }; + const fallback = + typeof source.printedText === 'string' + ? source.printedText + : source.kind === 'htmlText' + ? 'R HTML widget' + : source.kind === 'list' + ? 'R list' + : 'R table'; + return new vscode.NotebookCellOutput( + [ + vscode.NotebookCellOutputItem.json(data, DISPLAY_MIME), + vscode.NotebookCellOutputItem.text(fallback), + ], + { rDisplayId: displayId }, + ); + } + + async rendererMessage(message: Data): Promise { + if (this.closed || message.generation !== this.generation) { + throw new Error( + 'This output belongs to a previous webR session. Run its cell again to use live controls.', + ); + } + // Only dispatch addresses present in an output from this session. R handles + // are capability-like identifiers and must never come from renderer input. + const output = this.doc + .getCells() + .flatMap((cell) => cell.outputs) + .find((out) => out.metadata?.rDisplayId === message.displayId); + const item = output?.items.find((value) => value.mime === DISPLAY_MIME); + if (!item) { + throw new Error('This webR output is no longer available.'); + } + const data = object(JSON.parse(new TextDecoder().decode(item.data))); + if (data.generation !== this.generation || data.displayId !== message.displayId) { + throw new Error('This webR output is no longer connected.'); + } + if (message.action === 'table' && data.kind === 'table') { + await this.openValue('table', String(data.fullViewId ?? data.viewId), 'R Data Viewer'); + } else if (message.action === 'list' && data.kind === 'list') { + await this.openValue( + 'list', + String(data.viewId), + 'R List Viewer', + entryPath(message.path), + ); + } else { + return this.query(data, message); + } + } + + async openValue(kind: string, id: string, title: string, path: number[] = []): Promise { + if (kind === 'list') { + const params = { view_id: id, path }; + const navigation = object(await this.inspect('listview_navigate', params)); + const page = object(await this.inspect('workspace_children', { ...params, start: 1 })); + this.panel(title, { ...page, kind, viewId: id, navigation }); + } else if (kind === 'table') { + const meta = object(await this.inspect('dataview_init', { view_id: id })); + const page = object( + await this.inspect('dataview_page', { + view_id: id, + startRow: 0, + endRow: 20, + formatNumbers: true, + }), + ); + this.panel(title, { ...meta, ...page, kind, viewId: id }); + } + } + + private async query(data: Data, message: Data): Promise { + if (message.action === 'page' && data.kind === 'table') { + return queryTablePage(data, message, async (req) => + object(await this.inspect(req.method, req.params)), + ); + } + if (data.kind !== 'list') { + return; + } + const params = { view_id: data.viewId, path: entryPath(message.path) }; + if (message.action === 'listPage') { + const start = message.start; + if (!Number.isSafeInteger(start) || Number(start) < 1) { + throw new Error('Invalid R list page.'); + } + return this.inspect('workspace_children', { ...params, start }); + } + if (message.action === 'listNavigate' || message.action === 'listItem') { + const item = message.action === 'listItem'; + if (item && (!Number.isSafeInteger(message.index) || Number(message.index) < 1)) { + throw new Error('Invalid R list index.'); + } + const result = await this.inspect( + item ? 'listview_view' : 'listview_navigate', + item ? { ...params, index: message.index } : params, + ); + if (!result) { + throw new Error('This list item is no longer available.'); + } + return typeof result === 'object' ? { navigation: result } : undefined; + } + } + + private panel(title: string, data: Data): void { + if (this.closed) { + return; + } + const dist = vscode.Uri.joinPath(this.extension, 'dist'); + const panel = vscode.window.createWebviewPanel( + 'r.webR.viewer', + title, + { + viewColumn: vscode.ViewColumn.Beside, + preserveFocus: true, + }, + { + enableScripts: true, + localResourceRoots: [dist], + retainContextWhenHidden: true, + }, + ); + this.panels.add(panel); + const webview = panel.webview; + const displayId = crypto.randomUUID(); + const panelSecret = crypto.randomUUID(); + const dispose = webview.onDidReceiveMessage(async (message: Data) => { + if (this.closed) { + return; + } + if ( + !message || + message.panelSecret !== panelSecret || + message.displayId !== displayId || + message.generation !== this.generation + ) { + return; + } + try { + const result = await this.query(data, message); + await webview.postMessage({ + panelSecret, + outputId: message.outputId, + requestId: message.requestId, + action: message.action, + result, + }); + } catch (error) { + await webview.postMessage({ + panelSecret, + outputId: message.outputId, + requestId: message.requestId, + action: message.action, + error: String(error), + }); + } + }); + panel.onDidDispose(() => { + this.panels.delete(panel); + dispose.dispose(); + }); + const renderer = webview + .asWebviewUri(vscode.Uri.joinPath(dist, 'interactive-renderer.js')) + .toString(); + const nonce = crypto.randomUUID(); + webview.html = `
`; + } + + dispose(): void { + this.closed = true; + for (const panel of this.panels) { + panel.dispose(); + } + this.panels.clear(); + } +} diff --git a/src/webr/console.ts b/src/webr/console.ts index 99a78aa2e..baac33e1b 100644 --- a/src/webr/console.ts +++ b/src/webr/console.ts @@ -1,5 +1,7 @@ import type { WebR } from 'webr'; import { consoleRunner } from './consoleRunner'; +import { inspectWebRViewer, prepareWebRViewers } from './viewers'; +import { checkHtmlSize, type HtmlBundle, validateHtmlBundle } from '../interactive/htmlBundle'; export type WebRConsoleResult = 'success' | 'error' | 'interrupted'; @@ -7,7 +9,10 @@ export type WebRConsoleEvent = | { type: 'stream'; channel: 'stdout' | 'stderr'; text: string } | { type: 'started' } | { type: 'input'; prompt: string } - | { type: 'plot'; png: Uint8Array }; + | { type: 'plot'; png: Uint8Array } + | { type: 'display'; data: Record } + | { type: 'viewer'; method: 'dataview'; params: Record } + | { type: 'widget'; files: Record }; interface Cell { id: number; @@ -15,6 +20,9 @@ interface Cell { phase: 'preparing' | 'submitted' | 'running' | 'input' | 'finishing' | 'fence'; interrupted: boolean; outcome?: WebRConsoleResult; + widgetBytes: number; + widgetFiles: number; + widgetError?: boolean; resolve(result: WebRConsoleResult): void; reject(error: Error): void; } @@ -48,6 +56,7 @@ export class WebRConsole { } } await this.runtime.FS.mkdir(root); + await prepareWebRViewers(this.runtime); await this.runtime.evalRVoid(consoleRunner); void this.pump().catch((error) => this.end(error instanceof Error ? error : new Error(String(error))), @@ -71,6 +80,8 @@ export class WebRConsole { directory: root + '/' + id, phase: 'preparing', interrupted: false, + widgetBytes: 0, + widgetFiles: 0, resolve, reject, }; @@ -118,6 +129,16 @@ export class WebRConsole { } } + async inspect(method: string, params: Record): Promise { + if (this.closed) { + throw new Error('This webR session has ended.'); + } + if (this.active) { + throw new Error('R is busy. Retry when the cell finishes.'); + } + return inspectWebRViewer(this.runtime, method, params); + } + replyInput(value: string): void { const cell = this.active; if (!cell || cell.phase !== 'input' || cell.interrupted) { @@ -190,6 +211,64 @@ export class WebRConsole { } break; } + case 'vscode-r-widget': { + const packet = message.data as { id?: unknown; files?: HtmlBundle } | null; + if (cell && packet?.id === cell.id && packet.files && !cell.widgetError) { + try { + cell.widgetBytes += validateHtmlBundle(packet.files); + cell.widgetFiles += Object.keys(packet.files).length; + checkHtmlSize(cell.widgetFiles, cell.widgetBytes); + this.onEvent({ type: 'widget', files: packet.files }); + } catch (error) { + cell.widgetError = true; + this.onEvent({ + type: 'stream', + channel: 'stderr', + text: 'Unable to display the HTML widget: ' + String(error) + '\n', + }); + } + } + break; + } + case 'vscode-r-display': { + const data = message.data as Record | null; + if ( + cell && + (data?.kind === 'table' || data?.kind === 'list') && + typeof data.viewId === 'string' + ) { + this.onEvent({ type: 'display', data }); + } + break; + } + case 'vscode-r-viewer': { + // A retained Wasm object is opened by handle. Host filesystem paths + // are never accepted from the worker's viewer notification. + const request = message.data as { + method?: unknown; + params?: Record; + } | null; + const params = request?.params; + if ( + request?.method === 'dataview' && + params && + (params.source === 'table' || params.source === 'list') && + typeof params.view_id === 'string' + ) { + this.onEvent({ + type: 'viewer', + method: 'dataview', + params: { + source: params.source, + type: 'json', + title: params.title, + view_id: params.view_id, + navigation: params.navigation, + }, + }); + } + break; + } case 'vscode-r-execution': { const marker = message.data as { id?: unknown; state?: unknown } | null; if (!cell || marker?.id !== cell.id) { @@ -206,7 +285,8 @@ export class WebRConsole { marker.state === 'error' || marker.state === 'interrupted' ) { - cell.outcome = marker.state; + cell.outcome = + cell.widgetError && marker.state === 'success' ? 'error' : marker.state; } break; } diff --git a/src/webr/consoleRunner.ts b/src/webr/consoleRunner.ts index e11ba995a..dfb4e8e98 100644 --- a/src/webr/consoleRunner.ts +++ b/src/webr/consoleRunner.ts @@ -1,3 +1,5 @@ +import { widgetRunner } from './widget'; + // The console host reads the typed outcome and all subsequent output through the // next top-level prompt. R can print deferred warnings after the outcome. export const consoleRunner = String.raw` @@ -51,6 +53,15 @@ base::local({ return ops.write(...args); } }; } + const channel = runtime.webr.channel; + const write = channel.write.bind(channel); + channel.write = (message, transfer) => { + if (['vscode-r-widget', 'vscode-r-display', 'vscode-r-viewer'].includes(message.type)) { + flush(0); + flush(1); + } + return write(message, transfer); + }; const setPrompt = runtime.webr.setPrompt; runtime.webr.setPrompt = (prompt) => { flush(0); @@ -60,6 +71,8 @@ base::local({ return null; })()") +${widgetRunner} + rich_value <- getOption("vscodeR.webR.richValue") default_device <- getOption("device") notify <- function(id, state) { webr::eval_js(sprintf( @@ -97,15 +110,18 @@ base::local({ if (identical(getOption("device"), default_device)) options(device = capture_device) expressions <- parse(file = file.path(directory, "cell.R"), keep.source = TRUE, encoding = "UTF-8") - for (expression in expressions) { - value <- withVisible(eval(expression, envir = .GlobalEnv)) + for (index in seq_along(expressions)) { + value <- withVisible(eval(expressions[[index]], envir = .GlobalEnv)) if (file.exists(cancel)) { # Returning an empty console input releases a blocked # readline(). Give R a chance to consume its interrupt. Sys.sleep(0) return("interrupted") } - if (value$visible) print(value$value) + if (value$visible && !display_widget(value$value, directory, id) && + !rich_value(value$value)) { + print(value$value) + } } "success" } diff --git a/src/webr/resources/viewer-jsonlite.tgz b/src/webr/resources/viewer-jsonlite.tgz new file mode 100644 index 000000000..244aab270 Binary files /dev/null and b/src/webr/resources/viewer-jsonlite.tgz differ diff --git a/src/webr/viewerJsonlite.ts b/src/webr/viewerJsonlite.ts new file mode 100644 index 000000000..551cddc02 --- /dev/null +++ b/src/webr/viewerJsonlite.ts @@ -0,0 +1,6 @@ +// Both extension hosts and the detached agent embed this resource. Return a fresh +// buffer for each worker because webR can transfer ownership across the channel. +const archive = require('../../dist/resources/webr-viewer-jsonlite.json') as string; +export function viewerJsonlite(): Uint8Array { + return Uint8Array.from(atob(archive), (character) => character.charCodeAt(0)); +} diff --git a/src/webr/viewerRunner.ts b/src/webr/viewerRunner.ts new file mode 100644 index 000000000..5a8ec9619 --- /dev/null +++ b/src/webr/viewerRunner.ts @@ -0,0 +1,64 @@ +// esbuild embeds the generated resource in each runtime bundle. Node tests load +// it from dist after the normal compile step. +const nativeViewerSource = require('../../dist/resources/webr-viewers.json') as string; + +export const viewerRunner = String.raw` +base::local({ +${nativeViewerSource} + + .sess_env <- new.env(parent = emptyenv()) + .sess_env$tempdir <- tempdir() + .sess_env$interactive_connected <- TRUE + .sess_env$dataview_registry <- new.env(parent = emptyenv()) + + # Keep payloads as data throughout the bridge. JS reads a complete JSON + # envelope from an R-owned file while R is paused in eval_js(). + send <- function(type, data) { + json <- ipc_json(list(type = type, data = data)) + if (nchar(json, type = "bytes") > 2 * 1024^2) + stop("Rich output exceeds 2 MiB. Display a smaller preview.") + file <- tempfile("vscode-view-") + on.exit(unlink(file)) + writeBin(charToRaw(enc2utf8(as.character(json))), file) + file_json <- jsonlite::toJSON(file, auto_unbox = TRUE) + webr::eval_js(paste0("(globalThis.Module.webr.channel.write(JSON.parse(", + "globalThis.Module.FS.readFile(", file_json, ", {encoding:'utf8'}))), null)")) + invisible(TRUE) + } + # The viewer bridge uses worker-local handles; jdv needs a native socket. + .jdv_supported <- function() FALSE + .interactive_event <- function(type, data) send("vscode-r-display", data) + .interactive_rich_value <- .interactive_viewer_value + notify_client <- function(method, params) { + if (!identical(method, "dataview") || !params$source %in% c("table", "list")) + stop("webR supports table, list and vector viewers.") + send("vscode-r-viewer", list(method = method, params = params)) + } + + # Replace both the attached export and the namespace export in this worker. + # A user's own View binding in .GlobalEnv retains its usual precedence. + for (env in list(asNamespace("utils"), as.environment("package:utils"))) { + locked <- bindingIsLocked("View", env) + if (locked) unlockBinding("View", env) + tryCatch(assign("View", show_dataview, env), finally = if (locked) lockBinding("View", env)) + } + + handlers <- inspection_handlers()[c("workspace_children", "listview_navigate", "listview_view", + "dataview_init", "dataview_page", "dataview_dispose")] + inspect <- function(method, json) { + if (!is.character(method) || length(method) != 1L || !method %in% names(handlers)) + stop("Unsupported webR viewer request.") + params <- inspection_validate(method, inspection_decode(json)) + if (method == "workspace_children" && is.null(params$view_id)) + stop("List inspection requires a retained view ID.") + if (method == "dataview_page") { + start <- params$startRow %||% 0L + end <- params$endRow %||% (start + 500L) + if (start < 0 || end < start || end - start > 500L || end > .Machine$integer.max) + stop("Invalid table page. Request at most 500 rows.") + } + inspection_encode(handlers[[method]](params)) + } + options(vscodeR.webR.richValue = .interactive_viewer_value, vscodeR.webR.inspect = inspect) +}, envir = base::new.env(parent = base::asNamespace("utils"))) +`; diff --git a/src/webr/viewers.ts b/src/webr/viewers.ts new file mode 100644 index 000000000..7eddd0055 --- /dev/null +++ b/src/webr/viewers.ts @@ -0,0 +1,41 @@ +import type { WebR } from 'webr'; +import { viewerJsonlite } from './viewerJsonlite'; +import { viewerRunner } from './viewerRunner'; + +/** Load the viewer's private dependency without adding its directory to the user's library paths. */ +export async function prepareWebRViewers(runtime: WebR): Promise { + if (!(await runtime.evalRBoolean('base::isNamespaceLoaded("jsonlite")'))) { + const library = '/tmp/vscode-r-viewer-library'; + const archive = library + '/jsonlite.tgz'; + await runtime.FS.mkdir(library); + await runtime.FS.writeFile(archive, viewerJsonlite()); + try { + await runtime.evalRVoid( + 'utils::untar(archive, exdir = library, tar = "internal"); base::loadNamespace("jsonlite", lib.loc = library)', + { env: { archive, library } }, + ); + } finally { + await runtime.FS.unlink(archive); + } + } + await runtime.evalRVoid(viewerRunner); +} + +/** Use native sess validation and its size-limited JSON result envelope. Parameters are R data. */ +export async function inspectWebRViewer( + runtime: WebR, + method: string, + params: Record, +): Promise { + const raw = await runtime.evalRString( + 'base::getOption("vscodeR.webR.inspect")(method, packet)', + { + env: { method, packet: JSON.stringify(params) }, + }, + ); + const reply = JSON.parse(raw) as { version?: unknown; result?: unknown }; + if (reply?.version !== 1) { + throw new Error('Invalid webR viewer response.'); + } + return reply.result; +} diff --git a/src/webr/widget.ts b/src/webr/widget.ts new file mode 100644 index 000000000..81814fc63 --- /dev/null +++ b/src/webr/widget.ts @@ -0,0 +1,73 @@ +import { maxHtmlBytes, maxHtmlFiles } from '../interactive/htmlBundle'; + +// Evaluated inside the webR worker. Reading through its own FS while R is +// paused preserves the channel position without queueing an RPC behind R or +// a nested readline(). FS.readFile returns private buffers we can transfer. +const installWidgetTransport = String.raw`(() => { + const runtime = globalThis.Module; + const fs = runtime.FS; + let cell, bytes = 0, count = 0; + runtime.vscodeRWidget = (directory, id) => { + try { + if (cell !== id) { cell = id; bytes = 0; count = 0; } + const root = fs.lookupPath(directory, {follow: false, follow_mount: false}).node; + if (root.mounted || !fs.isDir(root.mode) || root.mount.type !== fs.filesystems.MEMFS || + fs.getPath(root) !== directory) throw Error('Invalid widget directory'); + const entries = []; + const dirs = [[root, '']]; + let size = 0, visited = 0; + while (dirs.length) { + const [dir, prefix] = dirs.pop(); + for (const [name, node] of Object.entries(dir.contents)) { + if (++visited > ${2 * maxHtmlFiles}) throw Error('HTML widget has too many entries'); + if (name === '.' || name === '..' || name.includes('/')) throw Error('Invalid widget file name'); + if (node.mounted || node.mount !== root.mount) throw Error('HTML widgets cannot include mounts'); + const path = prefix + name; + if (fs.isDir(node.mode)) { + dirs.push([node, path + '/']); + } else if (fs.isFile(node.mode)) { + size += fs.lstat(directory + '/' + path).size; + entries.push(path); + if (!Number.isSafeInteger(size) || bytes + size > ${maxHtmlBytes} || + count + entries.length > ${maxHtmlFiles}) { + throw Error('HTML widgets exceed the 64 MiB / 5000 file limit for this cell'); + } + } else throw Error('HTML widgets cannot include symlinks or special files'); + } + } + if (!entries.includes('index.html')) throw Error('HTML widget has no index.html'); + const files = Object.create(null); + const transfer = []; + for (const path of entries) { + files[path] = fs.readFile(directory + '/' + path); + transfer.push(files[path].buffer); + } + runtime.webr.channel.write({type: 'vscode-r-widget', data: {id, files}}, transfer); + bytes += size; + count += entries.length; + return ""; + } catch (error) { + return error.message || String(error); + } + }; + return null; +})()`; + +/** Included in the private R console environment. Errors return through the usual R cell outcome. */ +export const widgetRunner = String.raw` + webr::eval_js(${JSON.stringify(installWidgetTransport)}) + send_widget <- function(directory, id) { + error <- webr::eval_js(paste0("globalThis.Module.vscodeRWidget(", + jsonlite::toJSON(directory, auto_unbox = TRUE), ",", sprintf("%.0f", id), ")")) + if (nzchar(error)) stop(error, call. = FALSE) + invisible(TRUE) + } + display_widget <- function(value, directory, id) { + if (!inherits(value, "htmlwidget")) return(FALSE) + stage <- tempfile("widget-", tmpdir = directory) + if (!dir.create(stage)) stop("Could not create the HTML widget directory") + on.exit(unlink(stage, recursive = TRUE)) + htmlwidgets::saveWidget(value, file.path(stage, "index.html"), selfcontained = FALSE) + send_widget(stage, id) + } +`; diff --git a/src/webr/widgetHtml.ts b/src/webr/widgetHtml.ts new file mode 100644 index 000000000..a5492091e --- /dev/null +++ b/src/webr/widgetHtml.ts @@ -0,0 +1,124 @@ +import { load } from 'cheerio/slim'; +import { checkHtmlSize, type HtmlBundle, validateHtmlBundle } from '../interactive/htmlBundle'; + +const utf8 = new TextDecoder(); +const mime: Record = { + svg: 'image/svg+xml', + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + gif: 'image/gif', + webp: 'image/webp', + ico: 'image/x-icon', + woff: 'font/woff', + woff2: 'font/woff2', + ttf: 'font/ttf', + otf: 'font/otf', + eot: 'application/vnd.ms-fontobject', + css: 'text/css', +}; + +function binaryUrl(bytes: Uint8Array, type: string): string { + const chunks: string[] = []; + for (let i = 0; i < bytes.length; i += 0x4000) { + chunks.push(String.fromCharCode(...bytes.subarray(i, i + 0x4000))); + } + return 'data:' + type + ';base64,' + btoa(chunks.join('')); +} + +/** Inline a saved widget's static dependencies for an opaque, sandboxed browser iframe. */ +export function webRWidgetHtml(files: HtmlBundle): string { + validateHtmlBundle(files); + const $ = load(utf8.decode(files['index.html'])); + const origin = 'https://widget.invalid'; + let expanded = files['index.html'].length; + const reserve = (bytes: number) => { + expanded += bytes; + checkHtmlSize(1, expanded); + }; + const resolve = (reference: string, from: string): string | undefined => { + if (!reference || /^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(reference)) { + return; + } + try { + const base = new URL(from.split('/').map(encodeURIComponent).join('/'), origin); + const url = new URL(reference, base); + const path = decodeURIComponent(url.pathname.slice(1)); + if (url.origin === origin && Object.hasOwn(files, path)) { + return path; + } + } catch { + // Leave malformed or external references to the sandboxed document. + } + }; + const dataUrl = (reference: string, from: string): string | undefined => { + const file = resolve(reference, from); + if (!file) { + return; + } + const type = mime[file.split('.').pop()?.toLowerCase() ?? ''] ?? 'application/octet-stream'; + reserve(4 * Math.ceil(files[file].length / 3)); + return ( + binaryUrl(files[file], type) + + (reference.includes('#') ? reference.slice(reference.indexOf('#')) : '') + ); + }; + const css = (text: string, from: string) => + text.replace( + /url\(\s*(["']?)([^"')]+)\1\s*\)/gi, + (original, _quote: string, ref: string) => { + const url = dataUrl(ref.trim(), from); + return url ? 'url("' + url + '")' : original; + }, + ); + $('style').each((_, element) => { + const style = $(element); + style.text(css(style.text(), 'index.html')); + }); + $('[style]').each((_, element) => { + const tag = $(element); + tag.attr('style', css(tag.attr('style')!, 'index.html')); + }); + $('script[src]').each((_, element) => { + const script = $(element); + const file = resolve(script.attr('src') ?? '', 'index.html'); + if (file) { + reserve(files[file].length); + script + .removeAttr('src') + .text(utf8.decode(files[file]).replace(/<\/(?=script)/gi, '<\\/')); + } + }); + $('link[href]').each((_, element) => { + const link = $(element); + const ref = link.attr('href') ?? ''; + const file = resolve(ref, 'index.html'); + if (file && link.attr('rel')?.toLowerCase().split(/\s+/).includes('stylesheet')) { + reserve(files[file].length); + const style = $('').text( + css(utf8.decode(files[file]), file).replace(/<\/(?=style)/gi, '<\\/'), + ); + const media = link.attr('media'); + if (media) { + style.attr('media', media); + } + link.replaceWith(style); + } else { + const url = dataUrl(ref, 'index.html'); + if (url) { + link.attr('href', url); + } + } + }); + $('img[src],source[src],input[src],audio[src],video[src],video[poster]').each((_, element) => { + const tag = $(element); + for (const attr of ['src', 'poster']) { + const ref = tag.attr(attr); + const url = ref && dataUrl(ref, 'index.html'); + if (url) { + tag.attr(attr, url); + } + } + }); + return $.html(); +} diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index adc55ddeb..e704a80b1 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -160,7 +160,7 @@ Table headings and values use the same alignment: numbers (including integer64 I Printed snapshots require a session started with this extension build; older output explains why Text is unavailable. Snapshots retain at most 256 KiB of printed text, with a truncation notice. If a custom printer fails, the rich table remains available and the Text tooltip explains the failure. Live table paging and the full data viewer still require the original R process. -When the [jdv](./interactive-viewers.md#jdv) package can be used, inline tables and lists are served by jdv: an inline table references the original object instead of a saved copy of its first rows, and explicit `View()` opens the Data Viewer panel instead of an inline preview. The rest of this section describes the built-in viewer. +In a native arf session, [jdv](./interactive-viewers.md#jdv) serves inline tables and lists when available. The inline table references the original R object and `View()` opens the Data Viewer panel. webR uses the built-in table and list viewers described below. Data inspection does not initialize or advance R's random-number stream, so opening a table between `set.seed()` and a simulation or train/test split leaves the draws unchanged. Inline tables retain a snapshot of up to **1,000 rows**, reduced to fit **100,000 cells** for wide tables (at least one row). Row subsetting gives data.table snapshots independent columns without a full deep copy. Later `:=`, `setnames()`, and `setorder()` calls do not change those saved rows. Reference assignments remain quiet like the R console; evaluate `DT` or use `DT[, x := value][]` to display the result, or call `View()` / `sess::display()` explicitly. @@ -266,7 +266,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. Install session packages with `install.packages("ggplot2")` and load them with `library(ggplot2)`. The repository must supply compatible WebAssembly binaries. +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. Evaluating a data frame or a plain list, or calling `View()` on it, shows an inline preview. Use the arrows for table pages or expand a list entry to inspect its children. **Data viewer** and **List viewer** open a larger view of the same session object. HTML widgets such as `plotly::ggplotly(p)` include their JavaScript dependencies and render in an isolated interactive frame. 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.