context.sessionContext.session null after kernel restart

Hello there,

While developing my extension for Jupyterlite, I added a command to restart the Kernel:

commands.addCommand(CommandIDs.restartKernel, {
  label: 'Restart Kernel…',
  execute: args => {
    const current = getCurrent(args);
    if (!current) {
      return;
    }
    console.log("Restart: ");
    console.log(current.context.sessionContext);
    return sessionDialogs.restart(current.context.sessionContext);
  },
  isEnabled
});

I have another command to execute code on the kernel. However, when running this command after restarting the Kernel I get an error:

Uncaught (in promise) TypeError: Cannot read properties of null (reading ‘kernel’)

But I do see in the console logs that the Kernel has been restarted.

Looking at the sessionContext object, it seems the sessionContext.session is null. I would have thought the session would be updated automatically, so I’m wondering if I just did something completely wrong or if I need to handle the update of the sessionContext after a kernel restart somehow.

Any advice, guidance is appreciated!

Thank you in advance.
Thibaut

I’m still working on this issue. Here a simplified version of the code I use in my extension to restart the kernel and run code:

    // Get the current widget and activate unless the args specify otherwise.
    function getCurrent(args: ReadonlyPartialJSONObject): any | null {
      const widget = myWidgetTracker.currentWidget;
      const activate = args['activate'] !== false;
      if (activate && widget) {
        app.shell.activateById(widget.id);
      }
      return widget ?? null;
    }

    function isEnabled(): boolean {
      return (
        myWidgetTracker.currentWidget !== null &&
        myWidgetTracker.currentWidget === app.shell.currentWidget
      );
    }
    

    /**
     * Restart the Kernel linked to the current Editor
     */
    commands.addCommand(CommandIDs.restartKernel, {
      label: 'Restart Kernel…',
      execute: async args => {
        const current = getCurrent({ activate: false, ...args });
      if (!current) {
        return;
      }
        try {
          await current.context.sessionContext.restartKernel();
        } catch (error) {
          console.error("Failed to restart kernel: ", error);
        }
      },
      isEnabled
    });

    /**
     * Run  Kernel linked to the current Editor
     */
    commands.addCommand(CommandIDs.executeCode, {
      label: 'Execute code',
      execute: args => {

        const current = getCurrent(args);
        if (!current) {
          return;
        }

        console.log(current.context.sessionContext);
        // after a restart
        // at this point, current.context.sessionContext.session is null
        // kernel is not found and execution fails