diff --git a/sess/R/handlers.R b/sess/R/handlers.R index e0a212c8d..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,20 +1513,12 @@ 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) } - 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/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/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..4c99bbff4 100644 --- a/src/interactive/README.md +++ b/src/interactive/README.md @@ -68,6 +68,14 @@ 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. 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 identifies that submission; a managed `user_input` acknowledgement reports the diff --git a/src/interactive/agent.ts b/src/interactive/agent.ts index 919aede42..447c0e0f8 100644 --- a/src/interactive/agent.ts +++ b/src/interactive/agent.ts @@ -57,7 +57,13 @@ 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 leaseRevision = 0; + private leaseTimer?: NodeJS.Timeout; private manifest: SessionManifest; private backend: SessionBackend; private unsubscribe: () => void; @@ -387,6 +393,10 @@ export class SessionAgent { socket.on('close', () => { clearTimeout(authTimer); 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); } @@ -394,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 { @@ -432,32 +466,56 @@ 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 }; - result = true; + 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: 0, + // Helper connections can renew control without replacing the listener. + jdv: + address !== undefined + ? { socket: client.socket, address } + : sameWindow + ? previous.jdv + : undefined, + }; + this.renewLease(); + if (!sameWindow || this.lease.jdv !== previous?.jdv) { + this.publishLease(sameWindow ? undefined : previous?.client); + } } 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; @@ -655,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; @@ -718,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': @@ -1091,7 +1155,9 @@ 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, + }); let settled!: () => void; this.dispatchAttempt = new Promise((resolve) => { settled = resolve; @@ -1268,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 6e2283cf8..c1b9bba0d 100644 --- a/src/interactive/backend.ts +++ b/src/interactive/backend.ts @@ -72,6 +72,10 @@ export type BackendEvent = ( | { type: 'exit'; code?: number | null; signal?: string | null } ) & { executionId?: string }; +export interface DispatchOptions { + signal?: AbortSignal; +} + export interface SessionBackend { readonly ownership: BackendOwnership; readonly capabilities: BackendCapabilities; @@ -82,7 +86,8 @@ 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; + 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 241bd97f1..7554fb598 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, + pendingJdvRoute?: (signal?: AbortSignal) => Promise | undefined, + ): Promise { if (this.failure) { throw this.failure; } @@ -719,17 +723,26 @@ 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( `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 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 8fa94718b..834602f28 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,10 @@ 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 { + setJdvRoute(revision: number, address?: string): void { + this.bridge.setJdvRoute(revision, address); + } + async dispatch(submission: Submission, options?: DispatchOptions): Promise { await this.startup; if (this.closed) { throw new Error('Backend is disposed'); @@ -209,7 +213,9 @@ 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, (signal) => + this.bridge.pendingJdvRoute(signal), + ); } catch (error) { if (error instanceof DispatchNotSentError) { this.current = undefined; @@ -221,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 833767ad5..ba4ca4d94 100644 --- a/src/interactive/client.ts +++ b/src/interactive/client.ts @@ -19,7 +19,17 @@ export class AgentClient extends EventEmitter { private incomingPageBytes = 0; private closing = false; private ready = false; + 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; } @@ -27,6 +37,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(); } @@ -34,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; @@ -72,6 +88,14 @@ export class AgentClient extends EventEmitter { }); return; } + if (message.control === false && this.socket === socket) { + if (typeof message.leaseRevision !== 'number') { + this.legacyControlRevision++; + } + this.applyControl(false, message.leaseRevision); + this.emit('activity'); + return; + } const id = Number(message.id); const pending = this.pending.get(id); if (!pending) { @@ -178,20 +202,28 @@ 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(() => { - 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; } - 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'); }) @@ -201,6 +233,65 @@ 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 legacyRevision = this.legacyControlRevision; + const result = await this.request< + boolean | { accepted: boolean; leaseRevision: number } + >('claim', { force, jdvAddress: listener?.address, leaseRevision: true }, timeout); + this.assertConnection(socket); + 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) { + 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..d44662872 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( @@ -1824,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); }); @@ -2702,12 +2723,11 @@ 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); - } + // 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 @@ -2769,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 }, }); @@ -3423,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'), @@ -3509,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()) { @@ -3525,7 +3545,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..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'; @@ -22,6 +27,7 @@ import { BackendEvent, ClientReply, DispatchNotSentError, + type DispatchOptions, InspectionRequest, SessionBackend, StopRefusedError, @@ -39,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 }; @@ -71,7 +87,11 @@ class FakeBackend implements SessionBackend { } /** The cancellation signal of the latest dispatch. */ signal?: AbortSignal; - dispatch(submission: Submission, options?: { signal?: AbortSignal }): Promise { + 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; return this.dispatchResult(); @@ -185,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()' } }); @@ -582,6 +593,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 +933,167 @@ suite('Interactive backend contract', function () { next.close(); } }); + 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; + 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 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); + 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('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(); @@ -1899,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 e83278b7b..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)); @@ -211,21 +225,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 +292,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 +860,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))'; @@ -887,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', { @@ -899,7 +891,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(); } }); @@ -1148,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( @@ -1160,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); @@ -1198,25 +1190,22 @@ 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()}`); + 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(); - 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,35 +1217,105 @@ 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( + `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'), + ); + 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'), 'second'); 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', }, }); - 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.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) => + event.type === 'clientRequest' && event.data.method === 'jdv/address', + ), + ); } 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(); @@ -1273,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', ); @@ -1292,7 +1352,6 @@ huge`); { type: 'index', index: 1 }, ], title: 'Cell: List$review$table', - address: host.address, }, }); assert.strictEqual(nested as unknown, true); @@ -1310,7 +1369,6 @@ huge`); handle_id: output.data.handleId, path: [], title: 'Interactive root', - address: host.address, }, }); assert.strictEqual(root as unknown, true); @@ -3189,6 +3247,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 +3351,43 @@ 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')); + 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) => + 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 +3535,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(); 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);