-
Notifications
You must be signed in to change notification settings - Fork 441
Expand file tree
/
Copy pathapp.go
More file actions
840 lines (741 loc) · 23.4 KB
/
app.go
File metadata and controls
840 lines (741 loc) · 23.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
package app
import (
"claude-squad/config"
"claude-squad/keys"
"claude-squad/log"
"claude-squad/session"
"claude-squad/session/git"
"claude-squad/ui"
"claude-squad/ui/overlay"
"context"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/mattn/go-runewidth"
)
const GlobalInstanceLimit = 10
// Run is the main entrypoint into the application.
func Run(ctx context.Context, program string, autoYes bool) error {
p := tea.NewProgram(
newHome(ctx, program, autoYes),
tea.WithAltScreen(),
tea.WithMouseCellMotion(), // Mouse scroll
)
_, err := p.Run()
return err
}
type state int
const (
stateDefault state = iota
// stateNew is the state when the user is creating a new instance.
stateNew
// statePrompt is the state when the user is entering a prompt.
statePrompt
// stateHelp is the state when a help screen is displayed.
stateHelp
// stateConfirm is the state when a confirmation modal is displayed.
stateConfirm
)
type home struct {
ctx context.Context
// -- Storage and Configuration --
program string
autoYes bool
// storage is the interface for saving/loading data to/from the app's state
storage *session.Storage
// appConfig stores persistent application configuration
appConfig *config.Config
// appState stores persistent application state like seen help screens
appState config.AppState
// -- State --
// state is the current discrete state of the application
state state
// newInstanceFinalizer is called when the state is stateNew and then you press enter.
// It registers the new instance in the list after the instance has been started.
newInstanceFinalizer func()
// promptAfterName tracks if we should enter prompt mode after naming
promptAfterName bool
// keySent is used to manage underlining menu items
keySent bool
// instanceStarting is true while a background instance start is in progress.
// Prevents double-submission and guards against interacting with a not-yet-started instance.
instanceStarting bool
// startingInstance holds a reference to the instance being started in the background.
startingInstance *session.Instance
// -- UI Components --
// list displays the list of instances
list *ui.List
// menu displays the bottom menu
menu *ui.Menu
// tabbedWindow displays the tabbed window with preview and diff panes
tabbedWindow *ui.TabbedWindow
// errBox displays error messages
errBox *ui.ErrBox
// global spinner instance. we plumb this down to where it's needed
spinner spinner.Model
// textInputOverlay handles text input with state
textInputOverlay *overlay.TextInputOverlay
// textOverlay displays text information
textOverlay *overlay.TextOverlay
// confirmationOverlay displays confirmation modals
confirmationOverlay *overlay.ConfirmationOverlay
}
func newHome(ctx context.Context, program string, autoYes bool) *home {
// Load application config
appConfig := config.LoadConfig()
// Load application state
appState := config.LoadState()
// Initialize storage
storage, err := session.NewStorage(appState)
if err != nil {
fmt.Printf("Failed to initialize storage: %v\n", err)
os.Exit(1)
}
h := &home{
ctx: ctx,
spinner: spinner.New(spinner.WithSpinner(spinner.MiniDot)),
menu: ui.NewMenu(),
tabbedWindow: ui.NewTabbedWindow(ui.NewPreviewPane(), ui.NewDiffPane()),
errBox: ui.NewErrBox(),
storage: storage,
appConfig: appConfig,
program: program,
autoYes: autoYes,
state: stateDefault,
appState: appState,
}
h.list = ui.NewList(&h.spinner, autoYes)
// Load saved instances
instances, err := storage.LoadInstances()
if err != nil {
fmt.Printf("Failed to load instances: %v\n", err)
os.Exit(1)
}
// Add loaded instances to the list
for _, instance := range instances {
// Call the finalizer immediately.
h.list.AddInstance(instance)()
if autoYes {
instance.AutoYes = true
}
}
return h
}
// updateHandleWindowSizeEvent sets the sizes of the components.
// The components will try to render inside their bounds.
func (m *home) updateHandleWindowSizeEvent(msg tea.WindowSizeMsg) {
// List takes 30% of width, preview takes 70%
listWidth := int(float32(msg.Width) * 0.3)
tabsWidth := msg.Width - listWidth
// Menu takes 10% of height, list and window take 90%
contentHeight := int(float32(msg.Height) * 0.9)
menuHeight := msg.Height - contentHeight - 1 // minus 1 for error box
m.errBox.SetSize(int(float32(msg.Width)*0.9), 1) // error box takes 1 row
m.tabbedWindow.SetSize(tabsWidth, contentHeight)
m.list.SetSize(listWidth, contentHeight)
if m.textInputOverlay != nil {
m.textInputOverlay.SetSize(int(float32(msg.Width)*0.6), int(float32(msg.Height)*0.4))
}
if m.textOverlay != nil {
m.textOverlay.SetWidth(int(float32(msg.Width) * 0.6))
}
previewWidth, previewHeight := m.tabbedWindow.GetPreviewSize()
if err := m.list.SetSessionPreviewSize(previewWidth, previewHeight); err != nil {
log.ErrorLog.Print(err)
}
m.menu.SetSize(msg.Width, menuHeight)
}
func (m *home) Init() tea.Cmd {
// Upon starting, we want to start the spinner. Whenever we get a spinner.TickMsg, we
// update the spinner, which sends a new spinner.TickMsg. I think this lasts forever lol.
return tea.Batch(
m.spinner.Tick,
func() tea.Msg {
time.Sleep(100 * time.Millisecond)
return previewTickMsg{}
},
tickUpdateMetadataCmd(m.list.GetInstances()),
)
}
func (m *home) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case hideErrMsg:
m.errBox.Clear()
case previewTickMsg:
cmd := m.instanceChanged()
return m, tea.Batch(
cmd,
func() tea.Msg {
time.Sleep(100 * time.Millisecond)
return previewTickMsg{}
},
)
case keyupMsg:
m.menu.ClearKeydown()
return m, nil
case instanceStartDoneMsg:
m.instanceStarting = false
inst := msg.instance
m.startingInstance = nil
if msg.err != nil {
// Start failed — remove the instance from the list and show the error.
m.list.Kill()
return m, tea.Batch(tea.WindowSize(), m.instanceChanged(), m.handleError(msg.err))
}
// Save after successful start.
if err := m.storage.SaveInstances(m.list.GetInstances()); err != nil {
return m, m.handleError(err)
}
if m.promptAfterName {
m.state = statePrompt
m.menu.SetState(ui.StatePrompt)
m.textInputOverlay = overlay.NewTextInputOverlay("Enter prompt", "")
m.promptAfterName = false
} else {
m.showHelpScreen(helpStart(inst), nil)
}
return m, tea.Batch(tea.WindowSize(), m.instanceChanged())
case metadataUpdateDoneMsg:
for _, r := range msg.results {
if r.updated {
r.instance.SetStatus(session.Running)
} else if r.hasPrompt {
r.instance.TapEnter()
} else {
r.instance.SetStatus(session.Ready)
}
if r.diffStats != nil && r.diffStats.Error != nil {
if !strings.Contains(r.diffStats.Error.Error(), "base commit SHA not set") {
log.WarningLog.Printf("could not update diff stats: %v", r.diffStats.Error)
}
r.instance.SetDiffStats(nil)
} else {
r.instance.SetDiffStats(r.diffStats)
}
}
return m, tickUpdateMetadataCmd(m.list.GetInstances())
case tea.MouseMsg:
// Handle mouse wheel events for scrolling the diff/preview pane
if msg.Action == tea.MouseActionPress {
if msg.Button == tea.MouseButtonWheelDown || msg.Button == tea.MouseButtonWheelUp {
selected := m.list.GetSelectedInstance()
if selected == nil || selected.Status == session.Paused {
return m, nil
}
switch msg.Button {
case tea.MouseButtonWheelUp:
m.tabbedWindow.ScrollUp()
case tea.MouseButtonWheelDown:
m.tabbedWindow.ScrollDown()
}
}
}
return m, nil
case tea.KeyMsg:
return m.handleKeyPress(msg)
case tea.WindowSizeMsg:
m.updateHandleWindowSizeEvent(msg)
return m, nil
case error:
// Handle errors from confirmation actions
return m, m.handleError(msg)
case instanceChangedMsg:
// Handle instance changed after confirmation action
return m, m.instanceChanged()
case spinner.TickMsg:
var cmd tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
}
return m, nil
}
func (m *home) handleQuit() (tea.Model, tea.Cmd) {
if err := m.storage.SaveInstances(m.list.GetInstances()); err != nil {
return m, m.handleError(err)
}
return m, tea.Quit
}
func (m *home) handleMenuHighlighting(msg tea.KeyMsg) (cmd tea.Cmd, returnEarly bool) {
// Handle menu highlighting when you press a button. We intercept it here and immediately return to
// update the ui while re-sending the keypress. Then, on the next call to this, we actually handle the keypress.
if m.keySent {
m.keySent = false
return nil, false
}
if m.state == statePrompt || m.state == stateHelp || m.state == stateConfirm {
return nil, false
}
// If it's in the global keymap, we should try to highlight it.
name, ok := keys.GlobalKeyStringsMap[msg.String()]
if !ok {
return nil, false
}
if m.list.GetSelectedInstance() != nil && m.list.GetSelectedInstance().Paused() && name == keys.KeyEnter {
return nil, false
}
if name == keys.KeyShiftDown || name == keys.KeyShiftUp {
return nil, false
}
// Skip the menu highlighting if the key is not in the map or we are using the shift up and down keys.
// TODO: cleanup: when you press enter on stateNew, we use keys.KeySubmitName. We should unify the keymap.
if name == keys.KeyEnter && m.state == stateNew {
name = keys.KeySubmitName
}
m.keySent = true
return tea.Batch(
func() tea.Msg { return msg },
m.keydownCallback(name)), true
}
func (m *home) handleKeyPress(msg tea.KeyMsg) (mod tea.Model, cmd tea.Cmd) {
cmd, returnEarly := m.handleMenuHighlighting(msg)
if returnEarly {
return m, cmd
}
if m.state == stateHelp {
return m.handleHelpState(msg)
}
if m.state == stateNew {
// Handle quit commands first. Don't handle q because the user might want to type that.
if msg.String() == "ctrl+c" {
m.state = stateDefault
m.promptAfterName = false
m.list.Kill()
return m, tea.Sequence(
tea.WindowSize(),
func() tea.Msg {
m.menu.SetState(ui.StateDefault)
return nil
},
)
}
instance := m.list.GetInstances()[m.list.NumInstances()-1]
switch msg.Type {
// Start the instance (enable previews etc) and go back to the main menu state.
case tea.KeyEnter:
if len(instance.Title) == 0 {
return m, m.handleError(fmt.Errorf("title cannot be empty"))
}
// Set loading status for visual feedback (spinner in the list).
instance.SetStatus(session.Loading)
// Register the instance in the list (call finalizer once).
m.newInstanceFinalizer()
if m.autoYes {
instance.AutoYes = true
}
// Track the starting instance so the done handler can finish setup.
m.instanceStarting = true
m.startingInstance = instance
// Transition to default state immediately so the UI stays responsive.
m.state = stateDefault
m.menu.SetState(ui.StateDefault)
// Kick off the expensive Start() in a background goroutine.
return m, tea.Batch(tea.WindowSize(), m.instanceChanged(), runInstanceStartCmd(instance))
case tea.KeyRunes:
if runewidth.StringWidth(instance.Title) >= 32 {
return m, m.handleError(fmt.Errorf("title cannot be longer than 32 characters"))
}
if err := instance.SetTitle(instance.Title + string(msg.Runes)); err != nil {
return m, m.handleError(err)
}
case tea.KeyBackspace:
runes := []rune(instance.Title)
if len(runes) == 0 {
return m, nil
}
if err := instance.SetTitle(string(runes[:len(runes)-1])); err != nil {
return m, m.handleError(err)
}
case tea.KeySpace:
if err := instance.SetTitle(instance.Title + " "); err != nil {
return m, m.handleError(err)
}
case tea.KeyEsc:
m.list.Kill()
m.state = stateDefault
m.instanceChanged()
return m, tea.Sequence(
tea.WindowSize(),
func() tea.Msg {
m.menu.SetState(ui.StateDefault)
return nil
},
)
default:
}
return m, nil
} else if m.state == statePrompt {
// Use the new TextInputOverlay component to handle all key events
shouldClose := m.textInputOverlay.HandleKeyPress(msg)
// Check if the form was submitted or canceled
if shouldClose {
selected := m.list.GetSelectedInstance()
// TODO: this should never happen since we set the instance in the previous state.
if selected == nil {
return m, nil
}
if m.textInputOverlay.IsSubmitted() {
if err := selected.SendPrompt(m.textInputOverlay.GetValue()); err != nil {
// TODO: we probably end up in a bad state here.
return m, m.handleError(err)
}
}
// Close the overlay and reset state
m.textInputOverlay = nil
m.state = stateDefault
return m, tea.Sequence(
tea.WindowSize(),
func() tea.Msg {
m.menu.SetState(ui.StateDefault)
m.showHelpScreen(helpStart(selected), nil)
return nil
},
)
}
return m, nil
}
// Handle confirmation state
if m.state == stateConfirm {
shouldClose := m.confirmationOverlay.HandleKeyPress(msg)
if shouldClose {
m.state = stateDefault
m.confirmationOverlay = nil
return m, nil
}
return m, nil
}
// Exit scrolling mode when ESC is pressed and preview pane is in scrolling mode
// Check if Escape key was pressed and we're not in the diff tab (meaning we're in preview tab)
// Always check for escape key first to ensure it doesn't get intercepted elsewhere
if msg.Type == tea.KeyEsc {
// If in preview tab and in scroll mode, exit scroll mode
if !m.tabbedWindow.IsInDiffTab() && m.tabbedWindow.IsPreviewInScrollMode() {
// Use the selected instance from the list
selected := m.list.GetSelectedInstance()
err := m.tabbedWindow.ResetPreviewToNormalMode(selected)
if err != nil {
return m, m.handleError(err)
}
return m, m.instanceChanged()
}
}
// Handle quit commands first
if msg.String() == "ctrl+c" || msg.String() == "q" {
return m.handleQuit()
}
name, ok := keys.GlobalKeyStringsMap[msg.String()]
if !ok {
return m, nil
}
switch name {
case keys.KeyHelp:
return m.showHelpScreen(helpTypeGeneral{}, nil)
case keys.KeyPrompt:
if m.instanceStarting {
return m, m.handleError(fmt.Errorf("please wait for the current session to finish starting"))
}
if m.list.NumInstances() >= GlobalInstanceLimit {
return m, m.handleError(
fmt.Errorf("you can't create more than %d instances", GlobalInstanceLimit))
}
instance, err := session.NewInstance(session.InstanceOptions{
Title: "",
Path: ".",
Program: m.program,
})
if err != nil {
return m, m.handleError(err)
}
m.newInstanceFinalizer = m.list.AddInstance(instance)
m.list.SetSelectedInstance(m.list.NumInstances() - 1)
m.state = stateNew
m.menu.SetState(ui.StateNewInstance)
m.promptAfterName = true
return m, nil
case keys.KeyNew:
if m.instanceStarting {
return m, m.handleError(fmt.Errorf("please wait for the current session to finish starting"))
}
if m.list.NumInstances() >= GlobalInstanceLimit {
return m, m.handleError(
fmt.Errorf("you can't create more than %d instances", GlobalInstanceLimit))
}
instance, err := session.NewInstance(session.InstanceOptions{
Title: "",
Path: ".",
Program: m.program,
})
if err != nil {
return m, m.handleError(err)
}
m.newInstanceFinalizer = m.list.AddInstance(instance)
m.list.SetSelectedInstance(m.list.NumInstances() - 1)
m.state = stateNew
m.menu.SetState(ui.StateNewInstance)
return m, nil
case keys.KeyUp:
m.list.Up()
return m, m.instanceChanged()
case keys.KeyDown:
m.list.Down()
return m, m.instanceChanged()
case keys.KeyShiftUp:
m.tabbedWindow.ScrollUp()
return m, m.instanceChanged()
case keys.KeyShiftDown:
m.tabbedWindow.ScrollDown()
return m, m.instanceChanged()
case keys.KeyTab:
m.tabbedWindow.Toggle()
m.menu.SetInDiffTab(m.tabbedWindow.IsInDiffTab())
return m, m.instanceChanged()
case keys.KeyKill:
selected := m.list.GetSelectedInstance()
if selected == nil {
return m, nil
}
// Create the kill action as a tea.Cmd
killAction := func() tea.Msg {
// Get worktree and check if branch is checked out
worktree, err := selected.GetGitWorktree()
if err != nil {
return err
}
checkedOut, err := worktree.IsBranchCheckedOut()
if err != nil {
return err
}
if checkedOut {
return fmt.Errorf("instance %s is currently checked out", selected.Title)
}
// Delete from storage first
if err := m.storage.DeleteInstance(selected.Title); err != nil {
return err
}
// Then kill the instance
m.list.Kill()
return instanceChangedMsg{}
}
// Show confirmation modal
message := fmt.Sprintf("[!] Kill session '%s'?", selected.Title)
return m, m.confirmAction(message, killAction)
case keys.KeySubmit:
selected := m.list.GetSelectedInstance()
if selected == nil || selected.Status == session.Loading {
return m, nil
}
// Create the push action as a tea.Cmd
pushAction := func() tea.Msg {
// Default commit message with timestamp
commitMsg := fmt.Sprintf("[claudesquad] update from '%s' on %s", selected.Title, time.Now().Format(time.RFC822))
worktree, err := selected.GetGitWorktree()
if err != nil {
return err
}
if err = worktree.PushChanges(commitMsg, true); err != nil {
return err
}
return nil
}
// Show confirmation modal
message := fmt.Sprintf("[!] Push changes from session '%s'?", selected.Title)
return m, m.confirmAction(message, pushAction)
case keys.KeyCheckout:
selected := m.list.GetSelectedInstance()
if selected == nil || selected.Status == session.Loading {
return m, nil
}
// Show help screen before pausing
m.showHelpScreen(helpTypeInstanceCheckout{}, func() {
if err := selected.Pause(); err != nil {
m.handleError(err)
}
m.instanceChanged()
})
return m, nil
case keys.KeyResume:
selected := m.list.GetSelectedInstance()
if selected == nil {
return m, nil
}
if err := selected.Resume(); err != nil {
return m, m.handleError(err)
}
return m, tea.WindowSize()
case keys.KeyEnter:
if m.list.NumInstances() == 0 {
return m, nil
}
selected := m.list.GetSelectedInstance()
if selected == nil || selected.Paused() || selected.Status == session.Loading || !selected.TmuxAlive() {
return m, nil
}
// Show help screen before attaching
m.showHelpScreen(helpTypeInstanceAttach{}, func() {
ch, err := m.list.Attach()
if err != nil {
m.handleError(err)
return
}
<-ch
m.state = stateDefault
m.instanceChanged()
})
return m, nil
default:
return m, nil
}
}
// instanceChanged updates the preview pane, menu, and diff pane based on the selected instance. It returns an error
// Cmd if there was any error.
func (m *home) instanceChanged() tea.Cmd {
// selected may be nil
selected := m.list.GetSelectedInstance()
m.tabbedWindow.UpdateDiff(selected)
m.tabbedWindow.SetInstance(selected)
// Update menu with current instance
m.menu.SetInstance(selected)
// If there's no selected instance, we don't need to update the preview.
if err := m.tabbedWindow.UpdatePreview(selected); err != nil {
return m.handleError(err)
}
return nil
}
type keyupMsg struct{}
// keydownCallback clears the menu option highlighting after 500ms.
func (m *home) keydownCallback(name keys.KeyName) tea.Cmd {
m.menu.Keydown(name)
return func() tea.Msg {
select {
case <-m.ctx.Done():
case <-time.After(500 * time.Millisecond):
}
return keyupMsg{}
}
}
// hideErrMsg implements tea.Msg and clears the error text from the screen.
type hideErrMsg struct{}
// previewTickMsg implements tea.Msg and triggers a preview update
type previewTickMsg struct{}
type instanceChangedMsg struct{}
// instanceMetaResult holds the results of a single instance's metadata update,
// computed in a background goroutine.
type instanceMetaResult struct {
instance *session.Instance
updated bool
hasPrompt bool
diffStats *git.DiffStats
}
// metadataUpdateDoneMsg is sent when the background metadata update completes.
type metadataUpdateDoneMsg struct {
results []instanceMetaResult
}
// instanceStartDoneMsg is sent when the background instance start completes.
type instanceStartDoneMsg struct {
instance *session.Instance
err error
}
// runInstanceStartCmd returns a Cmd that performs the expensive instance.Start(true)
// in a background goroutine so the main event loop stays responsive.
func runInstanceStartCmd(instance *session.Instance) tea.Cmd {
return func() tea.Msg {
err := instance.Start(true)
return instanceStartDoneMsg{instance: instance, err: err}
}
}
// tickUpdateMetadataCmd returns a self-chaining Cmd that sleeps 500ms, then performs
// expensive metadata I/O (tmux capture, git diff) in parallel background goroutines.
// Because it only re-schedules after completing, overlapping ticks are impossible.
func tickUpdateMetadataCmd(instances []*session.Instance) tea.Cmd {
return func() tea.Msg {
time.Sleep(500 * time.Millisecond)
var active []*session.Instance
for _, inst := range instances {
if inst.Started() && !inst.Paused() {
active = append(active, inst)
}
}
if len(active) == 0 {
return metadataUpdateDoneMsg{}
}
results := make([]instanceMetaResult, len(active))
var wg sync.WaitGroup
for idx, inst := range active {
wg.Add(1)
go func(i int, instance *session.Instance) {
defer wg.Done()
r := &results[i]
r.instance = instance
r.updated, r.hasPrompt = instance.HasUpdated()
r.diffStats = instance.ComputeDiff()
}(idx, inst)
}
wg.Wait()
return metadataUpdateDoneMsg{results: results}
}
}
// handleError handles all errors which get bubbled up to the app. sets the error message. We return a callback tea.Cmd that returns a hideErrMsg message
// which clears the error message after 3 seconds.
func (m *home) handleError(err error) tea.Cmd {
log.ErrorLog.Printf("%v", err)
m.errBox.SetError(err)
return func() tea.Msg {
select {
case <-m.ctx.Done():
case <-time.After(3 * time.Second):
}
return hideErrMsg{}
}
}
// confirmAction shows a confirmation modal and stores the action to execute on confirm
func (m *home) confirmAction(message string, action tea.Cmd) tea.Cmd {
m.state = stateConfirm
// Create and show the confirmation overlay using ConfirmationOverlay
m.confirmationOverlay = overlay.NewConfirmationOverlay(message)
// Set a fixed width for consistent appearance
m.confirmationOverlay.SetWidth(50)
// Set callbacks for confirmation and cancellation
m.confirmationOverlay.OnConfirm = func() {
m.state = stateDefault
// Execute the action if it exists
if action != nil {
_ = action()
}
}
m.confirmationOverlay.OnCancel = func() {
m.state = stateDefault
}
return nil
}
func (m *home) View() string {
listWithPadding := lipgloss.NewStyle().PaddingTop(1).Render(m.list.String())
previewWithPadding := lipgloss.NewStyle().PaddingTop(1).Render(m.tabbedWindow.String())
listAndPreview := lipgloss.JoinHorizontal(lipgloss.Top, listWithPadding, previewWithPadding)
mainView := lipgloss.JoinVertical(
lipgloss.Center,
listAndPreview,
m.menu.String(),
m.errBox.String(),
)
if m.state == statePrompt {
if m.textInputOverlay == nil {
log.ErrorLog.Printf("text input overlay is nil")
}
return overlay.PlaceOverlay(0, 0, m.textInputOverlay.Render(), mainView, true, true)
} else if m.state == stateHelp {
if m.textOverlay == nil {
log.ErrorLog.Printf("text overlay is nil")
}
return overlay.PlaceOverlay(0, 0, m.textOverlay.Render(), mainView, true, true)
} else if m.state == stateConfirm {
if m.confirmationOverlay == nil {
log.ErrorLog.Printf("confirmation overlay is nil")
}
return overlay.PlaceOverlay(0, 0, m.confirmationOverlay.Render(), mainView, true, true)
}
return mainView
}