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
51 changes: 32 additions & 19 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
"onWebviewPanel:r.htmlViewer",
"onLanguage:r",
"onLanguage:rmd",
"onNotebook:r-interactive"
"onNotebook:r-interactive",
"onFileSystem:vscode-r-webr"
],
"main": "./dist/extension",
"browser": "./dist/web-extension.js",
Expand All @@ -54,7 +55,7 @@
"id": "workspaceViewer",
"title": "R",
"icon": "./images/Rlogo.svg",
"when": "r.isActive"
"when": "r.isActive || r.webExtension"
}
]
},
Expand All @@ -70,7 +71,8 @@
"id": "workspaceViewer",
"name": "Workspace",
"icon": "./images/Rlogo.svg",
"contextualTitle": "R"
"contextualTitle": "R",
"when": "!r.webExtension"
},
{
"id": "rHelpPages",
Expand Down Expand Up @@ -903,6 +905,12 @@
"icon": "$(plug)",
"enablement": "!r.webExtension"
},
{
"command": "r.interactive.openSessionFile",
"title": "Open webR Session File…",
"category": "R",
"icon": "$(folder-opened)"
},
{
"command": "r.interactive.open",
"title": "Open Interactive Session",
Expand Down Expand Up @@ -1541,6 +1549,11 @@
}
],
"view/item/context": [
{
"command": "r.interactive.openSessionFile",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession.webR",
"group": "session@0"
},
{
"command": "r.workspaceViewer.view",
"group": "inline",
Expand Down Expand Up @@ -1628,67 +1641,67 @@
},
{
"command": "r.interactive.cleanAssets",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "maintenance@1"
},
{
"command": "r.interactive.history",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@0"
},
{
"command": "r.interactive.plots",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@1"
},
{
"command": "r.interactive.cancelQueued",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@2"
},
{
"command": "r.interactive.input",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@3"
},
{
"command": "r.interactive.takeControl",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@4"
},
{
"command": "r.interactive.rename",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@5"
},
{
"command": "r.interactive.info",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@6"
},
{
"command": "r.interactive.export",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@7"
},
{
"command": "r.interactive.detach",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@8"
},
{
"command": "r.interactive.restart",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/",
"group": "session@9"
},
{
"command": "r.interactive.stop",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession && !listMultiSelection",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/ && !listMultiSelection",
"group": "session@10"
},
{
"command": "r.interactive.stopSelected",
"when": "view == rInteractiveSessions && viewItem == rInteractiveSession && listMultiSelection",
"when": "view == rInteractiveSessions && viewItem =~ /^rInteractiveSession(?:[.]webR)?$/ && listMultiSelection",
"group": "session@11"
}
],
Expand Down Expand Up @@ -1725,17 +1738,17 @@
},
{
"command": "r.interactive.connect",
"when": "view == rInteractiveSessions",
"when": "view == rInteractiveSessions && !r.webExtension",
"group": "navigation@2"
},
{
"command": "r.interactive.refresh",
"when": "view == rInteractiveSessions",
"when": "view == rInteractiveSessions && !r.webExtension",
"group": "navigation@3"
},
{
"command": "r.interactive.stopSelected",
"when": "view == rInteractiveSessions",
"when": "view == rInteractiveSessions && !r.webExtension",
"group": "navigation@4"
},
{
Expand Down
4 changes: 3 additions & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

// interfaces, functions, etc. provided by vscode
import { WebRSessionFiles } from './webr/sessionFiles';
import * as vscode from 'vscode';
import * as os from 'os';
import path = require('path');
Expand Down Expand Up @@ -280,7 +281,8 @@ export async function activate(

// initialize the package/help related functions
globalRHelp = await rHelp.initializeHelp(context, rExtension);
context.subscriptions.push(new InteractiveManager(context));
const sessionFiles = new WebRSessionFiles(context.workspaceState);
context.subscriptions.push(new InteractiveManager(context, sessionFiles), sessionFiles);

// register codelens and completion providers for r markdown and r files
const codeLensProvider = new rmarkdown.RMarkdownCodeLensProvider();
Expand Down
78 changes: 78 additions & 0 deletions src/interactive/agent.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { WebRFileError } from '../webr/filesystem';
import { WebRFileRequests } from './webRFiles';
import * as net from 'net';
import * as fs from 'fs';
import * as path from 'path';
Expand Down Expand Up @@ -63,6 +65,10 @@ export class SessionAgent {
// Retain the last successful write only while the backend is starting.
private startupManifest: string | undefined = '';
private backend: SessionBackend;
private readonly fileRequests = new WebRFileRequests();
private fileQueue = Promise.resolve();
private fileOperations = 0;
private fileLeaseRevision = 0;
private unsubscribe: () => void;
private servers: net.Server[] = [];
private frontendRequests = new Map<number, string>();
Expand Down Expand Up @@ -399,6 +405,7 @@ export class SessionAgent {
socket.on('close', () => {
clearTimeout(authTimer);
this.clients.delete(client);
this.fileRequests.disconnect(client);
if (this.manifest.status === 'exited' && !this.clients.size && !this.stopped) {
this.closeAfterExit(true);
}
Expand Down Expand Up @@ -457,6 +464,14 @@ export class SessionAgent {
!other.socket.destroyed,
)
) {
if (this.lease?.client !== client.id || this.lease.until < Date.now()) {
this.fileLeaseRevision++;
for (const previous of this.clients) {
if (previous.id === this.lease?.client) {
this.fileRequests.disconnect(previous);
}
}
}
this.lease = { client: client.id, until: Date.now() + 60000 };
result = true;
} else {
Expand Down Expand Up @@ -678,6 +693,66 @@ export class SessionAgent {
result = await this.backend.inspect(request);
break;
}
case 'webRFiles': {
const files = this.backend.webRFiles;
if (
!files ||
!this.backendReady ||
this.stopping ||
this.stopped ||
this.current ||
this.fileOperations >= 32
) {
throw new WebRFileError(
'Unavailable',
'The webR session is busy, closed, or does not support files.',
);
}
this.fileOperations++;
const leaseRevision = this.fileLeaseRevision;
const operation = this.fileQueue.then(() => {
if (
!this.clients.has(client) ||
!this.backendReady ||
this.stopping ||
this.stopped
) {
throw new WebRFileError('Unavailable', 'The webR session is unavailable.');
}
return this.fileRequests.handle(client, files, params, () => {
if (!this.clients.has(client)) {
throw new WebRFileError('Unavailable', 'The client disconnected.');
}
if (leaseRevision !== this.fileLeaseRevision) {
throw new WebRFileError(
'NoPermissions',
'Control changed during the webR file operation.',
);
}
try {
this.requireControl(client);
} catch {
throw new WebRFileError(
'NoPermissions',
'Take control of the session to change its files.',
);
}
});
});
this.fileQueue = operation.then(
() => {},
() => {},
);
try {
result = await operation;
} finally {
this.fileOperations--;
if (!this.fileOperations) {
void this.pump();
}
}
break;
}
case 'asset': {
result = this.assets.read(String(params.id), 2 * 1024 * 1024).toString('base64');
break;
Expand Down Expand Up @@ -733,6 +808,8 @@ export class SessionAgent {
case 'detach':
client.subscribed = false;
if (this.lease?.client === client.id) {
this.fileLeaseRevision++;
this.fileRequests.disconnect(client);
this.lease = undefined;
}
break;
Expand Down Expand Up @@ -1075,6 +1152,7 @@ export class SessionAgent {
this.dispatching ||
this.closingHandles ||
this.redispatchTimer ||
this.fileOperations ||
this.current ||
this.manifest.status === 'exited' ||
this.manifest.status === 'unknown'
Expand Down
2 changes: 2 additions & 0 deletions src/interactive/backend.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { WebRFileAccess } from '../webr/filesystem';
import type { HtmlBundle } from './htmlBundle';
import type { AgentSettings, Submission } from './protocol';

Expand Down Expand Up @@ -92,6 +93,7 @@ export type BackendEvent = (
) & { executionId?: string };

export interface SessionBackend {
readonly webRFiles?: WebRFileAccess;
readonly ownership: BackendOwnership;
readonly capabilities: BackendCapabilities;
onEvent(listener: (event: BackendEvent) => void): () => void;
Expand Down
18 changes: 18 additions & 0 deletions src/interactive/backends/webr.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createWebRFileAccess, type WebRFileAccess } from '../../webr/filesystem';
import { webcrypto } from 'node:crypto';
import { DesktopWebRPackageStore } from '../webRPackageStore';
import { WebRConsole, WebRConsoleEvent } from '../../webr/console';
Expand All @@ -7,8 +8,10 @@ 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;
webRFiles?: WebRFileAccess;
readonly capabilities = {
streaming: true,
webRFiles: true,
stdin: true,
debugger: false,
tables: true,
Expand All @@ -25,6 +28,7 @@ export class WebRBackend implements SessionBackend {
private readonly listeners = new Set<(event: BackendEvent) => void>();
private console?: WebRConsole;
private current?: string;
private openFiles: { path: string; create: boolean }[] = [];
private inputId = 0;
private stopped = false;
private readonly packages: DesktopWebRPackageStore;
Expand Down Expand Up @@ -73,7 +77,9 @@ export class WebRBackend implements SessionBackend {
await console.start();
await runtime.FS.mkdir('/project');
await runtime.FS.mount('NODEFS', { root: this.settings.directory }, '/project');
await runtime.evalRVoid('webr::eval_js("globalThis.Module.vscodeRPinFileProject()")');
await runtime.evalRVoid('base::setwd("/project")');
this.webRFiles = createWebRFileAccess(runtime);
const rVersion = await runtime.evalRString('R.version.string');
await this.publishPackages();
if (!this.stopped) {
Expand Down Expand Up @@ -127,6 +133,9 @@ export class WebRBackend implements SessionBackend {
case 'stream':
this.emit({ ...event, executionId });
break;
case 'openFile':
this.openFiles.push({ path: event.path, create: event.create });
break;
case 'input':
this.emit({
type: 'input',
Expand Down Expand Up @@ -181,6 +190,15 @@ export class WebRBackend implements SessionBackend {
this.current = undefined;
if (!this.stopped) {
this.emit({ type: 'finished', executionId: submission.id, state });
// File operations may now use the idle worker.
for (const params of this.openFiles.splice(0)) {
this.emit({
type: 'notification',
executionId: submission.id,
method: 'webR/openFile',
params,
});
}
}
},
(error: unknown) => {
Expand Down
Loading
Loading