# Error while creating new JupyterLab Notebook

**URL:** <https://discourse.jupyter.org/t/error-while-creating-new-jupyterlab-notebook/13259>\
**Category:** JupyterLab\
**Tags:** jupyterlab, how-to, notebook\
**Created:** [March 4, 2022, 4:45pm UTC](https://discourse.jupyter.org/t/error-while-creating-new-jupyterlab-notebook/13259 "2022-03-04T16:45:41Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jpthakkar](https://avatars.discourse-cdn.com/v4/letter/j/f04885/32.png) [@jpthakkar](https://discourse.jupyter.org/u/jpthakkar)\
**Post date:** [March 4, 2022, 4:45pm UTC](https://discourse.jupyter.org/t/error-while-creating-new-jupyterlab-notebook/13259/1 "2022-03-04T16:45:42Z")

</div>

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.

```auto
   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.

---

<div class="post-metadata">

**Author:** ![bollwyvl](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.jupyter.org/bollwyvl/32/904_2.png) [@bollwyvl](https://discourse.jupyter.org/u/bollwyvl)\
**Post date:** [March 5, 2022, 4:10pm UTC](https://discourse.jupyter.org/t/error-while-creating-new-jupyterlab-notebook/13259/2 "2022-03-05T16:10:07Z")

</div>

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

- [Lab extension: Open a notebook + dynamically create cell at top - #2 by jtp](https://discourse.jupyter.org/t/lab-extension-open-a-notebook-dynamically-create-cell-at-top/4277/2)

Notebook has its own [create-untitled command](https://github.com/jupyterlab/jupyterlab/blob/b8df068b2eb694cb93ec281526e6e131031f7fcd/packages/notebook-extension/src/index.ts#L1509) which will do some of this for you.

Further, have a look at some of the things in [notebook’s actions.tsx](https://github.com/jupyterlab/jupyterlab/blob/b8df068b2eb694cb93ec281526e6e131031f7fcd/packages/notebook/src/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`](https://github.com/jupyterlab/jupyterlab/blob/b8df068b2eb694cb93ec281526e6e131031f7fcd/packages/services/src/session/session.ts#L50) instead of `ready`, and check for it to be idle or something.

Finally

---

<div class="post-metadata">

**Author:** ![jpthakkar](https://avatars.discourse-cdn.com/v4/letter/j/f04885/32.png) [@jpthakkar](https://discourse.jupyter.org/u/jpthakkar)\
**Post date:** [March 7, 2022, 10:22am UTC](https://discourse.jupyter.org/t/error-while-creating-new-jupyterlab-notebook/13259/3 "2022-03-07T10:22:55Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![jpthakkar](https://avatars.discourse-cdn.com/v4/letter/j/f04885/32.png) [@jpthakkar](https://discourse.jupyter.org/u/jpthakkar)\
**Post date:** [March 7, 2022, 12:31pm UTC](https://discourse.jupyter.org/t/error-while-creating-new-jupyterlab-notebook/13259/4 "2022-03-07T12:31:18Z")

</div>

Hi @bollwyvl and all,

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

```auto
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.
