Repository navigation
Expand file tree
/
Copy pathapp.go
More file actions
1047 lines (914 loc) · 29 KB
/
Copy pathapp.go
File metadata and controls
1047 lines (914 loc) · 29 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 (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
goruntime "runtime"
"runtime/debug"
"strings"
"sync"
"time"
"prochub/internal/config"
"prochub/internal/control"
"prochub/internal/logging"
"prochub/internal/platform"
"prochub/internal/process"
"prochub/internal/service"
"prochub/internal/store"
"github.com/google/uuid"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
const (
AppName = "prochub"
AppDisplayName = "ProcHub"
)
// App struct
type App struct {
ctx context.Context
pm *process.Manager
store *store.Store
config config.AppConfig
logHub *logging.StreamHub
loggers map[string]*ProcessLogger
autoStartMgr *service.AutoStartManager
wslMgr *service.WSLManager
controlServer *control.Server
systemLogger *logging.RollingStore
wailsLogger *logging.WailsLogger
dataDir string
// configMu serializes configuration writes. Reads and writes can originate
// from the GUI, the CLI control server and the tray at the same time, so
// every read-modify-write sequence must hold this lock to avoid lost
// updates when two callers patch different fields concurrently.
configMu sync.Mutex
// processMu serializes process definition writes for the same reason.
processMu sync.Mutex
}
// ProcessLogger holds the logger for a specific process
type ProcessLogger struct {
store *logging.RollingStore
hub *logging.StreamHub
}
// NewApp creates a new App application struct
func NewApp() *App {
dataDir := platform.MustDataDir()
return &App{
dataDir: dataDir,
pm: process.NewManager(),
store: store.NewStore(dataDir),
logHub: logging.NewStreamHub(100),
loggers: make(map[string]*ProcessLogger),
autoStartMgr: service.NewAutoStartManager(AppName, AppDisplayName),
wslMgr: service.NewWSLManager(),
wailsLogger: logging.NewWailsLogger(),
}
}
// GetLocale returns the current app locale, implementing platform.AppRef
func (a *App) GetLocale() string {
defer a.recoverPanic("GetLocale")
return a.config.Locale
}
// GetCtx returns the Wails context, implementing platform.AppRef
func (a *App) GetCtx() context.Context {
defer a.recoverPanic("GetCtx")
return a.ctx
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
// Load configuration
cfg, err := a.store.Load()
if err != nil {
cfg = config.DefaultConfig()
// Initialize system logger first before logging errors
a.systemLogger = logging.NewSystemLogger(a.dataDir)
a.LogSystemError("startup", fmt.Sprintf("Failed to load config, using default: %v", err))
}
a.config = cfg
// Initialize log directory
if a.config.LogDir == "" {
a.config.LogDir = "logs"
}
logDir := filepath.Join(a.dataDir, a.config.LogDir)
os.MkdirAll(logDir, 0755)
// Initialize system logger
a.systemLogger = logging.NewSystemLogger(a.dataDir)
// Route the Wails framework logger into the same system log file.
if a.wailsLogger != nil {
a.wailsLogger.SetSink(func(level, message string) {
a.LogSystemError("wails."+level, message)
})
}
// Set up log callback for process manager
a.pm.SetLogCallback(func(processID, stream, line string) {
logger, ok := a.loggers[processID]
if !ok {
return
}
entry := logging.Entry{
Timestamp: time.Now(),
Stream: stream,
Line: line,
}
// Store in memory hub
logger.hub.Push(entry)
// Store in rolling file
logger.store.Append(entry)
})
// Register saved processes
for _, def := range a.config.Processes {
a.pm.Register(def)
// Create logger for this process
processLogDir := filepath.Join(logDir, def.ID)
a.loggers[def.ID] = &ProcessLogger{
store: logging.NewRollingStore(processLogDir, a.config.MaxLogLines, a.config.MaxLogFiles),
hub: logging.NewStreamHub(100),
}
// Auto-start processes if configured
if def.AutoStart {
go a.pm.Start(ctx, def.ID)
}
}
// Start the local control server used by the CLI.
a.startControlServer()
// Boot WSL on start-up when the independent WSL auto-start option is enabled.
if a.config.AutoStartWSL {
go a.startWSLOnBoot()
}
// Log successful startup
a.LogSystemError("startup", fmt.Sprintf("Application started successfully, version: %s, platform: %s", appConfig.Version, a.autoStartMgr.GetPlatform()))
// Start automation test HTTP server (no-op without autotest build tag)
startAutotestServer(ctx, a)
}
// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
defer a.recoverPanic("Greet")
return fmt.Sprintf("Hello %s, It's show time!", name)
}
// AddProcess registers a new process
func (a *App) AddProcess(def process.Definition) error {
defer a.recoverPanic("AddProcess")
a.processMu.Lock()
defer a.processMu.Unlock()
// Generate ID if not provided
if def.ID == "" {
def.ID = fmt.Sprintf("proc-%d", len(a.config.Processes)+1)
}
// Set default restart policy if not provided
if def.RestartPolicy == "" {
def.RestartPolicy = process.RestartOnFailure
}
// Register with process manager
a.pm.Register(def)
// Create logger for this process
logDir := filepath.Join(a.dataDir, a.config.LogDir, def.ID)
a.loggers[def.ID] = &ProcessLogger{
store: logging.NewRollingStore(logDir, a.config.MaxLogLines, a.config.MaxLogFiles),
hub: logging.NewStreamHub(100),
}
// Add to config and persist through the single write path so the change is
// broadcast to the frontend.
cfg := a.config
cfg.Processes = append(cfg.Processes, def)
if err := a.applyConfig(cfg, originGUI); err != nil {
a.LogSystemError("AddProcess", fmt.Sprintf("Failed to save config after adding process %s: %v", def.Name, err))
return err
}
a.notifyProcessesChanged()
return nil
}
// RemoveProcess removes a process by ID
func (a *App) RemoveProcess(id string) error {
defer a.recoverPanic("RemoveProcess")
// Stop the process first
err := a.pm.Stop(id)
if err != nil {
a.LogSystemError("RemoveProcess", fmt.Sprintf("Failed to stop process %s: %v", id, err))
}
// Unregister from process manager
a.pm.Unregister(id)
// Remove from config (lock only the read-modify-write of the config)
a.processMu.Lock()
cfg := a.config
newProcesses := make([]process.Definition, 0, len(cfg.Processes))
for _, p := range cfg.Processes {
if p.ID != id {
newProcesses = append(newProcesses, p)
}
}
cfg.Processes = newProcesses
// Remove logger
delete(a.loggers, id)
a.processMu.Unlock()
if err := a.applyConfig(cfg, originGUI); err != nil {
a.LogSystemError("RemoveProcess", fmt.Sprintf("Failed to save config after removing process %s: %v", id, err))
return err
}
a.notifyProcessesChanged()
return nil
}
// UpdateProcess updates a process configuration
func (a *App) UpdateProcess(id string, def process.Definition) error {
defer a.recoverPanic("UpdateProcess")
// Stop the process first (kept outside the lock: it can block for seconds)
err := a.pm.Stop(id)
if err != nil {
a.LogSystemError("UpdateProcess", fmt.Sprintf("Failed to stop process %s: %v", id, err))
}
// Update in config
a.processMu.Lock()
cfg := a.config
for i, p := range cfg.Processes {
if p.ID == id {
def.ID = id // Preserve the ID
cfg.Processes[i] = def
break
}
}
a.processMu.Unlock()
// Re-register with process manager
a.pm.Register(def)
if err := a.applyConfig(cfg, originGUI); err != nil {
a.LogSystemError("UpdateProcess", fmt.Sprintf("Failed to save config after updating process %s: %v", id, err))
return err
}
a.notifyProcessesChanged()
return nil
}
// SetProcessAutoStart toggles the auto-start flag of a process without
// stopping or restarting the process if it is currently running.
func (a *App) SetProcessAutoStart(id string, enabled bool) error {
defer a.recoverPanic("SetProcessAutoStart")
a.processMu.Lock()
cfg := a.config
found := false
for i, p := range cfg.Processes {
if p.ID == id {
p.AutoStart = enabled
cfg.Processes[i] = p
found = true
break
}
}
a.processMu.Unlock()
if !found {
return fmt.Errorf("process %s not found", id)
}
if err := a.pm.SetAutoStart(id, enabled); err != nil {
a.LogSystemError("SetProcessAutoStart", fmt.Sprintf("Failed to update auto-start flag for process %s: %v", id, err))
return err
}
if err := a.applyConfig(cfg, originGUI); err != nil {
a.LogSystemError("SetProcessAutoStart", fmt.Sprintf("Failed to save config after updating auto-start for process %s: %v", id, err))
return err
}
a.notifyProcessesChanged()
return nil
}
// StartProcess starts a process by ID
func (a *App) StartProcess(id string) error {
defer a.recoverPanic("StartProcess")
err := a.pm.Start(a.ctx, id)
if err != nil {
a.LogSystemError("StartProcess", fmt.Sprintf("Failed to start process %s: %v", id, err))
}
// The status change happens asynchronously; let the frontend re-read it.
a.notifyProcessesChanged()
return err
}
// StopProcess stops a process by ID
func (a *App) StopProcess(id string) error {
defer a.recoverPanic("StopProcess")
err := a.pm.Stop(id)
if err != nil {
a.LogSystemError("StopProcess", fmt.Sprintf("Failed to stop process %s: %v", id, err))
}
a.notifyProcessesChanged()
return err
}
// RestartProcess restarts a process by ID
func (a *App) RestartProcess(id string) error {
defer a.recoverPanic("RestartProcess")
if err := a.pm.Stop(id); err != nil {
a.LogSystemError("RestartProcess", fmt.Sprintf("Failed to stop process %s during restart: %v", id, err))
return err
}
err := a.pm.Start(a.ctx, id)
if err != nil {
a.LogSystemError("RestartProcess", fmt.Sprintf("Failed to start process %s during restart: %v", id, err))
}
a.notifyProcessesChanged()
return err
}
// notifyProcessesChanged tells the frontend that the process list or the state
// of some process changed, so it can re-read the list from the backend.
func (a *App) notifyProcessesChanged() {
a.emit("processes:changed", map[string]interface{}{})
}
// ListProcesses returns all processes with their status
func (a *App) ListProcesses() []process.Snapshot {
defer a.recoverPanic("ListProcesses")
return a.pm.List()
}
// GetProcessLogs returns logs for a specific process
func (a *App) GetProcessLogs(id string) []logging.Entry {
defer a.recoverPanic("GetProcessLogs")
logger, ok := a.loggers[id]
if !ok {
return []logging.Entry{}
}
return logger.hub.Snapshot()
}
// GetConfig returns the current configuration
func (a *App) GetConfig() config.AppConfig {
defer a.recoverPanic("GetConfig")
return a.config
}
// UpdateConfig updates the configuration
func (a *App) UpdateConfig(cfg config.AppConfig) error {
defer a.recoverPanic("UpdateConfig")
return a.applyConfig(cfg, originGUI)
}
// SelectDirectory opens a directory selection dialog
func (a *App) SelectDirectory() (string, error) {
defer a.recoverPanic("SelectDirectory")
dir, err := runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select Working Directory",
})
if err != nil {
return "", err
}
return dir, nil
}
// DataDirInfo describes the effective data directory resolved at runtime.
type DataDirInfo struct {
// Path is the absolute directory where app data is stored.
Path string `json:"path"`
// IsDefault is true when Path is the built-in default (~/.prochub/data).
IsDefault bool `json:"isDefault"`
}
// GetDataDirInfo returns the effective data directory and whether it is the
// built-in default, so the UI can warn about a custom location.
func (a *App) GetDataDirInfo() DataDirInfo {
defer a.recoverPanic("GetDataDirInfo")
return DataDirInfo{
Path: a.dataDir,
IsDefault: platform.IsDefaultDataDir(),
}
}
// OpenDataDir opens the effective data directory in the system file manager.
func (a *App) OpenDataDir() error {
defer a.recoverPanic("OpenDataDir")
return platform.RevealPath(a.dataDir)
}
// SelectFile opens a file selection dialog for selecting executable/command
func (a *App) SelectFile() (string, error) {
defer a.recoverPanic("SelectFile")
file, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select Command/Executable",
})
if err != nil {
return "", err
}
return file, nil
}
// GetAutoStartEnabled returns whether auto-start is enabled
func (a *App) GetAutoStartEnabled() (bool, error) {
defer a.recoverPanic("GetAutoStartEnabled")
return a.autoStartMgr.IsEnabled()
}
// SetAutoStartEnabled enables or disables auto-start
func (a *App) SetAutoStartEnabled(enabled bool) error {
defer a.recoverPanic("SetAutoStartEnabled")
return a.patchConfig(func(cfg *config.AppConfig) { cfg.AutoStart = enabled }, originGUI)
}
// GetAutoStartWSLEnabled returns whether WSL should start together with the app.
func (a *App) GetAutoStartWSLEnabled() bool {
defer a.recoverPanic("GetAutoStartWSLEnabled")
return a.config.AutoStartWSL
}
// SetAutoStartWSLEnabled enables or disables starting WSL when the app boots.
// It is an independent setting: it does not require the application auto-start
// option to be enabled, and it does not block manual start/stop.
func (a *App) SetAutoStartWSLEnabled(enabled bool) error {
defer a.recoverPanic("SetAutoStartWSLEnabled")
return a.patchConfig(func(cfg *config.AppConfig) { cfg.AutoStartWSL = enabled }, originGUI)
}
// GetWSLStatus returns the current WSL runtime status.
func (a *App) GetWSLStatus() service.WSLStatus {
defer a.recoverPanic("GetWSLStatus")
return a.wslMgr.Status()
}
// StartWSL boots the default WSL distribution.
func (a *App) StartWSL() error {
defer a.recoverPanic("StartWSL")
if err := a.wslMgr.Start(); err != nil {
a.LogSystemError("StartWSL", fmt.Sprintf("Failed to start WSL: %v", err))
return err
}
return nil
}
// StopWSL shuts down the whole WSL subsystem.
func (a *App) StopWSL() error {
defer a.recoverPanic("StopWSL")
if err := a.wslMgr.Stop(); err != nil {
a.LogSystemError("StopWSL", fmt.Sprintf("Failed to stop WSL: %v", err))
return err
}
return nil
}
// RestartWSL shuts down and boots the WSL subsystem again.
func (a *App) RestartWSL() error {
defer a.recoverPanic("RestartWSL")
if err := a.wslMgr.Restart(); err != nil {
a.LogSystemError("RestartWSL", fmt.Sprintf("Failed to restart WSL: %v", err))
return err
}
return nil
}
// startWSLOnBoot boots WSL when the WSL auto-start option is enabled. The
// option is independent from the application auto-start option.
func (a *App) startWSLOnBoot() {
if a.wslMgr == nil {
return
}
if err := a.wslMgr.Start(); err != nil {
a.LogSystemError("wsl", fmt.Sprintf("Failed to auto-start WSL: %v", err))
return
}
a.LogSystemError("wsl", "WSL started automatically on boot")
}
// GetPlatform returns the current operating system
func (a *App) GetPlatform() string {
defer a.recoverPanic("GetPlatform")
return a.autoStartMgr.GetPlatform()
}
// GetAppName returns the application display name
func (a *App) GetAppName() string {
defer a.recoverPanic("GetAppName")
return AppDisplayName
}
// GetAppVersion returns the current app version
func (a *App) GetAppVersion() string {
defer a.recoverPanic("GetAppVersion")
return appConfig.Version
}
// GetSystemVersion returns detailed system version information
func (a *App) GetSystemVersion() map[string]string {
defer a.recoverPanic("GetSystemVersion")
info := make(map[string]string)
info["os"] = goruntime.GOOS
info["arch"] = goruntime.GOARCH
info["platform"] = a.autoStartMgr.GetPlatform()
// Get OS version based on platform
var cmd *exec.Cmd
switch goruntime.GOOS {
case "darwin":
cmd = exec.Command("sw_vers", "-productVersion")
case "linux":
cmd = exec.Command("lsb_release", "-ds")
// Fallback to /etc/os-release if lsb_release not available
if _, err := exec.LookPath("lsb_release"); err != nil {
cmd = exec.Command("sh", "-c", "cat /etc/os-release | grep PRETTY_NAME | cut -d'=' -f2 | tr -d '\"'")
}
case "windows":
cmd = exec.Command("cmd", "/c", "ver")
}
if cmd != nil {
if output, err := cmd.Output(); err == nil {
info["osVersion"] = strings.TrimSpace(platform.DecodeOutput(output))
} else {
info["osVersion"] = "unknown"
}
}
// Get hostname
if hostname, err := os.Hostname(); err == nil {
info["hostname"] = hostname
}
info["goVersion"] = goruntime.Version()
info["numCPU"] = fmt.Sprintf("%d", goruntime.NumCPU())
return info
}
// LogSystemError logs system errors to the system log file
func (a *App) LogSystemError(component, message string) {
if a.systemLogger == nil {
return
}
entry := logging.Entry{
Timestamp: time.Now(),
Stream: component,
Line: message,
}
a.systemLogger.Append(entry)
}
// LogFrontendError writes a renderer-side event or error to the system log. It
// is the local counterpart of the remote analytics report, so renderer errors
// are still recorded when offline or when the analytics endpoint is down.
func (a *App) LogFrontendError(level string, label string, data map[string]interface{}) {
defer a.recoverPanic("LogFrontendError")
if a.systemLogger == nil {
return
}
if level != "error" {
level = "info"
}
line := label
if len(data) > 0 {
if raw, err := json.Marshal(data); err == nil {
line = label + " " + string(raw)
}
}
a.systemLogger.Append(logging.Entry{
Timestamp: time.Now(),
Stream: "renderer." + level,
Line: line,
})
}
// recoverPanic logs the panic that aborted a bound method call (with its stack)
// to the system log, then re-panics so the Wails dispatcher still turns the
// call into a rejected promise for the frontend instead of a silent success.
// It is meant to be used as `defer a.recoverPanic("MethodName")`.
func (a *App) recoverPanic(name string) {
if r := recover(); r != nil {
a.LogSystemError("panic", fmt.Sprintf("%s panicked: %v\n%s", name, r, debug.Stack()))
panic(r)
}
}
// GetSystemLogs returns system logs from the last 24 hours
func (a *App) GetSystemLogs() (string, error) {
defer a.recoverPanic("GetSystemLogs")
var logs strings.Builder
// Collect application system logs
dataDir := a.dataDir
if dataDir == "" {
dataDir = platform.MustDataDir()
}
systemLogDir := logging.SystemLogDir(dataDir)
logs.WriteString("=== Application System Logs ===\n")
if entries, err := os.ReadDir(systemLogDir); err == nil {
now := time.Now()
yesterday := now.Add(-24 * time.Hour)
totalSize := 0
maxSize := 500 * 1024 // Limit to 500KB of logs
for _, entry := range entries {
if entry.IsDir() {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
// Only include logs from last 24 hours
if info.ModTime().After(yesterday) {
filePath := filepath.Join(systemLogDir, entry.Name())
content, err := os.ReadFile(filePath)
if err == nil {
if totalSize+len(content) > maxSize {
logs.WriteString(fmt.Sprintf("\n... (remaining logs truncated, limit %dKB reached)\n", maxSize/1024))
break
}
logs.WriteString(fmt.Sprintf("\n--- %s ---\n", entry.Name()))
logs.Write(content)
logs.WriteString("\n")
totalSize += len(content)
}
}
}
if totalSize == 0 {
logs.WriteString("No system logs found in the last 24 hours\n")
}
} else {
logs.WriteString(fmt.Sprintf("Unable to read system logs directory: %v\n", err))
}
return logs.String(), nil
}
// GetAppConfig returns application configuration
func (a *App) GetAppConfig() map[string]interface{} {
defer a.recoverPanic("GetAppConfig")
return map[string]interface{}{
"name": appConfig.Name,
"title": appConfig.Title,
"slogan": appConfig.Slogan,
"version": appConfig.Version,
"website": appConfig.Website,
"websiteGithub": appConfig.WebsiteGithub,
"websiteGitee": appConfig.WebsiteGitee,
"apiBaseUrl": appConfig.ApiBaseUrl,
"analyticsUrl": appConfig.AnalyticsUrl,
"versionCheckUrl": appConfig.VersionCheckUrl,
"feedbackUrl": appConfig.FeedbackUrl,
"guideUrl": appConfig.GuideUrl,
"helpUrl": appConfig.HelpUrl,
}
}
// GetProcess returns a single process by ID
func (a *App) GetProcess(id string) (process.Snapshot, error) {
defer a.recoverPanic("GetProcess")
return a.pm.Get(id)
}
// AnalyticsEvent represents an analytics event to be sent
type AnalyticsEvent struct {
Name string `json:"name"`
Data map[string]interface{} `json:"data,omitempty"`
}
// AnalyticsPayload is the request body format for analytics
type AnalyticsPayload struct {
Data []AnalyticsEvent `json:"data"`
}
const baseURL = "https://open.tecmz.com/open_app/ProcHub"
// AppConfig holds application-wide configuration
var appConfig = struct {
Name string
Title string
Slogan string
Version string
Website string
WebsiteGithub string
WebsiteGitee string
ApiBaseUrl string
AnalyticsUrl string
VersionCheckUrl string
FeedbackUrl string
GuideUrl string
HelpUrl string
}{
Name: "ProcHub",
Title: "ProcHub",
Slogan: "Manage processes easily",
Version: "0.7.0",
Website: baseURL,
WebsiteGithub: "https://github.com/modstart-lib/prochub",
WebsiteGitee: "https://gitee.com/modstart-lib/prochub",
ApiBaseUrl: baseURL + "/api",
AnalyticsUrl: baseURL + "/app_manager/collect",
VersionCheckUrl: baseURL + "/app_manager/updater",
FeedbackUrl: baseURL + "/feedback_ticket",
GuideUrl: baseURL + "/app_manager/guide",
HelpUrl: baseURL + "/app_manager/help",
}
// getDeviceUUID returns a persistent UUID for this device
func (a *App) getDeviceUUID() string {
// Try to load existing UUID from config
if a.config.DeviceUUID != "" {
return a.config.DeviceUUID
}
// Generate new UUID
newUUID := uuid.New().String()
a.config.DeviceUUID = newUUID
// Persist through the single write path.
_ = a.applyConfig(a.config, originGUI)
return newUUID
}
// getPlatform returns the current platform name
func getPlatform() string {
switch goruntime.GOOS {
case "darwin":
return "mac"
case "windows":
return "win"
case "linux":
return "linux"
default:
return goruntime.GOOS
}
}
// getPlatformArch returns the current platform architecture
func getPlatformArch() string {
switch goruntime.GOARCH {
case "amd64":
return "x64"
case "arm64":
return "arm64"
case "386":
return "x86"
default:
return goruntime.GOARCH
}
}
// getPlatformVersion returns the OS version
func getPlatformVersion() string {
switch goruntime.GOOS {
case "darwin":
// macOS: use sw_vers command
out, err := exec.Command("sw_vers", "-productVersion").Output()
if err == nil {
return strings.TrimSpace(string(out))
}
case "windows":
// Windows: use cmd /c ver
out, err := exec.Command("cmd", "/c", "ver").Output()
if err == nil {
// Parse "Microsoft Windows [Version 10.0.19041.1234]"
s := platform.DecodeOutput(out)
if start := strings.Index(s, "[Version "); start != -1 {
s = s[start+9:]
if end := strings.Index(s, "]"); end != -1 {
return strings.TrimSpace(s[:end])
}
}
}
case "linux":
// Linux: try /etc/os-release
data, err := os.ReadFile("/etc/os-release")
if err == nil {
for _, line := range strings.Split(string(data), "\n") {
if strings.HasPrefix(line, "VERSION_ID=") {
v := strings.TrimPrefix(line, "VERSION_ID=")
return strings.Trim(v, "\"")
}
}
}
}
return "0"
}
// SendAnalytics sends analytics events to the collection endpoint
func (a *App) SendAnalytics(events []AnalyticsEvent) {
defer a.recoverPanic("SendAnalytics")
go func() {
client := &http.Client{Timeout: 10 * time.Second}
// Build User-Agent: AppOpen/{AppName}/{Version} Platform/{PlatformName}/{PlatformArch}/{PlatformVersion}/{UUID}
userAgent := fmt.Sprintf("AppOpen/%s/%s Platform/%s/%s/%s/%s",
appConfig.Name,
appConfig.Version,
getPlatform(),
getPlatformArch(),
getPlatformVersion(),
a.getDeviceUUID(),
)
// Build form data
formData := map[string]interface{}{
"uuid": a.getDeviceUUID(),
"version": appConfig.Version,
"data": events,
"platform": map[string]string{
"name": getPlatform(),
"arch": getPlatformArch(),
"version": getPlatformVersion(),
},
}
jsonData, err := json.Marshal(formData)
if err != nil {
fmt.Printf("[Analytics] Failed to marshal payload: %v\n", err)
return
}
req, err := http.NewRequest("POST", appConfig.AnalyticsUrl, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("[Analytics] Failed to create request: %v\n", err)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", userAgent)
resp, err := client.Do(req)
if err != nil {
fmt.Printf("[Analytics] Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
}()
}
// SaveLogsToFile opens a save dialog and saves logs to the selected file
func (a *App) SaveLogsToFile(processName string, content string) error {
defer a.recoverPanic("SaveLogsToFile")
filePath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Save Logs",
DefaultFilename: fmt.Sprintf("%s-logs.txt", processName),
Filters: []runtime.FileFilter{
{DisplayName: "Text Files", Pattern: "*.txt"},
{DisplayName: "All Files", Pattern: "*.*"},
},
})
if err != nil {
return err
}
if filePath == "" {
return nil // User cancelled
}
return os.WriteFile(filePath, []byte(content), 0644)
}
// ShowWindow shows the main window (used by the frontend)
func (a *App) ShowWindow() {
defer a.recoverPanic("ShowWindow")
platform.ShowMainWindow(a.ctx)
}
// HideWindow hides the main window and Dock icon
func (a *App) HideWindow() {
defer a.recoverPanic("HideWindow")
runtime.WindowHide(a.ctx)
// Hide Dock icon on macOS
platform.HideDockIcon()
}
// PrepareQuit marks the application as quitting so the window close handler
// stops preventing the close. Implements platform.AppRef.
func (a *App) PrepareQuit() {
defer a.recoverPanic("PrepareQuit")
SetQuitting(true)
}
// RunningProcessNames returns the names of processes that are still running or
// starting. Implements platform.AppRef.
func (a *App) RunningProcessNames() []string {
defer a.recoverPanic("RunningProcessNames")
return a.pm.RunningNames()
}
// NotifyQuitBlocked tells the frontend that quitting was blocked because some
// processes are still running. Implements platform.AppRef.
func (a *App) NotifyQuitBlocked(names []string) {
defer a.recoverPanic("NotifyQuitBlocked")
if a.ctx == nil {
return
}
runtime.EventsEmit(a.ctx, "app:quitBlocked", map[string]interface{}{
"count": len(names),
"names": names,
})
}
// QuitApp quits the application. Quitting is blocked while any process is still
// running: the window is shown and the frontend displays a warning instead.
func (a *App) QuitApp() {
defer a.recoverPanic("QuitApp")
if names := a.pm.RunningNames(); len(names) > 0 {
platform.ShowMainWindow(a.ctx)
a.NotifyQuitBlocked(names)
return
}
SetQuitting(true)
runtime.Quit(a.ctx)
}
// VersionInfo represents version information from the server
type VersionInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Time string `json:"time"`
Url string `json:"url,omitempty"`
}
// versionCheckResponse is the API response format
type versionCheckResponse struct {
Code int `json:"code"`
Data VersionInfo `json:"data"`
}
// CheckVersion checks for new version from the server
func (a *App) CheckVersion() (VersionInfo, error) {
defer a.recoverPanic("CheckVersion")
client := &http.Client{Timeout: 10 * time.Second}
// Build User-Agent: AppOpen/{AppName}/{Version} Platform/{PlatformName}/{PlatformArch}/{PlatformVersion}/{UUID}
userAgent := fmt.Sprintf("AppOpen/%s/%s Platform/%s/%s/%s/%s",
appConfig.Name,
appConfig.Version,
getPlatform(),
getPlatformArch(),
getPlatformVersion(),
a.getDeviceUUID(),
)
// Build form data
formData := map[string]interface{}{
"uuid": a.getDeviceUUID(),
"version": appConfig.Version,
"platform": map[string]string{
"name": getPlatform(),
"arch": getPlatformArch(),
"version": getPlatformVersion(),
},
}
jsonData, err := json.Marshal(formData)
if err != nil {