Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions scripts/test-activation.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)');
Expand Down
6 changes: 1 addition & 5 deletions sess/inst/tinytest/test-jdv.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 11 additions & 4 deletions src/interactive/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
12 changes: 11 additions & 1 deletion src/interactive/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ export class SessionAgent {
private clients = new Set<Client>();
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[] = [];
Expand Down Expand Up @@ -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
Expand All @@ -240,6 +245,8 @@ export class SessionAgent {
}
await this.close();
throw error;
} finally {
this.startupManifest = undefined;
}
return this.manifest;
}
Expand All @@ -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(
Expand Down
9 changes: 9 additions & 0 deletions src/interactive/agentMain.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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;
Expand Down
19 changes: 19 additions & 0 deletions src/interactive/backendRegistry.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as path from 'node:path';
import { prepareNodeWebR } from '../webr/nodeRuntime';
import {
AgentConfig,
AgentSettings,
Expand All @@ -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';
Expand Down Expand Up @@ -77,6 +80,22 @@ function sessOptions(descriptor: BackendDescriptor, prepared = true): SessOption
}

const definitions: Readonly<Record<string, BackendDefinition>> = {
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);
Expand Down
191 changes: 191 additions & 0 deletions src/interactive/backends/webr.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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<void> {
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<never> {
return Promise.reject(new Error('Object inspection is unavailable for webR Interactive.'));
}

replyInput(reply: { value: string }): Promise<void> {
return Promise.resolve().then(() => {
if (!this.console) {
throw new Error('webR session is closed.');
}
this.console.replyInput(reply.value);
});
}

replyClientRequest(): Promise<never> {
return Promise.reject(new Error('webR has no pending editor request.'));
}

async interrupt(): Promise<void> {
await this.console?.interrupt();
}

private exit(): void {
if (!this.stopped) {
this.stopped = true;
this.emit({ type: 'exit' });
}
}

stop(): Promise<void> {
this.console?.close();
this.exit();
return Promise.resolve();
}

async dispose(): Promise<void> {
this.listeners.clear();
await this.stop();
}
}
Loading
Loading