diff --git a/.github/actions/prepare-test-runtime/action.yml b/.github/actions/prepare-test-runtime/action.yml index 420de66f5..d0d30e717 100644 --- a/.github/actions/prepare-test-runtime/action.yml +++ b/.github/actions/prepare-test-runtime/action.yml @@ -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: @@ -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: | diff --git a/.github/actions/setup-test-tools/action.yml b/.github/actions/setup-test-tools/action.yml index b5f872b1a..842ce633e 100644 --- a/.github/actions/setup-test-tools/action.yml +++ b/.github/actions/setup-test-tools/action.yml @@ -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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 00bca4111..32f6090d5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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 @@ -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. diff --git a/package.json b/package.json index 8dee1d0db..590f0505b 100644 --- a/package.json +++ b/package.json @@ -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"], @@ -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"], diff --git a/sess/R/interactive.R b/sess/R/interactive.R index ccd178c1b..d7efca483 100644 --- a/sess/R/interactive.R +++ b/sess/R/interactive.R @@ -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)) "" 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) { diff --git a/src/interactive/README.md b/src/interactive/README.md index 6b953f187..e49236c86 100644 --- a/src/interactive/README.md +++ b/src/interactive/README.md @@ -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. @@ -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. diff --git a/src/interactive/agent.ts b/src/interactive/agent.ts index b123c6c73..a17d7c8e8 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -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'; @@ -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, @@ -169,11 +170,7 @@ export class SessionAgent { private async listen(endpoint: string, connect: (socket: net.Socket) => void): Promise { const server = net.createServer(connect); this.servers.push(server); - await new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(endpoint, resolve); - }); - fs.chmodSync(endpoint, 0o600); + await listenLocal(server, endpoint); } private saveManifest(): void { diff --git a/src/interactive/backends/process.ts b/src/interactive/backends/process.ts index 0c8643d5f..53b8b2509 100644 --- a/src/interactive/backends/process.ts +++ b/src/interactive/backends/process.ts @@ -22,6 +22,7 @@ export class RuntimeProcess { ): ChildProcess { this.child = spawn(command, args, { cwd: directory, + windowsHide: true, env, stdio: ['ignore', 'pipe', 'pipe'], }); @@ -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(); diff --git a/src/interactive/backends/sessBackend.ts b/src/interactive/backends/sessBackend.ts index 141c2cae1..cad8f06dd 100644 --- a/src/interactive/backends/sessBackend.ts +++ b/src/interactive/backends/sessBackend.ts @@ -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', @@ -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, @@ -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, diff --git a/src/interactive/backends/sessBridge.ts b/src/interactive/backends/sessBridge.ts index 4cc9edd2a..8f8d02184 100644 --- a/src/interactive/backends/sessBridge.ts +++ b/src/interactive/backends/sessBridge.ts @@ -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'; @@ -32,6 +31,10 @@ export class SessBridge { private notification: (method: string, params: Record) => void, ) {} + get endpoint(): string { + return localEndpoint(this.directory, 'sess.sock'); + } + async start(): Promise { await this.listen('sess.sock', (socket) => this.connectSess(socket)); } @@ -39,7 +42,7 @@ export class SessBridge { 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(() => { @@ -55,11 +58,7 @@ export class SessBridge { connect(socket); }); this.servers.push(server); - await new Promise((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) { diff --git a/src/interactive/launcher.ts b/src/interactive/launcher.ts index d6f5832a7..bee9d152c 100644 --- a/src/interactive/launcher.ts +++ b/src/interactive/launcher.ts @@ -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'; @@ -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)) { @@ -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 { @@ -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; } @@ -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, + env, + stdio: ['ignore', descriptor, descriptor], + }); + await new Promise((resolve, reject) => { + child.once('error', reject); + child.once('spawn', resolve); + }); + child.unref(); + } finally { + fs.closeSync(descriptor); + } } else { if (supervisor.notice) { log(supervisor.notice); @@ -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. */ diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index cc09502be..690904ae5 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -24,6 +24,7 @@ import { ExecutionCellIndex } from './cellIndex'; import type { StreamSnapshot, StreamText } from './streamText'; import { OutputQueue } from './outputQueue'; import { + defaultSessionDirectory, defaultStorage, discoverSessions, hasSessionEndpoint, @@ -1042,7 +1043,9 @@ export class InteractiveManager refresh(): void { try { - this.manifests = discoverSessions(this.root).filter(hasSessionEndpoint); + this.manifests = discoverSessions(this.root).filter((manifest) => + hasSessionEndpoint(manifest), + ); } catch (error) { this.manifests = []; this.report(error); @@ -1107,11 +1110,10 @@ export class InteractiveManager } const directory = adopt?.cwd ?? - vscode.workspace.getWorkspaceFolder(resource ?? vscode.Uri.file(this.root))?.uri - .fsPath ?? - vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? - process.env.HOME ?? - process.cwd(); + defaultSessionDirectory( + vscode.workspace.getWorkspaceFolder(resource ?? vscode.Uri.file(this.root))?.uri + .fsPath ?? vscode.workspace.workspaceFolders?.[0]?.uri.fsPath, + ); const rPath = await util.getRpath(false, resource); if (!rPath) { throw new Error('Configure an R executable before starting Interactive'); @@ -1282,7 +1284,9 @@ export class InteractiveManager private async sessionChoices(): Promise { this.refresh(); - const live = await runningSessions(this.manifests.filter(hasSessionEndpoint)); + const live = await runningSessions( + this.manifests.filter((manifest) => hasSessionEndpoint(manifest)), + ); const terminals: ArfSession[] = []; const arfCandidates = discoverArf().filter( (arf) => fs.existsSync(arf.socket_path) && !live.some((item) => item.rPid === arf.pid), diff --git a/src/interactive/supervisor.ts b/src/interactive/supervisor.ts index 040a2846d..4102ff391 100644 --- a/src/interactive/supervisor.ts +++ b/src/interactive/supervisor.ts @@ -11,9 +11,6 @@ export function prepareSupervisor( platform = process.platform, pathValue = process.env.PATH, ): SessionSupervisor { - if (platform === 'win32') { - throw new Error('Persistent Interactive sessions currently require Linux or macOS'); - } if (requested === 'detached' || (requested === 'auto' && platform !== 'linux')) { return { kind: 'detached' }; } @@ -22,6 +19,9 @@ export function prepareSupervisor( `Unknown session supervisor “${requested}”. Set r.interactive.supervision to auto, tmux, systemd, or detached.`, ); } + if (platform === 'win32') { + throw new Error('Windows supports auto or detached session supervision'); + } const kind = requested === 'systemd' ? 'systemd' : 'tmux'; const command = kind === 'systemd' ? 'systemd-run' : 'tmux'; const executable = resolveExecutable(command, directory, pathValue); diff --git a/src/interactive/transport.ts b/src/interactive/transport.ts new file mode 100644 index 000000000..d29601675 --- /dev/null +++ b/src/interactive/transport.ts @@ -0,0 +1,30 @@ +import * as fs from 'fs'; +import * as net from 'net'; +import * as path from 'path'; +import { createHash } from 'crypto'; + +/** Endpoint names are transport addresses, never evidence that an agent is alive. */ +export function localEndpoint( + directory: string, + name: string, + platform = process.platform, +): string { + if (platform === 'win32') { + const identity = createHash('sha256').update(directory).digest('hex').slice(0, 32); + return `\\\\.\\pipe\\vscode-r-${identity}-${name}`; + } + return path.join(directory, name); +} + +export async function listenLocal(server: net.Server, endpoint: string): Promise { + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(endpoint, () => { + server.removeListener('error', reject); + resolve(); + }); + }); + if (process.platform !== 'win32') { + fs.chmodSync(endpoint, 0o600); + } +} diff --git a/src/test/node/interactiveBackend.test.ts b/src/test/node/interactiveBackend.test.ts index 8c7551b0f..21a8dfd79 100644 --- a/src/test/node/interactiveBackend.test.ts +++ b/src/test/node/interactiveBackend.test.ts @@ -5,6 +5,7 @@ import * as path from 'path'; import { randomUUID } from 'crypto'; import { createServer } from 'http'; import * as net from 'net'; +import { localEndpoint } from '../../interactive/transport'; import { SessionAgent } from '../../interactive/agent'; import { AgentClient } from '../../interactive/client'; import { AgentConfig, ExecutionRecord, SessionEvent, Submission } from '../../interactive/protocol'; @@ -125,8 +126,8 @@ suite('Interactive backend configuration', () => { }); }); -// A fake backend still uses the agent's real Unix socket transport. -(process.platform === 'win32' ? suite.skip : suite)('Interactive backend contract', function () { +// A fake backend still uses the agent's real local transport. +suite('Interactive backend contract', function () { this.timeout(10000); let root: string, backend: FakeBackend, @@ -485,7 +486,7 @@ suite('Interactive backend configuration', () => { }); socket.on('error', () => undefined); }); - const endpoint = path.join(root, 'arf.sock'); + const endpoint = localEndpoint(root, 'arf.sock'); await new Promise((resolve) => listener.listen(endpoint, resolve)); const adapter = new Arf( 'unused', diff --git a/src/test/node/interactiveCore.test.ts b/src/test/node/interactiveCore.test.ts index b886146fc..7a03e7ed5 100644 --- a/src/test/node/interactiveCore.test.ts +++ b/src/test/node/interactiveCore.test.ts @@ -5,6 +5,7 @@ import * as path from 'path'; import * as net from 'net'; import { get } from 'http'; import { gunzipSync } from 'zlib'; +import { localEndpoint } from '../../interactive/transport'; import { SessionJournal, retainedAssetIds, readPreviousJournal } from '../../interactive/journal'; import { JsonLines } from '../../interactive/framing'; import { AssetStore, exportedAssetName } from '../../interactive/assets'; @@ -18,6 +19,7 @@ import { import { AgentClient, probeSession } from '../../interactive/client'; import { agentEnvironment, + defaultSessionDirectory, defaultStorage, discoverSessions, hasSessionEndpoint, @@ -183,6 +185,19 @@ suite('Interactive storage', () => { NODE_OPTIONS: '--max-old-space-size=2048', }); }); + test('starts sessions without a workspace in the user home, not the host cwd', () => { + const saved = process.env.HOME; + delete process.env.HOME; + try { + assert.notStrictEqual(os.homedir(), process.cwd()); + assert.strictEqual(defaultSessionDirectory(undefined), os.homedir()); + } finally { + if (saved !== undefined) { + process.env.HOME = saved; + } + } + assert.strictEqual(defaultSessionDirectory('/workspace'), '/workspace'); + }); let home: string; setup(() => { home = fs.mkdtempSync(path.join(os.tmpdir(), 'r-interactive-storage-')); @@ -364,9 +379,6 @@ suite('Interactive protocol and persistence', () => { }); test('session probes verify identity and live status without claiming control and bound unresponsive endpoints', async function () { - if (process.platform === 'win32') { - this.skip(); - } const manifest: SessionManifest = { id: 'probe', generation: 'first', @@ -374,7 +386,7 @@ suite('Interactive protocol and persistence', () => { label: 'Probe', host: os.hostname(), directory, - endpoint: path.join(directory, 'probe.sock'), + endpoint: localEndpoint(directory, 'probe.sock'), token: 'test-token', agentPid: process.pid, provider: 'r', @@ -425,22 +437,23 @@ suite('Interactive protocol and persistence', () => { const regularFile = path.join(directory, 'not-a-socket'); fs.writeFileSync(regularFile, ''); assert.ok(!hasSessionEndpoint({ ...manifest, endpoint: regularFile })); + assert.strictEqual( + await probeSession({ ...manifest, endpoint: regularFile }), + undefined, + ); } finally { await new Promise((resolve) => server.close(() => resolve())); } - assert.ok(!hasSessionEndpoint(manifest)); + assert.strictEqual(hasSessionEndpoint(manifest), process.platform === 'win32'); assert.strictEqual(await probeSession(manifest), undefined); }); test('a failed handshake closes its socket and a canceled attempt leaves its replacement connected', async function () { - if (process.platform === 'win32') { - this.skip(); - } const manifest = { id: 'connection', generation: 'first', protocol: 1, - endpoint: path.join(directory, 'connection.sock'), + endpoint: localEndpoint(directory, 'connection.sock'), token: 'test-token', } as SessionManifest; let identity = { ...manifest, generation: 'other' }; @@ -495,14 +508,11 @@ suite('Interactive protocol and persistence', () => { }); test('replays history before live events arriving in the same socket read', async function () { - if (process.platform === 'win32') { - this.skip(); - } const manifest = { id: 'replay', generation: 'first', protocol: 1, - endpoint: path.join(directory, 'replay.sock'), + endpoint: localEndpoint(directory, 'replay.sock'), token: 'test-token', } as SessionManifest; const journal = new SessionJournal(directory, manifest.generation); diff --git a/src/test/node/interactiveLibraries.test.ts b/src/test/node/interactiveLibraries.test.ts index 6a46dc105..be5916002 100644 --- a/src/test/node/interactiveLibraries.test.ts +++ b/src/test/node/interactiveLibraries.test.ts @@ -14,7 +14,7 @@ import { SessionEvent } from '../../interactive/protocol'; const run = promisify(execFile); -(process.platform === 'win32' ? suite.skip : suite)('Interactive library isolation', function () { +suite('Interactive library isolation', function () { this.timeout(120000); let root: string; let runtime: Awaited>; @@ -55,7 +55,11 @@ const run = promisify(execFile); const startup = '\nstartup_library_paths <- .libPaths()\nstartup_library_env <- Sys.getenv(c("R_LIBS", "R_LIBS_USER", "R_LIBS_SITE"))\n'; - test('loads private-only bridge dependencies without redirecting user package installs', async () => { + test('loads private-only bridge dependencies without redirecting user package installs', async function () { + // This fixture replaces the base library with symlinks, requiring Windows privileges. + if (process.platform === 'win32') { + this.skip(); + } const socketRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'r-lib-')); const endpoint = path.join(socketRoot, 's'); const sockets = new Set(); diff --git a/src/test/node/interactiveRuntime.test.ts b/src/test/node/interactiveRuntime.test.ts index 68421b18c..0a6c18cee 100644 --- a/src/test/node/interactiveRuntime.test.ts +++ b/src/test/node/interactiveRuntime.test.ts @@ -26,7 +26,7 @@ import { rString } from '../../interactive/backends/rCode'; const run = promisify(execFile); const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); -(process.platform === 'win32' ? suite.skip : suite)('Interactive real R runtime', function () { +suite('Interactive real R runtime', function () { this.timeout(60000); let temporary: string; let root: string; @@ -137,6 +137,15 @@ const delay = (ms: number): Promise => new Promise((resolve) => setTimeout .join(''); } + test('evaluates CRLF editor code while retaining its original text in history', async () => { + const code = 'crlf_value <- 41\r\ncrlf_value + 1\r\n'; + const id = await submit(code); + const record = await finished(id); + assert.strictEqual(record.state, 'success'); + assert.strictEqual(record.code, code); + assert.match(text(id), /42/); + }); + test('streams output before completion and keeps one R environment', async () => { const id = await submit( 'answer <- 42; cat("early λ🙂\\n"); Sys.sleep(0.5); cat("late\\n"); answer', @@ -1125,7 +1134,11 @@ dt`); assert.strictEqual((await client.snapshot()).manifest.rPid, manifest.rPid); }); - test('forked R workers cannot corrupt the parent console bridge', async () => { + test('forked R workers cannot corrupt the parent console bridge', async function () { + // R supports forked mclapply workers only on Unix. + if (process.platform === 'win32') { + this.skip(); + } const id = await submit(` values <- parallel::mclapply(1:4, function(i) { for (j in 1:10) cat(strrep(as.character(i), 8192)) @@ -1738,14 +1751,14 @@ ggplot(diamonds, aes(x = carat, y = price, color = cut)) + supervision === 'auto' ? `${process.platform === 'linux' ? 'Linux' : 'Desktop'} auto without tmux` : 'Detached'; - test(`${label} session leaves the editor process tree and retains objects after its termination`, async () => { + test(`${label} session ${process.platform === 'win32' ? 'survives editor termination and retains objects' : 'leaves the editor process tree and retains objects after its termination'}`, async () => { const runtime = hostNodeRuntime(); const node = runtime.executable; const rPath = resolveExecutable('R', root); assert.ok(rPath); const arfPath = resolveExecutable(process.env.ARF_PATH ?? 'arf', root); const environment = nodeEnvironment(runtime); - if (supervision === 'auto') { + if (supervision === 'auto' && process.platform !== 'win32') { // arf discovers R via PATH on Linux. Keep R and its shell utilities // available while excluding tmux even on CI hosts where it is installed. const bin = path.join(temporary, 'without-tmux'); @@ -1843,18 +1856,22 @@ ggplot(diamonds, aes(x = carat, y = price, color = cut)) + await complete(before); const originalPid = (await independent.snapshot()).manifest.rPid; assert.ok(originalPid); - // Check every ancestor, while the editor is still alive. A direct detached - // child survives ordinary exit but remains vulnerable to recursive cleanup. - let ancestor = value.agentPid; - for (let i = 0; ancestor > 1 && i < 50; i++) { - assert.notStrictEqual( - ancestor, - parent.pid, - 'Agent must not remain in the editor process tree', - ); - ancestor = Number( - (await run('ps', ['-p', String(ancestor), '-o', 'ppid='])).stdout.trim(), - ); + if (process.platform !== 'win32') { + // Check every ancestor, while the editor is still alive. A direct detached + // child survives ordinary exit but remains vulnerable to recursive cleanup. + let ancestor = value.agentPid; + for (let i = 0; ancestor > 1 && i < 50; i++) { + assert.notStrictEqual( + ancestor, + parent.pid, + 'Agent must not remain in the editor process tree', + ); + ancestor = Number( + ( + await run('ps', ['-p', String(ancestor), '-o', 'ppid=']) + ).stdout.trim(), + ); + } } independent.close(); await new Promise((resolve) => { @@ -1894,6 +1911,9 @@ ggplot(diamonds, aes(x = carat, y = price, color = cut)) + } test('adopts an existing arf process without losing its objects', async function () { + if (process.platform === 'win32') { + this.skip(); + } const arf = process.env.ARF_PATH ?? 'arf'; try { await run(arf, ['--version']); diff --git a/src/test/node/interactiveSupervisor.test.ts b/src/test/node/interactiveSupervisor.test.ts index b1373ca1d..b4b705881 100644 --- a/src/test/node/interactiveSupervisor.test.ts +++ b/src/test/node/interactiveSupervisor.test.ts @@ -66,10 +66,9 @@ import { AgentConfig } from '../../interactive/protocol'; () => prepareSupervisor('invalid', root, 'linux', root), /Unknown session supervisor.*r\.interactive\.supervision/, ); - assert.throws( - () => prepareSupervisor('auto', root, 'win32', root), - /require Linux or macOS/, - ); + assert.deepStrictEqual(prepareSupervisor('auto', root, 'win32', root), { + kind: 'detached', + }); }); test('missing explicit supervisors fail before creating storage or launching Node', async () => { diff --git a/src/test/node/interactiveTransport.test.ts b/src/test/node/interactiveTransport.test.ts new file mode 100644 index 000000000..2c25e3b9d --- /dev/null +++ b/src/test/node/interactiveTransport.test.ts @@ -0,0 +1,70 @@ +import * as assert from 'assert'; +import fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as sinon from 'sinon'; +import { localEndpoint } from '../../interactive/transport'; +import { defaultStorage, hasSessionEndpoint } from '../../interactive/launcher'; +import { prepareSupervisor } from '../../interactive/supervisor'; + +suite('Interactive Windows transport and storage', () => { + test('uses native, stable pipe names independent of the storage path length', () => { + const directory = 'C:\\Users\\example\\AppData\\Local\\' + 'long name '.repeat(40); + const endpoint = localEndpoint(directory, 'control.sock', 'win32'); + assert.match(endpoint, /^\\\\\.\\pipe\\vscode-r-[a-f0-9]{32}-control\.sock$/); + assert.strictEqual(endpoint, localEndpoint(directory, 'control.sock', 'win32')); + assert.notStrictEqual(endpoint, localEndpoint(directory, 'sess.sock', 'win32')); + assert.notStrictEqual( + endpoint, + localEndpoint(directory + 'other', 'control.sock', 'win32'), + ); + assert.strictEqual( + localEndpoint('/tmp/private', 'control.sock', 'linux'), + path.join('/tmp/private', 'control.sock'), + ); + }); + test('Windows auto uses detached supervision and user-local storage', () => { + assert.deepStrictEqual(prepareSupervisor('auto', '.', 'win32'), { kind: 'detached' }); + assert.deepStrictEqual(prepareSupervisor('detached', '.', 'win32'), { kind: 'detached' }); + assert.throws(() => prepareSupervisor('tmux', '.', 'win32'), /Windows supports/); + assert.strictEqual( + defaultStorage('win32', 'C:\\Users\\example', {}), + 'C:\\Users\\example\\AppData\\Local\\vscode-r\\interactive', + ); + assert.strictEqual( + defaultStorage('win32', 'C:\\Users\\example', { + LOCALAPPDATA: 'D:\\Local', + XDG_STATE_HOME: '/state', + }), + 'D:\\Local\\vscode-r\\interactive', + ); + }); + test('stale-entry pre-filter checks PIDs and only stats Unix sockets', () => { + const manifest = { + agentPid: process.pid, + endpoint: localEndpoint('private', 'control', 'win32'), + } as import('../../interactive/protocol').SessionManifest; + const stat = sinon.stub(fs, 'statSync').throws(new Error('Must not stat a pipe')); + const kill = sinon.stub(process, 'kill').returns(true); + try { + assert.ok(hasSessionEndpoint(manifest, 'win32')); + sinon.assert.notCalled(stat); + const unix = { ...manifest, endpoint: path.join(os.tmpdir(), 'control.sock') }; + stat.resetBehavior(); + stat.returns({ isSocket: () => false } as fs.Stats); + assert.ok(!hasSessionEndpoint(unix, 'linux')); + stat.returns({ isSocket: () => true } as fs.Stats); + assert.ok(hasSessionEndpoint(unix, 'linux')); + stat.throws(Object.assign(new Error('Missing socket'), { code: 'ENOENT' })); + assert.ok(!hasSessionEndpoint(unix, 'linux')); + stat.resetHistory(); + kill.throws(Object.assign(new Error('No such process'), { code: 'ESRCH' })); + assert.ok(!hasSessionEndpoint(manifest, 'win32')); + assert.ok(!hasSessionEndpoint(unix, 'linux')); + sinon.assert.notCalled(stat); + } finally { + kill.restore(); + stat.restore(); + } + }); +}); diff --git a/src/test/node/mise.lock b/src/test/node/mise.lock index 0ec64bf97..316e31766 100644 --- a/src/test/node/mise.lock +++ b/src/test/node/mise.lock @@ -23,3 +23,8 @@ url_api = "https://api.github.com/repos/eitsupi/arf/releases/assets/750984111" checksum = "sha256:123dd5fa45b14d96c2b46609063c8424fdba25ced91976b4ebab9eae187178f3" url = "https://github.com/eitsupi/arf/releases/download/v0.7.2-rc.1/arf-console-x86_64-apple-darwin.tar.xz" url_api = "https://api.github.com/repos/eitsupi/arf/releases/assets/750984161" + +[tools."github:eitsupi/arf"."platforms.windows-x64"] +checksum = "sha256:805f90edd9af3fea962d9ec592c03afafa006b53cc692d7db5d64f68105dca58" +url = "https://github.com/eitsupi/arf/releases/download/v0.7.2-rc.1/arf-console-x86_64-pc-windows-msvc.zip" +url_api = "https://api.github.com/repos/eitsupi/arf/releases/assets/750984167" diff --git a/src/test/node/mise.toml b/src/test/node/mise.toml index 752eb4bef..5bb874fcf 100644 --- a/src/test/node/mise.toml +++ b/src/test/node/mise.toml @@ -1,8 +1,7 @@ # Tools for the Interactive runtime tests. mise.lock pins each platform's # download and checksum; run `mise lock` after changing a version. [tools] -# arf is not installed on Windows, where Interactive runtime tests do not run. -"github:eitsupi/arf" = { version = "0.7.2-rc.1", os = ["linux", "macos"] } +"github:eitsupi/arf" = { version = "0.7.2-rc.1" } [settings] lockfile = true diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index 81d5ef715..1c4ce6834 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -29,14 +29,22 @@ import { StreamMessageWriter, createMessageConnection, DocumentOnTypeFormattingRequest, + ErrorCodes, + ResponseError, } from 'vscode-languageclient/node'; function treeTooltip(item: vscode.TreeItem): string { return typeof item.tooltip === 'string' ? item.tooltip : (item.tooltip?.value ?? ''); } -(process.platform === 'win32' ? suite.skip : suite)('Interactive VS Code integration', function () { +function documentEol(document: vscode.TextDocument): string { + return document.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n'; +} + +suite('Interactive VS Code integration', function () { this.timeout(60000); + // The Windows extension host can start in the VS Code installation directory. + const extensionRoot = path.resolve(__dirname, '../../..'); let root: string; const sourceDirectories: string[] = []; let previousRProfile: string | undefined; @@ -69,7 +77,7 @@ function treeTooltip(item: vscode.TreeItem): string { previousRProfile = process.env.R_PROFILE_USER; process.env.R_PROFILE_USER = path.join(root, '.Rprofile'); fs.mkdirSync(path.join(root, 'library')); - fs.cpSync(path.join(process.cwd(), 'sess'), path.join(root, 'sess'), { recursive: true }); + fs.cpSync(path.join(extensionRoot, 'sess'), path.join(root, 'sess'), { recursive: true }); await promisify(execFile)('R', [ 'CMD', 'INSTALL', @@ -101,7 +109,7 @@ function treeTooltip(item: vscode.TreeItem): string { storage: path.join(root, id), library: path.join(root, 'library'), rPath: 'R', - resources: path.join(process.cwd(), 'R'), + resources: path.join(extensionRoot, 'R'), provider: 'arf', arfPath: process.env.ARF_PATH ?? 'arf', supervision: 'detached', @@ -226,14 +234,14 @@ function treeTooltip(item: vscode.TreeItem): string { ); function bundleContext(): vscode.ExtensionContext { return ( - createRequire(__filename)(path.join(process.cwd(), 'dist/extension')) as { + createRequire(__filename)(path.join(extensionRoot, 'dist/extension')) as { extensionContext: vscode.ExtensionContext; } ).extensionContext; } function workspaceProvider(): WorkspaceDataProvider { return ( - createRequire(__filename)(path.join(process.cwd(), 'dist/extension')) as { + createRequire(__filename)(path.join(extensionRoot, 'dist/extension')) as { rWorkspace: WorkspaceDataProvider; } ).rWorkspace; @@ -329,7 +337,10 @@ function treeTooltip(item: vscode.TreeItem): string { await config.update('interactive.arfPath', previous, vscode.ConfigurationTarget.Global); } }); - test('usable custom arf is offered, but removal while naming a session prevents launch', async () => { + test('usable custom arf is offered, but removal while naming a session prevents launch', async function () { + if (process.platform === 'win32') { + this.skip(); + } const config = vscode.workspace.getConfiguration('r'); const previous = config.inspect('interactive.arfPath')?.globalValue; const executable = path.join(root, 'custom arf'); @@ -431,7 +442,10 @@ function treeTooltip(item: vscode.TreeItem): string { ); } }); - test('missing explicit tmux reports a recovery setting before installing or creating a session', async () => { + test('missing explicit tmux reports a recovery setting before installing or creating a session', async function () { + if (process.platform === 'win32') { + this.skip(); + } const config = vscode.workspace.getConfiguration('r'); const previous = config.inspect('interactive.supervision')?.globalValue; const entries = fs.readdirSync(root); @@ -741,7 +755,10 @@ function treeTooltip(item: vscode.TreeItem): string { } }); - test('refreshes a controller opened during startup when R becomes ready', async () => { + test('refreshes a controller opened during startup when R becomes ready', async function () { + if (process.platform === 'win32') { + this.skip(); + } const id = randomUUID(); const ready = path.join(root, 'release-startup'); const arf = resolveExecutable(process.env.ARF_PATH ?? 'arf', root); @@ -1400,13 +1417,14 @@ function treeTooltip(item: vscode.TreeItem): string { languageServerWaitMs, ); try { - for (const [text, ch, expected] of [ + for (const [text, ch, formatted] of [ ['typed_value<-sum(1,2', ')', 'typed_value <- sum(1, 2)'], ['typed_value<-x[1', ']', 'typed_value <- x[1]'], ['if(TRUE){typed_value<-1', '}', 'if (TRUE) {\n typed_value <- 1\n}'], ['typed_value<-1', '\n', 'typed_value <- 1\n'], ['if(TRUE){', '\n', 'if (TRUE) {\n '], ]) { + const expected = formatted.replace(/\n/g, documentEol(document)); await editor.edit((builder) => builder.replace(new vscode.Range(0, 0, document.lineCount, 0), text), ); @@ -1720,7 +1738,7 @@ function treeTooltip(item: vscode.TreeItem): string { test('keeps source-file diagnostics working with lint caching enabled', async function () { this.timeout(timeoutWithLanguageServerWaits(2)); // languageserver deliberately excludes files under the system temporary directory. - const directory = fs.mkdtempSync(path.join(process.cwd(), '.r-interactive-source-')); + const directory = fs.mkdtempSync(path.join(extensionRoot, '.r-interactive-source-')); try { const file = path.join(directory, 'diagnostics.R'); fs.writeFileSync(file, 'file_value<-1\n'); @@ -1766,7 +1784,8 @@ function treeTooltip(item: vscode.TreeItem): string { const client = service.clients.get(result.inputUri.toString()); return ( client?.isRunning() === true && - client.clientOptions.workspaceFolder?.uri.fsPath === manifest.directory + client.clientOptions.workspaceFolder?.uri.fsPath === + vscode.Uri.file(manifest.directory).fsPath ); }); } @@ -1801,7 +1820,7 @@ function treeTooltip(item: vscode.TreeItem): string { before, 'Cell reuse must keep the existing native Interactive tab', ); - assert.ok(input.getText().startsWith('# keep my draft\n')); + assert.ok(input.getText().startsWith(`# keep my draft${documentEol(input)}`)); assert.ok(input.getText().includes('editor_value <- 42')); assert.strictEqual((await client.snapshot()).executions.length, count); } finally { @@ -1834,7 +1853,7 @@ function treeTooltip(item: vscode.TreeItem): string { assert.ok(initial); const uri = cell.document.uri.toString(), summary = cell.executionSummary; - const code = cell.document.getText() + '\n# unsubmitted edit'; + const code = cell.document.getText() + documentEol(cell.document) + '# unsubmitted edit'; const edit = new vscode.WorkspaceEdit(); edit.replace(cell.document.uri, new vscode.Range(0, 0, cell.document.lineCount, 0), code); await vscode.workspace.applyEdit(edit); @@ -2253,7 +2272,10 @@ cat("\n")`; } }); - test('New Persistent Interactive Session focuses its own input and preserves the previous session draft', async () => { + test('New Persistent Interactive Session focuses its own input and preserves the previous session draft', async function () { + if (process.platform === 'win32') { + this.skip(); + } const settings = vscode.workspace.getConfiguration('r'); const previousArf = settings.inspect('interactive.arfPath')?.globalValue; const previousNode = settings.inspect('interactive.nodePath')?.globalValue; @@ -2467,7 +2489,9 @@ cat("\n")`; assert.deepStrictEqual(options?.filters, { [choice.label]: [choice.format] }); assert.strictEqual( options?.defaultUri?.fsPath, - path.join(root, `${manifests[0].label}-history.${choice.format}`), + vscode.Uri.file( + path.join(root, `${manifests[0].label}-history.${choice.format}`), + ).fsPath, ); } assert.strictEqual(save.callCount, 4); @@ -3925,6 +3949,9 @@ par(mfrow=c(1,1))`, }); test('restart keeps the window, drafts, transcript, bindings and kernel through multiple R processes', async function () { + if (process.platform === 'win32') { + this.skip(); + } const restartTimeouts = { 'cancelled restart': 30000, 'missing arf': 30000, @@ -4282,7 +4309,7 @@ par(mfrow=c(1,1))`, assert.strictEqual(notebook.metadata.rGeneration, config.generation); assert.deepStrictEqual(config.previousGenerations, [original.generation]); assert.notStrictEqual(config.library, path.join(root, 'library')); - assert.notStrictEqual(config.resources, path.join(process.cwd(), 'R')); + assert.notStrictEqual(config.resources, path.join(extensionRoot, 'R')); assert.strictEqual(config.maxOutputBytes, 1.5 * 1024 * 1024); assert.strictEqual(config.maxJournalBytes, 24 * 1024 * 1024); assert.strictEqual(config.maxAssetBytes, 96 * 1024 * 1024); @@ -4493,7 +4520,7 @@ par(mfrow=c(1,1))`, storage: path.join(root, id), library: path.join(root, 'library'), rPath: 'R', - resources: path.join(process.cwd(), 'R'), + resources: path.join(extensionRoot, 'R'), provider: 'arf', arfPath: process.env.ARF_PATH ?? 'arf', supervision: 'detached', @@ -4513,6 +4540,8 @@ par(mfrow=c(1,1))`, // Four arf sessions start one after another; slow macOS runners can // need more than the 60 second default before the shared notebook runs. this.timeout(180000); + // Do not depend on earlier lifecycle tests (including Unix-only restart) stopping R. + await Promise.all(agents.map((agent) => agent.close())); for (let i = 0; i < 4; i++) { await start(); } @@ -4699,7 +4728,7 @@ par(mfrow=c(1,1))`, storage: path.join(root, id), rPath: 'R', library: path.join(root, 'library'), - resources: path.join(process.cwd(), 'R'), + resources: path.join(extensionRoot, 'R'), provider: 'arf', arfPath: process.env.ARF_PATH ?? 'arf', supervision: 'test', @@ -4800,12 +4829,13 @@ async function stopLanguageClient(client: LanguageClient): Promise { await client.stop(10000); } catch (error) { // R's language server can close on shutdown before the client's exit - // notification is written. The client has already completed cleanup. + // notification is written (EPIPE), or, as seen on Windows, before its + // shutdown response arrives. The client has already completed cleanup. if ( client.state === State.Stopped && - error instanceof Error && - 'code' in error && - error.code === 'EPIPE' + ((error instanceof ResponseError && + error.code === ErrorCodes.PendingResponseRejected) || + (error instanceof Error && 'code' in error && error.code === 'EPIPE')) ) { return; } @@ -4880,10 +4910,58 @@ suite('Interactive language client cleanup', () => { } }); + test('accepts the server closing before it answers shutdown', async () => { + const connections: Array<{ dispose(): void }> = []; + const server = net.createServer((socket) => { + const connection = createMessageConnection( + new StreamMessageReader(socket), + new StreamMessageWriter(socket), + ); + connections.push(connection); + connection.onRequest('initialize', () => ({ capabilities: {} })); + // Close without replying, leaving the client's shutdown request pending. + connection.onRequest('shutdown', () => { + socket.destroy(); + return new Promise(() => undefined); + }); + connection.listen(); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const socket = net.connect((server.address() as net.AddressInfo).port, '127.0.0.1'); + const channel = vscode.window.createOutputChannel('Test language client cleanup', { + log: true, + }); + const client = new LanguageClient( + 'cleanup-test', + 'Cleanup test', + () => + Promise.resolve({ + reader: new StreamMessageReader(socket), + writer: new StreamMessageWriter(socket), + }), + { documentSelector: [], outputChannel: channel }, + ); + try { + await client.start(); + await stopLanguageClient(client); + assert.strictEqual(client.state, State.Stopped); + } finally { + socket.destroy(); + connections.forEach((connection) => connection.dispose()); + await new Promise((resolve) => server.close(() => resolve())); + channel.dispose(); + } + }); + test('does not suppress unrelated shutdown failures or an unstopped client', async () => { const error = Object.assign(new Error('Socket shutdown failed'), { code: 'EPIPE' }); + const pending = new ResponseError( + ErrorCodes.PendingResponseRejected, + 'Pending response rejected since connection got disposed', + ); for (const [state, failure] of [ [State.Running, error], + [State.Running, pending], [State.Stopped, new Error('Unexpected shutdown failure')], [State.Stopped, new Error('Stopping the server timed out')], ] as const) { diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index a50b45cea..b690aa8dd 100644 --- a/website/docs/features/r-interactive.md +++ b/website/docs/features/r-interactive.md @@ -8,7 +8,7 @@ R Interactive was introduced in vscode-R 3.2.0 ([PR #1805](https://github.com/RE ## Requirements and setup -Use **VS Code 1.101.0 or newer**. R Interactive currently supports Linux and macOS; persistent session supervision is not available on Windows. Existing R terminal workflows remain available. +Use **VS Code 1.101.0 or newer**. R Interactive supports Linux, macOS, and Windows. On Windows, [connecting to an existing arf session](#connect-to-an-existing-arf-session) is not yet supported. 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. @@ -60,7 +60,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 `auto` also uses 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 plain R and managed arf support this fallback with the same Interactive features. 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. @@ -186,7 +186,7 @@ Already-running sessions and older saved outputs also get compact numeric displa ## Persistence, storage, and export -The default registry is `$XDG_STATE_HOME/vscode-r/interactive` when `XDG_STATE_HOME` is a nonempty absolute path. Otherwise, new macOS installations use `~/Library/Application Support/vscode-r/interactive`, and Linux uses `~/.local/state/vscode-r/interactive`. An existing macOS registry at `~/.local/state/vscode-r/interactive` is reused so live sessions remain discoverable; it is never moved automatically. +The default registry is `$XDG_STATE_HOME/vscode-r/interactive` when `XDG_STATE_HOME` is a nonempty absolute path. Otherwise, new macOS installations use `~/Library/Application Support/vscode-r/interactive`, and Linux uses `~/.local/state/vscode-r/interactive`. An existing macOS registry at `~/.local/state/vscode-r/interactive` is reused so live sessions remain discoverable; it is never moved automatically. Windows always uses `%LOCALAPPDATA%\vscode-r\interactive`. `r.interactive.storagePath` overrides the default. Use an absolute, writable path, and reload VS Code after changing it. Keep this directory on private, reliable storage on the R host. With Remote SSH, the path and environment belong to the remote host.