forked from ghostty-org/ghostty
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathWorktrunkSidebarView.swift
More file actions
1459 lines (1361 loc) · 53.9 KB
/
WorktrunkSidebarView.swift
File metadata and controls
1459 lines (1361 loc) · 53.9 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
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 AppKit
import SwiftUI
import UniformTypeIdentifiers
struct WorktrunkSidebarView: View {
@ObservedObject var store: WorktrunkStore
@ObservedObject var sidebarState: WorktrunkSidebarState
@ObservedObject var openTabsModel: WorktrunkOpenTabsModel
@ObservedObject var tooltipState: StatusRingTooltipState
let openWorktree: (String) -> Void
let openWorktreeAgent: (String, WorktrunkAgent) -> Void
var resumeSession: ((AISession) -> Void)?
let focusNativeTab: (Int) -> Void
let closeNativeTab: (Int) -> Void
let moveNativeTabBefore: (Int, Int) -> Void
let moveNativeTabAfter: (Int, Int) -> Void
var onSelectWorktree: ((String?) -> Void)?
@AppStorage(WorktrunkPreferences.defaultAgentKey) private var defaultActionRaw: String = WorktrunkDefaultAction.terminal.rawValue
@AppStorage(WorktrunkPreferences.sidebarTabsKey) private var sidebarTabsEnabled: Bool = true
@AppStorage(WorktrunkPreferences.displaySessionTimeKey) private var displaySessionTimeEnabled: Bool = true
@State private var createSheetRepo: WorktrunkStore.Repository?
@State private var removeRepoConfirm: WorktrunkStore.Repository?
@State private var removeWorktreeConfirm: WorktrunkStore.Worktree?
@State private var removeWorktreeForceConfirm: WorktrunkStore.Worktree?
@State private var removeWorktreeForceError: String?
@State private var showRepoPicker: Bool = false
@State private var repoSearchText: String = ""
@State private var sidebarTabsEndDropTarget: Bool = false
@StateObject private var sidebarScrollPreserver = SidebarListScrollPreserver()
private var availableAgents: [WorktrunkAgent] {
WorktrunkAgent.availableAgents()
}
private var availableActions: [WorktrunkDefaultAction] {
WorktrunkDefaultAction.availableActions()
}
private var defaultAction: WorktrunkDefaultAction {
WorktrunkDefaultAction.preferredAction(from: defaultActionRaw, availableActions: availableActions)
}
var body: some View {
VStack(spacing: 0) {
list
Divider()
if store.isRefreshing {
SidebarRefreshProgressBar()
.transition(.opacity)
}
HStack(spacing: 8) {
Button {
Task { await promptAddRepository() }
} label: {
Label("Add Repo…", systemImage: "plus")
}
.buttonStyle(.plain)
.help("Add repository")
Spacer(minLength: 0)
Button {
toggleSidebarListMode()
} label: {
Image(systemName: store.sidebarListMode == .flatWorktrees ? "list.bullet.indent" : "list.bullet")
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.help(store.sidebarListMode == .flatWorktrees ? "Switch to nested list" : "Switch to flat list")
Menu {
ForEach(WorktreeSortOrder.allCases, id: \.self) { order in
Button {
store.worktreeSortOrder = order
} label: {
if store.worktreeSortOrder == order {
Label(order.label, systemImage: "checkmark")
} else {
Text(order.label)
}
}
}
} label: {
Image(systemName: "arrow.up.arrow.down")
.foregroundStyle(.secondary)
}
.menuStyle(.borderlessButton)
.fixedSize()
.help("Sort worktrees")
}
.padding(.horizontal, 10)
.padding(.vertical, 8)
if let err = store.errorMessage, !err.isEmpty {
Divider()
VStack(alignment: .leading, spacing: 8) {
Text(err)
.font(.caption)
.foregroundStyle(.secondary)
if store.needsWorktrunkInstall {
HStack(spacing: 8) {
Button {
Task { _ = await store.installWorktrunk() }
} label: {
Text("Install Worktrunk…")
}
.disabled(store.isInstallingWorktrunk)
if store.isInstallingWorktrunk {
ProgressView()
.controlSize(.small)
}
}
}
}
.padding(8)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.frame(minWidth: 240, idealWidth: 280)
.environment(\.statusRingTooltipState, tooltipState)
.animation(.easeOut(duration: 0.08), value: store.isRefreshing)
.sheet(item: $createSheetRepo) { repo in
CreateWorktreeSheet(
store: store,
repoID: repo.id,
repoName: repo.name,
onOpen: { openWorktree($0) }
)
}
.onChange(of: showRepoPicker) { isShowing in
if isShowing { repoSearchText = "" }
}
.onChange(of: sidebarState.selection) { newValue in
var focusedWorktreePath: String?
if sidebarTabsEnabled {
let worktreePath: String?
switch newValue {
case .worktree(_, let path):
worktreePath = path
case .session(_, _, let path):
worktreePath = path
default:
worktreePath = nil
}
if let worktreePath {
let key = standardizedPath(worktreePath)
if let tab = openTabsModel.tabs.first(where: { tab in
guard let root = tab.worktreeRootPath else { return false }
return standardizedPath(root) == key
}) {
focusedWorktreePath = worktreePath
DispatchQueue.main.async {
focusNativeTab(tab.windowNumber)
}
}
}
}
switch newValue {
case .worktree(_, let path):
store.acknowledgeAgentStatus(for: path)
if focusedWorktreePath == path {
return
}
onSelectWorktree?(path)
case .session(_, _, let worktreePath):
store.acknowledgeAgentStatus(for: worktreePath)
if focusedWorktreePath == worktreePath {
return
}
onSelectWorktree?(worktreePath)
default:
onSelectWorktree?(nil)
}
}
.onChange(of: store.sidebarModelRevision) { _ in
if store.isRefreshing { return }
sidebarState.reconcile(with: store, listMode: store.sidebarListMode)
}
.onChange(of: store.isRefreshing) { isRefreshing in
if isRefreshing { return }
clearSelectionIfMainInFlatMode()
sidebarState.reconcile(with: store, listMode: store.sidebarListMode)
}
.onChange(of: store.sidebarListMode) { _ in
clearSelectionIfMainInFlatMode()
}
.onAppear {
if store.sidebarListMode == .nestedByRepo, sidebarState.expandedRepoIDs.isEmpty {
sidebarState.applyExpandedRepoIDs(
Set(store.sidebarSnapshot.repositories.map(\.id)),
listMode: store.sidebarListMode,
alwaysVisibleWorktreePaths: currentAlwaysVisibleWorktreePaths()
)
}
clearSelectionIfMainInFlatMode()
Task { await store.refreshForSidebarAppearIfNeeded() }
}
.alert(
"Remove Repository?",
isPresented: Binding(
get: { removeRepoConfirm != nil },
set: { if !$0 { removeRepoConfirm = nil } }
),
presenting: removeRepoConfirm
) { repo in
Button("Remove", role: .destructive) {
store.removeRepository(id: repo.id)
}
Button("Cancel", role: .cancel) {}
} message: { repo in
Text("Remove \(repo.name) from the sidebar. Nothing will be deleted from disk.")
}
.alert(
"Remove Worktree?",
isPresented: Binding(
get: { removeWorktreeConfirm != nil },
set: { if !$0 { removeWorktreeConfirm = nil } }
),
presenting: removeWorktreeConfirm
) { wt in
Button("Remove", role: .destructive) {
Task {
let ok = await store.removeWorktree(repoID: wt.repositoryID, branch: wt.branch)
if !ok {
removeWorktreeForceError = store.errorMessage ?? "Failed to remove worktree."
store.errorMessage = nil
removeWorktreeForceConfirm = wt
}
}
}
Button("Cancel", role: .cancel) {}
} message: { wt in
Text("This runs `wt remove \(wt.branch)` and deletes the worktree directory. The branch may be deleted if it's merged.")
}
.alert(
"Force Remove Worktree?",
isPresented: Binding(
get: { removeWorktreeForceConfirm != nil },
set: { if !$0 {
removeWorktreeForceConfirm = nil
removeWorktreeForceError = nil
} }
),
presenting: removeWorktreeForceConfirm
) { wt in
Button("Force Remove", role: .destructive) {
Task {
_ = await store.removeWorktree(repoID: wt.repositoryID, branch: wt.branch, force: true)
}
}
Button("Cancel", role: .cancel) {}
} message: { wt in
if let error = removeWorktreeForceError {
Text("\(error)\n\nForce remove will run `wt remove \(wt.branch) --force` and discard uncommitted changes.")
} else {
Text("This will run `wt remove \(wt.branch) --force` and discard uncommitted changes in that worktree.")
}
}
}
private var list: some View {
let selection = Binding(
get: { sidebarState.selection },
set: { sidebarState.selection = $0 }
)
let snapshot = store.sidebarSnapshot
let worktreeTabs: [WorktrunkOpenTabsModel.Tab] = {
guard sidebarTabsEnabled else { return [] }
var seen = Set<String>()
var result: [WorktrunkOpenTabsModel.Tab] = []
result.reserveCapacity(openTabsModel.tabs.count)
for tab in openTabsModel.tabs {
guard let root = tab.worktreeRootPath else { continue }
let key = standardizedPath(root)
guard !seen.contains(key) else { continue }
seen.insert(key)
result.append(tab)
}
return result
}()
let activeTabs = sidebarTabItems(from: worktreeTabs)
let topWorktreePaths = Set(activeTabs.map { standardizedPath($0.worktree.path) })
let activeTabWindowNumbers: [String: Int] = Dictionary(
uniqueKeysWithValues: activeTabs.map { item in
(standardizedPath(item.worktree.path), item.tab.windowNumber)
}
)
let lastActiveTabWindowNumber = activeTabs.last?.tab.windowNumber
let hasVisibleWorktreeRows: Bool = {
if store.sidebarListMode == .flatWorktrees {
return snapshot.flatWorktrees.contains { wt in
!topWorktreePaths.contains(standardizedPath(wt.path))
}
} else {
return !snapshot.repositories.isEmpty
}
}()
let worktreesLoadingSpacer: CGFloat = {
guard store.isRefreshing else { return 0 }
guard !hasVisibleWorktreeRows else { return 0 }
// OCR on the same-geometry screenshots measured the loading
// header 21.19 px left of the resting position. User feedback
// tuned that down slightly; 9.6 pt matches the current target.
return 9.6
}()
return List(selection: selection) {
if !activeTabs.isEmpty {
sidebarHeaderRow("Active", topPadding: -4)
sidebarTabsList(
snapshot: snapshot,
shownTabs: activeTabs,
windowNumberByWorktreePath: activeTabWindowNumbers
)
}
HStack(spacing: 8) {
HStack(spacing: 8) {
Text("Worktrees")
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
.textCase(nil)
}
.padding(.leading, -16 + worktreesLoadingSpacer)
Spacer(minLength: 0)
Button {
presentCreateWorktree(from: snapshot)
} label: {
Image(systemName: "plus")
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.disabled(snapshot.repositories.isEmpty)
.help(snapshot.repositories.isEmpty ? "Add a repository first" : "Create worktree")
.padding(.trailing, 8)
.popover(isPresented: $showRepoPicker) {
RepoPickerPopover(
repositories: store.sidebarSnapshot.repositories,
searchText: $repoSearchText
) { repo in
showRepoPicker = false
createSheetRepo = repo
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.padding(.top, activeTabs.isEmpty ? -2 : 4)
.listRowInsets(EdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 0))
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
.overlay(alignment: .top) {
if sidebarTabsEndDropTarget {
SidebarInsertionIndicatorLine()
}
}
.onDrop(of: [UTType.fileURL.identifier], isTargeted: Binding(
get: { sidebarTabsEndDropTarget },
set: { targeted in
DispatchQueue.main.async {
sidebarTabsEndDropTarget = targeted
}
}
)) { providers in
guard let lastActiveTabWindowNumber else { return false }
return SidebarFileURLDrop.loadURL(from: providers) { url in
guard let url else { return }
let key = URL(fileURLWithPath: url.path).standardizedFileURL.path
guard let moving = activeTabWindowNumbers[key] else { return }
guard moving != lastActiveTabWindowNumber else { return }
let scrollY = sidebarScrollPreserver.captureScrollY()
moveNativeTabAfter(moving, lastActiveTabWindowNumber)
if let scrollY {
DispatchQueue.main.async {
sidebarScrollPreserver.restoreScrollY(scrollY)
}
}
}
}
if store.sidebarListMode == .flatWorktrees {
flatWorktreeList(snapshot: snapshot, excludingWorktreePaths: topWorktreePaths)
} else {
nestedRepoList(snapshot: snapshot, excludingWorktreePaths: topWorktreePaths)
}
}
.background(SidebarListScrollFinder(preserver: sidebarScrollPreserver))
.id(store.sidebarListMode.rawValue + (sidebarTabsEnabled ? ".sidebarTabs" : ""))
.listStyle(.sidebar)
}
private func standardizedPath(_ path: String) -> String {
URL(fileURLWithPath: path).standardizedFileURL.path
}
private func findWorktree(forWorktreeRootPath rootPath: String) -> WorktrunkStore.Worktree? {
let root = standardizedPath(rootPath)
for repo in store.repositories {
for wt in store.worktrees(for: repo.id) where standardizedPath(wt.path) == root {
return wt
}
}
return nil
}
private func currentAlwaysVisibleWorktreePaths() -> Set<String> {
guard sidebarTabsEnabled else { return [] }
guard store.sidebarListMode == .nestedByRepo else { return [] }
let tabRoots = Set(openTabsModel.tabs.compactMap(\.worktreeRootPath).map(standardizedPath))
return tabRoots.intersection(store.sidebarWorktreePaths)
}
private func sidebarTabItems(from tabs: [WorktrunkOpenTabsModel.Tab]) -> [SidebarTabItem] {
tabs.compactMap { tab in
guard let root = tab.worktreeRootPath else { return nil }
guard let worktree = findWorktree(forWorktreeRootPath: root) else { return nil }
return SidebarTabItem(tab: tab, worktree: worktree)
}
}
@ViewBuilder
private func sidebarTabsList(
snapshot: WorktrunkStore.SidebarSnapshot,
shownTabs: [SidebarTabItem],
windowNumberByWorktreePath: [String: Int]
) -> some View {
let alwaysVisibleWorktreePaths = Set(windowNumberByWorktreePath.keys)
let moveBeforePreservingScroll: (Int, Int) -> Void = { moving, target in
let scrollY = sidebarScrollPreserver.captureScrollY()
moveNativeTabBefore(moving, target)
if let scrollY {
DispatchQueue.main.async {
sidebarScrollPreserver.restoreScrollY(scrollY)
}
}
}
let moveAfterPreservingScroll: (Int, Int) -> Void = { moving, target in
let scrollY = sidebarScrollPreserver.captureScrollY()
moveNativeTabAfter(moving, target)
if let scrollY {
DispatchQueue.main.async {
sidebarScrollPreserver.restoreScrollY(scrollY)
}
}
}
ForEach(shownTabs, id: \.tab.id) { item in
WorktreeTabDisclosureGroup(
store: store,
sidebarState: sidebarState,
snapshot: snapshot,
tab: item.tab,
worktree: item.worktree,
repoName: snapshot.repoNameByID[item.worktree.repositoryID],
resumeSession: resumeSession,
openWorktree: openWorktree,
openWorktreeAgent: openWorktreeAgent,
defaultAction: defaultAction,
availableAgents: availableAgents,
alwaysVisibleWorktreePaths: alwaysVisibleWorktreePaths,
focusNativeTab: focusNativeTab,
closeNativeTab: closeNativeTab,
onRemoveWorktree: { worktree in
removeWorktreeConfirm = worktree
},
moveBefore: moveBeforePreservingScroll,
moveAfter: moveAfterPreservingScroll,
windowNumberByWorktreePath: windowNumberByWorktreePath
)
}
}
@ViewBuilder
private func nestedRepoList(
snapshot: WorktrunkStore.SidebarSnapshot,
excludingWorktreePaths: Set<String>
) -> some View {
ForEach(snapshot.repositories) { repo in
DisclosureGroup(
isExpanded: Binding(
get: { sidebarState.expandedRepoIDs.contains(repo.id) },
set: { newValue in
var next = sidebarState.expandedRepoIDs
if newValue {
next.insert(repo.id)
} else {
next.remove(repo.id)
}
sidebarState.applyExpandedRepoIDs(
next,
listMode: store.sidebarListMode,
alwaysVisibleWorktreePaths: excludingWorktreePaths
)
}
)
) {
let worktrees = (snapshot.worktreesByRepositoryID[repo.id] ?? []).filter { wt in
!excludingWorktreePaths.contains(standardizedPath(wt.path))
}
if worktrees.isEmpty {
Text("No worktrees")
.foregroundStyle(.secondary)
} else {
ForEach(worktrees) { wt in
worktreeDisclosureGroup(
wt: wt,
repoName: nil,
showsFolderIcon: true,
showsRepoName: false
)
}
}
} label: {
HStack(spacing: 4) {
Text(repo.name)
.lineLimit(1)
Spacer()
Button {
createSheetRepo = repo
} label: {
Image(systemName: "plus")
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.help("Create worktree")
}
.contentShape(Rectangle())
.contextMenu {
Button("Remove Repository…") {
removeRepoConfirm = repo
}
Button("Reveal in Finder") {
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: repo.path)])
}
}
}
.tag(SidebarSelection.repo(id: repo.id))
}
}
@ViewBuilder
private func flatWorktreeList(
snapshot: WorktrunkStore.SidebarSnapshot,
excludingWorktreePaths: Set<String>
) -> some View {
let repoNameByID = snapshot.repoNameByID
let worktrees = snapshot.flatWorktrees.filter { wt in
!excludingWorktreePaths.contains(standardizedPath(wt.path))
}
if worktrees.isEmpty {
if !store.isRefreshing {
Text("No worktrees")
.foregroundStyle(.secondary)
}
} else {
ForEach(worktrees) { wt in
worktreeDisclosureGroup(
wt: wt,
repoName: repoNameByID[wt.repositoryID],
showsFolderIcon: false,
showsRepoName: true
)
}
}
}
@ViewBuilder
private func sidebarHeaderRow(
_ title: String,
topPadding: CGFloat = 0,
bottomPadding: CGFloat = 0,
leadingShift: CGFloat = -16,
addAction: (() -> Void)? = nil,
addDisabled: Bool = false
) -> some View {
HStack(spacing: 8) {
HStack(spacing: 8) {
Text(title)
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
.textCase(nil)
}
.padding(.leading, leadingShift)
Spacer(minLength: 0)
if let addAction {
Button(action: addAction) {
Image(systemName: "plus")
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.disabled(addDisabled)
.help(addDisabled ? "Add a repository first" : "Create worktree")
.padding(.trailing, 8)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.padding(.top, topPadding)
.padding(.bottom, bottomPadding)
.listRowInsets(EdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 0))
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
}
private func presentCreateWorktree(from snapshot: WorktrunkStore.SidebarSnapshot) {
guard !snapshot.repositories.isEmpty else { return }
if snapshot.repositories.count == 1, let repo = snapshot.repositories.first {
createSheetRepo = repo
} else {
showRepoPicker = true
}
}
private func toggleSidebarListMode() {
if store.sidebarListMode == .flatWorktrees {
store.sidebarListMode = .nestedByRepo
} else {
store.sidebarListMode = .flatWorktrees
store.worktreeSortOrder = .recentActivity
clearSelectionIfMainInFlatMode()
}
}
private func clearSelectionIfMainInFlatMode() {
guard store.sidebarListMode == .flatWorktrees else { return }
guard let selection = sidebarState.selection else { return }
let selectedPath: String?
switch selection {
case .worktree(_, let path):
selectedPath = path
case .session(_, _, let worktreePath):
selectedPath = worktreePath
case .repo:
selectedPath = nil
}
guard let selectedPath else { return }
let isMain = store.repositories
.flatMap { store.worktrees(for: $0.id) }
.first(where: { $0.path == selectedPath })?
.isMain ?? false
if isMain {
sidebarState.selection = nil
}
}
@ViewBuilder
private func worktreeDisclosureGroup(
wt: WorktrunkStore.Worktree,
repoName: String?,
showsFolderIcon: Bool,
showsRepoName: Bool
) -> some View {
DisclosureGroup(
isExpanded: Binding(
get: { sidebarState.expandedWorktreePaths.contains(wt.path) },
set: { newValue in
var next = sidebarState.expandedWorktreePaths
if newValue {
next.insert(wt.path)
} else {
next.remove(wt.path)
}
sidebarState.applyExpandedWorktreePaths(
next,
listMode: store.sidebarListMode,
alwaysVisibleWorktreePaths: currentAlwaysVisibleWorktreePaths()
)
}
)
) {
let sessions = store.sessions(for: wt.path)
if sessions.isEmpty {
Text("No sessions")
.font(.caption)
.foregroundStyle(.secondary)
.padding(.leading, 8)
} else {
ForEach(sessions) { session in
SessionRow(session: session, onResume: {
store.acknowledgeAgentStatus(for: session.worktreePath)
resumeSession?(session)
})
.tag(SidebarSelection.session(
id: session.id,
repoID: wt.repositoryID,
worktreePath: wt.path
))
}
}
} label: {
worktreeRowLabel(
wt: wt,
repoName: repoName,
showsFolderIcon: showsFolderIcon,
showsRepoName: showsRepoName
)
.padding(.leading, 4)
.alignmentGuide(.firstTextBaseline) { d in
d[VerticalAlignment.center]
}
.contentShape(Rectangle())
.contextMenu {
Button("Remove Worktree…") {
removeWorktreeConfirm = wt
}
.disabled(wt.isMain)
Button("Reveal in Finder") {
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: wt.path)])
}
}
}
.tag(SidebarSelection.worktree(repoID: wt.repositoryID, path: wt.path))
}
@ViewBuilder
private func worktreeRowLabel(
wt: WorktrunkStore.Worktree,
repoName: String?,
showsFolderIcon: Bool,
showsRepoName: Bool
) -> some View {
HStack(spacing: 8) {
let tracking = store.gitTracking(for: wt.path)
let recencyDate = store.recencyDate(for: wt.path)
let status = store.agentStatus(for: wt.path)
let showsChanges = tracking.map { $0.lineAdditions > 0 || $0.lineDeletions > 0 } ?? false
if wt.isCurrent {
Image(systemName: "location.fill")
.foregroundStyle(.secondary)
} else if wt.isMain {
Image(systemName: "house.fill")
.foregroundStyle(.secondary)
} else if showsFolderIcon {
Image(systemName: "folder")
.foregroundStyle(.secondary)
}
if showsRepoName, let repoName {
VStack(alignment: .leading, spacing: 1) {
Text(wt.branch)
.lineLimit(1)
if displaySessionTimeEnabled, let recencyDate {
(Text(repoName) + Text(" • ") + Text(recencyDate, style: .relative))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
} else {
Text(repoName)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
}
.layoutPriority(1)
} else {
Text(wt.branch)
.lineLimit(1)
.layoutPriority(1)
}
Spacer(minLength: 0)
let ciState = store.ciState(for: wt.path)
let prStatus = store.prStatus(for: wt.path)
let hasStatusRing = status != nil || ciState != .none
if hasStatusRing || showsChanges {
HStack(spacing: 6) {
// Combined status ring (agent + CI)
if hasStatusRing {
StatusRingView(
agentStatus: status,
ciState: ciState,
prStatus: prStatus,
onTap: {
if let url = prStatus?.url, let nsURL = URL(string: url) {
NSWorkspace.shared.open(nsURL)
}
}
)
}
// Line changes badge
if let tracking, showsChanges {
WorktreeChangeBadge(
additions: tracking.lineAdditions,
deletions: tracking.lineDeletions
)
}
}
.fixedSize(horizontal: true, vertical: false)
.layoutPriority(2)
}
HStack(spacing: 4) {
Button {
if let agent = defaultAction.agent {
store.acknowledgeAgentStatus(for: wt.path)
openWorktreeAgent(wt.path, agent)
} else {
openWorktree(wt.path)
}
} label: {
Image(systemName: "plus")
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.help("New \(defaultAction.title) in \(wt.branch)")
Menu {
ForEach(availableAgents) { agent in
Button {
store.acknowledgeAgentStatus(for: wt.path)
openWorktreeAgent(wt.path, agent)
} label: {
Text("New \(agent.title) Session")
}
}
if !availableAgents.isEmpty {
Divider()
}
Button {
openWorktree(wt.path)
} label: {
Text("New Terminal")
}
} label: {
Image(systemName: "chevron.down")
.font(.system(size: 9))
.foregroundColor(Color.secondary)
.frame(width: 16, height: 16)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.menuIndicator(.hidden)
.help("New terminal or agent session")
}
}
}
private func promptAddRepository() async {
let panel = NSOpenPanel()
panel.canChooseFiles = false
panel.canChooseDirectories = true
panel.allowsMultipleSelection = false
panel.prompt = "Add"
panel.title = "Add Repository"
let url: URL? = await withCheckedContinuation { continuation in
panel.begin { response in
if response == .OK {
continuation.resume(returning: panel.url)
} else {
continuation.resume(returning: nil)
}
}
}
guard let url else { return }
await store.addRepositoryValidated(path: url.path)
}
}
private struct SidebarTabItem {
let tab: WorktrunkOpenTabsModel.Tab
let worktree: WorktrunkStore.Worktree
}
private enum SidebarFileURLDrop {
static func loadURL(from providers: [NSItemProvider], completion: @escaping (URL?) -> Void) -> Bool {
guard let provider = providers.first(where: {
$0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier)
}) else {
return false
}
provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, _ in
let url: URL? = {
guard let data = item as? Data else { return nil }
return URL(dataRepresentation: data, relativeTo: nil)
}()
DispatchQueue.main.async {
completion(url)
}
}
return true
}
}
private struct SidebarTabFallbackRow: View {
let tab: WorktrunkOpenTabsModel.Tab
let focusNativeTab: (Int) -> Void
var body: some View {
HStack(spacing: 8) {
Text(tab.title.isEmpty ? "Terminal" : tab.title)
.lineLimit(1)
Spacer(minLength: 0)
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.padding(.vertical, 2)
.onTapGesture {
focusNativeTab(tab.windowNumber)
}
}
}
private struct SidebarInsertionIndicatorLine: View {
@Environment(\.colorScheme) private var colorScheme
private var color: Color {
// High-contrast insertion indicator.
colorScheme == .dark ? Color.white.opacity(0.9) : Color.black.opacity(0.35)
}
var body: some View {
Rectangle()
.fill(color)
.frame(height: 2)
.padding(.horizontal, 12)
}
}
private struct WorktreeTabDisclosureGroup: View {
@ObservedObject var store: WorktrunkStore
@ObservedObject var sidebarState: WorktrunkSidebarState
let snapshot: WorktrunkStore.SidebarSnapshot
let tab: WorktrunkOpenTabsModel.Tab
let worktree: WorktrunkStore.Worktree
let repoName: String?
let resumeSession: ((AISession) -> Void)?
let openWorktree: (String) -> Void
let openWorktreeAgent: (String, WorktrunkAgent) -> Void
let defaultAction: WorktrunkDefaultAction
let availableAgents: [WorktrunkAgent]
let alwaysVisibleWorktreePaths: Set<String>
let focusNativeTab: (Int) -> Void
let closeNativeTab: (Int) -> Void
let onRemoveWorktree: (WorktrunkStore.Worktree) -> Void
let moveBefore: (Int, Int) -> Void
let moveAfter: (Int, Int) -> Void
let windowNumberByWorktreePath: [String: Int]
var body: some View {
DisclosureGroup(
isExpanded: Binding(
get: { sidebarState.expandedWorktreePaths.contains(worktree.path) },
set: { newValue in
var next = sidebarState.expandedWorktreePaths
if newValue {
next.insert(worktree.path)
} else {
next.remove(worktree.path)
}
sidebarState.applyExpandedWorktreePaths(
next,
listMode: store.sidebarListMode,
alwaysVisibleWorktreePaths: alwaysVisibleWorktreePaths
)
}
)
) {
let sessions = store.sessions(for: worktree.path)
if sessions.isEmpty {
Text("No sessions")
.font(.caption)
.foregroundStyle(.secondary)
.padding(.leading, 8)
} else {
ForEach(sessions) { session in
SessionRow(session: session, onResume: {
store.acknowledgeAgentStatus(for: session.worktreePath)
resumeSession?(session)
})
.tag(SidebarSelection.session(
id: session.id,
repoID: worktree.repositoryID,
worktreePath: worktree.path
))
}
}
} label: {
WorktreeTabRowLabel(