forked from jupyterlab/jupyterlab
/
clientsession.tsx
1261 lines (1134 loc) · 34.5 KB
/
clientsession.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { PathExt, IChangedArgs } from '@jupyterlab/coreutils';
import { UUID } from '@phosphor/coreutils';
import {
Kernel,
KernelMessage,
ServerConnection,
Session
} from '@jupyterlab/services';
import { IterableOrArrayLike, each, find } from '@phosphor/algorithm';
import { PromiseDelegate } from '@phosphor/coreutils';
import { IDisposable, IObservableDisposable } from '@phosphor/disposable';
import { ISignal, Signal } from '@phosphor/signaling';
import { Widget } from '@phosphor/widgets';
import * as React from 'react';
import { showDialog, Dialog } from './dialog';
import { KernelSpec } from '@jupyterlab/services/lib/kernelspec';
/**
* The interface of client session object.
*
* OLD: The client session represents the link between a path and its kernel
* for the duration of the lifetime of the session object. The session can
* have no current kernel, and can start a new kernel at any time.
*
* NEW: A client session represents a single object that proxies the session
* information for the session an object is connected to. This is a
* convenience object that points to a specific session (which in turn points
* to a specific kernel). The signals here are proxied from the current
* kernel.
*
* For any session-specific operations, use the .session attribute. For any
* kernel-specific things, use .session.kernel. For convenience, we proxy the
* current kernel and session signals to the client session (so you don't have
* to handle session or kernel changes in your slots).
*
* A session represents a persistent resource to address a kernel. The kernel
* can be restarted or changed.
*
* A clientSession represents a client-side handle to a single session.
* Essentially, the main thing it adds is a sessionChanged signal, which
* represents pointing your clientSession to a different session.
*
* For example, a variable explorer contains a clientSession. That points the
* current session the variable explorer is hooked to, and gives notifications
* when changing sessions. The clientSession object on the variable explorer
* is a single object whose lifecycle matches the variable explorer widget.
* The session object matches the persistent
*
* A kernel represents a computational process. Its lifecycle is determined by
* explicit restarts and shutdowns, computational conditions (such as OOM
* errors), etc.
*
* A session represents a connection to semantic kernel. It is initiated
* explicitly, and persists beyond kernel shutdowns, and provides a single
* handle for multiple activities talking to the same computational resource
* kernel (even if that kernel is restarted or changed). For example, a
* console and a notebook can point to the same session, which means they will
* continue pointing to the same kernel even if the session's kernel is
* switched. Sessions are stored on the server side in the rest API.
*
* A clientSession represents a mapping of a widget to a session. Its
* lifecycle is the widget lifecycle.
*
* A plugin for a widget would grab the widget's clientSession to have a
* persistent handle on whatever computation resource was tied to the widget.
* The session a clientSession points to may be restored as part of the widget
* restoration process (so refreshing a page will point the widget to the
* right session). The Running tab UI should provide a way to point a widget's
* clientSession to a new session. It should also provide a way to explicitly
* manage the kernel associated with the session (restart, change, interrupt,
* etc.).
*
* For many things, we only care about kernel signals from the current kernel,
* no matter how many times the session or kernel changes. Since it is
* inconvenient to disconnect and connect handlers every time a session or
* kernel changes, we proxy the kernel signals to the session, and the session
* signals to the clientSession. So to act on whatever the current kernel's
* iopubmessage signal, just hook up to the clientSession's iopubmessage
* signal.
*
* Another possibility would be to offer a utility function to
* connect/disconnect a specific function on a signal. Use one signal to
* affect the connection/disconnection of another signal. For example, given a
* change signal and a slot and an initial object, on any change signal, it
* would disconnect the slot from the old value and connect it to the new
* value.
*
* To manage a kernel lifecycle, you can change the kernel for a session
* (which affects all connections to that session), or you can create a
* connection to a new session (which does not affect other connections to a
* session).
*
*/
export interface IClientSession extends IObservableDisposable {
/**
* The current session connection.
*/
session: Session.ISessionConnection | null;
/**
* The current kernel connection, proxied from the session connection for convenience
*/
kernel: Kernel.IKernelConnection | null;
/**
* A signal emitted when the session connection changes.
*/
readonly sessionChanged: ISignal<
this,
IChangedArgs<Session.ISessionConnection | null, 'session'>
>;
// Signals proxied from the session connection for convenience.
/**
* A signal emitted when the kernel changes, proxied from the session connection.
*/
readonly kernelChanged: ISignal<
this,
IChangedArgs<Kernel.IKernelConnection | null, 'kernel'>
>;
/**
* A signal emitted when the kernel status changes, proxied from the session connection.
*/
readonly statusChanged: ISignal<this, Kernel.Status>;
/**
* A signal emitted for a kernel messages, proxied from the session connection.
*/
readonly iopubMessage: ISignal<this, KernelMessage.IMessage>;
/**
* A signal emitted for an unhandled kernel message, proxied from the session connection.
*/
readonly unhandledMessage: ISignal<this, KernelMessage.IMessage>;
/**
* A signal emitted when a session property changes, proxied from the session connection.
*/
readonly propertyChanged: ISignal<this, 'path' | 'name' | 'type'>;
/**
* The kernel preference for starting new kernels.
*/
kernelPreference: IClientSession.IKernelPreference;
/**
* The sensible display name for the kernel, or 'No Kernel'
*
* This is at this level since the underlying kernel connection does not
* have access to the kernel spec manager.
*/
readonly kernelDisplayName: string;
/**
* Change the current kernel associated with the document.
*
* TODO: this currently changes a kernel if the session exists, otherwise
* starts a new session, so it is kind of a shorthand convenience function.
*/
/**
* Kill the kernel and shutdown the session.
*
* @returns A promise that resolves when the session is shut down.
*/
shutdown(): Promise<void>;
/**
* Use a UX to select a new kernel for the session.
*
* TODO: should this select a new kernel for the session, or make a new session?
*/
selectKernel(): Promise<void>;
/**
* Restart the session.
*
* @returns A promise that resolves with whether the kernel has restarted.
*
* #### Notes
* The purpose here is to make it easy to get a new kernel running in a
* session when we once had a kernel running.
*
* TODO: We keep the last kernel that this session ran here, in case the
* session lifetime is tied to the kernel lifetime.
*
* * If there is a running kernel, present a dialog.
* * If there is no kernel, we start a kernel with the last run kernel name
* and resolves with `true`.
* * If no kernel has been started, this is a no-op, and resolves with
* `false`.
*/
restart(): Promise<boolean>;
}
/**
* The namespace for Client Session related interfaces.
*/
export namespace IClientSession {
/**
* A kernel preference.
*/
export interface IKernelPreference {
/**
* The name of the kernel.
*/
readonly name?: string;
/**
* The preferred kernel language.
*/
readonly language?: string;
/**
* The id of an existing kernel.
*/
readonly id?: string;
/**
* Whether to prefer starting a kernel.
*/
readonly shouldStart?: boolean;
/**
* Whether a kernel can be started.
*/
readonly canStart?: boolean;
/**
* Whether a kernel needs to be close with the associated session
*/
readonly shutdownOnClose?: boolean;
/**
* Whether to auto-start the default kernel if no matching kernel is found.
*/
readonly autoStartDefault?: boolean;
}
}
/**
* The default implementation of client session object.
*/
export class ClientSession implements IClientSession {
/**
* Construct a new client session.
*/
constructor(options: ClientSession.IOptions) {
this.manager = options.manager;
this.specsManager = options.specsManager;
this._path = options.path || UUID.uuid4();
this._type = options.type || '';
this._name = options.name || '';
this._setBusy = options.setBusy;
this._kernelPreference = options.kernelPreference || {};
}
/**
* The current kernel connection, proxied from the session connection for convenience
*/
get kernel(): Kernel.IKernelConnection | null {
return this.session?.kernel ?? null;
}
/**
* The current session connection.
*/
get session(): Session.ISessionConnection | null {
return this._session ?? null;
}
/**
* A signal emitted when the kernel connection changes, proxied from the session connection.
*/
get kernelChanged(): ISignal<this, Session.IKernelChangedArgs> {
return this._kernelChanged;
}
/**
* A signal emitted when the session connection changes.
*/
get sessionChanged(): ISignal<
this,
IChangedArgs<Session.ISessionConnection | null, 'session'>
> {
return this._sessionChanged;
}
/**
* A signal emitted when the kernel status changes, proxied from the kernel.
*/
get statusChanged(): ISignal<this, Kernel.Status> {
return this._statusChanged;
}
/**
* A signal emitted for iopub kernel messages, proxied from the kernel.
*/
get iopubMessage(): ISignal<this, KernelMessage.IIOPubMessage> {
return this._iopubMessage;
}
/**
* A signal emitted for an unhandled kernel message, proxied from the kernel.
*/
get unhandledMessage(): ISignal<this, KernelMessage.IMessage> {
return this._unhandledMessage;
}
/**
* A signal emitted when a session property changes, proxied from the current session.
*/
get propertyChanged(): ISignal<this, 'path' | 'name' | 'type'> {
return this._propertyChanged;
}
/**
* The kernel preference of this client session.
*
* This is used when selecting a new kernel, and should reflect the sort of
* kernel the activity prefers.
*/
get kernelPreference(): IClientSession.IKernelPreference {
return this._kernelPreference;
}
set kernelPreference(value: IClientSession.IKernelPreference) {
this._kernelPreference = value;
}
/**
* The session manager used by the session.
*/
readonly manager: Session.IManager;
/**
* The kernel spec manager
*/
readonly specsManager: KernelSpec.IManager;
/**
* The display name of the current kernel, or a sensible alternative.
*
* This is a convenience function to have a consistent sensible name for the
* kernel. Perhaps it should be pushed down to the kernel connection?
*/
get kernelDisplayName(): string {
let kernel = this.kernel;
if (!kernel) {
return 'No Kernel!';
}
return (
this.specsManager.specs?.kernelspecs[kernel.name]?.display_name ??
kernel.name
);
}
/**
* Test whether the client session is disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* A signal emitted when the poll is disposed.
*/
get disposed(): ISignal<this, void> {
return this._disposed;
}
/**
* Dispose of the resources held by the context.
*/
dispose(): void {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
if (this._session) {
if (this.kernelPreference.shutdownOnClose) {
// Fire and forget the session shutdown request
this._session.shutdown().catch(reason => {
console.error(`Kernel not shut down ${reason}`);
});
}
// Dispose the session connection
this._session.dispose();
this._session = null;
}
if (this._dialog) {
this._dialog.dispose();
}
if (this._busyDisposable) {
this._busyDisposable.dispose();
this._busyDisposable = null;
}
this._disposed.emit();
Signal.clearData(this);
}
/**
* Change the current kernel associated with the session.
*/
changeKernel(
options: Partial<Kernel.IModel>
): Promise<Kernel.IKernelConnection> {
return this.initialize().then(() => {
if (this.isDisposed) {
return Promise.reject('Disposed');
}
return this._changeKernel(options);
});
}
/**
* Select a kernel for the session.
*/
async selectKernel(): Promise<void> {
return this.initialize().then(() => {
if (this.isDisposed) {
throw new Error('Disposed');
}
return this._selectKernel(true);
});
}
/**
* Kill the kernel and shutdown the session.
*
* @returns A promise that resolves when the session is shut down.
*/
async shutdown(): Promise<void> {
return this._session?.shutdown();
}
/**
* Restart the session.
*
* @returns A promise that resolves with whether the kernel has restarted.
*
* #### Notes
* If there is a running kernel, present a dialog.
* If there is no kernel, we start a kernel with the last run
* kernel name and resolves with `true`.
*/
async restart(): Promise<boolean> {
return this.initialize().then(() => {
if (this.isDisposed) {
return Promise.reject('session already disposed');
}
let kernel = this.session?.kernel;
if (!kernel) {
if (this._prevKernelName) {
return this.changeKernel({ name: this._prevKernelName }).then(
() => true
);
}
// Bail if there is no previous kernel to start.
return Promise.reject('No kernel to restart');
}
return ClientSession.restartKernel(kernel);
});
}
/**
* Initialize the session.
*
* #### Notes
* If a server session exists on the current path, we will connect to it.
* If preferences include disabling `canStart` or `shouldStart`, no
* server session will be started.
* If a kernel id is given, we attempt to start a session with that id.
* If a default kernel is available, we connect to it.
* Otherwise we ask the user to select a kernel.
*/
async initialize(): Promise<void> {
if (this._initializing || this._isReady) {
return this._ready.promise;
}
this._initializing = true;
let manager = this.manager;
await manager.ready;
let model = find(manager.running(), item => {
return item.path === this._path;
});
if (model) {
try {
let session = manager.connectTo(model);
this._handleNewSession(session);
} catch (err) {
void this._handleSessionError(err);
return Promise.reject(err);
}
}
await this._startIfNecessary();
this._isReady = true;
this._ready.resolve(undefined);
}
/**
* Start the session if necessary.
*/
private _startIfNecessary(): Promise<void> {
let preference = this.kernelPreference;
if (
this.isDisposed ||
this.session?.kernel ||
preference.shouldStart === false ||
preference.canStart === false
) {
return Promise.resolve();
}
// Try to use an existing kernel.
if (preference.id) {
return this._changeKernel({ id: preference.id })
.then(() => undefined)
.catch(() => this._selectKernel(false));
}
let name = ClientSession.getDefaultKernel({
specs: this.specsManager.specs,
sessions: this.manager.running(),
preference
});
if (name) {
return this._changeKernel({ name })
.then(() => undefined)
.catch(() => this._selectKernel(false));
}
return this._selectKernel(false);
}
/**
* Change the kernel.
*/
private _changeKernel(
options: Partial<Kernel.IModel>
): Promise<Kernel.IKernelConnection> {
if (this.isDisposed) {
return Promise.reject('Disposed');
}
let session = this._session;
if (session && session.kernel.status !== 'dead') {
return session.changeKernel(options).catch(err => {
void this._handleSessionError(err);
return Promise.reject(err);
});
} else {
return this._startSession(options);
}
}
/**
* Select a kernel.
*
* @param cancelable: whether the dialog should have a cancel button.
*/
private _selectKernel(cancelable: boolean): Promise<void> {
if (this.isDisposed) {
return Promise.resolve();
}
const buttons = cancelable
? [Dialog.cancelButton(), Dialog.okButton({ label: 'Select' })]
: [Dialog.okButton({ label: 'Select' })];
let dialog = (this._dialog = new Dialog({
title: 'Select Kernel',
body: new Private.KernelSelector(this),
buttons
}));
return dialog
.launch()
.then(result => {
if (this.isDisposed || !result.button.accept) {
return;
}
let model = result.value;
if (model === null && this._session) {
return this.shutdown().then(() => {
this._kernelChanged.emit({
oldValue: null,
newValue: null,
name: 'kernel'
});
});
}
if (model) {
return this._changeKernel(model).then(() => undefined);
}
})
.then(() => {
this._dialog = null;
});
}
/**
* Start a session and set up its signals.
*/
private async _startSession(
model: Partial<Kernel.IModel>
): Promise<Kernel.IKernelConnection> {
if (this.isDisposed) {
throw 'Client session is disposed.';
}
try {
const session = await this.manager.startNew({
model: {
path: this._path,
type: this._type,
name: this._name,
kernel: model
}
});
return this._handleNewSession(session);
} catch (err) {
void this._handleSessionError(err);
throw err;
}
}
/**
* Handle a new session object.
*/
private _handleNewSession(
session: Session.ISessionConnection
): Kernel.IKernelConnection {
if (this.isDisposed) {
throw Error('Disposed');
}
if (this._session) {
this._session.dispose();
}
this._session = session;
if (session.path !== this._path) {
this._path = session.path;
this._propertyChanged.emit('path');
}
if (session.name !== this._name) {
this._name = session.name;
this._propertyChanged.emit('name');
}
if (session.type !== this._type) {
this._type = session.type;
this._propertyChanged.emit('type');
}
session.disposed.connect(this._onSessionDisposed, this);
session.propertyChanged.connect(this._onPropertyChanged, this);
session.kernelChanged.connect(this._onKernelChanged, this);
session.statusChanged.connect(this._onStatusChanged, this);
session.iopubMessage.connect(this._onIopubMessage, this);
session.unhandledMessage.connect(this._onUnhandledMessage, this);
this._prevKernelName = session.kernel.name;
// The session kernel was disposed above when the session was disposed, so
// the oldValue should be null.
this._kernelChanged.emit({
oldValue: null,
newValue: session.kernel,
name: 'kernel'
});
return session.kernel;
}
/**
* Handle an error in session startup.
*/
private _handleSessionError(
err: ServerConnection.ResponseError
): Promise<void> {
return err.response
.text()
.then(text => {
let message = err.message;
try {
message = JSON.parse(text)['traceback'];
} catch (err) {
// no-op
}
let dialog = (this._dialog = new Dialog({
title: 'Error Starting Kernel',
body: <pre>{message}</pre>,
buttons: [Dialog.okButton()]
}));
return dialog.launch();
})
.then(() => {
this._dialog = null;
});
}
/**
* Handle a session termination.
*/
private _onSessionDisposed(): void {
let kernel = this.session.kernel;
if (this._session) {
this._session.dispose();
}
this._session = null;
this._terminated.emit(undefined);
if (kernel) {
this._kernelChanged.emit({
oldValue: null,
newValue: null,
name: 'kernel'
});
}
}
/**
* Handle a change to a session property.
*/
private _onPropertyChanged(
sender: Session.ISessionConnection,
property: 'path' | 'name' | 'type'
) {
switch (property) {
case 'path':
this._path = sender.path;
break;
case 'name':
this._name = sender.name;
break;
default:
this._type = sender.type;
break;
}
this._propertyChanged.emit(property);
}
/**
* Handle a change to the kernel.
*/
private _onKernelChanged(
sender: Session.ISessionConnection,
args: Session.IKernelChangedArgs
): void {
this._kernelChanged.emit(args);
}
/**
* Handle a change to the session status.
*/
private _onStatusChanged(
sender: Session.ISessionConnection,
status: Kernel.Status
): void {
// Set that this kernel is busy, if we haven't already
// If we have already, and now we aren't busy, dispose
// of the busy disposable.
if (this._setBusy) {
if (status === 'busy') {
if (!this._busyDisposable) {
this._busyDisposable = this._setBusy();
}
} else {
if (this._busyDisposable) {
this._busyDisposable.dispose();
this._busyDisposable = null;
}
}
}
// Proxy the signal
this._statusChanged.emit(status);
}
/**
* Handle an iopub message.
*/
private _onIopubMessage(
sender: Session.ISessionConnection,
message: KernelMessage.IIOPubMessage
): void {
this._iopubMessage.emit(message);
}
/**
* Handle an unhandled message.
*/
private _onUnhandledMessage(
sender: Session.ISessionConnection,
message: KernelMessage.IMessage
): void {
this._unhandledMessage.emit(message);
}
private _path = '';
private _name = '';
private _type = '';
private _prevKernelName = '';
private _kernelPreference: IClientSession.IKernelPreference;
private _isDisposed = false;
private _disposed = new Signal<this, void>(this);
private _session: Session.ISessionConnection | null = null;
private _ready = new PromiseDelegate<void>();
private _initializing = false;
private _isReady = false;
private _terminated = new Signal<this, void>(this);
private _kernelChanged = new Signal<this, Session.IKernelChangedArgs>(this);
private _sessionChanged = new Signal<
this,
IChangedArgs<Session.ISessionConnection | null, 'session'>
>(this);
private _statusChanged = new Signal<this, Kernel.Status>(this);
private _iopubMessage = new Signal<this, KernelMessage.IIOPubMessage>(this);
private _unhandledMessage = new Signal<this, KernelMessage.IMessage>(this);
private _propertyChanged = new Signal<this, 'path' | 'name' | 'type'>(this);
private _dialog: Dialog<any> | null = null;
private _setBusy: () => IDisposable | undefined;
private _busyDisposable: IDisposable | null = null;
}
/**
* A namespace for `ClientSession` statics.
*/
export namespace ClientSession {
/**
* The options used to initialize a context.
*/
export interface IOptions {
/**
* A session manager instance.
*/
manager: Session.IManager;
/**
* A manager for kernel specs
*/
specsManager: KernelSpec.IManager;
/**
* The initial path of the file.
*/
path?: string;
/**
* The name of the session.
*/
name?: string;
/**
* The type of the session.
*/
type?: string;
/**
* A kernel preference.
*/
kernelPreference?: IClientSession.IKernelPreference;
/**
* A function to call when the session becomes busy.
*/
setBusy?: () => IDisposable;
}
/**
* Restart a kernel if the user accepts the risk.
*
* Returns a promise resolving with whether the kernel was restarted.
*/
export async function restartKernel(
kernel: Kernel.IKernelConnection
): Promise<boolean> {
let restartBtn = Dialog.warnButton({ label: 'Restart' });
const result = await showDialog({
title: 'Restart Kernel?',
body:
'Do you want to restart the current kernel? All variables will be lost.',
buttons: [Dialog.cancelButton(), restartBtn]
});
if (kernel.isDisposed) {
return false;
}
if (result.button.accept) {
await kernel.restart();
return true;
}
return false;
}
/**
* An interface for populating a kernel selector.
*/
export interface IKernelSearch {
/**
* The Kernel specs.
*/
specs: KernelSpec.ISpecModels | null;
/**
* The kernel preference.
*/
preference: IClientSession.IKernelPreference;
/**
* The current running sessions.
*/
sessions?: IterableOrArrayLike<Session.IModel>;
}
/**
* Get the default kernel name given select options.
*/
export function getDefaultKernel(options: IKernelSearch): string | null {
return Private.getDefaultKernel(options);
}
/**
* Populate a kernel dropdown list.
*
* @param node - The node to populate.
*
* @param options - The options used to populate the kernels.
*
* #### Notes
* Populates the list with separated sections:
* - Kernels matching the preferred language (display names).
* - "None" signifying no kernel.
* - The remaining kernels.
* - Sessions matching the preferred language (file names).
* - The remaining sessions.
* If no preferred language is given or no kernels are found using
* the preferred language, the default kernel is used in the first
* section. Kernels are sorted by display name. Sessions display the
* base name of the file with an ellipsis overflow and a tooltip with
* the explicit session information.
*/
export function populateKernelSelect(
node: HTMLSelectElement,
options: IKernelSearch
): void {
return Private.populateKernelSelect(node, options);
}
}
/**
* The namespace for module private data.
*/
namespace Private {
/**
* A widget that provides a kernel selection.
*/
export class KernelSelector extends Widget {
/**
* Create a new kernel selector widget.
*/
constructor(session: ClientSession) {
super({ node: createSelectorNode(session) });
}
/**
* Get the value of the kernel selector widget.
*/
getValue(): Kernel.IModel {
let selector = this.node.querySelector('select') as HTMLSelectElement;
return JSON.parse(selector.value) as Kernel.IModel;
}
}
/**
* Create a node for a kernel selector widget.
*/
function createSelectorNode(clientSession: ClientSession) {
// Create the dialog body.
let body = document.createElement('div');
let text = document.createElement('label');
text.textContent = `Select kernel for: "${clientSession.session.name}"`;
body.appendChild(text);
let options = getKernelSearch(clientSession);
let selector = document.createElement('select');
ClientSession.populateKernelSelect(selector, options);
body.appendChild(selector);
return body;
}
/**
* Get the default kernel name given select options.
*/
export function getDefaultKernel(
options: ClientSession.IKernelSearch