Skip to content
Merged
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
12 changes: 2 additions & 10 deletions .github/actions/prepare-test-runtime/action.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
name: Prepare test runtime
description: >-
Install R test dependencies, build the extension and bundled sess, install
sess, compile the tests and put arf on PATH (except on Windows). Run after
setup-test-tools.
sess, compile the tests and expose the arf installed by setup-test-tools. Run
after setup-test-tools.
runs:
using: composite
steps:
Expand Down Expand Up @@ -37,15 +37,7 @@ runs:
- name: Compile test files
run: pnpm run clean && pnpm exec tsc
shell: bash
# src/test/node/mise.toml and mise.lock pin the arf version and its
# checksums.
- name: Install arf for Interactive tests
if: runner.os != 'Windows'
uses: jdx/mise-action@6612f0ef07ed2a736cd1e00a94a065522dd41195 # v5.2.5
with:
working_directory: src/test/node
- name: Expose arf for Interactive tests
if: runner.os != 'Windows'
shell: bash
working-directory: src/test/node
run: |
Expand Down
11 changes: 9 additions & 2 deletions .github/actions/setup-test-tools/action.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
name: Set up test tools
description: >-
Install R, pnpm, Node.js and the locked npm dependencies. R packages are not
installed yet, so sess bootstrap checks can run in this base environment.
Install arf, R, pnpm, Node.js and the locked npm dependencies. R packages are
not installed yet, so sess bootstrap checks can run in this base environment.
runs:
using: composite
steps:
# src/test/node/mise.toml and mise.lock pin the arf version and its
# checksums. Run before setup-r: on Windows, the Rtools curl it puts on PATH
# breaks mise-action's packslip download (jdx/mise-action#743).
- name: Install arf for Interactive tests
uses: jdx/mise-action@6612f0ef07ed2a736cd1e00a94a065522dd41195 # v5.2.5
with:
working_directory: src/test/node
- uses: r-lib/actions/setup-r@f9a764fea8d5c63df6ef9a5c7795bf7deb5d7e05 # v2
with:
use-public-rspm: true
Expand Down
6 changes: 3 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ Interactive session. Run the source/bootstrap checks with

The [architecture and backend contract](src/interactive/README.md) live beside the implementation. User setup and behavior belong in the [R Interactive documentation page](https://reditorsupport.github.io/vscode-R/features/r-interactive).

Use Linux or macOS for Interactive runtime tests, with R and arf 0.7.2-rc.1 or later. Running `mise install` in `src/test/node` installs the arf version pinned in `src/test/node/mise.toml`, which CI also uses. Bundled sess is pure R and needs no compiler when its Imports are already installed; missing Imports are installed from the configured repository. Windows runs the remaining extension checks; persistent Interactive supervision remains limited to Linux/macOS. From the repository root, after installing pnpm dependencies, prepare a test library:
Use Linux, macOS, or Windows for managed Interactive runtime tests, with R and arf 0.7.2-rc.1 or later. Running `mise install` in `src/test/node` installs the arf version pinned in `src/test/node/mise.toml`, which CI also uses. Bundled sess is pure R and needs no compiler when its Imports are already installed; missing Imports are installed from the configured repository. Windows uses detached supervision for managed Interactive sessions. From the repository root, after installing pnpm dependencies, prepare a test library:

```sh
export R_LIBS=/path/to/test-library
Expand Down Expand Up @@ -150,8 +150,8 @@ PR CI, main pushes and manual runs execute the full supported suites on every
OS. Linux and macOS run the same Node and Interactive editor tests, including
the actual VS Code Electron runtime check with no Node executable on PATH and
successful session creation using the default VS Code runtime.
Windows skips the Interactive runtime/editor suites because persistent
supervision currently requires Linux/macOS. Linux additionally runs the tmux launcher survival case
Windows also runs managed Interactive runtime/editor tests; individual Unix shell
fixtures and existing-arf adoption tests remain excluded. Linux additionally runs the tmux launcher survival case
once with tmux enabled and uses Xvfb for extension-host tests. Source/bootstrap
checks, installed identity verification and sess package tests run on every OS.

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2408,7 +2408,7 @@
"detached"
],
"default": "auto",
"description": "Independent session supervision. Auto prefers tmux on Linux when available, otherwise uses a detached process; macOS uses a detached process. Explicit tmux/systemd selections require their executables on the R host. Detached processes survive editor reload/exit, but host logout policies may stop them. Changes apply to new or restarted sessions."
"description": "Independent session supervision. Auto prefers tmux on Linux when available, otherwise uses a detached process; macOS and Windows use a detached process. Explicit tmux/systemd selections require their executables on the R host. Detached processes survive editor reload/exit, but host logout policies may stop them. Changes apply to new or restarted sessions."
},
"r.interactive.nodePath": {
"tags": ["experimental"],
Expand All @@ -2429,7 +2429,7 @@
"type": "string",
"ignoreSync": true,
"default": "",
"description": "Absolute, writable path on the R host for persistent Interactive sessions. Empty uses $XDG_STATE_HOME/vscode-r/interactive when set, otherwise ~/Library/Application Support/vscode-r/interactive on macOS or ~/.local/state/vscode-r/interactive on Linux. Existing macOS registries at the Linux-style path are reused. Reload VS Code after changing this setting."
"description": "Absolute, writable path on the R host for persistent Interactive sessions. Empty uses $XDG_STATE_HOME/vscode-r/interactive when set, otherwise ~/Library/Application Support/vscode-r/interactive on macOS or ~/.local/state/vscode-r/interactive on Linux. Windows uses %LOCALAPPDATA%/vscode-r/interactive and inherits its existing ACL. Securing a custom or shared storage location is your responsibility. Existing macOS registries at the Linux-style path are reused. Reload VS Code after changing this setting."
},
"r.interactive.plotBackend": {
"tags": ["experimental"],
Expand Down
2 changes: 2 additions & 0 deletions sess/R/interactive.R
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,8 @@ interactive_execute <- function(id, code, source = NULL) {
.interactive_plot_context()
trace_state$depth <- sys.nframe()
filename <- if (is.null(source$uri)) "<R Interactive>" else source$uri
# Editor documents may use CRLF, which parse(text = ...) does not strip.
code <- gsub("\r\n", "\n", code, fixed = TRUE)
text <- strsplit(code, "\n", fixed = TRUE)[[1L]]
expressions <- parse(text = code, srcfile = srcfilecopy(filename, text), keep.source = TRUE)
for (expr in expressions) {
Expand Down
13 changes: 11 additions & 2 deletions src/interactive/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ Both 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
the version pinned in `src/test/node/mise.toml`. Persistent supervision
currently remains limited to Linux/macOS.
the version pinned in `src/test/node/mise.toml`. Managed sessions also support
Windows with detached supervision; existing-arf discovery/adoption remains Unix-only.

[SessGraphics](backends/sessGraphics.ts) owns JGD negotiation, its font-metrics worker, plot attribution/coalescing, SVG production, and resize transport. It emits display payloads with stable identities. The agent stores assets and journals references. Static graphics remains available without JGD; another backend can supply SVG/PNG directly.

Expand Down Expand Up @@ -177,3 +177,12 @@ The agent uses the extension host runtime by default: Electron in Node mode on d
[interactiveBackend.test.ts](../test/node/interactiveBackend.test.ts) uses a scripted backend without sess configuration to exercise agent policy, event ordering, ambiguity, input, and lifecycle rules. Real-runtime, library-isolation, supervisor, editor, and renderer checks cover the integration; see the [test instructions](../../CONTRIBUTING.md#testing-r-interactive) and [analysis fixtures](../test/examples/README.md).

The [original plans and dated review reports](https://github.com/REditorSupport/vscode-R/tree/c2167d2cdb403375fa10ad3e29cde73a49cfc014/docs) are preserved at a fixed revision of [PR #1805](https://github.com/REditorSupport/vscode-R/pull/1805). They describe development history, not the current contract. The backend boundary originated in [this review](https://github.com/REditorSupport/vscode-R/pull/1805#pullrequestreview-5392223174).

## Windows

Control, sess, and jgd endpoints are named pipes with the default security
descriptor, which other users cannot open for writing; control and sess still
require the session token. Storage under `%LOCALAPPDATA%` and runtime directories
under `%TEMP%` rely on the inherited user-profile ACL, which the extension does
not rewrite. The detached agent has no editor-owned stdio and cannot leave a Job
Object that forbids breakaway.
9 changes: 3 additions & 6 deletions src/interactive/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as path from 'path';
import * as os from 'os';
import { randomBytes, randomUUID } from 'crypto';
import { StringDecoder } from 'string_decoder';
import { localEndpoint, listenLocal } from './transport';
import { JsonLines } from './framing';
import { SessionJournal, atomicJson, retainedAssetIds } from './journal';
import { AssetStore } from './assets';
Expand Down Expand Up @@ -116,7 +117,7 @@ export class SessionAgent {
label: config.label,
host: os.hostname(),
directory: config.directory,
endpoint: path.join(this.runtime, 'control.sock'),
endpoint: localEndpoint(this.runtime, 'control.sock'),
token: randomBytes(32).toString('hex'),
agentPid: process.pid,
provider: config.provider,
Expand Down Expand Up @@ -169,11 +170,7 @@ export class SessionAgent {
private async listen(endpoint: string, connect: (socket: net.Socket) => void): Promise<void> {
const server = net.createServer(connect);
this.servers.push(server);
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(endpoint, resolve);
});
fs.chmodSync(endpoint, 0o600);
await listenLocal(server, endpoint);
}

private saveManifest(): void {
Expand Down
4 changes: 3 additions & 1 deletion src/interactive/backends/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export class RuntimeProcess {
): ChildProcess {
this.child = spawn(command, args, {
cwd: directory,
windowsHide: true,
env,
stdio: ['ignore', 'pipe', 'pipe'],
});
Expand Down Expand Up @@ -90,7 +91,8 @@ export class RuntimeProcess {
return;
}
try {
process.kill(this.pid!, signal);
// Node's Windows signals forcibly terminate; never use them for interrupt.
process.kill(this.pid!, process.platform === 'win32' ? 'SIGKILL' : signal);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ESRCH') {
this.exit();
Expand Down
6 changes: 3 additions & 3 deletions src/interactive/backends/sessBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export class SessBackend implements SessionBackend {
// Whether a slow inspection is stopped at its deadline, which needs
// arf handler calls. An adopted session is known only after attaching.
inspectionDeadline: options.ownership === 'managed',
interrupt: process.platform !== 'win32',
interrupt: true,
jgd: false,
plotResize: false,
restart: options.ownership === 'managed',
Expand Down Expand Up @@ -168,7 +168,7 @@ export class SessBackend implements SessionBackend {
this.capabilities.plotResize = this.graphics.enabled;
const bootstrap = path.join(this.runtime, 'bootstrap.json');
atomicJson(bootstrap, {
sess: path.join(this.runtime, 'sess.sock'),
sess: this.bridge.endpoint,
jgd: this.graphics.endpoint,
token: this.token,
useJgd: this.graphics.enabled,
Expand All @@ -183,7 +183,7 @@ export class SessBackend implements SessionBackend {
code,
{
...process.env,
SESS_ENDPOINT: path.join(this.runtime, 'sess.sock'),
SESS_ENDPOINT: this.bridge.endpoint,
JGD_SOCKET: this.graphics.endpoint,
},
expose,
Expand Down
15 changes: 7 additions & 8 deletions src/interactive/backends/sessBridge.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as fs from 'fs';
import * as net from 'net';
import * as path from 'path';
import { randomUUID } from 'crypto';
import { localEndpoint, listenLocal } from '../transport';
import { JsonLines } from '../framing';
import { object } from '../protocol';
import { BackendEvent, ClientReply } from '../backend';
Expand Down Expand Up @@ -32,14 +31,18 @@ export class SessBridge {
private notification: (method: string, params: Record<string, unknown>) => void,
) {}

get endpoint(): string {
return localEndpoint(this.directory, 'sess.sock');
}

async start(): Promise<void> {
await this.listen('sess.sock', (socket) => this.connectSess(socket));
}
private async listen(name: string, connect: (socket: net.Socket) => void): Promise<void> {
if (this.closed) {
throw new Error('Bridge disposed during startup');
}
const endpoint = path.join(this.directory, name);
const endpoint = localEndpoint(this.directory, name);
const server = net.createServer((socket) => {
this.sockets.add(socket);
const timer = setTimeout(() => {
Expand All @@ -55,11 +58,7 @@ export class SessBridge {
connect(socket);
});
this.servers.push(server);
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(endpoint, resolve);
});
fs.chmodSync(endpoint, 0o600);
await listenLocal(server, endpoint);
}
private send(socket: net.Socket, message: unknown): void {
if (!socket.destroyed) {
Expand Down
64 changes: 57 additions & 7 deletions src/interactive/launcher.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { execFile } from 'child_process';
import { execFile, spawn } from 'child_process';
import { createHash, randomUUID } from 'crypto';
import { promisify } from 'util';
import { probeSession } from './client';
import { AgentConfig, SessionManifest, identifier } from './protocol';
import { atomicJson } from './journal';
import { hostNodeRuntime, NodeRuntime } from './nodeExecutable';
Expand All @@ -19,6 +20,15 @@ export function defaultStorage(
home = os.homedir(),
environment = process.env,
): string {
if (platform === 'win32') {
return path.win32.join(
environment.LOCALAPPDATA && path.win32.isAbsolute(environment.LOCALAPPDATA)
? environment.LOCALAPPDATA
: path.win32.join(home, 'AppData', 'Local'),
'vscode-r',
'interactive',
);
}
const xdg = environment.XDG_STATE_HOME;
// XDG paths must be absolute; an empty value is equivalent to being unset.
if (xdg && path.isAbsolute(xdg)) {
Expand All @@ -32,6 +42,15 @@ export function defaultStorage(
return path.join(home, 'Library', 'Application Support', 'vscode-r', 'interactive');
}

/**
* Working directory for a new session. Without a workspace, use the user's home
* (USERPROFILE on Windows) rather than HOME or the extension host's cwd, which
* can be the editor's installation directory.
*/
export function defaultSessionDirectory(workspace: string | undefined): string {
return workspace ?? os.homedir();
}

export function discoverSessions(root: string): SessionManifest[] {
let names: string[];
try {
Expand Down Expand Up @@ -66,19 +85,25 @@ export function discoverSessions(root: string): SessionManifest[] {
return sessions.sort((a, b) => b.created - a.created);
}

/** Cheap rejection of stale registry entries; a socket still needs an authenticated probe. */
export function hasSessionEndpoint(manifest: SessionManifest): boolean {
/** Cheap stale-entry rejection only; an authenticated probe still establishes liveness. */
export function hasSessionEndpoint(
manifest: SessionManifest,
platform = process.platform,
): boolean {
if (
!Number.isSafeInteger(manifest.agentPid) ||
manifest.agentPid <= 0 ||
typeof manifest.endpoint !== 'string' ||
!path.isAbsolute(manifest.endpoint)
!(platform === 'win32'
? manifest.endpoint.startsWith('\\\\.\\pipe\\')
: path.isAbsolute(manifest.endpoint))
) {
return false;
}
try {
process.kill(manifest.agentPid, 0);
return fs.statSync(manifest.endpoint).isSocket();
// Named pipes have no socket-file entry. Do not open or stat the pipe here.
return platform === 'win32' || fs.statSync(manifest.endpoint).isSocket();
} catch {
return false;
}
Expand Down Expand Up @@ -216,6 +241,28 @@ export async function launchAgent(
{ cause: error },
);
}
} else if (process.platform === 'win32') {
// Detached avoids libuv's kill-child-on-parent-exit job and console inheritance.
// libuv does not request CREATE_BREAKAWAY_FROM_JOB: an enclosing job that
// disallows breakaway still controls lifetime, even with a second launcher.
// No editor-owned stdio/IPC handles are inherited, including with Electron.
const descriptor = fs.openSync(path.join(config.storage, 'agent.log'), 'a', 0o600);
try {
const child = spawn(node, [agent, file], {
detached: true,
windowsHide: true,
cwd: config.directory,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Use the user's home for Windows sessions without a workspace

This newly enabled Windows path inherits config.directory from InteractiveManager.create(), whose final fallback is process.env.HOME ?? process.cwd() (manager.ts:1110–1116). With no workspace open and HOME unset, a Windows extension host started from the VS Code installation directory therefore starts arf/R there too. For example, with USERPROFILE=C:\Users\example and cwd=C:\Program Files\Microsoft VS Code, I reproduced the compiled create method selecting the latter directory. In a system installation, ordinary relative writes such as saveRDS(x, "x.rds") then fail because that directory is not user-writable, and the session/export defaults point at the installation directory. The editor-test comment added in this PR also recognizes this possible Windows cwd. Please change the no-workspace fallback to os.homedir() and add a case with HOME absent, rather than relying on the extension host's cwd.

env,
stdio: ['ignore', descriptor, descriptor],
});
await new Promise<void>((resolve, reject) => {
child.once('error', reject);
child.once('spawn', resolve);
});
child.unref();
} finally {
fs.closeSync(descriptor);
}
} else {
if (supervisor.notice) {
log(supervisor.notice);
Expand Down Expand Up @@ -243,8 +290,11 @@ export async function launchAgent(
const manifest = JSON.parse(
fs.readFileSync(path.join(config.storage, 'manifest.json'), 'utf8'),
) as SessionManifest;
if (manifest.generation === config.generation) {
return manifest;
if (manifest.id === config.id && manifest.generation === config.generation) {
const live = await probeSession(manifest);
if (live) {
return live;
}
}
} catch {
/* Atomic manifest is published after the endpoints are ready. */
Expand Down
Loading
Loading