-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1773 lines (1536 loc) · 40.6 KB
/
main.go
File metadata and controls
1773 lines (1536 loc) · 40.6 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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
)
type ViewMode int
const (
ViewByService ViewMode = iota
ViewByNode
)
// Styles
var (
serviceStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("12"))
nodeStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("13"))
taskRunningStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("10"))
taskReadyStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("214"))
taskStartingStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("11"))
taskFailedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
taskOtherStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("8"))
selectedStyle = lipgloss.NewStyle().Background(lipgloss.Color("237"))
errorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Italic(true)
dimStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("8"))
)
// TreeNode represents a node in the tree view
type TreeNode struct {
Name string
IsParent bool // Service in service view, Node in node view
ServiceID string
TaskID string
ContainerID string
State string
Error string
Replicas string
Image string
Slot int
NodeID string
NodeName string
ServiceName string
Children []*TreeNode
}
// Model is the Bubble Tea model
type Model struct {
nodes []*TreeNode
flatList []flatNode
cursor int
offset int // Scroll offset
height int // Terminal height
width int // Terminal width
err error
loading bool
viewMode ViewMode
lastKey string // For vim-style gg command
// Logs panel
logs []string // Log lines
logsOffset int // Scroll offset for logs
logsLoading bool
lastSelectedID string // Track which task we're showing logs for
// Fullscreen logs mode
fullscreenLogs bool
logsLastKey string // For vim-style gg in logs view
// Line wrapping in logs panel
lineWrap bool
// Auto-refresh
autoRefresh bool
lastLogTime time.Time // Track last log timestamp for incremental fetching
lastDataRefresh time.Time // Track last data refresh
}
// Global socket override (set via -s/--socket flag)
var socketOverride string
type flatNode struct {
node *TreeNode
depth int
isLast bool
}
// Messages
type dataLoadedMsg struct {
nodes []*TreeNode
err error
}
type dataLoadedSilentMsg struct {
nodes []*TreeNode
err error
}
type logsLoadedMsg struct {
taskID string
lines []string
err error
}
type logsAppendedMsg struct {
taskID string
lines []string
err error
}
type tickMsg time.Time
const (
tickInterval = 500 * time.Millisecond
fullscreenLogRefreshDelay = 500 * time.Millisecond
normalLogRefreshDelay = 1 * time.Second
dataRefreshInterval = 2 * time.Second
)
// Docker config structures
type dockerConfig struct {
CurrentContext string `json:"currentContext"`
}
type contextMeta struct {
Name string `json:"Name"`
Endpoints map[string]contextEndpoint `json:"Endpoints"`
}
type contextEndpoint struct {
Host string `json:"Host"`
SkipTLSVerify bool `json:"SkipTLSVerify"`
}
func main() {
// Parse arguments
args := os.Args[1:]
viewMode := ViewByService
var remainingArgs []string
// Parse flags
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "-h" || arg == "--help" || arg == "help" {
printHelp()
return
}
if arg == "-s" || arg == "--socket" {
if i+1 >= len(args) {
fmt.Fprintf(os.Stderr, "Error: %s requires a socket path argument\n", arg)
os.Exit(1)
}
socketOverride = args[i+1]
i++ // Skip next arg (the socket path)
continue
}
// Handle -s=value or --socket=value
if strings.HasPrefix(arg, "-s=") {
socketOverride = strings.TrimPrefix(arg, "-s=")
continue
}
if strings.HasPrefix(arg, "--socket=") {
socketOverride = strings.TrimPrefix(arg, "--socket=")
continue
}
remainingArgs = append(remainingArgs, arg)
}
// Check for subcommand
if len(remainingArgs) > 0 {
switch remainingArgs[0] {
case "nodes":
viewMode = ViewByNode
default:
fmt.Fprintf(os.Stderr, "Unknown command: %s\n", remainingArgs[0])
printHelp()
os.Exit(1)
}
}
p := tea.NewProgram(initialModel(viewMode), tea.WithAltScreen())
_, err := p.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func printHelp() {
fmt.Println(`d - Docker Swarm service viewer
USAGE:
d [OPTIONS] [COMMAND]
COMMANDS:
(none) Show services with their tasks (default)
nodes Show nodes with their tasks
OPTIONS:
-s, --socket PATH Override Docker socket path (e.g. /var/run/docker.sock)
-h, --help Show this help message
KEYBINDINGS:
j, ↓ Move cursor down
k, ↑ Move cursor up
gg Jump to top
G Jump to bottom
yy Copy all logs to clipboard (wl-copy)
Enter Fullscreen logs (j/k:scroll gg/G:jump q/esc:exit)
n Toggle between services/nodes view
a Toggle auto-refresh (data:2s, logs:1s, fullscreen logs:500ms)
r Refresh
q, Ctrl+C Quit
DESCRIPTION:
Shows Docker Swarm services/tasks in a split view.
Left panel: tree view of services/tasks
Right panel: logs for the selected task (auto-updates on selection)
Default view groups tasks by service.
'nodes' command groups tasks by swarm node.
Respects Docker context (set via 'docker context use').`)
}
func initialModel(viewMode ViewMode) Model {
return Model{
loading: true,
viewMode: viewMode,
autoRefresh: true,
}
}
func (m Model) Init() tea.Cmd {
if m.autoRefresh {
return tea.Batch(m.loadData(), tickCmd())
}
return m.loadData()
}
func (m Model) loadData() tea.Cmd {
return func() tea.Msg {
var nodes []*TreeNode
var err error
if m.viewMode == ViewByNode {
nodes, err = fetchByNode()
} else {
nodes, err = fetchByService()
}
return dataLoadedMsg{nodes: nodes, err: err}
}
}
func tickCmd() tea.Cmd {
return tea.Tick(tickInterval, func(t time.Time) tea.Msg {
return tickMsg(t)
})
}
func copyToClipboard(text string) {
cmd := exec.Command("wl-copy")
cmd.Stdin = strings.NewReader(text)
_ = cmd.Run()
}
// getDockerHost resolves the Docker host from context configuration
func getDockerHost() (string, error) {
// Socket override from -s/--socket flag takes highest priority
if socketOverride != "" {
return "unix://" + socketOverride, nil
}
if host := os.Getenv("DOCKER_HOST"); host != "" {
return host, nil
}
contextName := os.Getenv("DOCKER_CONTEXT")
if contextName == "" {
home, err := os.UserHomeDir()
if err != nil {
return "", nil
}
configPath := filepath.Join(home, ".docker", "config.json")
data, err := os.ReadFile(configPath)
if err != nil {
return "", nil
}
var config dockerConfig
if err := json.Unmarshal(data, &config); err != nil {
return "", nil
}
contextName = config.CurrentContext
}
if contextName == "" || contextName == "default" {
return "", nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get home dir: %w", err)
}
hash := sha256.Sum256([]byte(contextName))
contextDir := hex.EncodeToString(hash[:])
metaPath := filepath.Join(home, ".docker", "contexts", "meta", contextDir, "meta.json")
data, err := os.ReadFile(metaPath)
if err != nil {
return "", fmt.Errorf("failed to read context %q: %w", contextName, err)
}
var meta contextMeta
if err := json.Unmarshal(data, &meta); err != nil {
return "", fmt.Errorf("failed to parse context metadata: %w", err)
}
endpoint, ok := meta.Endpoints["docker"]
if !ok {
return "", fmt.Errorf("no docker endpoint in context %q", contextName)
}
return endpoint.Host, nil
}
func newDockerClient() (*client.Client, error) {
dockerHost, err := getDockerHost()
if err != nil {
return nil, err
}
opts := []client.Opt{client.WithAPIVersionNegotiation()}
if dockerHost != "" {
opts = append(opts, client.WithHost(dockerHost))
} else {
opts = append(opts, client.FromEnv)
}
return client.NewClientWithOpts(opts...)
}
func fetchByService() ([]*TreeNode, error) {
ctx := context.Background()
cli, err := newDockerClient()
if err != nil {
return nil, fmt.Errorf("failed to create docker client: %w", err)
}
defer cli.Close()
info, err := cli.Info(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get docker info: %w", err)
}
if info.Swarm.LocalNodeState != swarm.LocalNodeStateActive {
return nil, fmt.Errorf("this node is not part of a swarm")
}
services, err := cli.ServiceList(ctx, types.ServiceListOptions{})
if err != nil {
return nil, fmt.Errorf("failed to list services: %w", err)
}
tasks, err := cli.TaskList(ctx, types.TaskListOptions{})
if err != nil {
return nil, fmt.Errorf("failed to list tasks: %w", err)
}
nodes, err := cli.NodeList(ctx, types.NodeListOptions{})
if err != nil {
return nil, fmt.Errorf("failed to list nodes: %w", err)
}
nodeMap := make(map[string]string)
for _, n := range nodes {
name := n.Description.Hostname
if name == "" {
name = truncateID(n.ID)
}
nodeMap[n.ID] = name
}
tasksByService := make(map[string][]swarm.Task)
for _, task := range tasks {
tasksByService[task.ServiceID] = append(tasksByService[task.ServiceID], task)
}
var result []*TreeNode
for _, svc := range services {
var replicas string
if svc.Spec.Mode.Replicated != nil {
desired := *svc.Spec.Mode.Replicated.Replicas
running := countRunningTasks(tasksByService[svc.ID])
replicas = fmt.Sprintf("%d/%d", running, desired)
} else if svc.Spec.Mode.Global != nil {
running := countRunningTasks(tasksByService[svc.ID])
replicas = fmt.Sprintf("%d/global", running)
}
image := ""
if svc.Spec.TaskTemplate.ContainerSpec != nil {
image = truncateImage(svc.Spec.TaskTemplate.ContainerSpec.Image)
}
serviceNode := &TreeNode{
Name: svc.Spec.Name,
IsParent: true,
ServiceID: svc.ID,
Replicas: replicas,
Image: image,
}
serviceTasks := tasksByService[svc.ID]
isGlobal := svc.Spec.Mode.Global != nil
sort.Slice(serviceTasks, func(i, j int) bool {
// First, group by slot/node
if isGlobal {
if serviceTasks[i].NodeID != serviceTasks[j].NodeID {
return serviceTasks[i].NodeID < serviceTasks[j].NodeID
}
} else {
if serviceTasks[i].Slot != serviceTasks[j].Slot {
return serviceTasks[i].Slot < serviceTasks[j].Slot
}
}
// Within same slot/node, running tasks come first
iRunning := serviceTasks[i].Status.State == swarm.TaskStateRunning
jRunning := serviceTasks[j].Status.State == swarm.TaskStateRunning
if iRunning != jRunning {
return iRunning
}
// Then by most recent
return serviceTasks[i].CreatedAt.After(serviceTasks[j].CreatedAt)
})
// For each slot/node, show only ONE task:
// - Running task if exists
// - Otherwise the most recent task (already sorted by CreatedAt desc)
seenKeys := make(map[string]bool)
for _, task := range serviceTasks {
var key string
if isGlobal {
key = task.NodeID
} else {
key = fmt.Sprintf("%d", task.Slot)
}
// Skip if we've already added a task for this slot/node
if seenKeys[key] {
continue
}
seenKeys[key] = true
nodeName := nodeMap[task.NodeID]
if nodeName == "" && task.NodeID != "" {
nodeName = truncateID(task.NodeID)
}
containerID := ""
if task.Status.ContainerStatus != nil {
containerID = task.Status.ContainerStatus.ContainerID
}
// For global services, use node name in task name
taskName := fmt.Sprintf("%s.%d", svc.Spec.Name, task.Slot)
if isGlobal {
taskName = fmt.Sprintf("%s.%s", svc.Spec.Name, nodeName)
}
taskNode := &TreeNode{
Name: taskName,
IsParent: false,
ServiceID: svc.ID,
ServiceName: svc.Spec.Name,
TaskID: task.ID,
ContainerID: containerID,
State: string(task.Status.State),
Error: task.Status.Err,
Slot: int(task.Slot),
NodeID: task.NodeID,
NodeName: nodeName,
}
serviceNode.Children = append(serviceNode.Children, taskNode)
}
result = append(result, serviceNode)
}
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result, nil
}
func fetchByNode() ([]*TreeNode, error) {
ctx := context.Background()
cli, err := newDockerClient()
if err != nil {
return nil, fmt.Errorf("failed to create docker client: %w", err)
}
defer cli.Close()
info, err := cli.Info(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get docker info: %w", err)
}
if info.Swarm.LocalNodeState != swarm.LocalNodeStateActive {
return nil, fmt.Errorf("this node is not part of a swarm")
}
services, err := cli.ServiceList(ctx, types.ServiceListOptions{})
if err != nil {
return nil, fmt.Errorf("failed to list services: %w", err)
}
serviceMap := make(map[string]swarm.Service)
for _, svc := range services {
serviceMap[svc.ID] = svc
}
tasks, err := cli.TaskList(ctx, types.TaskListOptions{})
if err != nil {
return nil, fmt.Errorf("failed to list tasks: %w", err)
}
nodes, err := cli.NodeList(ctx, types.NodeListOptions{})
if err != nil {
return nil, fmt.Errorf("failed to list nodes: %w", err)
}
// Build node info map
type nodeInfo struct {
ID string
Hostname string
State swarm.NodeState
Role swarm.NodeRole
}
nodeInfoMap := make(map[string]nodeInfo)
for _, n := range nodes {
hostname := n.Description.Hostname
if hostname == "" {
hostname = truncateID(n.ID)
}
nodeInfoMap[n.ID] = nodeInfo{
ID: n.ID,
Hostname: hostname,
State: n.Status.State,
Role: n.Spec.Role,
}
}
// Group tasks by node
tasksByNode := make(map[string][]swarm.Task)
for _, task := range tasks {
if task.NodeID != "" {
tasksByNode[task.NodeID] = append(tasksByNode[task.NodeID], task)
}
}
var result []*TreeNode
for _, n := range nodes {
ni := nodeInfoMap[n.ID]
taskCount := len(tasksByNode[n.ID])
runningCount := countRunningTasks(tasksByNode[n.ID])
roleStr := "worker"
if ni.Role == swarm.NodeRoleManager {
roleStr = "manager"
}
swarmNode := &TreeNode{
Name: ni.Hostname,
IsParent: true,
NodeID: n.ID,
NodeName: ni.Hostname,
Replicas: fmt.Sprintf("%d/%d tasks", runningCount, taskCount),
State: string(ni.State),
Image: roleStr,
}
// Filter out tasks whose service no longer exists
nodeTasks := tasksByNode[n.ID]
var validTasks []swarm.Task
for _, task := range nodeTasks {
if _, ok := serviceMap[task.ServiceID]; ok {
validTasks = append(validTasks, task)
}
}
// Sort tasks by service name, slot, then newest first
sort.Slice(validTasks, func(i, j int) bool {
svcI := serviceMap[validTasks[i].ServiceID]
svcJ := serviceMap[validTasks[j].ServiceID]
if svcI.Spec.Name != svcJ.Spec.Name {
return svcI.Spec.Name < svcJ.Spec.Name
}
if validTasks[i].Slot != validTasks[j].Slot {
return validTasks[i].Slot < validTasks[j].Slot
}
return validTasks[i].CreatedAt.After(validTasks[j].CreatedAt)
})
// Filter: show only running task OR most recent task per service+slot
type slotKey struct {
serviceID string
slot int
}
seenSlots := make(map[slotKey]bool)
for _, task := range validTasks {
key := slotKey{task.ServiceID, int(task.Slot)}
if seenSlots[key] {
continue // Already have a task for this slot
}
seenSlots[key] = true
svc := serviceMap[task.ServiceID]
containerID := ""
if task.Status.ContainerStatus != nil {
containerID = task.Status.ContainerStatus.ContainerID
}
image := ""
if svc.Spec.TaskTemplate.ContainerSpec != nil {
image = truncateImage(svc.Spec.TaskTemplate.ContainerSpec.Image)
}
taskNode := &TreeNode{
Name: fmt.Sprintf("%s.%d", svc.Spec.Name, task.Slot),
IsParent: false,
ServiceID: task.ServiceID,
ServiceName: svc.Spec.Name,
TaskID: task.ID,
ContainerID: containerID,
State: string(task.Status.State),
Error: task.Status.Err,
Slot: int(task.Slot),
NodeID: task.NodeID,
NodeName: ni.Hostname,
Image: image,
}
swarmNode.Children = append(swarmNode.Children, taskNode)
}
result = append(result, swarmNode)
}
// Sort nodes by hostname
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result, nil
}
func countRunningTasks(tasks []swarm.Task) int {
count := 0
for _, t := range tasks {
if t.Status.State == swarm.TaskStateRunning {
count++
}
}
return count
}
func truncateID(id string) string {
if len(id) >= 12 {
return id[:12]
}
return id
}
func truncateImage(image string) string {
// Remove @sha256:... digest
if idx := strings.Index(image, "@sha256:"); idx != -1 {
image = image[:idx]
}
// Strip registry path, keep only image name and tag
if idx := strings.LastIndex(image, "/"); idx != -1 {
image = image[idx+1:]
}
if len(image) > 40 {
return image[:37] + "..."
}
return image
}
func (m *Model) buildFlatList() {
m.flatList = nil
for _, node := range m.nodes {
m.flatList = append(m.flatList, flatNode{node: node, depth: 0, isLast: false})
for i, child := range node.Children {
isLast := i == len(node.Children)-1
m.flatList = append(m.flatList, flatNode{node: child, depth: 1, isLast: isLast})
}
}
}
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.height = msg.Height
m.width = msg.Width
m.fixOffset()
return m, nil
case dataLoadedMsg:
m.loading = false
m.err = msg.err
m.nodes = msg.nodes
m.buildFlatList()
m.cursor = 0
m.offset = 0
// Load logs for first selected item
cmd := m.maybeLoadLogs()
return m, cmd
case dataLoadedSilentMsg:
// Silent refresh - update data but preserve cursor position
if msg.err == nil {
oldSelectedID := m.lastSelectedID
oldCursor := m.cursor
m.nodes = msg.nodes
m.buildFlatList()
// Try to preserve cursor position
if oldCursor < len(m.flatList) {
m.cursor = oldCursor
} else if len(m.flatList) > 0 {
m.cursor = len(m.flatList) - 1
}
m.fixOffset()
// Preserve lastSelectedID so we don't trigger a log reload
m.lastSelectedID = oldSelectedID
}
return m, nil
case logsLoadedMsg:
// Only update if this is for the currently selected task
if msg.taskID == m.lastSelectedID {
m.logsLoading = false
if msg.err != nil {
m.logs = []string{fmt.Sprintf("Error: %v", msg.err)}
} else {
m.logs = msg.lines
}
m.lastLogTime = time.Now()
// Start at the bottom of logs (most recent)
m.logsOffset = len(m.logs) - (m.height - 3)
if m.logsOffset < 0 {
m.logsOffset = 0
}
}
return m, nil
case logsAppendedMsg:
// Append new logs if this is for the currently selected task
if msg.taskID == m.lastSelectedID {
if msg.err == nil && len(msg.lines) > 0 {
// Check if we were at the bottom before appending
visibleLines := m.height - 3
if visibleLines < 1 {
visibleLines = 1
}
wasAtBottom := m.logsOffset >= len(m.logs)-visibleLines
m.logs = append(m.logs, msg.lines...)
m.lastLogTime = time.Now()
// Auto-scroll to bottom if we were already there
if wasAtBottom {
m.logsOffset = len(m.logs) - visibleLines
if m.logsOffset < 0 {
m.logsOffset = 0
}
}
}
}
return m, nil
case tickMsg:
if !m.autoRefresh {
return m, nil
}
var cmds []tea.Cmd
cmds = append(cmds, tickCmd()) // Schedule next tick
now := time.Now()
// Refresh data periodically
if now.Sub(m.lastDataRefresh) >= dataRefreshInterval {
m.lastDataRefresh = now
cmds = append(cmds, m.loadDataSilent())
}
// Refresh logs incrementally with different delays for fullscreen vs normal
logDelay := normalLogRefreshDelay
if m.fullscreenLogs {
logDelay = fullscreenLogRefreshDelay
}
if m.lastSelectedID != "" && !m.logsLoading && now.Sub(m.lastLogTime) >= logDelay {
cmds = append(cmds, m.loadLogsIncremental())
}
return m, tea.Batch(cmds...)
case tea.KeyMsg:
// Handle fullscreen logs mode
if m.fullscreenLogs {
return m.handleFullscreenLogsKey(msg)
}
switch msg.String() {
case "q", "ctrl+c":
return m, tea.Quit
case "up", "k":
m.lastKey = ""
if m.cursor > 0 {
m.cursor--
m.fixOffset()
cmd := m.maybeLoadLogs()
return m, cmd
}
return m, nil
case "down", "j":
m.lastKey = ""
if m.cursor < len(m.flatList)-1 {
m.cursor++
m.fixOffset()
cmd := m.maybeLoadLogs()
return m, cmd
}
return m, nil
case "enter":
m.lastKey = ""
// Enter fullscreen logs mode
if len(m.logs) > 0 {
m.fullscreenLogs = true
}
return m, nil
case "g":
if m.lastKey == "g" {
// gg - jump to top of tree
m.cursor = 0
m.offset = 0
m.lastKey = ""
cmd := m.maybeLoadLogs()
return m, cmd
}
m.lastKey = "g"
return m, nil
case "G":
// G - jump to bottom of tree
m.lastKey = ""
if len(m.flatList) > 0 {
m.cursor = len(m.flatList) - 1
m.fixOffset()
cmd := m.maybeLoadLogs()
return m, cmd
}
return m, nil
case "r":
m.lastKey = ""
m.loading = true
return m, m.loadData()
case "a":
m.lastKey = ""
m.autoRefresh = !m.autoRefresh
if m.autoRefresh {
m.lastDataRefresh = time.Now()
m.lastLogTime = time.Now()
return m, tickCmd()
}
return m, nil
case "n":
m.lastKey = ""
// Toggle between service and node view
if m.viewMode == ViewByService {
m.viewMode = ViewByNode
} else {
m.viewMode = ViewByService
}
m.loading = true
m.lastSelectedID = ""
m.logs = nil
return m, m.loadData()
case "W":
m.lastKey = ""
m.lineWrap = !m.lineWrap
return m, nil
case "y":
if m.lastKey == "y" {
// yy - copy all logs to clipboard
m.lastKey = ""
if len(m.logs) > 0 {
copyToClipboard(strings.Join(m.logs, "\n"))
}
return m, nil
}
m.lastKey = "y"
return m, nil
}
}
return m, nil
}
func (m Model) handleFullscreenLogsKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
visibleLines := m.height - 3
if visibleLines < 1 {
visibleLines = 1
}
switch msg.String() {
case "q", "esc":
m.fullscreenLogs = false
m.logsLastKey = ""
return m, nil
case "ctrl+c":
return m, tea.Quit
case "up", "k":
m.logsLastKey = ""
if m.logsOffset > 0 {
m.logsOffset--
}
return m, nil
case "down", "j":
m.logsLastKey = ""
maxOffset := len(m.logs) - visibleLines
if maxOffset < 0 {
maxOffset = 0
}
if m.logsOffset < maxOffset {
m.logsOffset++
}
return m, nil
case "g":
if m.logsLastKey == "g" {
// gg - jump to top of logs
m.logsOffset = 0
m.logsLastKey = ""
return m, nil
}
m.logsLastKey = "g"
return m, nil
case "G":
// G - jump to bottom of logs
m.logsLastKey = ""
maxOffset := len(m.logs) - visibleLines
if maxOffset < 0 {
maxOffset = 0
}
m.logsOffset = maxOffset
return m, nil
case "a":