-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-workflows.js
More file actions
801 lines (732 loc) · 25.8 KB
/
Copy pathgithub-workflows.js
File metadata and controls
801 lines (732 loc) · 25.8 KB
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
import { toWorkspaceRecordKey } from '../workspace/workspace-tab-helpers.js'
const initializeGitHubWorkflows = ({
createGitHubPrEditorSyncController,
createGitHubChatDrawer,
createGitHubPrDrawer,
createWorkspacesDrawer,
ensureJsxTransformSource,
collectTopLevelDeclarations,
cdnImports,
importFromCdnWithFallback,
githubAiContextState,
byotControls,
getCurrentGitHubToken,
getCurrentSelectedRepository,
aiChatToggle,
aiChatDrawer,
aiChatClose,
aiChatPrompt,
aiChatModel,
aiChatIncludeEditors,
aiChatSend,
aiChatClear,
aiChatStatus,
aiChatRepository,
aiChatMessages,
githubPrToggle,
githubPrDrawer,
githubPrClose,
githubPrRepoSelect,
githubPrBaseBranch,
githubPrHeadBranch,
githubPrTitle,
githubPrBody,
githubPrCommitMessage,
githubPrIncludeAppWrapper,
githubPrSubmit,
openPrTitle,
githubPrStatus,
workspacesToggle,
workspacesDrawer,
workspacesClose,
workspacesStatus,
workspacesRepository,
workspacesInitialize,
workspacesShare,
workspacesNew,
workspacesSelect,
workspacesFontCssUrlInput,
workspacesFontCssUrlLoad,
workspacesOpen,
workspacesRename,
workspacesRemove,
workspaceStorage,
getActiveWorkspaceRecordId,
getActiveWorkspaceDisplayLabel,
setActiveWorkspacePersistedMetadata,
setActiveWorkspaceRecordId,
setActiveWorkspaceCreatedAt,
buildWorkspaceRecordSnapshot,
listLocalContextRecords,
refreshLocalContextOptions,
applyWorkspaceRecord,
applyWorkspaceFontCssUrl,
syncActiveWorkspaceRepositoryScope,
forkWorkspaceFromCurrentState,
flushWorkspaceSave,
getWorkspacePrFileCommits,
getEditorSyncTargets,
getRenderMode,
getStyleMode,
setCurrentSelectedRepository,
clearCurrentSelectedRepository,
getPersistedActivePrContext,
reconcileWorkspaceTabsWithPushUpdates,
getActivePrContextSyncKey,
prContextUi,
onPrContextStateChange,
onPrContextVerifiedClosed,
onPrContextClosed,
getTokenForVisibility,
getActivePrEditorSyncKey,
syncFromActiveContext,
applyRenderMode,
applyStyleMode,
formatActivePrReference,
githubPrContextClose,
confirmAction,
setStatus,
showAppToast,
shareCurrentLocalWorkspace,
getActiveWorkspaceTabContext,
getWorkspaceTabContexts,
applyWorkspaceTabContent,
scheduleRender,
}) => {
const getCurrentWritableRepositories = () =>
githubAiContextState.writableRepositories.length > 0
? [...githubAiContextState.writableRepositories]
: byotControls.getWritableRepositories()
const getTopLevelDeclarations = async source => {
if (typeof source !== 'string' || !source.trim()) {
return []
}
const transformJsxSource = await ensureJsxTransformSource({
cdnImports,
importFromCdnWithFallback,
})
return collectTopLevelDeclarations({ source, transformJsxSource })
}
const shouldReconcileWorkspaceUpdatesForRepository = repositoryFullName => {
const normalizedActiveRepository =
typeof githubAiContextState.activePrContext?.repositoryFullName === 'string'
? githubAiContextState.activePrContext.repositoryFullName.trim()
: ''
const normalizedIncomingRepository =
typeof repositoryFullName === 'string' ? repositoryFullName.trim() : ''
return (
!normalizedActiveRepository ||
!normalizedIncomingRepository ||
normalizedActiveRepository === normalizedIncomingRepository
)
}
const toSafeRepositoryFullName = value =>
typeof value === 'string' ? value.trim() : ''
const toSafeWorkspaceText = value => (typeof value === 'string' ? value.trim() : '')
const shouldApplyActivePrEditorSync = ({ repository, activeContext }) => {
const syncedContextKey = getActivePrContextSyncKey(activeContext)
const currentSyncKey = getActivePrEditorSyncKey()
if (!syncedContextKey || syncedContextKey !== currentSyncKey) {
return false
}
const selectedRepositoryFullName = toSafeRepositoryFullName(
getCurrentSelectedRepository()?.fullName,
)
const incomingRepositoryFullName = toSafeRepositoryFullName(repository?.fullName)
const activeContextRepositoryFullName = toSafeRepositoryFullName(
activeContext?.repositoryFullName,
)
if (
selectedRepositoryFullName &&
incomingRepositoryFullName &&
selectedRepositoryFullName !== incomingRepositoryFullName
) {
return false
}
if (
activeContextRepositoryFullName &&
incomingRepositoryFullName &&
activeContextRepositoryFullName !== incomingRepositoryFullName
) {
return false
}
return true
}
const persistActiveWorkspaceSnapshot = async () => {
if (typeof buildWorkspaceRecordSnapshot !== 'function') {
return null
}
const activeWorkspaceRecordId =
typeof getActiveWorkspaceRecordId === 'function' ? getActiveWorkspaceRecordId() : ''
const snapshot =
typeof activeWorkspaceRecordId === 'string' && activeWorkspaceRecordId.trim()
? buildWorkspaceRecordSnapshot({ recordId: activeWorkspaceRecordId })
: buildWorkspaceRecordSnapshot()
if (!snapshot || typeof snapshot !== 'object') {
return null
}
const savedWorkspaceRecord = await workspaceStorage.upsertWorkspace(snapshot)
setActiveWorkspaceRecordId(savedWorkspaceRecord.id)
setActiveWorkspaceCreatedAt(savedWorkspaceRecord.createdAt ?? null)
return savedWorkspaceRecord
}
const prEditorSyncController = createGitHubPrEditorSyncController({
shouldApplySyncResult: shouldApplyActivePrEditorSync,
})
const chatDrawerController = createGitHubChatDrawer({
toggleButton: aiChatToggle,
drawer: aiChatDrawer,
closeButton: aiChatClose,
promptInput: aiChatPrompt,
modelSelect: aiChatModel,
includeEditorsContextToggle: aiChatIncludeEditors,
sendButton: aiChatSend,
clearButton: aiChatClear,
statusNode: aiChatStatus,
repositoryNode: aiChatRepository,
messagesNode: aiChatMessages,
getToken: getCurrentGitHubToken,
getSelectedRepository: getCurrentSelectedRepository,
getActiveWorkspaceTabContext,
getWorkspaceTabContexts,
applyWorkspaceTabContent,
scheduleRender,
getRenderMode,
getStyleMode,
getDrawerSide: () => {
return 'right'
},
getPersistedActivePrContext,
})
const prDrawerController = createGitHubPrDrawer({
toggleButton: githubPrToggle,
drawer: githubPrDrawer,
closeButton: githubPrClose,
repositorySelect: githubPrRepoSelect,
baseBranchInput: githubPrBaseBranch,
headBranchInput: githubPrHeadBranch,
prTitleInput: githubPrTitle,
prBodyInput: githubPrBody,
commitMessageInput: githubPrCommitMessage,
includeAppWrapperToggle: githubPrIncludeAppWrapper,
submitButton: githubPrSubmit,
titleNode: openPrTitle,
statusNode: githubPrStatus,
getToken: getCurrentGitHubToken,
getSelectedRepository: getCurrentSelectedRepository,
getWritableRepositories: getCurrentWritableRepositories,
setSelectedRepository: setCurrentSelectedRepository,
getFileCommits: getWorkspacePrFileCommits,
getEditorSyncTargets,
getTopLevelDeclarations,
getRenderMode,
getStyleMode,
getDrawerSide: () => {
return 'right'
},
confirmBeforeSubmit: options => {
confirmAction(options)
},
onPullRequestOpened: async ({
url,
fileUpdates,
repositoryFullName,
pullRequestNumber,
branch,
}) => {
if (typeof onPrContextStateChange === 'function') {
onPrContextStateChange(githubAiContextState.activePrContext)
}
const activeContextSyncKey = getActivePrContextSyncKey(
githubAiContextState.activePrContext,
)
if (activeContextSyncKey && activeContextSyncKey === getActivePrEditorSyncKey()) {
prContextUi.markActivePrEditorContentSynced()
}
const message = url
? `Pull request opened: ${url}`
: 'Pull request opened successfully.'
if (shouldReconcileWorkspaceUpdatesForRepository(repositoryFullName)) {
reconcileWorkspaceTabsWithPushUpdates(fileUpdates)
}
if (typeof flushWorkspaceSave === 'function') {
try {
await flushWorkspaceSave({ preserveRecordId: true })
} catch {
/* Save failures are already surfaced through saver onError. */
}
}
const activeWorkspaceRecordId =
typeof getActiveWorkspaceRecordId === 'function'
? getActiveWorkspaceRecordId()
: ''
if (activeWorkspaceRecordId) {
const activeWorkspaceRecord = await workspaceStorage.getWorkspaceById(
activeWorkspaceRecordId,
)
if (activeWorkspaceRecord && typeof activeWorkspaceRecord === 'object') {
const nextHeadBranch =
typeof githubAiContextState.activePrContext?.headBranch === 'string' &&
githubAiContextState.activePrContext.headBranch.trim()
? githubAiContextState.activePrContext.headBranch.trim()
: typeof branch === 'string' && branch.trim()
? branch.trim()
: typeof activeWorkspaceRecord.head === 'string'
? activeWorkspaceRecord.head
: ''
const nextBaseBranch =
typeof githubAiContextState.activePrContext?.baseBranch === 'string' &&
githubAiContextState.activePrContext.baseBranch.trim()
? githubAiContextState.activePrContext.baseBranch.trim()
: typeof activeWorkspaceRecord.base === 'string'
? activeWorkspaceRecord.base
: ''
const nextRepositoryFullName =
toSafeRepositoryFullName(repositoryFullName) ||
toSafeRepositoryFullName(
githubAiContextState.activePrContext?.repositoryFullName,
) ||
toSafeRepositoryFullName(activeWorkspaceRecord.repo)
const nextPrTitle =
typeof githubAiContextState.activePrContext?.prTitle === 'string' &&
githubAiContextState.activePrContext.prTitle.trim()
? githubAiContextState.activePrContext.prTitle
: typeof activeWorkspaceRecord.prTitle === 'string'
? activeWorkspaceRecord.prTitle
: ''
const nextPrNumber =
typeof pullRequestNumber === 'number' && Number.isFinite(pullRequestNumber)
? pullRequestNumber
: typeof githubAiContextState.activePrContext?.pullRequestNumber ===
'number' &&
Number.isFinite(githubAiContextState.activePrContext.pullRequestNumber)
? githubAiContextState.activePrContext.pullRequestNumber
: null
const savedWorkspaceRecord = await workspaceStorage.upsertWorkspace({
...activeWorkspaceRecord,
workspaceScope: nextRepositoryFullName ? 'repository' : 'local',
workspaceKey: toWorkspaceRecordKey({
repositoryFullName: nextRepositoryFullName,
headBranch: nextHeadBranch,
}),
repo: nextRepositoryFullName,
base: nextBaseBranch,
head: nextHeadBranch,
prContextState: 'active',
prNumber: nextPrNumber,
prTitle: nextPrTitle,
})
setActiveWorkspaceRecordId(savedWorkspaceRecord.id)
setActiveWorkspaceCreatedAt(savedWorkspaceRecord.createdAt ?? null)
}
}
await refreshLocalContextOptions()
showAppToast(message)
},
onPullRequestCommitPushed: async ({ repositoryFullName, branch, fileUpdates }) => {
if (shouldReconcileWorkspaceUpdatesForRepository(repositoryFullName)) {
reconcileWorkspaceTabsWithPushUpdates(fileUpdates)
}
try {
await persistActiveWorkspaceSnapshot()
} catch {
/* Fall back to debounced saver flush below. */
}
if (typeof flushWorkspaceSave === 'function') {
try {
await flushWorkspaceSave({ preserveRecordId: true })
} catch {
/* Save failures are already surfaced through saver onError. */
}
}
const fileCount = Array.isArray(fileUpdates) ? fileUpdates.length : 0
const message =
fileCount > 0
? `Pushed commit to ${branch} (${fileCount} file${fileCount === 1 ? '' : 's'}).`
: `Pushed commit to ${branch}.`
showAppToast(message)
},
onActivePrContextChange: activeContext => {
prContextUi.setActivePrContext(activeContext)
prContextUi.syncAiChatTokenVisibility(getTokenForVisibility())
if (typeof onPrContextStateChange === 'function') {
onPrContextStateChange(activeContext)
}
},
onSavedPullRequestContextClosed: payload => {
if (typeof onPrContextVerifiedClosed === 'function') {
onPrContextVerifiedClosed(payload)
}
},
onSyncActivePrEditorContent: async args => {
if (!shouldApplyActivePrEditorSync(args ?? {})) {
const tabTargets = Array.isArray(args?.syncTargets?.tabTargets)
? args.syncTargets.tabTargets
: []
return {
synced: false,
syncedTabCount: 0,
totalTabCount: tabTargets.length,
}
}
const result = await prEditorSyncController.syncFromActiveContext(args)
if (!shouldApplyActivePrEditorSync(args ?? {})) {
return result
}
if (result?.synced === true) {
prContextUi.markActivePrEditorContentSynced()
syncFromActiveContext({
tabTargets: result?.syncTargets?.tabTargets ?? args?.syncTargets?.tabTargets,
})
}
return result
},
onRestoreRenderMode: mode => {
applyRenderMode({ mode, fromActivePrContext: true })
},
onRestoreStyleMode: mode => {
applyStyleMode({ mode })
},
})
const workspacesDrawerController = createWorkspacesDrawer({
toggleButton: workspacesToggle,
drawer: workspacesDrawer,
closeButton: workspacesClose,
statusNode: workspacesStatus,
repositorySelect: workspacesRepository,
getActiveWorkspaceId: () => getActiveWorkspaceRecordId(),
initializeButton: workspacesInitialize,
shareButton: workspacesShare,
newButton: workspacesNew,
selectInput: workspacesSelect,
fontCssUrlInput: workspacesFontCssUrlInput,
fontCssUrlLoadButton: workspacesFontCssUrlLoad,
openButton: workspacesOpen,
renameButton: workspacesRename,
removeButton: workspacesRemove,
getActiveWorkspaceDisplayLabel: workspace =>
typeof getActiveWorkspaceDisplayLabel === 'function'
? toSafeWorkspaceText(getActiveWorkspaceDisplayLabel(workspace))
: '',
getRepositoryFilterOptions: () =>
getCurrentWritableRepositories().map(repository => ({
value: repository.fullName,
label: repository.fullName,
})),
getSelectedRepositoryFilter: () => {
const selectedRepository = getCurrentSelectedRepository()
if (typeof selectedRepository?.fullName === 'string') {
const fullName = selectedRepository.fullName.trim()
if (fullName) {
return fullName
}
}
return '__local__'
},
onRepositoryFilterChange: async () => {
prDrawerController.resetStatus?.()
prDrawerController.syncRepositories()
},
getDrawerSide: () => {
return 'right'
},
onRefreshRequested: listLocalContextRecords,
onShareCurrentWorkspace: async repositoryFilter => {
const normalizedFilter =
typeof repositoryFilter === 'string' ? repositoryFilter.trim() : ''
const isLocalFilter = !normalizedFilter || normalizedFilter === '__local__'
if (!isLocalFilter) {
workspacesDrawerController?.setStatus(
'Share is only available for Local workspaces.',
'error',
)
return false
}
if (typeof shareCurrentLocalWorkspace !== 'function') {
workspacesDrawerController?.setStatus('Share is currently unavailable.', 'error')
return false
}
try {
await shareCurrentLocalWorkspace()
return true
} catch (error) {
const message =
error instanceof Error ? error.message : 'Could not share workspace.'
workspacesDrawerController?.setStatus(`Share failed: ${message}`, 'error')
return false
}
},
onInitializeWorkspace: async repositoryFilter => {
const normalizedFilter =
typeof repositoryFilter === 'string' ? repositoryFilter.trim() : ''
if (!normalizedFilter || normalizedFilter === '__local__') {
return false
}
const repositoryFullName = normalizedFilter
try {
await syncActiveWorkspaceRepositoryScope?.(repositoryFullName, {
rekeyRecord: false,
})
setCurrentSelectedRepository?.(repositoryFullName)
await refreshLocalContextOptions()
prDrawerController.resetStatus?.()
prDrawerController.syncRepositories()
return true
} catch {
workspacesDrawerController?.setStatus('Could not initialize workspace.', 'error')
return false
}
},
onCreateWorkspace: async repositoryFilter => {
const normalizedFilter =
typeof repositoryFilter === 'string' ? repositoryFilter.trim() : ''
const repositoryFullName =
normalizedFilter && normalizedFilter !== '__local__' ? normalizedFilter : ''
try {
await forkWorkspaceFromCurrentState?.(repositoryFullName)
prDrawerController.clearSelectedRepositoryActivePrContext?.({
resetForm: false,
})
if (repositoryFullName) {
setCurrentSelectedRepository?.(repositoryFullName)
} else {
clearCurrentSelectedRepository?.()
}
await refreshLocalContextOptions()
prDrawerController.resetStatus?.()
prDrawerController.syncRepositories()
return true
} catch {
workspacesDrawerController?.setStatus('Could not create workspace.', 'error')
return false
}
},
onLoadFontCssUrl: async fontCssUrl => {
if (typeof applyWorkspaceFontCssUrl !== 'function') {
return false
}
try {
await applyWorkspaceFontCssUrl(fontCssUrl)
if (typeof scheduleRender === 'function') {
await Promise.resolve(scheduleRender())
}
return true
} catch {
workspacesDrawerController?.setStatus('Could not load font CSS URL.', 'error')
return false
}
},
onOpenSelected: async workspaceId => {
try {
try {
await flushWorkspaceSave?.({ preserveRecordId: true })
} catch {
/* Save failures are surfaced via saver onError; continue with open attempt. */
}
const record = await workspaceStorage.getWorkspaceById(workspaceId)
if (!record) {
await refreshLocalContextOptions()
workspacesDrawerController?.setStatus(
'Stored workspace no longer exists.',
'error',
)
return false
}
const applied = await applyWorkspaceRecord(record, { silent: false })
if (applied) {
prDrawerController.resetStatus?.()
prDrawerController.syncRepositories()
}
return applied
} catch {
workspacesDrawerController?.setStatus(
'Could not load selected workspace.',
'error',
)
return false
}
},
onRenameSelected: async workspaceId => {
try {
const record = await workspaceStorage.getWorkspaceById(workspaceId)
if (!record) {
await refreshLocalContextOptions()
workspacesDrawerController?.setStatus(
'Stored workspace no longer exists.',
'error',
)
return false
}
const workspaceScope = toSafeWorkspaceText(record.workspaceScope).toLowerCase()
const isLocalWorkspace =
workspaceScope === 'local' ||
(!workspaceScope && !toSafeWorkspaceText(record.repo))
if (!isLocalWorkspace) {
workspacesDrawerController?.setStatus(
'Only Local workspaces can be renamed here.',
'error',
)
return false
}
const workspacePrContextState =
toSafeWorkspaceText(record.prContextState).toLowerCase() || 'inactive'
const hasWorkspacePrNumber =
typeof record.prNumber === 'number' && Number.isFinite(record.prNumber)
const isPrAssociatedWorkspace =
workspacePrContextState !== 'inactive' || hasWorkspacePrNumber
if (isPrAssociatedWorkspace) {
workspacesDrawerController?.setStatus(
'Use Pull Request controls to rename PR-associated workspaces.',
'error',
)
return false
}
const isActiveWorkspace = getActiveWorkspaceRecordId() === workspaceId
const currentWorkspaceName =
toSafeWorkspaceText(record.prTitle) ||
toSafeWorkspaceText(record.head) ||
toSafeWorkspaceText(record.id) ||
'workspace'
const promptedWorkspaceName = window.prompt(
'Rename local workspace',
currentWorkspaceName,
)
if (promptedWorkspaceName === null) {
return false
}
const nextWorkspaceName = promptedWorkspaceName.trim()
if (!nextWorkspaceName) {
workspacesDrawerController?.setStatus(
'Workspace name cannot be empty.',
'error',
)
return false
}
if (nextWorkspaceName === currentWorkspaceName) {
return false
}
await workspaceStorage.upsertWorkspace({
...record,
prTitle: nextWorkspaceName,
lastModified: Date.now(),
})
if (
isActiveWorkspace &&
typeof setActiveWorkspacePersistedMetadata === 'function'
) {
setActiveWorkspacePersistedMetadata({
prTitle: nextWorkspaceName,
head: toSafeWorkspaceText(record.head),
})
}
await refreshLocalContextOptions()
return true
} catch {
workspacesDrawerController?.setStatus(
'Could not rename stored workspace.',
'error',
)
return false
}
},
onRemoveSelected: async workspaceId => {
confirmAction({
title: 'Remove stored workspace?',
copy: 'This removes only local workspace metadata and editor content from this browser.',
confirmButtonText: 'Remove',
onConfirm: () => {
void workspaceStorage
.removeWorkspace(workspaceId)
.then(async () => {
if (getActiveWorkspaceRecordId() === workspaceId) {
setActiveWorkspaceRecordId('')
setActiveWorkspaceCreatedAt(null)
}
await refreshLocalContextOptions()
workspacesDrawerController?.setStatus(
'Removed stored workspace.',
'neutral',
)
})
.catch(() => {
workspacesDrawerController?.setStatus(
'Could not remove stored workspace.',
'error',
)
})
},
})
return false
},
})
prDrawerController.setToken(githubAiContextState.token)
prDrawerController.setSelectedRepository(githubAiContextState.selectedRepository)
prDrawerController.syncRepositories()
prContextUi.setActivePrContext(prDrawerController.getActivePrContext())
if (typeof onPrContextStateChange === 'function') {
onPrContextStateChange(prDrawerController.getActivePrContext())
}
let isClosingActivePullRequest = false
githubPrContextClose?.addEventListener('click', () => {
if (!githubAiContextState.activePrContext || isClosingActivePullRequest) {
return
}
const activePrReference = formatActivePrReference(
githubAiContextState.activePrContext,
)
const referenceLine = activePrReference ? `PR: ${activePrReference}\n` : ''
confirmAction({
title: 'Close pull request on GitHub?',
copy: `${referenceLine}PR title: ${githubAiContextState.activePrContext.prTitle}\nHead branch: ${githubAiContextState.activePrContext.headBranch}\n\nThis will close the pull request on GitHub and clear the active pull request context for the selected repository.`,
confirmButtonText: 'Close PR on GitHub',
onConfirm: () => {
if (isClosingActivePullRequest) {
return
}
isClosingActivePullRequest = true
if (githubPrContextClose instanceof HTMLButtonElement) {
githubPrContextClose.disabled = true
}
void prDrawerController
.closeActivePullRequestOnGitHub()
.then(result => {
const reference = result?.reference
setStatus(
reference
? `Closed pull request on GitHub and cleared active context (${reference}).`
: 'Closed pull request on GitHub and cleared active context.',
'neutral',
)
if (typeof onPrContextClosed === 'function') {
onPrContextClosed(result)
}
showAppToast(
reference
? `Closed pull request on GitHub and cleared active context (${reference}).`
: 'Closed pull request on GitHub and cleared active context.',
)
})
.catch(error => {
const message =
error instanceof Error
? error.message
: 'Could not close pull request context on GitHub.'
setStatus(`Close context failed: ${message}`, 'error')
showAppToast(`Close context failed: ${message}`)
})
.finally(() => {
isClosingActivePullRequest = false
if (githubPrContextClose instanceof HTMLButtonElement) {
githubPrContextClose.disabled = false
}
})
},
})
})
return {
chatDrawerController,
prDrawerController,
workspacesDrawerController,
}
}
export { initializeGitHubWorkflows }