-
Notifications
You must be signed in to change notification settings - Fork 16
/
extension.ts
629 lines (565 loc) · 21.7 KB
/
extension.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
import {
Disposable,
workspace,
notebooks,
commands,
ExtensionContext,
tasks,
window,
env,
Uri,
NotebookCell,
} from 'vscode'
import { TelemetryReporter } from 'vscode-telemetry'
import Channel from 'tangle/webviews'
import { NotebookUiEvent, Serializer, SyncSchema, FeatureName } from '../types'
import {
getDocsUrlFor,
getForceNewWindowConfig,
getServerRunnerVersion,
getSessionOutputs,
getServerLifecycleIdentity,
} from '../utils/configuration'
import {
AuthenticationProviders,
NOTEBOOK_LIFECYCLE_ID,
TELEMETRY_EVENTS,
WebViews,
} from '../constants'
import { Kernel } from './kernel'
import KernelServer from './server/kernelServer'
import KernelServerError from './server/kernelServerError'
import {
ToggleTerminalProvider,
BackgroundTaskProvider,
StopBackgroundTaskProvider,
} from './provider/background'
import {
getDefaultWorkspace,
bootFile,
resetNotebookSettings,
openFileAsRunmeNotebook,
} from './utils'
import { RunmeTaskProvider } from './provider/runmeTask'
import {
toggleTerminal,
runCLICommand,
copyCellToClipboard,
openAsRunmeNotebook,
openSplitViewAsMarkdownText,
stopBackgroundTask,
createNewRunmeNotebook,
welcome,
tryIt,
openFileInRunme,
openIntegratedTerminal,
authenticateWithGitHub,
displayCategoriesSelector,
runCellsByCategory,
addToRecommendedExtension,
openRunmeSettings,
toggleAutosave,
askNewRunnerSession,
runCellWithPrompts,
toggleMasking,
createGistCommand,
toggleAuthorMode,
createCellGistCommand,
runForkCommand,
selectEnvironment,
} from './commands'
import { WasmSerializer, GrpcSerializer, SerializerBase } from './serializer'
import { RunmeLauncherProvider, RunmeTreeProvider } from './provider/launcher'
import { RunmeLauncherProvider as RunmeLauncherProviderBeta } from './provider/launcherBeta'
import { RunmeUriHandler } from './handler/uri'
import GrpcRunner, { IRunner } from './runner'
import * as survey from './survey'
import { RunmeCodeLensProvider } from './provider/codelens'
import CloudPanel from './panels/cloud'
import { createBootFileRunnerForActiveNotebook, createBootFileRunnerWatcher } from './handler/utils'
import { GithubAuthProvider } from './provider/githubAuth'
import { StatefulAuthProvider } from './provider/statefulAuth'
import { IPanel } from './panels/base'
import { EnvStorePanel } from './panels/notebook'
import { NotebookCellStatusBarProvider } from './provider/cellStatusBar/notebook'
import { SessionOutputCellStatusBarProvider } from './provider/cellStatusBar/sessionOutput'
import { GrpcReporter } from './reporter'
import * as manager from './ai/manager'
import getLogger from './logger'
import { EnvironmentManager } from './environment/manager'
import ContextState from './contextState'
import { RunmeIdentity } from './grpc/serializerTypes'
import * as features from './features'
import AuthSessionChangeHandler from './authSessionChangeHandler'
export class RunmeExtension {
protected serializer?: SerializerBase
async initialize(context: ExtensionContext) {
const kernel = new Kernel(context)
const grpcSerializer = kernel.hasExperimentEnabled('grpcSerializer')
const grpcServer = kernel.hasExperimentEnabled('grpcServer')
const grpcRunner = kernel.hasExperimentEnabled('grpcRunner')
const server = new KernelServer(
context.extensionUri,
kernel.envProps,
{
retryOnFailure: true,
maxNumberOfIntents: 10,
},
!grpcServer,
grpcRunner,
)
let runner: IRunner | undefined
if (grpcRunner) {
runner = new GrpcRunner(server)
kernel.useRunner(runner)
}
// register ahead of attempting to server launch for error handling
context.subscriptions.push(
RunmeExtension.registerCommand('runme.openSettings', openRunmeSettings),
)
const reporter = new GrpcReporter(context, server)
const serializer = grpcSerializer
? new GrpcSerializer(context, server, kernel)
: new WasmSerializer(context, kernel)
this.serializer = serializer
kernel.setSerializer(serializer as GrpcSerializer)
kernel.setReporter(reporter)
let treeViewer: RunmeTreeProvider
if (kernel.isFeatureOn(FeatureName.NewTreeProvider)) {
await commands.executeCommand('setContext', 'runme.launcher.isExpanded', false)
await commands.executeCommand('setContext', 'runme.launcher.includeUnnamed', false)
treeViewer = new RunmeLauncherProviderBeta(kernel, serializer)
if (treeViewer.openNotebook) {
context.subscriptions.push(
RunmeExtension.registerCommand(
'runme.openNotebook',
treeViewer.openNotebook.bind(treeViewer),
),
)
}
if (treeViewer.runCell) {
context.subscriptions.push(
RunmeExtension.registerCommand(
'runme.runSelectedCell',
treeViewer.runCell.bind(treeViewer),
),
)
}
if (treeViewer.openCell) {
RunmeExtension.registerCommand(
'runme.openSelectedCell',
treeViewer.openCell.bind(treeViewer),
)
}
} else {
treeViewer = new RunmeLauncherProvider(getDefaultWorkspace())
}
const runmeTaskProvider = tasks.registerTaskProvider(
RunmeTaskProvider.id,
new RunmeTaskProvider(context, treeViewer, serializer, kernel, server, runner),
)
/**
* Start the Kernel server
*/
try {
await server.launch()
} catch (e) {
// Unrecoverable error happened
if (e instanceof KernelServerError) {
TelemetryReporter.sendTelemetryErrorEvent('extension.server', { data: e.message })
if (server.transportType === KernelServer.transportTypeDefault) {
return window
.showErrorMessage(
`Failed to start Kernel server (reason: ${e.message}).` +
' Consider switching from TCP to Unix Domain Socket in Settings.',
'Open Settings',
)
.then((action) => {
if (!action) {
return
}
return commands.executeCommand('runme.openSettings', 'runme.server.transportType')
})
}
return window
.showErrorMessage(`Failed to start Kernel server. Reason: ${e.message}`)
.then((action) => {
if (!action) {
return
}
})
}
TelemetryReporter.sendTelemetryErrorEvent('extension.server', { data: (e as Error).message })
return window.showErrorMessage(
'Failed to start Kernel server, please try to reload the window. ' +
`Reason: ${(e as any).message}`,
)
}
// Start the AIManager. This will enable the AI services if the user has enabled them.
const aiManager = new manager.AIManager(kernel)
// We need to hang onto a reference to the AIManager so it doesn't get garbage collected until the
// extension is deactivated.
context.subscriptions.push(aiManager)
const winCodeLensRunSurvey = new survey.SurveyWinCodeLensRun(context)
const surveys: Disposable[] = [
winCodeLensRunSurvey,
new survey.SurveyAddExtensionToRepo(context),
new survey.SurveyActiveUserFeedback(context),
new survey.SurveyFeedbackButton(context),
new survey.SurveyNotifyV2(context),
]
const stopBackgroundTaskProvider = new StopBackgroundTaskProvider()
const runCLI = runCLICommand(kernel, context.extensionUri, !!grpcRunner)
const runFork = runForkCommand(kernel, context.extensionUri, !!grpcRunner)
const codeLensProvider = new RunmeCodeLensProvider(
context.extensionUri,
serializer,
runCLI,
winCodeLensRunSurvey,
runner,
kernel,
server,
)
const environment = new EnvironmentManager(context)
await resetNotebookSettings()
const transientOutputs = !getSessionOutputs()
const omitKeys: Serializer.Metadata = {
['runme.dev/name']: undefined,
['runme.dev/nameGenerated']: undefined,
['runme.dev/id']: undefined,
['runme.dev/textRange']: undefined,
}
const transientCellMetadata = Object.fromEntries(Object.keys(omitKeys).map((k) => [k, true]))
context.subscriptions.push(
kernel,
serializer,
server,
treeViewer,
StatefulAuthProvider.instance,
AuthSessionChangeHandler.instance,
...this.registerPanels(kernel, context),
...surveys,
workspace.registerNotebookSerializer(Kernel.type, serializer, {
transientCellMetadata,
transientOutputs,
}),
notebooks.registerNotebookCellStatusBarItemProvider(
Kernel.type,
new ToggleTerminalProvider(kernel),
),
notebooks.registerNotebookCellStatusBarItemProvider(
Kernel.type,
new BackgroundTaskProvider(),
),
notebooks.registerNotebookCellStatusBarItemProvider(Kernel.type, stopBackgroundTaskProvider),
notebooks.registerNotebookCellStatusBarItemProvider(
Kernel.type,
new NotebookCellStatusBarProvider(kernel),
),
notebooks.registerNotebookCellStatusBarItemProvider(
Kernel.type,
new SessionOutputCellStatusBarProvider(kernel),
),
stopBackgroundTaskProvider,
codeLensProvider,
RunmeExtension.registerCommand('runme.resetRunnerSession', () => askNewRunnerSession(kernel)),
RunmeExtension.registerCommand('runme.openIntegratedTerminal', openIntegratedTerminal),
RunmeExtension.registerCommand('runme.toggleTerminal', toggleTerminal(kernel, !!grpcRunner)),
RunmeExtension.registerCommand('runme.runCliCommand', runCLI),
RunmeExtension.registerCommand('runme.runForkCommand', runFork),
RunmeExtension.registerCommand('runme.copyCellToClipboard', copyCellToClipboard),
RunmeExtension.registerCommand('runme.stopBackgroundTask', stopBackgroundTask),
RunmeExtension.registerCommand(
'runme.openSplitViewAsMarkdownText',
openSplitViewAsMarkdownText,
),
RunmeExtension.registerCommand('runme.openAsRunmeNotebook', openAsRunmeNotebook),
RunmeExtension.registerCommand('runme.runCategory', (notebook) => {
return displayCategoriesSelector({ context, kernel, notebookToolbarCommand: notebook })
}),
RunmeExtension.registerCommand('runme.runCellCategory', (cell) =>
runCellsByCategory(cell, kernel),
),
RunmeExtension.registerCommand('runme.new', createNewRunmeNotebook),
RunmeExtension.registerCommand('runme.welcome', welcome),
RunmeExtension.registerCommand('runme.try', () => tryIt(context)),
RunmeExtension.registerCommand('runme.openRunmeFile', treeViewer.openFile.bind(treeViewer)),
RunmeExtension.registerCommand('runme.keybinding.noop', () => {}),
RunmeExtension.registerCommand('runme.file.openInRunme', openFileInRunme),
RunmeExtension.registerCommand('runme.runWithPrompts', (cell) =>
runCellWithPrompts(cell, kernel),
),
runmeTaskProvider,
/**
* tree viewer items
*/
window.registerTreeDataProvider('runme.launcher', treeViewer),
RunmeExtension.registerCommand(
'runme.collapseTreeView',
treeViewer.collapseAll.bind(treeViewer),
),
RunmeExtension.registerCommand('runme.expandTreeView', treeViewer.expandAll.bind(treeViewer)),
RunmeExtension.registerCommand(
'runme.tasksIncludeUnnamed',
treeViewer.includeUnnamed.bind(treeViewer),
),
RunmeExtension.registerCommand(
'runme.tasksExcludeUnnamed',
treeViewer.excludeUnnamed.bind(treeViewer),
),
RunmeExtension.registerCommand('runme.authenticateWithGitHub', authenticateWithGitHub),
/**
* Uri handler
*/
window.registerUriHandler(new RunmeUriHandler(context, kernel, getForceNewWindowConfig())),
/**
* Runme Message Display commands
*/
RunmeExtension.registerCommand('runme.addToRecommendedExtensions', () =>
addToRecommendedExtension(context),
),
createBootFileRunnerForActiveNotebook(context, kernel),
createBootFileRunnerWatcher(context, kernel),
RunmeExtension.registerCommand(
'runme.notebookOutputsMasked',
this.handleMasking(kernel, true).bind(this),
),
RunmeExtension.registerCommand(
'runme.notebookOutputsUnmasked',
this.handleMasking(kernel, false).bind(this),
),
RunmeExtension.registerCommand('runme.notebookGistShare', (event: NotebookUiEvent) =>
createGistCommand(event, context),
),
RunmeExtension.registerCommand('runme.cellGistShare', (cell: NotebookCell) =>
createCellGistCommand(cell, context),
),
RunmeExtension.registerCommand('runme.notebookAutoSaveOn', () => toggleAutosave(false)),
RunmeExtension.registerCommand('runme.notebookAutoSaveOff', () => toggleAutosave(true)),
RunmeExtension.registerCommand('runme.environments', () => selectEnvironment(environment)),
RunmeExtension.registerCommand('runme.notebookAuthorMode', () =>
toggleAuthorMode(false, kernel),
),
RunmeExtension.registerCommand('runme.notebookExplorerMode', () =>
toggleAuthorMode(true, kernel),
),
RunmeExtension.registerCommand('runme.notebookSessionOutputs', (e: NotebookUiEvent) => {
const runnerEnv = kernel.getRunnerEnvironment()
const sessionId = runnerEnv?.getSessionId()
if (!e.ui || !sessionId) {
return
}
const { notebookUri } = e.notebookEditor
const outputFilePath = GrpcSerializer.getOutputsUri(notebookUri, sessionId)
openFileAsRunmeNotebook(outputFilePath)
}),
RunmeExtension.registerCommand('runme.lifecycleIdentityNone', () =>
commands.executeCommand('runme.lifecycleIdentitySelection', RunmeIdentity.UNSPECIFIED),
),
RunmeExtension.registerCommand('runme.lifecycleIdentityAll', () =>
commands.executeCommand('runme.lifecycleIdentitySelection', RunmeIdentity.ALL),
),
RunmeExtension.registerCommand('runme.lifecycleIdentityDoc', () =>
commands.executeCommand('runme.lifecycleIdentitySelection', RunmeIdentity.DOCUMENT),
),
RunmeExtension.registerCommand('runme.lifecycleIdentityCell', () =>
commands.executeCommand('runme.lifecycleIdentitySelection', RunmeIdentity.CELL),
),
commands.registerCommand(
'runme.lifecycleIdentitySelection',
async (identity?: RunmeIdentity) => {
if (identity === undefined) {
window.showErrorMessage('Cannot run command without identity selection')
return
}
// skip if lifecycle identity selection didn't change
const current = ContextState.getKey(NOTEBOOK_LIFECYCLE_ID)
if (current === identity) {
return
}
TelemetryReporter.sendTelemetryEvent('extension.command', {
command: 'runme.lifecycleIdentitySelection',
})
await ContextState.addKey(NOTEBOOK_LIFECYCLE_ID, identity)
await Promise.all(
workspace.notebookDocuments.map((doc) =>
serializer.switchLifecycleIdentity(doc, identity),
),
)
},
),
RunmeExtension.registerCommand('runme.openCloudPanel', () =>
commands.executeCommand('workbench.view.extension.runme'),
),
// Register a command to generate completions using foyle
RunmeExtension.registerCommand(
'runme.aiGenerate',
aiManager.completionGenerator.generateCompletion,
),
)
TelemetryReporter.sendTelemetryEvent('config', { runnerVersion: getServerRunnerVersion() })
await bootFile(context)
if (
kernel.hasExperimentEnabled('shellWarning', false) &&
context.globalState.get<boolean>(TELEMETRY_EVENTS.ShellWarning, true)
) {
const showUnsupportedShellMessage = async () => {
const learnMore = 'Learn more'
const dontAskAgain = "Don't ask again"
TelemetryReporter.sendTelemetryEvent(TELEMETRY_EVENTS.ShellWarning)
const answer = await window.showWarningMessage(
'Your current shell has limited or no support.' +
' Please consider switching to sh, bash, or zsh.' +
' Click "Learn more" for additional resources.',
learnMore,
dontAskAgain,
)
if (answer === learnMore) {
const url = getDocsUrlFor('/r/extension/unsupported-shell')
env.openExternal(Uri.parse(url))
} else if (answer === dontAskAgain) {
await context.globalState.update(TELEMETRY_EVENTS.ShellWarning, false)
}
}
const logger = getLogger('runme.experiments.shellWarning')
kernel
.runProgram('echo $SHELL')
.then((output) => {
if (output === false) {
return
}
const supportedShells = ['bash', 'zsh']
const isSupported = supportedShells.some((sh) => output?.includes(sh))
logger.info(`Shell: ${output}`)
if (!isSupported) {
showUnsupportedShellMessage()
}
})
.catch((e) => {
logger.error(e)
showUnsupportedShellMessage()
})
}
if (kernel.isFeatureOn(FeatureName.RequireStatefulAuth)) {
const logger = getLogger(FeatureName.RequireStatefulAuth)
try {
const session = await StatefulAuthProvider.instance.ensureSession()
const nunmeIdentity = session ? RunmeIdentity.ALL : getServerLifecycleIdentity()
await commands.executeCommand('runme.lifecycleIdentitySelection', nunmeIdentity)
kernel.updateFeatureContext('statefulAuth', !!session)
} catch (error) {
let message
if (error instanceof Error) {
message = error.message
} else {
message = JSON.stringify(error)
}
logger.error(message)
}
}
if (kernel.isFeatureOn(FeatureName.Gist)) {
context.subscriptions.push(new GithubAuthProvider(context, kernel))
}
AuthSessionChangeHandler.instance.addListener((e) => {
if (
StatefulAuthProvider.instance &&
kernel.isFeatureOn(FeatureName.RequireStatefulAuth) &&
e.provider.id === AuthenticationProviders.Stateful
) {
StatefulAuthProvider.instance.currentSession().then(async (session) => {
if (session) {
await commands.executeCommand('runme.lifecycleIdentitySelection', RunmeIdentity.ALL)
kernel.emitPanelEvent('runme.cloud', 'onCommand', {
name: 'signIn',
panelId: 'runme.cloud',
})
} else {
const settingsDefault = getServerLifecycleIdentity()
await commands.executeCommand('runme.lifecycleIdentitySelection', settingsDefault)
kernel.emitPanelEvent('runme.cloud', 'onCommand', {
name: 'signOut',
panelId: 'runme.cloud',
})
}
kernel.updateFeatureContext('statefulAuth', !!session)
})
}
})
// only ever enabled in hosted playground
if (features.isOnInContextState(FeatureName.HostedPlayground)) {
await features.addTrustedDomains()
}
if (features.isOnInContextState(FeatureName.OpenTerminalOnStartup)) {
await features.autoOpenTerminal()
}
}
protected handleMasking(kernel: Kernel, maskingIsOn: boolean): (e: NotebookUiEvent) => void {
const showSessionExpiryErrMessage = () => {
return window.showErrorMessage(
'Cannot toggle masking of outputs for expired sessions. Consider re-running the original notebook',
{ modal: true },
)
}
return async (e: NotebookUiEvent) => {
if (!e.ui) {
return
}
const uri = e.notebookEditor.notebookUri
const runnerEnv = kernel.getRunnerEnvironment()
const sessionId = runnerEnv?.getSessionId()
if (!sessionId || !uri.fsPath.includes(sessionId)) {
await showSessionExpiryErrMessage()
return
}
await toggleMasking(maskingIsOn)
const written = (await this.serializer?.saveNotebookOutputs(uri)) ?? -1
if (written > -1) {
// success early return
return
}
await toggleMasking(!maskingIsOn)
await showSessionExpiryErrMessage()
}
}
protected registerPanels(kernel: Kernel, context: ExtensionContext): Disposable[] {
const register = (channel: Channel<SyncSchema>, factory: (pid: string) => IPanel) => {
return (id: string): Disposable[] => {
const p = factory(id)
const bus$ = channel.register([p.webview])
p.registerBus(bus$)
const webviewProvider = window.registerWebviewViewProvider(id, p)
kernel.registerWebview(id, p, webviewProvider)
return [webviewProvider]
}
}
const appChannel = new Channel<SyncSchema>('app')
const runmePanelIds: string[] = [
WebViews.RunmeCloud as const,
WebViews.RunmeChat as const,
WebViews.RunmeSearch as const,
]
const notebookChannel = new Channel<SyncSchema>('notebooks')
const notebookPanelIds: string[] = [WebViews.NotebookEnvStore as const]
return [
...runmePanelIds.map(register(appChannel, (id) => new CloudPanel(context, id))),
...notebookPanelIds.map(
register(notebookChannel, (id) => new EnvStorePanel(context, id, kernel.useMonitor())),
),
].flat()
}
static registerCommand(command: string, callback: (...args: any[]) => any, thisArg?: any) {
return commands.registerCommand(
command,
(...wrappedArgs: any[]) => {
TelemetryReporter.sendTelemetryEvent('extension.command', { command })
return callback(...wrappedArgs, thisArg)
},
thisArg,
)
}
static getExtensionIdentifier(context: ExtensionContext) {
const publisher = context.extension.packageJSON.publisher
const name = context.extension.packageJSON.name
return `${publisher}.${name}`
}
}