v0.31.0 bf0756b

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 []any
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	var indent strings.Builder
716	indent.WriteString("  ") // Base indent (minimal, tree branches provide visual alignment)
717	for range depth {
718		indent.WriteString("   ") // 3 spaces per depth level
719	}
720
721	// Branch character
722	if hasSibling {
723		prefix = "├── "
724	} else {
725		prefix = "└── "
726	}
727
728	// Icon based on node type
729	var icon string
730	switch nodeType {
731	case "tab":
732		icon = "󰓩 " // Tab icon (nerd font)
733	case "pane":
734		icon = "󰕮 " // Pane icon
735	case "split":
736		icon = "󰯍 " // Split icon
737	default:
738		icon = "  "
739	}
740
741	// Create the label with all parts
742	labelText := indent.String() + prefix + icon + text
743	label := gtk.NewLabel(&labelText)
744	if label == nil {
745		return nil
746	}
747	label.AddCssClass("session-tree-label")
748	label.SetHalign(gtk.AlignStartValue)
749	label.SetEllipsize(2) // PANGO_ELLIPSIZE_END
750
751	hbox.Append(&label.Widget)
752	row.SetChild(&hbox.Widget)
753
754	return row
755}
756
757func (sm *SessionManager) createDividerRow(text string) *gtk.ListBoxRow {
758	row := gtk.NewListBoxRow()
759	if row == nil {
760		return nil
761	}
762	row.SetSelectable(false)
763	row.SetActivatable(false)
764
765	label := gtk.NewLabel(&text)
766	if label == nil {
767		return nil
768	}
769	label.AddCssClass("session-divider")
770	label.SetHalign(gtk.AlignStartValue)
771	row.SetChild(&label.Widget)
772
773	return row
774}
775
776func (sm *SessionManager) createSessionRow(info entity.SessionInfo) *gtk.ListBoxRow {
777	row := gtk.NewListBoxRow()
778	if row == nil {
779		return nil
780	}
781	row.AddCssClass("session-manager-row-wrapper")
782
783	hbox := gtk.NewBox(gtk.OrientationHorizontalValue, sessionRowBoxSpacing)
784	if hbox == nil {
785		return nil
786	}
787	hbox.AddCssClass("session-manager-row")
788
789	sm.addStatusIndicator(hbox, info)
790	sm.addSessionInfo(hbox, info)
791	sm.addRelativeTime(hbox, info)
792
793	row.SetChild(&hbox.Widget)
794	return row
795}
796
797func (sm *SessionManager) addStatusIndicator(hbox *gtk.Box, info entity.SessionInfo) {
798	var statusText string
799	switch {
800	case info.IsCurrent:
801		statusText = "●" // Filled dot for current
802		hbox.AddCssClass("session-current")
803	case info.IsActive:
804		statusText = "○" // Empty dot for other active instance
805		hbox.AddCssClass("session-active")
806	default:
807		statusText = "◼" // Small square for exited (like stop icon)
808		hbox.AddCssClass("session-exited")
809	}
810	statusLabel := gtk.NewLabel(&statusText)
811	if statusLabel != nil {
812		statusLabel.AddCssClass("session-status")
813		hbox.Append(&statusLabel.Widget)
814	}
815}
816
817func (sm *SessionManager) addSessionInfo(hbox *gtk.Box, info entity.SessionInfo) {
818	const infoBoxSpacing = 2
819	infoBox := gtk.NewBox(gtk.OrientationVerticalValue, infoBoxSpacing)
820	if infoBox == nil {
821		return
822	}
823	infoBox.SetHexpand(true)
824
825	// Session ID row: shortID (accent) + rest of ID (dimmed) + optional (current) badge
826	idRowBox := gtk.NewBox(gtk.OrientationHorizontalValue, 0)
827	if idRowBox != nil {
828		idRowBox.SetHalign(gtk.AlignStartValue)
829
830		fullID := string(info.Session.ID)
831		shortID := info.Session.ShortID() // Last 4 chars
832
833		// Short ID with accent color (displayed first)
834		shortLabel := gtk.NewLabel(&shortID)
835		if shortLabel != nil {
836			shortLabel.AddCssClass("session-id-short")
837			idRowBox.Append(&shortLabel.Widget)
838		}
839
840		// Rest of the ID (prefix before the short suffix), dimmed
841		// Format: "20251225_083026_7566" -> shortID="7566", prefix="20251225_083026"
842		// Remove trailing underscore for cleaner display
843		if len(fullID) > 4 {
844			prefix := fullID[:len(fullID)-4]
845			// Trim trailing underscore if present
846			prefix = strings.TrimSuffix(prefix, "_")
847			prefix = " " + prefix
848			prefixLabel := gtk.NewLabel(&prefix)
849			if prefixLabel != nil {
850				prefixLabel.AddCssClass("session-id-prefix")
851				idRowBox.Append(&prefixLabel.Widget)
852			}
853		}
854
855		// Current badge
856		if info.IsCurrent {
857			badge := " (current)"
858			badgeLabel := gtk.NewLabel(&badge)
859			if badgeLabel != nil {
860				badgeLabel.AddCssClass("session-id-badge")
861				idRowBox.Append(&badgeLabel.Widget)
862			}
863		}
864
865		infoBox.Append(&idRowBox.Widget)
866	}
867
868	// Tab/pane count
869	countText := fmt.Sprintf("%d tabs, %d panes", info.TabCount, info.PaneCount)
870	countLabel := gtk.NewLabel(&countText)
871	if countLabel != nil {
872		countLabel.AddCssClass("session-count")
873		countLabel.SetHalign(gtk.AlignStartValue)
874		infoBox.Append(&countLabel.Widget)
875	}
876
877	hbox.Append(&infoBox.Widget)
878}
879
880func (sm *SessionManager) addRelativeTime(hbox *gtk.Box, info entity.SessionInfo) {
881	relTime := usecase.GetRelativeTime(info.UpdatedAt)
882	timeLabel := gtk.NewLabel(&relTime)
883	if timeLabel != nil {
884		timeLabel.AddCssClass("session-time")
885		timeLabel.SetValign(gtk.AlignCenterValue)
886		hbox.Append(&timeLabel.Widget)
887	}
888}
889
890func (sm *SessionManager) selectPrevious() {
891	sm.mu.Lock()
892	maxIndex := len(sm.sessions) - 1
893	if maxIndex < 0 {
894		sm.mu.Unlock()
895		return
896	}
897	sm.selectedIndex--
898	if sm.selectedIndex < 0 {
899		sm.selectedIndex = maxIndex // Wrap to bottom
900	}
901	idx := sm.selectedIndex
902	sm.mu.Unlock()
903
904	sm.selectBySessionIndex(idx)
905}
906
907func (sm *SessionManager) selectNext() {
908	sm.mu.Lock()
909	maxIndex := len(sm.sessions) - 1
910	if maxIndex < 0 {
911		sm.mu.Unlock()
912		return
913	}
914	sm.selectedIndex++
915	if sm.selectedIndex > maxIndex {
916		sm.selectedIndex = 0 // Wrap to top
917	}
918	idx := sm.selectedIndex
919	sm.mu.Unlock()
920
921	sm.selectBySessionIndex(idx)
922}
923
924func (sm *SessionManager) toggleExpanded() {
925	sm.mu.Lock()
926	if sm.expandedIndex == sm.selectedIndex {
927		sm.expandedIndex = -1 // collapse
928	} else {
929		sm.expandedIndex = sm.selectedIndex // expand
930	}
931	sm.mu.Unlock()
932
933	// Rebuild the list to show/hide tree
934	sm.populateList()
935}
936
937func (sm *SessionManager) openSelected() {
938	sm.mu.RLock()
939	if sm.selectedIndex < 0 || sm.selectedIndex >= len(sm.sessions) {
940		sm.mu.RUnlock()
941		return
942	}
943	info := sm.sessions[sm.selectedIndex]
944	sm.mu.RUnlock()
945
946	log := logging.FromContext(sm.ctx)
947
948	// Don't open current session
949	if info.IsCurrent {
950		log.Debug().Msg("cannot open current session")
951		return
952	}
953
954	log.Info().Str("session_id", string(info.Session.ID)).Msg("opening session")
955
956	sm.Hide(sm.ctx)
957
958	if sm.onOpen != nil {
959		sm.onOpen(info.Session.ID)
960	}
961}
962
963func (sm *SessionManager) deleteSelected() {
964	sm.mu.RLock()
965	if sm.selectedIndex < 0 || sm.selectedIndex >= len(sm.sessions) {
966		sm.mu.RUnlock()
967		return
968	}
969	info := sm.sessions[sm.selectedIndex]
970	sm.mu.RUnlock()
971
972	log := logging.FromContext(sm.ctx)
973
974	// Don't delete current or active sessions (early check before async)
975	if info.IsCurrent || info.IsActive {
976		log.Debug().Msg("cannot delete current or active session")
977		if sm.onToast != nil {
978			sm.onToast(sm.ctx, "Cannot delete active session", ToastWarning)
979		}
980		return
981	}
982
983	if sm.deleteSessionUC == nil {
984		log.Error().Msg("delete session use case not available")
985		return
986	}
987
988	sessionID := info.Session.ID
989	log.Info().Str("session_id", string(sessionID)).Msg("deleting session")
990
991	go func() {
992		err := sm.deleteSessionUC.Execute(sm.ctx, usecase.DeleteSessionInput{
993			SessionID:        sessionID,
994			CurrentSessionID: sm.currentSession,
995		})
996
997		cb := glib.SourceFunc(func(_ uintptr) bool {
998			if err != nil {
999				log.Error().Err(err).Msg("failed to delete session")
1000				if sm.onToast != nil {
1001					sm.onToast(sm.ctx, "Failed to delete session", ToastError)
1002				}
1003			} else if sm.onToast != nil {
1004				sm.onToast(sm.ctx, "Session deleted", ToastSuccess)
1005			}
1006			sm.loadSessions()
1007			return false
1008		})
1009		glib.IdleAdd(&cb, 0)
1010	}()
1011}
1012
1013// Destroy cleans up session manager resources.
1014func (sm *SessionManager) Destroy() {
1015	sm.mu.Lock()
1016	sm.visible = false
1017	sm.mu.Unlock()
1018
1019	sm.parentOverlay = nil
1020	sm.retainedCallbacks = nil
1021
1022	if sm.outerBox != nil {
1023		sm.outerBox.Unparent()
1024		sm.outerBox = nil
1025	}
1026}

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