v0.29.0 21b3150

session_manager.go RawHistoryFolder

1package component
2
3import (
4	"context"
5	"fmt"
6	"strings"
7	"sync"
8
9	"github.com/bnema/dumber/internal/application/port"
10	"github.com/bnema/dumber/internal/application/usecase"
11	"github.com/bnema/dumber/internal/domain/entity"
12	"github.com/bnema/dumber/internal/logging"
13	"github.com/bnema/dumber/internal/ui/layout"
14	"github.com/bnema/puregotk/v4/gdk"
15	"github.com/bnema/puregotk/v4/glib"
16	"github.com/bnema/puregotk/v4/gtk"
17)
18
19const (
20	sessionIDMaxDisplay  = 20
21	sessionRowBoxSpacing = 8
22	sessionMaxTitleLen   = 45 // Max chars for pane title display
23)
24
25// SessionManager is a modal overlay for managing sessions.
26type SessionManager struct {
27	// GTK widgets
28	outerBox       *gtk.Box
29	mainBox        *gtk.Box
30	headerBox      *gtk.Box
31	titleLabel     *gtk.Label
32	scrolledWindow *gtk.ScrolledWindow
33	listBox        *gtk.ListBox
34	footerLabel    *gtk.Label
35
36	// Parent overlay reference for sizing
37	parentOverlay layout.OverlayWidget
38
39	// State
40	mu               sync.RWMutex
41	visible          bool
42	sessions         []entity.SessionInfo
43	selectedIndex    int   // Index into sessions slice
44	expandedIndex    int   // -1 means none expanded
45	sessionToListRow []int // Maps session index to list row index
46	listRowToSession []int // Maps list row index to session index (-1 for non-session rows)
47	populatingList   bool  // True while rebuilding list, to ignore selection callbacks
48
49	// Dependencies
50	listSessionsUC  *usecase.ListSessionsUseCase
51	deleteSessionUC *usecase.DeleteSessionUseCase
52	spawner         port.SessionSpawner
53	currentSession  entity.SessionID
54
55	// Callbacks
56	onClose func()
57	onOpen  func(sessionID entity.SessionID)
58	onToast func(ctx context.Context, message string, level ToastLevel)
59
60	// GTK callback retention
61	retainedCallbacks []interface{}
62
63	// Scaling
64	uiScale float64
65
66	// Cached measurements (populated after first layout)
67	measuredHeights struct {
68		sessionRow int  // Session row natural height
69		treeRow    int  // Tree row natural height
70		dividerRow int  // Divider row natural height
71		valid      bool // Whether cache is valid
72	}
73
74	ctx context.Context
75}
76
77// SessionManagerConfig holds configuration for creating a SessionManager.
78type SessionManagerConfig struct {
79	ListSessionsUC  *usecase.ListSessionsUseCase
80	DeleteSessionUC *usecase.DeleteSessionUseCase
81	Spawner         port.SessionSpawner
82	CurrentSession  entity.SessionID
83	UIScale         float64
84	OnClose         func()
85	OnOpen          func(sessionID entity.SessionID)
86	OnToast         func(ctx context.Context, message string, level ToastLevel)
87}
88
89// NewSessionManager creates a new SessionManager component.
90func NewSessionManager(ctx context.Context, cfg SessionManagerConfig) *SessionManager {
91	log := logging.FromContext(ctx)
92
93	uiScale := cfg.UIScale
94	if uiScale <= 0 {
95		uiScale = 1.0
96	}
97
98	sm := &SessionManager{
99		ctx:             ctx,
100		listSessionsUC:  cfg.ListSessionsUC,
101		deleteSessionUC: cfg.DeleteSessionUC,
102		spawner:         cfg.Spawner,
103		currentSession:  cfg.CurrentSession,
104		onClose:         cfg.OnClose,
105		onOpen:          cfg.OnOpen,
106		onToast:         cfg.OnToast,
107		selectedIndex:   -1,
108		expandedIndex:   -1,
109		uiScale:         uiScale,
110	}
111
112	if err := sm.createWidgets(); err != nil {
113		log.Error().Err(err).Msg("failed to create session manager widgets")
114		return nil
115	}
116
117	sm.attachKeyController()
118
119	log.Debug().Msg("session manager created")
120	return sm
121}
122
123// SetParentOverlay sets the overlay widget used for sizing calculations.
124// Must be called before Show().
125func (sm *SessionManager) SetParentOverlay(overlay layout.OverlayWidget) {
126	sm.mu.Lock()
127	defer sm.mu.Unlock()
128	sm.parentOverlay = overlay
129}
130
131// WidgetAsLayout returns the session manager's outer widget as a layout.Widget.
132func (sm *SessionManager) WidgetAsLayout(factory layout.WidgetFactory) layout.Widget {
133	if sm.outerBox == nil {
134		return nil
135	}
136	return factory.WrapWidget(&sm.outerBox.Widget)
137}
138
139// Widget returns the session manager widget for embedding in an overlay.
140func (sm *SessionManager) Widget() *gtk.Widget {
141	if sm.outerBox == nil {
142		return nil
143	}
144	return &sm.outerBox.Widget
145}
146
147// Show displays the session manager and loads sessions.
148func (sm *SessionManager) Show(ctx context.Context) {
149	log := logging.FromContext(ctx)
150	log.Debug().Msg("showing session manager")
151
152	sm.mu.Lock()
153	if sm.visible {
154		sm.mu.Unlock()
155		return
156	}
157	sm.visible = true
158	sm.mu.Unlock()
159
160	// Calculate size and position
161	sm.resizeAndCenter()
162
163	// Show the widget
164	sm.outerBox.SetVisible(true)
165
166	// Load sessions asynchronously
167	go sm.loadSessions()
168
169	// Focus the list
170	if sm.listBox != nil {
171		sm.listBox.GrabFocus()
172	}
173}
174
175// Hide hides the session manager.
176func (sm *SessionManager) Hide(ctx context.Context) {
177	log := logging.FromContext(ctx)
178	log.Debug().Msg("hiding session manager")
179
180	sm.mu.Lock()
181	if !sm.visible {
182		sm.mu.Unlock()
183		return
184	}
185	sm.visible = false
186	sm.mu.Unlock()
187
188	sm.outerBox.SetVisible(false)
189
190	// Clear state
191	sm.listBox.RemoveAll()
192
193	if sm.onClose != nil {
194		sm.onClose()
195	}
196}
197
198// IsVisible returns whether the session manager is visible.
199func (sm *SessionManager) IsVisible() bool {
200	sm.mu.RLock()
201	defer sm.mu.RUnlock()
202	return sm.visible
203}
204
205// Toggle shows if hidden, hides if visible.
206func (sm *SessionManager) Toggle(ctx context.Context) {
207	sm.mu.RLock()
208	visible := sm.visible
209	sm.mu.RUnlock()
210
211	if visible {
212		sm.Hide(ctx)
213	} else {
214		sm.Show(ctx)
215	}
216}
217
218func (sm *SessionManager) resizeAndCenter() {
219	if sm.outerBox == nil || sm.mainBox == nil {
220		return
221	}
222
223	width, marginTop := CalculateModalDimensions(sm.parentOverlay, SessionManagerSizeDefaults)
224
225	sm.mainBox.SetSizeRequest(width, -1)
226	sm.outerBox.SetMarginTop(marginTop)
227}
228
229func (sm *SessionManager) createWidgets() error {
230	// Outer container for positioning
231	sm.outerBox = gtk.NewBox(gtk.OrientationVerticalValue, 0)
232	if sm.outerBox == nil {
233		return errNilWidget("sessionOuterBox")
234	}
235	sm.outerBox.AddCssClass("session-manager-outer")
236	sm.outerBox.SetHalign(gtk.AlignCenterValue)
237	sm.outerBox.SetValign(gtk.AlignStartValue)
238	sm.outerBox.SetVisible(false)
239
240	// Main container with styling
241	sm.mainBox = gtk.NewBox(gtk.OrientationVerticalValue, 0)
242	if sm.mainBox == nil {
243		return errNilWidget("sessionMainBox")
244	}
245	sm.mainBox.AddCssClass("session-manager-container")
246
247	// Header
248	if err := sm.initHeader(); err != nil {
249		return err
250	}
251
252	// Scrolled window for list
253	if err := sm.initList(); err != nil {
254		return err
255	}
256
257	// Footer with shortcuts
258	if err := sm.initFooter(); err != nil {
259		return err
260	}
261
262	// Assemble
263	sm.mainBox.Append(&sm.headerBox.Widget)
264	sm.mainBox.Append(&sm.scrolledWindow.Widget)
265	sm.mainBox.Append(&sm.footerLabel.Widget)
266	sm.outerBox.Append(&sm.mainBox.Widget)
267
268	return nil
269}
270
271func (sm *SessionManager) initHeader() error {
272	sm.headerBox = gtk.NewBox(gtk.OrientationHorizontalValue, 0)
273	if sm.headerBox == nil {
274		return errNilWidget("sessionHeaderBox")
275	}
276	sm.headerBox.AddCssClass("session-manager-header")
277
278	title := "Sessions"
279	sm.titleLabel = gtk.NewLabel(&title)
280	if sm.titleLabel == nil {
281		return errNilWidget("sessionTitleLabel")
282	}
283	sm.titleLabel.AddCssClass("session-manager-title")
284	sm.titleLabel.SetHalign(gtk.AlignStartValue)
285	sm.titleLabel.SetHexpand(true)
286	sm.headerBox.Append(&sm.titleLabel.Widget)
287
288	// Shortcut badge
289	shortcutText := "Ctrl+O"
290	shortcutLabel := gtk.NewLabel(&shortcutText)
291	if shortcutLabel != nil {
292		shortcutLabel.AddCssClass("omnibox-shortcut-badge")
293		sm.headerBox.Append(&shortcutLabel.Widget)
294	}
295
296	return nil
297}
298
299func (sm *SessionManager) initList() error {
300	sm.scrolledWindow = gtk.NewScrolledWindow()
301	if sm.scrolledWindow == nil {
302		return errNilWidget("sessionScrolledWindow")
303	}
304	sm.scrolledWindow.AddCssClass("session-manager-scrolled")
305	sm.scrolledWindow.SetPolicy(gtk.PolicyNeverValue, gtk.PolicyAutomaticValue)
306	// Don't propagate natural height - we control it via resizeForContent
307	sm.scrolledWindow.SetPropagateNaturalHeight(false)
308
309	sm.listBox = gtk.NewListBox()
310	if sm.listBox == nil {
311		return errNilWidget("sessionListBox")
312	}
313	sm.listBox.AddCssClass("session-manager-list")
314	sm.listBox.SetSelectionMode(gtk.SelectionSingleValue)
315
316	// Connect row selection - map list row index to session index
317	rowSelectedCb := func(_ gtk.ListBox, rowPtr uintptr) {
318		row := gtk.ListBoxRowNewFromInternalPtr(rowPtr)
319		if row == nil {
320			return
321		}
322		listRowIdx := row.GetIndex()
323		sm.mu.Lock()
324		// Ignore selection changes while rebuilding the list
325		if sm.populatingList {
326			sm.mu.Unlock()
327			return
328		}
329		if listRowIdx >= 0 && listRowIdx < len(sm.listRowToSession) {
330			sessionIdx := sm.listRowToSession[listRowIdx]
331			if sessionIdx >= 0 {
332				sm.selectedIndex = sessionIdx
333			}
334		}
335		sm.mu.Unlock()
336	}
337	sm.retainedCallbacks = append(sm.retainedCallbacks, rowSelectedCb)
338	sm.listBox.ConnectRowSelected(&rowSelectedCb)
339
340	sm.scrolledWindow.SetChild(&sm.listBox.Widget)
341	return nil
342}
343
344func (sm *SessionManager) initFooter() error {
345	footerText := "↑↓/jk navigate  Enter expand  r restore  x delete  Esc close"
346	sm.footerLabel = gtk.NewLabel(&footerText)
347	if sm.footerLabel == nil {
348		return errNilWidget("sessionFooterLabel")
349	}
350	sm.footerLabel.AddCssClass("session-manager-footer")
351	sm.footerLabel.SetHalign(gtk.AlignCenterValue)
352	return nil
353}
354
355func (sm *SessionManager) attachKeyController() {
356	controller := gtk.NewEventControllerKey()
357	if controller == nil {
358		return
359	}
360	controller.SetPropagationPhase(gtk.PhaseCaptureValue)
361
362	keyPressedCb := func(_ gtk.EventControllerKey, keyval uint, _ uint, state gdk.ModifierType) bool {
363		return sm.handleKeyPress(keyval, state)
364	}
365	sm.retainedCallbacks = append(sm.retainedCallbacks, keyPressedCb)
366	controller.ConnectKeyPressed(&keyPressedCb)
367	sm.outerBox.AddController(&controller.EventController)
368}
369
370func (sm *SessionManager) handleKeyPress(keyval uint, _ gdk.ModifierType) bool {
371	switch keyval {
372	case uint(gdk.KEY_Escape):
373		sm.Hide(sm.ctx)
374		return true
375
376	case uint(gdk.KEY_Up), uint(gdk.KEY_k):
377		sm.selectPrevious()
378		return true
379
380	case uint(gdk.KEY_Down), uint(gdk.KEY_j):
381		sm.selectNext()
382		return true
383
384	case uint(gdk.KEY_Return), uint(gdk.KEY_KP_Enter), uint(gdk.KEY_space):
385		// Enter/Space expands/collapses to preview session contents
386		sm.toggleExpanded()
387		return true
388
389	case uint(gdk.KEY_r), uint(gdk.KEY_o):
390		// r/o restores the selected session
391		sm.openSelected()
392		return true
393
394	case uint(gdk.KEY_x), uint(gdk.KEY_d), uint(gdk.KEY_Delete):
395		sm.deleteSelected()
396		return true
397	}
398	return false
399}
400
401func (sm *SessionManager) loadSessions() {
402	log := logging.FromContext(sm.ctx)
403
404	if sm.listSessionsUC == nil {
405		log.Warn().Msg("listSessionsUC is nil")
406		return
407	}
408
409	output, err := sm.listSessionsUC.Execute(sm.ctx, sm.currentSession, SessionManagerListDefaults.MaxResults)
410	if err != nil {
411		log.Error().Err(err).Msg("failed to list sessions")
412		return
413	}
414
415	sm.mu.Lock()
416	sm.sessions = output.Sessions
417	sm.selectedIndex = 0
418	sm.mu.Unlock()
419
420	// Update UI on main thread
421	cb := glib.SourceFunc(func(_ uintptr) bool {
422		sm.populateList()
423		return false
424	})
425	glib.IdleAdd(&cb, 0)
426}
427
428// populateListState holds state during list population.
429type populateListState struct {
430	listRowToSession []int
431	listRowCount     int
432	sessionRowCount  int
433	treeRowCount     int
434	dividerCount     int
435	expandedIdx      int
436	firstExitedIdx   int
437	hasActive        bool
438}
439
440func (sm *SessionManager) populateList() {
441	sm.mu.Lock()
442	sessions := sm.sessions
443	selectedIdx := sm.selectedIndex
444	sm.populatingList = true
445	sm.sessionToListRow = make([]int, len(sessions))
446	sm.listRowToSession = nil
447	expandedIdx := sm.expandedIndex
448	sm.mu.Unlock()
449
450	if sm.listBox == nil {
451		sm.mu.Lock()
452		sm.populatingList = false
453		sm.mu.Unlock()
454		return
455	}
456
457	sm.listBox.RemoveAll()
458
459	state := &populateListState{expandedIdx: expandedIdx, firstExitedIdx: -1}
460	for i, info := range sessions {
461		if info.IsCurrent || info.IsActive {
462			state.hasActive = true
463		} else if state.firstExitedIdx == -1 {
464			state.firstExitedIdx = i
465		}
466	}
467
468	for i, info := range sessions {
469		sm.addSessionToList(i, info, state)
470	}
471
472	sm.mu.Lock()
473	sm.listRowToSession = state.listRowToSession
474	sm.populatingList = false
475	sm.mu.Unlock()
476
477	sm.selectBySessionIndex(selectedIdx)
478
479	// Attempt to measure actual widget heights for accurate sizing
480	width, _ := CalculateModalDimensions(sm.parentOverlay, SessionManagerSizeDefaults)
481	sm.measureWidgetHeights(width)
482
483	sm.resizeForContent(state.sessionRowCount, state.dividerCount, state.treeRowCount)
484}
485
486func (sm *SessionManager) addSessionToList(i int, info entity.SessionInfo, state *populateListState) {
487	// Add divider before first exited session
488	if i == state.firstExitedIdx && state.hasActive {
489		if divider := sm.createDividerRow("EXITED"); divider != nil {
490			sm.listBox.Append(&divider.Widget)
491			state.listRowToSession = append(state.listRowToSession, -1)
492			state.listRowCount++
493			state.dividerCount++
494		}
495	}
496
497	sm.mu.Lock()
498	sm.sessionToListRow[i] = state.listRowCount
499	sm.mu.Unlock()
500	state.listRowToSession = append(state.listRowToSession, i)
501
502	if row := sm.createSessionRow(info); row != nil {
503		sm.listBox.Append(&row.Widget)
504		state.listRowCount++
505		state.sessionRowCount++
506	}
507
508	if i == state.expandedIdx && info.State != nil {
509		for _, treeRow := range sm.createTreeRows(info.State) {
510			sm.listBox.Append(&treeRow.Widget)
511			state.listRowToSession = append(state.listRowToSession, -1)
512			state.listRowCount++
513			state.treeRowCount++
514		}
515	}
516}
517
518func (sm *SessionManager) selectBySessionIndex(sessionIdx int) {
519	sm.mu.RLock()
520	if sessionIdx < 0 || sessionIdx >= len(sm.sessionToListRow) {
521		sm.mu.RUnlock()
522		return
523	}
524	listRow := sm.sessionToListRow[sessionIdx]
525	sm.mu.RUnlock()
526
527	row := sm.listBox.GetRowAtIndex(listRow)
528	if row == nil {
529		return
530	}
531
532	sm.listBox.SelectRow(row)
533
534	// Scroll the row into view using GrabFocus which triggers scroll
535	row.GrabFocus()
536}
537
538func (sm *SessionManager) resizeForContent(sessionRowCount, dividerCount, treeRowCount int) {
539	if sm.scrolledWindow == nil {
540		return
541	}
542
543	// Get row heights - use measured values if available, otherwise scale defaults
544	var sessionH, treeH, dividerH int
545	if sm.measuredHeights.valid {
546		sessionH = sm.measuredHeights.sessionRow
547		treeH = sm.measuredHeights.treeRow
548		dividerH = sm.measuredHeights.dividerRow
549	} else {
550		sessionH = ScaleValue(DefaultRowHeights.Standard, sm.uiScale)
551		treeH = ScaleValue(DefaultRowHeights.Compact, sm.uiScale)
552		dividerH = ScaleValue(DefaultRowHeights.Divider, sm.uiScale)
553	}
554
555	// Calculate actual content height
556	contentHeight := sessionRowCount*sessionH + dividerCount*dividerH + treeRowCount*treeH
557
558	// Calculate max visible height - limit to prevent oversized modal
559	maxVisibleHeight := SessionManagerListDefaults.MaxVisibleRows*sessionH + dividerH
560
561	// Cap at max visible height - rest will be scrollable
562	if contentHeight > maxVisibleHeight {
563		contentHeight = maxVisibleHeight
564	}
565
566	// Ensure minimum height for at least one row
567	if contentHeight < sessionH {
568		contentHeight = sessionH
569	}
570
571	// Schedule resize on main thread using shared helper
572	cb := glib.SourceFunc(func(_ uintptr) bool {
573		SetScrolledWindowHeight(sm.scrolledWindow, contentHeight)
574		sm.outerBox.QueueResize()
575		return false
576	})
577	glib.IdleAdd(&cb, 0)
578}
579
580// measureWidgetHeights attempts to measure actual row heights from the list.
581// Must be called after list is populated. Updates measuredHeights cache if successful.
582func (sm *SessionManager) measureWidgetHeights(forWidth int) {
583	if sm.listBox == nil || sm.measuredHeights.valid {
584		return
585	}
586
587	// We need to find different row types and measure them.
588	// Session rows have "session-row" class, tree rows have "session-tree-row" class,
589	// divider rows have "session-divider" class.
590
591	// For now, measure using first row and estimate others based on ratio.
592	// This is simpler and works well enough since we have fallback scaling.
593	row := sm.listBox.GetRowAtIndex(0)
594	if row == nil {
595		return
596	}
597
598	sessionH := MeasureWidgetHeight(&row.Widget, forWidth)
599	if sessionH <= 0 {
600		return
601	}
602
603	// Estimate tree and divider heights based on ratio to standard row
604	// These ratios match the original constants: tree=28/50, divider=30/50
605	treeH := sessionH * DefaultRowHeights.Compact / DefaultRowHeights.Standard
606	dividerH := sessionH * DefaultRowHeights.Divider / DefaultRowHeights.Standard
607
608	sm.measuredHeights.sessionRow = sessionH
609	sm.measuredHeights.treeRow = treeH
610	sm.measuredHeights.dividerRow = dividerH
611	sm.measuredHeights.valid = true
612}
613
614// createTreeRows creates tree rows showing the tab/pane structure of a session.
615func (sm *SessionManager) createTreeRows(state *entity.SessionState) []*gtk.ListBoxRow {
616	if state == nil {
617		return nil
618	}
619
620	var rows []*gtk.ListBoxRow
621
622	for tabIdx, tab := range state.Tabs {
623		isLastTab := tabIdx == len(state.Tabs)-1
624
625		// Tab row
626		tabRow := sm.createTreeRow(tab.Name, "tab", !isLastTab, 0)
627		if tabRow != nil {
628			rows = append(rows, tabRow)
629		}
630
631		// Pane rows under this tab
632		paneRows := sm.createPaneTreeRows(&tab.Workspace)
633		rows = append(rows, paneRows...)
634	}
635
636	return rows
637}
638
639// createPaneTreeRows creates rows for the pane tree under a tab.
640func (sm *SessionManager) createPaneTreeRows(ws *entity.WorkspaceSnapshot) []*gtk.ListBoxRow {
641	if ws == nil || ws.Root == nil {
642		return nil
643	}
644
645	var rows []*gtk.ListBoxRow
646	sm.collectPaneRows(&rows, ws.Root, 1, true)
647	return rows
648}
649
650// collectPaneRows recursively collects pane tree rows.
651func (sm *SessionManager) collectPaneRows(
652	rows *[]*gtk.ListBoxRow,
653	node *entity.PaneNodeSnapshot,
654	depth int,
655	isLast bool,
656) {
657	if node == nil {
658		return
659	}
660
661	if node.Pane != nil {
662		// Leaf node (actual pane)
663		title := node.Pane.Title
664		if title == "" {
665			title = node.Pane.URI
666		}
667		if len(title) > sessionMaxTitleLen {
668			title = title[:sessionMaxTitleLen-3] + "..."
669		}
670
671		row := sm.createTreeRow(title, "pane", !isLast, depth)
672		if row != nil {
673			*rows = append(*rows, row)
674		}
675	} else if len(node.Children) > 0 {
676		// Container node (split)
677		splitLabel := "split"
678		if node.IsStacked {
679			splitLabel = "stacked"
680		} else if node.SplitRatio > 0 {
681			splitLabel = fmt.Sprintf("split %.0f%%", node.SplitRatio*100)
682		}
683
684		row := sm.createTreeRow(splitLabel, "split", !isLast, depth)
685		if row != nil {
686			*rows = append(*rows, row)
687		}
688
689		// Recurse into children
690		for i, child := range node.Children {
691			isLastChild := i == len(node.Children)-1
692			sm.collectPaneRows(rows, child, depth+1, isLastChild)
693		}
694	}
695}
696
697// createTreeRow creates a single tree row with proper indentation and branch characters.
698func (sm *SessionManager) createTreeRow(text, nodeType string, hasSibling bool, depth int) *gtk.ListBoxRow {
699	row := gtk.NewListBoxRow()
700	if row == nil {
701		return nil
702	}
703	row.SetSelectable(false)
704	row.SetActivatable(false)
705	row.AddCssClass("session-tree-row")
706
707	hbox := gtk.NewBox(gtk.OrientationHorizontalValue, 4)
708	if hbox == nil {
709		return nil
710	}
711	hbox.AddCssClass("session-tree-content")
712
713	// Build indent and branch prefix
714	var prefix string
715	indent := "  " // Base indent (minimal, tree branches provide visual alignment)
716	for i := 0; i < depth; i++ {
717		indent += "   " // 3 spaces per depth level
718	}
719
720	// Branch character
721	if hasSibling {
722		prefix = "├── "
723	} else {
724		prefix = "└── "
725	}
726
727	// Icon based on node type
728	var icon string
729	switch nodeType {
730	case "tab":
731		icon = "󰓩 " // Tab icon (nerd font)
732	case "pane":
733		icon = "󰕮 " // Pane icon
734	case "split":
735		icon = "󰯍 " // Split icon
736	default:
737		icon = "  "
738	}
739
740	// Create the label with all parts
741	labelText := indent + prefix + icon + text
742	label := gtk.NewLabel(&labelText)
743	if label == nil {
744		return nil
745	}
746	label.AddCssClass("session-tree-label")
747	label.SetHalign(gtk.AlignStartValue)
748	label.SetEllipsize(2) // PANGO_ELLIPSIZE_END
749
750	hbox.Append(&label.Widget)
751	row.SetChild(&hbox.Widget)
752
753	return row
754}
755
756func (sm *SessionManager) createDividerRow(text string) *gtk.ListBoxRow {
757	row := gtk.NewListBoxRow()
758	if row == nil {
759		return nil
760	}
761	row.SetSelectable(false)
762	row.SetActivatable(false)
763
764	label := gtk.NewLabel(&text)
765	if label == nil {
766		return nil
767	}
768	label.AddCssClass("session-divider")
769	label.SetHalign(gtk.AlignStartValue)
770	row.SetChild(&label.Widget)
771
772	return row
773}
774
775func (sm *SessionManager) createSessionRow(info entity.SessionInfo) *gtk.ListBoxRow {
776	row := gtk.NewListBoxRow()
777	if row == nil {
778		return nil
779	}
780	row.AddCssClass("session-manager-row-wrapper")
781
782	hbox := gtk.NewBox(gtk.OrientationHorizontalValue, sessionRowBoxSpacing)
783	if hbox == nil {
784		return nil
785	}
786	hbox.AddCssClass("session-manager-row")
787
788	sm.addStatusIndicator(hbox, info)
789	sm.addSessionInfo(hbox, info)
790	sm.addRelativeTime(hbox, info)
791
792	row.SetChild(&hbox.Widget)
793	return row
794}
795
796func (sm *SessionManager) addStatusIndicator(hbox *gtk.Box, info entity.SessionInfo) {
797	var statusText string
798	switch {
799	case info.IsCurrent:
800		statusText = "●" // Filled dot for current
801		hbox.AddCssClass("session-current")
802	case info.IsActive:
803		statusText = "○" // Empty dot for other active instance
804		hbox.AddCssClass("session-active")
805	default:
806		statusText = "◼" // Small square for exited (like stop icon)
807		hbox.AddCssClass("session-exited")
808	}
809	statusLabel := gtk.NewLabel(&statusText)
810	if statusLabel != nil {
811		statusLabel.AddCssClass("session-status")
812		hbox.Append(&statusLabel.Widget)
813	}
814}
815
816func (sm *SessionManager) addSessionInfo(hbox *gtk.Box, info entity.SessionInfo) {
817	const infoBoxSpacing = 2
818	infoBox := gtk.NewBox(gtk.OrientationVerticalValue, infoBoxSpacing)
819	if infoBox == nil {
820		return
821	}
822	infoBox.SetHexpand(true)
823
824	// Session ID row: shortID (accent) + rest of ID (dimmed) + optional (current) badge
825	idRowBox := gtk.NewBox(gtk.OrientationHorizontalValue, 0)
826	if idRowBox != nil {
827		idRowBox.SetHalign(gtk.AlignStartValue)
828
829		fullID := string(info.Session.ID)
830		shortID := info.Session.ShortID() // Last 4 chars
831
832		// Short ID with accent color (displayed first)
833		shortLabel := gtk.NewLabel(&shortID)
834		if shortLabel != nil {
835			shortLabel.AddCssClass("session-id-short")
836			idRowBox.Append(&shortLabel.Widget)
837		}
838
839		// Rest of the ID (prefix before the short suffix), dimmed
840		// Format: "20251225_083026_7566" -> shortID="7566", prefix="20251225_083026"
841		// Remove trailing underscore for cleaner display
842		if len(fullID) > 4 {
843			prefix := fullID[:len(fullID)-4]
844			// Trim trailing underscore if present
845			prefix = strings.TrimSuffix(prefix, "_")
846			prefix = " " + prefix
847			prefixLabel := gtk.NewLabel(&prefix)
848			if prefixLabel != nil {
849				prefixLabel.AddCssClass("session-id-prefix")
850				idRowBox.Append(&prefixLabel.Widget)
851			}
852		}
853
854		// Current badge
855		if info.IsCurrent {
856			badge := " (current)"
857			badgeLabel := gtk.NewLabel(&badge)
858			if badgeLabel != nil {
859				badgeLabel.AddCssClass("session-id-badge")
860				idRowBox.Append(&badgeLabel.Widget)
861			}
862		}
863
864		infoBox.Append(&idRowBox.Widget)
865	}
866
867	// Tab/pane count
868	countText := fmt.Sprintf("%d tabs, %d panes", info.TabCount, info.PaneCount)
869	countLabel := gtk.NewLabel(&countText)
870	if countLabel != nil {
871		countLabel.AddCssClass("session-count")
872		countLabel.SetHalign(gtk.AlignStartValue)
873		infoBox.Append(&countLabel.Widget)
874	}
875
876	hbox.Append(&infoBox.Widget)
877}
878
879func (sm *SessionManager) addRelativeTime(hbox *gtk.Box, info entity.SessionInfo) {
880	relTime := usecase.GetRelativeTime(info.UpdatedAt)
881	timeLabel := gtk.NewLabel(&relTime)
882	if timeLabel != nil {
883		timeLabel.AddCssClass("session-time")
884		timeLabel.SetValign(gtk.AlignCenterValue)
885		hbox.Append(&timeLabel.Widget)
886	}
887}
888
889func (sm *SessionManager) selectPrevious() {
890	sm.mu.Lock()
891	maxIndex := len(sm.sessions) - 1
892	if maxIndex < 0 {
893		sm.mu.Unlock()
894		return
895	}
896	sm.selectedIndex--
897	if sm.selectedIndex < 0 {
898		sm.selectedIndex = maxIndex // Wrap to bottom
899	}
900	idx := sm.selectedIndex
901	sm.mu.Unlock()
902
903	sm.selectBySessionIndex(idx)
904}
905
906func (sm *SessionManager) selectNext() {
907	sm.mu.Lock()
908	maxIndex := len(sm.sessions) - 1
909	if maxIndex < 0 {
910		sm.mu.Unlock()
911		return
912	}
913	sm.selectedIndex++
914	if sm.selectedIndex > maxIndex {
915		sm.selectedIndex = 0 // Wrap to top
916	}
917	idx := sm.selectedIndex
918	sm.mu.Unlock()
919
920	sm.selectBySessionIndex(idx)
921}
922
923func (sm *SessionManager) toggleExpanded() {
924	sm.mu.Lock()
925	if sm.expandedIndex == sm.selectedIndex {
926		sm.expandedIndex = -1 // collapse
927	} else {
928		sm.expandedIndex = sm.selectedIndex // expand
929	}
930	sm.mu.Unlock()
931
932	// Rebuild the list to show/hide tree
933	sm.populateList()
934}
935
936func (sm *SessionManager) openSelected() {
937	sm.mu.RLock()
938	if sm.selectedIndex < 0 || sm.selectedIndex >= len(sm.sessions) {
939		sm.mu.RUnlock()
940		return
941	}
942	info := sm.sessions[sm.selectedIndex]
943	sm.mu.RUnlock()
944
945	log := logging.FromContext(sm.ctx)
946
947	// Don't open current session
948	if info.IsCurrent {
949		log.Debug().Msg("cannot open current session")
950		return
951	}
952
953	log.Info().Str("session_id", string(info.Session.ID)).Msg("opening session")
954
955	sm.Hide(sm.ctx)
956
957	if sm.onOpen != nil {
958		sm.onOpen(info.Session.ID)
959	}
960}
961
962func (sm *SessionManager) deleteSelected() {
963	sm.mu.RLock()
964	if sm.selectedIndex < 0 || sm.selectedIndex >= len(sm.sessions) {
965		sm.mu.RUnlock()
966		return
967	}
968	info := sm.sessions[sm.selectedIndex]
969	sm.mu.RUnlock()
970
971	log := logging.FromContext(sm.ctx)
972
973	// Don't delete current or active sessions (early check before async)
974	if info.IsCurrent || info.IsActive {
975		log.Debug().Msg("cannot delete current or active session")
976		if sm.onToast != nil {
977			sm.onToast(sm.ctx, "Cannot delete active session", ToastWarning)
978		}
979		return
980	}
981
982	if sm.deleteSessionUC == nil {
983		log.Error().Msg("delete session use case not available")
984		return
985	}
986
987	sessionID := info.Session.ID
988	log.Info().Str("session_id", string(sessionID)).Msg("deleting session")
989
990	go func() {
991		err := sm.deleteSessionUC.Execute(sm.ctx, usecase.DeleteSessionInput{
992			SessionID:        sessionID,
993			CurrentSessionID: sm.currentSession,
994		})
995
996		cb := glib.SourceFunc(func(_ uintptr) bool {
997			if err != nil {
998				log.Error().Err(err).Msg("failed to delete session")
999				if sm.onToast != nil {
1000					sm.onToast(sm.ctx, "Failed to delete session", ToastError)
1001				}
1002			} else if sm.onToast != nil {
1003				sm.onToast(sm.ctx, "Session deleted", ToastSuccess)
1004			}
1005			sm.loadSessions()
1006			return false
1007		})
1008		glib.IdleAdd(&cb, 0)
1009	}()
1010}
1011
1012// Destroy cleans up session manager resources.
1013func (sm *SessionManager) Destroy() {
1014	sm.mu.Lock()
1015	sm.visible = false
1016	sm.mu.Unlock()
1017
1018	sm.parentOverlay = nil
1019	sm.retainedCallbacks = nil
1020
1021	if sm.outerBox != nil {
1022		sm.outerBox.Unparent()
1023		sm.outerBox = nil
1024	}
1025}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 8

Tags 42

↑↓ moveenter openesc close