From 2205b22602e6bbf710e6d2736d00883713ff0216 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 16 Nov 2026 12:43:22 +0000 Subject: [PATCH 1/9] feat(interactive): support managed sessions on Windows Centralize local endpoint creation in a transport module that uses named pipes on Windows and keeps Unix sockets with mode 0600 elsewhere. Enable detached supervision on Windows, store sessions under LOCALAPPDATA, and confirm a launched agent with an authenticated probe. Interrupt is available on Windows through arf IPC, and Stop force-terminates there. Windows CI installs arf and runs the managed runtime tests. --- .../actions/prepare-test-runtime/action.yml | 4 +- CONTRIBUTING.md | 6 +- package.json | 4 +- src/interactive/README.md | 26 ++++++- src/interactive/agent.ts | 9 +-- src/interactive/backends/process.ts | 4 +- src/interactive/backends/sessBackend.ts | 6 +- src/interactive/backends/sessBridge.ts | 15 ++-- src/interactive/launcher.ts | 55 +++++++++++++-- src/interactive/manager.ts | 8 ++- src/interactive/supervisor.ts | 6 +- src/interactive/transport.ts | 30 ++++++++ src/test/node/interactiveBackend.test.ts | 7 +- src/test/node/interactiveCore.test.ts | 22 +++--- src/test/node/interactiveLibraries.test.ts | 8 ++- src/test/node/interactiveRuntime.test.ts | 37 ++++++---- src/test/node/interactiveSupervisor.test.ts | 7 +- src/test/node/interactiveTransport.test.ts | 70 +++++++++++++++++++ src/test/node/mise.lock | 5 ++ src/test/node/mise.toml | 3 +- src/test/suite/interactiveEditor.test.ts | 25 +++++-- website/docs/features/r-interactive.md | 8 +-- 22 files changed, 277 insertions(+), 88 deletions(-) create mode 100644 src/interactive/transport.ts create mode 100644 src/test/node/interactiveTransport.test.ts diff --git a/.github/actions/prepare-test-runtime/action.yml b/.github/actions/prepare-test-runtime/action.yml index 420de66f5..b94e37a59 100644 --- a/.github/actions/prepare-test-runtime/action.yml +++ b/.github/actions/prepare-test-runtime/action.yml @@ -1,7 +1,7 @@ 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 + sess, compile the tests and put arf on PATH. Run after setup-test-tools. runs: using: composite @@ -40,12 +40,10 @@ runs: # 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/CONTRIBUTING.md b/CONTRIBUTING.md index 987614d34..e0ef8f726 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 @@ -136,8 +136,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 ee442d263..0eeda896c 100644 --- a/package.json +++ b/package.json @@ -2410,7 +2410,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"], @@ -2431,7 +2431,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/src/interactive/README.md b/src/interactive/README.md index 6b953f187..97a39f982 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,25 @@ 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 transport and persistence + +Control, sess, and JGD use native named pipes on Windows, with no socket-file +operations. JGD receives an `npipe:` URI. Registry entries are metadata only; +reconnection and launch readiness require an authenticated agent handshake. +Windows auto supervision launches a detached agent directly, without inheriting the editor console, +with hidden windows and file-backed logs, without an editor IPC channel or inherited console handles. +Electron agents retain `ELECTRON_RUN_AS_NODE`; R children do not. Unlike Unix +orphaning, a second launcher cannot escape a Windows kill-on-close Job Object. +Full VS Code exit must therefore be checked in the actual supported editor: +Node detachment alone does not promise survival under arbitrary job policies. + +Named pipes keep the default Windows security descriptor: other users cannot +open them for writing. Control and sess reuse the existing token authentication; +JGD replies only on the requesting connection. This is not a Unix 0600 ACL. + +Default storage under `%LOCALAPPDATA%` and runtime directories under per-user +`%TEMP%` inherit the user-profile ACL (user, SYSTEM, and administrators). +The extension does not rewrite Windows ACLs. Securing shared or custom storage +and TEMP locations is the user's responsibility. The default registry is +`%LOCALAPPDATA%/vscode-r/interactive` (with a home-relative fallback). 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..e2611e9bf 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)) { @@ -66,19 +76,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 +232,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 +281,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..b8979dc0b 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1042,7 +1042,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); @@ -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..8b2a02785 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'; @@ -364,9 +365,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 +372,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 +423,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 +494,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..18622fa14 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; @@ -1738,14 +1738,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 +1843,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 +1898,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..b535ce43d 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -35,7 +35,7 @@ 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 () { +suite('Interactive VS Code integration', function () { this.timeout(60000); let root: string; const sourceDirectories: string[] = []; @@ -329,7 +329,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 +434,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 +747,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); @@ -2253,7 +2262,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; @@ -3925,6 +3937,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, diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index 361f58042..8c40d82d2 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**. Managed R Interactive sessions support Linux, macOS, and Windows. Windows uses detached supervision; existing-arf discovery/adoption remains available only on Unix. 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,13 +186,13 @@ 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. +On Windows the default registry is `%LOCALAPPDATA%/vscode-r/interactive`. Default storage and runtime directories under per-user `%TEMP%` inherit the user-profile ACL (user, SYSTEM, and administrators). The extension does not rewrite Windows ACLs. Securing a custom or shared storage location is your responsibility. On Linux and macOS, 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. `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. If session creation reports `EACCES`, the storage directory or an ancestor is not writable by the R host's user. For example, a root-owned `~/.local` can prevent creating the Linux-style path on macOS. New macOS installations use Application Support to avoid this problem. For a custom path, choose a writable directory using `r.interactive.storagePath` and reload. Changing this setting selects a different registry; it does not migrate existing sessions. Reuse the original setting to reconnect to sessions stored there. -Each session stores a manifest, immutable assets, and one journal directory per process generation. Private Unix sockets and credentials live in a mode-0700 runtime directory. The extension discovers existing agents after a reload and reconstructs the recent transcript. Asset URLs are regenerated through VS Code's remote forwarding support. +Each session stores a manifest, immutable assets, and one journal directory per process generation. Unix sockets live in a mode-0700 runtime directory. Windows uses named pipes with their default security descriptor, which prevents other users from opening them for writing. Control and sess reuse the existing token authentication. The extension discovers existing agents after a reload and reconstructs the recent transcript. Asset URLs are regenerated through VS Code's remote forwarding support. With `r.interactive.restore` enabled (the default), reopening the same workspace reconnects its saved sessions, even when no R source file is open. Native Interactive tabs are matched by their saved URI, since VS Code does not retain their notebook metadata across reload. This restores the existing views without opening duplicate empty tabs. A failed reconnect preserves the saved association for a later retry. Sessions remain discoverable through **R: Open Interactive Session** from another workspace or when automatic restoration is disabled. Closing a view or choosing **Disconnect** removes its automatic-restoration entry while leaving R alive. From dcc933bec73338d85b8ba5dd2f53affc21c1055b Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 16 Nov 2026 12:46:13 +0000 Subject: [PATCH 2/9] docs(interactive): shorten the Windows notes in the architecture README --- src/interactive/README.md | 29 ++++++++--------------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/src/interactive/README.md b/src/interactive/README.md index 97a39f982..e49236c86 100644 --- a/src/interactive/README.md +++ b/src/interactive/README.md @@ -178,24 +178,11 @@ The agent uses the extension host runtime by default: Electron in Node mode on d 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 transport and persistence - -Control, sess, and JGD use native named pipes on Windows, with no socket-file -operations. JGD receives an `npipe:` URI. Registry entries are metadata only; -reconnection and launch readiness require an authenticated agent handshake. -Windows auto supervision launches a detached agent directly, without inheriting the editor console, -with hidden windows and file-backed logs, without an editor IPC channel or inherited console handles. -Electron agents retain `ELECTRON_RUN_AS_NODE`; R children do not. Unlike Unix -orphaning, a second launcher cannot escape a Windows kill-on-close Job Object. -Full VS Code exit must therefore be checked in the actual supported editor: -Node detachment alone does not promise survival under arbitrary job policies. - -Named pipes keep the default Windows security descriptor: other users cannot -open them for writing. Control and sess reuse the existing token authentication; -JGD replies only on the requesting connection. This is not a Unix 0600 ACL. - -Default storage under `%LOCALAPPDATA%` and runtime directories under per-user -`%TEMP%` inherit the user-profile ACL (user, SYSTEM, and administrators). -The extension does not rewrite Windows ACLs. Securing shared or custom storage -and TEMP locations is the user's responsibility. The default registry is -`%LOCALAPPDATA%/vscode-r/interactive` (with a home-relative fallback). +## 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. From fa90f26df0bba63ddf58d7fa188701d375bdc2ad Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 16 Nov 2026 12:47:09 +0000 Subject: [PATCH 3/9] docs(interactive): trim the Windows notes in the user guide --- website/docs/features/r-interactive.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/website/docs/features/r-interactive.md b/website/docs/features/r-interactive.md index 8c40d82d2..5d1945192 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**. Managed R Interactive sessions support Linux, macOS, and Windows. Windows uses detached supervision; existing-arf discovery/adoption remains available only on Unix. 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. @@ -186,13 +186,13 @@ Already-running sessions and older saved outputs also get compact numeric displa ## Persistence, storage, and export -On Windows the default registry is `%LOCALAPPDATA%/vscode-r/interactive`. Default storage and runtime directories under per-user `%TEMP%` inherit the user-profile ACL (user, SYSTEM, and administrators). The extension does not rewrite Windows ACLs. Securing a custom or shared storage location is your responsibility. On Linux and macOS, 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. If session creation reports `EACCES`, the storage directory or an ancestor is not writable by the R host's user. For example, a root-owned `~/.local` can prevent creating the Linux-style path on macOS. New macOS installations use Application Support to avoid this problem. For a custom path, choose a writable directory using `r.interactive.storagePath` and reload. Changing this setting selects a different registry; it does not migrate existing sessions. Reuse the original setting to reconnect to sessions stored there. -Each session stores a manifest, immutable assets, and one journal directory per process generation. Unix sockets live in a mode-0700 runtime directory. Windows uses named pipes with their default security descriptor, which prevents other users from opening them for writing. Control and sess reuse the existing token authentication. The extension discovers existing agents after a reload and reconstructs the recent transcript. Asset URLs are regenerated through VS Code's remote forwarding support. +Each session stores a manifest, immutable assets, and one journal directory per process generation. Private Unix sockets and credentials live in a mode-0700 runtime directory. The extension discovers existing agents after a reload and reconstructs the recent transcript. Asset URLs are regenerated through VS Code's remote forwarding support. With `r.interactive.restore` enabled (the default), reopening the same workspace reconnects its saved sessions, even when no R source file is open. Native Interactive tabs are matched by their saved URI, since VS Code does not retain their notebook metadata across reload. This restores the existing views without opening duplicate empty tabs. A failed reconnect preserves the saved association for a later retry. Sessions remain discoverable through **R: Open Interactive Session** from another workspace or when automatic restoration is disabled. Closing a view or choosing **Disconnect** removes its automatic-restoration entry while leaving R alive. From e2697900322681ec8771e1d8fb5496ec195f587a Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 16 Nov 2026 12:59:05 +0000 Subject: [PATCH 4/9] ci: install arf with mise before Rtools on Windows The Rtools MSYS curl splits the newline in the write-out argument that mise-action uses to fetch the packslip bundle, so the download always fails once Rtools is first on PATH. Run mise-action before setup-r on Windows; Linux and macOS keep the existing order. --- .github/actions/prepare-test-runtime/action.yml | 3 ++- .github/actions/setup-test-tools/action.yml | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/actions/prepare-test-runtime/action.yml b/.github/actions/prepare-test-runtime/action.yml index b94e37a59..a3d27261f 100644 --- a/.github/actions/prepare-test-runtime/action.yml +++ b/.github/actions/prepare-test-runtime/action.yml @@ -38,8 +38,9 @@ runs: run: pnpm run clean && pnpm exec tsc shell: bash # src/test/node/mise.toml and mise.lock pin the arf version and its - # checksums. + # checksums. Windows installs them in setup-test-tools before Rtools changes PATH. - name: Install arf for Interactive tests + if: runner.os != 'Windows' uses: jdx/mise-action@6612f0ef07ed2a736cd1e00a94a065522dd41195 # v5.2.5 with: working_directory: src/test/node diff --git a/.github/actions/setup-test-tools/action.yml b/.github/actions/setup-test-tools/action.yml index b5f872b1a..0a77d3e1a 100644 --- a/.github/actions/setup-test-tools/action.yml +++ b/.github/actions/setup-test-tools/action.yml @@ -5,6 +5,13 @@ description: >- runs: using: composite steps: + # Rtools puts its MSYS curl on PATH; install mise first on Windows so its + # packslip download keeps the literal newline in curl's -w argument. + - name: Install arf before Rtools on Windows + if: runner.os == 'Windows' + 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 From 81dd769d2ffda1c1268c04d390b2bfaea875bc41 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 16 Nov 2026 13:05:29 +0000 Subject: [PATCH 5/9] ci: install arf before R on every OS Running mise-action ahead of setup-r everywhere keeps one install location instead of a Windows-only step. --- .github/actions/prepare-test-runtime/action.yml | 11 ++--------- .github/actions/setup-test-tools/action.yml | 12 ++++++------ 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/.github/actions/prepare-test-runtime/action.yml b/.github/actions/prepare-test-runtime/action.yml index a3d27261f..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. 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,13 +37,6 @@ 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. Windows installs them in setup-test-tools before Rtools changes PATH. - - 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 shell: bash working-directory: src/test/node diff --git a/.github/actions/setup-test-tools/action.yml b/.github/actions/setup-test-tools/action.yml index 0a77d3e1a..842ce633e 100644 --- a/.github/actions/setup-test-tools/action.yml +++ b/.github/actions/setup-test-tools/action.yml @@ -1,14 +1,14 @@ 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: - # Rtools puts its MSYS curl on PATH; install mise first on Windows so its - # packslip download keeps the literal newline in curl's -w argument. - - name: Install arf before Rtools on Windows - if: runner.os == 'Windows' + # 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 From ceea92d7d5e41f1d9fd7b04da3664cd45ede5c80 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 16 Nov 2026 13:18:25 +0000 Subject: [PATCH 6/9] test(interactive): resolve repository paths and skip fork-only checks on Windows The Windows extension host can start in the VS Code installation directory, so locate sess, R resources and the bundle from the test file. mclapply forks only on Unix. --- src/test/node/interactiveRuntime.test.ts | 6 +++++- src/test/suite/interactiveEditor.test.ts | 18 ++++++++++-------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/test/node/interactiveRuntime.test.ts b/src/test/node/interactiveRuntime.test.ts index 18622fa14..d9284f6a4 100644 --- a/src/test/node/interactiveRuntime.test.ts +++ b/src/test/node/interactiveRuntime.test.ts @@ -1125,7 +1125,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)) diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index b535ce43d..6b2f28ac2 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -37,6 +37,8 @@ function treeTooltip(item: vscode.TreeItem): string { 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 +71,7 @@ suite('Interactive VS Code integration', function () { 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 +103,7 @@ suite('Interactive VS Code integration', function () { 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 +228,14 @@ suite('Interactive VS Code integration', function () { ); 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; @@ -1729,7 +1731,7 @@ suite('Interactive VS Code integration', function () { 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'); @@ -4297,7 +4299,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); @@ -4508,7 +4510,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', @@ -4714,7 +4716,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', From 0d59c8845acd0e0f2c1086e2161a016ba6aab2e7 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 16 Nov 2026 13:40:20 +0000 Subject: [PATCH 7/9] fix(interactive): evaluate CRLF editor code on Windows Windows editor documents can submit CRLF line endings, which R's parser rejects. Normalize them to LF before parsing while keeping the submitted text in history. Extension tests now follow each document's EOL and VS Code's path normalization, and the bulk session suite closes earlier agents itself instead of relying on a Unix-only restart test. --- sess/R/interactive.R | 2 ++ src/test/node/interactiveRuntime.test.ts | 9 +++++++++ src/test/suite/interactiveEditor.test.ts | 20 +++++++++++++++----- 3 files changed, 26 insertions(+), 5 deletions(-) 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/test/node/interactiveRuntime.test.ts b/src/test/node/interactiveRuntime.test.ts index d9284f6a4..0a6c18cee 100644 --- a/src/test/node/interactiveRuntime.test.ts +++ b/src/test/node/interactiveRuntime.test.ts @@ -137,6 +137,15 @@ suite('Interactive real R runtime', function () { .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', diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index 6b2f28ac2..1406f13db 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -35,6 +35,10 @@ function treeTooltip(item: vscode.TreeItem): string { return typeof item.tooltip === 'string' ? item.tooltip : (item.tooltip?.value ?? ''); } +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. @@ -1411,13 +1415,14 @@ suite('Interactive VS Code integration', function () { 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), ); @@ -1777,7 +1782,8 @@ suite('Interactive VS Code integration', function () { 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 ); }); } @@ -1812,7 +1818,7 @@ suite('Interactive VS Code integration', function () { 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 { @@ -1845,7 +1851,7 @@ suite('Interactive VS Code integration', function () { 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); @@ -2481,7 +2487,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); @@ -4530,6 +4538,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(); } From 3a8c8a2acd0ed6dcf0bd0e92c5b2954bc5fc9d6a Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 16 Nov 2026 22:38:59 +0000 Subject: [PATCH 8/9] fix(interactive): start sessions without a workspace in the user home Resolve the default working directory with os.homedir() instead of HOME or the extension host's cwd. On Windows, HOME is usually unset and the host can start in the VS Code installation directory, which is not user-writable. --- src/interactive/launcher.ts | 9 +++++++++ src/interactive/manager.ts | 10 +++++----- src/test/node/interactiveCore.test.ts | 14 ++++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/interactive/launcher.ts b/src/interactive/launcher.ts index e2611e9bf..bee9d152c 100644 --- a/src/interactive/launcher.ts +++ b/src/interactive/launcher.ts @@ -42,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 { diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index b8979dc0b..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, @@ -1109,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'); diff --git a/src/test/node/interactiveCore.test.ts b/src/test/node/interactiveCore.test.ts index 8b2a02785..7a03e7ed5 100644 --- a/src/test/node/interactiveCore.test.ts +++ b/src/test/node/interactiveCore.test.ts @@ -19,6 +19,7 @@ import { import { AgentClient, probeSession } from '../../interactive/client'; import { agentEnvironment, + defaultSessionDirectory, defaultStorage, discoverSessions, hasSessionEndpoint, @@ -184,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-')); From d376a809381a8f6141b04cc1ea1e343310bb3d31 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 16 Nov 2026 23:17:03 +0000 Subject: [PATCH 9/9] test(interactive): accept language servers closing before the shutdown reply On Windows, R's language server can close its connection before it answers the client's shutdown request. The client rejects the pending request with PendingResponseRejected after it has already stopped, so suite teardown failed. Treat it like the EPIPE case, and only when the client is stopped. --- src/test/suite/interactiveEditor.test.ts | 59 ++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 4 deletions(-) diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index 1406f13db..1c4ce6834 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -29,6 +29,8 @@ import { StreamMessageWriter, createMessageConnection, DocumentOnTypeFormattingRequest, + ErrorCodes, + ResponseError, } from 'vscode-languageclient/node'; function treeTooltip(item: vscode.TreeItem): string { @@ -4827,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; } @@ -4907,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) {