From 3d21cef8280e007cb05ef3e81d28700807cb9d04 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sat, 28 Nov 2026 18:07:10 +0800 Subject: [PATCH 01/12] Add a managed webR provider to R Interactive --- src/interactive/README.md | 15 +- src/interactive/backendRegistry.ts | 19 ++ src/interactive/backends/webr.ts | 191 ++++++++++++++++ src/interactive/manager.ts | 67 ++++-- src/interactive/protocol.ts | 2 +- src/interactive/sessionPresentation.ts | 27 ++- src/test/node/interactiveCore.test.ts | 12 + src/test/node/interactiveWebR.test.ts | 144 ++++++++++++ src/test/suite/interactiveEditor.test.ts | 137 ++++++++++- src/webr/console.ts | 279 +++++++++++++++++++++++ src/webr/consoleRunner.ts | 103 +++++++++ website/docs/features/r-interactive.md | 25 +- 12 files changed, 959 insertions(+), 62 deletions(-) create mode 100644 src/interactive/backends/webr.ts create mode 100644 src/test/node/interactiveWebR.test.ts create mode 100644 src/webr/console.ts create mode 100644 src/webr/consoleRunner.ts diff --git a/src/interactive/README.md b/src/interactive/README.md index 29d0809ea..2b297875c 100644 --- a/src/interactive/README.md +++ b/src/interactive/README.md @@ -27,14 +27,21 @@ the input changes, the session is replaced, or the manager is disposed. Paste keeps native insertion behavior and separate undo steps for formatting and insertion. -## Current backend - -The shipped `sess` backend uses arf with pure R sess helpers: +## Runtime backends | Public provider | Backend | Frontend | Ownership | | --- | --- | --- | --- | | `arf` | `sess` | arf headless | Managed | | `arf-existing` | `sess` | arf | Adopted | +| `webr` | `webr` | webR Wasm worker | Managed | + +The webR provider starts a console in the agent and mounts the selected host directory +at `/project`. The shared console stages complete submissions in the Wasm filesystem +and tags each one with its execution outcome. A subsequent REPL prompt completes the +cell after delayed output has arrived. Nested prompts use the ordinary editor input +flow. The agent journals static PNGs, so the editor can reconnect to a running session +and replay its plots. [webR backend](backends/webr.ts) · [Console](../webr/console.ts) + [SessBackend](backends/sessBackend.ts) owns readiness, metadata, capabilities, and ordered output. [SessBridge](backends/sessBridge.ts) owns authenticated sess @@ -125,7 +132,7 @@ and the captured response. There is no subscription for arbitrary terminal conso output. Terminal task notifications and rich viewers still work. Disposal restores sess hooks without changing frontend console callbacks or killing adopted R. -Both providers report notebook stdin/debugger support as unavailable: arf IPC +Both arf providers report notebook stdin/debugger support as unavailable: arf IPC `user_input` submits code, rather than answering nested R prompts. Use ordinary R terminals for `readline`, `scan`, and debugger interaction. arf IPC is experimental; the integration requires arf 0.7.2-rc.1 or later and is tested with diff --git a/src/interactive/backendRegistry.ts b/src/interactive/backendRegistry.ts index 0e213cc6f..a6e4714cc 100644 --- a/src/interactive/backendRegistry.ts +++ b/src/interactive/backendRegistry.ts @@ -1,3 +1,5 @@ +import * as path from 'node:path'; +import { prepareNodeWebR } from '../webr/nodeRuntime'; import { AgentConfig, AgentSettings, @@ -7,6 +9,7 @@ import { } from './protocol'; import { SessionBackend } from './backend'; import { SessBackend, SessOptions } from './backends/sessBackend'; +import { WebRBackend } from './backends/webr'; import { installAgentBundle } from './launcher'; import { installSessRuntime } from './backends/sessPreparation'; import { resolveArfExecutable } from './arfExecutable'; @@ -77,6 +80,22 @@ function sessOptions(descriptor: BackendDescriptor, prepared = true): SessOption } const definitions: Readonly> = { + webr: { + preflight(descriptor) { + return descriptor; + }, + async prepare(_descriptor, context) { + const baseUrl = await prepareNodeWebR(context.root); + return { kind: 'webr', options: { baseUrl } }; + }, + create(descriptor, settings) { + const baseUrl = descriptor.options.baseUrl; + if (typeof baseUrl !== 'string' || !path.isAbsolute(baseUrl)) { + throw new Error('Missing local webR runtime.'); + } + return new WebRBackend(settings, baseUrl); + }, + }, sess: { preflight(descriptor, settings) { const options = sessOptions(descriptor, false); diff --git a/src/interactive/backends/webr.ts b/src/interactive/backends/webr.ts new file mode 100644 index 000000000..67011e709 --- /dev/null +++ b/src/interactive/backends/webr.ts @@ -0,0 +1,191 @@ +import { WebRConsole, WebRConsoleEvent } from '../../webr/console'; +import { BackendEvent, DispatchNotSentError, SessionBackend } from '../backend'; +import type { AgentSettings, Submission } from '../protocol'; + +/** An R runtime managed by the session agent's Node process. */ +export class WebRBackend implements SessionBackend { + readonly ownership = 'managed' as const; + readonly capabilities = { + streaming: true, + stdin: true, + debugger: false, + tables: false, + html: false, + inspection: false, + inspectionDeadline: false, + interrupt: true, + jgd: false, + plotResize: false, + restart: true, + }; + private readonly listeners = new Set<(event: BackendEvent) => void>(); + private console?: WebRConsole; + private current?: string; + private inputId = 0; + private stopped = false; + + constructor( + private readonly settings: AgentSettings, + private readonly baseUrl: string, + ) {} + + onEvent(listener: (event: BackendEvent) => void): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + + private emit(event: BackendEvent): void { + for (const listener of this.listeners) { + listener(event); + } + } + + async start(): Promise { + const { ChannelType, WebR } = await import('webr'); + const runtime = new WebR({ + baseUrl: this.baseUrl, + channelType: ChannelType.SharedArrayBuffer, + interactive: true, + }); + const console = new WebRConsole( + runtime, + (event) => this.receive(event), + true, + (error) => { + if (error) { + this.emit({ type: 'error', message: error.message }); + } + this.exit(); + }, + ); + this.console = console; + try { + await console.start(); + await runtime.FS.mkdir('/project'); + await runtime.FS.mount('NODEFS', { root: this.settings.directory }, '/project'); + await runtime.evalRVoid('base::setwd("/project")'); + const rVersion = await runtime.evalRString('R.version.string'); + if (!this.stopped) { + this.emit({ + type: 'ready', + capabilities: this.capabilities, + metadata: { rVersion }, + }); + } + } catch (error) { + console.close(); + throw error; + } + } + + private receive(event: WebRConsoleEvent): void { + if (this.stopped) { + return; + } + const executionId = this.current; + switch (event.type) { + case 'started': + case 'stream': + this.emit({ ...event, executionId }); + break; + case 'input': + this.emit({ + type: 'input', + executionId, + data: { inputId: ++this.inputId, prompt: event.prompt }, + }); + break; + case 'plot': + this.emit({ + type: 'display', + executionId, + data: { + kind: 'image', + mime: 'image/png', + data: Buffer.from(event.png).toString('base64'), + }, + }); + break; + } + } + + dispatch(submission: Submission, options?: { signal?: AbortSignal }): Promise { + const console = this.console; + if (this.stopped || !console) { + return Promise.reject(new DispatchNotSentError('webR session is closed.')); + } + if (this.current) { + return Promise.reject( + new DispatchNotSentError('webR is already evaluating a submission.'), + ); + } + this.current = submission.id; + return new Promise((resolve, reject) => { + let submitted = false; + void console + .execute(submission.code, options?.signal, () => { + submitted = true; + resolve(); + }) + .then( + (state) => { + this.current = undefined; + if (!this.stopped) { + this.emit({ type: 'finished', executionId: submission.id, state }); + } + }, + (error: unknown) => { + this.current = undefined; + if (!submitted) { + reject(new DispatchNotSentError(String(error))); + } else if (!this.stopped) { + this.emit({ + type: 'unavailable', + executionId: submission.id, + message: String(error), + }); + } + }, + ); + }); + } + + inspect(): Promise { + return Promise.reject(new Error('Object inspection is unavailable for webR Interactive.')); + } + + replyInput(reply: { value: string }): Promise { + return Promise.resolve().then(() => { + if (!this.console) { + throw new Error('webR session is closed.'); + } + this.console.replyInput(reply.value); + }); + } + + replyClientRequest(): Promise { + return Promise.reject(new Error('webR has no pending editor request.')); + } + + async interrupt(): Promise { + await this.console?.interrupt(); + } + + private exit(): void { + if (!this.stopped) { + this.stopped = true; + this.emit({ type: 'exit' }); + } + } + + stop(): Promise { + this.console?.close(); + this.exit(); + return Promise.resolve(); + } + + async dispose(): Promise { + this.listeners.clear(); + await this.stop(); + } +} diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 2532d1942..cdc70ec20 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -63,7 +63,7 @@ import { queryTablePage } from './tableQuery'; import { tableColumnAlignment, tableDisplayValue, tableSnapshotSummary } from './tableFormatting'; import { HistoryPage, searchHistory } from './history'; import { readExecutionRecordsAsync, readPreviousJournalAsync } from './journal'; -import { sessionAge, sessionPresentation } from './sessionPresentation'; +import { sessionAge, sessionPresentation, sessionProcessLabel } from './sessionPresentation'; import { STOP_REQUEST_TIMEOUT_MS, runningSessions, @@ -611,7 +611,9 @@ export class InteractiveManager ? 'R session disconnected. Reconnecting to its workspace…' : view.client.manifest.status === 'starting' ? 'R is starting…' - : undefined; + : view.client.manifest.capabilities.inspection === false + ? 'Workspace inspection is unavailable for this session provider.' + : undefined; if ( view.target.label !== view.client.manifest.label || view.target.workspaceUnavailable !== unavailable @@ -1157,26 +1159,30 @@ export class InteractiveManager const adopt = adoptable?.session; const folder = this.sessionFolder(resource); const directory = adopt?.cwd ?? defaultSessionDirectory(folder?.fsPath); - const rPath = await util.getRpath(false, resource); - if (!rPath) { - throw new Error('Configure an R executable before starting Interactive'); - } const arfCommand = this.arfCommand(folder ?? resource); // An adopted session keeps the listing that found it, which finds the // session again if its IPC restarts at another socket path, even if // another folder has become active since. const listing = adoptable?.listing; let arfPath = listing ? listing.command : resolveArfExecutable(arfCommand, directory); + const webR = { + label: 'webR', + detail: 'Run R in WebAssembly using the project directory and a separate package library.', + value: 'webr' as const, + }; const provider = adopt ? 'arf-existing' - : await vscode.window.showQuickPick( + : await vscode.window.showQuickPick< + vscode.QuickPickItem & { value: 'arf' | 'webr' | 'configure' } + >( arfPath - ? [{ label: 'arf', detail: arfPath, value: 'arf' as const }] + ? [{ label: 'arf', detail: arfPath, value: 'arf' as const }, webR] : [ + webR, { label: '$(gear) Configure arf…', - description: 'Required for Interactive · executable unavailable', - detail: `Install arf on this host and set its path. Ordinary R terminals remain available. Checked: ${arfCommand}`, + description: 'Native R session', + detail: `Install arf on this host and set its path. Checked: ${arfCommand}`, value: 'configure' as const, }, ], @@ -1190,6 +1196,10 @@ export class InteractiveManager await this.configureArf(); return; } + const rPath = kind === 'webr' ? undefined : await util.getRpath(false, resource); + if (kind !== 'webr' && !rPath) { + return; + } const label = await vscode.window.showInputBox({ title: 'Session name', value: adopt ? `arf ${adopt.pid}` : path.basename(directory), @@ -1225,18 +1235,25 @@ export class InteractiveManager label, directory, storage: path.join(this.root, identity.id), - rPath, provider: kind, - arfPath, - arfEndpoint: adopt?.socket_path, - arfSessionId: adopt?.session_id, - arfPid: adopt?.pid, - arfDiscoveryDirectory: listing?.directory, - arfRegistryEnvironment: listing?.registry, + ...(kind === 'webr' + ? { backend: { kind, options: {} } } + : { + rPath, + arfPath, + arfEndpoint: adopt?.socket_path, + arfSessionId: adopt?.session_id, + arfPid: adopt?.pid, + arfDiscoveryDirectory: listing?.directory, + arfRegistryEnvironment: listing?.registry, + plotBackend: util + .config() + .get( + 'interactive.plotBackend', + 'auto', + ), + }), supervision, - plotBackend: util - .config() - .get('interactive.plotBackend', 'auto'), historyLimit: util.config().get('interactive.historyLimit', 100), ...this.retentionLimits(), }; @@ -1341,7 +1358,7 @@ export class InteractiveManager void Promise.resolve( vscode.window.showWarningMessage( `Cannot ${restarting ? 'restart' : 'start'} Headless arf: “${command}” was not found or is not executable on this host. ` + - 'Install arf or set r.interactive.arfPath to its executable. Plain R sessions do not require arf.' + + 'Install arf or set r.interactive.arfPath to its executable.' + (restarting ? ' The current R session has not been stopped.' : ''), 'Configure arf', ), @@ -1422,6 +1439,7 @@ export class InteractiveManager description: `${arf.session.r_version ?? ''} · ${arf.session.cwd ?? ''}`, arf, })), + { label: '$(add) New persistent R session', create: true }, ...(discovery.available ? [] : [ @@ -1432,7 +1450,6 @@ export class InteractiveManager configureArf: true, }, ]), - { label: '$(add) New persistent R session', create: true }, ]; } @@ -1485,7 +1502,7 @@ export class InteractiveManager private sessionChoiceDescription(manifest: SessionManifest): string { const age = sessionAge(manifest); - return `${manifest.status} · ${manifest.provider} · PID ${manifest.rPid ?? 'starting'}${age ? ` · ${age}` : ''}`; + return `${manifest.status} · ${manifest.provider} · ${sessionProcessLabel(manifest)}${age ? ` · ${age}` : ''}`; } private async pick(): Promise { @@ -3239,7 +3256,7 @@ export class InteractiveManager targets .map( (manifest) => - `${manifest.label} — PID ${manifest.rPid ?? 'starting'} · ${manifest.id.slice(0, 8)}\n${manifest.directory}`, + `${manifest.label} — ${sessionProcessLabel(manifest)} · ${manifest.id.slice(0, 8)}\n${manifest.directory}`, ) .join('\n\n'), ...(targets.some( @@ -3286,7 +3303,7 @@ export class InteractiveManager stopped.add(`${manifest.id}:${manifest.generation}`); } else { failures.push( - `${manifest.label} (PID ${manifest.rPid ?? 'starting'}): ${String(result.reason)}`, + `${manifest.label} (${sessionProcessLabel(manifest)}): ${String(result.reason)}`, ); } }); diff --git a/src/interactive/protocol.ts b/src/interactive/protocol.ts index 51ee4be17..8bddb5310 100644 --- a/src/interactive/protocol.ts +++ b/src/interactive/protocol.ts @@ -4,7 +4,7 @@ export const MAX_MESSAGE_BYTES = 4 * 1024 * 1024; export const MAX_CODE_BYTES = 1024 * 1024; export const DEFAULT_MAX_ASSET_BYTES = 1024 * 1024 * 1024; -export type ProviderKind = 'r' | 'arf' | 'arf-existing'; +export type ProviderKind = 'r' | 'arf' | 'arf-existing' | 'webr'; export type ExecutionState = | 'queued' | 'running' diff --git a/src/interactive/sessionPresentation.ts b/src/interactive/sessionPresentation.ts index 4315dd364..2f8bbf927 100644 --- a/src/interactive/sessionPresentation.ts +++ b/src/interactive/sessionPresentation.ts @@ -16,6 +16,13 @@ export function sessionAge(manifest: SessionManifest, now = Date.now()): string : `${Math.floor(minutes / 1440)}d`; } +/** The webR worker runs inside the session agent and has no separate process ID. */ +export function sessionProcessLabel(manifest: SessionManifest, pending = 'starting'): string { + return manifest.provider === 'webr' + ? `Agent PID ${manifest.agentPid}` + : `PID ${manifest.rPid ?? pending}`; +} + /** Public session details; never include connection credentials. */ export function sessionPresentation( manifest: SessionManifest, @@ -33,12 +40,12 @@ export function sessionPresentation( : manifest.status === 'input' ? 'waiting for input' : manifest.status; - const provider = - manifest.provider === 'r' - ? 'plain' - : manifest.provider === 'arf-existing' - ? 'arf (attached)' - : 'arf'; + const provider = { + r: { short: 'plain', name: 'Plain R' }, + arf: { short: 'arf', name: 'Headless arf' }, + 'arf-existing': { short: 'arf (attached)', name: 'Attached arf' }, + webr: { short: 'webR', name: 'webR' }, + }[manifest.provider]; const version = manifest.rVersion?.match(/^R version (\S+)/)?.[1]; const supervision = manifest.supervision === 'detached' ? 'Independent process' : manifest.supervision; @@ -48,7 +55,7 @@ export function sessionPresentation( label: `R: ${manifest.label} · ${state}`, // Description is inline (and doubles as the native button tooltip); detail // gets a second picker row. Neither supports arbitrary multiline content. - description: `${version ? `R ${version}` : 'R'} · ${provider} · PID ${manifest.rPid ?? 'pending'}${age ? ` · ${age}` : ''}${connected && !control ? ' · observing' : ''}`, + description: `${version ? `R ${version}` : 'R'} · ${provider.short} · ${sessionProcessLabel(manifest, 'pending')}${age ? ` · ${age}` : ''}${connected && !control ? ' · observing' : ''}`, detail: `${directory} · ${manifest.host} · ${supervision}`, // The full details remain available in the status bar hover and Session Details. tooltip: [ @@ -61,9 +68,11 @@ export function sessionPresentation( ? `Connected · ${control ? 'controlling' : 'observing'}` : 'Disconnected' }`, - `Provider: ${manifest.provider === 'r' ? 'Plain R' : manifest.provider === 'arf-existing' ? 'Attached arf' : 'Headless arf'}`, + `Provider: ${provider.name}`, manifest.rVersion ?? 'R version: pending', - `PID: ${manifest.rPid ?? 'pending'}`, + manifest.provider === 'webr' + ? `Agent PID: ${manifest.agentPid}` + : `PID: ${manifest.rPid ?? 'pending'}`, ...(age ? [`${manifest.status === 'exited' ? 'Lifetime' : 'Session age'}: ${age}`] : []), diff --git a/src/test/node/interactiveCore.test.ts b/src/test/node/interactiveCore.test.ts index 7a03e7ed5..a922ab1ef 100644 --- a/src/test/node/interactiveCore.test.ts +++ b/src/test/node/interactiveCore.test.ts @@ -92,6 +92,18 @@ suite('Interactive session button', () => { ); }); + test('identifies the webR agent without reporting a native R process', () => { + const presentation = sessionPresentation( + { ...manifest, provider: 'webr', rPid: undefined, rPath: undefined, agentPid: 456 }, + true, + true, + ); + assert.match(presentation.description, /webR · Agent PID 456/); + assert.match(presentation.tooltip, /Provider: webR/); + assert.match(presentation.tooltip, /Agent PID: 456/); + assert.doesNotMatch(presentation.tooltip, /PID: pending|R executable:/); + }); + test('does not report pending process metadata as a starting session', () => { const presentation = sessionPresentation( { ...manifest, status: 'exited', rPid: undefined, rVersion: undefined }, diff --git a/src/test/node/interactiveWebR.test.ts b/src/test/node/interactiveWebR.test.ts new file mode 100644 index 000000000..8d0d1b139 --- /dev/null +++ b/src/test/node/interactiveWebR.test.ts @@ -0,0 +1,144 @@ +import * as assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { SessionAgent } from '../../interactive/agentMain'; +import { prepareNodeWebR } from '../../webr/nodeRuntime'; +import { AgentClient } from '../../interactive/client'; +import type { AgentConfig, SessionEvent, SessionManifest } from '../../interactive/protocol'; + +suite('R Interactive webR provider', function () { + this.timeout(60000); + let root: string; + let project: string; + let agent: SessionAgent; + let client: AgentClient; + let manifest: SessionManifest; + let events: SessionEvent[]; + + setup(async () => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-r-webr-')); + project = path.join(root, 'my project'); + fs.mkdirSync(project); + const baseUrl = await prepareNodeWebR(root, (directory) => + fs.promises.cp(path.dirname(require.resolve('webr')), directory, { recursive: true }), + ); + const config: AgentConfig = { + id: randomUUID(), + generation: randomUUID(), + label: 'webR test', + directory: project, + storage: path.join(root, 'session'), + provider: 'webr', + supervision: 'test', + historyLimit: 100, + maxOutputBytes: 1024 * 1024, + maxJournalBytes: 4 * 1024 * 1024, + // The npm distribution includes real Wasm assets for an offline test. + backend: { + kind: 'webr', + options: { baseUrl }, + }, + }; + agent = new SessionAgent(config); + manifest = await agent.start(); + await connect(); + }); + + teardown(async () => { + client?.close(); + await agent?.close(); + fs.rmSync(root, { recursive: true, force: true }); + }); + + async function connect(): Promise { + events = []; + client = new AgentClient(manifest); + client.on('event', (event: SessionEvent) => events.push(event)); + await client.connect({ claim: true }); + await client.subscribe(0); + } + async function submit(code: string): Promise { + const id = randomUUID(); + await client.request('submit', { submission: { id, code } }); + return id; + } + async function wait(id: string, type: string): Promise { + for (let i = 0; i < 500; i++) { + const event = events.find((item) => item.executionId === id && item.type === type); + if (event) { + return event; + } + await delay(20); + } + throw new Error('Missing ' + type + ' for ' + id + ': ' + JSON.stringify(events.slice(-6))); + } + function output(id: string): string { + return events + .filter((event) => event.type === 'stream' && event.executionId === id) + .map((e) => e.data.text) + .join(''); + } + + test('mounts a project and retains R objects, files and PNG output across an editor reconnect', async () => { + assert.equal(manifest.backend, 'webr'); + assert.equal(manifest.rPath, undefined); + assert.equal(manifest.rPid, undefined); + assert.match(manifest.rVersion!, /^R version /); + fs.writeFileSync(path.join(project, 'data.csv'), 'x,y\n1,3\n2,5\n3,7\n'); + fs.writeFileSync(path.join(project, 'fit.R'), 'fit <- lm(y ~ x, read.csv("data.csv"))\n'); + const first = await submit( + 'source("fit.R")\nplot(1:3)\nplot(3:1)\nwarning("cell warning")', + ); + assert.equal((await wait(first, 'finished')).data.state, 'success'); + assert.match(output(first), /cell warning/); + const plots = events.filter( + (event) => event.executionId === first && event.type === 'display', + ); + assert.equal(plots.length, 2); + for (const plot of plots) { + assert.equal(plot.data.mime, 'image/png'); + assert.equal(typeof plot.data.asset, 'string'); + } + client.close(); + await connect(); + const snapshot = await client.snapshot(); + assert.ok(snapshot.events.some((e) => e.executionId === first && e.type === 'display')); + const next = await submit( + 'writeLines(as.character(unname(coef(fit)[2])), "slope.txt")\ncoef(fit)[2]', + ); + assert.equal((await wait(next, 'finished')).data.state, 'success'); + assert.equal(fs.readFileSync(path.join(project, 'slope.txt'), 'utf8').trim(), '2'); + }); + + test('reports cell errors, answers nested prompts, and interrupts a busy or waiting cell without losing R state', async () => { + const bad = await submit('stop("sample error")'); + assert.equal((await wait(bad, 'finished')).data.state, 'error'); + assert.match(output(bad), /sample error/); + const question = await submit('word <- readline("> "); cat(word)'); + const prompt = await wait(question, 'input'); + await client.request('input', { + id: prompt.data.inputId, + executionId: question, + value: 'kept', + }); + assert.equal((await wait(question, 'finished')).data.state, 'success'); + assert.match(output(question), /kept/); + const busy = await submit('repeat { }'); + await wait(busy, 'started'); + await client.request('interrupt'); + assert.equal((await wait(busy, 'finished')).data.state, 'interrupted'); + const waiting = await submit('readline("another prompt")'); + await wait(waiting, 'input'); + await client.request('interrupt'); + assert.equal((await wait(waiting, 'finished')).data.state, 'interrupted'); + const next = await submit('cat(word)'); + assert.equal((await wait(next, 'finished')).data.state, 'success'); + assert.match(output(next), /kept/); + const quitting = await submit('q("no", runLast=FALSE)'); + await wait(quitting, 'finished'); + assert.equal((await client.snapshot()).manifest.status, 'exited'); + }); +}); diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index d723b5168..57d717a47 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -24,6 +24,7 @@ import type { NotebookOutputState } from '../../interactive/notebookOutput'; import { AssetStorageStats, exportedAssetName, readAsset } from '../../interactive/assets'; import { resolveExecutable } from '../../interactive/executable'; import { shellQuote } from '../../interactive/launcher'; +import { prepareNodeWebR } from '../../webr/nodeRuntime'; import { listenLocal, localEndpoint } from '../../interactive/transport'; import type { InteractiveManager } from '../../interactive/manager'; import type { GlobalEnvItem, WorkspaceDataProvider } from '../../workspaceViewer'; @@ -725,10 +726,16 @@ suite('Interactive VS Code integration', function () { } }); - test('missing arf offers setup, with no failed session or runtime installation', async () => { + test('missing native R and arf still offers webR and the native setup action', async () => { const config = vscode.workspace.getConfiguration('r'); const previous = config.inspect('interactive.arfPath')?.globalValue; const missing = path.join(root, 'missing-arf'); + const previousR = config.inspect('executablePath')?.globalValue; + await config.update( + 'executablePath', + path.join(root, 'missing-R'), + vscode.ConfigurationTarget.Global, + ); await config.update('interactive.arfPath', missing, vscode.ConfigurationTarget.Global); const entries = fs.readdirSync(root); const picker = sinon.stub(vscode.window, 'showQuickPick').resolves(undefined); @@ -743,18 +750,22 @@ suite('Interactive VS Code integration', function () { })[]; assert.deepStrictEqual( choices.map((item) => item.value), - ['configure'], + ['webr', 'configure'], ); - assert.ok(choices[0].detail?.includes(missing)); - picker.resolves(choices[0]); + assert.ok(choices[1].detail?.includes(missing)); + picker.resolves(choices[1]); await vscode.commands.executeCommand('r.interactive.new'); sinon.assert.calledOnce( commands.withArgs('workbench.action.openSettings', 'r.interactive.arfPath'), ); sinon.assert.notCalled(input); + picker.resolves(choices[0]); + await vscode.commands.executeCommand('r.interactive.new'); + sinon.assert.calledOnce(input); sinon.assert.notCalled(errors); assert.deepStrictEqual(fs.readdirSync(root), entries); } finally { + await config.update('executablePath', previousR, vscode.ConfigurationTarget.Global); commands.restore(); picker.restore(); input.restore(); @@ -802,9 +813,9 @@ suite('Interactive VS Code integration', function () { })[]; assert.deepStrictEqual( choices.map((item) => item.value), - ['configure'], + ['webr', 'configure'], ); - assert.ok(choices[0].detail?.includes(missing), choices[0].detail); + assert.ok(choices[1].detail?.includes(missing), choices[1].detail); } finally { picker.restore(); stubs.forEach((stub) => stub.restore()); @@ -879,9 +890,9 @@ suite('Interactive VS Code integration', function () { })[]; assert.deepStrictEqual( providers.map((item) => item.value), - ['configure'], + ['webr', 'configure'], ); - assert.ok(providers[0].detail?.includes(missing[0]), providers[0].detail); + assert.ok(providers[1].detail?.includes(missing[0]), providers[1].detail); } finally { sandbox.restore(); folders.forEach((folder) => @@ -916,11 +927,11 @@ suite('Interactive VS Code integration', function () { })[]; assert.deepStrictEqual( choices.map((item) => item.value), - ['arf'], + ['arf', 'webr'], ); assert.deepStrictEqual( choices.map((item) => item.label), - ['arf'], + ['arf', 'webR'], ); assert.ok(choices.every((item) => item.description === undefined)); assert.strictEqual(choices[0].detail, executable); @@ -994,6 +1005,112 @@ suite('Interactive VS Code integration', function () { ); } }); + test('the webR picker runs a selection and renders a PNG without native R or arf', async () => { + const config = vscode.workspace.getConfiguration('r'); + const overrides = { + executablePath: path.join(root, 'missing-native-R'), + 'interactive.arfPath': path.join(root, 'missing-native-arf'), + 'interactive.supervision': 'detached', + }; + const previous = Object.keys(overrides).map( + (key) => [key, config.inspect(key)?.globalValue] as const, + ); + // Seed the same versioned cache the detached agent uses, using the installed npm assets. + await prepareNodeWebR(root, (directory) => + fs.promises.cp(path.dirname(require.resolve('webr')), directory, { recursive: true }), + ); + + const label = 'webR picker test'; + const sandbox = sinon.createSandbox(); + const folder = { uri: vscode.Uri.file(root), name: label, index: 0 }; + sandbox.stub(vscode.workspace, 'workspaceFolders').value([folder]); + const errors = sandbox.stub(vscode.window, 'showErrorMessage').resolves(undefined); + sandbox.stub(vscode.window, 'showQuickPick').callsFake((async (items: unknown) => { + const choices = (await items) as (vscode.QuickPickItem & { value?: string })[]; + const selected = choices.find((item) => item.value === 'webr'); + assert.ok(selected, 'The picker should offer webR'); + return selected; + }) as never); + sandbox.stub(vscode.window, 'showInputBox').resolves(label); + let manifest: SessionManifest | undefined; + try { + for (const [key, value] of Object.entries(overrides)) { + await config.update(key, value, vscode.ConfigurationTarget.Global); + } + await vscode.commands.executeCommand('r.interactive.new'); + const manager = interactiveManager(); + manager.refresh(); + manifest = manager.getChildren().find((item) => item.label === label); + assert.ok(manifest, JSON.stringify(errors.args)); + assert.strictEqual(manifest.provider, 'webr'); + assert.strictEqual(manifest.supervision, 'detached'); + const notebook = vscode.workspace.notebookDocuments.find( + (doc) => doc.metadata.rSessionId === manifest?.id, + ); + assert.ok(notebook, JSON.stringify(errors.args)); + + const code = 'value <- 6 * 7\ncat("webR result", value, "\\n")\nplot(1:3)'; + const document = await vscode.workspace.openTextDocument({ + content: code, + language: 'r', + }); + const editor = await vscode.window.showTextDocument(document, vscode.ViewColumn.One); + editor.selection = new vscode.Selection( + document.positionAt(0), + document.positionAt(code.length), + ); + await vscode.commands.executeCommand('r.runSelection'); + await until(() => + notebook + .getCells() + .some( + (cell) => + cell.document.getText().includes('plot(1:3)') && + cell.executionSummary?.success === true, + ), + ); + const cell = notebook + .getCells() + .find((item) => item.document.getText().includes('plot(1:3)')); + assert.ok(cell); + const items = cell.outputs.flatMap((output) => output.items); + assert.ok( + items.some( + (item) => + item.mime.includes('stdout') && + Buffer.from(item.data).toString().includes('webR result 42'), + ), + ); + const png = items.find((item) => item.mime === 'image/png'); + const rich = items.find((item) => item.mime === DISPLAY_MIME); + assert.ok(png && rich); + const plot = JSON.parse(Buffer.from(rich.data).toString()) as { + kind: string; + imageData: string; + }; + assert.strictEqual(plot.kind, 'plot'); + assert.strictEqual(plot.imageData, Buffer.from(png.data).toString('base64')); + assert.strictEqual( + Buffer.from(png.data).subarray(0, 8).toString('hex'), + '89504e470d0a1a0a', + ); + } finally { + try { + if (manifest) { + sandbox + .stub(vscode.window, 'showWarningMessage') + .resolves('Stop Session' as never); + await vscode.commands.executeCommand('r.interactive.stop', manifest); + await vscode.commands.executeCommand('r.interactive.detach', manifest); + } + } finally { + sandbox.restore(); + for (const [key, value] of previous) { + await config.update(key, value, vscode.ConfigurationTarget.Global); + } + } + } + }); test('missing explicit tmux reports a recovery setting before installing or creating a session', async function () { if (process.platform === 'win32') { this.skip(); diff --git a/src/webr/console.ts b/src/webr/console.ts new file mode 100644 index 000000000..99a78aa2e --- /dev/null +++ b/src/webr/console.ts @@ -0,0 +1,279 @@ +import type { WebR } from 'webr'; +import { consoleRunner } from './consoleRunner'; + +export type WebRConsoleResult = 'success' | 'error' | 'interrupted'; + +export type WebRConsoleEvent = + | { type: 'stream'; channel: 'stdout' | 'stderr'; text: string } + | { type: 'started' } + | { type: 'input'; prompt: string } + | { type: 'plot'; png: Uint8Array }; + +interface Cell { + id: number; + directory: string; + phase: 'preparing' | 'submitted' | 'running' | 'input' | 'finishing' | 'fence'; + interrupted: boolean; + outcome?: WebRConsoleResult; + resolve(result: WebRConsoleResult): void; + reject(error: Error): void; +} + +const encoder = new TextEncoder(); +const root = '/tmp/vscode-r-interactive'; + +/** One live R console. Each submitted program has its own source and graphics directory. */ +export class WebRConsole { + private active?: Cell; + private sequence = 0; + private closed = false; + + constructor( + private readonly runtime: WebR, + private readonly onEvent: (event: WebRConsoleEvent) => void, + private readonly supportsInterrupt: boolean, + private readonly onExit?: (error?: Error) => void, + ) {} + + async start(): Promise { + await this.runtime.init(); + // Consume the startup banner and the initial prompt before accepting a cell. + for (;;) { + const message = await this.runtime.read(); + if (message.type === 'closed') { + throw new Error('webR exited during startup.'); + } + if (message.type === 'prompt') { + break; + } + } + await this.runtime.FS.mkdir(root); + await this.runtime.evalRVoid(consoleRunner); + void this.pump().catch((error) => + this.end(error instanceof Error ? error : new Error(String(error))), + ); + } + + execute( + code: string, + signal?: AbortSignal, + onSubmitted?: () => void, + ): Promise { + if (this.closed || this.active) { + return Promise.reject( + new Error(this.closed ? 'webR session is closed.' : 'webR is busy.'), + ); + } + const id = ++this.sequence; + return new Promise((resolve, reject) => { + const cell: Cell = { + id, + directory: root + '/' + id, + phase: 'preparing', + interrupted: false, + resolve, + reject, + }; + this.active = cell; + void this.submit(cell, code, signal, onSubmitted).catch((error) => { + if (this.active === cell) { + this.active = undefined; + reject(error); + } + }); + }); + } + + private async submit( + cell: Cell, + code: string, + signal?: AbortSignal, + onSubmitted?: () => void, + ): Promise { + const directory = JSON.stringify(cell.directory); + await this.runtime.FS.mkdir(cell.directory); + try { + await this.runtime.FS.writeFile(cell.directory + '/cell.R', encoder.encode(code)); + if (signal?.aborted || cell !== this.active) { + throw new Error('webR submission cancelled before dispatch.'); + } + if (cell.interrupted) { + await this.runtime.FS.writeFile(cell.directory + '/cancel', new Uint8Array()); + } + if (signal?.aborted || cell !== this.active) { + throw new Error('webR submission cancelled before dispatch.'); + } + this.runtime.writeConsole( + 'base::getOption("vscodeR.webR.execute")(' + directory + ', ' + cell.id + 'L)', + ); + cell.phase = 'submitted'; + onSubmitted?.(); + } catch (error) { + if (!this.closed) { + await this.runtime + .evalRVoid('base::unlink(' + directory + ', recursive = TRUE)') + .catch(() => undefined); + } + throw error; + } + } + + replyInput(value: string): void { + const cell = this.active; + if (!cell || cell.phase !== 'input' || cell.interrupted) { + throw new Error('webR is not waiting for input.'); + } + cell.phase = 'running'; + this.runtime.writeConsole(value); + } + + async interrupt(): Promise { + const cell = this.active; + if (!cell || cell.outcome || cell.interrupted) { + return; + } + if (!this.supportsInterrupt) { + throw new Error('This webR communication channel does not support interruption.'); + } + cell.interrupted = true; + if (cell.phase === 'input') { + // The worker is waiting for ReadConsole. A reply releases that wait; the + // runner also sees cancellation before executing the next expression. + await this.cancelInput(cell); + } else if (cell.phase === 'running') { + this.runtime.interrupt(); + } + // An interrupt before the runner starts must not clear queued Wasm messages. + // The started event delivers it once R has installed the interrupt handler. + } + + private async cancelInput(cell: Cell): Promise { + await this.runtime.FS.writeFile(cell.directory + '/cancel', new Uint8Array()); + if (cell === this.active && cell.phase === 'input') { + cell.phase = 'running'; + this.runtime.interrupt(); + this.runtime.writeConsole(''); + } + } + + private async pump(): Promise { + while (!this.closed) { + const message = await this.runtime.read(); + if (this.closed) { + return; + } + const cell = this.active; + switch (message.type) { + case 'vscode-r-exit': + case 'closed': + this.end(); + return; + case 'stdout': + case 'stderr': + this.onEvent({ + type: 'stream', + channel: message.type, + text: String(message.data) + '\n', + }); + break; + case 'vscode-r-stream-fragment': { + const fragment = message.data as { channel?: unknown; text?: unknown } | null; + if ( + (fragment?.channel === 'stdout' || fragment?.channel === 'stderr') && + typeof fragment.text === 'string' + ) { + this.onEvent({ + type: 'stream', + channel: fragment.channel, + text: fragment.text, + }); + } + break; + } + case 'vscode-r-execution': { + const marker = message.data as { id?: unknown; state?: unknown } | null; + if (!cell || marker?.id !== cell.id) { + break; + } + if (marker.state === 'started' && cell.phase === 'submitted') { + cell.phase = 'running'; + if (cell.interrupted) { + this.runtime.interrupt(); + } + this.onEvent({ type: 'started' }); + } else if ( + marker.state === 'success' || + marker.state === 'error' || + marker.state === 'interrupted' + ) { + cell.outcome = marker.state; + } + break; + } + case 'prompt': + if (cell && cell.phase !== 'preparing') { + await this.prompt(cell, String(message.data)); + } + break; + } + } + } + + private async prompt(cell: Cell, prompt: string): Promise { + if (cell.outcome) { + if (cell.interrupted && cell.phase !== 'fence') { + // A late interrupt may still be pending when a fast cell finishes. + // Consume it before the next R call, including cleanup of this cell. + cell.phase = 'fence'; + this.runtime.writeConsole( + 'base::tryCatch(base::Sys.sleep(0), interrupt = function(e) NULL)', + ); + return; + } + cell.phase = 'finishing'; + // A warning may arrive after the outcome marker. At this prompt the + // preceding output is drained and the runner has closed its plots. + try { + const entries = await this.runtime.FS.lookupPath(cell.directory); + for (const file of Object.keys(entries.contents ?? {}).sort()) { + if (/^plot-\d+-\d+\.png$/.test(file)) { + const png = await this.runtime.FS.readFile(cell.directory + '/' + file); + this.onEvent({ type: 'plot', png }); + } + } + } finally { + await this.runtime.evalRVoid( + 'base::unlink(' + JSON.stringify(cell.directory) + ', recursive = TRUE)', + ); + } + this.active = undefined; + cell.resolve(cell.outcome); + } else if (cell.phase === 'submitted') { + throw new Error('webR returned to the console before acknowledging the submission.'); + } else { + cell.phase = 'input'; + if (cell.interrupted) { + await this.cancelInput(cell); + } else { + this.onEvent({ type: 'input', prompt }); + } + } + } + + private end(error?: Error): void { + if (this.closed) { + return; + } + this.close(error); + this.onExit?.(error); + } + + close(error = new Error('webR session closed during execution.')): void { + if (!this.closed) { + this.closed = true; + this.active?.reject(error); + this.active = undefined; + this.runtime.close(); + } + } +} diff --git a/src/webr/consoleRunner.ts b/src/webr/consoleRunner.ts new file mode 100644 index 000000000..eee14be0e --- /dev/null +++ b/src/webr/consoleRunner.ts @@ -0,0 +1,103 @@ +// The console host reads the typed outcome and all subsequent output through the +// next top-level prompt. R can print deferred warnings after the outcome. +export const consoleRunner = String.raw` +base::local({ + # Emscripten emits complete tty lines. Preserve an unterminated fragment + # before another channel writes or R asks for input. File sinks have their + # own streams and retain the regular R connection semantics. + webr::eval_js("(() => { + const runtime = globalThis.Module; + const streams = [runtime.FS.getStream(1), runtime.FS.getStream(2)]; + const decoder = new TextDecoder('utf-8', { ignoreBOM: true }); + const flush = (index) => { + const bytes = streams[index].tty?.output; + if (!bytes?.length) return; + const text = decoder.decode(Uint8Array.from(bytes)); + bytes.length = 0; + runtime.webr.channel.write({ type: 'vscode-r-stream-fragment', + data: { channel: index === 0 ? 'stdout' : 'stderr', text } }); + }; + for (const [index, stream] of streams.entries()) { + const ops = stream.stream_ops; + stream.stream_ops = { ...ops, write(...args) { + flush(1 - index); + return ops.write(...args); + } }; + } + const setPrompt = runtime.webr.setPrompt; + runtime.webr.setPrompt = (prompt) => { + flush(0); + flush(1); + return setPrompt(prompt); + }; + return null; + })()") + + default_device <- getOption("device") + notify <- function(id, state) { + webr::eval_js(sprintf( + "(globalThis.Module.webr.channel.write({type:'vscode-r-execution',data:{id:%.0f,state:'%s'}}),null)", + id, state + )) + invisible(NULL) + } + + execute <- function(directory, id) suspendInterrupts({ + cancel <- file.path(directory, "cancel") + devices <- character() + sequence <- 0L + capture_device <- function(width = 8, height = 6, pointsize = 12, bg = "white") { + sequence <<- sequence + 1L + filename <- file.path(directory, sprintf("plot-%06d-%%06d.png", sequence)) + grDevices::png(filename, width = width, height = height, units = "in", + res = 96, pointsize = pointsize, bg = bg) + devices[as.character(as.integer(grDevices::dev.cur()))] <<- filename + } + close_devices <- function() { + if (identical(getOption("device"), capture_device)) options(device = default_device) + for (number in names(devices)) { + slot <- as.integer(number) + # A user can close a capture device and reuse its number for + # their own file. The graphics engine records each PNG's path. + if (length(.Devices) >= slot && + identical(attr(.Devices[[slot]], "filepath", exact = TRUE), devices[[number]])) { + grDevices::dev.off(slot) + } + } + } + run <- function() { + if (file.exists(cancel)) return("interrupted") + if (identical(getOption("device"), default_device)) options(device = capture_device) + expressions <- parse(file = file.path(directory, "cell.R"), + keep.source = TRUE, encoding = "UTF-8") + for (expression in expressions) { + value <- withVisible(eval(expression, envir = .GlobalEnv)) + if (file.exists(cancel)) { + # Returning an empty console input releases a blocked + # readline(). Give R a chance to consume its interrupt. + Sys.sleep(0) + return("interrupted") + } + if (value$visible) print(value$value) + } + "success" + } + failed <- function(error) { + message("Error: ", conditionMessage(error)) + "error" + } + state <- tryCatch({ + notify(id, "started") + allowInterrupts(run()) + }, interrupt = function(e) "interrupted", error = failed) + tryCatch(close_devices(), error = function(e) { state <<- failed(e) }) + notify(id, state) + }) + # webR can leave the worker alive after R exits its main loop. Notify the + # owner when q() runs so it can settle the submission and release the worker. + reg.finalizer(.GlobalEnv, function(e) { + webr::eval_js("(globalThis.Module.webr.channel.write({type:'vscode-r-exit'}),null)") + }, onexit = TRUE) + options(vscodeR.webR.execute = execute) +}, envir = base::new.env(parent = base::baseenv())) +`; diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index d20b7164d..c05a71302 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -10,15 +10,14 @@ R Interactive was introduced in vscode-R 3.2.0 ([PR #1805](https://github.com/RE Use **VS Code 1.101.0 or newer**. R Interactive supports Linux, macOS, and Windows, including [connecting to an existing arf session](#connect-to-an-existing-arf-session). Existing R terminal workflows remain available. -For Remote SSH, install this extension **on the remote host**. R, its packages, optional executables, and session storage must be available on that host. For local use, the same requirements apply to your computer. +For Remote SSH, install this extension **on the remote host**. The session agent uses the extension host’s bundled Node.js runtime on that host. On desktop it uses VS Code’s Electron runtime in Node mode. A separate Node.js installation is optional. -The R host needs: +Choose **webR** to run R in WebAssembly with no native R or arf installation. Relative paths such as `source("helpers.R")` and `read.csv("data.csv")` use the session’s project directory. Writes to that directory are visible on the host. Install a WebAssembly build into the session with `webr::install("data.table")`, then use `library(data.table)` as usual. Additional packages live in the running webR session. Static plots appear in the transcript. Workspace inspection and the native graphics devices described below are available with arf. [webR package installation](https://docs.r-wasm.org/webr/latest/packages.html) -- R. The bundled sess package is pure R and needs no compiler; its missing Imports are installed from the configured R repository and may need build tools when installed from source. -- The session agent automatically uses the extension host's bundled runtime: VS Code's Electron runtime in Node mode on desktop, or VS Code Server's Node runtime remotely. A separate Node.js installation is optional. -- `tmux` is optional. On Linux, the default supervisor uses tmux when available and otherwise starts an independent detached process. `systemd --user` is another configurable option. -- R packages processx, later, jsonlite, and rstudioapi. Install languageserver for language features, jgd and systemfonts for jgd graphics, and htmlwidgets/htmltools for HTML output. Static plots use SVG when `svglite` is available and PNG otherwise. -- arf. Creating a new Interactive session requires an arf executable on the R host. Listing already-running arf sessions to connect to uses the arf CLI on the R host, found through `r.interactive.arfPath`; the connection itself then uses the session's socket. R Interactive requires arf 0.7.2-rc.1 or later. +Choose **arf** to use an installed R and its project libraries. On the R host, install: + +- Native R and arf 0.7.2-rc.1 or later. The arf CLI is also used to list running arf sessions for adoption. +- R packages processx, later, jsonlite, and rstudioapi. Install languageserver for native language features, jgd and systemfonts for jgd graphics, and htmlwidgets/htmltools for HTML output. Static plots use SVG when `svglite` is available and PNG otherwise. The bundled sess package is pure R. Installing missing packages from source may require build tools. For example, run in the R installation used on the server: @@ -35,9 +34,9 @@ The experimental `r.interactive.nodePath` setting provides an optional standalon Runtime availability and version (Node.js 18+) are checked before installation or restart, so a failed check leaves the current R process running. If an editor update removes the automatic runtime, reload VS Code to select its current executable. Reconnecting to an existing agent does not launch or replace its runtime; new and restarted sessions reread `r.interactive.nodePath`. -### R packages and project libraries +### Native R packages and project libraries -The extension installs its bundled pure R sess into a private, content-addressed library when starting an Interactive session. It does not replace your installed sess package. Missing Imports are installed from the configured R repository; no global repository settings are changed. Installation diagnostics appear in the **R Interactive** output channel. +The extension installs its bundled pure R sess into a private, content-addressed library when starting an arf Interactive session. It does not replace your installed sess package. Missing Imports are installed from the configured R repository; no global repository settings are changed. Installation diagnostics appear in the **R Interactive** output channel. That private library is used only to load the bridge; it is not added to your session's `.libPaths()` or `R_LIBS`. Package installation follows ordinary R behavior: `install.packages()` defaults to the first library in `.libPaths()`, usually your user library. Startup files can customize that order, and an explicit `lib=` still takes precedence. The extension does not force a user-library destination over a project library. @@ -62,7 +61,7 @@ Typical remote settings: Executable paths, storage location, supervision, graphics backend, and output/journal/asset size limits are excluded from VS Code Settings Sync by default because they depend on the R host. Execution target, table presentation, automatic reconnection, and history-length preferences can still sync. -Use the paths appropriate for your server. Linux `auto` prefers tmux when its executable is on the extension host's PATH. If tmux is missing or not executable, it uses a detached agent and records the fallback in the **R Interactive** output channel and agent log. Session Details shows **Independent process**. macOS and Windows `auto` also use a detached agent. Both plain R and managed arf support this fallback with the same Interactive features. +Use the paths appropriate for your server. Linux `auto` prefers tmux when its executable is on the extension host's PATH. If tmux is missing or not executable, it uses a detached agent and records the fallback in the **R Interactive** output channel and agent log. Session Details shows **Independent process**. macOS and Windows `auto` also use a detached agent. Both webR and managed arf use the same agent supervision. Selecting `tmux` or `systemd` explicitly requires `tmux` or `systemd-run` on the R host. Missing executables produce an actionable error before installing a runtime or stopping the current R process for restart. Install the selected supervisor or change `r.interactive.supervision` to `auto` or `detached`. New sessions and restarts use the current setting; merely reconnecting leaves the existing supervisor unchanged. If an installed supervisor fails to launch (for example, a systemd user service is unavailable), the error includes its diagnostics. The extension does not retry with another supervisor after a launch attempt, which could create duplicate R processes. @@ -70,7 +69,7 @@ Detached launch goes through a short-lived bootstrap so the agent leaves the edi ## Start a session -Run **R: New Persistent Interactive Session**, choose **arf**, and name the session. Each session opens its own Interactive window; select it in **R → Interactive Sessions** to return to it. Multiple sessions execute concurrently; each R process runs submitted cells serially. +Run **R: New Persistent Interactive Session**, choose **webR** or **arf**, and name the session. Each session opens its own Interactive window; select it in **R → Interactive Sessions** to return to it. Multiple sessions execute concurrently; each runtime runs its submitted cells serially. ### Connect to an existing arf session @@ -86,7 +85,7 @@ The agent itself runs under the separately selected supervisor (`tmux`, `systemd ### Configure managed arf sessions -The provider picker shows **R** and **arf**, each with its resolved executable path on a second line. **arf** appears only when `r.interactive.arfPath` resolves to an executable file on this host (the remote server with Remote SSH). Otherwise, **Configure arf…** opens its setting without creating a session. Install arf separately and configure its path, or choose **R** with the same persistence and multi-session controls. The setting accepts names on PATH, absolute or workspace-relative paths, `~/`, `${userHome}`, and `${workspaceFolder}`. Configured paths containing spaces do not need quotes. Changing the setting takes effect the next time the picker opens; shell aliases are not executables. +The provider picker shows **arf** with its executable path when `r.interactive.arfPath` resolves to an executable file on this host (the remote server with Remote SSH). Otherwise, **Configure arf…** opens its setting without creating a session. Choose **webR** to start an Interactive session while arf is unavailable. The setting accepts names on PATH, absolute or workspace-relative paths, `~/`, `${userHome}`, and `${workspaceFolder}`. Configured paths containing spaces do not need quotes. Changing the setting takes effect the next time the picker opens; shell aliases are not executables. The setting must name arf itself, or a script that replaces itself with arf using `exec` (for example, `exec arf "$@"`). A launcher that starts arf as another process and waits for it is not supported: the extension signals, and waits for the exit of, only the process it started. A managed session refuses such a launcher when arf reports a different PID, and asks you to change the setting. The arf it started may then still be running and need to be ended by hand. @@ -103,7 +102,7 @@ New arf sessions save their resolved absolute executable path, so a later PATH c - Session age appears in the session list, connection/stop pickers, and kernel description as **<1m**, **30m**, **1h**, or **1d**. It refreshes once a minute; the tooltip includes the start time. Age uses the persisted start of the current process generation, so reloading preserves it and restarting resets it. The recorded process exit time keeps a stopped session's lifetime fixed. - **R: Stop Selected Interactive Sessions…** in the Command Palette opens a checkbox picker with session names, PIDs, and directories. Use Ctrl/Cmd-click or Shift-click to select entries in **Interactive Sessions**, then click the header's stop icon or right-click **Stop Selected Interactive Sessions…** to stop that selection. With no tree selection, the header icon opens the picker. **R: Stop All Interactive Sessions…**, also in the view's **…** menu, targets running Interactive sessions in the configured registry on this host, including those without open tabs. Both ask once with the target list, retain history, and leave the current editor layout intact. Sessions controlled by another VS Code window are skipped; the result offers **Show Details** for failures. Use **Take Control** explicitly before retrying those sessions. Sessions created or restarted after confirmation opens are not added to its targets. - The Interactive toolbar includes **Restart**, **Session…**, **History**, and **Clear Completed**, alongside VS Code's **Interrupt** control. **Session…** opens a searchable action picker for switching/creating sessions, rename/details, queued-work cancellation, input/control, plots/export/asset cleanup, disconnect, and stop. These actions target that window's notebook, even when another session or editor has focus. On narrow windows, VS Code moves excess actions into its toolbar overflow. The controls also work in the fallback R notebook and stay out of other kernels' notebooks. -- Restart and Stop confirmations name the affected session and explain that in-memory objects will be lost. Restart is available for managed plain R and arf sessions; restart an adopted arf session in its original terminal or session manager, then reconnect. **Disconnect** leaves R running. **Clear Completed** retains active/queued cells, drafts, and saved history. +- Restart and Stop confirmations name the affected session and explain that in-memory objects will be lost. Restart is available for managed webR and arf sessions; restart an adopted arf session in its original terminal or session manager, then reconnect. **Disconnect** leaves R running. **Clear Completed** retains active/queued cells, drafts, and saved history. - When R stops, the Interactive window shows a **R session stopped** notice, including when R exits itself. Reopening the stopped session restores one notice along with its history. Restart keeps the same Interactive window, its input draft, edited cells, code, and output. A **R session restarted** boundary marks where the fresh process begins; subsequent execution uses that process. Source-document bindings and the existing kernel controls follow the replacement. A failed restart leaves an explanation and the transcript in place so it can be retried. - **Search Interactive History** (`Ctrl+Alt+H`, or `Cmd+Alt+H` on macOS) searches admitted code in the session's durable history, including commands older than the restored window. Enter inserts a command into the input for editing and preserves any existing draft. Item buttons copy, run again, or navigate to the original source; the history button loads older matches. Disconnected and older agents use the locally restored history. - **New Persistent Interactive Session** focuses the new session's input, preserving drafts in other sessions. Creating a target through **Run Selection** preserves source-editor focus. From 28336f9653f53157cbeb684052d7c981f58fde44 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sat, 28 Nov 2026 18:43:17 +0800 Subject: [PATCH 02/12] Focus the source editor before testing webR Run Selection --- src/test/suite/interactiveEditor.test.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index 57d717a47..d585fe9eb 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -1054,11 +1054,23 @@ suite('Interactive VS Code integration', function () { content: code, language: 'r', }); - const editor = await vscode.window.showTextDocument(document, vscode.ViewColumn.One); + // Run Selection reads the focused editor. Earlier tests can leave a + // split layout where column one is visible but the Interactive input owns focus. + const editor = await vscode.window.showTextDocument(document, { + viewColumn: vscode.ViewColumn.Active, + preserveFocus: false, + preview: false, + }); editor.selection = new vscode.Selection( document.positionAt(0), document.positionAt(code.length), ); + await until( + () => + vscode.window.activeTextEditor === editor && + document.getText(editor.selection) === code, + 'Run Selection needs the source editor and its full selection', + ); await vscode.commands.executeCommand('r.runSelection'); await until(() => notebook From 90c567444dffc465affe0f6281f7656479c5ce27 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sat, 28 Nov 2026 19:21:27 +0800 Subject: [PATCH 03/12] Install WebAssembly packages with install.packages in Interactive sessions --- src/test/node/interactiveWebR.test.ts | 53 ++++++++++++++++++++++++++ src/webr/consoleRunner.ts | 27 +++++++++++++ website/docs/features/r-interactive.md | 2 +- 3 files changed, 81 insertions(+), 1 deletion(-) diff --git a/src/test/node/interactiveWebR.test.ts b/src/test/node/interactiveWebR.test.ts index 8d0d1b139..edd883870 100644 --- a/src/test/node/interactiveWebR.test.ts +++ b/src/test/node/interactiveWebR.test.ts @@ -141,4 +141,57 @@ suite('R Interactive webR provider', function () { await wait(quitting, 'finished'); assert.equal((await client.snapshot()).manifest.status, 'exited'); }); + + test('installs packages from the configured Wasm repository without replacing library or require', async () => { + // Serve a tiny binary fixture through the ordinary package index and tarball paths. + const http = await import('node:http'); + const server = http.createServer((request, response) => { + const name = request.url?.split('/').at(-1); + if (name === 'PACKAGES.rds' || name === 'vscoderfixture_1.0.0.tgz') { + response.end(fs.readFileSync(path.join(project, name))); + } else { + response.writeHead(404).end(); + } + }); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }); + try { + const address = server.address(); + assert.ok(address && typeof address === 'object'); + const id = await submit(`local({ + pkg <- "vscoderfixture" + dir.create(file.path(pkg, "Meta"), recursive = TRUE) + meta <- readRDS(system.file("Meta", "package.rds", package = "datasets")) + meta$DESCRIPTION[c("Package", "Version")] <- c(pkg, "1.0.0") + write.dcf(as.data.frame(as.list(meta$DESCRIPTION)), file.path(pkg, "DESCRIPTION")) + saveRDS(meta, file.path(pkg, "Meta", "package.rds")) + writeLines(character(), file.path(pkg, "NAMESPACE")) + utils::tar("vscoderfixture_1.0.0.tgz", pkg, tar = "internal", compression = "gzip") + index <- as.matrix(data.frame(Package = pkg, Version = "1.0.0", + Depends = NA_character_, Imports = NA_character_, LinkingTo = NA_character_, row.names = pkg)) + saveRDS(index, "PACKAGES.rds") + + lib <- tempfile() + dir.create(lib) + options(webr_pkg_repos = "http://127.0.0.1:${address.port}") + install.packages(pkgs = pkg, lib, quiet = TRUE) + stopifnot(identical(library, base::library), identical(require, base::require), + identical(requireNamespace, base::requireNamespace)) + library(pkg, character.only = TRUE, lib.loc = lib) + stopifnot(as.character(utils::packageVersion(pkg, lib.loc = lib)) == "1.0.0") + })`); + assert.equal((await wait(id, 'finished')).data.state, 'success', output(id)); + const absent = await submit('install.packages("missingfixture", quiet = TRUE)'); + assert.equal((await wait(absent, 'finished')).data.state, 'error'); + assert.match( + output(absent), + /Could not install missingfixture from the webR binary repositories/, + ); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); }); diff --git a/src/webr/consoleRunner.ts b/src/webr/consoleRunner.ts index eee14be0e..e11ba995a 100644 --- a/src/webr/consoleRunner.ts +++ b/src/webr/consoleRunner.ts @@ -2,6 +2,33 @@ // next top-level prompt. R can print deferred warnings after the outcome. export const consoleRunner = String.raw` base::local({ + # Install from the Wasm repository while keeping ordinary package loading semantics. + install_packages <- function(pkgs, lib = NULL, repos = getOption("repos"), ..., + type = "binary", quiet = FALSE) { + if (is.null(repos) || !identical(type, "binary")) { + stop("webR installs prebuilt WebAssembly packages from a repository.", call. = FALSE) + } + if (...length()) { + stop("The webR installer supports pkgs, lib, repos, type = 'binary' and quiet.", + call. = FALSE) + } + repos <- unlist(lapply(repos, function(repo) { + if (identical(repo, "@CRAN@")) getOption("webr_pkg_repos") else repo + }), use.names = FALSE) + webr::install(packages = pkgs, lib = lib, repos = repos, quiet = quiet) + # The upstream installer can warn and return normally after an index download fails. + libraries <- unique(c(lib, .libPaths())) + missing <- pkgs[!vapply(pkgs, function(pkg) { + length(find.package(pkg, lib.loc = libraries, quiet = TRUE)) > 0L + }, logical(1))] + if (length(missing)) { + stop("Could not install ", paste(missing, collapse = ", "), + " from the webR binary repositories: ", paste(repos, collapse = ", "), call. = FALSE) + } + invisible(NULL) + } + attach(list(install.packages = install_packages), name = "vscodeR:webR", warn.conflicts = FALSE) + # Emscripten emits complete tty lines. Preserve an unterminated fragment # before another channel writes or R asks for input. File sinks have their # own streams and retain the regular R connection semantics. diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index c05a71302..3f03c53c9 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -12,7 +12,7 @@ Use **VS Code 1.101.0 or newer**. R Interactive supports Linux, macOS, and Windo For Remote SSH, install this extension **on the remote host**. The session agent uses the extension host’s bundled Node.js runtime on that host. On desktop it uses VS Code’s Electron runtime in Node mode. A separate Node.js installation is optional. -Choose **webR** to run R in WebAssembly with no native R or arf installation. Relative paths such as `source("helpers.R")` and `read.csv("data.csv")` use the session’s project directory. Writes to that directory are visible on the host. Install a WebAssembly build into the session with `webr::install("data.table")`, then use `library(data.table)` as usual. Additional packages live in the running webR session. Static plots appear in the transcript. Workspace inspection and the native graphics devices described below are available with arf. [webR package installation](https://docs.r-wasm.org/webr/latest/packages.html) +Choose **webR** to run R in WebAssembly with no native R or arf installation. Relative paths such as `source("helpers.R")` and `read.csv("data.csv")` use the session’s project directory. Writes to that directory are visible on the host. Use `install.packages("ggplot2")` and then `library(ggplot2)`. The installer downloads compatible WebAssembly binaries and their runtime dependencies into the current session. For an alternative binary repository, pass its URL with `repos =`. webR-specific installation options are available through `webr::install()`. Static plots appear in the transcript. Workspace inspection and the native graphics devices described below are available with arf. [webR package installation](https://docs.r-wasm.org/webr/latest/packages.html) Choose **arf** to use an installed R and its project libraries. On the R host, install: From b268799c49b64a2733fe448aadbceac96a723cbd Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sat, 28 Nov 2026 19:19:32 +0800 Subject: [PATCH 04/12] Give managed webR downloads a writable agent directory --- src/interactive/agentMain.ts | 9 ++++ src/test/node/interactiveWebR.test.ts | 70 ++++++++++++++++++++++++--- 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/src/interactive/agentMain.ts b/src/interactive/agentMain.ts index f420f2870..79f586b92 100644 --- a/src/interactive/agentMain.ts +++ b/src/interactive/agentMain.ts @@ -1,4 +1,5 @@ import * as fs from 'fs'; +import * as path from 'path'; import { AgentConfig } from './protocol'; import { SessionAgent as Agent } from './agent'; import { createBackend } from './backendRegistry'; @@ -15,6 +16,14 @@ if (require.main === module) { // other Electron applications (including the editor's CLI). delete process.env.ELECTRON_RUN_AS_NODE; const config = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')) as AgentConfig; + if (config.backend?.kind === 'webr') { + // webR's Node HTTP client creates scratch files in the process cwd. A + // graphical editor can start its detached agent in an unwritable root. + // launchAgent has already created this private session directory. + config.storage = path.resolve(config.storage); + config.directory = path.resolve(config.directory); + process.chdir(config.storage); + } const agent = new SessionAgent(config); let exiting = false; let exitCode = 0; diff --git a/src/test/node/interactiveWebR.test.ts b/src/test/node/interactiveWebR.test.ts index edd883870..3efe96896 100644 --- a/src/test/node/interactiveWebR.test.ts +++ b/src/test/node/interactiveWebR.test.ts @@ -1,10 +1,13 @@ import * as assert from 'node:assert/strict'; +import { spawn, type ChildProcess } from 'node:child_process'; import { randomUUID } from 'node:crypto'; +import { once } from 'node:events'; import * as fs from 'node:fs'; +import { createServer } from 'node:http'; import * as os from 'node:os'; import * as path from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; -import { SessionAgent } from '../../interactive/agentMain'; +import { readSessionManifest } from '../../interactive/launcher'; import { prepareNodeWebR } from '../../webr/nodeRuntime'; import { AgentClient } from '../../interactive/client'; import type { AgentConfig, SessionEvent, SessionManifest } from '../../interactive/protocol'; @@ -13,7 +16,9 @@ suite('R Interactive webR provider', function () { this.timeout(60000); let root: string; let project: string; - let agent: SessionAgent; + let launchDirectory: string; + let agent: ChildProcess; + let closed: Promise; let client: AgentClient; let manifest: SessionManifest; let events: SessionEvent[]; @@ -42,14 +47,40 @@ suite('R Interactive webR provider', function () { options: { baseUrl }, }, }; - agent = new SessionAgent(config); - manifest = await agent.start(); - await connect(); + // Exercise the same process entry point as a managed Interactive agent. + launchDirectory = path.join(root, 'launcher'); + fs.mkdirSync(launchDirectory); + fs.mkdirSync(config.storage, { mode: 0o700 }); + const configFile = path.join(config.storage, 'config.json'); + fs.writeFileSync(configFile, JSON.stringify(config)); + agent = spawn( + process.execPath, + [require.resolve('../../interactive/agentMain'), configFile], + { + cwd: launchDirectory, + stdio: 'inherit', + }, + ); + closed = once(agent, 'close'); + for (let i = 0; i < 500; i++) { + const ready = readSessionManifest(config.storage, config.id, config.generation); + if (ready?.status === 'idle') { + manifest = ready; + await connect(); + return; + } + if (ready?.startupError || agent.exitCode !== null || agent.signalCode !== null) { + throw new Error(ready?.startupError ?? 'webR agent exited during startup'); + } + await delay(20); + } + throw new Error('webR agent did not become ready'); }); teardown(async () => { client?.close(); - await agent?.close(); + agent?.kill(); + await closed; fs.rmSync(root, { recursive: true, force: true }); }); @@ -82,6 +113,33 @@ suite('R Interactive webR provider', function () { .join(''); } + test('downloads a repository index with private host scratch files and the R project as its working directory', async () => { + // This makes the upstream synchronous HTTP bridge fail in the launcher + // directory even when a privileged runner could write to a read-only folder. + fs.mkdirSync(path.join(launchDirectory, '.node-xmlhttprequest-sync-' + manifest.agentPid)); + const index = 'Package: fixture\nVersion: 1.0.0\n'; + const http = createServer((_request, response) => response.end(index)); + try { + http.listen(0, '127.0.0.1'); + await once(http, 'listening'); + const address = http.address(); + assert.ok(address && typeof address === 'object'); + const id = await submit( + [ + 'stopifnot(getwd() == "/project")', + 'writeLines(webr::eval_js("process.cwd()"), "host-cwd.txt")', + `download.file("http://127.0.0.1:${address.port}/PACKAGES", "PACKAGES", quiet = TRUE)`, + ].join('\n'), + ); + assert.equal((await wait(id, 'finished')).data.state, 'success', output(id)); + assert.equal(fs.readFileSync(path.join(project, 'PACKAGES'), 'utf8'), index); + const hostCwd = fs.readFileSync(path.join(project, 'host-cwd.txt'), 'utf8').trimEnd(); + assert.equal(fs.realpathSync(hostCwd), fs.realpathSync(path.join(root, 'session'))); + } finally { + http.close(); + } + }); + test('mounts a project and retains R objects, files and PNG output across an editor reconnect', async () => { assert.equal(manifest.backend, 'webr'); assert.equal(manifest.rPath, undefined); From eecc3af862bf3e5245c3fcacb2aeb20ddd87f104 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sat, 28 Nov 2026 19:27:17 +0800 Subject: [PATCH 05/12] Select the bound webR runtime for Interactive language features --- src/interactive/manager.ts | 1 + src/languageService.ts | 11 ++- src/session.ts | 59 ++++++++----- src/test/suite/languageService.test.ts | 110 +++++++++++++++++++++++++ website/docs/features/r-interactive.md | 2 +- 5 files changed, 160 insertions(+), 23 deletions(-) diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index cdc70ec20..9ce11f3d6 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1808,6 +1808,7 @@ export class InteractiveManager { method: data.method, params: data.params ?? {} }, data.method === 'hover' || data.method === 'completion' ? 250 : 6000, ), + manifest.provider, ); target.pid = String(manifest.rPid ?? ''); target.rVer = manifest.rVersion ?? ''; diff --git a/src/languageService.ts b/src/languageService.ts index 19aece9b7..5f7948dd1 100644 --- a/src/languageService.ts +++ b/src/languageService.ts @@ -243,8 +243,10 @@ export class LanguageService implements Disposable { const debug = this.config.get('lsp.debug'); const useRenvLibPath = this.config.get('useRenvLibPath') ?? false; const policy = resourceConfig.get('lsp.runtime', 'auto'); + // Interactive input/cell clients follow their bound runtime in auto mode. + // Ordinary source files keep their shared workspace language server. const rPath = - policy === 'webR' + policy === 'webR' || (policy === 'auto' && target?.interactiveProvider === 'webr') ? '' : target?.rPath || (await withRpcCancellation( @@ -593,7 +595,7 @@ export class LanguageService implements Disposable { selector, target?.workingDir ?? folder?.uri.fsPath ?? os.homedir(), folder, - folder?.uri, + folder?.uri ?? document.uri, target, ); } @@ -778,7 +780,10 @@ export class LanguageService implements Disposable { return; } const document = workspace.textDocuments.find( - (doc) => this.getKey(doc.uri) === this.getKey(uri), + (doc) => + !doc.isClosed && + (doc.languageId === 'r' || doc.languageId === 'rmd') && + this.getKey(doc.uri) === this.getKey(uri), ); if (document) { updateDocument(document, true); diff --git a/src/session.ts b/src/session.ts index fe8e1e18d..30a79d92c 100644 --- a/src/session.ts +++ b/src/session.ts @@ -18,6 +18,7 @@ import { TerminalSessionRegistry } from './terminalSessionRegistry'; import { TerminalStartupMonitor } from './terminalStartupMonitor'; import { SessionProcessMonitor } from './sessionProcessMonitor'; import { sessionProcessIdentity } from './sessionIdentity'; +import type { ProviderKind } from './interactive/protocol'; import { NativeTerminalPidWaitRegistry } from './nativeTerminalPidWait'; import { WorkspaceRefreshScheduler } from './workspaceRefresh'; import { @@ -131,6 +132,7 @@ export class Session { public execute?: (code: string) => Promise; public rPath?: string; public libraryPaths?: string[]; + public interactiveProvider?: ProviderKind; public requester?: (data: Record) => Promise; public connectionId?: string; public attachmentId?: string; @@ -301,16 +303,40 @@ export function bindSessionDocument(uri: Uri, session: Session): void { } export function unbindSessionDocument(uri: Uri): void { - documentSessions.delete(uri.toString()); + const previous = boundSessionForDocument(uri); + if (documentSessions.delete(uri.toString()) && previous !== boundSessionForDocument(uri)) { + sessionDocumentBound.fire(uri); + } } -export function unregisterSessionTransport(target: Session): void { - workspaceRefreshes.get(target)?.dispose(); - for (const [uri, owner] of documentSessions) { - if (owner === target) { - documentSessions.delete(uri); +/** Let per-notebook language clients reselect their runtime after restart or detach. */ +function retargetDocuments(previous: Session, next?: Session): void { + const changed = new Set(); + for (const [key, owner] of documentSessions) { + if (owner !== previous) { + continue; + } + if (next) { + documentSessions.set(key, next); + } else { + documentSessions.delete(key); } + const uri = Uri.parse(key); + // All cells of a notebook use the same language client. + changed.add( + uri.scheme === 'vscode-notebook-cell' + ? uri.with({ query: '', fragment: '' }).toString() + : key, + ); } + for (const key of changed) { + sessionDocumentBound.fire(Uri.parse(key)); + } +} + +export function unregisterSessionTransport(target: Session): void { + workspaceRefreshes.get(target)?.dispose(); + retargetDocuments(target); terminalRegistry.releaseSession(target); const current = sessions.get(target.sessionId) === target; if (current) { @@ -402,11 +428,7 @@ export function invalidateWorkspaceChildren(target: Session): void { /** Move document routing to a new process; existing data viewers keep their old owner. */ export function replaceSessionTransport(previous: Session, next: Session): void { workspaceRefreshes.get(previous)?.dispose(); - for (const [uri, owner] of documentSessions) { - if (owner === previous) { - documentSessions.set(uri, next); - } - } + retargetDocuments(previous, next); terminalRegistry.releaseSession(previous); const current = sessions.get(previous.sessionId) === previous; if (current) { @@ -427,20 +449,19 @@ export function registerSessionTransport( host: string, directory: string, requester: (data: Record) => Promise, + provider?: ProviderKind, ): Session { const previous = sessions.get(id); - const target = previous?.connectionId - ? new Session(id, host, '', '', new net.Socket()) - : (previous ?? new Session(id, host, '', '', new net.Socket())); + const target = + previous && (previous.connectionId || previous.interactiveProvider !== provider) + ? new Session(id, host, '', '', new net.Socket()) + : (previous ?? new Session(id, host, '', '', new net.Socket())); target.requester = requester; target.workingDir = directory; + target.interactiveProvider = provider; sessions.set(id, target); if (previous && previous !== target) { - for (const [uri, owner] of documentSessions) { - if (owner === previous) { - documentSessions.set(uri, target); - } - } + retargetDocuments(previous, target); terminalRegistry.releaseSession(previous); const disconnected = invalidateSessionConnection(previous); if (activeSession === previous) { diff --git a/src/test/suite/languageService.test.ts b/src/test/suite/languageService.test.ts index de08511f5..5cb74ee91 100644 --- a/src/test/suite/languageService.test.ts +++ b/src/test/suite/languageService.test.ts @@ -22,6 +22,12 @@ import * as util from '../../util'; import * as webRNode from '../../webr/nodeRuntime'; import * as webRLanguage from '../../webr/languageSession'; import { Message } from 'vscode-jsonrpc'; +import { + bindSessionDocument, + registerSessionTransport, + replaceSessionTransport, + unregisterSessionTransport, +} from '../../session'; import { mockExtensionContext } from '../common/mockvscode'; import { deferred } from '../common/sessionConnections'; @@ -370,6 +376,110 @@ suite('Language service startup lifecycle', () => { }); }); +suite('Language service for bound Interactive documents', () => { + for (const policy of ['auto', 'native', 'webR']) { + test(`uses the configured runtime across binding, restart, and detach (${policy})`, async () => { + const sandbox = sinon.createSandbox(); + const tester = (scheme: string, path: string, fragment?: string) => + ({ + uri: vscode.Uri.from({ scheme, path, fragment }), + isClosed: false, + languageId: 'r', + }) as vscode.TextDocument; + const source = tester('file', '/test/script.R'); + const notebook = tester('vscode-notebook-cell', '/test/Interactive.rnb', 'cell1'); + const prompt = tester('vscode-interactive-input', '/test/Interactive.input'); + const docs = [source, notebook, prompt]; + const getConfiguration = vscode.workspace.getConfiguration; + sandbox.stub(vscode.workspace, 'getConfiguration').callsFake((...args) => { + const config = getConfiguration(...args); + return args[0] === 'r' + ? ({ + ...config, + get: (key: string, fallback?: unknown) => { + if (key === 'lsp.runtime') { + return policy; + } + if (key === 'lsp.multiServer') { + return false; + } + return config.get(key, fallback); + }, + } as vscode.WorkspaceConfiguration) + : config; + }); + mockExtensionContext(path.resolve(__dirname, '../../..'), sandbox); + sandbox.stub(vscode.workspace, 'textDocuments').get(() => docs); + sandbox.stub(vscode.workspace, 'createFileSystemWatcher').returns({ + dispose() {}, + } as vscode.FileSystemWatcher); + sandbox.stub(util, 'getRpath').resolves(process.execPath); + // Only transport startup is stubbed: createClient must select the real + // client type/providers using the same document events as an editor. + const start = sandbox.stub(CancellableLanguageClient.prototype, 'start').resolves(); + sandbox.stub(CancellableLanguageClient.prototype, 'needsStop').returns(true); + sandbox.stub(CancellableLanguageClient.prototype, 'stop').resolves(); + const session = (id: string, provider: 'webr' | 'arf') => + registerSessionTransport(id, 'host', '/test', () => Promise.resolve({}), provider); + const wasm = session('lsp-test-webr', 'webr'); + const native = session('lsp-test-arf', 'arf'); + const languageService = new LanguageService(); + const state = languageService as unknown as { + startup: Promise; + clients: Map; + clientUpdates: Map>; + }; + const settle = async () => { + await state.startup; + while (state.clientUpdates.size) { + await Promise.all(state.clientUpdates.values()); + } + }; + const check = (usesWasm: boolean) => { + const expected = usesWasm ? 'R Language Server (webR)' : 'R Language Server'; + assert.strictEqual( + state.clients.get(`vscode-notebook:${notebook.uri.fsPath}`)?.name, + expected, + ); + assert.strictEqual(state.clients.get(prompt.uri.toString(true))?.name, expected); + }; + try { + await settle(); + const project = state.clients.get('global'); + check(policy === 'webR'); + bindSessionDocument(source.uri, wasm); + bindSessionDocument(notebook.uri.with({ fragment: '' }), wasm); + bindSessionDocument(prompt.uri, wasm); + await settle(); + check(policy !== 'native'); + assert.strictEqual(state.clients.get('global'), project); + const count = start.callCount; + bindSessionDocument(notebook.uri, wasm); + await settle(); + assert.strictEqual( + start.callCount, + count, + 'Adding another binding to the same notebook restarted its client', + ); + replaceSessionTransport(wasm, native); + await settle(); + check(policy === 'webR'); + replaceSessionTransport(native, wasm); + await settle(); + check(policy !== 'native'); + unregisterSessionTransport(wasm); + await settle(); + check(policy === 'webR'); + } finally { + await languageService.dispose(); + unregisterSessionTransport(wasm); + unregisterSessionTransport(native); + sandbox.restore(); + } + }); + } +}); + suite('Language service initialization cancellation', () => { let sandbox: sinon.SinonSandbox; let service: LanguageService | undefined; diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index 3f03c53c9..109fd4e6c 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -130,7 +130,7 @@ External terminal output observed through the arf console bridge is retained in ### Language features -- Separate language-server processes serve virtual documents with the session's R executable, library paths, and working directory. Cell and input diagnostics lint the live text with lintr's disk cache disabled, because virtual documents have no corresponding R source file. Blank or whitespace-only Interactive prompts clear diagnostics and ignore late lint replies; nonempty code and source files still receive normal diagnostics. Unsaved notebook cells also use a pathless language-server URI so namespace linters do not try to read a nonexistent file; diagnostics still map to the original cell. Source-file language servers retain the user's cache setting. Live completion and hover use the owning session with short timeouts. The existing source-file language-server configuration remains available. +- Separate language-server processes serve virtual documents with the session's R executable, library paths, and working directory. Cell and input diagnostics lint the live text with lintr's disk cache disabled, because virtual documents have no corresponding R source file. Blank or whitespace-only Interactive prompts clear diagnostics and ignore late lint replies; nonempty code and source files still receive normal diagnostics. Unsaved notebook cells also use a pathless language-server URI so namespace linters do not try to read a nonexistent file; diagnostics still map to the original cell. Source-file language servers retain the user's cache setting. Live completion and hover use the owning session with short timeouts. With `r.lsp.runtime` set to `auto`, webR Interactive inputs and cells use the webR language server even if native R is installed. Explicit `native` and `webR` preferences apply to these editors. Ordinary source files keep the workspace language server when routed to an Interactive session. - Custom `.lintr` linter lists in cells and inputs require the [pathless-document settings fix in `languageserver`](https://github.com/REditorSupport/languageserver/pull/782). `languageserver` 0.3.20 selects default linters for these documents, even when source files use your configured rules. Updating the extension alone does not fix that package behavior. - Function hovers and parameter hints can use the owning session's cached function metadata, including while R is busy. After executing `fun1 <- function(x, y) x + y`, hovering over `fun1` shows its formals, and typing `fun1(` or `fun1(1, ` shows and highlights the corresponding parameter. Hints handle defaults, named arguments, `...`, nested expressions, and quoted names. Source-local definitions and package signatures from languageserver take priority. Session hints are a fallback for simple function names in source documents, notebook cells, and Interactive inputs; they do not evaluate code. Different sessions can define the same name with different signatures. From 8c002adcadadefbc10fecadcb351d399356c8ba1 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Sun, 29 Nov 2026 09:07:11 +0800 Subject: [PATCH 06/12] Identify the experimental webR backend when choosing an Interactive session --- src/interactive/manager.ts | 2 +- website/docs/features/r-interactive.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 9ce11f3d6..9282de1c3 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1167,7 +1167,7 @@ export class InteractiveManager let arfPath = listing ? listing.command : resolveArfExecutable(arfCommand, directory); const webR = { label: 'webR', - detail: 'Run R in WebAssembly using the project directory and a separate package library.', + detail: 'Experimental backend. Run R in WebAssembly using the project directory and a separate package library.', value: 'webr' as const, }; const provider = adopt diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index 109fd4e6c..92e1233f4 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -4,6 +4,7 @@ R Interactive runs R independently of the VS Code extension host. Each session h ::: warning Experimental R Interactive was introduced in vscode-R 3.2.0 ([PR #1805](https://github.com/REditorSupport/vscode-R/pull/1805)). The feature and its `r.interactive.*` settings may change in future releases. +The webR backend is experimental. Its implementation and behavior may change substantially between releases. ::: ## Requirements and setup From a9b8277416875570b6d4038d193cee3e55afbe58 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Mon, 30 Nov 2026 11:06:56 +0800 Subject: [PATCH 07/12] Retain the actual language-client owner when reusing an Interactive input --- src/languageService.ts | 11 ++++++++--- src/test/suite/languageService.test.ts | 19 ++++++++++++++++--- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/languageService.ts b/src/languageService.ts index 5f7948dd1..c131d32d6 100644 --- a/src/languageService.ts +++ b/src/languageService.ts @@ -598,6 +598,9 @@ export class LanguageService implements Disposable { folder?.uri ?? document.uri, target, ); + if (this.clients.has(key)) { + clientTargets.set(key, target); + } } return; } @@ -622,6 +625,9 @@ export class LanguageService implements Disposable { folder?.uri ?? document.uri, target, ); + if (this.clients.has(key)) { + clientTargets.set(key, target); + } } return; } @@ -763,10 +769,9 @@ export class LanguageService implements Disposable { await this.stopClient(client); } } + // A reused client still belongs to its original owner. Only + // creating the client above establishes a new binding. await didOpenTextDocument(document); - if (this.clients.has(key)) { - clientTargets.set(key, target); - } } catch (error) { this.outputChannel.appendLine( `Failed to start language server: ${String(error)}`, diff --git a/src/test/suite/languageService.test.ts b/src/test/suite/languageService.test.ts index 5cb74ee91..f34a4b779 100644 --- a/src/test/suite/languageService.test.ts +++ b/src/test/suite/languageService.test.ts @@ -19,15 +19,15 @@ import { LanguageService } from '../../languageService'; import { connectTcpLanguageServer } from '../../languageServerTransport'; import { CancellableLanguageClient } from '../../languageServerClient'; import * as util from '../../util'; -import * as webRNode from '../../webr/nodeRuntime'; -import * as webRLanguage from '../../webr/languageSession'; -import { Message } from 'vscode-jsonrpc'; import { bindSessionDocument, registerSessionTransport, replaceSessionTransport, unregisterSessionTransport, } from '../../session'; +import * as webRNode from '../../webr/nodeRuntime'; +import * as webRLanguage from '../../webr/languageSession'; +import { Message } from 'vscode-jsonrpc'; import { mockExtensionContext } from '../common/mockvscode'; import { deferred } from '../common/sessionConnections'; @@ -390,6 +390,8 @@ suite('Language service for bound Interactive documents', () => { const notebook = tester('vscode-notebook-cell', '/test/Interactive.rnb', 'cell1'); const prompt = tester('vscode-interactive-input', '/test/Interactive.input'); const docs = [source, notebook, prompt]; + const opened = new vscode.EventEmitter(); + sandbox.stub(vscode.workspace, 'onDidOpenTextDocument').callsFake(opened.event); const getConfiguration = vscode.workspace.getConfiguration; sandbox.stub(vscode.workspace, 'getConfiguration').callsFake((...args) => { const config = getConfiguration(...args); @@ -447,11 +449,21 @@ suite('Language service for bound Interactive documents', () => { await settle(); const project = state.clients.get('global'); check(policy === 'webR'); + const unboundPrompt = state.clients.get(prompt.uri.toString(true)); + // An ordinary open update can run after the input acquires its owner. + opened.fire(notebook); + opened.fire(prompt); bindSessionDocument(source.uri, wasm); bindSessionDocument(notebook.uri.with({ fragment: '' }), wasm); bindSessionDocument(prompt.uri, wasm); await settle(); check(policy !== 'native'); + const boundPrompt = state.clients.get(prompt.uri.toString(true)); + assert.notStrictEqual(boundPrompt, unboundPrompt); + assert.strictEqual( + boundPrompt?.clientOptions.workspaceFolder?.uri.fsPath, + vscode.Uri.file(wasm.workingDir).fsPath, + ); assert.strictEqual(state.clients.get('global'), project); const count = start.callCount; bindSessionDocument(notebook.uri, wasm); @@ -474,6 +486,7 @@ suite('Language service for bound Interactive documents', () => { await languageService.dispose(); unregisterSessionTransport(wasm); unregisterSessionTransport(native); + opened.dispose(); sandbox.restore(); } }); From 4e3813f2d987df6ca3407481ca875a7e7468683c Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Tue, 1 Dec 2026 00:45:07 +0800 Subject: [PATCH 08/12] Hold the running R cell until queued work is cancelled --- src/test/node/interactiveRuntime.test.ts | 43 ++++++++++++++---------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/src/test/node/interactiveRuntime.test.ts b/src/test/node/interactiveRuntime.test.ts index e83278b7b..5d49e18ae 100644 --- a/src/test/node/interactiveRuntime.test.ts +++ b/src/test/node/interactiveRuntime.test.ts @@ -305,6 +305,16 @@ suite('Interactive real R runtime', function () { assert.match(text(id), /42/); }); + function waitForGate(gate: string): string { + return `local({ + started <- Sys.time() + while (!file.exists(${rString(gate)})) { + if (difftime(Sys.time(), started, units = "secs") > 30) stop("The test did not open the gate") + Sys.sleep(0.02) + } +})`; + } + test('streams output before completion and keeps one R environment', async () => { // R waits after the early output until the test has seen it, rather // than for a fixed time the test must resume within. @@ -312,13 +322,7 @@ suite('Interactive real R runtime', function () { let id: string; try { id = await submit(`answer <- 42; cat("early λ🙂\\n") -local({ - started <- Sys.time() - while (!file.exists(${rString(gate)})) { - if (difftime(Sys.time(), started, units = "secs") > 30) stop("The test did not open the gate") - Sys.sleep(0.02) - } -}) +${waitForGate(gate)} cat("late\\n"); answer`); await until(() => text(id).includes('early')); assert.ok( @@ -456,16 +460,21 @@ sess::display("display-${cell}", "text/plain"); cat("stderr-${cell}\\n", file=st }); test('cancels queued work without interrupting the running cell', async () => { - const running = await submit('Sys.sleep(0.4); cat("running-finished")'); - await until(() => - events.some((event) => event.type === 'started' && event.executionId === running), - ); - const queued = await submit('stop("must not execute")'); - assert.strictEqual(await client.request('cancelQueued'), 1); - assert.strictEqual( - (await client.request('execution', { id: queued })).state, - 'cancelled', - ); + const gate = path.join(temporary, `cancel-gate-${randomUUID()}`); + const running = await submit(waitForGate(gate)); + try { + await until(() => + events.some((event) => event.type === 'started' && event.executionId === running), + ); + const queued = await submit('stop("must not execute")'); + assert.strictEqual(await client.request('cancelQueued'), 1); + assert.strictEqual( + (await client.request('execution', { id: queued })).state, + 'cancelled', + ); + } finally { + fs.writeFileSync(gate, ''); + } assert.strictEqual((await finished(running)).state, 'success'); }); From 5704dd481978d7358277a3dfadb1a41b74beba26 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Tue, 1 Dec 2026 01:21:54 +0800 Subject: [PATCH 09/12] Wait for the explicit Interactive view in the jdv test --- sess/inst/tinytest/test-jdv.R | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/sess/inst/tinytest/test-jdv.R b/sess/inst/tinytest/test-jdv.R index 0c0845190..1a2417a87 100644 --- a/sess/inst/tinytest/test-jdv.R +++ b/sess/inst/tinytest/test-jdv.R @@ -417,11 +417,7 @@ local({ runtime$interactive_connected <- TRUE utils::View(sample, "interactive explicit") runtime$interactive_connected <- FALSE - host_messages(1L) - expect_identical( - tail(vapply(opens(), function(message) message$params$title, ""), 1L), - "interactive explicit" - ) + expect_identical(wait_generations("interactive explicit", 1L), 1L) # While sess answers a socket request, a session that only this client # controls keeps its connection. An Interactive session falls back to the sess From 4c80f6174857351e09dd98cf26b5bafca2e81293 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Tue, 1 Dec 2026 01:24:19 +0800 Subject: [PATCH 10/12] Keep Interactive kernel refresh assertions at a fixed session age --- src/test/suite/interactiveEditor.test.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index d585fe9eb..befe6639e 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -1557,7 +1557,8 @@ suite('Interactive VS Code integration', function () { await new Promise((resolve) => setImmediate(resolve)); const refreshed: string[] = []; const update = controller.updateNotebookAffinity.bind(controller); - const affinity = sinon + const sandbox = sinon.createSandbox(); + const affinity = sandbox .stub(controller, 'updateNotebookAffinity') .callsFake((notebook, value) => { assert.strictEqual(notebook.metadata.rSessionId, manifest.id); @@ -1578,17 +1579,22 @@ suite('Interactive VS Code integration', function () { [], 'Presentation refresh must not deselect the execution kernel', ); + // The kernel description includes the session age in whole minutes. + // Render once at a fixed time and drain its pending affinity notification. + const now = Date.now(); + sandbox.stub(Date, 'now').returns(now); + const status = interactiveManager() as unknown as { updateStatus(): void }; + status.updateStatus(); + await new Promise((resolve) => setImmediate(resolve)); affinity.resetHistory(); // Repeated unchanged status updates must not continually rebuild the picker. - const manager = interactiveManager(); - const status = manager as unknown as { updateStatus(): void }; status.updateStatus(); status.updateStatus(); await new Promise((resolve) => setImmediate(resolve)); sinon.assert.notCalled(affinity); } finally { listener.dispose(); - affinity.restore(); + sandbox.restore(); } }); From 7cd72870e0c8376a734ea63ccb66e6b2cc420ba9 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Tue, 1 Dec 2026 01:26:02 +0800 Subject: [PATCH 11/12] Wait for discovery republication before testing revived R attachment --- scripts/test-activation.cjs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/scripts/test-activation.cjs b/scripts/test-activation.cjs index 7137d8675..c107302e3 100644 --- a/scripts/test-activation.cjs +++ b/scripts/test-activation.cjs @@ -276,6 +276,11 @@ exports.run = async (api) => { 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'); + // A backed-off R terminal can take eight seconds to announce a fresh + // retry and another eight to connect to the replacement endpoint. + // Windows also resolves the wrapper PID before publishing that endpoint. + await until(() => fs.existsSync(discovery), + `The editor did not republish the discovery file for revived R terminal ${terminalPid}: ${discovery}`, 30000); 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)'); From c2ac4a86266e17a1485057b88de746c1e380e1df Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Tue, 1 Dec 2026 01:32:16 +0800 Subject: [PATCH 12/12] Keep the published Interactive manifest when backend startup finishes --- src/interactive/agent.ts | 12 ++++++++- src/test/node/interactiveBackend.test.ts | 34 ++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/interactive/agent.ts b/src/interactive/agent.ts index 919aede42..0123057d3 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -59,6 +59,8 @@ export class SessionAgent { private clients = new Set(); private lease?: { client: string; until: number }; private manifest: SessionManifest; + // Retain the last successful write only while the backend is starting. + private startupManifest: string | undefined = ''; private backend: SessionBackend; private unsubscribe: () => void; private servers: net.Server[] = []; @@ -226,7 +228,10 @@ export class SessionAgent { throw new Error('Agent stopped during startup'); } Object.assign(this.manifest.capabilities, this.backend.capabilities); - this.saveManifest(); + // A ready event can publish this exact manifest before start() returns. + if (JSON.stringify(this.manifest) !== this.startupManifest) { + this.saveManifest(); + } } catch (error) { if (!this.stopped) { // The editor may already have opened the control endpoint. Save the @@ -240,6 +245,8 @@ export class SessionAgent { } await this.close(); throw error; + } finally { + this.startupManifest = undefined; } return this.manifest; } @@ -252,6 +259,9 @@ export class SessionAgent { private saveManifest(): void { atomicJson(path.join(this.config.storage, 'manifest.json'), this.manifest); + if (this.startupManifest !== undefined) { + this.startupManifest = JSON.stringify(this.manifest); + } } private event( diff --git a/src/test/node/interactiveBackend.test.ts b/src/test/node/interactiveBackend.test.ts index d8f97d2ad..72c875484 100644 --- a/src/test/node/interactiveBackend.test.ts +++ b/src/test/node/interactiveBackend.test.ts @@ -1107,6 +1107,40 @@ suite('Interactive backend contract', function () { await client.request('interrupt'); assert.strictEqual(backend.interrupts, 1); }); + for (const lateChange of [false, true]) { + const name = lateChange + ? 'publishes capabilities learned after ready' + : 'keeps the published ready manifest'; + test(name, async () => { + const startingConfig = fakeConfig(path.join(root, 'starting')); + const startingBackend = new FakeBackend(); + const ready = startingBackend.start.bind(startingBackend); + startingBackend.start = async () => { + await ready(); + if (lateChange) { + startingBackend.capabilities.interrupt = false; + } else { + // Make a second atomic write fail after the ready manifest is on disk. + fs.mkdirSync( + path.join(startingConfig.storage, `manifest.json.${process.pid}.tmp`), + ); + } + }; + const startingAgent = new SessionAgent(startingConfig, () => startingBackend); + try { + const manifest = await startingAgent.start(); + const saved = readSessionManifest( + startingConfig.storage, + manifest.id, + manifest.generation, + ); + assert.strictEqual(saved?.status, 'idle'); + assert.strictEqual(saved.capabilities.interrupt, !lateChange); + } finally { + await startingAgent.close(); + } + }); + } test('startup failure disposes once, and late events cannot write a closed journal', async () => { const id = await submit(); const stale = backend.listener!;