From 35e0779fe5691df81ec8507ad38390a560414ca9 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Mon, 30 Nov 2026 15:52:40 +0000 Subject: [PATCH 1/2] feat(interactive): pass the controller's jdv address when a cell is dispatched R no longer asks the extension for the jdv listener address with a synchronous jdv/address request while an Interactive cell runs. The editor registers its listener when it claims control, and the agent reads the current lease immediately before writing a cell to arf, for both managed and adopted sessions. A cell queued before Take Control therefore opens its View() in the window that controls the session when the cell starts. A cell already running keeps its original address. Control is still decided per client ID, so a helper connection from the controlling window, such as Stop, keeps that window's control. Moving control to another window notifies the previous one. The address is kept in memory only and is not written to the history or the session manifest. --- sess/R/handlers.R | 12 +-- sess/R/interactive.R | 8 +- sess/inst/tinytest/test-jdv.R | 40 ------- src/interactive/README.md | 7 ++ src/interactive/agent.ts | 55 ++++++++-- src/interactive/backend.ts | 8 +- src/interactive/backends/arf.ts | 9 +- src/interactive/backends/sessBackend.ts | 5 +- src/interactive/client.ts | 51 +++++++-- src/interactive/manager.ts | 33 ++++-- src/test/node/interactiveBackend.test.ts | 103 +++++++++++++++++- src/test/node/interactiveRuntime.test.ts | 130 +++++++++++++---------- 12 files changed, 325 insertions(+), 136 deletions(-) diff --git a/sess/R/handlers.R b/sess/R/handlers.R index e0a212c8d..812a869eb 100644 --- a/sess/R/handlers.R +++ b/sess/R/handlers.R @@ -1518,17 +1518,7 @@ handle_dataview_dispose <- function(params) { if (!owned && !identical(connection$state, "disconnected")) { return(FALSE) } - if (is.null(address)) { - if (isTRUE(.sess_env$interactive_connected)) { - # Interactive resolves the current controller's viewer host. - if (isTRUE(.sess_env$answering_request)) { - return(FALSE) - } - address <- request_client("jdv/address")$address - } else { - address <- .sess_env$attach_jdv[["address"]] - } - } + address <- address %||% .sess_env$attach_jdv[["address"]] if (!is.character(address) || length(address) != 1L || is.na(address) || !nzchar(address)) { return(FALSE) } diff --git a/sess/R/interactive.R b/sess/R/interactive.R index 9aef118cf..a2ec5fcbb 100644 --- a/sess/R/interactive.R +++ b/sess/R/interactive.R @@ -273,7 +273,7 @@ interactive_start <- function(config, managed = FALSE) { #' @param code R code to evaluate in the global environment. #' @param source Optional source-location metadata. #' @keywords internal -interactive_execute <- function(id, code, source = NULL) { +interactive_execute <- function(id, code, source = NULL, jdv_address = NULL) { .sess_env$interactive_skip_task <- TRUE if (!isTRUE(.sess_env$interactive_connected)) { stop("No Interactive agent connected") @@ -288,6 +288,9 @@ interactive_execute <- function(id, code, source = NULL) { stop("Execution identifier already evaluated; query the agent for its result") } assign(id, TRUE, envir = .sess_env$interactive_seen) + previous_jdv <- .sess_env$attach_jdv + generation <- .sess_env$transport_generation + .sess_env$attach_jdv <- if (.ipc_json_string(jdv_address)) list(address = jdv_address) .sess_env$interactive_id <- id .sess_env$interactive_plot_groups <- integer() on.exit( @@ -295,6 +298,9 @@ interactive_execute <- function(id, code, source = NULL) { # Live full-table viewers must discard cached filter/sort indices after code # may have edited their data by reference (including failed executions). .sess_env$dataview_revision <- (.sess_env$dataview_revision %||% 0) + 1 + if (identical(generation, .sess_env$transport_generation)) { + .sess_env$attach_jdv <- previous_jdv + } .sess_env$interactive_id <- NULL .interactive_plot_context() }, diff --git a/sess/inst/tinytest/test-jdv.R b/sess/inst/tinytest/test-jdv.R index d93019958..0c90212a5 100644 --- a/sess/inst/tinytest/test-jdv.R +++ b/sess/inst/tinytest/test-jdv.R @@ -16,7 +16,6 @@ local({ session_server <- NULL previous_plot_path <- runtime$latest_plot_path previous_interactive_connected <- runtime$interactive_connected - original_request_client <- ns$request_client pipe <- processx::conn_create_pipepair() host <- NULL on.exit( @@ -29,9 +28,6 @@ local({ if (.Platform$OS.type != "windows") unlink(endpoint) } jdv::jdv_disconnect() - unlockBinding("request_client", ns) - assign("request_client", original_request_client, envir = ns) - lockBinding("request_client", ns) runtime$con <- previous_con runtime$attach_jdv <- previous_attach_jdv runtime$latest_plot_path <- previous_plot_path @@ -433,42 +429,6 @@ local({ expect_identical(wait_generations("arrow", 1L), 1L) } - # Explicit View() in Interactive opens the regular jdv panel before trying - # the inline rich-output path used by ordinary cell results. - unlockBinding("request_client", ns) - assign( - "request_client", - function(action, args = list()) { - expect_identical(action, "jdv/address") - list(address = address) - }, - envir = ns - ) - lockBinding("request_client", ns) - runtime$interactive_connected <- TRUE - utils::View(sample, "interactive explicit") - runtime$interactive_connected <- FALSE - host_messages(1L) - expect_identical( - tail(vapply(opens(), function(message) message$params$title, ""), 1L), - "interactive explicit" - ) - - # An Interactive session answering a request cannot ask for its controller's address. - unlockBinding("request_client", ns) - assign("request_client", original_request_client, envir = ns) - lockBinding("request_client", ns) - local({ - # Interactive notifications do not use this pipe, so the decision is checked. - on.exit({ - runtime$interactive_connected <- FALSE - runtime$answering_request <- NULL - }) - runtime$interactive_connected <- TRUE - runtime$answering_request <- TRUE - expect_false(sess:::.jdv_connect()) - }) - expect_identical(jdv::jdv_connection()$address, address) configured <- runtime$attach_jdv runtime$attach_jdv <- list(unavailable = list(code = "listener_failed", message = "No listener")) expect_false(sess:::.jdv_connect()) diff --git a/src/interactive/README.md b/src/interactive/README.md index 29d0809ea..03f3ac9ce 100644 --- a/src/interactive/README.md +++ b/src/interactive/README.md @@ -68,6 +68,13 @@ R sinks, frontend styling, and forked workers cannot rewrite those frames. A server reply timeout after execution started does not cancel R; its events still establish completion. Other transport failures remain ambiguous without retries. +The editor registers its jdv listener with its control claim. Immediately before +writing a cell to arf, the agent reads the current lease and passes that listener +address to the cell. A queued cell therefore uses the editor that controls the +session at dispatch. A running cell keeps its original address. Control claims +and their addresses are kept in memory, and reconnecting editors claim again. +Explicit Open Data Viewer requests continue to carry their own address. + The backend attaches to arf before submitting code. Before running a submission, sess publishes an arf event carrying its ID, so the event's arf execution ID identifies that submission; a managed `user_input` acknowledgement reports the diff --git a/src/interactive/agent.ts b/src/interactive/agent.ts index 919aede42..1d8ece807 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -57,7 +57,11 @@ export class SessionAgent { private journal: SessionJournal; private assets: AssetStore; private clients = new Set(); - private lease?: { client: string; until: number }; + private lease?: { + client: string; + until: number; + jdv?: { socket: net.Socket; address: string }; + }; private manifest: SessionManifest; private backend: SessionBackend; private unsubscribe: () => void; @@ -387,6 +391,9 @@ export class SessionAgent { socket.on('close', () => { clearTimeout(authTimer); this.clients.delete(client); + if (this.lease?.jdv?.socket === socket) { + this.lease.jdv = undefined; + } if (this.manifest.status === 'exited' && !this.clients.size && !this.stopped) { this.closeAfterExit(true); } @@ -432,25 +439,53 @@ export class SessionAgent { case 'messagePage': result = client.pages.read(String(params.token), Number(params.offset)); break; - case 'claim': + case 'claim': { + const previous = this.lease; if ( !this.lease || this.lease.until < Date.now() || - this.lease.client === client.id || + previous?.client === client.id || params.force === true || ![...this.clients].some( (other) => other.authenticated && - other.id === this.lease?.client && + other.id === previous?.client && !other.socket.destroyed, ) ) { - this.lease = { client: client.id, until: Date.now() + 60000 }; + const address = params.jdvAddress; + if (address !== undefined && (typeof address !== 'string' || !address.trim())) { + throw new Error('Invalid jdv listener address'); + } + const sameWindow = previous?.client === client.id; + this.lease = { + client: client.id, + until: Date.now() + 60000, + // Helper connections can renew control without replacing the listener. + jdv: + address !== undefined + ? { socket: client.socket, address } + : sameWindow + ? previous.jdv + : undefined, + }; + if (previous && !sameWindow) { + for (const other of this.clients) { + if ( + other.authenticated && + other.id === previous.client && + !other.socket.destroyed + ) { + this.send(other.socket, { control: false }); + } + } + } result = true; } else { result = false; } break; + } case 'heartbeat': if (this.lease?.client === client.id) { this.lease.until = Date.now() + 60000; @@ -1091,7 +1126,15 @@ export class SessionAgent { this.dispatching = true; const abort = new AbortController(); this.dispatchAbort = abort; - const attempt = this.backend.dispatch(record, { signal: abort.signal }); + const attempt = this.backend.dispatch(record, { + signal: abort.signal, + jdvAddress: () => { + const lease = this.lease; + return lease?.jdv && lease.until >= Date.now() && !lease.jdv.socket.destroyed + ? lease.jdv.address + : undefined; + }, + }); let settled!: () => void; this.dispatchAttempt = new Promise((resolve) => { settled = resolve; diff --git a/src/interactive/backend.ts b/src/interactive/backend.ts index 6e2283cf8..2ccc36339 100644 --- a/src/interactive/backend.ts +++ b/src/interactive/backend.ts @@ -72,6 +72,12 @@ export type BackendEvent = ( | { type: 'exit'; code?: number | null; signal?: string | null } ) & { executionId?: string }; +export interface DispatchOptions { + signal?: AbortSignal; + /** Read the controller's address immediately before writing the evaluation. */ + jdvAddress?: () => string | undefined; +} + export interface SessionBackend { readonly ownership: BackendOwnership; readonly capabilities: BackendCapabilities; @@ -82,7 +88,7 @@ export interface SessionBackend { * outcome. `signal` cancels the dispatch until the code is written, which * then rejects with {@link DispatchNotSentError}; it has no effect after. */ - dispatch(submission: Submission, options?: { signal?: AbortSignal }): Promise; + dispatch(submission: Submission, options?: DispatchOptions): Promise; inspect(request: InspectionRequest): Promise; replyInput(reply: InputReply): Promise; replyClientRequest(id: string, reply: ClientReply): Promise; diff --git a/src/interactive/backends/arf.ts b/src/interactive/backends/arf.ts index 241bd97f1..037f69b74 100644 --- a/src/interactive/backends/arf.ts +++ b/src/interactive/backends/arf.ts @@ -700,7 +700,11 @@ export class Arf { throw new Error('Managed arf has not exited after forced termination'); } } - async dispatch(submission: Submission, signal?: AbortSignal): Promise { + async dispatch( + submission: Submission, + signal?: AbortSignal, + jdvAddress?: () => string | undefined, + ): Promise { if (this.failure) { throw this.failure; } @@ -725,11 +729,12 @@ export class Arf { `arf could not be reached: ${connection.closed.message}`, ); } - const code = `sess:::interactive_execute(${rString(submission.id)}, ${rString(submission.code)}, jsonlite::fromJSON(${rString(JSON.stringify(submission.source ?? null))}, simplifyVector=FALSE))`; // Nothing awaits from here until the request is written. if (signal?.aborted) { throw new DispatchNotSentError('The code was cancelled before it was sent'); } + const address = jdvAddress?.(); + const code = `sess:::interactive_execute(${rString(submission.id)}, ${rString(submission.code)}, jsonlite::fromJSON(${rString(JSON.stringify(submission.source ?? null))}, simplifyVector=FALSE), ${address ? rString(address) : 'NULL'})`; this.started = false; this.execution = { submission: submission.id, diff --git a/src/interactive/backends/sessBackend.ts b/src/interactive/backends/sessBackend.ts index 8fa94718b..444f1d7e9 100644 --- a/src/interactive/backends/sessBackend.ts +++ b/src/interactive/backends/sessBackend.ts @@ -8,6 +8,7 @@ import { BackendCapabilities, BackendEvent, ClientReply, + type DispatchOptions, DispatchNotSentError, InputReply, InspectionRequest, @@ -199,7 +200,7 @@ export class SessBackend implements SessionBackend { `${rString(this.options.library)}, ${rString(bootstrap)}, ${support}, managed=${this.ownership === 'managed' ? 'TRUE' : 'FALSE'})`; await this.frontend.bootstrap(code); } - async dispatch(submission: Submission, options?: { signal?: AbortSignal }): Promise { + async dispatch(submission: Submission, options?: DispatchOptions): Promise { await this.startup; if (this.closed) { throw new Error('Backend is disposed'); @@ -209,7 +210,7 @@ export class SessBackend implements SessionBackend { this.stderrFlushed = false; this.outputDrained = false; try { - await this.frontend.dispatch(submission, options?.signal); + await this.frontend.dispatch(submission, options?.signal, options?.jdvAddress); } catch (error) { if (error instanceof DispatchNotSentError) { this.current = undefined; diff --git a/src/interactive/client.ts b/src/interactive/client.ts index 833767ad5..b73e03d70 100644 --- a/src/interactive/client.ts +++ b/src/interactive/client.ts @@ -19,6 +19,7 @@ export class AgentClient extends EventEmitter { private incomingPageBytes = 0; private closing = false; private ready = false; + private controlRevision = 0; control = false; get connected(): boolean { return this.ready && this.socket !== undefined && !this.socket.destroyed; @@ -27,6 +28,10 @@ export class AgentClient extends EventEmitter { constructor( public manifest: SessionManifest, readonly clientId: string = randomUUID(), + private readonly jdvListener?: (manifest: SessionManifest) => Promise<{ + address: string; + dispose(): void | Promise; + }>, ) { super(); } @@ -72,6 +77,12 @@ export class AgentClient extends EventEmitter { }); return; } + if (message.control === false && this.socket === socket) { + this.controlRevision++; + this.control = false; + this.emit('activity'); + return; + } const id = Number(message.id); const pending = this.pending.get(id); if (!pending) { @@ -178,20 +189,21 @@ export class AgentClient extends EventEmitter { ); } this.manifest = manifest; - const control = - options.claim === false - ? false - : await this.request('claim', {}, options.timeout); + if (options.claim !== false) { + await this.claim(false, options.timeout); + } this.assertConnection(socket); - this.control = control; this.ready = true; this.heartbeat = setInterval(() => { + const revision = this.controlRevision; void this.request<{ control: boolean; status: SessionManifest['status'] }>('heartbeat') .then((value) => { if (this.socket !== socket || socket.destroyed) { return; } - this.control = value.control; + if (revision === this.controlRevision) { + this.control = value.control; + } this.manifest.status = value.status; this.emit('activity'); }) @@ -201,6 +213,33 @@ export class AgentClient extends EventEmitter { this.emit('activity'); } + async claim(force = false, timeout?: number): Promise { + const socket = this.socket; + if (!socket || socket.destroyed) { + throw new Error('Session agent is disconnected'); + } + const listener = await this.jdvListener?.(this.manifest).catch(() => undefined); + let claimed = false; + try { + this.assertConnection(socket); + const revision = this.controlRevision; + const accepted = await this.request( + 'claim', + { force, jdvAddress: listener?.address }, + timeout, + ); + this.assertConnection(socket); + claimed = accepted && revision === this.controlRevision; + this.control = claimed; + this.emit('activity'); + return claimed; + } finally { + if (!claimed) { + await listener?.dispose(); + } + } + } + private emitEvent(event: SessionEvent): void { if (event.generation === this.manifest.generation && event.type === 'state') { const data = event.data; diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index 2532d1942..bfb3d7709 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -260,7 +260,7 @@ export class InteractiveManager ); command('r.interactive.takeControl', (value) => this.forView(value, async (view) => { - view.client.control = await view.client.request('claim', { force: true }); + await view.client.claim(true); this.updateStatus(); this.changes.fire(undefined); }), @@ -1557,8 +1557,15 @@ export class InteractiveManager if (previous) { this.disposeView(previous, false); } - const client = new AgentClient(manifest, this.clientId); - const created: vscode.Disposable[] = [{ dispose: () => client.close() }]; + const client = this.createClient(manifest); + const created: vscode.Disposable[] = [ + { + dispose: () => { + client.close(); + disposeJdvHost(interactiveJdvHostKey(manifest.id, manifest.generation)); + }, + }, + ]; try { try { await client.connect(); @@ -1779,6 +1786,17 @@ export class InteractiveManager } } + private createClient(manifest: SessionManifest): AgentClient { + return new AgentClient(manifest, this.clientId, async (current) => { + if (current.status === 'exited' || current.status === 'stopping') { + throw new Error('The R session is unavailable.'); + } + const hostKey = interactiveJdvHostKey(current.id, current.generation); + const address = await getJdvAddress(`${current.id}:${current.generation}`, hostKey); + return { address, dispose: () => disposeJdvHost(hostKey, address) }; + }); + } + private registerTarget(client: AgentClient): session.Session { const manifest = client.manifest; const target = session.registerSessionTransport( @@ -2702,12 +2720,7 @@ export class InteractiveManager const client = view.client; const params = object(data.params ?? {}); try { - let result: unknown; - if (data.method === 'jdv/address') { - result = { address: await this.jdvAddress(view) }; - } else { - result = await session.handleEditorRequest(String(data.method), params); - } + const result = await session.handleEditorRequest(String(data.method), params); await client.request('clientReply', { id: data.id, result }); } catch (error) { await client @@ -3525,7 +3538,7 @@ export class InteractiveManager this.views.delete(`${manifest.id}:${generation}`); view.history.push(view.model); view.model = new Transcript(manifest.generation); - view.client = new AgentClient(manifest, this.clientId); + view.client = this.createClient(manifest); this.views.set(`${manifest.id}:${manifest.generation}`, view); const target = this.registerTarget(view.client); session.replaceSessionTransport(view.target, target); diff --git a/src/test/node/interactiveBackend.test.ts b/src/test/node/interactiveBackend.test.ts index d8f97d2ad..4c4fa9672 100644 --- a/src/test/node/interactiveBackend.test.ts +++ b/src/test/node/interactiveBackend.test.ts @@ -22,6 +22,7 @@ import { BackendEvent, ClientReply, DispatchNotSentError, + type DispatchOptions, InspectionRequest, SessionBackend, StopRefusedError, @@ -71,9 +72,11 @@ class FakeBackend implements SessionBackend { } /** The cancellation signal of the latest dispatch. */ signal?: AbortSignal; - dispatch(submission: Submission, options?: { signal?: AbortSignal }): Promise { + jdvAddress?: () => string | undefined; + dispatch(submission: Submission, options?: DispatchOptions): Promise { this.submissions.push(submission); this.signal = options?.signal; + this.jdvAddress = options?.jdvAddress; return this.dispatchResult(); } inspect(request: InspectionRequest): Promise { @@ -582,6 +585,19 @@ suite('Interactive backend contract', function () { await stopSession(manifest, client.clientId); assert.strictEqual(stops, 1); }); + test('stops from a second connection without revoking its window control', async () => { + let stops = 0; + backend.stopResult = async () => { + stops++; + const heartbeat = await client.request<{ control: boolean }>('heartbeat'); + assert.strictEqual(heartbeat.control, true); + assert.strictEqual(client.control, true); + backend.emit({ type: 'exit', code: 0 }); + }; + await stopSession(client.manifest, client.clientId); + assert.strictEqual(stops, 1); + }); + test('overlapping Stop requests each receive the outcome of the one in flight', async () => { let refuse!: () => void; let stops = 0; @@ -909,6 +925,91 @@ suite('Interactive backend contract', function () { next.close(); } }); + test('dispatch reads the address of the live lease without persisting it', async () => { + const firstAddress = '/tmp/first-jdv.sock'; + const nextAddress = '/tmp/next-jdv.sock'; + let released = 0; + const next = new AgentClient(client.manifest, undefined, () => + Promise.resolve({ + address: nextAddress, + dispose: () => { + released++; + }, + }), + ); + try { + assert.strictEqual(await client.request('claim', { jdvAddress: firstAddress }), true); + await next.connect(); + assert.strictEqual(next.control, false); + assert.strictEqual(released, 1); + const id = await submit(); + await until(() => backend.jdvAddress !== undefined); + assert.strictEqual(backend.jdvAddress?.(), firstAddress); + + // arf can still be opening its connection when ownership changes. + assert.strictEqual(await next.claim(true), true); + await until(() => !client.control); + assert.strictEqual(backend.jdvAddress?.(), nextAddress); + const { manifest } = await next.snapshot(); + assert.ok(!JSON.stringify(manifest).includes(nextAddress)); + assert.ok(!JSON.stringify(await record(id)).includes(firstAddress)); + assert.ok(!JSON.stringify(await record(id)).includes(nextAddress)); + + next.close(); + await until(() => backend.jdvAddress?.() === undefined); + } finally { + next.close(); + } + }); + + test('shares control by client ID and dispatches to the last registered listener', async () => { + const first = '/tmp/first-jdv.sock'; + const second = '/tmp/second-jdv.sock'; + const helper = new AgentClient(client.manifest, client.clientId); + const other = new AgentClient(client.manifest); + try { + assert.strictEqual(await client.request('claim', { jdvAddress: first }), true); + await helper.connect({ claim: false }); + assert.strictEqual( + (await helper.request<{ control: boolean }>('heartbeat')).control, + true, + ); + assert.strictEqual(await helper.claim(), true); + await submit(); + await until(() => backend.jdvAddress !== undefined); + assert.strictEqual(backend.jdvAddress?.(), first); + assert.strictEqual(client.control, true); + + assert.strictEqual(await helper.request('claim', { jdvAddress: second }), true); + assert.strictEqual(backend.jdvAddress?.(), second); + assert.strictEqual(client.control, true); + await helper.request('detach'); + assert.strictEqual( + (await client.request<{ control: boolean }>('heartbeat')).control, + false, + ); + assert.strictEqual(backend.jdvAddress?.(), undefined); + + await client.claim(); + assert.strictEqual(await helper.request('claim', { jdvAddress: second }), true); + helper.close(); + await until(() => backend.jdvAddress?.() === undefined); + assert.strictEqual( + (await client.request<{ control: boolean }>('heartbeat')).control, + true, + ); + + await helper.connect(); + await other.connect({ claim: false }); + assert.strictEqual(await other.claim(true), true); + await until(() => !client.control && !helper.control); + assert.strictEqual(backend.jdvAddress?.(), undefined); + } finally { + helper.close(); + other.close(); + } + }); + test('observer requests and stale generations cannot invoke the backend', async () => { const observer = new AgentClient(client.manifest); await observer.connect(); diff --git a/src/test/node/interactiveRuntime.test.ts b/src/test/node/interactiveRuntime.test.ts index e83278b7b..3afea8fc6 100644 --- a/src/test/node/interactiveRuntime.test.ts +++ b/src/test/node/interactiveRuntime.test.ts @@ -211,21 +211,8 @@ suite('Interactive real R runtime', function () { viewTracking: () => undefined, disconnected: (_peer, reason) => rejectOpen(new Error(reason)), }); - const onEvent = (event: SessionEvent): void => { - if (event.type !== 'clientRequest' || event.data.method !== 'jdv/address') { - return; - } - void client - .request('clientReply', { - id: event.data.id, - result: { address: host.address }, - }) - .catch((error) => - rejectOpen(error instanceof Error ? error : new Error(String(error))), - ); - }; - client.on('event', onEvent); try { + assert.strictEqual(await client.request('claim', { jdvAddress: host.address }), true); // Repeated strings keep the R fixture small while its encoded page exceeds the byte budget. const id = await submit( 'utils::View(data.frame(a = 1:300, b = rep(letters, length.out = 300), c = rep(strrep("x", 12000), 300), d = rep(strrep("y", 12000), 300)), "interactive jdv test")', @@ -291,7 +278,7 @@ suite('Interactive real R runtime', function () { assert.strictEqual(column.data.values[0], (index === 0 ? 'x' : 'y').repeat(12000)); } } finally { - client.off('event', onEvent); + await client.request('claim').catch(() => undefined); host.dispose(); } }); @@ -859,16 +846,8 @@ sess::display("display-${cell}", "text/plain"); cat("stderr-${cell}\\n", file=st viewTracking: () => undefined, disconnected: () => undefined, }); - const onEvent = (event: SessionEvent): void => { - if (event.type === 'clientRequest' && event.data.method === 'jdv/address') { - void client.request('clientReply', { - id: event.data.id, - result: { address: host.address }, - }); - } - }; - client.on('event', onEvent); try { + assert.strictEqual(await client.request('claim', { jdvAddress: host.address }), true); const source = sized ? 'arrow::Table$create(data.frame(a=1:3))' : 'nanoarrow::as_nanoarrow_array_stream(data.frame(a=1:3))'; @@ -899,7 +878,7 @@ sess::display("display-${cell}", "text/plain"); cat("stderr-${cell}\\n", file=st assert.strictEqual((page.result as JsonObject).done, false); assert.ok(page.body); } finally { - client.off('event', onEvent); + await client.request('claim').catch(() => undefined); host.dispose(); } }); @@ -1198,25 +1177,14 @@ huge`); }; const first = await createHost('first'); const second = await createHost('second'); - // Each client answers `jdv/address` with its own listener; the agent accepts - // only the controller's reply. - const answer = - (agentClient: AgentClient, host: JdvHost) => - (event: SessionEvent): void => { - if (event.type === 'clientRequest' && event.data.method === 'jdv/address') { - void agentClient - .request('clientReply', { - id: event.data.id, - result: { address: host.address }, - }) - .catch(() => undefined); - } - }; - client.on('event', answer(client, first)); - const observer = new AgentClient(manifest); + const observer = new AgentClient(manifest, undefined, () => + Promise.resolve({ address: second.address, dispose: () => undefined }), + ); + const gate = path.join(root, `jdv-handoff-${randomUUID()}`); try { + assert.strictEqual(await client.request('claim', { jdvAddress: first.address }), true); await observer.connect(); - observer.on('event', answer(observer, second)); + assert.strictEqual(observer.control, false); await observer.subscribe(0); const id = await submit( 'controlled <- list(df = data.frame(z = 1:3)); utils::View(controlled$df, "before handoff"); controlled', @@ -1228,29 +1196,45 @@ huge`); ); assert.ok(output); - // The first view after each handoff goes to the new controller, both - // from View() in a cell and from an inline output. - assert.strictEqual(await observer.request('claim', { force: true }), true); - const viewed = randomUUID(); - await observer.request('submit', { - submission: { id: viewed, code: 'utils::View(controlled$df, "after handoff")' }, - }); + const blocking = await submit( + `while (!file.exists(${rString(gate)})) Sys.sleep(0.02); utils::View(controlled$df, "in flight")`, + ); + await until(() => + events.some((event) => event.executionId === blocking && event.type === 'started'), + ); + const viewed = await submit('utils::View(controlled$df, "queued before handoff")'); + assert.strictEqual( + (await client.request('execution', { id: viewed })).state, + 'queued', + ); + + assert.strictEqual(await observer.claim(true), true); + await until(() => !client.control); + fs.writeFileSync(gate, ''); + assert.strictEqual((await finished(blocking)).state, 'success'); + assert.strictEqual(await openedAt('in flight'), 'first'); assert.strictEqual((await finished(viewed)).state, 'success'); - assert.strictEqual(await openedAt('after handoff'), 'second'); + assert.strictEqual(await openedAt('queued before handoff'), 'second'); - assert.strictEqual(await client.request('claim', { force: true }), true); - const reopened = await inspect({ + const reopened = await observer.request('inspect', { method: 'jdv_open_viewer', params: { handle_id: output.data.handleId, path: [{ type: 'index', index: 1 }], - title: 'after handing back', - address: first.address, + title: 'explicit viewer after handoff', + address: second.address, }, }); - assert.strictEqual(reopened as unknown, true); - assert.strictEqual(await openedAt('after handing back'), 'first'); + assert.strictEqual(reopened, true); + assert.strictEqual(await openedAt('explicit viewer after handoff'), 'second'); + assert.ok( + !events.some( + (event) => + event.type === 'clientRequest' && event.data.method === 'jdv/address', + ), + ); } finally { + fs.writeFileSync(gate, ''); observer.close(); first.dispose(); second.dispose(); @@ -3189,6 +3173,7 @@ ggplot(diamonds, aes(x = carat, y = price, color = cut)) + }); let adopted: SessionAgent | undefined; let connection: AgentClient | undefined; + let viewerHost: JdvHost | undefined; try { const endpoint = await new Promise((resolve, reject) => { let buffer = ''; @@ -3292,6 +3277,38 @@ ggplot(diamonds, aes(x = carat, y = price, color = cut)) + ); return id; }; + + const supportsJdv = await completed('cat(sess:::.jdv_supported())'); + if ( + observed.some( + (event) => + event.executionId === supportsJdv && + event.type === 'stream' && + String(event.data.text).includes('TRUE'), + ) + ) { + const opened: unknown[] = []; + viewerHost = await JdvHost.create({ + viewOpen: (_peer, params) => opened.push(params.title), + viewClosed: () => undefined, + viewUpdateFailed: () => undefined, + viewTracking: () => undefined, + disconnected: () => undefined, + }); + assert.strictEqual( + await connection.request('claim', { jdvAddress: viewerHost.address }), + true, + ); + await completed('utils::View(data.frame(a = 1:3), "adopted jdv")'); + await waitFor(() => opened.includes('adopted jdv')); + assert.ok( + !observed.some( + (event) => + event.type === 'clientRequest' && event.data.method === 'jdv/address', + ), + ); + await connection.request('claim'); + } const rich = await completed( 'cat("adopted stdout"); cat("adopted stderr", file=stderr()); head(iris); plot(1:3)', ); @@ -3439,6 +3456,7 @@ lockBinding(".interactive_plot_context", ns) await waitFor(() => child.exitCode !== null || child.signalCode !== null); assert.strictEqual((await connection.snapshot()).manifest.status, 'exited'); } finally { + viewerHost?.dispose(); connection?.close(); await adopted?.close(); child.kill(); From c78811b2dcbd3cf9571d32133a06a98d821b25f4 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Tue, 1 Dec 2026 12:29:42 +0000 Subject: [PATCH 2/2] feat(interactive): push the controller's jdv address to R on lease changes Instead of embedding the listener address in each dispatched cell, the agent sends the current lease's address to R over SessBridge whenever control moves, the listener disconnects or the lease expires, and resends it when sess reconnects. A queued cell is written to arf only after R has acknowledged the latest route. This keeps the address out of arf's command history and gives View() at the adopted console and nested Workspace opens the controller's address between cells. A cell already running during a handoff uses the new address once R has applied it. Claim replies and control-loss notices now carry an agent-issued lease revision so a stale notice cannot dispose the listener of a later successful claim. Restart keeps the listener until its preflight checks pass, and agents that survived an extension update with protocol 1 still get a reply to jdv/address. --- sess/R/handlers.R | 8 +- sess/R/interactive.R | 8 +- sess/R/server.R | 16 +- src/interactive/README.md | 13 +- src/interactive/agent.ts | 70 +++++--- src/interactive/backend.ts | 3 +- src/interactive/backends/arf.ts | 14 +- src/interactive/backends/sessBackend.ts | 17 +- src/interactive/backends/sessBridge.ts | 61 ++++++- src/interactive/client.ts | 84 +++++++-- src/interactive/manager.ts | 31 ++-- src/test/node/interactiveBackend.test.ts | 216 ++++++++++++++++++++--- src/test/node/interactiveRuntime.test.ts | 95 +++++++++- src/test/suite/interactiveEditor.test.ts | 35 ++++ 14 files changed, 564 insertions(+), 107 deletions(-) diff --git a/sess/R/handlers.R b/sess/R/handlers.R index 812a869eb..e9dda83e3 100644 --- a/sess/R/handlers.R +++ b/sess/R/handlers.R @@ -1502,9 +1502,7 @@ handle_dataview_dispose <- function(params) { # viewer should be used instead: jdv is missing, too old or opted out, VS Code # offers no transport, or jdv is already connected elsewhere or owned by an # embedding host. -# Every failure, whether a jdv_error (jdv_error_in_use, jdv_error_connect_failed) -# or the transport request itself failing, means the same fallback, so errors -# are not told apart. +# A connection failure falls back to the sess data viewer. .jdv_connect <- function(address = NULL) { if (identical(getOption("sess.dataviewer", "auto"), "sess") || !.jdv_supported()) { return(FALSE) @@ -1515,7 +1513,9 @@ handle_dataview_dispose <- function(params) { owned <- identical(connection$state, "connected") && is.character(.sess_env$jdv_address) && identical(connection$address, .sess_env$jdv_address) - if (!owned && !identical(connection$state, "disconnected")) { + # jdv_connect() can finish cleaning up a closing transport after its peer + # disconnected. It still refuses a transport that is in use. + if (!owned && !connection$state %in% c("disconnected", "closing")) { return(FALSE) } address <- address %||% .sess_env$attach_jdv[["address"]] diff --git a/sess/R/interactive.R b/sess/R/interactive.R index a2ec5fcbb..9aef118cf 100644 --- a/sess/R/interactive.R +++ b/sess/R/interactive.R @@ -273,7 +273,7 @@ interactive_start <- function(config, managed = FALSE) { #' @param code R code to evaluate in the global environment. #' @param source Optional source-location metadata. #' @keywords internal -interactive_execute <- function(id, code, source = NULL, jdv_address = NULL) { +interactive_execute <- function(id, code, source = NULL) { .sess_env$interactive_skip_task <- TRUE if (!isTRUE(.sess_env$interactive_connected)) { stop("No Interactive agent connected") @@ -288,9 +288,6 @@ interactive_execute <- function(id, code, source = NULL, jdv_address = NULL) { stop("Execution identifier already evaluated; query the agent for its result") } assign(id, TRUE, envir = .sess_env$interactive_seen) - previous_jdv <- .sess_env$attach_jdv - generation <- .sess_env$transport_generation - .sess_env$attach_jdv <- if (.ipc_json_string(jdv_address)) list(address = jdv_address) .sess_env$interactive_id <- id .sess_env$interactive_plot_groups <- integer() on.exit( @@ -298,9 +295,6 @@ interactive_execute <- function(id, code, source = NULL, jdv_address = NULL) { # Live full-table viewers must discard cached filter/sort indices after code # may have edited their data by reference (including failed executions). .sess_env$dataview_revision <- (.sess_env$dataview_revision %||% 0) + 1 - if (identical(generation, .sess_env$transport_generation)) { - .sess_env$attach_jdv <- previous_jdv - } .sess_env$interactive_id <- NULL .interactive_plot_context() }, diff --git a/sess/R/server.R b/sess/R/server.R index f74b44a1a..2b77aff5f 100644 --- a/sess/R/server.R +++ b/sess/R/server.R @@ -197,7 +197,7 @@ connect <- function( return(FALSE) } - .sess_env$attach_jdv <- acknowledgement$jdv + .set_jdv_route(acknowledgement$jdv) if (is.na(use_rstudioapi)) { use_rstudioapi <- TRUE } @@ -521,7 +521,7 @@ connect <- function( settings <- .sess_env$reconnect .sess_env$attaching_generation <- NULL .sess_env$reconnect <- NULL - .sess_env$attach_jdv <- NULL + .set_jdv_route(NULL) .sess_env$con <- NULL .sess_env$transport_generation <- if (is.null(.sess_env$transport_generation)) { 1L @@ -669,6 +669,11 @@ connect <- function( } } +# Both the terminal attach reply and Interactive route updates feed the next open. +.set_jdv_route <- function(jdv) { + .sess_env$attach_jdv <- jdv +} + #' Poll the IPC connection for incoming messages (internal) #' #' Runs as a recurring later callback; dispatches NDJSON messages from vscode. @@ -753,6 +758,13 @@ dispatch_message <- function(line) { "hover" = function(p) handle_hover(p$expr), "completion" = function(p) handle_complete(p$expr, p$trigger), "plot_latest" = function(p) handle_plot_latest(p), + "jdv_route" = function(p) { + if (!is.null(p$address) && !.ipc_json_string(p$address)) { + stop("Invalid jdv listener address") + } + .set_jdv_route(if (!is.null(p$address)) list(address = p$address)) + TRUE + }, "jdv_handle_request" = function(p) handle_jdv_request(p), "jdv_handle_close" = function(p) handle_jdv_handle_close(p), "jdv_open_viewer" = function(p) handle_jdv_open_viewer(p) diff --git a/src/interactive/README.md b/src/interactive/README.md index 03f3ac9ce..4c99bbff4 100644 --- a/src/interactive/README.md +++ b/src/interactive/README.md @@ -68,12 +68,13 @@ R sinks, frontend styling, and forked workers cannot rewrite those frames. A server reply timeout after execution started does not cancel R; its events still establish completion. Other transport failures remain ambiguous without retries. -The editor registers its jdv listener with its control claim. Immediately before -writing a cell to arf, the agent reads the current lease and passes that listener -address to the cell. A queued cell therefore uses the editor that controls the -session at dispatch. A running cell keeps its original address. Control claims -and their addresses are kept in memory, and reconnecting editors claim again. -Explicit Open Data Viewer requests continue to carry their own address. +The editor registers its jdv listener with its control claim. The agent sends the +current lease's address to R over SessBridge and clears it when the lease ends +or the listener disconnects. R acknowledges each update, and the agent waits +for the current acknowledgement before writing a queued cell to arf. Running +cells and console input use the address R has applied when they open a viewer. +A viewer open during handoff may fall back while R is still applying the update. +The route is held in memory and synchronized on sess reconnect. The backend attaches to arf before submitting code. Before running a submission, sess publishes an arf event carrying its ID, so the event's arf execution ID diff --git a/src/interactive/agent.ts b/src/interactive/agent.ts index 1d8ece807..447c0e0f8 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -62,6 +62,8 @@ export class SessionAgent { until: number; jdv?: { socket: net.Socket; address: string }; }; + private leaseRevision = 0; + private leaseTimer?: NodeJS.Timeout; private manifest: SessionManifest; private backend: SessionBackend; private unsubscribe: () => void; @@ -393,6 +395,7 @@ export class SessionAgent { this.clients.delete(client); if (this.lease?.jdv?.socket === socket) { this.lease.jdv = undefined; + this.publishLease(); } if (this.manifest.status === 'exited' && !this.clients.size && !this.stopped) { this.closeAfterExit(true); @@ -401,13 +404,37 @@ export class SessionAgent { }); } + private publishLease(lostClient?: string): void { + const revision = ++this.leaseRevision; + const jdv = this.lease?.jdv; + this.backend.setJdvRoute?.(revision, jdv?.address); + if (lostClient !== undefined) { + for (const client of this.clients) { + if (client.authenticated && client.id === lostClient && !client.socket.destroyed) { + this.send(client.socket, { control: false, leaseRevision: revision }); + } + } + } + } + + private renewLease(): void { + const lease = this.lease!; + lease.until = Date.now() + 60000; + clearTimeout(this.leaseTimer); + this.leaseTimer = setTimeout(() => { + this.lease = undefined; + this.publishLease(lease.client); + }, 60000); + this.leaseTimer.unref(); + } + private requireControl(client: Client): void { if (!this.lease || this.lease.client !== client.id || this.lease.until < Date.now()) { throw new Error( 'This window is observing the session. Take control before changing it.', ); } - this.lease.until = Date.now() + 60000; + this.renewLease(); } private async handleClient(client: Client, request: Record): Promise { @@ -460,7 +487,7 @@ export class SessionAgent { const sameWindow = previous?.client === client.id; this.lease = { client: client.id, - until: Date.now() + 60000, + until: 0, // Helper connections can renew control without replacing the listener. jdv: address !== undefined @@ -469,30 +496,26 @@ export class SessionAgent { ? previous.jdv : undefined, }; - if (previous && !sameWindow) { - for (const other of this.clients) { - if ( - other.authenticated && - other.id === previous.client && - !other.socket.destroyed - ) { - this.send(other.socket, { control: false }); - } - } + this.renewLease(); + if (!sameWindow || this.lease.jdv !== previous?.jdv) { + this.publishLease(sameWindow ? undefined : previous?.client); } - result = true; } else { result = false; } + if (params.leaseRevision === true) { + result = { accepted: result, leaseRevision: this.leaseRevision }; + } break; } case 'heartbeat': - if (this.lease?.client === client.id) { - this.lease.until = Date.now() + 60000; + if (this.lease?.client === client.id && this.lease.until >= Date.now()) { + this.renewLease(); } result = { status: this.manifest.status, - control: this.lease?.client === client.id, + control: this.lease?.client === client.id && this.lease.until >= Date.now(), + leaseRevision: this.leaseRevision, queued: this.queue.length, }; break; @@ -690,9 +713,13 @@ export class SessionAgent { } throw new Error('R is busy; cached data remains available. Retry when idle.'); } + const inspectionParams = object(params.params ?? {}); + if (method === 'jdv_open_viewer') { + delete inspectionParams.address; + } result = await this.backend.inspect({ method, - params: object(params.params ?? {}), + params: inspectionParams, timeout: 5000, }); break; @@ -753,6 +780,8 @@ export class SessionAgent { client.subscribed = false; if (this.lease?.client === client.id) { this.lease = undefined; + clearTimeout(this.leaseTimer); + this.publishLease(client.id); } break; case 'stop': @@ -1128,12 +1157,6 @@ export class SessionAgent { this.dispatchAbort = abort; const attempt = this.backend.dispatch(record, { signal: abort.signal, - jdvAddress: () => { - const lease = this.lease; - return lease?.jdv && lease.until >= Date.now() && !lease.jdv.socket.destroyed - ? lease.jdv.address - : undefined; - }, }); let settled!: () => void; this.dispatchAttempt = new Promise((resolve) => { @@ -1311,6 +1334,7 @@ export class SessionAgent { this.workspaceRefresh.dispose(); this.unsubscribe(); clearTimeout(this.externalTimer); + clearTimeout(this.leaseTimer); clearTimeout(this.redispatchTimer); clearTimeout(this.handleCloseTimer); this.assets.close(); diff --git a/src/interactive/backend.ts b/src/interactive/backend.ts index 2ccc36339..c1b9bba0d 100644 --- a/src/interactive/backend.ts +++ b/src/interactive/backend.ts @@ -74,8 +74,6 @@ export type BackendEvent = ( export interface DispatchOptions { signal?: AbortSignal; - /** Read the controller's address immediately before writing the evaluation. */ - jdvAddress?: () => string | undefined; } export interface SessionBackend { @@ -89,6 +87,7 @@ export interface SessionBackend { * then rejects with {@link DispatchNotSentError}; it has no effect after. */ dispatch(submission: Submission, options?: DispatchOptions): Promise; + setJdvRoute?(revision: number, address?: string): void; inspect(request: InspectionRequest): Promise; replyInput(reply: InputReply): Promise; replyClientRequest(id: string, reply: ClientReply): Promise; diff --git a/src/interactive/backends/arf.ts b/src/interactive/backends/arf.ts index 037f69b74..7554fb598 100644 --- a/src/interactive/backends/arf.ts +++ b/src/interactive/backends/arf.ts @@ -703,7 +703,7 @@ export class Arf { async dispatch( submission: Submission, signal?: AbortSignal, - jdvAddress?: () => string | undefined, + pendingJdvRoute?: (signal?: AbortSignal) => Promise | undefined, ): Promise { if (this.failure) { throw this.failure; @@ -723,6 +723,15 @@ export class Arf { `arf could not be reached: ${error instanceof Error ? error.message : String(error)}`, ); } + try { + let pending = pendingJdvRoute?.(signal); + while (pending) { + await pending; + pending = pendingJdvRoute?.(signal); + } + } catch (error) { + throw new DispatchNotSentError(`jdv route could not be applied: ${String(error)}`); + } if (this.process.adopted && connection.closed) { // The request would be rejected before it is written. throw new DispatchNotSentError( @@ -733,8 +742,7 @@ export class Arf { if (signal?.aborted) { throw new DispatchNotSentError('The code was cancelled before it was sent'); } - const address = jdvAddress?.(); - const code = `sess:::interactive_execute(${rString(submission.id)}, ${rString(submission.code)}, jsonlite::fromJSON(${rString(JSON.stringify(submission.source ?? null))}, simplifyVector=FALSE), ${address ? rString(address) : 'NULL'})`; + const code = `sess:::interactive_execute(${rString(submission.id)}, ${rString(submission.code)}, jsonlite::fromJSON(${rString(JSON.stringify(submission.source ?? null))}, simplifyVector=FALSE))`; this.started = false; this.execution = { submission: submission.id, diff --git a/src/interactive/backends/sessBackend.ts b/src/interactive/backends/sessBackend.ts index 444f1d7e9..834602f28 100644 --- a/src/interactive/backends/sessBackend.ts +++ b/src/interactive/backends/sessBackend.ts @@ -200,6 +200,9 @@ export class SessBackend implements SessionBackend { `${rString(this.options.library)}, ${rString(bootstrap)}, ${support}, managed=${this.ownership === 'managed' ? 'TRUE' : 'FALSE'})`; await this.frontend.bootstrap(code); } + setJdvRoute(revision: number, address?: string): void { + this.bridge.setJdvRoute(revision, address); + } async dispatch(submission: Submission, options?: DispatchOptions): Promise { await this.startup; if (this.closed) { @@ -210,7 +213,9 @@ export class SessBackend implements SessionBackend { this.stderrFlushed = false; this.outputDrained = false; try { - await this.frontend.dispatch(submission, options?.signal, options?.jdvAddress); + await this.frontend.dispatch(submission, options?.signal, (signal) => + this.bridge.pendingJdvRoute(signal), + ); } catch (error) { if (error instanceof DispatchNotSentError) { this.current = undefined; @@ -222,7 +227,15 @@ export class SessBackend implements SessionBackend { this.finish(this.completion); } } - inspect(request: InspectionRequest): Promise { + async inspect(request: InspectionRequest): Promise { + if (request.method === 'workspace_view') { + // Workspace opens can run over arf, independently of the sess socket. + let pending = this.bridge.pendingJdvRoute(); + while (pending) { + await pending; + pending = this.bridge.pendingJdvRoute(); + } + } // An adopted session that does not publish the handlers keeps the socket, // as do the methods that are never published. return this.frontend.callsInspection() && !socketInspectionMethod(request.method) diff --git a/src/interactive/backends/sessBridge.ts b/src/interactive/backends/sessBridge.ts index e4eee5510..9f46fbddf 100644 --- a/src/interactive/backends/sessBridge.ts +++ b/src/interactive/backends/sessBridge.ts @@ -28,6 +28,9 @@ export class SessBridge { { socket: net.Socket; id: unknown; timer: NodeJS.Timeout } >(); private counter = 0; + private jdvRoute?: { revision: number; address?: string }; + private appliedJdvRevision?: number; + private applyingJdvRoute?: Promise; private closed = false; constructor( private directory: string, @@ -131,10 +134,12 @@ export class SessBridge { return; } socket.write(acknowledgeSessAttach(id)); + this.sess = socket; + this.appliedJdvRevision = undefined; + this.pushJdvRoute(); if (sessionId) { return; } - this.sess = socket; sessionId = requestedSession; this.emit({ type: 'metadata', @@ -197,6 +202,8 @@ export class SessBridge { return; } this.sess = undefined; + this.appliedJdvRevision = undefined; + this.applyingJdvRoute = undefined; this.rejectPending(); for (const [id, request] of this.requests) { clearTimeout(request.timer); @@ -210,6 +217,58 @@ export class SessBridge { } }); } + setJdvRoute(revision: number, address?: string): void { + this.jdvRoute = { revision, address }; + this.pushJdvRoute(); + } + + private pushJdvRoute(): void { + const route = this.jdvRoute; + if (!this.sess || !route) { + return; + } + const applying = this.request('jdv_route', route).then((applied) => { + if (applied !== true) { + throw new Error('R did not acknowledge the jdv route'); + } + if (this.applyingJdvRoute === applying) { + this.appliedJdvRevision = route.revision; + } + }); + this.applyingJdvRoute = applying; + void applying.catch(() => { + if (this.applyingJdvRoute === applying) { + this.applyingJdvRoute = undefined; + } + }); + } + + pendingJdvRoute(signal?: AbortSignal): Promise | undefined { + if (!this.jdvRoute || this.appliedJdvRevision === this.jdvRoute.revision) { + return; + } + if (signal?.aborted) { + return Promise.reject(new Error('Dispatch cancelled')); + } + if (!this.applyingJdvRoute) { + this.pushJdvRoute(); + } + const applying = this.applyingJdvRoute; + if (!applying) { + return Promise.reject(new Error('R session is disconnected')); + } + if (!signal) { + return applying; + } + return new Promise((resolve, reject) => { + const abort = () => reject(new Error('Dispatch cancelled')); + signal.addEventListener('abort', abort, { once: true }); + void applying.then(resolve, reject).finally(() => { + signal.removeEventListener('abort', abort); + }); + }); + } + request(method: string, params: Record, timeout = 10000): Promise { const socket = this.sess; if (this.closed || !socket || socket.destroyed) { diff --git a/src/interactive/client.ts b/src/interactive/client.ts index b73e03d70..ba4ca4d94 100644 --- a/src/interactive/client.ts +++ b/src/interactive/client.ts @@ -19,8 +19,17 @@ export class AgentClient extends EventEmitter { private incomingPageBytes = 0; private closing = false; private ready = false; - private controlRevision = 0; + private legacyControlRevision = 0; + private leaseRevision = -1; + private claimAttempt?: Promise; + get claimingControl(): boolean { + return this.claimAttempt !== undefined; + } control = false; + get usesLeaseRevisions(): boolean { + return this.leaseRevision >= 0; + } + get connected(): boolean { return this.ready && this.socket !== undefined && !this.socket.destroyed; } @@ -39,6 +48,8 @@ export class AgentClient extends EventEmitter { async connect(options: { claim?: boolean; timeout?: number } = {}): Promise { this.close(); this.eventDelivery = Promise.resolve(); + this.legacyControlRevision = 0; + this.leaseRevision = -1; this.closing = false; const socket = net.createConnection(this.manifest.endpoint); this.socket = socket; @@ -78,8 +89,10 @@ export class AgentClient extends EventEmitter { return; } if (message.control === false && this.socket === socket) { - this.controlRevision++; - this.control = false; + if (typeof message.leaseRevision !== 'number') { + this.legacyControlRevision++; + } + this.applyControl(false, message.leaseRevision); this.emit('activity'); return; } @@ -195,14 +208,21 @@ export class AgentClient extends EventEmitter { this.assertConnection(socket); this.ready = true; this.heartbeat = setInterval(() => { - const revision = this.controlRevision; - void this.request<{ control: boolean; status: SessionManifest['status'] }>('heartbeat') + const legacyRevision = this.legacyControlRevision; + void this.request<{ + control: boolean; + status: SessionManifest['status']; + leaseRevision?: number; + }>('heartbeat') .then((value) => { if (this.socket !== socket || socket.destroyed) { return; } - if (revision === this.controlRevision) { - this.control = value.control; + if ( + value.leaseRevision !== undefined || + legacyRevision === this.legacyControlRevision + ) { + this.applyControl(value.control, value.leaseRevision); } this.manifest.status = value.status; this.emit('activity'); @@ -213,25 +233,57 @@ export class AgentClient extends EventEmitter { this.emit('activity'); } + private applyControl(control: boolean, revision: unknown): boolean { + if (typeof revision === 'number') { + if (revision < this.leaseRevision) { + return false; + } + this.leaseRevision = revision; + } + this.control = control; + return true; + } + async claim(force = false, timeout?: number): Promise { const socket = this.socket; if (!socket || socket.destroyed) { throw new Error('Session agent is disconnected'); } + while (this.claimAttempt) { + await this.claimAttempt.catch(() => undefined); + this.assertConnection(socket); + } + const attempt = this.claimOnSocket(socket, force, timeout); + this.claimAttempt = attempt; + try { + return await attempt; + } finally { + this.claimAttempt = undefined; + this.emit('activity'); + } + } + + private async claimOnSocket( + socket: net.Socket, + force: boolean, + timeout?: number, + ): Promise { const listener = await this.jdvListener?.(this.manifest).catch(() => undefined); let claimed = false; try { this.assertConnection(socket); - const revision = this.controlRevision; - const accepted = await this.request( - 'claim', - { force, jdvAddress: listener?.address }, - timeout, - ); + const legacyRevision = this.legacyControlRevision; + const result = await this.request< + boolean | { accepted: boolean; leaseRevision: number } + >('claim', { force, jdvAddress: listener?.address, leaseRevision: true }, timeout); this.assertConnection(socket); - claimed = accepted && revision === this.controlRevision; - this.control = claimed; - this.emit('activity'); + if (typeof result === 'boolean') { + claimed = result && legacyRevision === this.legacyControlRevision; + this.control = claimed; + } else { + claimed = + this.applyControl(result.accepted, result.leaseRevision) && result.accepted; + } return claimed; } finally { if (!claimed) { diff --git a/src/interactive/manager.ts b/src/interactive/manager.ts index bfb3d7709..d44662872 100644 --- a/src/interactive/manager.ts +++ b/src/interactive/manager.ts @@ -1842,10 +1842,13 @@ export class InteractiveManager return; } const hasControl = client.control; - disposeInteractiveJdvHostOnControlLoss(hadControl, hasControl, () => - disposeJdvHost(hostKey), - ); - hadControl = hasControl; + // A queued loss notice can precede a successful claim on this socket. + if (!client.claimingControl) { + disposeInteractiveJdvHostOnControlLoss(hadControl, hasControl, () => + disposeJdvHost(hostKey), + ); + hadControl = hasControl; + } this.updateStatus(); this.changes.fire(undefined); }); @@ -2720,7 +2723,11 @@ export class InteractiveManager const client = view.client; const params = object(data.params ?? {}); try { - const result = await session.handleEditorRequest(String(data.method), params); + // Protocol 1 agents already running before the extension update still ask R's client. + const result = + data.method === 'jdv/address' + ? { address: await this.jdvAddress(view) } + : await session.handleEditorRequest(String(data.method), params); await client.request('clientReply', { id: data.id, result }); } catch (error) { await client @@ -2782,10 +2789,10 @@ export class InteractiveManager path: unknown[], title: string, ): Promise { - // R cannot wait for a reply to its own request while answering this inspection, - // so the listener address is handed over instead of being requested. - const address = await this.jdvAddress(view); - const opened = await view.client.request('inspect', { + const client = view.client; + // Existing protocol 1 agents still need an address on explicit opens. + const address = client.usesLeaseRevisions ? undefined : await this.jdvAddress(view); + const opened = await client.request('inspect', { method: 'jdv_open_viewer', params: { handle_id: data.handleId, path, title, address }, }); @@ -3436,9 +3443,6 @@ export class InteractiveManager if (answer !== 'Restart Session' || view.disposed) { return; } - disposeJdvHost( - interactiveJdvHostKey(view.client.manifest.id, view.client.manifest.generation), - ); const storage = path.join(this.root, view.client.manifest.id); let config = JSON.parse( fs.readFileSync(path.join(storage, 'config.json'), 'utf8'), @@ -3522,6 +3526,9 @@ export class InteractiveManager } else if (view.client.manifest.status !== 'exited') { throw new Error('Reconnect to the R session before restarting it.'); } + disposeJdvHost( + interactiveJdvHostKey(view.client.manifest.id, view.client.manifest.generation), + ); await view.chain; await view.outputQueue.flush(); for (const { task } of view.executions.values()) { diff --git a/src/test/node/interactiveBackend.test.ts b/src/test/node/interactiveBackend.test.ts index 4c4fa9672..9a731abae 100644 --- a/src/test/node/interactiveBackend.test.ts +++ b/src/test/node/interactiveBackend.test.ts @@ -5,8 +5,13 @@ import * as path from 'path'; import { randomUUID } from 'crypto'; import { createServer } from 'http'; import * as net from 'net'; +import * as sinon from 'sinon'; import { spawn } from 'child_process'; import { localEndpoint } from '../../interactive/transport'; +import { JsonLines } from '../../interactive/framing'; +import { SESS_PROTOCOL_VERSION } from '../../sessProtocol'; +import { SessBridge } from '../../interactive/backends/sessBridge'; +import { disposeInteractiveJdvHostOnControlLoss } from '../../interactive/jdvAddress'; import { SessionAgent } from '../../interactive/agent'; import { AgentClient } from '../../interactive/client'; import { readSessionManifest } from '../../interactive/launcher'; @@ -40,6 +45,16 @@ import { ARF_METHOD_NOT_FOUND, ArfRpcError } from '../../interactive/arf'; import { INSPECTION_SELECTORS, inspectionFailure } from '../../interactive/backends/arfInspection'; import { SessBackend } from '../../interactive/backends/sessBackend'; +async function until(predicate: () => boolean): Promise { + const deadline = Date.now() + 3000; + while (!predicate()) { + if (Date.now() > deadline) { + throw new Error('Timed out waiting for backend event'); + } + await new Promise((resolve) => setTimeout(resolve, 5)); + } +} + class FakeBackend implements SessionBackend { readonly ownership = 'managed' as const; readonly capabilities = { inspection: true, interrupt: true, restart: true, stdin: true }; @@ -72,11 +87,13 @@ class FakeBackend implements SessionBackend { } /** The cancellation signal of the latest dispatch. */ signal?: AbortSignal; - jdvAddress?: () => string | undefined; + jdvAddress?: string; + setJdvRoute(_revision: number, address?: string): void { + this.jdvAddress = address; + } dispatch(submission: Submission, options?: DispatchOptions): Promise { this.submissions.push(submission); this.signal = options?.signal; - this.jdvAddress = options?.jdvAddress; return this.dispatchResult(); } inspect(request: InspectionRequest): Promise { @@ -188,15 +205,6 @@ suite('Interactive backend contract', function () { await agent?.close(); fs.rmSync(root, { recursive: true, force: true }); }); - async function until(predicate: () => boolean): Promise { - const deadline = Date.now() + 3000; - while (!predicate()) { - if (Date.now() > deadline) { - throw new Error('Timed out waiting for backend event'); - } - await new Promise((resolve) => setTimeout(resolve, 5)); - } - } async function submit(): Promise { const id = randomUUID(); await client.request('submit', { submission: { id, code: 'side_effect()' } }); @@ -925,7 +933,7 @@ suite('Interactive backend contract', function () { next.close(); } }); - test('dispatch reads the address of the live lease without persisting it', async () => { + test('pushes the live lease address without persisting it', async () => { const firstAddress = '/tmp/first-jdv.sock'; const nextAddress = '/tmp/next-jdv.sock'; let released = 0; @@ -944,25 +952,25 @@ suite('Interactive backend contract', function () { assert.strictEqual(released, 1); const id = await submit(); await until(() => backend.jdvAddress !== undefined); - assert.strictEqual(backend.jdvAddress?.(), firstAddress); + assert.strictEqual(backend.jdvAddress, firstAddress); // arf can still be opening its connection when ownership changes. assert.strictEqual(await next.claim(true), true); await until(() => !client.control); - assert.strictEqual(backend.jdvAddress?.(), nextAddress); + assert.strictEqual(backend.jdvAddress, nextAddress); const { manifest } = await next.snapshot(); assert.ok(!JSON.stringify(manifest).includes(nextAddress)); assert.ok(!JSON.stringify(await record(id)).includes(firstAddress)); assert.ok(!JSON.stringify(await record(id)).includes(nextAddress)); next.close(); - await until(() => backend.jdvAddress?.() === undefined); + await until(() => backend.jdvAddress === undefined); } finally { next.close(); } }); - test('shares control by client ID and dispatches to the last registered listener', async () => { + test('shares control by client ID and publishes the last registered listener', async () => { const first = '/tmp/first-jdv.sock'; const second = '/tmp/second-jdv.sock'; const helper = new AgentClient(client.manifest, client.clientId); @@ -977,23 +985,23 @@ suite('Interactive backend contract', function () { assert.strictEqual(await helper.claim(), true); await submit(); await until(() => backend.jdvAddress !== undefined); - assert.strictEqual(backend.jdvAddress?.(), first); + assert.strictEqual(backend.jdvAddress, first); assert.strictEqual(client.control, true); assert.strictEqual(await helper.request('claim', { jdvAddress: second }), true); - assert.strictEqual(backend.jdvAddress?.(), second); + assert.strictEqual(backend.jdvAddress, second); assert.strictEqual(client.control, true); await helper.request('detach'); assert.strictEqual( (await client.request<{ control: boolean }>('heartbeat')).control, false, ); - assert.strictEqual(backend.jdvAddress?.(), undefined); + assert.strictEqual(backend.jdvAddress, undefined); await client.claim(); assert.strictEqual(await helper.request('claim', { jdvAddress: second }), true); helper.close(); - await until(() => backend.jdvAddress?.() === undefined); + await until(() => backend.jdvAddress === undefined); assert.strictEqual( (await client.request<{ control: boolean }>('heartbeat')).control, true, @@ -1003,13 +1011,89 @@ suite('Interactive backend contract', function () { await other.connect({ claim: false }); assert.strictEqual(await other.claim(true), true); await until(() => !client.control && !helper.control); - assert.strictEqual(backend.jdvAddress?.(), undefined); + assert.strictEqual(backend.jdvAddress, undefined); } finally { helper.close(); other.close(); } }); + test('clears the jdv route when the lease expires without more client requests', async () => { + const clock = sinon.useFakeTimers({ + toFake: ['Date', 'setTimeout', 'clearTimeout'], + shouldClearNativeTimers: true, + }); + try { + const address = '/tmp/expires-jdv.sock'; + assert.strictEqual(await client.request('claim', { jdvAddress: address }), true); + assert.strictEqual(backend.jdvAddress, address); + await clock.tickAsync(60001); + assert.strictEqual(backend.jdvAddress, undefined); + } finally { + clock.restore(); + } + await until(() => !client.control); + }); + + for (const lossFirst of [true, false]) { + test(`keeps the listener for the newest lease when control loss is delivered ${lossFirst ? 'before' : 'after'} claim success`, async () => { + const otherAddress = '/tmp/other-jdv.sock'; + const candidateAddress = '/tmp/candidate-jdv.sock'; + let disposed = false; + const dispose = () => { + disposed = true; + }; + const candidate = new AgentClient(client.manifest, undefined, () => + Promise.resolve({ address: candidateAddress, dispose }), + ); + const other = new AgentClient(client.manifest); + try { + await candidate.connect(); + assert.strictEqual(await candidate.claim(true), true); + disposed = false; + let hadControl = candidate.control; + candidate.on('activity', () => { + if (!candidate.claimingControl) { + disposeInteractiveJdvHostOnControlLoss( + hadControl, + candidate.control, + dispose, + ); + hadControl = candidate.control; + } + }); + await other.connect({ claim: false }); + await candidate.request('claim', { force: true, jdvAddress: '/tmp/old-jdv.sock' }); + const { socket } = candidate as unknown as { socket: net.Socket }; + socket.pause(); + const takeOther = () => + other.request('claim', { force: true, jdvAddress: otherAddress }); + if (lossFirst) { + await takeOther(); + } + const leaseAddress = () => + (agent as unknown as { lease?: { jdv?: { address: string } } }).lease?.jdv + ?.address; + const claim = candidate.claim(true); + // The agent has processed the claim while A's replies are held. + await until(() => leaseAddress() === candidateAddress); + if (!lossFirst) { + await takeOther(); + } + socket.resume(); + const claimed = await claim; + if (lossFirst) { + assert.strictEqual(claimed, true); + } + await until(() => candidate.control === lossFirst && disposed === !lossFirst); + assert.strictEqual(leaseAddress(), lossFirst ? candidateAddress : otherAddress); + } finally { + candidate.close(); + other.close(); + } + }); + } + test('observer requests and stale generations cannot invoke the backend', async () => { const observer = new AgentClient(client.manifest); await observer.connect(); @@ -2000,6 +2084,96 @@ suite('Interactive backend contract', function () { await session.close(); } }); + test('waits for the latest jdv route before writing to arf and resends on sess reconnect', async () => { + const session = await adopt({}); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'r-jdv-route-')); + let disconnected = false; + const bridge = new SessBridge( + directory, + 'route-test', + (event) => { + disconnected ||= event.type === 'unavailable'; + }, + () => {}, + () => {}, + ); + const sockets: net.Socket[] = []; + const attach = () => { + const socket = net.createConnection(bridge.endpoint); + sockets.push(socket); + const messages: Record[] = []; + const parser = new JsonLines((message) => messages.push(message)); + socket.on('data', (chunk: Buffer) => parser.push(chunk)); + const send = (message: Record) => + socket.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n'); + send({ + id: 'attach', + method: 'attach', + params: { + protocol_version: SESS_PROTOCOL_VERSION, + interactive_token: 'route-test', + session_id: 'r', + }, + }); + return { + socket, + messages, + ack: (request: Record) => send({ id: request.id, result: true }), + }; + }; + const evaluations = () => + session.methods.filter((method) => method.endsWith('evaluate')).length; + try { + await bridge.start(); + bridge.setJdvRoute(1, '/tmp/first.sock'); + const r = attach(); + await until(() => r.messages.length === 2); + assert.deepStrictEqual(r.messages[1]?.params, { + revision: 1, + address: '/tmp/first.sock', + }); + const before = evaluations(); + let checkedRoute = 0; + const submitted = session.adapter.dispatch( + { id: randomUUID(), code: 'queued()' }, + undefined, + () => { + checkedRoute++; + return bridge.pendingJdvRoute(); + }, + ); + await until(() => checkedRoute === 1); + bridge.setJdvRoute(2, '/tmp/second.sock'); + await until(() => r.messages.length === 3); + r.ack(r.messages[1]); + await until(() => checkedRoute === 2); + assert.strictEqual(evaluations(), before); + r.ack(r.messages[2]); + await submitted; + assert.strictEqual(evaluations(), before + 1); + + bridge.setJdvRoute(3); + await until(() => r.messages.length === 4); + assert.deepStrictEqual(r.messages[3]?.params, { revision: 3 }); + r.ack(r.messages[3]); + await bridge.pendingJdvRoute(); + r.socket.destroy(); + await until(() => disconnected); + const reconnected = attach(); + await until(() => reconnected.messages.length === 2); + assert.deepStrictEqual(reconnected.messages[1]?.params, { revision: 3 }); + reconnected.ack(reconnected.messages[1]); + await bridge.pendingJdvRoute(); + } finally { + for (const socket of sockets) { + socket.destroy(); + } + bridge.dispose(); + fs.rmSync(directory, { recursive: true, force: true }); + await session.close(); + } + }); + test('an adopted execution is interrupted on the connection that started it', async () => { const session = await adopt({}, undefined, (method) => method === 'evaluate' ? { result: { status: 'ok', execution_id: 7 } } : undefined, diff --git a/src/test/node/interactiveRuntime.test.ts b/src/test/node/interactiveRuntime.test.ts index 3afea8fc6..4861f291c 100644 --- a/src/test/node/interactiveRuntime.test.ts +++ b/src/test/node/interactiveRuntime.test.ts @@ -5,6 +5,8 @@ import * as path from 'path'; import { execFile, spawn } from 'child_process'; import { promisify, stripVTControlCharacters } from 'util'; import { randomUUID } from 'crypto'; +import { DatabaseSync } from 'node:sqlite'; +import { disposeInteractiveJdvHostOnControlLoss } from '../../interactive/jdvAddress'; import { arfRequest, discoverArf, probeArfSession } from '../../interactive/arf'; import { SessionAgent } from '../../interactive/agentMain'; import { AgentClient } from '../../interactive/client'; @@ -45,6 +47,7 @@ suite('Interactive real R runtime', function () { let client: AgentClient; let manifest: SessionManifest; let events: SessionEvent[]; + let historyDirectory: string; suiteSetup(async () => { temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'r-interactive-runtime-')); @@ -100,7 +103,18 @@ suite('Interactive real R runtime', function () { maxJournalBytes: 16 * 1024 * 1024, }; agent = new SessionAgent(config); - manifest = await agent.start(); + historyDirectory = path.join(temporary, 'arf-history', id); + const previousHistoryDirectory = process.env.ARF_HISTORY_DIR; + process.env.ARF_HISTORY_DIR = historyDirectory; + try { + manifest = await agent.start(); + } finally { + if (previousHistoryDirectory === undefined) { + delete process.env.ARF_HISTORY_DIR; + } else { + process.env.ARF_HISTORY_DIR = previousHistoryDirectory; + } + } client = new AgentClient(manifest); await client.connect(); client.on('event', (event: SessionEvent) => events.push(event)); @@ -866,7 +880,6 @@ sess::display("display-${cell}", "text/plain"); cat("stderr-${cell}\\n", file=st view: params.view, generation: params.generation, nrow: 3, - address: host.address, }); } const page = await peer.requestWithBody('stream/next', { @@ -1127,6 +1140,7 @@ huge`); disconnected: () => undefined, }); try { + assert.strictEqual(await client.request('claim', { jdvAddress: host.address }), true); const id = await submit('opened <- list(a=1, df=data.frame(z=1:3)); opened'); assert.strictEqual((await finished(id)).state, 'success'); const output = events.find( @@ -1139,7 +1153,6 @@ huge`); handle_id: output.data.handleId, path: [{ type: 'index', index: 2 }], title: 'Cell: List$df', - address: host.address, }, }); assert.strictEqual(viewer as unknown, true); @@ -1181,6 +1194,14 @@ huge`); Promise.resolve({ address: second.address, dispose: () => undefined }), ); const gate = path.join(root, `jdv-handoff-${randomUUID()}`); + let hadControl = client.control; + const disposeOnControlLoss = () => { + disposeInteractiveJdvHostOnControlLoss(hadControl, client.control, () => + first.dispose(), + ); + hadControl = client.control; + }; + client.on('activity', disposeOnControlLoss); try { assert.strictEqual(await client.request('claim', { jdvAddress: first.address }), true); await observer.connect(); @@ -1197,7 +1218,15 @@ huge`); assert.ok(output); const blocking = await submit( - `while (!file.exists(${rString(gate)})) Sys.sleep(0.02); utils::View(controlled$df, "in flight")`, + `local({ + previous <- sess:::.sess_env$attach_jdv + while (!file.exists(${rString(gate)})) Sys.sleep(0.02) + deadline <- Sys.time() + 2 + while (identical(previous, sess:::.sess_env$attach_jdv) && Sys.time() < deadline) { + later::run_now(0.02) + } + utils::View(controlled$df, "in flight") + })`, ); await until(() => events.some((event) => event.executionId === blocking && event.type === 'started'), @@ -1212,7 +1241,7 @@ huge`); await until(() => !client.control); fs.writeFileSync(gate, ''); assert.strictEqual((await finished(blocking)).state, 'success'); - assert.strictEqual(await openedAt('in flight'), 'first'); + assert.strictEqual(await openedAt('in flight'), 'second'); assert.strictEqual((await finished(viewed)).state, 'success'); assert.strictEqual(await openedAt('queued before handoff'), 'second'); @@ -1222,11 +1251,18 @@ huge`); handle_id: output.data.handleId, path: [{ type: 'index', index: 1 }], title: 'explicit viewer after handoff', - address: second.address, }, }); assert.strictEqual(reopened, true); assert.strictEqual(await openedAt('explicit viewer after handoff'), 'second'); + assert.strictEqual( + await observer.request('inspect', { + method: 'workspace_view', + params: { name: 'controlled', path: [{ kind: 'index', value: 1, name: 'df' }] }, + }), + true, + ); + assert.strictEqual(await openedAt('controlled$df'), 'second'); assert.ok( !events.some( (event) => @@ -1235,12 +1271,51 @@ huge`); ); } finally { fs.writeFileSync(gate, ''); + client.off('activity', disposeOnControlLoss); observer.close(); first.dispose(); second.dispose(); } }); + test('keeps the jdv listener address out of the managed arf history database', async () => { + const host = await JdvHost.create({ + viewOpen: () => undefined, + viewClosed: () => undefined, + viewUpdateFailed: () => undefined, + viewTracking: () => undefined, + disconnected: () => undefined, + }); + try { + assert.strictEqual(await client.request('claim', { jdvAddress: host.address }), true); + const code = 'cat("history route regression")'; + assert.strictEqual((await finished(await submit(code))).state, 'success'); + await client.request('stop'); + const history = new DatabaseSync(path.join(historyDirectory, 'r.db'), { + readOnly: true, + }); + try { + const commands = history.prepare('SELECT command_line FROM history').all(); + assert.ok( + commands.some( + ({ command_line }) => + String(command_line).includes('sess:::interactive_execute') && + String(command_line).includes('history route regression'), + ), + 'arf should have written the dispatched wrapper to history', + ); + for (const { command_line } of commands) { + assert.ok(!String(command_line).includes(host.address)); + assert.ok(!String(command_line).includes('vscr-jdv-')); + } + } finally { + history.close(); + } + } finally { + host.dispose(); + } + }); + test('opens nested and root jdv handles without dispatching list subsetting methods', async function () { if (!(await jdvAvailable())) { this.skip(); @@ -1257,6 +1332,7 @@ huge`); disconnected: () => undefined, }); try { + assert.strictEqual(await client.request('claim', { jdvAddress: host.address }), true); const id = await submit( '`[[.review_list` <- function(x, i, ...) stop("review_list [[ called"); review <- structure(list(table=data.frame(z=1:3)), class="review_list"); outer <- list(review=review); outer', ); @@ -1276,7 +1352,6 @@ huge`); { type: 'index', index: 1 }, ], title: 'Cell: List$review$table', - address: host.address, }, }); assert.strictEqual(nested as unknown, true); @@ -1294,7 +1369,6 @@ huge`); handle_id: output.data.handleId, path: [], title: 'Interactive root', - address: host.address, }, }); assert.strictEqual(root as unknown, true); @@ -3301,6 +3375,11 @@ ggplot(diamonds, aes(x = carat, y = price, color = cut)) + ); await completed('utils::View(data.frame(a = 1:3), "adopted jdv")'); await waitFor(() => opened.includes('adopted jdv')); + await arfRequest(endpoint, 'evaluate', { + code: 'utils::View(data.frame(a = 1:3), "adopted outside a cell")', + visible: true, + }); + await waitFor(() => opened.includes('adopted outside a cell')); assert.ok( !observed.some( (event) => diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index d723b5168..7d02ff227 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -1883,6 +1883,29 @@ suite('Interactive VS Code integration', function () { listener.dispose(); } }); + test('answers jdv/address from an existing protocol 1 Interactive session', async () => { + const manifest = manifests[0]; + await vscode.commands.executeCommand('r.interactive.open', manifest); + const manager = interactiveManager() as unknown as { + views: Map; + clientRequest( + view: { client: AgentClient }, + data: Record, + ): Promise; + }; + const view = manager.views.get(`${manifest.id}:${manifest.generation}`); + assert.ok(view?.client.control); + const request = sinon.stub(view.client, 'request'); + const reply = request.withArgs('clientReply').resolves(); + try { + await manager.clientRequest(view, { id: 1, method: 'jdv/address' }); + sinon.assert.calledOnce(reply); + const [, response] = reply.firstCall.args; + assert.ok((response?.result as { address?: string } | undefined)?.address); + } finally { + request.restore(); + } + }); test('observer execution consistently reports errors from native input, cells and source commands', async () => { await vscode.commands.executeCommand('r.interactive.open', manifests[0]); const manager = interactiveManager() as InteractiveManager; @@ -5194,9 +5217,21 @@ par(mfrow=c(1,1))`, path.join(root, 'missing-restart-node'), vscode.ConfigurationTarget.Global, ); + const manager = interactiveManager() as unknown as { + views: Map; + jdvAddress(view: { client: AgentClient }): Promise; + }; + const view = manager.views.get(`${original.id}:${original.generation}`); + assert.ok(view); + const listenerBeforePreflight = await manager.jdvAddress(view); await restartPhase('missing Node override', () => vscode.commands.executeCommand('r.interactive.restart', notebook.uri), ); + assert.strictEqual( + await manager.jdvAddress(view), + listenerBeforePreflight, + 'Restart preflight must preserve the registered jdv listener', + ); sinon.assert.calledOnce(interactiveErrors); assert.match(interactiveErrors.firstCall.args[0], /r\.interactive\.nodePath/); assert.strictEqual(notebook.cellCount, oldCount);