Error while creating new JupyterLab Notebook

Hello Everyone,

This is my first post here. I have recently got a chance to work with JupyterLab eco system, and started to develop JupyterLab extension.

As part of my extension, I am suppose to create a new notebook → fill up code cell with python code snippet → execute this snippet.

Good thing is I could achieve the goal, however, when I create new notebook, I see an error in console - “Canceled future for execute_request message before replies were done”. I am using following code to create new notebook.

   const createNew = async (cwd: string, kernelName?: string) => {
      // docManager.createNew(cwd + '/example', FACTORY, { name: kernelName });
      return commands
        .execute('docmanager:new-untitled', { path: cwd, type: 'notebook' })
        .then(model => {  // Error is reported here.
          if (model != undefined) {
            return commands.execute('docmanager:open', {
              path: model.path,
              factory: FACTORY,
              kernel: { name: kernelName }
            });
          }
        })
        .catch(e => console.log(e));
    };

    const populateCode = () => {
      // Modelled after completer-extension's notebooks plugin
      notebooks.widgetAdded.connect(
        async (sender: INotebookTracker, panel: NotebookPanel) => {
    
          await panel.revealed;
          await panel.sessionContext.ready;
          let activeCell = panel.content.activeCell;
          let editor = activeCell?.editor ?? null;
          const session = panel.sessionContext;

          if (editor) {
            editor.model.value.text = "print('Hello') \nprint('World')";
            if (activeCell instanceof CodeCell) {
              void CodeCell.execute(activeCell, session);
            }
          }
        }
      );
    };

   commands.addCommand(CommandIDs.open, {
      label: 'Open',
      execute: async args => {
        await createNew(cwd, kernelName);
        populateCode();
      },
      icon: folderIcon.bindprops({ stylesheet: 'menuItem' }),
      mnemonic: 0
    });

Now, if I comment “populateCode()”, I don’t face above mentioned issue. Can you please guide what might be causing this issue / direction to resolve this?

Thank you.

Best regards
Jigar.

At least one previous thread on here (probably worth some additional searching):

Notebook has its own create-untitled command which will do some of this for you.

Further, have a look at some of the things in notebook’s actions.tsx. These might have some higher-level patterns you can use.

Of note… adding and running code code on every notebook is pretty… invasive. you might want to consider doing it inside your notebook-creating command rather than hanging off the UI signal. As for signals, you may also want to use statusChanged instead of ready, and check for it to be idle or something.

Finally

Hi @bollwyvl ,

Thank you for your reply. These are really good pointers. I will look into it and align my code accordingly.

Appreciate your help. Thanks.

Best regards,
Jigar.

Hi @bollwyvl and all,

Here is the snippet that I intend to use. I hope this helps to other members.

const createNewOrAdd = async (
      cwd: string,
      kernelName?: string
    ) => {
      const current = notebookTracker.currentWidget;
      if (current) {
        const notebook = current.content;
        const sesssionContext = current.sessionContext;
        NotebookActions.insertAbove(notebook);
        const activeCell = notebook.activeCell;
        if (activeCell) {
          activeCell.model.value.text = 'print(\'hello\')';
        }
        sesssionContext.ready
          .then(() => {
            NotebookActions.run(notebook, sesssionContext);
          })
          .catch(e => console.log(e));
      } else {
        commands
          .execute('notebook:create-new', { cwd: cwd, kernelName: kernelName })
          .then(notebook => {
            Promise.all([notebook.revealed, notebook.sessionContext.ready])
              .then(() => {
                NotebookActions.insertAbove(notebook);
                let activeCell = notebook.content.activeCell;
                if (activeCell) {
                  activeCell.model.value.text = 'print(\'hello\')';
                }
                NotebookActions.run(notebook.content, notebook.sessionContext);
              })
              .catch(e => console.log(e));
          })
          .catch(e => console.log(e));
      }
    };

Please free to suggest an improvements.

Thanks @bollwyvl. Appreciate your help.

Best regards,
Jigar.

1 Like