From 0e8d2c2c1cb28cf1252d78020de4e536e9a8573d Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 30 Nov 2026 16:24:38 +0000 Subject: [PATCH 1/2] feat: offer to install jdv in the managed tool library on View() When no compatible jdv is available, an explicit View() in the terminal or in an Interactive cell, including the code that a Workspace root item runs, now offers to install jdv in the vscode-R managed tool library through the same file-based consent as jgd and rstudioapi. The installed copy is loaded with loadNamespace(lib.loc = ...) without adding the tool library to .libPaths(). A compatible copy in the user's libraries is still preferred, and an already loaded older jdv asks for a restart instead of being replaced. Short requests from the editor, such as opening a nested Workspace item, never start an installation. Without jdv they keep the sess data viewer, as does a declined or failed installation. Arrow input without nanoarrow is ruled out before jdv is selected, so it never triggers an installation. Opening a nested Workspace item in an Interactive session now requires control of the session and uses the controlling window's jdv listener. Errors from that request are shown where the item was clicked. --- .github/workflows/main.yml | 2 + R/attach_sess.R | 9 + R/prepare-tools.R | 41 +++- R/tests/prepare-jdv.R | 217 +++++++++++++++++++ R/tests/tool-library.R | 2 +- R/tool-library.R | 2 +- package.json | 1 + sess/R/handlers.R | 74 ++++++- sess/R/hooks.R | 39 +++- sess/R/interactive.R | 1 + src/interactive/agent.ts | 16 +- src/interactive/backends/sessBackend.ts | 13 ++ src/interactive/backends/sessPreparation.ts | 25 ++- src/interactive/manager.ts | 26 +++ src/interactive/protocol.ts | 1 + src/session.ts | 5 +- src/test/node/interactiveRuntime.test.ts | 19 +- src/toolConsentAdapter.ts | 1 + src/toolVersions.ts | 1 + src/workspaceViewer.ts | 21 +- website/docs/features/interactive-viewers.md | 14 +- 21 files changed, 473 insertions(+), 57 deletions(-) create mode 100644 R/tests/prepare-jdv.R diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 4ab36fa8e..b46e0e44f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -76,6 +76,8 @@ jobs: - uses: ./.github/actions/prepare-test-runtime - name: Verify terminal profile inheritance run: Rscript --vanilla R/tests/terminal-profile.R + - name: Verify managed jdv preparation + run: pnpm run test:prepare-jdv - name: Verify managed jgd preparation run: pnpm run test:prepare-jgd - name: Verify managed rstudioapi preparation diff --git a/R/attach_sess.R b/R/attach_sess.R index 1e3cc6d07..f2e804334 100644 --- a/R/attach_sess.R +++ b/R/attach_sess.R @@ -384,6 +384,15 @@ vscode_r_attach_sess <- function( args$attachment_id <- attachment_id args$auto_activate <- auto_activate } + if (exists(".configure_jdv_tools", envir = ns, inherits = FALSE)) { + get(".configure_jdv_tools", envir = ns)(list( + tool_root = tool_root, + consent_directory = tool_consent_directory, + library_helper = tool_library_helper, + consent_helper = tool_consent_helper, + prepare_helper = tool_prepare_helper + )) + } vscode_r_with_rstudioapi( use_rstudioapi, tool_prepare_helper, diff --git a/R/prepare-tools.R b/R/prepare-tools.R index 1026a8fb3..eb0383de2 100644 --- a/R/prepare-tools.R +++ b/R/prepare-tools.R @@ -27,6 +27,15 @@ vscode_r_connect_with_jgd <- function( connect(allow_jgd = ready) } +# Source the tool helpers once, so a caller can reuse them across preparations. +vscode_r_load_tool_helpers <- function(helpers) { + tools <- new.env(parent = environment(vscode_r_load_tool_helpers)) + for (helper in helpers) { + sys.source(helper, envir = tools) + } + tools +} + # Select, install if approved, and eagerly load one tool package. Returns TRUE # when a compatible copy is loaded, otherwise prints a short message and # returns FALSE so the caller can continue with its fallback. `policy` is the @@ -43,7 +52,8 @@ vscode_r_prepare_tool_package <- function( minimum_version, support, fallback, - report_load_failure = TRUE + report_load_failure = TRUE, + tool_environment = vscode_r_load_tool_helpers(helpers) ) { if (!(is.logical(can_prompt) && length(can_prompt) == 1L && !is.na(can_prompt))) { stop("can_prompt must be a single non-NA logical value.", call. = FALSE) @@ -56,10 +66,6 @@ vscode_r_prepare_tool_package <- function( tryCatch( { - tool_environment <- new.env(parent = environment(vscode_r_prepare_tool_package)) - for (helper in helpers) { - sys.source(helper, envir = tool_environment) - } if (!can_prompt) { # A compatible ordinary or managed copy remains usable without resolving a new plan. return(!is.null(tool_environment$tool_library_load(package, minimum_version, tool_root))) @@ -164,3 +170,28 @@ vscode_r_prepare_rstudioapi <- function( report_load_failure = FALSE ) } + +# Select an available jdv before permitting an explicit View() to ask for installation. +vscode_r_prepare_jdv <- function( + tool_root, + consent_directory, + library_helper, + consent_helper, + minimum_version, + can_prompt, + tool_environment +) { + vscode_r_prepare_tool_package( + "jdv", + "once", + tool_root, + consent_directory, + library_helper, + consent_helper, + can_prompt, + minimum_version, + support = "jdv data viewer", + fallback = "using the available data viewer fallback; install a compatible jdv in your R library", + tool_environment = tool_environment + ) +} diff --git a/R/tests/prepare-jdv.R b/R/tests/prepare-jdv.R new file mode 100644 index 000000000..b015ec805 --- /dev/null +++ b/R/tests/prepare-jdv.R @@ -0,0 +1,217 @@ +# Run with the freshly installed sess on R_LIBS. All jdv candidates are local fixtures. +loadNamespace("sess") +loadNamespace("processx") +loadNamespace("jsonlite") +loadNamespace("later") +local({ + root <- tempfile("prepare-jdv-") + dir.create(root) + on.exit(unlink(root, recursive = TRUE), add = TRUE) + helpers <- normalizePath(file.path("R", c("tool-library.R", "tool-consent.R", "prepare-tools.R"))) + source(helpers[[1L]], local = TRUE) + + fixture <- function(version, broken = FALSE) { + package <- file.path(root, paste0("source-", version, if (broken) "-broken"), "jdv") + dir.create(file.path(package, "R"), recursive = TRUE) + writeLines( + c( + "Package: jdv", + paste("Version:", version), + "Title: Local Viewer Fixture", + "Description: A local test fixture for the viewer.", + "License: MIT", + "Author: Test Author", + "Maintainer: Test Author " + ), + file.path(package, "DESCRIPTION") + ) + writeLines("exportPattern('^jdv_')", file.path(package, "NAMESPACE")) + writeLines( + c( + "state <- new.env(parent=emptyenv())", + "jdv_connection <- function() if (is.null(state$address)) list(state='disconnected') else list(state='connected', address=state$address)", + "jdv_connect <- function(address) state$address <- address", + "jdv_disconnect <- function() state$address <- NULL", + "jdv_binding <- function(...) NULL", + "jdv_register <- function(x, title, ...) {", + " options(test.jdv.open=list(title=title, address=state$address))", + " list(id='fixture', generation=1L)", + "}", + if (broken) ".onLoad <- function(...) stop('fixture load failure')" + ), + file.path(package, "R", "fixture.R") + ) + package + } + run_r <- function(args) { + output <- system2(file.path(R.home("bin"), "R"), args, stdout = TRUE, stderr = TRUE) + if (!is.null(attr(output, "status"))) { + stop(paste(output, collapse = "\n")) + } + invisible(output) + } + repository <- function(package, name) { + repo <- file.path(root, name) + contrib <- file.path(repo, "src", "contrib") + dir.create(contrib, recursive = TRUE) + original <- setwd(contrib) + on.exit(setwd(original)) + run_r(c("CMD", "build", shQuote(package))) + tools::write_PACKAGES(".", type = "source") + paste0("file:///", sub("^/", "", normalizePath(repo, winslash = "/"))) + } + old <- fixture("0.0.1") + valid <- fixture("0.1.0") + repo <- repository(valid, "valid") + broken_repo <- repository(fixture("0.1.0", broken = TRUE), "broken") + install <- function(package, library) { + dir.create(library, recursive = TRUE) + run_r(c("CMD", "INSTALL", "-l", shQuote(library), shQuote(package))) + } + old_library <- file.path(root, "old-library") + valid_library <- file.path(root, "valid-library") + install(old, old_library) + install(valid, valid_library) + + responder <- function(directory, decision, log) { + script <- " + args <- commandArgs(TRUE) + deadline <- Sys.time() + 15 + repeat { + requests <- list.files(args[[1L]], pattern='[.]request$', full.names=TRUE) + if (length(requests)) break + if (Sys.time() >= deadline) quit(status=1L) + Sys.sleep(0.01) + } + writeLines(readLines(requests[[1L]]), args[[3L]]) + response <- sub('[.]request$', '.response', requests[[1L]]) + temporary <- paste0(response, '.tmp') + writeLines(args[[2L]], temporary) + stopifnot(file.rename(temporary, response)) + " + script_path <- paste0(log, ".R") + writeLines(script, script_path) + processx::process$new( + file.path(R.home("bin"), "Rscript"), + c("--vanilla", script_path, directory, decision, log), + stderr = paste0(log, ".err") + ) + } + + check <- function(mode) { + tool_root <- file.path(root, mode) + consent <- file.path(tool_root, "consent") + dir.create(consent, recursive = TRUE) + opts <- options( + repos = c(CRAN = if (mode == "failed") broken_repo else repo), + pkgType = "source", + test.jdv.open = NULL + ) + paths <- .libPaths() + user <- switch( + mode, + approved = old_library, + old_loaded = old_library, + compatible = valid_library, + consent + ) + .libPaths(c(user, .Library), include.site = FALSE) + expected_paths <- .libPaths() + if (mode == "old_loaded") { + loadNamespace("jdv", lib.loc = old_library) + } + state <- sess:::.sess_env + pipe <- processx::conn_create_pipepair() + state$con <- pipe[[2L]] + state$tempdir <- root + state$latest_plot_path <- file.path(root, "plot.png") + state$attach_jdv <- list(address = "fixture-address") + sess:::.configure_jdv_tools(list( + tool_root = tool_root, + consent_directory = consent, + library_helper = helpers[[1L]], + consent_helper = helpers[[2L]], + prepare_helper = helpers[[3L]] + )) + sess:::runtime_start(use_rstudioapi = FALSE, plot_backend = "standard") + child <- NULL + on.exit({ + if (!is.null(child)) { + child$kill() + } + sess:::runtime_stop() + sess:::.configure_jdv_tools(NULL) + state$con <- NULL + state$attach_jdv <- NULL + lapply(pipe, close) + if (isNamespaceLoaded("jdv")) { + unloadNamespace("jdv") + } + .libPaths(paths) + options(opts) + rm(list = "jdv_fixture_root", envir = .GlobalEnv) + }) + root_value <- list(table = data.frame(value = 1L)) + assign("jdv_fixture_root", root_value, envir = .GlobalEnv) + selector <- list(list(kind = "index", value = 1L, name = "table")) + log <- file.path(root, paste0(mode, ".consent")) + if (mode %in% c("approved", "declined", "failed")) { + child <- responder(consent, if (mode == "declined") "decline" else "approve", log) + } + if (mode == "approved") { + # Missing nanoarrow must short-circuit before selecting or installing jdv. + stopifnot(!requireNamespace("nanoarrow", quietly = TRUE)) + utils::View(structure(list(), class = "RecordBatchReader")) + stopifnot(!isNamespaceLoaded("jdv"), !length(list.files(consent))) + # A nested Workspace open never starts installation; it keeps the sess viewer. + stopifnot(isTRUE(sess:::handle_workspace_view("jdv_fixture_root", selector))) + stopifnot(!isNamespaceLoaded("jdv"), !length(list.files(consent))) + payload <- processx::conn_read_chars(pipe[[1L]]) + stopifnot(grepl('"method":"dataview"', payload, fixed = TRUE)) + } + if (mode == "compatible") { + stopifnot(sess:::handle_workspace_view("jdv_fixture_root", selector)) + stopifnot(identical(getOption("test.jdv.open")$address, "fixture-address")) + } + # The Workspace root action currently evaluates this same View() expression. + messages <- capture.output( + View(get("jdv_fixture_root", envir = .GlobalEnv, inherits = FALSE), title = "root"), + type = "message" + ) + if (!is.null(child)) { + child$wait(2000) + stopifnot(child$get_exit_status() == 0L) + plan <- readLines(log) + stopifnot(identical(plan[c(4L, 6L)], c("once", "jdv"))) + } + if (mode %in% c("approved", "compatible")) { + actual <- normalizePath(getNamespaceInfo(asNamespace("jdv"), "path")) + library <- if (mode == "approved") tool_library_path(tool_root) else valid_library + stopifnot(identical(actual, normalizePath(file.path(library, "jdv")))) + stopifnot(identical(getOption("test.jdv.open")$title, "root")) + stopifnot(sess:::handle_workspace_view("jdv_fixture_root", selector)) + stopifnot(identical(getOption("test.jdv.open")$title, "jdv_fixture_root$table")) + } else { + stopifnot(is.null(getOption("test.jdv.open"))) + payload <- processx::conn_read_chars(pipe[[1L]]) + stopifnot(grepl('"method":"dataview"', payload, fixed = TRUE)) + expected <- switch( + mode, + declined = "not approved", + failed = "could not prepare", + old_loaded = "Restart R" + ) + stopifnot(any(grepl(expected, messages, fixed = TRUE))) + } + stopifnot(identical(.libPaths(), expected_paths), !length(list.files(consent))) + } + + for (mode in c("approved", "declined", "failed", "old_loaded", "compatible")) { + check(mode) + } + stopifnot(identical( + unname(read.dcf(file.path(old_library, "jdv", "DESCRIPTION"))[1L, "Version"]), + "0.0.1" + )) +}) +cat("Managed jdv preparation tests passed\n") diff --git a/R/tests/tool-library.R b/R/tests/tool-library.R index 64353f19f..4a5b551e5 100644 --- a/R/tests/tool-library.R +++ b/R/tests/tool-library.R @@ -121,7 +121,7 @@ local({ tryCatch(tool_library_check("arbitrary", "1.0.0", root_path), error = identity), "error" )) - stopifnot(identical(unname(.vscode_r_tool_packages), c("jgd", "rstudioapi"))) + stopifnot(identical(unname(.vscode_r_tool_packages), c("jgd", "jdv", "rstudioapi"))) stopifnot(isTRUE(.tool_validate_request("rstudioapi", "0.4.0"))) for (invalid in c("", "1.foo", "https://example.com/pkg")) { stopifnot(inherits( diff --git a/R/tool-library.R b/R/tool-library.R index b116762d9..bd0109ca8 100644 --- a/R/tool-library.R +++ b/R/tool-library.R @@ -1,7 +1,7 @@ # R-side support for packages managed by vscode-R as optional tools. # The allowlist is intentionally fixed here; callers may select a minimum version # but cannot use this installer to fetch arbitrary package names or URLs. -.vscode_r_tool_packages <- c(jgd = "jgd", rstudioapi = "rstudioapi") +.vscode_r_tool_packages <- c(jgd = "jgd", jdv = "jdv", rstudioapi = "rstudioapi") tool_library_path <- function(root) { .tool_validate_root(root) diff --git a/package.json b/package.json index d9054fad0..5859369c7 100644 --- a/package.json +++ b/package.json @@ -2622,6 +2622,7 @@ "coverage:sess": "node scripts/prepare-sess.js && Rscript --vanilla scripts/coverage-sess.R", "test:tool-library": "Rscript --vanilla R/tests/tool-library.R", "test:tool-consent": "Rscript --vanilla R/tests/tool-consent.R", + "test:prepare-jdv": "Rscript --vanilla R/tests/prepare-jdv.R", "test:prepare-jgd": "Rscript --vanilla R/tests/prepare-jgd.R", "test:prepare-rstudioapi": "Rscript --vanilla R/tests/prepare-rstudioapi.R", "test:interactive": "pnpm run pretest && pnpm run test:node", diff --git a/sess/R/handlers.R b/sess/R/handlers.R index e9dda83e3..ec3f657db 100644 --- a/sess/R/handlers.R +++ b/sess/R/handlers.R @@ -1486,12 +1486,72 @@ handle_dataview_dispose <- function(params) { # The oldest jdv release whose handle API and protocol sess implements. .jdv_min_version <- "0.1.0" -# Whether the jdv namespace loads and is a supported version. An older -# development build can load but lack parts of the API, such as -# jdv_handle_register(), so the version is checked rather than single functions. -.jdv_supported <- function() { - requireNamespace("jdv", quietly = TRUE) && - package_version(getNamespaceVersion("jdv")) >= .jdv_min_version +.configure_jdv_tools <- function(config) { + .sess_env$jdv_tools <- if ( + is.list(config) && + all(vapply( + config[c("tool_root", "library_helper", "consent_helper", "prepare_helper")], + .ipc_json_string, + logical(1L) + )) + ) { + config + } +} + +.jdv_tool_preparer <- function() { + config <- .sess_env$jdv_tools + if (is.null(config)) { + return(NULL) + } + setup <- new.env(parent = baseenv()) + sys.source(config$prepare_helper, envir = setup) + tool_environment <- setup$vscode_r_load_tool_helpers(c( + config$library_helper, + config$consent_helper + )) + function(install) { + setup$vscode_r_prepare_jdv( + config$tool_root, + config$consent_directory, + config$library_helper, + config$consent_helper, + as.character(.jdv_min_version), + can_prompt = install && + .ipc_json_string(config$consent_directory) && + dir.exists(config$consent_directory), + tool_environment = tool_environment + ) + } +} + +# Whether the jdv namespace loads and meets the supported minimum version. +.jdv_supported <- function(install = FALSE, prepare = .jdv_tool_preparer()) { + if (isNamespaceLoaded("jdv")) { + compatible <- package_version(getNamespaceVersion("jdv")) >= .jdv_min_version + if (!compatible && install) { + message("Restart R before using a compatible jdv version; an older jdv is already loaded.") + } + return(compatible) + } + prepared <- tryCatch( + if (!is.null(prepare)) prepare(install), + error = function(e) { + if (install) message("Could not prepare jdv: ", conditionMessage(e)) + FALSE + } + ) + if (isTRUE(prepared)) { + return(TRUE) + } + # A manually connected sess can still use a compatible user library. + for (library in .libPaths()) { + version <- tryCatch(utils::packageVersion("jdv", lib.loc = library), error = function(e) NULL) + if (!is.null(version) && version >= .jdv_min_version) { + return(requireNamespace("jdv", lib.loc = library, quietly = TRUE)) + } + } + FALSE } # Make sure jdv has a persistent connection to the viewer host of the client @@ -1572,7 +1632,7 @@ handle_dataview_dispose <- function(params) { !is.symbol(expression) || !nzchar(as.character(expression)) || !isTRUE(track) || - !.jdv_supported() + !isNamespaceLoaded("jdv") ) { return(NULL) } diff --git a/sess/R/hooks.R b/sess/R/hooks.R index c62a9d9cf..cd42b6cd3 100644 --- a/sess/R/hooks.R +++ b/sess/R/hooks.R @@ -126,10 +126,22 @@ runtime_start <- function( 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()) - + jdv_enabled <- !identical(getOption("sess.dataviewer", "auto"), "sess") + # Reuse the sourced helpers if this View() needs to install jdv. + prepare <- NULL + if (jdv_enabled && !isNamespaceLoaded("jdv")) { + prepare <- tryCatch(.jdv_tool_preparer(), error = function(e) NULL) + } + jdv_ready <- FALSE + binding <- NULL + if (jdv_enabled) { + # Resolve the caller's binding before forcing x. Forcing an unreadable + # promise can change whether jdv considers it safe to follow. + jdv_ready <- .jdv_supported(prepare = prepare) + if (jdv_ready) { + binding <- .jdv_track_binding(original_expression, parent.frame()) + } + } view_type <- if (dataview_is_table(x)) { "table" } else if (listview_supported(x)) { @@ -138,11 +150,24 @@ runtime_start <- function( "object" } title_key <- paste(as.character(title), collapse = "\n") + arrow <- .jdv_is_arrow(x) if ( - (view_type %in% c("table", "list") || .jdv_is_arrow(x)) && - .jdv_show(x, title_key, tracked_binding) + (view_type %in% c("table", "list") || arrow) && + jdv_enabled && + (!arrow || requireNamespace("nanoarrow", quietly = TRUE)) ) { - return(invisible(NULL)) + can_install <- is.null(.sess_env$view_owner) && !isTRUE(.sess_env$answering_request) + # The value is needed to rule out Arrow input without nanoarrow before + # offering installation. A newly installed jdv has no pre-force binding. + if (jdv_ready || (can_install && .jdv_supported(install = TRUE, prepare = prepare))) { + if (.jdv_show(x, title_key, if (!arrow) binding)) { + return(invisible(NULL)) + } + } else if (can_install) { + message( + "Could not use a compatible jdv. Install jdv in a library visible to this R session and try again." + ) + } } # Explicit View() in Interactive should open the normal data viewer when # jdv is available. Inline rich output remains the fallback when it is not. diff --git a/sess/R/interactive.R b/sess/R/interactive.R index 9aef118cf..97f98ddac 100644 --- a/sess/R/interactive.R +++ b/sess/R/interactive.R @@ -164,6 +164,7 @@ interactive_start <- function(config, managed = FALSE) { if (!isTRUE(attached)) { stop("Could not connect to the session agent") } + .configure_jdv_tools(cfg$jdvTools) .sess_env$interactive_pid <- Sys.getpid() .sess_env$interactive_managed <- managed .sess_env$interactive_event_counter <- 0L diff --git a/src/interactive/agent.ts b/src/interactive/agent.ts index 447c0e0f8..0065ccc28 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -699,13 +699,22 @@ export class SessionAgent { const method = inspectionMethod(params.method); // 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') { + const inspectionParams = object(params.params ?? {}); + const workspaceOpen = + method === 'workspace_view' && + Array.isArray(inspectionParams.path) && + inspectionParams.path.length > 0; + if ( + workspaceOpen || + method === 'jdv_open_viewer' || + method === 'jdv_handle_close' + ) { this.requireControl(client); } 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 = inspectionParams.handle_id; if (method === 'jdv_handle_close' && typeof handle === 'string') { this.pendingHandleCloses.set(handle, 0); result = true; @@ -713,8 +722,7 @@ export class SessionAgent { } throw new Error('R is busy; cached data remains available. Retry when idle.'); } - const inspectionParams = object(params.params ?? {}); - if (method === 'jdv_open_viewer') { + if (method === 'jdv_open_viewer' || method === 'workspace_view') { delete inspectionParams.address; } result = await this.backend.inspect({ diff --git a/src/interactive/backends/sessBackend.ts b/src/interactive/backends/sessBackend.ts index 834602f28..03d64521d 100644 --- a/src/interactive/backends/sessBackend.ts +++ b/src/interactive/backends/sessBackend.ts @@ -185,6 +185,19 @@ export class SessBackend implements SessionBackend { jgd: this.graphics.endpoint, token: this.token, useJgd: this.graphics.enabled, + jdvTools: this.settings.toolRoot + ? { + tool_root: this.settings.toolRoot, + consent_directory: path.join( + this.settings.storage, + 'jdv-consent', + this.settings.generation, + ), + library_helper: path.join(this.options.resources, 'tool-library.R'), + consent_helper: path.join(this.options.resources, 'tool-consent.R'), + prepare_helper: path.join(this.options.resources, 'prepare-tools.R'), + } + : undefined, }); // renv can overwrite these variables in arf. Its host-only support packages // remain reachable with the library environment inherited by the agent. diff --git a/src/interactive/backends/sessPreparation.ts b/src/interactive/backends/sessPreparation.ts index fd8b70518..80f443239 100644 --- a/src/interactive/backends/sessPreparation.ts +++ b/src/interactive/backends/sessPreparation.ts @@ -7,6 +7,17 @@ import { prepareStorage } from '../storage'; const run = promisify(execFile); +const runtimeHelpers = [ + 'interactive-worker.R', + 'interactive-metrics.R', + 'install_sess.R', + 'sess-package-install.R', + 'sess_source.R', + 'prepare-tools.R', + 'tool-library.R', + 'tool-consent.R', +]; + export async function installSessRuntime( extensionPath: string, root: string, @@ -19,11 +30,7 @@ export async function installSessRuntime( const sources = [ `${bundledSess}/DESCRIPTION`, `${bundledSess}/NAMESPACE`, - 'R/interactive-worker.R', - 'R/interactive-metrics.R', - 'R/install_sess.R', - 'R/sess-package-install.R', - 'R/sess_source.R', + ...runtimeHelpers.map((file) => `R/${file}`), ]; for (const directory of [`${bundledSess}/R`]) { for (const name of fs.readdirSync(path.join(extensionPath, directory)).sort()) { @@ -82,13 +89,7 @@ export async function installSessRuntime( recursive: true, filter: (source) => !/\.(o|so|dll)$/.test(source), }); - for (const file of [ - 'interactive-worker.R', - 'interactive-metrics.R', - 'install_sess.R', - 'sess-package-install.R', - 'sess_source.R', - ]) { + for (const file of runtimeHelpers) { fs.copyFileSync(path.join(extensionPath, 'R', file), path.join(resources, file)); } await new Promise((resolve, reject) => { diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index d44662872..1da78a7ce 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1,3 +1,4 @@ +import { createToolConsentService } from '../toolConsentAdapter'; import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; @@ -124,6 +125,7 @@ function interactiveJdvHostKey(id: string, generation: string): string { export class InteractiveManager implements vscode.Disposable, vscode.TreeDataProvider { + private readonly stopToolConsent = new WeakMap void>(); private views = new Map(); private opening = new Map>(); private presentationRefresh = new Set(); @@ -1225,6 +1227,7 @@ export class InteractiveManager label, directory, storage: path.join(this.root, identity.id), + toolRoot: this.context.globalStorageUri.fsPath, rPath, provider: kind, arfPath, @@ -1828,6 +1831,24 @@ export class InteractiveManager private listen(view: InteractiveView, client: AgentClient): void { const hostKey = interactiveJdvHostKey(client.manifest.id, client.manifest.generation); + const consent = createToolConsentService( + path.join(this.root, client.manifest.id, 'jdv-consent', client.manifest.generation), + () => !view.disposed && view.client === client && client.connected && client.control, + this.context.globalState, + ); + let watching = false; + let consentTransition = Promise.resolve(); + const watchConsent = (enabled: boolean) => { + if (enabled === watching) { + return; + } + watching = enabled; + consentTransition = consentTransition + .then(() => (enabled ? consent.start() : consent.stop())) + .catch((error: unknown) => this.report(error)); + }; + this.stopToolConsent.set(client, () => watchConsent(false)); + watchConsent(client.connected && client.control); let hadControl = client.control; client.on('event', (event: SessionEvent) => { if (view.client !== client) { @@ -1842,6 +1863,7 @@ export class InteractiveManager return; } const hasControl = client.control; + watchConsent(client.connected && hasControl); // A queued loss notice can precede a successful claim on this socket. if (!client.claimingControl) { disposeInteractiveJdvHostOnControlLoss(hadControl, hasControl, () => @@ -1853,6 +1875,7 @@ export class InteractiveManager this.changes.fire(undefined); }); client.on('disconnect', () => { + watchConsent(false); disposeJdvHost(hostKey); hadControl = false; if (view.client !== client || view.restarting) { @@ -3449,6 +3472,7 @@ export class InteractiveManager ) as AgentConfig; // Re-evaluate auto and honor repaired settings; the saved config records // the actual supervisor of the old process, not the current preference. + config.toolRoot = this.context.globalStorageUri.fsPath; config.supervision = util .config(vscode.Uri.file(config.directory)) .get('interactive.supervision', 'auto'); @@ -3535,6 +3559,7 @@ export class InteractiveManager task.end(undefined); } view.executions.clear(); + this.stopToolConsent.get(view.client)?.(); view.client.close(); const manifest = await launchAgent(config, runtime.agent, node, (text) => this.output.appendLine(text), @@ -3799,6 +3824,7 @@ export class InteractiveManager disposeJdvHost( interactiveJdvHostKey(view.client.manifest.id, view.client.manifest.generation), ); + this.stopToolConsent.get(view.client)?.(); view.client.close(); for (const { task } of view.executions.values()) { task.end(undefined); diff --git a/src/interactive/protocol.ts b/src/interactive/protocol.ts index 51ee4be17..1f0a2b02e 100644 --- a/src/interactive/protocol.ts +++ b/src/interactive/protocol.ts @@ -96,6 +96,7 @@ export interface AgentSettings extends SessionIdentity { maxOutputBytes: number; maxJournalBytes: number; maxAssetBytes?: number; + toolRoot?: string; } /** Persisted backend descriptor. Its definition validates and owns its options. */ diff --git a/src/session.ts b/src/session.ts index cef17e760..33a48fcab 100644 --- a/src/session.ts +++ b/src/session.ts @@ -4651,7 +4651,7 @@ export async function cleanupSession(sessionId: string, closingSocket?: IpcSocke export async function sessionRequest( data: Record, target: Session | string | null | undefined = activeSession, - options: RpcRequestOptions = {}, + options: RpcRequestOptions & { throwOnError?: boolean } = {}, ): Promise { try { const owner = typeof target === 'string' ? sessions.get(target) : target; @@ -4667,6 +4667,9 @@ export async function sessionRequest( } return await rpc.request(data, options); } catch (error) { + if (options.throwOnError) { + throw error; + } if (error instanceof Error && error.name === 'AbortError') { return undefined; } diff --git a/src/test/node/interactiveRuntime.test.ts b/src/test/node/interactiveRuntime.test.ts index 4861f291c..b63b70409 100644 --- a/src/test/node/interactiveRuntime.test.ts +++ b/src/test/node/interactiveRuntime.test.ts @@ -87,6 +87,7 @@ suite('Interactive real R runtime', function () { label: 'Integration test', directory: process.cwd(), storage: path.join(root, id), + toolRoot: path.join(root, 'tools'), rPath: 'R', library, resources, @@ -229,7 +230,7 @@ suite('Interactive real R runtime', function () { assert.strictEqual(await client.request('claim', { jdvAddress: host.address }), true); // Repeated strings keep the R fixture small while its encoded page exceeds the byte budget. const id = await submit( - 'utils::View(data.frame(a = 1:300, b = rep(letters, length.out = 300), c = rep(strrep("x", 12000), 300), d = rep(strrep("y", 12000), 300)), "interactive jdv test")', + 'stopifnot(file.exists(sess:::.sess_env$jdv_tools$prepare_helper)); utils::View(data.frame(a = 1:300, b = rep(letters, length.out = 300), c = rep(strrep("x", 12000), 300), d = rep(strrep("y", 12000), 300)), "interactive jdv test")', ); assert.strictEqual((await finished(id)).state, 'success'); const { peer, params } = await Promise.race([ @@ -1245,6 +1246,14 @@ huge`); assert.strictEqual((await finished(viewed)).state, 'success'); assert.strictEqual(await openedAt('queued before handoff'), 'second'); + const workspaceOpen = { + method: 'workspace_view', + params: { name: 'controlled', path: [{ kind: 'index', value: 1, name: 'df' }] }, + }; + await assert.rejects(client.request('inspect', workspaceOpen), /observing/); + assert.strictEqual(await observer.request('inspect', workspaceOpen), true); + assert.strictEqual(await openedAt('controlled$df'), 'second'); + const reopened = await observer.request('inspect', { method: 'jdv_open_viewer', params: { @@ -1255,14 +1264,6 @@ huge`); }); assert.strictEqual(reopened, true); assert.strictEqual(await openedAt('explicit viewer after handoff'), 'second'); - assert.strictEqual( - await observer.request('inspect', { - method: 'workspace_view', - params: { name: 'controlled', path: [{ kind: 'index', value: 1, name: 'df' }] }, - }), - true, - ); - assert.strictEqual(await openedAt('controlled$df'), 'second'); assert.ok( !events.some( (event) => diff --git a/src/toolConsentAdapter.ts b/src/toolConsentAdapter.ts index 816f01620..b5b5aef5d 100644 --- a/src/toolConsentAdapter.ts +++ b/src/toolConsentAdapter.ts @@ -15,6 +15,7 @@ function dismissedMinimumVersionKey(packageName: string): string { const hostSessionState: ToolConsentSessionState = { promptedPackages: new Set() }; const OPTIONAL_NOTICES: Record = { + jdv: 'Declining keeps the available data viewer fallback.', jgd: 'Automatic plot backend setup is optional; declining uses the available fallback.', rstudioapi: 'RStudio API emulation is optional; declining skips installing rstudioapi.', }; diff --git a/src/toolVersions.ts b/src/toolVersions.ts index 40d89128d..5603ccb4e 100644 --- a/src/toolVersions.ts +++ b/src/toolVersions.ts @@ -2,6 +2,7 @@ // Shared by consent eligibility and R package preparation. export const TOOL_MINIMUM_VERSIONS = { jgd: '0.1.0', + jdv: '0.1.0', // The first release that exports the document position and range helpers used by sess. rstudioapi: '0.4.0', } as const; diff --git a/src/workspaceViewer.ts b/src/workspaceViewer.ts index f498165be..27382ab5d 100644 --- a/src/workspaceViewer.ts +++ b/src/workspaceViewer.ts @@ -585,13 +585,20 @@ export async function viewItem(node: GlobalEnvItem): Promise { ); return; } - await sessionRequest( - { - method: 'workspace_view', - params: { name: node.rootName, path: node.objectPath }, - }, - node.owner, - ); + try { + await sessionRequest( + { + method: 'workspace_view', + params: { name: node.rootName, path: node.objectPath }, + }, + node.owner, + { throwOnError: true }, + ); + } catch (error) { + void window.showWarningMessage( + `R Workspace: ${error instanceof Error ? error.message : String(error)}`, + ); + } } } diff --git a/website/docs/features/interactive-viewers.md b/website/docs/features/interactive-viewers.md index a79ef6002..a6bc01f38 100644 --- a/website/docs/features/interactive-viewers.md +++ b/website/docs/features/interactive-viewers.md @@ -18,9 +18,17 @@ display tabular data, graphics, [htmlwidgets](http://www.htmlwidgets.org/) and ### jdv -When the [jdv](https://cran.r-project.org/package=jdv) package is installed in -the library that the R session uses (`install.packages("jdv")`), `View()` on a -data frame, matrix, list or Arrow data is served by jdv when it can be used. +A compatible [jdv](https://cran.r-project.org/package=jdv) package serves +`View()` on a data frame, matrix, list or Arrow data when available. +If the session has no compatible jdv, an explicit `View()` can offer to install +it in the vscode-R-managed tool library. The installed copy is loaded without +changing the project's library paths. If an older jdv is already loaded, +restart R before using a compatible copy. An unloaded older copy in a project +library can be superseded by a compatible managed namespace for that R process. + +Opening a nested Workspace item uses the built-in viewer if jdv is unavailable. +To use jdv for these items, first run `View()` on a table in the same R session. + The table and list viewers stay the same; jdv reads the pages, sorts and filters in R. From 044b3eea8fc29019bac45baa548c33855a410140 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Tue, 1 Dec 2026 13:03:29 +0000 Subject: [PATCH 2/2] fix: offer jdv from R terminals and only while a controller can answer The terminal profile now configures jdv before connecting, so View() in an R: Create R Terminal session finds a managed jdv or offers to install it. An Interactive session offers installation only while the controlling editor refreshes a consent marker, and stops waiting if it disappears, so a detached controller no longer holds the queue. A declined offer is remembered for the R session, and Arrow input without nanoarrow falls back before jdv is selected or loaded. The View() call that installs jdv does not track the variable, since base R cannot tell an ordinary binding from a promise that call forced; the next View() does. The code and the viewer docs note this. --- R/attach_sess.R | 36 +++- R/prepare-tools.R | 16 +- R/profile.R | 1 + R/tests/prepare-jdv.R | 178 ++++++++++++++++-- R/tests/tool-consent.R | 6 +- R/tool-consent.R | 29 ++- sess/R/handlers.R | 27 ++- sess/R/hooks.R | 29 ++- sess/R/interactive.R | 3 + src/interactive/manager.ts | 2 + src/test/node/toolConsent.test.ts | 31 +++ src/toolConsent.ts | 46 ++++- src/toolConsentAdapter.ts | 2 + .../docs/configuration/extension-settings.md | 5 +- website/docs/features/interactive-viewers.md | 3 +- 15 files changed, 351 insertions(+), 63 deletions(-) diff --git a/R/attach_sess.R b/R/attach_sess.R index f2e804334..56105b9f8 100644 --- a/R/attach_sess.R +++ b/R/attach_sess.R @@ -91,6 +91,25 @@ vscode_r_with_rstudioapi <- function( invisible(FALSE) } +vscode_r_configure_jdv <- function( + ns, + tool_root = Sys.getenv("VSCODE_R_TOOL_ROOT", unset = ""), + consent_directory = Sys.getenv("VSCODE_R_TOOL_CONSENT_DIRECTORY", unset = ""), + library_helper = Sys.getenv("VSCODE_R_TOOL_LIBRARY_HELPER", unset = ""), + consent_helper = Sys.getenv("VSCODE_R_TOOL_CONSENT_HELPER", unset = ""), + prepare_helper = Sys.getenv("VSCODE_R_TOOL_PREPARE_HELPER", unset = "") +) { + if (exists(".configure_jdv_tools", envir = ns, inherits = FALSE)) { + get(".configure_jdv_tools", envir = ns)(list( + tool_root = tool_root, + consent_directory = consent_directory, + library_helper = library_helper, + consent_helper = consent_helper, + prepare_helper = prepare_helper + )) + } +} + vscode_r_prepare_sess <- function( pkg_path, managed_root, @@ -384,15 +403,14 @@ vscode_r_attach_sess <- function( args$attachment_id <- attachment_id args$auto_activate <- auto_activate } - if (exists(".configure_jdv_tools", envir = ns, inherits = FALSE)) { - get(".configure_jdv_tools", envir = ns)(list( - tool_root = tool_root, - consent_directory = tool_consent_directory, - library_helper = tool_library_helper, - consent_helper = tool_consent_helper, - prepare_helper = tool_prepare_helper - )) - } + vscode_r_configure_jdv( + ns, + tool_root, + tool_consent_directory, + tool_library_helper, + tool_consent_helper, + tool_prepare_helper + ) vscode_r_with_rstudioapi( use_rstudioapi, tool_prepare_helper, diff --git a/R/prepare-tools.R b/R/prepare-tools.R index eb0383de2..05c707d90 100644 --- a/R/prepare-tools.R +++ b/R/prepare-tools.R @@ -53,7 +53,9 @@ vscode_r_prepare_tool_package <- function( support, fallback, report_load_failure = TRUE, - tool_environment = vscode_r_load_tool_helpers(helpers) + tool_environment = vscode_r_load_tool_helpers(helpers), + consent_available = function() TRUE, + on_decline = function() NULL ) { if (!(is.logical(can_prompt) && length(can_prompt) == 1L && !is.na(can_prompt))) { stop("can_prompt must be a single non-NA logical value.", call. = FALSE) @@ -78,7 +80,9 @@ vscode_r_prepare_tool_package <- function( policy, consent_timeout_seconds = 180, install_timeout_seconds = 300, - resolution_timeout_seconds = 30 + resolution_timeout_seconds = 30, + consent_available = consent_available, + on_decline = on_decline ) if (is.null(prepared)) { message("vscode-R optional ", package, " installation was not approved; ", fallback, ".") @@ -179,7 +183,9 @@ vscode_r_prepare_jdv <- function( consent_helper, minimum_version, can_prompt, - tool_environment + tool_environment, + consent_available, + on_decline ) { vscode_r_prepare_tool_package( "jdv", @@ -192,6 +198,8 @@ vscode_r_prepare_jdv <- function( minimum_version, support = "jdv data viewer", fallback = "using the available data viewer fallback; install a compatible jdv in your R library", - tool_environment = tool_environment + tool_environment = tool_environment, + consent_available = consent_available, + on_decline = on_decline ) } diff --git a/R/profile.R b/R/profile.R index 75c2750f8..e50e24139 100644 --- a/R/profile.R +++ b/R/profile.R @@ -57,6 +57,7 @@ invisible(local({ return(invisible(FALSE)) } + vscode_r_configure_jdv(ns) plot_backend <- Sys.getenv("SESS_PLOT_BACKEND", "auto") connect <- get("connect", envir = ns, inherits = FALSE) use_rstudioapi <- as.logical(Sys.getenv("SESS_RSTUDIOAPI", "TRUE")) diff --git a/R/tests/prepare-jdv.R b/R/tests/prepare-jdv.R index b015ec805..1656659b0 100644 --- a/R/tests/prepare-jdv.R +++ b/R/tests/prepare-jdv.R @@ -32,9 +32,9 @@ local({ "jdv_connection <- function() if (is.null(state$address)) list(state='disconnected') else list(state='connected', address=state$address)", "jdv_connect <- function(address) state$address <- address", "jdv_disconnect <- function() state$address <- NULL", - "jdv_binding <- function(...) NULL", - "jdv_register <- function(x, title, ...) {", - " options(test.jdv.open=list(title=title, address=state$address))", + "jdv_binding <- function(name, env) list(name=as.character(name), env=env)", + "jdv_register <- function(x, title, binding=NULL, ...) {", + " options(test.jdv.open=list(title=title, address=state$address, binding=binding))", " list(id='fixture', generation=1L)", "}", if (broken) ".onLoad <- function(...) stop('fixture load failure')" @@ -73,6 +73,111 @@ local({ install(old, old_library) install(valid, valid_library) + check_terminal_profile <- function() { + tool_root <- file.path(root, "terminal-tools") + managed <- tool_library_path(tool_root) + install(valid, managed) + endpoint <- if (.Platform$OS.type == "windows") { + paste0("\\\\?\\pipe\\", basename(tempfile("profile-jdv-"))) + } else { + tempfile(fileext = ".sock") + } + server <- processx::conn_create_unix_socket(endpoint, encoding = "") + on.exit(close(server), add = TRUE) + user_profile <- file.path(root, "user-profile.R") + writeLines( + c( + "invisible(lapply(c('sess', 'processx', 'jsonlite', 'later'), loadNamespace))", + ".libPaths(c(Sys.getenv('TEST_JDV_PROJECT_LIBRARY'), .Library), include.site=FALSE)" + ), + user_profile + ) + child <- processx::process$new( + file.path(R.home("bin"), "Rscript"), + c( + "--no-environ", + "--no-site-file", + "-e", + paste( + "stopifnot(!Sys.getenv('TEST_JDV_MANAGED') %in% normalizePath(.libPaths(), winslash='/'));", + "utils::View(data.frame(a=1:2), title='profile viewer');", + "stopifnot(identical(getOption('test.jdv.open')$address, 'profile-address'));", + "stopifnot(identical(normalizePath(getNamespaceInfo(asNamespace('jdv'), 'path'), winslash='/'),", + "paste0(Sys.getenv('TEST_JDV_MANAGED'), '/jdv')))" + ) + ), + env = c( + "current", + R_PROFILE_USER = normalizePath("R/profile.R"), + R_PROFILE_USER_OLD = user_profile, + R_LIBS = paste(.libPaths(), collapse = .Platform$path.sep), + VSCODE_R_SESS_PKG_PATH = system.file(package = "sess"), + VSCODE_R_SESS_ROOT = file.path(root, "sess-root"), + VSCODE_R_SESS_CONSENT_DIRECTORY = file.path(root, "sess-consent"), + VSCODE_R_SESS_SOURCE_HELPER = normalizePath("R/sess_source.R"), + VSCODE_R_SESS_ATTACH_HELPER = normalizePath("R/attach_sess.R"), + VSCODE_R_SESS_INSTALLER_HELPER = normalizePath("R/sess-package-install.R"), + VSCODE_R_TOOL_ROOT = tool_root, + VSCODE_R_TOOL_LIBRARY_HELPER = helpers[[1L]], + VSCODE_R_TOOL_CONSENT_HELPER = helpers[[2L]], + VSCODE_R_TOOL_PREPARE_HELPER = helpers[[3L]], + VSCODE_R_SESS_STARTUP_FILE = "", + SESS_ENDPOINT = endpoint, + SESS_PLOT_BACKEND = "standard", + SESS_RSTUDIOAPI = "FALSE", + TEST_JDV_MANAGED = normalizePath(managed, winslash = "/"), + TEST_JDV_PROJECT_LIBRARY = old_library + ), + stdout = file.path(root, "profile.out"), + stderr = file.path(root, "profile.err") + ) + on.exit(child$kill(), add = TRUE) + diagnostic <- function() { + paste(readLines(file.path(root, "profile.err")), collapse = "\n") + } + if (!identical(processx::poll(list(server), 10000L)[[1L]], "connect")) { + stop("The terminal profile did not connect. ", diagnostic()) + } + processx::conn_accept_unix_socket(server) + if (!identical(processx::poll(list(server), 5000L)[[1L]], "ready")) { + stop("The terminal profile did not send an attach request. ", diagnostic()) + } + message <- jsonlite::fromJSON(processx::conn_read_chars(server)) + stopifnot(identical(message$method, "attach"), message$params$protocol_version == 3) + bytes <- charToRaw(paste0( + jsonlite::toJSON( + list( + jsonrpc = "2.0", + id = message$id, + result = list(jdv = list(address = "profile-address")) + ), + auto_unbox = TRUE + ), + "\n" + )) + while (length(bytes)) { + bytes <- processx::conn_write(server, bytes) + } + child$wait(10000L) + if (!identical(child$get_exit_status(), 0L)) stop(diagnostic()) + } + + counting_helper <- file.path(root, "counting-tool-library.R") + dump_helper <- function(file) { + paste(deparse(file), collapse = "") + } + writeLines( + c( + paste0("sys.source(", dump_helper(helpers[[1L]]), ", envir=environment())"), + "original_plan <- tool_library_plan", + "tool_library_plan <- function(...) {", + " options(test.jdv.plans=getOption('test.jdv.plans', 0L) + 1L)", + " original_plan(...)", + "}" + ), + counting_helper + ) + responder <- function(directory, decision, log) { script <- " args <- commandArgs(TRUE) @@ -105,18 +210,23 @@ local({ opts <- options( repos = c(CRAN = if (mode == "failed") broken_repo else repo), pkgType = "source", - test.jdv.open = NULL + test.jdv.open = NULL, + test.jdv.plans = 0L ) paths <- .libPaths() user <- switch( mode, approved = old_library, old_loaded = old_library, + arrow = old_library, compatible = valid_library, consent ) .libPaths(c(user, .Library), include.site = FALSE) expected_paths <- .libPaths() + if (mode == "arrow") { + install(valid, tool_library_path(tool_root)) + } if (mode == "old_loaded") { loadNamespace("jdv", lib.loc = old_library) } @@ -126,12 +236,14 @@ local({ state$tempdir <- root state$latest_plot_path <- file.path(root, "plot.png") state$attach_jdv <- list(address = "fixture-address") + state$jdv_offer_declined <- NULL sess:::.configure_jdv_tools(list( tool_root = tool_root, consent_directory = consent, - library_helper = helpers[[1L]], + library_helper = counting_helper, consent_helper = helpers[[2L]], - prepare_helper = helpers[[3L]] + prepare_helper = helpers[[3L]], + require_live_consent = mode == "detached" )) sess:::runtime_start(use_rstudioapi = FALSE, plot_backend = "standard") child <- NULL @@ -141,6 +253,7 @@ local({ } sess:::runtime_stop() sess:::.configure_jdv_tools(NULL) + state$jdv_offer_declined <- NULL state$con <- NULL state$attach_jdv <- NULL lapply(pipe, close) @@ -155,8 +268,23 @@ local({ assign("jdv_fixture_root", root_value, envir = .GlobalEnv) selector <- list(list(kind = "index", value = 1L, name = "table")) log <- file.path(root, paste0(mode, ".consent")) - if (mode %in% c("approved", "declined", "failed")) { - child <- responder(consent, if (mode == "declined") "decline" else "approve", log) + if (mode %in% c("approved", "declined", "failed", "detached")) { + decision <- if (mode %in% c("declined", "detached")) "decline" else "approve" + child <- responder(consent, decision, log) + } + if (mode == "detached") { + stale <- file.path(consent, ".jdv-consent-live-dead") + stopifnot(file.create(stale), Sys.setFileTime(stale, Sys.time() - 10)) + suppressMessages(View(root_value, title = "detached")) + stopifnot(getOption("test.jdv.plans") == 0L, !file.exists(log)) + unlink(stale) + return(invisible()) + } + if (mode == "arrow") { + stopifnot(!requireNamespace("nanoarrow", quietly = TRUE)) + utils::View(structure(list(), class = "RecordBatchReader")) + stopifnot(!isNamespaceLoaded("jdv"), getOption("test.jdv.plans") == 0L) + return(invisible()) } if (mode == "approved") { # Missing nanoarrow must short-circuit before selecting or installing jdv. @@ -173,18 +301,29 @@ local({ stopifnot(sess:::handle_workspace_view("jdv_fixture_root", selector)) stopifnot(identical(getOption("test.jdv.open")$address, "fixture-address")) } - # The Workspace root action currently evaluates this same View() expression. - messages <- capture.output( - View(get("jdv_fixture_root", envir = .GlobalEnv, inherits = FALSE), title = "root"), - type = "message" - ) + messages <- capture.output(View(root_value, title = "root"), type = "message") if (!is.null(child)) { child$wait(2000) stopifnot(child$get_exit_status() == 0L) plan <- readLines(log) stopifnot(identical(plan[c(4L, 6L)], c("once", "jdv"))) } - if (mode %in% c("approved", "compatible")) { + if (mode == "declined") { + second_log <- paste0(log, ".second") + child <- responder(consent, "decline", second_log) + suppressMessages(View(root_value, title = "after decline")) + stopifnot(getOption("test.jdv.plans") == 1L, !file.exists(second_log)) + .libPaths(c(valid_library, expected_paths), include.site = FALSE) + View(root_value, title = "installed separately") + stopifnot(identical(getOption("test.jdv.open")$title, "installed separately")) + stopifnot(getOption("test.jdv.plans") == 1L) + .libPaths(expected_paths, include.site = FALSE) + } else if (mode %in% c("approved", "compatible")) { + if (mode == "approved" && getRversion() >= "4.6.0") { + View(root_value, title = "root") + binding <- getOption("test.jdv.open")$binding + stopifnot(identical(binding$name, "root_value"), identical(binding$env, environment())) + } actual <- normalizePath(getNamespaceInfo(asNamespace("jdv"), "path")) library <- if (mode == "approved") tool_library_path(tool_root) else valid_library stopifnot(identical(actual, normalizePath(file.path(library, "jdv")))) @@ -206,9 +345,18 @@ local({ stopifnot(identical(.libPaths(), expected_paths), !length(list.files(consent))) } - for (mode in c("approved", "declined", "failed", "old_loaded", "compatible")) { + for (mode in c( + "approved", + "declined", + "failed", + "old_loaded", + "compatible", + "arrow", + "detached" + )) { check(mode) } + check_terminal_profile() stopifnot(identical( unname(read.dcf(file.path(old_library, "jdv", "DESCRIPTION"))[1L, "Version"]), "0.0.1" diff --git a/R/tests/tool-consent.R b/R/tests/tool-consent.R index 154186472..1d5366789 100644 --- a/R/tests/tool-consent.R +++ b/R/tests/tool-consent.R @@ -109,7 +109,8 @@ local({ received, policy, directory, - timeout_seconds + timeout_seconds, + ... ) { prompt_calls <<- prompt_calls + 1L stopifnot( @@ -161,7 +162,8 @@ local({ received, policy, directory, - timeout_seconds + timeout_seconds, + ... ) { request <- .tool_publish_consent_request(received, strrep("1", 32L), policy, directory) prepare_environment$.tool_wait_for_consent(request, timeout_seconds) diff --git a/R/tool-consent.R b/R/tool-consent.R index 77c3e668d..830d83ca6 100644 --- a/R/tool-consent.R +++ b/R/tool-consent.R @@ -70,7 +70,9 @@ list(id = id, lines = lines, request_path = request_path, response_path = response_path) } -.tool_wait_for_consent <- function(request, timeout_seconds = 180) { +.tool_wait_for_consent <- function(request, timeout_seconds = 180, consent_available = function() { + TRUE + }, on_decline = function() NULL) { directory <- dirname(request$request_path) on.exit(unlink(c(request$request_path, request$response_path)), add = TRUE) if ( @@ -84,7 +86,7 @@ } deadline <- Sys.time() + timeout_seconds repeat { - if (!dir.exists(directory) || !file.exists(request$request_path)) { + if (!consent_available() || !dir.exists(directory) || !file.exists(request$request_path)) { return(FALSE) } request_size <- file.info(request$request_path)$size @@ -112,6 +114,7 @@ return(TRUE) } if (identical(response, "decline")) { + on_decline() return(FALSE) } stop("Invalid response to the managed tool consent request.", call. = FALSE) @@ -123,7 +126,17 @@ } } -.tool_request_consent <- function(plan, policy, directory, timeout_seconds = 180) { +.tool_request_consent <- function( + plan, + policy, + directory, + timeout_seconds = 180, + consent_available = function() TRUE, + on_decline = function() NULL +) { + if (!consent_available()) { + return(FALSE) + } if ( !(is.character(directory) && length(directory) == 1L && @@ -150,7 +163,7 @@ if (!file.exists(request_path) && !file.exists(response_path)) break } request <- .tool_publish_consent_request(plan, id, policy, directory) - .tool_wait_for_consent(request, timeout_seconds) + .tool_wait_for_consent(request, timeout_seconds, consent_available, on_decline) } # Request consent only when no compatible namespace is already available. @@ -165,7 +178,9 @@ tool_library_prepare <- function( repos = getOption("repos"), consent_timeout_seconds = 180, install_timeout_seconds = 300, - resolution_timeout_seconds = 30 + resolution_timeout_seconds = 30, + consent_available = function() TRUE, + on_decline = function() NULL ) { available <- tool_library_check(package, minimum_version, root) if (!available$install_required) { @@ -194,7 +209,9 @@ tool_library_prepare <- function( plan, policy, consent_directory, - timeout_seconds = consent_timeout_seconds + timeout_seconds = consent_timeout_seconds, + consent_available = consent_available, + on_decline = on_decline ) if (!isTRUE(approved)) { return(invisible(NULL)) diff --git a/sess/R/handlers.R b/sess/R/handlers.R index ec3f657db..091086443 100644 --- a/sess/R/handlers.R +++ b/sess/R/handlers.R @@ -1510,6 +1510,25 @@ handle_dataview_dispose <- function(params) { config$library_helper, config$consent_helper )) + consent_available <- function() { + directory <- config$consent_directory + if (!.ipc_json_string(directory) || !dir.exists(directory)) { + return(FALSE) + } + if (!isTRUE(config$require_live_consent)) { + return(TRUE) + } + # Interactive services refresh a marker every second while they control the + # session. The expiry also handles a host that exited without removing it. + markers <- list.files( + directory, + "^\\.jdv-consent-live-[a-f0-9]+$", + all.files = TRUE, + full.names = TRUE + ) + age <- as.numeric(difftime(Sys.time(), file.mtime(markers), units = "secs")) + any(age <= 3, na.rm = TRUE) + } function(install) { setup$vscode_r_prepare_jdv( config$tool_root, @@ -1517,10 +1536,10 @@ handle_dataview_dispose <- function(params) { config$library_helper, config$consent_helper, as.character(.jdv_min_version), - can_prompt = install && - .ipc_json_string(config$consent_directory) && - dir.exists(config$consent_directory), - tool_environment = tool_environment + can_prompt = install && !isTRUE(.sess_env$jdv_offer_declined) && consent_available(), + tool_environment = tool_environment, + consent_available = consent_available, + on_decline = function() .sess_env$jdv_offer_declined <- TRUE ) } } diff --git a/sess/R/hooks.R b/sess/R/hooks.R index cd42b6cd3..ace395af4 100644 --- a/sess/R/hooks.R +++ b/sess/R/hooks.R @@ -127,21 +127,11 @@ runtime_start <- function( } force(title) jdv_enabled <- !identical(getOption("sess.dataviewer", "auto"), "sess") - # Reuse the sourced helpers if this View() needs to install jdv. - prepare <- NULL - if (jdv_enabled && !isNamespaceLoaded("jdv")) { - prepare <- tryCatch(.jdv_tool_preparer(), error = function(e) NULL) - } - jdv_ready <- FALSE - binding <- NULL - if (jdv_enabled) { - # Resolve the caller's binding before forcing x. Forcing an unreadable - # promise can change whether jdv considers it safe to follow. - jdv_ready <- .jdv_supported(prepare = prepare) - if (jdv_ready) { - binding <- .jdv_track_binding(original_expression, parent.frame()) - } - } + # Installation eligibility depends on the evaluated value. After forcing x, + # base R cannot distinguish an ordinary binding from a promise this call + # forced. The View() that installs jdv skips tracking; later calls can use + # the loaded jdv to inspect the binding before forcing x. + binding <- if (jdv_enabled) .jdv_track_binding(original_expression, parent.frame()) view_type <- if (dataview_is_table(x)) { "table" } else if (listview_supported(x)) { @@ -156,10 +146,13 @@ runtime_start <- function( jdv_enabled && (!arrow || requireNamespace("nanoarrow", quietly = TRUE)) ) { + # Select and load jdv only after the value passes the Arrow eligibility check. + prepare <- tryCatch(.jdv_tool_preparer(), error = function(e) NULL) can_install <- is.null(.sess_env$view_owner) && !isTRUE(.sess_env$answering_request) - # The value is needed to rule out Arrow input without nanoarrow before - # offering installation. A newly installed jdv has no pre-force binding. - if (jdv_ready || (can_install && .jdv_supported(install = TRUE, prepare = prepare))) { + if ( + .jdv_supported(prepare = prepare) || + (can_install && .jdv_supported(install = TRUE, prepare = prepare)) + ) { if (.jdv_show(x, title_key, if (!arrow) binding)) { return(invisible(NULL)) } diff --git a/sess/R/interactive.R b/sess/R/interactive.R index 97f98ddac..ea071c8e9 100644 --- a/sess/R/interactive.R +++ b/sess/R/interactive.R @@ -164,6 +164,9 @@ interactive_start <- function(config, managed = FALSE) { if (!isTRUE(attached)) { stop("Could not connect to the session agent") } + if (!is.null(cfg$jdvTools)) { + cfg$jdvTools$require_live_consent <- TRUE + } .configure_jdv_tools(cfg$jdvTools) .sess_env$interactive_pid <- Sys.getpid() .sess_env$interactive_managed <- managed diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 1da78a7ce..e050c7586 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1835,6 +1835,8 @@ export class InteractiveManager path.join(this.root, client.manifest.id, 'jdv-consent', client.manifest.generation), () => !view.disposed && view.client === client && client.connected && client.control, this.context.globalState, + undefined, + true, ); let watching = false; let consentTransition = Promise.resolve(); diff --git a/src/test/node/toolConsent.test.ts b/src/test/node/toolConsent.test.ts index 22522b278..1a876f662 100644 --- a/src/test/node/toolConsent.test.ts +++ b/src/test/node/toolConsent.test.ts @@ -108,6 +108,37 @@ suite('managed package consent bridge', () => { return request; } + test('advertises only running Interactive jdv consent services', async () => { + const makeService = () => { + const result = new ToolConsentService({ + directory, + isEnabled: () => true, + isPromptEnabled: () => true, + sessionState, + rememberPromptDismissal: () => Promise.resolve(), + prompt: () => Promise.resolve('notNow'), + publishJdvAvailability: true, + }); + services.push(result); + return result; + }; + const markers = async () => + (await fs.readdir(directory)).filter((file) => file.startsWith('.jdv-consent-live-')); + const first = makeService(); + const second = makeService(); + await first.start(); + const [firstMarker] = await markers(); + assert.ok(firstMarker); + await second.start(); + assert.equal((await markers()).length, 2); + await first.stop(); + const [remaining] = await markers(); + assert.ok(remaining); + assert.notEqual(remaining, firstMarker); + await second.stop(); + assert.deepEqual(await markers(), []); + }); + test('explicit jgd asks on each request and does not alter automatic prompt preference', async () => { const broker = service(); await broker.start(); diff --git a/src/toolConsent.ts b/src/toolConsent.ts index bdbd9b769..80e93e898 100644 --- a/src/toolConsent.ts +++ b/src/toolConsent.ts @@ -1,3 +1,6 @@ +import { randomBytes } from 'node:crypto'; +import { rmSync, writeFileSync } from 'node:fs'; +import * as path from 'node:path'; import { ConsentResponse, FileConsentService } from './fileConsent'; import { isToolPackageName } from './toolVersions'; @@ -37,6 +40,7 @@ export interface ToolConsentServiceOptions { rememberPromptDismissal: (packageName: string) => Promise; prompt: (request: ToolConsentRequest) => Promise; intervalMs?: number; + publishJdvAvailability?: boolean; } const REQUEST_NAME = /^[A-Za-z0-9_-]{1,64}\.request$/; @@ -107,8 +111,16 @@ export function parseToolConsentRequest(id: string, content: string): ToolConsen export class ToolConsentService { private readonly bridge: FileConsentService; private running = false; + private markerTimer?: NodeJS.Timeout; + private readonly jdvMarker?: string; constructor(private readonly options: ToolConsentServiceOptions) { + if (options.publishJdvAvailability) { + this.jdvMarker = path.join( + options.directory, + `.jdv-consent-live-${randomBytes(12).toString('hex')}`, + ); + } this.bridge = new FileConsentService({ directory: options.directory, requestName: REQUEST_NAME, @@ -120,16 +132,46 @@ export class ToolConsentService { }); } - start(): Promise { + async start(): Promise { + if (this.running) { + return; + } this.running = true; - return this.bridge.start(); + try { + await this.bridge.start(); + } catch (error) { + this.running = false; + throw error; + } + if (this.running && this.jdvMarker) { + this.refreshJdvMarker(); + this.markerTimer = setInterval(() => this.refreshJdvMarker(), 1000); + this.markerTimer.unref(); + } } stop(): Promise { this.running = false; + clearInterval(this.markerTimer); + this.refreshJdvMarker(); return this.bridge.stop(); } + private refreshJdvMarker(): void { + if (!this.jdvMarker) { + return; + } + try { + if (this.running && this.options.isEnabled()) { + writeFileSync(this.jdvMarker, '', { mode: 0o600 }); + } else { + rmSync(this.jdvMarker, { force: true }); + } + } catch { + // If this directory cannot be updated, the last marker expires. + } + } + /** Whether a request for these packages under this policy could currently be shown. */ canPrompt(packageNames: readonly string[], policy: ToolConsentPolicy): boolean { if (!this.running || !this.options.isEnabled() || packageNames.length === 0) { diff --git a/src/toolConsentAdapter.ts b/src/toolConsentAdapter.ts index b5b5aef5d..5ffe47ed5 100644 --- a/src/toolConsentAdapter.ts +++ b/src/toolConsentAdapter.ts @@ -47,6 +47,7 @@ export function createToolConsentService( isEnabled: () => boolean, globalState: vscode.Memento, intervalMs?: number, + publishJdvAvailability = false, ): ToolConsentService { return new ToolConsentService({ directory, @@ -66,6 +67,7 @@ export function createToolConsentService( ); }, intervalMs, + publishJdvAvailability, prompt: async (request): Promise => { const install = 'Install package'; const notNow = 'Not now'; diff --git a/website/docs/configuration/extension-settings.md b/website/docs/configuration/extension-settings.md index a0f751e8d..8a41919ca 100644 --- a/website/docs/configuration/extension-settings.md +++ b/website/docs/configuration/extension-settings.md @@ -80,8 +80,9 @@ longer forces the standard viewer: if that was your 2.x configuration, set viewer. `0` disables pagination. - `r.session.viewers.trackVariables`: with [jdv](../features/interactive-viewers.md#jdv) and R >= 4.6, update the data viewer when the variable passed to `View()` is - reassigned. Applies to R terminals started or attached after the setting is - changed. + reassigned. If `View()` installs jdv, tracking is available starting with the + next `View()`. Applies to R terminals started or attached after the setting + is changed. ## R Markdown Settings diff --git a/website/docs/features/interactive-viewers.md b/website/docs/features/interactive-viewers.md index a6bc01f38..cadae23b2 100644 --- a/website/docs/features/interactive-viewers.md +++ b/website/docs/features/interactive-viewers.md @@ -38,7 +38,8 @@ filters in R. frames. This requires the nanoarrow package, and these views cannot be sorted or filtered. - On R >= 4.6, `View(df)` follows the variable `df`: assigning a new value to it - updates the open view. Turn this off with `options(sess.dataviewer.track = + updates the open view. If `View()` installs jdv, run `View(df)` again to open + a view that follows `df`. Turn tracking off with `options(sess.dataviewer.track = FALSE)` in R, or for R terminals with `r.session.viewers.trackVariables`; the R option takes precedence. - When jdv cannot be used (for example, it is not installed or is already