-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesktop_sidebar.dart
More file actions
1279 lines (1210 loc) · 48.4 KB
/
Copy pathdesktop_sidebar.dart
File metadata and controls
1279 lines (1210 loc) · 48.4 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 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
import '../../app/theme.dart';
import '../../store/connection.dart';
import '../../store/models.dart';
import '../../store/ports.dart';
import '../../store/store.dart';
import '../../ui/home/repo_chips.dart';
import '../../ui/ports/ports_popover.dart';
import '../../ui/ports/session_ports_glyph.dart';
import '../../ui/widgets/pr_state_style.dart';
import '../../ui/project/folder_browser.dart';
import '../../ui/widgets/connection_chip.dart';
import '../desktop_ports_route.dart';
import '../../status/status_event.dart';
import '../../status/status_providers.dart';
import '../metrics/metrics_button.dart';
import 'closed_sidebar_view.dart';
import 'connection_endpoint.dart';
import 'github_budget_button.dart';
import 'groups/group.dart';
import 'groups/group_providers.dart';
import 'groups/groups_controller.dart';
import 'new_worktree_dialog.dart';
import 'selected_session.dart';
import 'server_profile_badge.dart';
import '../../ui/widgets/session_status_dot.dart';
import 'split_view.dart' show SessionDragData;
import 'title_bar_strip.dart';
/// The left pane of the desktop two-pane chat. Mirrors the mobile repo-centric
/// home (SPEC-11): repos → worktrees (branch, diff stats, open PR) → the
/// sessions bound to each worktree. Footer shows the connection status + a hook
/// for the Settings/Server section.
class DesktopSidebar extends ConsumerWidget {
/// Creates the sidebar.
const DesktopSidebar({super.key, this.onOpenSettings});
/// Invoked when the user opens the Settings/Server section (Unit E wires the
/// existing control-panel screens here). Null hides the button.
final VoidCallback? onOpenSettings;
@override
Widget build(BuildContext context, WidgetRef ref) {
final repos = ref.watch(reposProvider).repos;
final sessions = ref.watch(sessionsProvider);
final selected = ref.watch(selectedSessionProvider);
final closed = ref.watch(sidebarClosedProvider);
final cs = Theme.of(context).colorScheme;
return Material(
color: cs.surfaceContainer,
child: Column(
children: [
const _Header(),
Expanded(
child: closed
? const ClosedSidebarView()
: repos.isEmpty
? const _EmptySidebar()
: ListView(
padding: const EdgeInsets.symmetric(vertical: kSpace8),
children: [
for (final repo in repos)
_RepoGroup(
repo: repo,
sessions: sessions.forProject(repo.id),
selectedId: selected,
onSelect: (id) => selectSessionExclusive(ref, id),
),
],
),
),
const Divider(height: 1),
_Footer(onOpenSettings: onOpenSettings),
],
),
);
}
}
class _Header extends ConsumerWidget {
const _Header();
@override
Widget build(BuildContext context, WidgetRef ref) {
// The OS titlebar is hidden (TitleBarStyle.hidden), so this strip is the
// window's drag handle. Its height clears the macOS traffic-light buttons
// that overlay the top-left corner. The fold button sits just to the right
// of the traffic lights and hides the sidebar entirely; Activity sits next
// to it, so the app's own voice lives in the chrome rather than at the far
// end of the footer's telemetry row.
return const TitleBarStrip(
leading: SidebarToggleControls(collapse: true),
trailing: Padding(
padding: EdgeInsets.only(right: 8),
child: ServerProfileBadge(),
),
);
}
}
/// One repo section: header row (name + current branch + stats), then its
/// worktrees with their sessions, then any pending draft sessions.
class _RepoGroup extends ConsumerStatefulWidget {
const _RepoGroup({
required this.repo,
required this.sessions,
required this.selectedId,
required this.onSelect,
});
final RepoInfo repo;
final List<Session> sessions;
final String? selectedId;
final void Function(String id) onSelect;
@override
ConsumerState<_RepoGroup> createState() => _RepoGroupState();
}
class _RepoGroupState extends ConsumerState<_RepoGroup> {
/// How many worktrees to show before the "show more" pill kicks in.
static const int _maxCollapsed = 5;
bool _showAll = false;
/// Whether the repo group is expanded. Clicking the header row toggles it;
/// when collapsed the worktrees and the "show more" pill are hidden.
bool _expanded = true;
/// Whether the pointer is over the repo header row. Gates the repo actions
/// menu, mirroring the worktree row's overflow menu.
bool _repoHovering = false;
/// Whether the repo header's expand toggle holds keyboard focus. Also gates
/// the repo actions menu so it stays reachable without a pointer (keyboard /
/// non-hover input), mirroring the worktree row's `_focused` handling.
bool _repoFocused = false;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final repo = widget.repo;
// Exited sessions are hidden from the sidebar's repo groups — but only the
// truly dead ones. A cold, RESUMABLE session (e.g. every session right
// after a server restart, before re-attach) stays visible so it remains
// discoverable and can be reopened (it auto-attaches on subscribe).
// Closed sessions live in the Closed view. Drafts + live sessions stay.
final sessions = widget.sessions
.where((s) => s.status != SessionStatus.exited || s.resumable)
.toList();
final selectedId = widget.selectedId;
final onSelect = widget.onSelect;
final byId = {for (final s in sessions) s.id: s};
final worktrees = sortWorktreesForDisplay(repo.worktrees);
final showMore = worktrees.length > _maxCollapsed;
final visible = (_showAll || !showMore)
? worktrees
: worktrees.take(_maxCollapsed).toList();
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(8, 10, 8, 1),
child: MouseRegion(
onEnter: (_) => setState(() => _repoHovering = true),
onExit: (_) => setState(() => _repoHovering = false),
child: Material(
type: MaterialType.transparency,
// Whole row is one inset pill (matches the worktree/session rows):
// the hover background spans folder + name + caret + the actions,
// instead of covering only the name.
child: InkWell(
borderRadius: BorderRadius.circular(kRadius10),
onTap: () => setState(() => _expanded = !_expanded),
onFocusChange: (f) => setState(() => _repoFocused = f),
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 4, 4),
child: Row(
children: [
Icon(
PhosphorIconsLight.folder,
size: 16,
color: theme.colorScheme.outline,
),
const SizedBox(width: kSpace8),
Expanded(
child: Text(
// Sentence case + bold, not upper-cased with tracking:
// the repo is a name, and bold carries the hierarchy
// that shouting used to.
repo.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.labelMedium?.copyWith(
color: theme.colorScheme.onSurface,
fontWeight: FontWeight.w700,
// labelMedium carries 0.5 tracking, which exists for
// all-caps labels. This is a name now, so drop it.
letterSpacing: 0,
),
),
),
// Repo actions (overflow menu + new worktree) reveal
// together on hover or keyboard focus, nested inside the
// pill; their slot stays reserved so the header text never
// reflows. maintainState keeps the menu button mounted
// while its popup is open (the modal barrier drops hover).
Visibility(
visible: _repoHovering || _repoFocused,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(width: kSpace2),
_RepoMenuButton(repo: repo),
IconButton(
tooltip: 'New worktree',
padding: EdgeInsets.zero,
iconSize: 16,
color: Theme.of(context).colorScheme.onSurface,
visualDensity: VisualDensity.compact,
constraints: const BoxConstraints(
minWidth: 22,
minHeight: 22,
),
icon: const Icon(
PhosphorIconsLight.plus,
size: 16,
),
// Create a worktree up front (a fresh branch by
// default); you pick the harness and write the
// first message on the pane you land on.
onPressed: () => showNewWorktreeDialog(
context,
ref,
projectId: repo.id,
),
),
],
),
),
],
),
),
),
),
),
),
if (_expanded) ...[
for (final wt in visible)
_WorktreeGroup(
key: ValueKey(wt.id),
repo: repo,
worktree: wt,
sessions: wt.sessionIds
.map((id) => byId[id])
.whereType<Session>()
.toList(),
selectedId: selectedId,
onSelect: onSelect,
),
if (showMore)
Padding(
padding: const EdgeInsets.fromLTRB(32, 2, 16, 4),
child: Align(
alignment: Alignment.centerLeft,
child: InkWell(
onTap: () => setState(() => _showAll = !_showAll),
borderRadius: BorderRadius.circular(kRadius10),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: kSpace8,
vertical: 3,
),
child: Text(
_showAll
? 'Show less'
: 'Show ${worktrees.length - _maxCollapsed} more',
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.primary,
fontWeight: FontWeight.w500,
),
),
),
),
),
),
],
],
);
}
}
/// Width reserved for the disclosure caret, so a row without one still lines its
/// branch name up with the rows that have one.
const double _kCaretSlot = 18;
/// The worktree row's disclosure control. Separate from the row's own tap
/// (SPEC-30 decision 15: the row navigates, the caret discloses), so neither
/// gesture has to guess which of the two the user meant.
class _WorktreeCaret extends StatelessWidget {
const _WorktreeCaret({
super.key,
required this.expanded,
required this.onPressed,
});
final bool expanded;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return SizedBox(
width: _kCaretSlot,
height: _kCaretSlot,
child: InkWell(
borderRadius: BorderRadius.circular(kRadius6),
onTap: onPressed,
child: Center(
child: AnimatedRotation(
turns: expanded ? 0 : -0.25,
duration: const Duration(milliseconds: 120),
child: Icon(
PhosphorIconsLight.caretDown,
size: 12,
color: Theme.of(context).colorScheme.outline,
),
),
),
),
);
}
}
/// A compact overflow-menu trigger sized to match the sidebar's + button: a
/// [VisualDensity.compact] [IconButton] (so its hover state layer is the small
/// circle the + uses) that opens a popup via [showMenu]. PopupMenuButton's own
/// `icon` can't be shrunk to this size — it wraps the icon in a default 48px
/// IconButton and Material 3 fills that whole box with the hover state layer.
class _CompactMenuButton extends StatelessWidget {
const _CompactMenuButton({
required this.icon,
required this.tooltip,
required this.itemBuilder,
required this.onSelected,
this.onOpened,
});
final IconData icon;
final String tooltip;
final List<PopupMenuEntry<String>> Function(BuildContext) itemBuilder;
/// Invoked with the chosen value, or the empty string when the menu is
/// dismissed without a selection (so callers can clear open-state flags).
final void Function(String value) onSelected;
/// Invoked just before the menu opens (parity with PopupMenuButton.onOpened).
final VoidCallback? onOpened;
Future<void> _open(BuildContext context) async {
final button = context.findRenderObject() as RenderBox;
final overlay =
Navigator.of(context).overlay!.context.findRenderObject() as RenderBox;
final position = RelativeRect.fromRect(
Rect.fromPoints(
button.localToGlobal(Offset.zero, ancestor: overlay),
button.localToGlobal(
button.size.bottomRight(Offset.zero),
ancestor: overlay,
),
),
Offset.zero & overlay.size,
);
onOpened?.call();
final selected = await showMenu<String>(
context: context,
position: position,
items: itemBuilder(context),
popUpAnimationStyle: AnimationStyle.noAnimation,
);
// The trigger can unmount while the menu is open (its row/worktree removed);
// its callbacks touch parent state, so bail if we're gone.
if (!context.mounted) return;
onSelected(selected ?? '');
}
@override
Widget build(BuildContext context) {
return IconButton(
tooltip: tooltip,
visualDensity: VisualDensity.compact,
// Tightly bounded so hovering never grows the worktree row (which would
// shift the branch name): the box matches the 16px glyph plus a hair,
// staying within the row's leading-icon height.
padding: EdgeInsets.zero,
iconSize: 16,
color: Theme.of(context).colorScheme.onSurface,
constraints: const BoxConstraints(minWidth: 22, minHeight: 22),
icon: Icon(icon, size: 16),
onPressed: () => _open(context),
);
}
}
/// The repo header's overflow menu (the triple-dots left of +). Hosts repo-
/// scoped actions: hide the repo (untrack it). More items land here later.
class _RepoMenuButton extends ConsumerWidget {
const _RepoMenuButton({required this.repo});
final RepoInfo repo;
@override
Widget build(BuildContext context, WidgetRef ref) {
return _CompactMenuButton(
tooltip: 'Repo actions',
icon: PhosphorIconsRegular.dotsThree,
onSelected: (value) {
switch (value) {
case 'hide':
_hideRepo(ref);
}
},
itemBuilder: (context) => [
PopupMenuItem(
value: 'hide',
height: 36,
child: Text(
'Hide the repo',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.error,
),
),
),
],
);
}
/// Untrack the repo, surfacing failures the way rename/delete do rather than
/// dropping the rejected command as an unhandled async error.
Future<void> _hideRepo(WidgetRef ref) async {
// Resolved before the first await: `ref` throws once its widget is
// unmounted, and the record must survive the thing that reported to it.
final status = ref.status;
try {
await ref.read(storeControllerProvider.notifier).removeProject(repo.id);
} catch (e) {
status.failure(
'Could not hide the repo',
error: e,
source: StatusSources.repo,
);
}
}
}
/// A worktree line (branch + diff, then an optional PR line) with its sessions
/// nested below. Clicking the branch row collapses/expands its sessions.
class _WorktreeGroup extends ConsumerStatefulWidget {
const _WorktreeGroup({
super.key,
required this.repo,
required this.worktree,
required this.sessions,
required this.selectedId,
required this.onSelect,
});
final RepoInfo repo;
final Worktree worktree;
final List<Session> sessions;
final String? selectedId;
final void Function(String id) onSelect;
@override
ConsumerState<_WorktreeGroup> createState() => _WorktreeGroupState();
}
class _WorktreeGroupState extends ConsumerState<_WorktreeGroup> {
bool _expanded = true;
bool _hovering = false;
bool _focused = false;
// Kept true while the actions popup is open. Opening the menu drops a modal
// barrier that steals mouse-hover (flipping `_hovering` off), which would
// otherwise unmount `_WorktreeMenuButton` — and its dialog-owning context —
// before `onSelected` runs.
bool _menuOpen = false;
// OR-ed into the line-1 swap condition below for the SAME reason as
// `_menuOpen`: opening the ports popover drops a modal-ish barrier / moves the
// pointer off the row, flipping `_hovering` off — which would snap the `…`
// menu back to a diff pill under the cursor while the popover is open. The
// popover reports its open-state through `onOpenChanged` (SPEC-41 §5 trap).
bool _portsOpen = false;
// Hold the ref-counted ports watch while any worktree group is mounted in the
// sidebar, so the server polls `lsof` only while the sidebar is up (SPEC-41
// §Delivery); the ref-count collapses every mounted group to one
// `ports.watch {on:true}`.
late final PortsWatch _portsWatch = ref.read(portsWatchProvider);
@override
void initState() {
super.initState();
_portsWatch.watch();
}
@override
void dispose() {
_portsWatch.release();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final repo = widget.repo;
final worktree = widget.worktree;
final sessions = widget.sessions;
final branch = worktree.branch ?? 'detached';
final isCurrent =
worktree.branch != null && worktree.branch == repo.currentBranch;
final worktreeSelected =
ref.watch(selectedWorktreeProvider)?.path == worktree.path;
// Glyph + tint per PR state (open / merged / closed / none) — shared with
// the composer pill and the window title strip.
final prStyle = prStateStyle(theme.colorScheme, worktree.pr);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
MouseRegion(
onEnter: (_) => setState(() => _hovering = true),
onExit: (_) => setState(() => _hovering = false),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: kSpace8,
vertical: 1,
),
child: Material(
type: MaterialType.transparency,
child: InkWell(
borderRadius: BorderRadius.circular(kRadius10),
onFocusChange: (f) => setState(() => _focused = f),
// Decision 15: the row *navigates* — it activates (minting if
// needed) this worktree's group, and an empty scope also seeds
// the in-pane starter. It deliberately does NOT toggle
// disclosure: one tap doing both meant peeking at a branch's
// children yanked the canvas, and moving the canvas collapsed
// the row you were reading. The caret owns disclosure.
onTap: () => selectWorktree(
ref,
SelectedWorktree(
projectId: repo.id,
path: worktree.path,
branch: worktree.branch,
),
),
child: Ink(
decoration: BoxDecoration(
color: worktreeSelected
? theme.colorScheme.surfaceContainerHighest
: null,
borderRadius: BorderRadius.circular(kRadius10),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(6, 6, 8, 2),
child: Row(
children: [
// Disclosure. Only rows that have something to show
// get one, so an empty worktree does not offer a
// control that would do nothing; its slot is kept so
// branch names stay aligned down the column.
if (sessions.isEmpty)
const SizedBox(width: _kCaretSlot)
else
_WorktreeCaret(
key: Key('worktreeCaret-${worktree.path}'),
expanded: _expanded,
onPressed: () =>
setState(() => _expanded = !_expanded),
),
prStyle.glyph.build(size: 16, color: prStyle.color),
const SizedBox(width: kSpace6),
Expanded(
child: Row(
children: [
Flexible(
child: Text(
branch,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall,
),
),
if (isCurrent) ...[
const SizedBox(width: 5),
Icon(
PhosphorIconsFill.star,
size: 8,
color: theme.colorScheme.outline,
),
],
],
),
),
const SizedBox(width: kSpace8),
// On hover or keyboard focus the diff pill is replaced
// by the worktree overflow menu (rename / delete), so
// the actions are reachable without a pointer. Otherwise
// it shows the diff stats (when the tree has changes).
if (_hovering ||
_focused ||
_menuOpen ||
_portsOpen)
_WorktreeMenuButton(
worktree: worktree,
onMenuOpened: () =>
setState(() => _menuOpen = true),
onSelected: (action) {
setState(() => _menuOpen = false);
switch (action) {
case 'rename':
_renameBranch();
case 'delete':
_deleteWorktree();
case 'ports':
// D8: explicit navigation to the global
// Ports screen pre-filtered to this repo —
// never a lift of the popover's private
// open/pinned controller. Pushed on this
// shell's Navigator: the desktop window is
// not a router app (desktop_ports_route.dart).
unawaited(
DesktopPortsRoute.open(
Navigator.of(context),
repoId: repo.id,
),
);
}
},
)
else if (worktree.hasChanges)
DiffChip(
insertions: worktree.insertions,
deletions: worktree.deletions,
),
],
),
),
// Sub-row below the branch, inside the same hover/tap group: the
// PR number label (when present) followed by the low-emphasis
// branch age. Fixed height so the row always reserves its place.
Padding(
padding: const EdgeInsets.fromLTRB(46, 0, 8, 4),
child: SizedBox(
height: 16,
child: Row(
children: [
Expanded(
child: Align(
alignment: Alignment.centerLeft,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (worktree.pr != null) ...[
Text(
'PR #${worktree.pr!.number}',
style: theme.textTheme.labelSmall
?.copyWith(
color:
theme.colorScheme.outline,
fontWeight: FontWeight.w300,
),
),
const SizedBox(width: kSpace4),
Text(
'•',
style: theme.textTheme.labelSmall
?.copyWith(
color:
theme.colorScheme.outline,
fontWeight: FontWeight.w300,
),
),
const SizedBox(width: kSpace4),
],
Text(
branchAgeLabel(worktree.committedAt),
style: theme.textTheme.labelSmall
?.copyWith(
color: theme.colorScheme.outline,
fontWeight: FontWeight.w300,
),
),
],
),
),
),
// Ports glyph, right-aligned on the same 8 pt edge
// as line 1's swap (SPEC-41 §5). 14 pt glyph in a
// 22 × 16 target: wider than tall, so the fixed
// 16 pt sub-row does NOT grow. Renders nothing when
// the branch is serving nothing.
_SubRowPortsGlyph(
worktreePath: worktree.path,
branch: branch,
onOpenChanged: (open) =>
setState(() => _portsOpen = open),
),
],
),
),
),
],
),
),
),
),
),
),
if (_expanded)
for (final s in sessions)
_SessionTile(
session: s,
selected: s.id == widget.selectedId,
indented: true,
onTap: () => widget.onSelect(s.id),
),
],
);
}
Future<void> _renameBranch() async {
// Resolved before the first await: `ref` throws once its widget is
// unmounted, and the record must survive the thing that reported to it.
final status = ref.status;
final repo = widget.repo;
final worktree = widget.worktree;
final newName = await showDialog<String>(
context: context,
builder: (ctx) => _RenameBranchDialog(initial: worktree.branch ?? ''),
);
if (newName == null || newName.isEmpty || newName == worktree.branch) {
return;
}
try {
await ref
.read(storeControllerProvider.notifier)
.renameBranch(repo.id, worktree.path, newName);
} catch (e) {
status.failure(
'Could not rename the branch',
error: e,
source: StatusSources.worktree,
);
}
}
Future<void> _deleteWorktree() async {
// Resolved before the first await: `ref` throws once its widget is
// unmounted, and the record must survive the thing that reported to it.
final status = ref.status;
final repo = widget.repo;
final worktree = widget.worktree;
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Delete worktree'),
content: Text(
'Delete the worktree for "${worktree.branch ?? worktree.path}"? '
'Uncommitted changes will be lost and any running sessions in it '
'will be stopped.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: const Text('Delete'),
),
],
),
);
if (confirmed != true) return;
try {
await ref
.read(storeControllerProvider.notifier)
.removeWorktree(repo.id, worktree.path);
} catch (e) {
status.failure(
'Could not delete the worktree',
error: e,
source: StatusSources.worktree,
);
}
}
}
/// The worktree row's hover overflow menu (triple dots that replace the diff
/// pill on hover). Reports the chosen action up to [_WorktreeGroupState], which
/// owns the dialogs and store calls with a context/ref that outlives the menu.
/// "Rename branch" and "Delete worktree" are disabled for the primary worktree;
/// "Rename branch" is also disabled for detached worktrees and open PRs.
class _WorktreeMenuButton extends ConsumerWidget {
const _WorktreeMenuButton({
required this.worktree,
required this.onMenuOpened,
required this.onSelected,
});
final Worktree worktree;
final VoidCallback onMenuOpened;
final void Function(String action) onSelected;
bool get _hasOpenPr => worktree.pr?.state.toUpperCase() == 'OPEN';
@override
Widget build(BuildContext context, WidgetRef ref) {
final isPrimary = worktree.isPrimary;
final isDetached = worktree.branch == null;
final canRename = !_hasOpenPr && !isPrimary && !isDetached;
// The count is a glance at what this branch is serving; the item routes to
// the global Ports screen either way (D8), so it shows even at zero.
final portCount = ref.watch(portsForWorktreeProvider(worktree.path)).length;
return _CompactMenuButton(
tooltip: 'Worktree actions',
icon: PhosphorIconsRegular.dotsThree,
onOpened: onMenuOpened,
// A cancelled menu resolves to null → forward '' so the parent's
// "keep mounted while open" flag is cleared just like a real selection.
onSelected: onSelected,
itemBuilder: (context) => [
PopupMenuItem(
value: 'rename',
enabled: canRename,
height: 36,
child: Tooltip(
message: isPrimary
? "Can't rename the primary worktree's branch"
: isDetached
? "Can't rename a detached worktree (no branch)"
: _hasOpenPr
? "Can't rename a branch with an open pull request"
: '',
child: Text(
'Rename branch',
// Match PopupMenuItem's disabled greying (it tints the child's
// DefaultTextStyle with disabledColor): keep bodyMedium's size
// but hand the color back to the disabled default when disabled.
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: canRename ? null : Theme.of(context).disabledColor,
),
),
),
),
const PopupMenuDivider(),
PopupMenuItem(
value: 'delete',
enabled: !isPrimary,
height: 36,
child: Tooltip(
message: isPrimary ? "Can't delete the primary worktree" : '',
child: Text(
'Delete worktree',
// Destructive: tint red when enabled; when disabled (primary),
// fall back to disabledColor so it greys like PopupMenuItem's
// default disabled child rather than reading as an active item.
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: isPrimary
? Theme.of(context).disabledColor
: Theme.of(context).colorScheme.error,
),
),
),
),
const PopupMenuDivider(),
PopupMenuItem(
value: 'ports',
height: 36,
child: Text(
'Ports ($portCount)…',
style: Theme.of(context).textTheme.bodyMedium,
),
),
],
);
}
}
/// The worktree sub-row's ports glyph (SPEC-41 §5), desktop form. A 14 pt glyph
/// in a fixed 22 × 16 hit target — wider, not taller — so the sub-row keeps its
/// reserved 16 pt height. Hit testing is bounded by this box (Flutter clips to
/// the parent), so the target is honestly 22 × 16, not 22 × 22. Renders nothing
/// when the branch is serving nothing.
class _SubRowPortsGlyph extends ConsumerWidget {
const _SubRowPortsGlyph({
required this.worktreePath,
required this.branch,
required this.onOpenChanged,
});
final String worktreePath;
final String branch;
final ValueChanged<bool> onOpenChanged;
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(portsGlyphStateProvider(worktreePath));
if (state == PortsGlyphState.none) return const SizedBox.shrink();
final ports = ref.watch(portsForWorktreeProvider(worktreePath));
return SizedBox(
key: ValueKey('portsSubRowTarget-$worktreePath'),
width: 22,
height: 16,
child: Center(
child: PortsPopover(
state: state,
count: ports.length,
branch: branch,
ports: ports,
nowMs: DateTime.now().millisecondsSinceEpoch,
onOpenChanged: onOpenChanged,
),
),
);
}
}
/// The rename-branch dialog. Owns its [TextEditingController] as a State field
/// so it is disposed only after the route is fully removed — disposing it the
/// moment `showDialog` returns would crash the dialog's exit animation, which
/// still rebuilds the [TextField].
class _RenameBranchDialog extends StatefulWidget {
const _RenameBranchDialog({required this.initial});
final String initial;
@override
State<_RenameBranchDialog> createState() => _RenameBranchDialogState();
}
class _RenameBranchDialogState extends State<_RenameBranchDialog> {
late final TextEditingController _controller = TextEditingController(
text: widget.initial,
);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Rename branch'),
content: TextField(
controller: _controller,
autofocus: true,
decoration: const InputDecoration(labelText: 'New branch name'),
onSubmitted: (v) => Navigator.of(context).pop(v.trim()),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(_controller.text.trim()),
child: const Text('Rename'),
),
],
);
}
}
class _SessionTile extends ConsumerStatefulWidget {
const _SessionTile({
required this.session,
required this.selected,
required this.onTap,
this.indented = false,
});
final Session session;
final bool selected;
final bool indented;
final VoidCallback onTap;