diff --git a/scripts/test-activation.cjs b/scripts/test-activation.cjs index 83cb9438f..7d0e33d47 100644 --- a/scripts/test-activation.cjs +++ b/scripts/test-activation.cjs @@ -11,7 +11,7 @@ const cases = [ 'workspace', 'command', 'terminal-profile', 'task', 'r-notebook', 'interactive-create', 'interactive-restore', 'interactive-background-create', 'interactive-background-restore', - 'terminal-persistent-reload', + 'terminal-persistent-reload', 'terminal-revive-create', 'terminal-revive-restore', ]; const pause = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); @@ -22,9 +22,9 @@ function clearElectronNodeMode(environment) { } exports.clearElectronNodeMode = clearElectronNodeMode; -async function until(predicate, message) { - const deadline = Date.now() + 15000; - while (!predicate()) { +async function until(predicate, message, timeout = 15000) { + const deadline = Date.now() + timeout; + while (!(await predicate())) { assert.ok(Date.now() < deadline, message); await pause(50); } @@ -164,6 +164,63 @@ exports.run = async (api) => { vscode.window.terminals.forEach((terminal) => terminal.dispose()); break; } + case 'terminal-revive-create': + case 'terminal-revive-restore': { + const creating = testCase === 'terminal-revive-create'; + const previousFile = path.join(root, 'terminal-before-quit.json'); + if (creating) { + await within(vscode.commands.executeCommand('r.createRTerm'), 'Could not create R terminal'); + } + const previous = creating ? undefined : JSON.parse(fs.readFileSync(previousFile, 'utf8')); + const name = previous?.name ?? 'R Interactive'; + await until(() => vscode.window.terminals.some((term) => term.name === name), + 'The R terminal was missing from the restored window'); + const terminal = vscode.window.terminals.find((term) => term.name === name); + const terminalPid = await within(terminal.processId, 'Missing terminal PID'); + const stateFile = path.join(root, testCase + '-state'); + const rPath = (value) => JSON.stringify(value.replace(/\\/g, '/')); + const deadline = Date.now() + 30000; + while (!fs.existsSync(stateFile)) { + assert.ok(Date.now() < deadline, 'R terminal did not report its startup state'); + terminal.sendText(`writeLines(c(Sys.getpid(), sess:::.session_id(), Sys.getenv('SESS_DISCOVERY_FILE')), ` + + `${rPath(stateFile + '.pending')}); invisible(file.rename(${rPath(stateFile + '.pending')}, ${rPath(stateFile)}))`); + for (let i = 0; i < 20 && !fs.existsSync(stateFile); ++i) { await pause(100); } + } + const [pid, sessionId, discovery] = fs.readFileSync(stateFile, 'utf8').trim().split(/\r?\n/); + if (creating) { + await until(() => extension.exports.session.getSessionReference(sessionId), 'Initial sess attachment failed'); + const logs = path.join(root, 'profile', 'logs'); + await until(() => terminalLayoutState(logs, terminalPid).saved, 'R terminal layout was not saved'); + fs.writeFileSync(previousFile, JSON.stringify({ name: terminal.name, pid, sessionId })); + } else { + assert.notEqual(pid, previous.pid, 'A full restart must create a new R process'); + assert.notEqual(sessionId, previous.sessionId); + // The new R process has already tried the saved endpoint. Exercise + // recovery even if its stale discovery record is removed before activation. + const sessionsDir = path.join(root, 'profile', 'User', 'globalStorage', 'reditorsupport.r', 'sessions'); + assert.equal(path.relative(sessionsDir, path.dirname(discovery)), ''); + fs.rmSync(discovery, { force: true }); + const document = await vscode.workspace.openTextDocument({ language: 'r', content: 'revived' }); + await vscode.window.showTextDocument(document); + await until(() => extension.isActive, 'R file did not activate vscode-R'); + await until(() => extension.exports.session.getSessionReference(sessionId), + `Revived R terminal ${terminalPid} did not attach R process ${pid} through ${discovery}`); + terminal.sendText('revivedTable <- data.frame(x = 1)'); + // The connection is public before the native process lookup selects + // its Workspace. Wait for the editor's session completion to observe + // the object created in this R process. + await until(async () => { + const completions = await vscode.commands.executeCommand('vscode.executeCompletionItemProvider', + document.uri, new vscode.Position(0, 7)); + return completions.items.some((item) => item.label === 'revivedTable' && item.detail === '[session]'); + }, 'The refreshed Workspace did not contain the revived session object', 30000); + terminal.sendText('View(revivedTable); plot(1)'); + const hasTab = (label) => vscode.window.tabGroups.all.some((group) => group.tabs.some((tab) => tab.label === label)); + await until(() => hasTab('revivedTable') && hasTab('R Plot'), 'Data and plot viewers did not open after revival'); + terminal.dispose(); + } + break; + } case 'terminal-persistent-reload': { const phaseFile = path.join(root, 'terminal-reload-state.json'); const reloading = fs.existsSync(phaseFile); @@ -356,7 +413,7 @@ async function main() { const executable = process.env.VSCR_ACTIVATION_VSCODE || await downloadAndUnzipVSCode(); const selected = process.env.VSCR_ACTIVATION_CASES?.split(',') || cases; selected.forEach((testCase) => assert.ok(cases.includes(testCase), `Unknown case: ${testCase}`)); - for (const prefix of ['interactive-', 'interactive-background-']) { + for (const prefix of ['interactive-', 'interactive-background-', 'terminal-revive-']) { if (selected.includes(`${prefix}restore`)) { assert.ok(selected.includes(`${prefix}create`), 'Restore requires its create stage in the same run'); assert.ok(selected.indexOf(`${prefix}create`) < selected.indexOf(`${prefix}restore`)); @@ -402,19 +459,21 @@ exports.activate = async () => { try { const reports = []; for (const testCase of selected) { - const persistentTerminal = testCase === 'terminal-persistent-reload'; + const revive = testCase.startsWith('terminal-revive-'); + const persistentTerminal = testCase === 'terminal-persistent-reload' || revive; const name = testCase.startsWith('interactive-background-') ? 'restore-background' - : testCase.startsWith('interactive-') ? 'restore' : testCase; + : testCase.startsWith('interactive-') ? 'restore' : revive ? 'terminal-revive' : testCase; const caseRoot = path.join(root, name); const workspace = path.join(caseRoot, 'workspace'); const profile = path.join(caseRoot, 'profile'); fs.mkdirSync(workspace, { recursive: true }); fs.mkdirSync(path.join(profile, 'User'), { recursive: true }); fs.writeFileSync(path.join(profile, 'User', 'settings.json'), JSON.stringify({ - 'r.lsp.enabled': false, 'r.sessionWatcher': persistentTerminal, 'r.plot.backend': 'native', + 'r.lsp.enabled': false, 'r.sessionWatcher': persistentTerminal, 'r.plot.backend': revive ? 'standard' : 'native', 'r.interactive.restore': false, 'r.interactive.storagePath': path.join(caseRoot, 'sessions'), 'update.mode': 'none', 'extensions.autoUpdate': false, 'workbench.startupEditor': 'none', 'window.restoreWindows': 'all', 'terminal.integrated.enablePersistentSessions': persistentTerminal, + ...(revive ? { 'terminal.integrated.persistentSessionReviveProcess': 'onExitAndWindowClose' } : {}), ...(persistentTerminal ? { 'r.session.emulateRStudioAPI': false, 'r.consoleArgs': ['--no-save', '--no-restore', '--no-site-file'] } : {}), })); @@ -437,15 +496,17 @@ exports.activate = async () => { const library = path.join(caseRoot, 'r-library'); const librariesFile = path.join(caseRoot, 'r-library-paths'); const emptyProfile = path.join(caseRoot, 'empty-profile'); - fs.mkdirSync(library); + fs.mkdirSync(library, { recursive: true }); fs.writeFileSync(emptyProfile, ''); const rString = (value) => JSON.stringify(value.replace(/\\/g, '/')); - const setup = spawnSync('Rscript', ['--vanilla', '-e', - `writeLines(.libPaths(), ${rString(librariesFile)}); ` + - `install.packages(${rString(path.join(repository, 'dist', 'resources', 'sess'))}, ` + - `lib=${rString(library)}, repos=NULL, type='source')`], - { encoding: 'utf8', timeout: 300000 }); - assert.equal(setup.status, 0, `Could not prepare isolated terminal sess: ${setup.stderr}`); + if (!fs.existsSync(librariesFile)) { + const setup = spawnSync('Rscript', ['--vanilla', '-e', + `writeLines(.libPaths(), ${rString(librariesFile)}); ` + + `install.packages(${rString(path.join(repository, 'dist', 'resources', 'sess'))}, ` + + `lib=${rString(library)}, repos=NULL, type='source')`], + { encoding: 'utf8', timeout: 300000 }); + assert.equal(setup.status, 0, `Could not prepare isolated terminal sess: ${setup.stderr}`); + } env.R_LIBS_USER = [library, ...fs.readFileSync(librariesFile, 'utf8').trim().split(/\r?\n/)].join(path.delimiter); env.R_PROFILE_USER = emptyProfile; } @@ -495,20 +556,21 @@ exports.activate = async () => { for (const directory of fs.readdirSync(root, { withFileTypes: true })) { if (!directory.isDirectory()) { continue; } const caseRoot = path.join(root, directory.name); - if (directory.name === 'terminal-persistent-reload') { + const terminalCase = directory.name === 'terminal-persistent-reload' || directory.name === 'terminal-revive'; + if (terminalCase) { fs.mkdirSync(path.join(artifacts, directory.name), { recursive: true }); } for (const file of fs.readdirSync(caseRoot, { withFileTypes: true })) { if (file.name.endsWith('.log')) { fs.copyFileSync(path.join(caseRoot, file.name), path.join(artifacts, `${directory.name}-${file.name}`)); - } else if (directory.name === 'terminal-persistent-reload' && file.isFile()) { + } else if (terminalCase && file.isFile()) { // Phase and probe files show how far each window got. fs.copyFileSync(path.join(caseRoot, file.name), path.join(artifacts, directory.name, file.name)); } } - if (directory.name === 'terminal-persistent-reload') { + if (terminalCase) { const logs = path.join(caseRoot, 'profile', 'logs'); if (fs.existsSync(logs)) { fs.cpSync(logs, path.join(artifacts, directory.name, 'logs'), { recursive: true }); diff --git a/sess/R/server.R b/sess/R/server.R index 48c100470..d0b02219e 100644 --- a/sess/R/server.R +++ b/sess/R/server.R @@ -18,9 +18,11 @@ #' @details #' When SESS_DISCOVERY_FILE describes the connected endpoint, an unexpected disconnect waits for a #' replacement endpoint in that file and reconnects with the same runtime options and session -#' identity. The optional discovery jgdSocket string updates JGD_SOCKET when the resolved backend -#' includes jgd and `allow_jgd` is `TRUE`; an empty string clears it, and an omitted field leaves it -#' unchanged. Set `options(sess.quiet = TRUE)` to suppress the successful connection message. +#' identity. A managed R terminal that starts before its editor is ready retries its first discovery +#' connection in the background. A new R process gets its own workspace and session identity. The +#' optional discovery jgdSocket string updates JGD_SOCKET when the resolved backend includes jgd and +#' `allow_jgd` is `TRUE`; an empty string clears it, and an omitted field leaves it unchanged. Set +#' `options(sess.quiet = TRUE)` to suppress the successful connection message. #' @export connect <- function( endpoint = NULL, @@ -69,21 +71,27 @@ connect <- function( .sess_env$latest_plot_path <- file.path(.sess_env$tempdir, "sess_plot.png") - endpoint <- .resolve_endpoint(endpoint) - if (!nzchar(endpoint)) { - warning("[sess] Connection info not available. Cannot connect to VS Code.") - return(invisible(FALSE)) - } - discovery_file <- Sys.getenv("SESS_DISCOVERY_FILE") + registration <- getOption("vscodeR.terminalStartup") + managed_startup <- is.null(endpoint) && + !nzchar(Sys.getenv("SESS_ENDPOINT")) && + nzchar(discovery_file) && + is.list(registration) && + identical(registration$pid, Sys.getpid()) && + identical(registration$file, paste0(discovery_file, ".startup")) && + is.function(registration$run) # Only follow discovery if it describes this connection, including explicit # endpoints from the generated attach script. Never redirect an unrelated client. discovery <- if (nzchar(discovery_file)) .read_discovery(discovery_file) else NULL - if (!is.null(discovery) && identical(discovery$endpoint, endpoint)) { + endpoint <- if (managed_startup) discovery$endpoint %||% "" else .resolve_endpoint(endpoint) + if (managed_startup || (!is.null(discovery) && identical(discovery$endpoint, endpoint))) { .configure_discovery_jgd(discovery, allow_jgd && plot_backend %in% c("auto", "jgd")) .sess_env$reconnect <- list( path = discovery_file, - endpoint = endpoint, + # The first handshake can lose its socket during the attach write or poll. + # Until startup succeeds, even the same endpoint is eligible for retry. + endpoint = if (managed_startup) NULL else endpoint, + startup_run = if (managed_startup) registration$run, options = list( use_rstudioapi = use_rstudioapi, plot_backend = plot_backend, @@ -94,6 +102,21 @@ connect <- function( ) } + retry_startup <- function() { + if (managed_startup) { + message("[sess] Waiting for VS Code to accept the terminal connection.") + .schedule_reconnect(.sess_env$reconnect) + } + invisible(FALSE) + } + if (!nzchar(endpoint)) { + if (!managed_startup) { + warning("[sess] Connection info not available. Cannot connect to VS Code.") + } + return(retry_startup()) + } + discovery_endpoint <- endpoint + # processx uses the \\?\pipe\ namespace on Windows. # Normalize \\.\pipe\* paths from Node.js to improve compatibility. if (.Platform$OS.type == "windows") { @@ -106,7 +129,7 @@ connect <- function( # and the console does not redraw it. Startup and console calls to connect() # are followed by the frontend's own prompt. print_async_msg <- function(msg) { - redraw <- isTRUE(.sess_env$reconnecting) && interactive() + redraw <- !is.null(.sess_env$reconnecting) && interactive() prompt <- if (redraw) getOption("prompt") else "" cat(sprintf("\r%s\n\n%s", msg, prompt)) } @@ -115,12 +138,14 @@ connect <- function( con <- tryCatch( processx::conn_connect_unix_socket(endpoint, encoding = ""), error = function(e) { - print_async_msg(sprintf("[sess] Failed to connect to IPC endpoint: %s", e$message)) + if (!managed_startup && !identical(.sess_env$reconnecting, "startup")) { + print_async_msg(sprintf("[sess] Failed to connect to IPC endpoint: %s", e$message)) + } NULL } ) if (is.null(con)) { - return(FALSE) + return(retry_startup()) } .sess_env$con <- con @@ -138,15 +163,12 @@ connect <- function( # Start the polling loop poll_connection(.sess_env$transport_generation) - TRUE - } - - connected <- do_connect() - - if (is.na(use_rstudioapi)) { - use_rstudioapi <- TRUE - } - if (isTRUE(connected) && !is.null(.sess_env$con)) { + if (is.null(.sess_env$con)) { + return(FALSE) + } + if (is.na(use_rstudioapi)) { + use_rstudioapi <- TRUE + } tryCatch( runtime_start( use_rstudioapi = use_rstudioapi, @@ -180,9 +202,18 @@ connect <- function( .sess_env$runtime_start_phase <- NULL } ) + if (!is.null(.sess_env$con) && managed_startup) { + .sess_env$reconnect$endpoint <- discovery_endpoint + .sess_env$reconnect$startup_run <- NULL + } + invisible(!is.null(.sess_env$con)) } - - invisible(isTRUE(connected) && !is.null(.sess_env$con)) + if (managed_startup && !identical(registration$endpoint, discovery_endpoint)) { + # The editor replaced discovery before the revived profile reached sess. + # Publish readiness for the actual endpoint, superseding the saved attempt. + return(.reconnect_with_startup(discovery_endpoint, do_connect)) + } + do_connect() } # Resolve the direct argument, environment variables, then discovery data. @@ -343,7 +374,8 @@ connect <- function( .schedule_reconnect <- function( settings, generation = .sess_env$transport_generation, - schedule = later::later + schedule = later::later, + delay = 1 ) { if (is.null(settings)) { return(invisible(NULL)) @@ -359,8 +391,22 @@ connect <- function( ) { return(invisible(NULL)) } + registration <- getOption("vscodeR.terminalStartup") + if ( + is.null(settings$endpoint) && + (!is.list(registration) || + !identical(registration$pid, pid) || + !identical(registration$file, paste0(settings$path, ".startup")) || + !identical(registration$run, settings$startup_run)) + ) { + return(invisible(NULL)) + } discovery <- .read_discovery(settings$path) endpoint <- discovery$endpoint + if (is.null(endpoint) && is.null(settings$endpoint)) { + # Wake an editor which started after the discovery file disappeared. + .reconnect_with_startup(registration$endpoint, function() FALSE) + } if ( is.character(endpoint) && length(endpoint) == 1L && @@ -377,7 +423,7 @@ connect <- function( discovery, isTRUE(allow_jgd) && settings$options$plot_backend %in% c("auto", "jgd") ) - .sess_env$reconnecting <- TRUE + .sess_env$reconnecting <- if (is.null(settings$endpoint)) "startup" else TRUE tryCatch( .reconnect_with_startup( endpoint, @@ -390,6 +436,7 @@ connect <- function( ) if (!is.null(.sess_env$con)) { settings$endpoint <- endpoint + settings$startup_run <- NULL .sess_env$reconnect <- settings return(invisible(NULL)) } @@ -397,9 +444,10 @@ connect <- function( # before scheduling our retry so there is only one pending chain. .transport_disconnect(silent = TRUE, preserve_plots = TRUE) } - .schedule_reconnect(settings, .sess_env$transport_generation, schedule) + next_delay <- if (is.null(settings$endpoint)) min(delay * 2, 8) else 1 + .schedule_reconnect(settings, .sess_env$transport_generation, schedule, next_delay) }, - 1 + delay ) invisible(NULL) } diff --git a/sess/inst/tinytest/test-reconnect.R b/sess/inst/tinytest/test-reconnect.R index 167d119f6..8c0624e18 100644 --- a/sess/inst/tinytest/test-reconnect.R +++ b/sess/inst/tinytest/test-reconnect.R @@ -199,3 +199,105 @@ local({ tick() # Invalidate the retry without invoking setup. expect_equal(length(callbacks), 0L) }) + +# Initial discovery retries belong only to a managed profile in this process. +local({ + env <- new.env(parent = asNamespace("sess")) + env$connect <- sess::connect + environment(env$connect) <- env + scheduled <- list() + env$.schedule_reconnect <- function(settings) scheduled[[length(scheduled) + 1L]] <<- settings + directory <- tempfile("revive-") + dir.create(directory) + discovery <- file.path(directory, "terminal.json") + socket <- if (.Platform$OS.type == "windows") { + paste0("\\\\?\\pipe\\vscode-r-", basename(directory)) + } else { + file.path(directory, "r.sock") + } + original <- Sys.getenv(c("SESS_DISCOVERY_FILE", "SESS_ENDPOINT"), unset = NA_character_) + registration <- list( + file = paste0(discovery, ".startup"), + pid = Sys.getpid(), + endpoint = socket, + run = function(endpoint, setup) setup() + ) + old <- options(vscodeR.terminalStartup = registration, warn = 2) + on.exit( + { + options(old) + for (key in names(original)) { + if (is.na(original[[key]])) { + Sys.unsetenv(key) + } else { + do.call(Sys.setenv, as.list(original[key])) + } + } + sess:::.transport_disconnect(silent = TRUE) + unlink(directory, recursive = TRUE) + }, + add = TRUE + ) + Sys.setenv(SESS_DISCOVERY_FILE = discovery) + Sys.unsetenv("SESS_ENDPOINT") + attempt <- function(...) { + capture.output(result <- env$connect(..., use_rstudioapi = FALSE, plot_backend = "native")) + expect_false(result) + } + attempt() + expect_length(scheduled, 1L) + expect_identical(scheduled[[1L]]$path, discovery) + expect_null(scheduled[[1L]]$endpoint) + expect_identical(scheduled[[1L]]$options$use_rstudioapi, FALSE) + expect_identical(scheduled[[1L]]$options$plot_backend, "native") + writeLines(jsonlite::toJSON(list(version = 1L, endpoint = socket), auto_unbox = TRUE), discovery) + attempt() + expect_length(scheduled, 2L) + expect_null(scheduled[[2L]]$endpoint) + + # The current endpoint can be published before this profile even starts. + registration$endpoint <- "saved-endpoint" + notified <- NULL + registration$run <- function(endpoint, setup) { + notified <<- endpoint + setup() + } + options(vscodeR.terminalStartup = registration) + attempt() + expect_identical(notified, socket) + expect_length(scheduled, 3L) + # A direct attach, environment override, or inherited registration stays one-shot. + attempt(endpoint = socket) + Sys.setenv(SESS_ENDPOINT = socket) + attempt() + Sys.unsetenv("SESS_ENDPOINT") + registration$pid <- Sys.getpid() + 1L + options(vscodeR.terminalStartup = registration) + attempt() + expect_length(scheduled, 3L) + + # If the first connection is lost during its attach write, it has never + # been ready. The same endpoint must still be eligible for exactly one retry. + registration$pid <- Sys.getpid() + registration$endpoint <- socket + options(vscodeR.terminalStartup = registration) + env$.transport_disconnect <- sess:::.transport_disconnect + environment(env$.transport_disconnect) <- env + env$notify_client <- function(...) env$.transport_disconnect(silent = TRUE, reconnect = TRUE) + server <- processx::conn_create_unix_socket(socket, encoding = "") + on.exit(try(close(server), silent = TRUE), add = TRUE) + attempt() + expect_length(scheduled, 4L) + expect_null(scheduled[[4L]]$endpoint) + expect_identical(scheduled[[4L]]$startup_run, registration$run) + + # Replacing the managed registration cancels the original process's retry. + callbacks <- list() + retry <- sess:::.schedule_reconnect + environment(retry) <- env + retry(scheduled[[4L]], schedule = function(f, delay) callbacks[[length(callbacks) + 1L]] <<- f) + options(vscodeR.terminalStartup = NULL) + callbacks[[1L]]() + expect_length(callbacks, 1L) + expect_null(sess:::.sess_env$con) +}) diff --git a/sess/man/connect.Rd b/sess/man/connect.Rd index 302f54856..a5663f084 100644 --- a/sess/man/connect.Rd +++ b/sess/man/connect.Rd @@ -43,7 +43,10 @@ Connect to the VS Code IPC server \details{ When SESS_DISCOVERY_FILE describes the connected endpoint, an unexpected disconnect waits for a replacement endpoint in that file and -reconnects with the same runtime options and session identity. The optional +reconnects with the same runtime options and session identity. A managed R +terminal that starts before its editor is ready retries its first discovery +connection in the background. A new R process gets its own workspace and +session identity. The optional discovery jgdSocket string updates JGD_SOCKET when the resolved backend includes jgd and \code{allow_jgd} is \code{TRUE}; an empty string clears it, and an omitted field leaves it unchanged. Set diff --git a/src/session.ts b/src/session.ts index 1e0a8970d..3ff9e5b3c 100644 --- a/src/session.ts +++ b/src/session.ts @@ -15,6 +15,7 @@ import { config, readContent, readSessSourceRevision, setContext, UriIcon } from import * as rTerminal from './rTerminal'; import { getProcessAncestors } from './processTree'; import { TerminalSessionRegistry } from './terminalSessionRegistry'; +import { TerminalStartupMonitor } from './terminalStartupMonitor'; import { SessionProcessMonitor } from './sessionProcessMonitor'; import { sessionProcessIdentity } from './sessionIdentity'; import { NativeTerminalPidWaitRegistry } from './nativeTerminalPidWait'; @@ -458,7 +459,7 @@ const TERMINAL_ATTACH_TIMEOUT = 30000; /** Read the bounded status sidecar written by the R startup helper. */ async function readTerminalStartupRecord( filePath: string, - token: string, + token?: string, ): Promise { let file: fs.promises.FileHandle | undefined; try { @@ -905,13 +906,19 @@ export function deploySessionWatcher(extensionPath: string): void { attachSessionScriptPath = undefined; } attachmentLifecycleGeneration++; + void terminalStartupWatcher?.dispose(); + terminalStartupWatcher = undefined; attachmentLifecycleStopping = false; console.info(`[deploySessionWatcher] extensionPath: ${extensionPath}`); resDir = path.join(extensionPath, 'dist', 'resources'); + const generation = attachmentLifecycleGeneration; void getGlobalPipePath() .then(async (pipePath) => { - await refreshTerminalDiscoveryFiles(pipePath); + await Promise.all([ + watchTerminalStartupRecords(pipePath, generation), + refreshTerminalDiscoveryFiles(pipePath), + ]); }) .catch((err) => { console.error('Failed to initialize global session server', err); @@ -1242,6 +1249,86 @@ async function findDiscoveryFileForTerminal(terminalPid: number): Promise { + const isCurrent = () => + generation === attachmentLifecycleGeneration && !attachmentLifecycleStopping; + if (!isCurrent()) { + return; + } + terminalStartupWatcher = new TerminalStartupMonitor( + getSessionDiscoveryDir(), + readTerminalStartupRecord, + async (file, record, observedRetry) => { + const discovery = file.slice(0, -'.startup'.length); + if (!isCurrent() || !isExtensionDiscoveryPath(discovery)) { + return; + } + await refreshRevivedTerminal(discovery, endpoint, isCurrent, record, observedRetry); + }, + ); + await terminalStartupWatcher.start(); +} + +async function refreshRevivedTerminal( + discovery: string, + endpoint: string, + isCurrent: () => boolean, + record: TerminalStartupRecord, + observedRetry: boolean, +): Promise { + const file = discovery + '.startup'; + if ( + !window.terminals.some( + (term) => + isNativeTerminalEligible(term) && + (observedRetry || terminalDiscoveryPath(term) === discovery), + ) + ) { + return; + } + if (await pathExists(discovery)) { + const saved = (await readJson(discovery)) as Partial; + if ( + saved.version !== 1 || + saved.endpoint !== record.endpoint || + saved.endpoint === endpoint + ) { + return; + } + } + const candidate = await findLocalTerminal(String(record.pid)); + const options = candidate?.terminal.creationOptions as vscode.TerminalOptions | undefined; + const envPath = options?.env?.['SESS_DISCOVERY_FILE']; + if ( + !candidate?.isCurrent() || + !isCurrent() || + (envPath !== discovery && (!observedRetry || envPath !== undefined)) + ) { + return; + } + const latest = await readTerminalStartupRecord(file, record.token); + if ( + latest?.attemptId !== record.attemptId || + latest.pid !== record.pid || + latest.endpoint !== record.endpoint || + latest.status !== 'failed' + ) { + return; + } + await updateTerminalSessionDiscoveryFile( + candidate.terminal, + discovery, + endpoint, + Number(candidate.pid), + () => isCurrent() && candidate.isCurrent(), + ); +} + export async function refreshTerminalDiscoveryFiles( pipePath: string, terminals: readonly vscode.Terminal[] = vscode.window.terminals, @@ -1997,6 +2084,8 @@ export async function shutdownSessionWatcher(): Promise { nativeTerminalPidWaits.invalidateAll(); attachmentLifecycleGeneration++; attachmentLifecycleStopping = true; + const startupMonitorStopped = terminalStartupWatcher?.dispose(); + terminalStartupWatcher = undefined; const terminalIntegrationSnapshot = [...terminalIntegrations.values()]; const shutdownGeneration = attachmentLifecycleGeneration; const consentStartup = attachConsentStartup; @@ -2053,7 +2142,7 @@ export async function shutdownSessionWatcher(): Promise { sessionSelectionRevision++; revokeTerminalIntegrationSnapshot(terminalIntegrationSnapshot); enqueueSessionConnectionChanges(shutdownChanges); - await Promise.allSettled(pendingOperations); + await Promise.allSettled([...pendingOperations, startupMonitorStopped]); await manualCleanup.catch(() => undefined); await consentStartup?.catch(() => undefined); await consentService?.stop(); diff --git a/src/terminalStartup.ts b/src/terminalStartup.ts index 4d1b67a39..6c145253d 100644 --- a/src/terminalStartup.ts +++ b/src/terminalStartup.ts @@ -22,7 +22,7 @@ const MAX_RECORD_BYTES = 512; /** Parse the small base-R sidecar without accepting partial or cross-terminal records. */ export function parseTerminalStartupRecord( contents: string, - expectedToken: string, + expectedToken?: string, ): TerminalStartupRecord | undefined { if (Buffer.byteLength(contents, 'utf8') > MAX_RECORD_BYTES) { return; @@ -32,7 +32,11 @@ export function parseTerminalStartupRecord( return; } lines.pop(); - if (lines.length !== 6 || lines[0] !== PROTOCOL || lines[1] !== expectedToken) { + if ( + lines.length !== 6 || + lines[0] !== PROTOCOL || + (expectedToken !== undefined && lines[1] !== expectedToken) + ) { return; } if (!/^[a-f0-9]{32}$/.test(lines[1])) { diff --git a/src/terminalStartupMonitor.ts b/src/terminalStartupMonitor.ts new file mode 100644 index 000000000..d79080406 --- /dev/null +++ b/src/terminalStartupMonitor.ts @@ -0,0 +1,268 @@ +import fs from 'node:fs'; +import * as path from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import type { TerminalStartupRecord } from './terminalStartup'; + +const recordName = /^[a-f0-9]{32}\.json\.startup$/i; +const pollMs = 2_000; +const fullPollMs = 60_000; + +interface Snapshot { + stamp: string; + record?: TerminalStartupRecord; +} + +function stamp(stat: fs.BigIntStats): string { + return `${stat.dev}:${stat.ino}:${stat.ctimeNs}:${stat.mtimeNs}:${stat.size}`; +} + +/** Watch atomic terminal startup publications. Polling also works on filesystems + * which omit filenames or silently drop notifications. Each instance owns one + * extension-host lifetime and serializes record inspection and publication. */ +export class TerminalStartupMonitor { + private readonly stopped = new AbortController(); + private watcher?: fs.FSWatcher; + private watchedDirectory?: string; + private retry?: NodeJS.Timeout; + private interval?: NodeJS.Timeout; + private retryMs = 250; + private scanRequested = false; + private forceScan = false; + private readonly named = new Set(); + private readonly seen = new Map(); + private directoryStamp?: string; + private lastFullScan = 0; + private running?: Promise; + + constructor( + private readonly directory: string, + private readonly read: (file: string) => Promise, + private readonly failed: ( + file: string, + record: TerminalStartupRecord, + observedRetry: boolean, + ) => Promise, + ) {} + + async start(): Promise { + if (this.interval || this.stopped.signal.aborted) { + return; + } + this.interval = setInterval(() => void this.scan(false), pollMs); + this.interval.unref(); + await this.arm(); + } + + dispose(): Promise { + this.stopped.abort(); + clearInterval(this.interval); + clearTimeout(this.retry); + this.watcher?.close(); + this.watcher = undefined; + this.named.clear(); + this.seen.clear(); + return this.running ?? Promise.resolve(); + } + + private async arm(): Promise { + try { + await fs.promises.mkdir(this.directory, { recursive: true }); + const stat = await fs.promises.stat(this.directory, { bigint: true }); + if (this.stopped.signal.aborted) { + return; + } + const watcher = fs.watch(this.directory, { persistent: false }, (_, name) => { + if (this.watcher !== watcher || this.stopped.signal.aborted) { + return; + } + this.retryMs = 250; + if (!name) { + void this.scan(true); + } else if (recordName.test(name)) { + this.named.add(name); + void this.drain(); + } + }); + this.watcher = watcher; + this.watchedDirectory = `${stat.dev}:${stat.ino}`; + const lost = (error?: Error) => { + if (this.watcher !== watcher || this.stopped.signal.aborted) { + return; + } + this.retire(watcher, error); + void this.scan(true); + }; + watcher.on('error', lost); + watcher.on('close', lost); + } catch (error) { + this.scheduleRetry(error); + } + // A publication may precede registration or land while the watcher is down. + await this.scan(true); + } + + private retire(watcher: fs.FSWatcher, error?: Error): void { + if (this.watcher !== watcher || this.stopped.signal.aborted) { + return; + } + this.watcher = undefined; + this.watchedDirectory = undefined; + this.named.clear(); + watcher.close(); + this.scheduleRetry(error); + } + + private scheduleRetry(error?: unknown): void { + if (this.retry || this.stopped.signal.aborted) { + return; + } + if (error && this.retryMs === 250) { + console.warn( + '[session discovery] Terminal startup watch unavailable, polling for recovery', + error, + ); + } + this.retry = setTimeout(() => { + this.retry = undefined; + void this.arm(); + }, this.retryMs); + this.retry.unref(); + this.retryMs = Math.min(30_000, this.retryMs * 2); + } + + private scan(force: boolean): Promise { + this.scanRequested = true; + this.forceScan ||= force; + return this.drain(); + } + + private drain(): Promise { + this.running ??= Promise.resolve().then(async () => { + try { + while (!this.stopped.signal.aborted && (this.named.size || this.scanRequested)) { + if (this.scanRequested) { + const force = this.forceScan; + this.scanRequested = this.forceScan = false; + await this.scanDirectory(force); + } else { + await this.nextNamed(); + } + } + } finally { + this.running = undefined; + } + }); + return this.running; + } + + private async nextNamed(): Promise { + const name = this.named.values().next().value; + if (name !== undefined) { + this.named.delete(name); + await this.inspect(name, true); + } + } + + private async scanDirectory(force: boolean): Promise { + const watcher = this.watcher; + try { + const stat = await fs.promises.stat(this.directory, { bigint: true }); + const identity = `${stat.dev}:${stat.ino}`; + if (watcher && watcher === this.watcher && identity !== this.watchedDirectory) { + // fs.watch can stay bound to an unlinked inode without emitting an error. + this.retire(watcher); + } + if (this.directoryStamp && !this.directoryStamp.startsWith(identity + ':')) { + this.seen.clear(); + } + const current = stamp(stat); + if ( + !force && + current === this.directoryStamp && + Date.now() - this.lastFullScan < fullPollMs + ) { + return; + } + const missing = new Set(this.seen.keys()); + const entries = await fs.promises.opendir(this.directory); + let count = 0; + for await (const entry of entries) { + if (this.stopped.signal.aborted) { + return; + } + if (entry.isFile() && recordName.test(entry.name)) { + missing.delete(entry.name); + await this.inspect(entry.name, this.named.delete(entry.name)); + } + if (this.named.size) { + await this.nextNamed(); + } + // Pace metadata I/O in large historical directories. Named events + // continue to make progress while a full scan is in flight. + if (++count % 32 === 0) { + await delay(100, undefined, { ref: false, signal: this.stopped.signal }); + } + } + for (const name of missing) { + this.seen.delete(name); + } + this.directoryStamp = current; + this.lastFullScan = Date.now(); + } catch (error) { + this.directoryStamp = undefined; + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT' || code === 'ENOTDIR') { + this.seen.clear(); + if (watcher) { + this.retire(watcher); + } + } + } + } + + private async inspect(name: string, named: boolean): Promise { + const file = path.join(this.directory, name); + try { + const stat = await fs.promises.lstat(file, { bigint: true }); + if (!stat.isFile() || this.stopped.signal.aborted) { + return; + } + const current = stamp(stat); + const previous = this.seen.get(name); + if (!named && previous?.stamp === current) { + return; + } + const record = await this.read(file); + if (this.stopped.signal.aborted) { + return; + } + // A scan can find a historical failure whose PID has since been + // reused. An unlabelled terminal needs a live publication or a new + // retry from the same managed R process before it can claim a file. + const prior = previous?.record; + const observedRetry = + named || + Boolean( + record && + prior && + prior.pid === record.pid && + prior.token === record.token && + (prior.attemptId !== record.attemptId || + (prior.status === 'pending' && record.status === 'failed')), + ); + this.seen.set(name, { stamp: current, record }); + if (record?.status !== 'failed') { + return; + } + await this.failed(file, record, observedRetry); + } catch (error) { + this.seen.delete(name); + if ( + !this.stopped.signal.aborted && + (error as NodeJS.ErrnoException).code !== 'ENOENT' + ) { + console.warn('[session discovery] Could not inspect terminal startup', error); + } + } + } +} diff --git a/src/test/node/terminalStartupMonitor.test.ts b/src/test/node/terminalStartupMonitor.test.ts new file mode 100644 index 000000000..6dc091877 --- /dev/null +++ b/src/test/node/terminalStartupMonitor.test.ts @@ -0,0 +1,231 @@ +import * as assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { EventEmitter } from 'node:events'; +import * as sinon from 'sinon'; +import { TerminalStartupMonitor } from '../../terminalStartupMonitor'; +import type { TerminalStartupRecord } from '../../terminalStartup'; + +suite('Terminal startup monitor', () => { + const name = 'a'.repeat(32) + '.json.startup'; + let directory: string; + let sandbox: sinon.SinonSandbox; + let clock: sinon.SinonFakeTimers; + let open: sinon.SinonStub; + let monitor: TerminalStartupMonitor; + let received: { attempt: string; live: boolean }[]; + let reads: number; + let revision: number; + let hooks: { + watcher: EventEmitter; + change: (name: string | null) => void; + close: sinon.SinonSpy; + }[]; + + async function publish(attempt: string, status: TerminalStartupRecord['status'] = 'failed') { + const file = path.join(directory, name); + const data: TerminalStartupRecord = { + attemptId: attempt, + token: 't', + pid: 123, + endpoint: 'saved', + status, + }; + await fs.promises.writeFile(file + '.tmp', JSON.stringify(data)); + await fs.promises.rename(file + '.tmp', file); + // Make the directory timestamp distinct even on a coarse test filesystem. + await fs.promises.utimes(directory, ++revision, revision); + } + + async function until(condition: () => boolean) { + const deadline = Date.now() + 5000; + while (!condition()) { + assert.ok(Date.now() < deadline, 'monitor did not finish the requested operation'); + await new Promise((resolve) => setImmediate(resolve)); + } + } + + setup(async () => { + directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'vscode-r-startup-')); + sandbox = sinon.createSandbox(); + clock = sandbox.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'], + }); + hooks = []; + open = sandbox.stub(fs, 'watch').callsFake((( + _dir: string, + _options: object, + notify: (event: string, name: string | null) => void, + ) => { + const watcher = new EventEmitter(); + const close = sinon.spy(() => watcher.emit('close')); + hooks.push({ watcher, close, change: (name) => notify('rename', name) }); + return Object.assign(watcher, { close }); + }) as unknown as typeof fs.watch); + received = []; + reads = 0; + revision = 100; + monitor = new TerminalStartupMonitor( + directory, + async (file) => { + reads++; + return JSON.parse( + await fs.promises.readFile(file, 'utf8'), + ) as TerminalStartupRecord; + }, + (_file, record, live) => { + received.push({ attempt: record.attemptId, live }); + return Promise.resolve(); + }, + ); + }); + + teardown(async () => { + await monitor.dispose(); + sandbox.restore(); + await fs.promises.rm(directory, { recursive: true, force: true }); + }); + + test('scans at startup and on nameless events, and requires live evidence for a scan-only record', async () => { + await publish('historical'); + await monitor.start(); + assert.deepEqual(received, [{ attempt: 'historical', live: false }]); + await publish('retry'); + hooks[0].change(null); + await until(() => received.length === 2); + assert.deepEqual(received[1], { attempt: 'retry', live: true }); + assert.equal(reads, 2); + await clock.tickAsync(2000); // Unchanged directory only needs a metadata check. + assert.equal(reads, 2); + }); + + test('finds silent atomic replacements and retains evidence from a pending retry', async () => { + await monitor.start(); + await publish('first'); + await clock.tickAsync(2000); + await until(() => received.length === 1); + assert.deepEqual(received[0], { attempt: 'first', live: false }); + await publish('second', 'pending'); + await clock.tickAsync(2000); + await until(() => reads === 2); + await publish('second'); + await clock.tickAsync(2000); + await until(() => received.length === 2); + assert.deepEqual(received[1], { attempt: 'second', live: true }); + }); + + test('treats a nameless pending-to-failed publication as evidence for the same attempt', async () => { + await publish('one', 'pending'); + await monitor.start(); + assert.equal(received.length, 0); + await publish('one'); + hooks[0].change(null); + await until(() => received.length === 1); + assert.deepEqual(received[0], { attempt: 'one', live: true }); + }); + + test('recreates a silently removed directory and rebinds a silently replaced inode', async () => { + await monitor.start(); + await fs.promises.rm(directory, { recursive: true }); + await clock.tickAsync(2000); + await until(() => hooks[0].close.calledOnce); + await clock.tickAsync(250); + await until(() => hooks.length === 2); + assert.ok((await fs.promises.stat(directory)).isDirectory()); + const old = directory + '-old'; + await fs.promises.rename(directory, old); + try { + await fs.promises.mkdir(directory); + await clock.tickAsync(2000); + await until(() => hooks[1].close.calledOnce); + await clock.tickAsync(500); + await until(() => hooks.length === 3); + await publish('current'); + hooks[2].change(name); + await until(() => received.length === 1); + assert.equal(received[0].live, true); + } finally { + await fs.promises.rm(old, { recursive: true, force: true }); + } + }); + + test('coalesces overlapping hints and stops before publishing an in-flight record', async () => { + await monitor.dispose(); + let resume!: () => void; + let readStarted!: () => void; + const reading = new Promise((resolve) => { + readStarted = resolve; + }); + const blocked = new Promise((resolve) => { + resume = resolve; + }); + let calls = 0; + monitor = new TerminalStartupMonitor( + directory, + async (file) => { + const record = JSON.parse( + await fs.promises.readFile(file, 'utf8'), + ) as TerminalStartupRecord; + calls++; + if (calls === 1) { + readStarted(); + await blocked; + } + return record; + }, + (_file, record, live) => { + received.push({ attempt: record.attemptId, live }); + return Promise.resolve(); + }, + ); + await monitor.start(); + await publish('old', 'pending'); + hooks[0].change(name); + await reading; + await publish('new'); + hooks[0].change(name); + hooks[0].change(name); + assert.equal(calls, 1); + resume(); + await until(() => received.length === 1); + assert.equal(calls, 2); + assert.deepEqual(received, [{ attempt: 'new', live: true }]); + // An event queued immediately before disposal must not reach the publisher. + await publish('after-stop'); + hooks[0].change(name); + await monitor.dispose(); + assert.equal(received.length, 1); + }); + + test('retries failed watch setup and errors with backoff, ignores stale handles and disposes timers', async () => { + const warn = sandbox.stub(console, 'warn'); + open.onFirstCall().throws(new Error('watch initially unavailable')); + await publish('initial'); + await monitor.start(); + assert.equal(received.length, 1); + assert.ok(warn.calledOnce); + await clock.tickAsync(249); + assert.equal(open.callCount, 1); + await clock.tickAsync(1); + await until(() => hooks.length === 1); + const old = hooks[0]; + old.watcher.emit('error', new Error('watch lost')); + assert.equal(old.close.callCount, 1); + await clock.tickAsync(499); + assert.equal(open.callCount, 2); + await clock.tickAsync(1); + await until(() => hooks.length === 2); + const current = hooks[1]; + old.watcher.emit('error', new Error('late error')); + assert.equal(current.close.callCount, 0); + current.watcher.emit('close'); + await monitor.dispose(); + const count = open.callCount; + old.change(name); + current.change(null); + await clock.tickAsync(60000); + assert.equal(open.callCount, count); + assert.equal(clock.countTimers(), 0); + }); +}); diff --git a/src/test/suite/sessionTerminalIntegration.test.ts b/src/test/suite/sessionTerminalIntegration.test.ts index 3bca5661f..b75660cfd 100644 --- a/src/test/suite/sessionTerminalIntegration.test.ts +++ b/src/test/suite/sessionTerminalIntegration.test.ts @@ -2,6 +2,7 @@ import * as assert from 'assert'; import * as os from 'os'; import * as path from 'path'; import * as fsp from 'node:fs/promises'; +import fs from 'node:fs'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; import * as extension from '../../extension'; @@ -221,6 +222,165 @@ suite('External Terminal Integration', () => { } }); + test('revival observes a failed startup while a pending record is still being read', async () => { + const endpoint = await session.getGlobalPipePath(); + const discovery = await session.createSessionDiscoveryFile('previous-endpoint'); + const foreign = await session.createSessionDiscoveryFile('previous-endpoint'); + const startup = discovery + '.startup'; + const pid = 55142; + const checkedTerminal = deferred(); + setTerminals([ + { + ...makeTerminal(Promise.resolve(pid)), + get creationOptions() { + checkedTerminal.resolve(); + return { env: { SESS_DISCOVERY_FILE: discovery } }; + }, + } as vscode.Terminal, + ]); + const status = (state: string) => + [ + 'vscode-r-terminal-startup-v1', + 'a'.repeat(32), + 'a'.repeat(16), + String(pid), + 'previous-endpoint', + state, + '', + ].join('\n'); + async function publish(file: string, state: string): Promise { + await fsp.writeFile(file + '.tmp', status(state)); + await fsp.rename(file + '.tmp', file); + } + const firstRead = deferred(); + const resume = deferred(); + const open = fs.promises.open.bind(fs.promises); + let held = false; + sandbox.stub(fs.promises, 'open').callsFake(async (...args) => { + const handle = await open(...args); + if (args[0] === startup && !held) { + held = true; + const close = handle.close.bind(handle); + handle.close = async () => { + await close(); + firstRead.resolve(); + await resume.promise; + }; + } + return handle; + }); + try { + // Although the claimed process matches, it explicitly belongs to another file. + await publish(foreign + '.startup', 'failed'); + await checkedTerminal.promise; + await publish(startup, 'pending'); + await firstRead.promise; + await publish(startup, 'failed'); + resume.resolve(); + await waitForValue(() => { + const record = JSON.parse(fs.readFileSync(discovery, 'utf8')) as { + endpoint: string; + terminalPid?: number; + }; + return record.endpoint === endpoint && record.terminalPid === pid + ? true + : undefined; + }); + assert.strictEqual( + ((await readJson(foreign)) as { endpoint: string }).endpoint, + 'previous-endpoint', + ); + } finally { + resume.resolve(); + await Promise.all( + [ + discovery, + startup, + startup + '.tmp', + foreign, + foreign + '.startup', + foreign + '.startup.tmp', + ].map((file) => fsp.rm(file, { force: true })), + ); + } + }); + + test('a silent watcher recovers a live retry without claiming an old record with the same PID', async () => { + await session.shutdownSessionWatcher(); + const stale = await session.createSessionDiscoveryFile('old'); + const live = await session.createSessionDiscoveryFile('old'); + const pid = 55162; + const terminal = makeTerminal(Promise.resolve(pid)); // Restored terminal has no creation env. + setTerminals([terminal]); + const watch = fs.watch.bind(fs); + let rescan: (() => void) | undefined; + const directory = path.dirname(stale); + sandbox.stub(fs, 'watch').callsFake((( + target: fs.PathLike, + options: fs.WatchOptionsWithStringEncoding, + notify: fs.WatchListener, + ) => { + if (target === directory) { + rescan = () => notify('rename', null); + return watch(directory, { persistent: false }, () => {}); + } + return watch(target, options, notify); + }) as typeof fs.watch); + const opens = sandbox.spy(fs.promises, 'open'); + async function publish(discovery: string, attempt: string) { + const file = discovery + '.startup'; + await fsp.writeFile( + file + '.tmp', + [ + 'vscode-r-terminal-startup-v1', + 'a'.repeat(32), + attempt, + String(pid), + 'old', + 'failed', + '', + ].join('\n'), + ); + await fsp.rename(file + '.tmp', file); + } + try { + await publish(stale, 'a'.repeat(16)); + await publish(live, 'b'.repeat(16)); + session.deploySessionWatcher(extensionRoot); + const endpoint = await session.getGlobalPipePath(); + await waitForValue(() => + opens.calledWith(stale + '.startup') && opens.calledWith(live + '.startup') + ? true + : undefined, + ); + // Allow the initial read of the live file to close before its atomic replacement on Windows. + const handle = await opens + .getCalls() + .find((call) => call.args[0] === live + '.startup')!.returnValue; + await waitForValue(() => (handle.fd === -1 ? true : undefined)); + await publish(live, 'c'.repeat(16)); + assert.ok(rescan); + rescan(); + await waitForValue(() => { + const data = JSON.parse(fs.readFileSync(live, 'utf8')) as { + endpoint: string; + terminalPid?: number; + }; + return data.endpoint === endpoint && data.terminalPid === pid ? true : undefined; + }); + assert.equal(((await readJson(stale)) as { endpoint: string }).endpoint, 'old'); + } finally { + await session.shutdownSessionWatcher(); + for (const file of [stale, live]) { + await Promise.all( + [file, file + '.startup', file + '.startup.tmp'].map((entry) => + fsp.rm(entry, { force: true }), + ), + ); + } + } + }); + test('discovery refresh updates later native terminals while an unrelated PID remains pending', async () => { const pendingPid = deferred(); const external = makeTerminal(pendingPid.promise);