summaryrefslogtreecommitdiffhomepage
path: root/packages/tui/internal/components/dialog/models.go
blob: 110151147b3dbc5ee537e4c3579061a712c8d4be (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
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
package dialog

import (
	"context"
	"fmt"
	"sort"
	"time"

	"github.com/charmbracelet/bubbles/v2/key"
	tea "github.com/charmbracelet/bubbletea/v2"
	"github.com/lithammer/fuzzysearch/fuzzy"
	"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/layout"
	"github.com/sst/opencode/internal/styles"
	"github.com/sst/opencode/internal/theme"
	"github.com/sst/opencode/internal/util"
)

const (
	numVisibleModels = 10
	minDialogWidth   = 40
	maxDialogWidth   = 80
	maxRecentModels  = 5
)

// ModelDialog interface for the model selection dialog
type ModelDialog interface {
	layout.Modal
}

type modelDialog struct {
	app          *app.App
	allModels    []ModelWithProvider
	width        int
	height       int
	modal        *modal.Modal
	searchDialog *SearchDialog
	dialogWidth  int
}

type ModelWithProvider struct {
	Model    opencode.Model
	Provider opencode.Provider
}

// modelItem is a custom list item for model selections
type modelItem struct {
	model ModelWithProvider
}

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

	itemStyle := baseStyle.
		Background(t.BackgroundPanel()).
		Foreground(t.Text())

	if selected {
		itemStyle = itemStyle.Foreground(t.Primary())
	}

	providerStyle := baseStyle.
		Foreground(t.TextMuted()).
		Background(t.BackgroundPanel())

	modelPart := itemStyle.Render(m.model.Model.Name)
	providerPart := providerStyle.Render(fmt.Sprintf(" %s", m.model.Provider.Name))

	combinedText := modelPart + providerPart
	return baseStyle.
		Background(t.BackgroundPanel()).
		PaddingLeft(1).
		Render(combinedText)
}

func (m modelItem) Selectable() bool {
	return true
}

type modelKeyMap struct {
	Enter  key.Binding
	Escape key.Binding
}

var modelKeys = modelKeyMap{
	Enter: key.NewBinding(
		key.WithKeys("enter"),
		key.WithHelp("enter", "select model"),
	),
	Escape: key.NewBinding(
		key.WithKeys("esc"),
		key.WithHelp("esc", "close"),
	),
}

func (m *modelDialog) Init() tea.Cmd {
	m.setupAllModels()
	return m.searchDialog.Init()
}

func (m *modelDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case SearchSelectionMsg:
		// Handle selection from search dialog
		if item, ok := msg.Item.(modelItem); ok {
			return m, tea.Sequence(
				util.CmdHandler(modal.CloseModalMsg{}),
				util.CmdHandler(
					app.ModelSelectedMsg{
						Provider: item.model.Provider,
						Model:    item.model.Model,
					}),
			)
		}
		return m, util.CmdHandler(modal.CloseModalMsg{})
	case SearchCancelledMsg:
		return m, util.CmdHandler(modal.CloseModalMsg{})

	case SearchRemoveItemMsg:
		if item, ok := msg.Item.(modelItem); ok {
			if m.isModelInRecentSection(item.model, msg.Index) {
				m.app.State.RemoveModelFromRecentlyUsed(item.model.Provider.ID, item.model.Model.ID)
				items := m.buildDisplayList(m.searchDialog.GetQuery())
				m.searchDialog.SetItems(items)
				return m, m.app.SaveState()
			}
		}
		return m, nil

	case SearchQueryChangedMsg:
		// Update the list based on search query
		items := m.buildDisplayList(msg.Query)
		m.searchDialog.SetItems(items)
		return m, nil

	case tea.WindowSizeMsg:
		m.width = msg.Width
		m.height = msg.Height
		m.searchDialog.SetWidth(m.dialogWidth)
		m.searchDialog.SetHeight(msg.Height)
	}

	updatedDialog, cmd := m.searchDialog.Update(msg)
	m.searchDialog = updatedDialog.(*SearchDialog)
	return m, cmd
}

func (m *modelDialog) View() string {
	return m.searchDialog.View()
}

func (m *modelDialog) calculateOptimalWidth(models []ModelWithProvider) int {
	maxWidth := minDialogWidth

	for _, model := range models {
		// Calculate the width needed for this item: "ModelName (ProviderName)"
		// Add 4 for the parentheses, space, and some padding
		itemWidth := len(model.Model.Name) + len(model.Provider.Name) + 4
		if itemWidth > maxWidth {
			maxWidth = itemWidth
		}
	}

	if maxWidth > maxDialogWidth {
		maxWidth = maxDialogWidth
	}

	return maxWidth
}

func (m *modelDialog) setupAllModels() {
	providers, _ := m.app.ListProviders(context.Background())

	m.allModels = make([]ModelWithProvider, 0)
	for _, provider := range providers {
		for _, model := range provider.Models {
			m.allModels = append(m.allModels, ModelWithProvider{
				Model:    model,
				Provider: provider,
			})
		}
	}

	m.sortModels()

	// Calculate optimal width based on all models
	m.dialogWidth = m.calculateOptimalWidth(m.allModels)

	// Initialize search dialog
	m.searchDialog = NewSearchDialog("Search models...", numVisibleModels)
	m.searchDialog.SetWidth(m.dialogWidth)

	// Build initial display list (empty query shows grouped view)
	items := m.buildDisplayList("")
	m.searchDialog.SetItems(items)
}

func (m *modelDialog) sortModels() {
	sort.Slice(m.allModels, func(i, j int) bool {
		modelA := m.allModels[i]
		modelB := m.allModels[j]

		usageA := m.getModelUsageTime(modelA.Provider.ID, modelA.Model.ID)
		usageB := m.getModelUsageTime(modelB.Provider.ID, modelB.Model.ID)

		// If both have usage times, sort by most recent first
		if !usageA.IsZero() && !usageB.IsZero() {
			return usageA.After(usageB)
		}

		// If only one has usage time, it goes first
		if !usageA.IsZero() && usageB.IsZero() {
			return true
		}
		if usageA.IsZero() && !usageB.IsZero() {
			return false
		}

		// If neither has usage time, sort by release date desc if available
		if modelA.Model.ReleaseDate != "" && modelB.Model.ReleaseDate != "" {
			dateA := m.parseReleaseDate(modelA.Model.ReleaseDate)
			dateB := m.parseReleaseDate(modelB.Model.ReleaseDate)
			if !dateA.IsZero() && !dateB.IsZero() {
				return dateA.After(dateB)
			}
		}

		// If only one has release date, it goes first
		if modelA.Model.ReleaseDate != "" && modelB.Model.ReleaseDate == "" {
			return true
		}
		if modelA.Model.ReleaseDate == "" && modelB.Model.ReleaseDate != "" {
			return false
		}

		// If neither has usage time nor release date, fall back to alphabetical sorting
		return modelA.Model.Name < modelB.Model.Name
	})
}

func (m *modelDialog) parseReleaseDate(dateStr string) time.Time {
	if parsed, err := time.Parse("2006-01-02", dateStr); err == nil {
		return parsed
	}

	return time.Time{}
}

func (m *modelDialog) getModelUsageTime(providerID, modelID string) time.Time {
	for _, usage := range m.app.State.RecentlyUsedModels {
		if usage.ProviderID == providerID && usage.ModelID == modelID {
			return usage.LastUsed
		}
	}
	return time.Time{}
}

// buildDisplayList creates the list items based on search query
func (m *modelDialog) buildDisplayList(query string) []list.Item {
	if query != "" {
		// Search mode: use fuzzy matching
		return m.buildSearchResults(query)
	} else {
		// Grouped mode: show Recent section and provider groups
		return m.buildGroupedResults()
	}
}

// buildSearchResults creates a flat list of search results using fuzzy matching
func (m *modelDialog) buildSearchResults(query string) []list.Item {
	type modelMatch struct {
		model ModelWithProvider
		score int
	}

	modelNames := []string{}
	modelMap := make(map[string]ModelWithProvider)

	// Create search strings and perform fuzzy matching
	for _, model := range m.allModels {
		searchStr := fmt.Sprintf("%s %s", model.Model.Name, model.Provider.Name)
		modelNames = append(modelNames, searchStr)
		modelMap[searchStr] = model

		searchStr = fmt.Sprintf("%s %s", model.Provider.Name, model.Model.Name)
		modelNames = append(modelNames, searchStr)
		modelMap[searchStr] = model
	}

	matches := fuzzy.RankFindFold(query, modelNames)
	sort.Sort(matches)

	items := []list.Item{}
	seenModels := make(map[string]bool)

	for _, match := range matches {
		model := modelMap[match.Target]
		// Create a unique key to avoid duplicates
		key := fmt.Sprintf("%s:%s", model.Provider.ID, model.Model.ID)
		if seenModels[key] {
			continue
		}
		seenModels[key] = true
		items = append(items, modelItem{model: model})
	}

	return items
}

// buildGroupedResults creates a grouped list with Recent section and provider groups
func (m *modelDialog) buildGroupedResults() []list.Item {
	var items []list.Item

	// Add Recent section
	recentModels := m.getRecentModels(maxRecentModels)
	if len(recentModels) > 0 {
		items = append(items, list.HeaderItem("Recent"))
		for _, model := range recentModels {
			items = append(items, modelItem{model: model})
		}
	}

	// Group models by provider
	providerGroups := make(map[string][]ModelWithProvider)
	for _, model := range m.allModels {
		providerName := model.Provider.Name
		providerGroups[providerName] = append(providerGroups[providerName], model)
	}

	// Get sorted provider names for consistent order
	var providerNames []string
	for name := range providerGroups {
		providerNames = append(providerNames, name)
	}
	sort.Strings(providerNames)

	// Add provider groups
	for _, providerName := range providerNames {
		models := providerGroups[providerName]

		// Sort models within provider group
		sort.Slice(models, func(i, j int) bool {
			modelA := models[i]
			modelB := models[j]

			usageA := m.getModelUsageTime(modelA.Provider.ID, modelA.Model.ID)
			usageB := m.getModelUsageTime(modelB.Provider.ID, modelB.Model.ID)

			// Sort by usage time first, then by release date, then alphabetically
			if !usageA.IsZero() && !usageB.IsZero() {
				return usageA.After(usageB)
			}
			if !usageA.IsZero() && usageB.IsZero() {
				return true
			}
			if usageA.IsZero() && !usageB.IsZero() {
				return false
			}

			// Sort by release date if available
			if modelA.Model.ReleaseDate != "" && modelB.Model.ReleaseDate != "" {
				dateA := m.parseReleaseDate(modelA.Model.ReleaseDate)
				dateB := m.parseReleaseDate(modelB.Model.ReleaseDate)
				if !dateA.IsZero() && !dateB.IsZero() {
					return dateA.After(dateB)
				}
			}

			return modelA.Model.Name < modelB.Model.Name
		})

		// Add provider header
		items = append(items, list.HeaderItem(providerName))

		// Add models in this provider group
		for _, model := range models {
			items = append(items, modelItem{model: model})
		}
	}

	return items
}

// getRecentModels returns the most recently used models
func (m *modelDialog) getRecentModels(limit int) []ModelWithProvider {
	var recentModels []ModelWithProvider

	// Get recent models from app state
	for _, usage := range m.app.State.RecentlyUsedModels {
		if len(recentModels) >= limit {
			break
		}

		// Find the corresponding model
		for _, model := range m.allModels {
			if model.Provider.ID == usage.ProviderID && model.Model.ID == usage.ModelID {
				recentModels = append(recentModels, model)
				break
			}
		}
	}

	return recentModels
}

func (m *modelDialog) isModelInRecentSection(model ModelWithProvider, index int) bool {
	// Only check if we're in grouped mode (no search query)
	if m.searchDialog.GetQuery() != "" {
		return false
	}

	recentModels := m.getRecentModels(maxRecentModels)
	if len(recentModels) == 0 {
		return false
	}

	// Index 0 is the "Recent" header, so recent models are at indices 1 to len(recentModels)
	if index >= 1 && index <= len(recentModels) {
		if index-1 < len(recentModels) {
			recentModel := recentModels[index-1]
			return recentModel.Provider.ID == model.Provider.ID &&
				recentModel.Model.ID == model.Model.ID
		}
	}

	return false
}

func (m *modelDialog) Render(background string) string {
	return m.modal.Render(m.View(), background)
}

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

func NewModelDialog(app *app.App) ModelDialog {
	dialog := &modelDialog{
		app: app,
	}

	dialog.setupAllModels()

	dialog.modal = modal.New(
		modal.WithTitle("Select Model"),
		modal.WithMaxWidth(dialog.dialogWidth+4),
	)

	return dialog
}