How to make new nb tab default to connect to kernel of existing session

Hi there,
Instead of opening a kernel selection dialogue when opening a new nb file, I want it to connect to an existing session’s kernel by default. i.e. the first nb file creates a kernel, and all later nb file tabs use the previously created kernel.

What’s the best way to do this? Do I need to modify the lab code?

Thanks.

1 Like

It seems that Jupyterlab cannot be configured to do this, and I managed to find a way to modify the Jupyterlab source to achieve this.

In packages/docregistry/src/context.ts, find the existing kernel id from running sessions and set the sessionContext kernel preference with the found kernel id. The newly started kernel will then use the existing kernel. The patch is as follows:

diff --git a/packages/docregistry/src/context.ts b/packages/docregistry/src/context.ts
index ef5df6f109..a08d94da45 100644
--- a/packages/docregistry/src/context.ts
+++ b/packages/docregistry/src/context.ts
@@ -92,14 +92,28 @@ export class Context<
       return this._populatedPromise.promise;
     });
 
+    const sessions = [];
+    let iterator = manager.sessions.running();
+    let item = iterator.next();
+    while (item != undefined) {
+        sessions.push(item);
+        item = iterator.next();
+    }
+    let kernelIdPref = {}
+    if (sessions.length > 0) {
+      let kernelId = sessions[0].kernel?.id
+      kernelIdPref = { id: kernelId }
+    }
+
     const ext = PathExt.extname(this._path);
+    let pref = {...kernelIdPref, shouldStart: true}
     this.sessionContext = new SessionContext({
       sessionManager: manager.sessions,
       specsManager: manager.kernelspecs,
       path: this._path,
       type: ext === '.ipynb' ? 'notebook' : 'file',
       name: PathExt.basename(localPath),
-      kernelPreference: options.kernelPreference || { shouldStart: false },
+      kernelPreference: pref,
       setBusy: options.setBusy
     });
     this.sessionContext.propertyChanged.connect(this._onSessionChanged, this);