summaryrefslogtreecommitdiffhomepage
path: root/packages/tui/internal/components/dialog/session.go
blob: a0eac8eb7639c024aeacbecba00d024d253a7444 (plain)
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
package dialog

import (
	"context"
	"strings"

	"slices"

	tea "github.com/charmbracelet/bubbletea/v2"
	"github.com/muesli/reflow/truncate"
	"github.com/sst/opencode-sdk-go"
	"github.com/sst/opencode/internal/app"
	"github.com/sst/opencode/internal/components/list"
	"github.com/sst/opencode/internal/components/modal"
	"github.com/sst/opencode/internal/components/toast"
	"github.com/sst/opencode/internal/layout"
	"github.com/sst/opencode/internal/styles"
	"github.com/sst/opencode/internal/theme"
	"github.com/sst/opencode/internal/util"
)

// SessionDialog interface for the session switching dialog
type SessionDialog interface {
	layout.Modal
}

// sessionItem is a custom list item for sessions that can show delete confirmation
type sessionItem struct {
	title              string
	isDeleteConfirming bool
}

func (s sessionItem) Render(
	selected bool,
	width int,
	isFirstInViewport bool,
	baseStyle styles.Style,
) string {
	t := theme.CurrentTheme()

	var text string
	if s.isDeleteConfirming {
		text = "Press again to confirm delete"
	} else {
		text = s.title
	}

	truncatedStr := truncate.StringWithTail(text, uint(width-1), "...")

	var itemStyle styles.Style
	if selected {
		if s.isDeleteConfirming {
			// Red background for delete confirmation
			itemStyle = baseStyle.
				Background(t.Error()).
				Foreground(t.BackgroundElement()).
				Width(width).
				PaddingLeft(1)
		} else {
			// Normal selection
			itemStyle = baseStyle.
				Background(t.Primary()).
				Foreground(t.BackgroundElement()).
				Width(width).
				PaddingLeft(1)
		}
	} else {
		if s.isDeleteConfirming {
			// Red text for delete confirmation when not selected
			itemStyle = baseStyle.
				Foreground(t.Error()).
				PaddingLeft(1)
		} else {
			itemStyle = baseStyle.
				PaddingLeft(1)
		}
	}

	return itemStyle.Render(truncatedStr)
}

func (s sessionItem) Selectable() bool {
	return true
}

type sessionDialog struct {
	width              int
	height             int
	modal              *modal.Modal
	sessions           []opencode.Session
	list               list.List[sessionItem]
	app                *app.App
	deleteConfirmation int // -1 means no confirmation, >= 0 means confirming deletion of session at this index
}

func (s *sessionDialog) Init() tea.Cmd {
	return nil
}

func (s *sessionDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		s.width = msg.Width
		s.height = msg.Height
		s.list.SetMaxWidth(layout.Current.Container.Width - 12)
	case tea.KeyPressMsg:
		switch msg.String() {
		case "enter":
			if s.deleteConfirmation >= 0 {
				s.deleteConfirmation = -1
				s.updateListItems()
				return s, nil
			}
			if _, idx := s.list.GetSelectedItem(); idx >= 0 && idx < len(s.sessions) {
				selectedSession := s.sessions[idx]
				return s, tea.Sequence(
					util.CmdHandler(modal.CloseModalMsg{}),
					util.CmdHandler(app.SessionSelectedMsg(&selectedSession)),
				)
			}
		case "n":
			s.app.Session = &opencode.Session{}
			s.app.Messages = []app.Message{}
			return s, tea.Sequence(
				util.CmdHandler(modal.CloseModalMsg{}),
				util.CmdHandler(app.SessionClearedMsg{}),
			)
		case "x", "delete", "backspace":
			if _, idx := s.list.GetSelectedItem(); idx >= 0 && idx < len(s.sessions) {
				if s.deleteConfirmation == idx {
					// Second press - actually delete the session
					sessionToDelete := s.sessions[idx]
					return s, tea.Sequence(
						func() tea.Msg {
							s.sessions = slices.Delete(s.sessions, idx, idx+1)
							s.deleteConfirmation = -1
							s.updateListItems()
							return nil
						},
						s.deleteSession(sessionToDelete.ID),
					)
				} else {
					// First press - enter delete confirmation mode
					s.deleteConfirmation = idx
					s.updateListItems()
					return s, nil
				}
			}
		case "esc":
			if s.deleteConfirmation >= 0 {
				s.deleteConfirmation = -1
				s.updateListItems()
				return s, nil
			}
		}
	}

	var cmd tea.Cmd
	listModel, cmd := s.list.Update(msg)
	s.list = listModel.(list.List[sessionItem])
	return s, cmd
}

func (s *sessionDialog) Render(background string) string {
	listView := s.list.View()

	t := theme.CurrentTheme()
	keyStyle := styles.NewStyle().Foreground(t.Text()).Background(t.BackgroundPanel()).Render
	mutedStyle := styles.NewStyle().Foreground(t.TextMuted()).Background(t.BackgroundPanel()).Render

	leftHelp := keyStyle("n") + mutedStyle(" new session")
	rightHelp := keyStyle("x/del") + mutedStyle(" delete session")

	bgColor := t.BackgroundPanel()
	helpText := layout.Render(layout.FlexOptions{
		Direction:  layout.Row,
		Justify:    layout.JustifySpaceBetween,
		Width:      layout.Current.Container.Width - 14,
		Background: &bgColor,
	}, layout.FlexItem{View: leftHelp}, layout.FlexItem{View: rightHelp})

	helpText = styles.NewStyle().PaddingLeft(1).PaddingTop(1).Render(helpText)

	content := strings.Join([]string{listView, helpText}, "\n")

	return s.modal.Render(content, background)
}

func (s *sessionDialog) updateListItems() {
	_, currentIdx := s.list.GetSelectedItem()

	var items []sessionItem
	for i, sess := range s.sessions {
		item := sessionItem{
			title:              sess.Title,
			isDeleteConfirming: s.deleteConfirmation == i,
		}
		items = append(items, item)
	}
	s.list.SetItems(items)
	s.list.SetSelectedIndex(currentIdx)
}

func (s *sessionDialog) deleteSession(sessionID string) tea.Cmd {
	return func() tea.Msg {
		ctx := context.Background()
		if err := s.app.DeleteSession(ctx, sessionID); err != nil {
			return toast.NewErrorToast("Failed to delete session: " + err.Error())()
		}
		return nil
	}
}

func (s *sessionDialog) Close() tea.Cmd {
	return nil
}

// NewSessionDialog creates a new session switching dialog
func NewSessionDialog(app *app.App) SessionDialog {
	sessions, _ := app.ListSessions(context.Background())

	var filteredSessions []opencode.Session
	var items []sessionItem
	for _, sess := range sessions {
		if sess.ParentID != "" {
			continue
		}
		filteredSessions = append(filteredSessions, sess)
		items = append(items, sessionItem{
			title:              sess.Title,
			isDeleteConfirming: false,
		})
	}

	listComponent := list.NewListComponent(
		list.WithItems(items),
		list.WithMaxVisibleHeight[sessionItem](10),
		list.WithFallbackMessage[sessionItem]("No sessions available"),
		list.WithAlphaNumericKeys[sessionItem](true),
		list.WithRenderFunc(
			func(item sessionItem, selected bool, width int, baseStyle styles.Style) string {
				return item.Render(selected, width, false, baseStyle)
			},
		),
		list.WithSelectableFunc(func(item sessionItem) bool {
			return true
		}),
	)
	listComponent.SetMaxWidth(layout.Current.Container.Width - 12)

	return &sessionDialog{
		sessions:           filteredSessions,
		list:               listComponent,
		app:                app,
		deleteConfirmation: -1,
		modal: modal.New(
			modal.WithTitle("Switch Session"),
			modal.WithMaxWidth(layout.Current.Container.Width-8),
		),
	}
}