Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 5 additions & 15 deletions sess/R/handlers.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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"]]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Provide the controller’s address for View() outside a dispatched cell. The bridge acknowledges with jdv = NULL, and interactive_execute() restores that value on exit. I compared two entry points against 4f5ac17. Opening a nested table from the Interactive Workspace tree now emits a legacy dataview notification. Calling utils::View(data.frame(a = 1:3)) at the adopted arf console opens no panel. The transcript drops the fallback display because it has no execution ID. Both opened jdv on the base commit. Please make the current controller’s address available between cells as well as preserving the individual cell’s address while it runs.

if (!is.character(address) || length(address) != 1L || is.na(address) || !nzchar(address)) {
return(FALSE)
}
Expand Down
16 changes: 14 additions & 2 deletions sess/R/server.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
40 changes: 0 additions & 40 deletions sess/inst/tinytest/test-jdv.R
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand Down Expand Up @@ -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())
Expand Down
8 changes: 8 additions & 0 deletions src/interactive/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
91 changes: 79 additions & 12 deletions src/interactive/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,13 @@ export class SessionAgent {
private journal: SessionJournal;
private assets: AssetStore;
private clients = new Set<Client>();
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;
Expand Down Expand Up @@ -387,20 +393,48 @@ 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);
}
// Keep the lease briefly for reconnect; accepted executions keep running.
});
}

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<string, unknown>): Promise<void> {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Honor explicit viewer opens from a protocol-1 client connected to the new agent. An older window can successfully claim this session without a jdvAddress and supplies its listener only on jdv_open_viewer. I tried that client against this agent with a live jdv host and a retained table handle. Deleting the address here made Open Data Viewer return false with no panel. Keep the explicit address for the controlling legacy client, or negotiate this capability before accepting its claim. The compatibility test for a new editor talking to an old agent covers the opposite pairing.

}
result = await this.backend.inspect({
method,
params: object(params.params ?? {}),
params: inspectionParams,
timeout: 5000,
});
break;
Expand Down Expand Up @@ -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':
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down
7 changes: 6 additions & 1 deletion src/interactive/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<void>;
dispatch(submission: Submission, options?: DispatchOptions): Promise<void>;
setJdvRoute?(revision: number, address?: string): void;
inspect(request: InspectionRequest): Promise<unknown>;
replyInput(reply: InputReply): Promise<void>;
replyClientRequest(id: string, reply: ClientReply): Promise<void>;
Expand Down
17 changes: 15 additions & 2 deletions src/interactive/backends/arf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
async dispatch(
submission: Submission,
signal?: AbortSignal,
pendingJdvRoute?: (signal?: AbortSignal) => Promise<void> | undefined,
): Promise<void> {
if (this.failure) {
throw this.failure;
}
Expand All @@ -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,
Expand Down
Loading
Loading