Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(jupyter): support confirm and prompt in notebooks #23592

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
48 changes: 47 additions & 1 deletion cli/js/40_jupyter.js
Copy link
Member

Choose a reason for hiding this comment

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

@zph it seems this doesn't work in vscode. I'm guessing vscode doesn't support it?

Copy link
Author

@zph zph Apr 30, 2024

Choose a reason for hiding this comment

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

Hmm, I validated in the web based jupyter notebook but by architecture I expect it should similarly work in both. VSCode does support the python version of input popups.

I'll report back.

Copy link
Author

Choose a reason for hiding this comment

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

It does work in vscode (screenshot)
image

But to see it yourself, you'll need to update your deno jupyter kernelspec to point to the debug built binary either by updateing the "argv" location or by overwriting your deno binary with the debug binary. On my mac the location is here and I'm attaching the file content:

❯ cat ~/Library/Jupyter/kernels/deno/kernel.json 
{
  "argv": [
    "/Users/zph/.local/bin/deno",
    "jupyter",
    "--kernel",
    "--conn",
    "{connection_file}"
  ],
  "display_name": "Deno",
  "language": "typescript"
}

What I'm doing locally to validate this is building the debug binary and installing it into that location, overriding my normal deno. 😸

Copy link
Author

Choose a reason for hiding this comment

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

But viewing it when not passing any defaultValue looks bad b/c of the surrounding brackets. I'll fix it.

Copy link
Author

Choose a reason for hiding this comment

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

image

Ok, when defaultValue == "" we hide the empty square brackets in f4faf22

Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,14 @@ async function formatInner(obj, raw) {
internals.jupyter = { formatInner };

function enableJupyter() {
const { op_jupyter_broadcast } = core.ops;
const { op_jupyter_broadcast, op_jupyter_input } = core.ops;

async function input(
prompt,
password,
) {
return await op_jupyter_input(prompt, password);
}

async function broadcast(
msgType,
Expand Down Expand Up @@ -412,6 +419,45 @@ function enableJupyter() {
return;
}

/**
* Prompt for user confirmation (in Jupyter Notebook context)
* Override confirm and prompt because they depend on a tty
* and in the Deno.jupyter environment that doesn't exist.
* @param {string} message - The message to display.
* @returns {Promise<boolean>} User confirmation.
*/
async function confirm(message = "Confirm") {
const answer = await input(`${message} [y/N] `, false);
return answer === "Y" || answer === "y";
}
Copy link
Member

Choose a reason for hiding this comment

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

This PR looks great, but prompt and confirm are not async functions. Probably we should make op_jupyter_input sync, then block on the future in rust.

Copy link
Member

Choose a reason for hiding this comment

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

I believe the way to do this is to do the following inside the op:

tokio::runtime::Handle::current().block_on(async {
 // async code goes here
})

Copy link
Author

Choose a reason for hiding this comment

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

Makes sense! I was unsure how to make the rust work for sync and will try that out :)

Copy link
Author

@zph zph Apr 30, 2024

Choose a reason for hiding this comment

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

I tried converting to block_on and hit the following error:

thread 'main' panicked at cli/ops/jupyter.rs:53:46:
Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks.

I'll dig into that further and if you have advice from already having more context let me know!

Copy link
Member

@dsherret dsherret Apr 30, 2024

Choose a reason for hiding this comment

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

So apparently the answer is this isn't possible to do with a single threaded runtime. We'll have to move a bunch of the messaging off into a separate thread then make this other code have the ability to send and receive message from that thread in a synchronous manner.

Copy link
Member

Choose a reason for hiding this comment

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

I opened #23617

Copy link
Author

Choose a reason for hiding this comment

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

Ok! 👍 . Thanks for opening up the other feature request.


/**
* Prompt for user input (in Jupyter Notebook context)
* @param {string} message - The message to display.
* @param {string} defaultValue - The value used if none is provided.
* @param {object} options Options
* @param {boolean} options.password Hide the output characters
* @returns {Promise<string>} The user input.
*/
async function prompt(
message = "Prompt",
defaultValue = "",
{ password = false } = {},
) {
if (defaultValue != "") {
message += ` [${defaultValue}]`;
}
const answer = await input(`${message}`, password);

if (answer === "") {
return defaultValue;
}

return answer;
}

globalThis.confirm = confirm;
globalThis.prompt = prompt;
bartlomieju marked this conversation as resolved.
Show resolved Hide resolved
globalThis.Deno.jupyter = {
broadcast,
display,
Expand Down
57 changes: 57 additions & 0 deletions cli/ops/jupyter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ use crate::tools::jupyter::server::StdioMsg;
use deno_core::error::AnyError;
use deno_core::op2;
use deno_core::serde_json;
use deno_core::serde_json::json;
use deno_core::OpState;
use tokio::sync::mpsc;
use tokio::sync::Mutex;

deno_core::extension!(deno_jupyter,
ops = [
op_jupyter_broadcast,
op_jupyter_input,
],
options = {
sender: mpsc::UnboundedSender<StdioMsg>,
Expand All @@ -30,6 +32,61 @@ deno_core::extension!(deno_jupyter,
},
);

#[op2(async)]
#[string]
pub async fn op_jupyter_input(
state: Rc<RefCell<OpState>>,
#[string] prompt: String,
#[serde] is_password: serde_json::Value,
) -> Result<Option<String>, AnyError> {
let (_iopub_socket, last_execution_request, stdin_socket) = {
let s = state.borrow();

(
s.borrow::<Arc<Mutex<Connection<zeromq::PubSocket>>>>()
.clone(),
s.borrow::<Rc<RefCell<Option<JupyterMessage>>>>().clone(),
s.borrow::<Arc<Mutex<Connection<zeromq::RouterSocket>>>>()
.clone(),
)
};

let mut stdin = stdin_socket.lock().await;

let maybe_last_request = last_execution_request.borrow().clone();
if let Some(last_request) = maybe_last_request {
if !last_request.allow_stdin() {
return Ok(None);
}

/*
* Using with_identities() because of jupyter client docs instruction
* Requires cloning identities per :
* https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-channel
* The stdin socket of the client is required to have the
* same zmq IDENTITY as the client’s shell socket.
* Because of this, the input_request must be sent with the same IDENTITY
* routing prefix as the execute_reply in order for the frontend to receive the message.
* """
*/
last_request
Copy link
Contributor

Choose a reason for hiding this comment

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

AFAIK, I think this is correct.

Copy link
Author

Choose a reason for hiding this comment

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

Thank you 👏

Copy link
Contributor

Choose a reason for hiding this comment

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

Confirmed this by the way and incorporated it directly into the new library to make it easier to do.

.new_message("input_request")
.with_identities(&last_request)
.with_content(json!({
"prompt": prompt,
"password": is_password,
}))
.send(&mut *stdin)
.await?;

let response = JupyterMessage::read(&mut *stdin).await?;

return Ok(Some(response.value().to_string()));
}

Ok(None)
}

#[op2(async)]
pub async fn op_jupyter_broadcast(
state: Rc<RefCell<OpState>>,
Expand Down
16 changes: 16 additions & 0 deletions cli/tools/jupyter/jupyter_msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,14 @@ impl JupyterMessage {
self.content["comm_id"].as_str().unwrap_or("")
}

pub(crate) fn allow_stdin(&self) -> bool {
self.content["allow_stdin"].as_bool().unwrap_or(false)
}

pub(crate) fn value(&self) -> &str {
self.content["value"].as_str().unwrap_or("")
}
Comment on lines +183 to +189
Copy link
Member

Choose a reason for hiding this comment

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

Are you sure that these values are always present in the Jupyter messages? If not, we should use self.content.get(...) instead and provide default values that are "falsy".


// Creates a new child message of this message. ZMQ identities are not transferred.
pub(crate) fn new_message(&self, msg_type: &str) -> JupyterMessage {
let mut header = self.header.clone();
Expand Down Expand Up @@ -235,6 +243,14 @@ impl JupyterMessage {
self
}

pub(crate) fn with_identities(
mut self,
msg: &JupyterMessage,
) -> JupyterMessage {
self.zmq_identities = msg.zmq_identities.clone();
self
}

pub(crate) async fn send<S: zeromq::SocketSend>(
&self,
connection: &mut Connection<S>,
Expand Down
6 changes: 4 additions & 2 deletions cli/tools/jupyter/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,21 @@ impl JupyterServer {
bind_socket::<zeromq::RouterSocket>(&spec, spec.shell_port).await?;
let control_socket =
bind_socket::<zeromq::RouterSocket>(&spec, spec.control_port).await?;
let _stdin_socket =
let stdin_socket =
bind_socket::<zeromq::RouterSocket>(&spec, spec.stdin_port).await?;
let iopub_socket =
bind_socket::<zeromq::PubSocket>(&spec, spec.iopub_port).await?;
let iopub_socket = Arc::new(Mutex::new(iopub_socket));
let stdin_socket = Arc::new(Mutex::new(stdin_socket));
let last_execution_request = Rc::new(RefCell::new(None));

// Store `iopub_socket` in the op state so it's accessible to the runtime API.
// Store `iopub_socket` and `stdin_socket` in the op state for access to the runtime API.
{
let op_state_rc = repl_session.worker.js_runtime.op_state();
let mut op_state = op_state_rc.borrow_mut();
op_state.put(iopub_socket.clone());
op_state.put(last_execution_request.clone());
op_state.put(stdin_socket.clone());
}

let cancel_handle = CancelHandle::new_rc();
Expand Down
1 change: 1 addition & 0 deletions runtime/js/99_main.js
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,7 @@ const NOT_IMPORTED_OPS = [

// Related to `Deno.jupyter` API
"op_jupyter_broadcast",
"op_jupyter_input",

// Related to `Deno.test()` API
"op_test_event_step_result_failed",
Expand Down