-
Notifications
You must be signed in to change notification settings - Fork 16
/
kernel.ts
1318 lines (1164 loc) · 42.9 KB
/
kernel.ts
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
import path from 'node:path'
import os from 'node:os'
import {
Disposable,
notebooks,
window,
workspace,
ExtensionContext,
NotebookEditor,
NotebookCell,
NotebookCellKind,
WorkspaceEdit,
NotebookEdit,
NotebookDocument,
env,
Uri,
commands,
languages,
TextDocument,
NotebookRange,
NotebookEditorRevealType,
NotebookEditorSelectionChangeEvent,
CancellationToken,
NotebookData,
version,
NotebookCellData,
} from 'vscode'
import { TelemetryReporter } from 'vscode-telemetry'
import { UnaryCall } from '@protobuf-ts/runtime-rpc'
import { map } from 'rxjs/operators'
import {
type ActiveTerminal,
type ClientMessage,
type RunmeTerminal,
type Serializer,
type ExtensionName,
type FeatureContext,
FeatureName,
} from '../types'
import {
ClientMessages,
DEFAULT_LANGUAGEID,
NOTEBOOK_HAS_CATEGORIES,
SUPPORTED_FILE_EXTENSIONS,
CATEGORY_SEPARATOR,
NOTEBOOK_MODE,
NotebookMode,
OutputType,
} from '../constants'
import { API } from '../utils/deno/api'
import { postClientMessage } from '../utils/messaging'
import { getNotebookExecutionOrder, registerExtensionEnvVarsMutation } from '../utils/configuration'
import features, { FEATURES_CONTEXT_STATE_KEY } from '../features'
import getLogger from './logger'
import executor, {
type IEnvironmentManager,
ENV_STORE_MANAGER,
IKernelExecutor,
IKernelExecutorOptions,
} from './executors'
import { DENO_ACCESS_TOKEN_KEY } from './constants'
import {
getKeyInfo,
getAnnotations,
hashDocumentUri,
processEnviron,
isWindows,
setNotebookCategories,
getTerminalRunmeId,
suggestCategories,
handleNotebookAutosaveSettings,
getWorkspaceFolder,
getRunnerSessionEnvs,
getEnvProps,
warnBetaRequired,
} from './utils'
import { getEventReporter } from './ai/events'
import { getSystemShellPath, isShellLanguage } from './executors/utils'
import './wasm/wasm_exec.js'
import { RpcError, TransformRequest, TransformResponse } from './grpc/client'
import { IRunner, IRunnerReady, RunProgramOptions } from './runner'
import { IRunnerEnvironment } from './runner/environment'
import { IKernelRunnerOptions, executeRunner } from './executors/runner'
import { ITerminalState, NotebookTerminalType } from './terminal/terminalState'
import {
NotebookCellManager,
NotebookCellOutputManager,
RunmeNotebookCellExecution,
getCellById,
insertCodeCell,
} from './cell'
import { handleCellOutputMessage } from './messages/cellOutput'
import handleGitHubMessage, { handleGistMessage } from './messages/github'
import { getNotebookCategories } from './utils'
import PanelManager from './panels/panelManager'
import { GrpcSerializer, SerializerBase } from './serializer'
import { askAlternativeOutputsAction, openSplitViewAsMarkdownText } from './commands'
import { handlePlatformApiMessage } from './messages/platformRequest'
import { handleGCPMessage } from './messages/gcp'
import { IPanel } from './panels/base'
import { handleAWSMessage } from './messages/aws'
import EnvVarsChangedEvent from './events/envVarsChanged'
import { SessionEnvStoreType } from './grpc/runner/v1'
import ContextState from './contextState'
import { uri as runUriResource } from './executors/resource'
import { CommandModeEnum } from './grpc/runner/types'
import { GrpcReporter } from './reporter'
enum ConfirmationItems {
Yes = 'Yes',
No = 'No',
Skip = 'Skip confirmation and run all',
Cancel = 'Cancel',
}
const log = getLogger('Kernel')
export class Kernel implements Disposable {
static readonly type = 'runme' as const
readonly #experiments = new Map<string, boolean>()
readonly #featuresSettings = new Map<string, boolean>()
#disposables: Disposable[] = []
#controller = notebooks.createNotebookController(
Kernel.type,
Kernel.type,
Kernel.type.toUpperCase(),
)
public readonly messaging = notebooks.createRendererMessaging('runme-renderer')
protected address?: string
protected runner?: IRunner
protected runnerEnv?: IRunnerEnvironment
protected runnerReadyListener?: Disposable
protected cellManager: NotebookCellManager
protected activeTerminals: ActiveTerminal[] = []
protected category?: string
protected panelManager: PanelManager
protected serializer?: SerializerBase
protected reporter?: GrpcReporter
protected featuresState$?
readonly onVarsChangeEvent: EnvVarsChangedEvent
constructor(protected context: ExtensionContext) {
const config = workspace.getConfiguration('runme.experiments')
this.onVarsChangeEvent = new EnvVarsChangedEvent()
this.#experiments.set('grpcSerializer', config.get<boolean>('grpcSerializer', true))
this.#experiments.set('grpcRunner', config.get<boolean>('grpcRunner', true))
this.#experiments.set('grpcServer', config.get<boolean>('grpcServer', true))
this.#experiments.set('smartEnvStore', config.get<boolean>('smartEnvStore', false))
this.#experiments.set('shellWarning', config.get<boolean>('shellWarning', false))
this.#experiments.set('reporter', config.get<boolean>('reporter', false))
this.cellManager = new NotebookCellManager(this.#controller)
this.#controller.supportsExecutionOrder = getNotebookExecutionOrder()
this.#controller.description = 'Run your Markdown'
this.#controller.executeHandler = this._executeAll.bind(this)
languages.getLanguages().then((l) => {
this.#controller.supportedLanguages = [
// TODO(mxs): smartly select default language depending on user shell
// e.g., use powershell/bat for respective shells
DEFAULT_LANGUAGEID,
...l.filter((x) => x !== DEFAULT_LANGUAGEID),
// need to include file extensions since people often use file
// extension to tag code blocks
// TODO(mxs): should allow users to select their own
...SUPPORTED_FILE_EXTENSIONS,
]
})
this.messaging.postMessage({ from: 'kernel' })
this.panelManager = new PanelManager(context)
this.#disposables.push(
this.messaging.onDidReceiveMessage(this.#handleRendererMessage.bind(this)),
workspace.onDidOpenNotebookDocument(this.#handleOpenNotebook.bind(this)),
workspace.onDidSaveNotebookDocument(this.#handleSaveNotebook.bind(this)),
window.onDidChangeActiveColorTheme(this.#handleActiveColorThemeMessage.bind(this)),
window.onDidChangeActiveNotebookEditor(this.#handleActiveNotebook.bind(this)),
this.panelManager,
this.onVarsChangeEvent,
this.registerTerminalProfile(),
)
const packageJSON = context?.extension?.packageJSON || {}
const featContext: FeatureContext = {
os: os.platform(),
vsCodeVersion: version as string,
extensionVersion: packageJSON?.version,
githubAuth: false,
statefulAuth: false,
extensionId: context?.extension?.id as ExtensionName,
}
const runmeFeatureSettings = workspace.getConfiguration('runme.features')
const featureNames = Object.keys(FeatureName)
featureNames.forEach((feature) => {
if (runmeFeatureSettings.has(feature)) {
const result = runmeFeatureSettings.get<boolean>(feature, false)
this.#featuresSettings.set(feature, result)
}
})
this.featuresState$ = features.loadState(packageJSON, featContext, this.#featuresSettings)
if (this.featuresState$) {
const subscription = this.featuresState$
.pipe(map((_state) => features.getSnapshot(this.featuresState$)))
.subscribe((snapshot) => {
ContextState.addKey(FEATURES_CONTEXT_STATE_KEY, snapshot)
postClientMessage(this.messaging, ClientMessages.featuresUpdateAction, {
snapshot: snapshot,
})
})
this.#disposables.push({
dispose: () => subscription.unsubscribe(),
})
}
}
get envProps() {
const ext = {
id: this.context!.extension.id,
version: this.context!.extension.packageJSON.version,
}
return getEnvProps(ext)
}
isFeatureOn(featureName: FeatureName): boolean {
if (!this.featuresState$) {
return false
}
return features.isOn(featureName, this.featuresState$)
}
updateFeatureContext<K extends keyof FeatureContext>(key: K, value: FeatureContext[K]) {
features.updateContext(this.featuresState$, key, value, this.#featuresSettings)
}
registerNotebookCell(cell: NotebookCell) {
this.cellManager.registerCell(cell)
}
setCategory(category: string) {
this.category = category
}
setSerializer(serializer: GrpcSerializer) {
this.serializer = serializer
}
setReporter(reporter: GrpcReporter) {
this.reporter = reporter
}
hasExperimentEnabled(key: string, defaultValue?: boolean) {
return this.#experiments.get(key) ?? defaultValue
}
dispose() {
this.getEnvironmentManager()?.reset()
this.#controller.dispose()
this.#disposables.forEach((d) => d.dispose())
this.runnerReadyListener?.dispose()
this.activeTerminals = []
}
async getTerminalState(cell: NotebookCell): Promise<ITerminalState | undefined> {
return (await this.getCellOutputs(cell)).getCellTerminalState()
}
async saveOutputState(cell: NotebookCell, type: OutputType, value: any) {
const cellId = cell.metadata?.['runme.dev/id']
const outputs = await this.getCellOutputs(cell)
outputs.saveOutputState(cellId, type, value)
}
async cleanOutputState(cell: NotebookCell, type: OutputType) {
const cellId = cell.metadata?.['runme.dev/id']
const outputs = await this.getCellOutputs(cell)
outputs.cleanOutputState(cellId, type)
}
async registerCellTerminalState(
cell: NotebookCell,
type: NotebookTerminalType,
): Promise<ITerminalState> {
const outputs = await this.cellManager.getNotebookOutputs(cell)
return outputs.registerCellTerminalState(type)
}
async #setNotebookMode(notebookDocument: NotebookDocument): Promise<void> {
const isSessionsOutput = GrpcSerializer.isDocumentSessionOutputs(notebookDocument.metadata)
const notebookMode = isSessionsOutput ? NotebookMode.SessionOutputs : NotebookMode.Execution
await ContextState.addKey(NOTEBOOK_MODE, notebookMode)
}
async #handleSaveNotebook({ uri, isUntitled, notebookType, getCells }: NotebookDocument) {
if (notebookType !== Kernel.type) {
return
}
const availableCategories = new Set<string>([
...getCells()
.map((cell) => getAnnotations(cell).category.split(CATEGORY_SEPARATOR))
.flat()
.filter((c) => c.length > 0),
])
await setNotebookCategories(this.context, uri, availableCategories)
await commands.executeCommand('setContext', NOTEBOOK_HAS_CATEGORIES, !!availableCategories.size)
const isReadme = uri.fsPath.toUpperCase().includes('README')
const hashed = hashDocumentUri(uri.toString())
TelemetryReporter.sendTelemetryEvent('notebook.save', {
'notebook.hashedUri': hashed,
'notebook.isReadme': isReadme.toString(),
'notebook.isUntitled': isUntitled.toString(),
})
}
async #handleOpenNotebook(notebookDocument: NotebookDocument) {
const { uri, isUntitled, notebookType, getCells } = notebookDocument
if (notebookType !== Kernel.type) {
return
}
await this.#setNotebookMode(notebookDocument)
getCells().forEach((cell) => this.registerNotebookCell(cell))
let availableCategories = new Set<string>()
try {
availableCategories = new Set<string>([
...getCells()
.map((cell) => getAnnotations(cell).category.split(CATEGORY_SEPARATOR))
.flat()
.filter((c) => c.length > 0),
])
} catch (err) {
if (err instanceof Error) {
const action = 'Edit Markdown'
const taken = await window.showErrorMessage(
`Failed to retrieve cell annotations in markdown; possibly invalid: ${err.message}`,
action,
)
if (taken && taken === action) {
openSplitViewAsMarkdownText(notebookDocument.uri)
}
}
}
await setNotebookCategories(this.context, uri, availableCategories)
const isReadme = uri.fsPath.toUpperCase().includes('README')
const hashed = hashDocumentUri(uri.toString())
await handleNotebookAutosaveSettings()
TelemetryReporter.sendTelemetryEvent('notebook.open', {
'notebook.hashedUri': hashed,
'notebook.isReadme': isReadme.toString(),
'notebook.isUntitled': isUntitled.toString(),
})
}
async #handleActiveNotebook(listener: NotebookEditor | undefined) {
const notebookDocument = listener?.notebook
if (!notebookDocument || notebookDocument.notebookType !== Kernel.type) {
return
}
await this.#setNotebookMode(notebookDocument)
const { uri } = notebookDocument
const categories = await getNotebookCategories(this.context, uri)
await commands.executeCommand('setContext', NOTEBOOK_HAS_CATEGORIES, !!categories.length)
}
// eslint-disable-next-line max-len
async #handleRendererMessage({
editor,
message,
}: {
editor: NotebookEditor
message: ClientMessage<ClientMessages>
}) {
if (message.type === ClientMessages.mutateAnnotations) {
const payload = message as ClientMessage<ClientMessages.mutateAnnotations>
let editCell: NotebookCell | undefined = undefined
for (const document of workspace.notebookDocuments) {
for (const cell of document.getCells()) {
if (
cell.kind !== NotebookCellKind.Code ||
cell.document.uri.fsPath !== editor.notebook.uri.fsPath
) {
continue
}
if (cell.metadata?.['runme.dev/id'] === undefined) {
log.error(`Cell with index ${cell.index} lacks id`)
continue
}
if (cell.metadata?.['runme.dev/id'] === payload.output.annotations['runme.dev/id']) {
editCell = cell
break
}
}
if (editCell) {
break
}
}
if (editCell) {
const edit = new WorkspaceEdit()
const newMetadata = {
...editCell.metadata,
...payload.output.annotations,
}
const notebookEdit = NotebookEdit.updateCellMetadata(editCell.index, newMetadata)
edit.set(editCell.notebook.uri, [notebookEdit])
await workspace.applyEdit(edit)
}
return
} else if (message.type === ClientMessages.denoPromote) {
const payload = message
const token = await this.getEnvironmentManager().get(DENO_ACCESS_TOKEN_KEY)
if (!token) {
return
}
const api = API.fromToken(token)
const deployed = await api.promoteDeployment(
payload.output.id,
payload.output.productionDeployment,
)
postClientMessage(this.messaging, ClientMessages.denoUpdate, {
promoted: deployed.valueOf(),
})
} else if (message.type === ClientMessages.vercelProd) {
const payload = message as ClientMessage<ClientMessages.vercelProd>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const cell = editor.notebook.cellAt(payload.output.cellIndex)
if (cell.executionSummary?.success) {
process.env['vercelProd'] = 'true'
return this._doExecuteCell(cell)
}
} else if (message.type === ClientMessages.infoMessage) {
return window.showInformationMessage(message.output as string)
} else if (message.type === ClientMessages.errorMessage) {
return window.showErrorMessage(message.output as string)
} else if (message.type === ClientMessages.openLink) {
return env.openExternal(Uri.parse(message.output))
} else if (message.type === ClientMessages.closeCellOutput) {
const cell = await getCellById({ editor, id: message.output.id })
if (!cell) {
return
}
return handleCellOutputMessage({
message,
cell,
kernel: this,
outputType: message.output.outputType,
})
} else if (message.type === ClientMessages.githubWorkflowDispatch) {
await handleGitHubMessage({ messaging: this.messaging, message })
} else if (message.type === ClientMessages.displayPrompt) {
const cell = await getCellById({ editor, id: message.output.id })
if (!cell || message.output.id !== cell.metadata?.['runme.dev/id']) {
return
}
const categories = await getNotebookCategories(this.context, cell.document.uri)
const { disposables, answer } = await suggestCategories(
categories,
message.output.title,
message.output.placeholder,
)
this.#disposables.push(...disposables)
postClientMessage(this.messaging, ClientMessages.onPrompt, {
answer,
id: message.output.id,
})
} else if (message.type === ClientMessages.getState) {
const cell = await getCellById({ editor, id: message.output.id })
if (!cell) {
return
}
postClientMessage(this.messaging, ClientMessages.onGetState, {
state: message.output.state,
value: getAnnotations(cell).category.split(CATEGORY_SEPARATOR).filter(Boolean),
id: message.output.id,
})
} else if (message.type === ClientMessages.setState) {
const cell = await getCellById({ editor, id: message.output.id })
if (!cell) {
return
}
const categories = await getNotebookCategories(this.context, cell.notebook.uri)
await setNotebookCategories(
this.context,
cell.notebook.uri,
new Set([...message.output.value, ...categories].sort()),
)
} else if (message.type === ClientMessages.onCategoryChange) {
const btnSave = 'Save Now'
window.showWarningMessage('Save changes?', btnSave).then((val) => {
if (val === btnSave) {
commands.executeCommand('workbench.action.files.save')
}
})
} else if (message.type === ClientMessages.platformApiRequest) {
return handlePlatformApiMessage({
messaging: this.messaging,
message,
editor,
kernel: this,
})
} else if (message.type === ClientMessages.optionsModal) {
if (message.output.telemetryEvent) {
TelemetryReporter.sendTelemetryEvent(message.output.telemetryEvent)
}
const answer = await window.showInformationMessage(
message.output.title,
{ modal: true },
...message.output.options,
)
if (answer === 'Open') {
await commands.executeCommand(
'vscode.open',
Uri.parse('https://stateful.com/redirect/runme-panel'),
)
}
} else if (message.type === ClientMessages.optionsMessage) {
if (message.output.telemetryEvent) {
TelemetryReporter.sendTelemetryEvent(message.output.telemetryEvent)
}
const answer = await window.showInformationMessage(
message.output.title,
{ modal: !!message.output.modal },
...message.output.options,
)
return postClientMessage(this.messaging, ClientMessages.onOptionsMessage, {
option: answer,
id: message.output.id,
})
} else if (message.type === ClientMessages.copyTextToClipboard) {
await env.clipboard.writeText(message.output.text)
return postClientMessage(this.messaging, ClientMessages.onCopyTextToClipboard, {
id: message.output.id,
})
} else if (message.type === ClientMessages.openExternalLink) {
TelemetryReporter.sendRawTelemetryEvent(message.output.telemetryEvent)
return env.openExternal(Uri.parse(message.output.link))
} else if (message.type === ClientMessages.tangleEvent) {
const webviewPanel = this.panelManager.getPanel(message.output.webviewId)
if (webviewPanel) {
return webviewPanel.getBus()?.emit('onSave', {
cellId: message.output.data.cellId,
})
}
} else if (
[
ClientMessages.gcpClusterCheckStatus,
ClientMessages.gcpClusterDetails,
ClientMessages.gcpClusterDetailsNewCell,
ClientMessages.gcpVMInstanceAction,
ClientMessages.gcpCloudRunAction,
ClientMessages.gcpLoadServices,
].includes(message.type)
) {
return handleGCPMessage({ messaging: this.messaging, message, editor })
} else if (
[ClientMessages.awsEC2InstanceAction, ClientMessages.awsEKSClusterAction].includes(
message.type,
)
) {
return handleAWSMessage({ messaging: this.messaging, message, editor })
} else if (message.type === ClientMessages.gistCell) {
TelemetryReporter.sendRawTelemetryEvent(message.output.telemetryEvent)
return handleGistMessage({
kernel: this,
editor,
message,
})
} else if (message.type === ClientMessages.daggerCliAction) {
let args: string[] = []
switch (message.output.argument) {
case 'path':
if (!message.output.command.trimEnd().includes('export')) {
const remotePath = await window.showInputBox({
title: 'Specify path please',
})
if (!remotePath) {
return
}
args.push('--path')
args.push(remotePath || '')
break
}
const loc = await window.showSaveDialog({
title: 'Specify path please',
})
if (loc) {
args.push('--path')
const dir = path.dirname(editor.notebook.uri.fsPath)
const idx = loc.fsPath.lastIndexOf(dir)
if (idx >= 0) {
args.push(loc.fsPath.substring(idx + dir.length + 1))
} else {
args.push(loc.fsPath)
}
break
}
return
case 'address':
const address = await window.showInputBox({
prompt: 'Specify the address please',
})
if (address) {
args.push('--address')
args.push(address)
break
}
return
}
const cellText = `${message.output.command} ${args.join(' ')}`
return insertCodeCell(message.output.cellId, editor, cellText, 'sh', false)
} else if (message.type.startsWith('terminal:')) {
return
} else if (message.type === ClientMessages.featuresRequest) {
const snapshot = features.getSnapshot(this.featuresState$)
postClientMessage(this.messaging, ClientMessages.featuresResponse, {
snapshot: snapshot,
})
return
}
log.error(`Unknown kernel event type: ${message.type}`)
}
private async _executeAll(cells: NotebookCell[]) {
const sessionOutputsDoc = cells.find((c) =>
GrpcSerializer.isDocumentSessionOutputs(c.notebook.metadata),
)
if (sessionOutputsDoc) {
const { notebook } = sessionOutputsDoc
await askAlternativeOutputsAction(path.dirname(notebook.uri.fsPath), notebook.metadata)
return
}
await commands.executeCommand('setContext', NOTEBOOK_HAS_CATEGORIES, false)
const totalNotebookCells =
(cells[0] &&
cells[0].notebook.getCells().filter((cell) => cell.kind === NotebookCellKind.Code)
.length) ||
0
const totalCellsToExecute = cells.length
let showConfirmPrompt = totalNotebookCells === totalCellsToExecute && totalNotebookCells > 1
let cellsExecuted = 0
for (const cell of cells) {
const annotations = getAnnotations(cell)
// Skip cells that are not assigned to requested category if requested
if (
totalCellsToExecute > 1 &&
this.category &&
!annotations.category.split(CATEGORY_SEPARATOR).includes(this.category)
) {
continue
}
// skip cells that are excluded from run all
if (totalCellsToExecute > 1 && annotations.excludeFromRunAll) {
continue
}
if (showConfirmPrompt) {
const cellText = cell.document.getText()
const cellLabel =
annotations.name || cellText.length > 20 ? `${cellText.slice(0, 20)}...` : cellText
const answer = (await window.showQuickPick(Object.values(ConfirmationItems), {
title: `Are you sure you like to run "${cellLabel}"?`,
ignoreFocusOut: true,
})) as ConfirmationItems | undefined
if (answer === ConfirmationItems.No) {
continue
}
if (answer === ConfirmationItems.Skip) {
showConfirmPrompt = false
}
if (answer === ConfirmationItems.Cancel) {
TelemetryReporter.sendTelemetryEvent('cells.executeAll', {
'cells.total': totalNotebookCells?.toString(),
'cells.executed': cellsExecuted?.toString(),
})
return
}
}
await this._doExecuteCell(cell)
cellsExecuted++
}
this.category = undefined
const uri = cells[0] && cells[0].notebook.uri
const categories = await getNotebookCategories(this.context, uri)
await commands.executeCommand('setContext', NOTEBOOK_HAS_CATEGORIES, !!categories.length)
TelemetryReporter.sendTelemetryEvent('cells.executeAll', {
'cells.total': totalNotebookCells?.toString(),
'cells.executed': cellsExecuted?.toString(),
})
}
#handleActiveColorThemeMessage(): void {
this.messaging.postMessage(<ClientMessage<ClientMessages.activeThemeChanged>>{
type: ClientMessages.activeThemeChanged,
})
}
public async createCellExecution(
cell: NotebookCell,
): Promise<RunmeNotebookCellExecution | undefined> {
return await this.cellManager.createNotebookCellExecution(cell)
}
public async getCellOutputs(cell: NotebookCell): Promise<NotebookCellOutputManager> {
return await this.cellManager.getNotebookOutputs(cell)
}
public async openAndWaitForTextDocument(uri: Uri): Promise<TextDocument | undefined> {
let textDocument = await workspace.openTextDocument(uri)
if (!textDocument) {
textDocument = await new Promise((resolve) => {
workspace.onDidOpenTextDocument((document: TextDocument) => {
resolve(document)
})
})
}
return textDocument
}
private async _doExecuteCell(cell: NotebookCell): Promise<void> {
const runningCell = await this.openAndWaitForTextDocument(cell.document.uri)
if (!runningCell) {
throw new Error(`Failed to open ${cell.document.uri}`)
}
const runmeExec = await this.createCellExecution(cell)
if (!runmeExec) {
log.warn('Unable to create execution')
return
}
const exec = runmeExec.underlyingExecution
const id = (cell.metadata as Serializer.Metadata)['runme.dev/id']
if (!id) {
throw new Error('Executable cell does not have ID field!')
}
TelemetryReporter.sendTelemetryEvent('cell.startExecute')
// todo(sebastian): rewrite to use non-blocking impl
const execCellReport = getEventReporter().reportExecution(cell)
runmeExec.start(Date.now())
const annotations = getAnnotations(cell)
const { key: execKey, resource } = getKeyInfo(runningCell, annotations)
let successfulCellExecution: boolean
const envMgr = this.getEnvironmentManager()
const outputs = await this.getCellOutputs(cell)
const runnerOpts: IKernelRunnerOptions = {
kernel: this,
doc: cell.document,
context: this.context,
runner: this.runner!,
exec,
runningCell,
messaging: this.messaging,
cellId: id,
execKey,
outputs,
runnerEnv: this.runnerEnv,
envMgr,
resource,
}
const executorOpts: IKernelExecutorOptions = {
context: this.context,
kernel: this,
runner: this.runner,
runnerEnv: this.runnerEnv,
doc: runningCell,
exec,
outputs,
messaging: this.messaging,
envMgr,
resource,
cellText: runningCell.getText(),
}
try {
successfulCellExecution = await this.executeCell(runnerOpts, executorOpts)
} catch (e: any) {
successfulCellExecution = false
log.error('Error executing cell', e.message)
window.showErrorMessage(e.message)
} finally {
await execCellReport
}
TelemetryReporter.sendTelemetryEvent('cell.endExecute', {
'cell.success': successfulCellExecution?.toString(),
'cell.mimeType': annotations.mimeType,
})
runmeExec.end(successfulCellExecution, Date.now())
}
private async executeCell(
runnerOpts: IKernelRunnerOptions,
executorOpts: IKernelExecutorOptions,
): Promise<boolean> {
// hard disable gRPC runner on windows
// TODO(sebastian): support windows shells?
const supportsGrpcRunner = this.runner && !isWindows()
const execKey = runnerOpts.execKey
const hasExecutor = execKey in executor
if (
supportsGrpcRunner &&
(isShellLanguage(execKey) || !hasExecutor) &&
executorOpts.resource === 'None'
) {
return this.executeRunnerSafe(runnerOpts)
}
/**
* error if no custom notebook executor + renderer is available
*/
if (!hasExecutor) {
throw Error('Cell language is not executable')
}
const executorByKey: IKernelExecutor = executor[execKey as keyof typeof executor]
if (executorOpts.resource === 'URI' && supportsGrpcRunner) {
const runScript = (text?: string) => {
const cellText = text || executorOpts.cellText
return executorByKey({ ...executorOpts, cellText })
}
const opts: IKernelRunnerOptions = {
...runnerOpts,
runScript,
}
return runUriResource(opts)
}
if (execKey === 'dagger' && supportsGrpcRunner) {
const notify = async (res?: string): Promise<boolean> => {
try {
const daggerJsonParsed = JSON.parse(res || '{}')
daggerJsonParsed.runme = { cellText: runnerOpts.runningCell.getText() }
await this.saveOutputState(runnerOpts.exec.cell, OutputType.dagger, {
json: JSON.stringify(daggerJsonParsed),
})
return new Promise<boolean>((resolve) => {
this.messaging
.postMessage(<ClientMessage<ClientMessages.daggerSyncState>>{
type: ClientMessages.daggerSyncState,
output: {
id: runnerOpts.cellId,
cellId: runnerOpts.cellId,
json: daggerJsonParsed,
},
})
.then(() => resolve(true))
})
} catch (e) {
// not a fatal error
if (e instanceof Error) {
console.error(e.message)
}
await this.saveOutputState(runnerOpts.exec.cell, OutputType.dagger, {
text: res,
})
return new Promise<boolean>((resolve) => {
this.messaging
.postMessage(<ClientMessage<ClientMessages.daggerSyncState>>{
type: ClientMessages.daggerSyncState,
output: {
id: runnerOpts.cellId,
cellId: runnerOpts.cellId,
text: res,
},
})
.then(() => resolve(true))
})
}
}
const runSecondary = () => {
return runUriResource({ ...runnerOpts, runScript: notify })
}
this.cleanOutputState(runnerOpts.exec.cell, OutputType.dagger)
return this.executeRunnerSafe({ ...runnerOpts, runScript: runSecondary })
}
return executorByKey(executorOpts)
}
private async executeRunnerSafe(executor: IKernelRunnerOptions): Promise<boolean> {
return executeRunner(executor).catch((e) => {
if (e instanceof RpcError) {
if (e.message.includes('invalid LanguageId')) {
// todo(sebastian): provide "Configure" button to trigger foldout
window
.showWarningMessage(
// eslint-disable-next-line max-len
'Not every language is automatically executable. ' +
'Click below to learn what language runtimes are auto-detected. ' +
'You can also set an "interpreter" in the "Configure" foldout to define how this cell executes.',
'See Auto-Detected Languages',
)
.then((link) => {
if (!link) {
return
}
TelemetryReporter.sendTelemetryEvent('survey.shebangAutoDetectRedirect', {})
commands.executeCommand(
'vscode.open',
Uri.parse('https://runme.dev/redirect/shebang-auto-detect'),
)
})
return false
}
// cover runnerv1 and v2
if (
e.message.includes('invalid ProgramName') ||
e.message.includes('failed program lookup') ||
e.message.includes('unable to locate program')
) {
window.showErrorMessage(
// eslint-disable-next-line max-len
'Unable to locate interpreter specified in shebang (aka #!). Please check the cell\'s "Configure" foldout.',
)
return false
}
}
window.showErrorMessage(`Internal failure executing runner: ${e.message}`)
log.error('Internal failure executing runner', e.message)
return false
})
}
useRunner(runner: IRunner) {
this.runnerReadyListener?.dispose()
if (this.hasExperimentEnabled('grpcRunner') && runner) {
if (this.runner === runner) {
return
}
this.runner = runner
this.runnerReadyListener = runner.onReady(this.newRunnerEnvironment.bind(this))
}
}
getRunnerEnvironment(): IRunnerEnvironment | undefined {
return this.runnerEnv
}
async newRunnerEnvironment({ address }: IRunnerReady): Promise<void> {
if (!this.runner) {
log.error('Skipping new runner environment request since runner is not initialized.')
return
}
// keep old address unless there's a new one
this.address = address || this.address