-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.go
More file actions
2603 lines (2244 loc) · 68.8 KB
/
app.go
File metadata and controls
2603 lines (2244 loc) · 68.8 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 (
"archive/tar"
"archive/zip"
"bufio"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/hackafterdark/context-sherpa/pkg/database"
"github.com/hackafterdark/context-sherpa/pkg/inference"
"github.com/hackafterdark/context-sherpa/pkg/mcp"
"github.com/hackafterdark/context-sherpa/pkg/sysutils"
scip "github.com/sourcegraph/scip/bindings/go/scip"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
"gopkg.in/yaml.v3"
)
// Workspace represents a detected workspace from a Node
type Workspace struct {
PID int `json:"pid"`
Root string `json:"root"`
Client string `json:"client"`
State string `json:"state"`
LastSeen string `json:"lastSeen"`
IsManaged bool `json:"isManaged"`
}
// UserPreferences represents persistent user settings
type UserPreferences struct {
Theme string `json:"theme"`
WindowWidth int `json:"windowWidth"`
WindowHeight int `json:"windowHeight"`
WindowX int `json:"windowX"`
WindowY int `json:"windowY"`
IsMaximized bool `json:"isMaximized"`
InferenceProvider string `json:"inferenceProvider"` // "ollama" or "openai"
InferenceURL string `json:"inferenceURL"`
InferenceModel string `json:"inferenceModel"`
}
// App struct
type App struct {
ctx context.Context
workspaces []Workspace
isHub bool
downloader *inference.Downloader
inference *inference.InferenceService
db *database.DB
localDBs map[string]*database.DB
localDBMu sync.Mutex
}
// MarkdownEntry represents a markdown file with optional front-matter metadata
type MarkdownEntry struct {
Path string `json:"path"`
FrontMatter map[string]string `json:"frontMatter"`
}
// LocalRuleDetails represents the parsed content of a local rule file
type LocalRuleDetails struct {
ID string `json:"id"`
Message string `json:"message"`
Severity string `json:"severity"`
Content string `json:"content"`
Language string `json:"language"`
Path string `json:"path"`
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{
localDBs: make(map[string]*database.DB),
}
}
// startup is called when the app starts.
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
a.workspaces = make([]Workspace, 0)
// Restore window position if not maximized
prefs := a.GetPreferences()
if !prefs.IsMaximized && (prefs.WindowX != 0 || prefs.WindowY != 0) {
wailsRuntime.WindowSetPosition(a.ctx, prefs.WindowX, prefs.WindowY)
}
// Ensure we have a clean start by checking lock liveness
if a.tryAcquireHubLock() {
a.isHub = true
fmt.Println("Hub: Successfully acquired hub.lock. Starting as Master Hub.")
// Initialize Inference services
configDir, _ := getSherpaConfigDir()
modelsDir := filepath.Join(configDir, "models")
a.downloader = inference.NewDownloader(modelsDir)
// Set up provider based on preferences
var provider inference.InferenceProvider
switch prefs.InferenceProvider {
case "ollama":
provider = inference.NewOllamaProvider(prefs.InferenceURL)
case "openai":
provider = inference.NewOpenAIProvider(prefs.InferenceURL)
case "disabled":
// Explicitly disabled
provider = nil
default:
// No provider configured yet or invalid
provider = nil
}
a.inference = inference.NewInferenceService(provider)
// Initialize Hub Database
a.initDatabase()
// Start the Hub's registration server on a background goroutine
go a.startHubServer()
go a.startSweeper()
} else {
fmt.Println("Hub: Another instance is already Master Hub. Starting as Node viewer.")
go a.startViewerPoller()
}
}
func isProcessRunning(pid int) bool {
if pid <= 0 {
return false
}
// platform specific check
if runtime.GOOS == "windows" {
cmd := sysutils.SilentCommand("tasklist", "/FI", fmt.Sprintf("PID eq %d", pid), "/NH")
out, err := cmd.Output()
if err != nil {
return false
}
return strings.Contains(string(out), fmt.Sprintf("%d", pid))
}
p, err := os.FindProcess(pid)
if err != nil {
return false
}
// On Unix, Signal(0) checks for existence
err = p.Signal(syscall.Signal(0))
return err == nil
}
func (a *App) tryAcquireHubLock() bool {
lockPath := mcp.GetHubLockPath()
// 1. Try to read existing lock
if data, err := os.ReadFile(lockPath); err == nil {
var lock mcp.HubLock
if err := json.Unmarshal(data, &lock); err == nil {
// Check if process still exists
if isProcessRunning(lock.PID) {
// Hub is truly already running
return false
}
fmt.Printf("Hub: Stale lock found (PID %d not running). Overwriting...\n", lock.PID)
}
}
// 2. Try to take the lock
lock := mcp.HubLock{
PID: os.Getpid(),
Port: 9000,
StartTime: time.Now().Format(time.RFC3339),
}
data, _ := json.MarshalIndent(lock, "", " ")
// Create directory if it doesn't exist (GetHubLockPath does this, but being safe)
_ = os.MkdirAll(filepath.Dir(lockPath), 0755)
err := os.WriteFile(lockPath, data, 0644)
return err == nil
}
// normalizePath ensures paths are absolute and have consistent casing for drive letters on Windows
func (a *App) normalizePath(path string) string {
abs, err := filepath.Abs(path)
if err != nil {
return path
}
if runtime.GOOS == "windows" && len(abs) > 1 && abs[1] == ':' {
// Uppercase drive letter for consistency
abs = strings.ToUpper(string(abs[0])) + abs[1:]
}
return filepath.Clean(abs)
}
func (a *App) initDatabase() {
configDir, err := getSherpaConfigDir()
if err != nil {
return
}
dbPath := filepath.Join(configDir, "hub.db")
a.db, err = database.InitDB(dbPath)
if err != nil {
fmt.Printf("Hub: Failed to initialize hub.db: %v\n", err)
return
}
// Create workspaces table
_, err = a.db.Exec(`
CREATE TABLE IF NOT EXISTS workspaces (
root TEXT PRIMARY KEY,
client TEXT,
last_seen DATETIME,
is_managed BOOLEAN DEFAULT 0
)
`)
if err != nil {
fmt.Printf("Hub: Failed to create workspaces table: %v\n", err)
}
// Load existing workspaces into memory
rows, err := a.db.Query("SELECT root, client, last_seen, is_managed FROM workspaces")
if err == nil {
defer rows.Close()
for rows.Next() {
var ws Workspace
var lastSeen string
var isManaged int
if err := rows.Scan(&ws.Root, &ws.Client, &lastSeen, &isManaged); err == nil {
ws.Root = a.normalizePath(ws.Root)
ws.LastSeen = lastSeen
ws.IsManaged = isManaged == 1
ws.State = "offline"
a.workspaces = append(a.workspaces, ws)
}
}
}
}
// RegisterWorkspace manually adds a workspace directory to the Hub's persistent list
func (a *App) RegisterWorkspace(path string) error {
if !a.isHub {
return fmt.Errorf("only the Master Hub can register workspaces")
}
// 1. Verify path exists
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
if !info.IsDir() {
return fmt.Errorf("path is not a directory")
}
// 2. Canonicalize path
absPath := a.normalizePath(path)
// 3. Initialize local state (.context-sherpa folder)
sherpaDir := filepath.Join(absPath, ".context-sherpa")
if err := os.MkdirAll(sherpaDir, 0755); err != nil {
return fmt.Errorf("failed to create .context-sherpa dir: %w", err)
}
// 4. Persist to database
if a.db != nil {
_, err := a.db.Exec(`
INSERT INTO workspaces (root, client, last_seen, is_managed)
VALUES (?, ?, ?, ?)
ON CONFLICT(root) DO UPDATE SET last_seen = excluded.last_seen, is_managed = 1
`, absPath, "manual", time.Now().Format(time.RFC3339), 1)
if err != nil {
return fmt.Errorf("database error: %w", err)
}
}
// 5. Update in-memory list
found := false
for i, ws := range a.workspaces {
if ws.Root == absPath {
a.workspaces[i].LastSeen = time.Now().Format(time.RFC3339)
a.workspaces[i].IsManaged = true
found = true
break
}
}
if !found {
a.workspaces = append(a.workspaces, Workspace{
Root: absPath,
Client: "manual",
State: "offline",
LastSeen: time.Now().Format(time.RFC3339),
IsManaged: true,
})
}
// 6. Notify UI
wailsRuntime.EventsEmit(a.ctx, "workspace-updated", a.workspaces)
return nil
}
// ReadMarkdown loads the raw text for MDXEditor.
func (a *App) ReadMarkdown(path string) (string, error) {
fmt.Printf("Hub: ReadMarkdown requested for path: %s\n", path)
if !a.isPathInWorkspace(path) {
fmt.Printf("Hub: ReadMarkdown access denied for path: %s\n", path)
return "", fmt.Errorf("access denied: path is outside of registered workspaces")
}
data, err := os.ReadFile(path)
if err != nil {
fmt.Printf("Hub: ReadMarkdown error for %s: %v\n", path, err)
return "", fmt.Errorf("failed to read file: %w", err)
}
// Safety: Strip null bytes to prevent bridge truncation
content := strings.ReplaceAll(string(data), "\x00", "")
fmt.Printf("Hub: ReadMarkdown success, read %d bytes from %s\n", len(data), path)
return content, nil
}
// WriteMarkdown commits the edits to the workspace.
func (a *App) WriteMarkdown(path string, content string) error {
fmt.Printf("Hub: WriteMarkdown requested for path: %s\n", path)
if !a.isPathInWorkspace(path) {
return fmt.Errorf("access denied: path is outside of registered workspaces")
}
// Audit: Ensure path is within workspace boundaries
err := os.WriteFile(path, []byte(content), 0644)
if err != nil {
return fmt.Errorf("failed to write file: %w", err)
}
return nil
}
// DiscoverMarkdownFiles recursively scans a workspace for .md files and extracts front-matter.
func (a *App) DiscoverMarkdownFiles(root string) ([]MarkdownEntry, error) {
if !a.isPathInWorkspace(root) {
return nil, fmt.Errorf("access denied: path is outside of registered workspaces")
}
var results []MarkdownEntry
// Robust skip list for common non-content directories
skipDirs := map[string]bool{
".git": true,
".svn": true,
".hg": true,
".bzr": true,
"_darcs": true,
".context-sherpa": true,
".ssh": true,
".aws": true,
".kube": true,
".env": true,
"node_modules": true,
"vendor": true,
"__pycache__": true,
".idea": true,
".vscode": true,
".history": true,
}
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
base := filepath.Base(path)
if skipDirs[base] {
return filepath.SkipDir
}
return nil
}
if strings.ToLower(filepath.Ext(path)) == ".md" {
entry := MarkdownEntry{Path: path}
// Try to extract front-matter
if fm, err := a.extractFrontMatter(path); err == nil {
entry.FrontMatter = fm
}
results = append(results, entry)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to scan for markdown files: %w", err)
}
return results, nil
}
// extractFrontMatter reads the beginning of a file and attempts to parse YAML front-matter
func (a *App) extractFrontMatter(path string) (map[string]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
// Read first 4KB (usually enough for front-matter)
buf := make([]byte, 4096)
n, err := file.Read(buf)
if err != nil && err != io.EOF {
return nil, err
}
content := string(buf[:n])
// Check if it starts with ---
if !strings.HasPrefix(content, "---\n") && !strings.HasPrefix(content, "---\r\n") {
return nil, fmt.Errorf("no front-matter prefix")
}
// Find the closing ---
// Start searching after the first ---
startSearch := 4
if strings.HasPrefix(content, "---\r\n") {
startSearch = 5
}
endIdx := strings.Index(content[startSearch:], "---")
if endIdx == -1 {
return nil, fmt.Errorf("no front-matter closer")
}
yamlContent := content[startSearch : startSearch+endIdx]
var fm map[string]string
if err := yaml.Unmarshal([]byte(yamlContent), &fm); err != nil {
return nil, err
}
return fm, nil
}
// isPathInWorkspace checks if the given path is within any registered workspace.
func (a *App) isPathInWorkspace(path string) bool {
absPath, err := filepath.Abs(path)
if err != nil {
return false
}
// On Windows, drive letters and paths are case-insensitive
isWindows := runtime.GOOS == "windows"
if isWindows {
absPath = strings.ToLower(absPath)
}
for _, ws := range a.workspaces {
wsAbs, err := filepath.Abs(ws.Root)
if err != nil {
continue
}
if isWindows {
wsAbs = strings.ToLower(wsAbs)
}
// Ensure we're comparing clean directory boundaries
wsAbs = filepath.Clean(wsAbs)
if !strings.HasSuffix(wsAbs, string(filepath.Separator)) {
wsAbs += string(filepath.Separator)
}
// Check if absPath is equal to wsAbs (root file) or a child
if absPath == strings.TrimSuffix(wsAbs, string(filepath.Separator)) || strings.HasPrefix(absPath, wsAbs) {
return true
}
}
return false
}
// IndexTarget represents a directory and language that should be indexed
type IndexTarget struct {
Path string
Lang string
}
// RunIndexingTask triggers the SCIP indexer for a workspace and streams log output.
// It discovers language-specific roots and runs indexers from those locations.
func (a *App) RunIndexingTask(workspacePath string) error {
if !a.isHub {
return fmt.Errorf("only the Master Hub can run indexing tasks")
}
targets := a.discoverIndexTargets(workspacePath)
a.emitIndexingLog(workspacePath, fmt.Sprintf("Discovered %d indexing targets.", len(targets)))
if len(targets) == 0 {
a.emitIndexingLog(workspacePath, "No indexable code files found (.go, .ts, .py, etc.).")
return fmt.Errorf("no indexable targets found")
}
go func() {
successCount := 0
for _, target := range targets {
a.emitIndexingLog(workspacePath, fmt.Sprintf("Processing %s in %s...", target.Lang, target.Path))
// Resolve indexer tool
status := a.GetScipIndexerStatus(target.Lang)
if !status["installed"].(bool) {
a.emitIndexingLog(workspacePath, fmt.Sprintf("Error: Indexer for %s not installed. Please visit Settings to install it.", target.Lang))
continue
}
toolPath := status["path"].(string)
// Prepare command and output path
// We use relative paths for --output to be safer on Windows
scipFilename := fmt.Sprintf("index-%s.scip", target.Lang)
scipRelPath := filepath.Join(".context-sherpa", scipFilename)
scipAbsPath := filepath.Join(target.Path, scipRelPath)
_ = os.MkdirAll(filepath.Join(target.Path, ".context-sherpa"), 0755)
var cmd *exec.Cmd
indexerArgs := []string{}
if target.Lang == "go" {
indexerArgs = []string{"--project-root", ".", "--repository-root", ".", "--output", scipRelPath}
} else {
// For scip-typescript, scip-python, etc.
indexerArgs = []string{"index", "--output", scipRelPath}
}
if runtime.GOOS == "windows" {
ext := strings.ToLower(filepath.Ext(toolPath))
if ext == ".ps1" {
// Use powershell for .ps1 files
fullArgs := append([]string{"-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-File", toolPath}, indexerArgs...)
cmd = sysutils.SilentCommand("powershell", fullArgs...)
} else if ext == ".cmd" || ext == ".bat" {
// Use cmd /c for .cmd and .bat files
fullArgs := append([]string{"/c", toolPath}, indexerArgs...)
cmd = sysutils.SilentCommand("cmd", fullArgs...)
} else {
cmd = sysutils.SilentCommand(toolPath, indexerArgs...)
}
} else {
cmd = sysutils.SilentCommand(toolPath, indexerArgs...)
}
cmd.Dir = target.Path
// Log the actual command being run
actualCmd := cmd.Path
if len(cmd.Args) > 1 {
actualCmd += " " + strings.Join(cmd.Args[1:], " ")
}
a.emitIndexingLog(workspacePath, fmt.Sprintf("Running: %s", actualCmd))
// Stream logs
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()
go a.streamLogsToUI(workspacePath, stdout)
go a.streamLogsToUI(workspacePath, stderr)
if err := cmd.Run(); err != nil {
a.emitIndexingLog(workspacePath, fmt.Sprintf("Indexing %s failed in %s: %v", target.Lang, target.Path, err))
} else {
// Verify file existence
if _, err := os.Stat(scipAbsPath); err == nil {
a.emitIndexingLog(workspacePath, fmt.Sprintf("Indexing %s complete! %s created at %s", target.Lang, scipFilename, scipAbsPath))
successCount++
} else {
a.emitIndexingLog(workspacePath, fmt.Sprintf("Indexing %s finished with success code, but %s was not found at expected path: %s", target.Lang, scipFilename, scipAbsPath))
}
}
}
wailsRuntime.EventsEmit(a.ctx, "indexing-finished", map[string]interface{}{
"root": workspacePath,
"success": successCount > 0,
"count": successCount,
})
}()
return nil
}
type langSignal struct {
path string
strength int // 2 = Strong (config file), 1 = Weak (code file/hint)
}
func (a *App) discoverIndexTargets(root string) []IndexTarget {
// 1. Walk tree and collect all directories with any language signal
allSignals := make(map[string]map[string]int) // path -> lang -> strength
isExcluded := func(path string) bool {
base := filepath.Base(path)
return base == "node_modules" || base == ".git" || base == ".context-sherpa" || base == "vendor"
}
queue := []string{root}
for len(queue) > 0 {
path := queue[0]
queue = queue[1:]
if isExcluded(path) {
continue
}
files, err := os.ReadDir(path)
if err != nil {
continue
}
signals := make(map[string]int)
for _, f := range files {
if f.IsDir() {
queue = append(queue, filepath.Join(path, f.Name()))
continue
}
name := f.Name()
ext := filepath.Ext(name)
// Go Signals
if name == "go.mod" {
signals["go"] = 2
} else if ext == ".go" && signals["go"] < 1 {
signals["go"] = 1
}
// TypeScript/JS Signals
if name == "tsconfig.json" {
signals["typescript"] = 2
} else if (name == "package.json" || ext == ".ts" || ext == ".tsx" || ext == ".js" || ext == ".jsx") && signals["typescript"] < 1 {
signals["typescript"] = 1
}
// Python Signals
if name == "pyproject.toml" || name == "requirements.txt" {
signals["python"] = 2
} else if ext == ".py" && signals["python"] < 1 {
signals["python"] = 1
}
}
if len(signals) > 0 {
allSignals[path] = signals
}
}
// 2. Filter targets per language
var targets []IndexTarget
langs := []string{"go", "typescript", "python"}
for _, lang := range langs {
// Identify candidate paths for this language
var candidates []langSignal
for p, signals := range allSignals {
if strength, ok := signals[lang]; ok {
candidates = append(candidates, langSignal{path: p, strength: strength})
}
}
// Pruning logic:
// A candidate path P is kept for language L if:
// - NO ancestor of P has a Strong signal (Strength=2) for L.
// - AND (If P is Weak (Strength=1), NO descendant of P has a Strong signal for L).
for _, candidate := range candidates {
keep := true
// Check ancestors
parent := filepath.Dir(candidate.path)
for {
if signals, ok := allSignals[parent]; ok {
if signals[lang] == 2 {
keep = false
break
}
}
if parent == root || parent == filepath.Dir(parent) {
break
}
parent = filepath.Dir(parent)
}
if !keep {
continue
}
// If Weak, check descendants for Strong signals
if candidate.strength == 1 {
for p, signals := range allSignals {
if signals[lang] == 2 && strings.HasPrefix(p, candidate.path+string(filepath.Separator)) {
keep = false
break
}
}
}
if keep {
targets = append(targets, IndexTarget{Path: candidate.path, Lang: lang})
}
}
}
// 3. Final pruning of targets for the same language (keep only highest ancestor among selected targets)
var finalTargets []IndexTarget
for _, t := range targets {
isSub := false
for _, other := range targets {
if t.Lang == other.Lang && t.Path != other.Path && strings.HasPrefix(t.Path, other.Path+string(filepath.Separator)) {
isSub = true
break
}
}
if !isSub {
finalTargets = append(finalTargets, t)
}
}
return finalTargets
}
func (a *App) detectLanguage(root string) string {
targets := a.discoverIndexTargets(root)
if len(targets) > 0 {
return targets[0].Lang
}
return ""
}
func (a *App) streamLogsToUI(root string, r io.Reader) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
a.emitIndexingLog(root, scanner.Text())
}
}
func (a *App) emitIndexingLog(root string, message string) {
wailsRuntime.EventsEmit(a.ctx, "indexing-log", map[string]string{
"root": root,
"message": message,
})
}
// PickDirectory opens a native directory picker and returns the selected path
func (a *App) PickDirectory() (string, error) {
return wailsRuntime.OpenDirectoryDialog(a.ctx, wailsRuntime.OpenDialogOptions{
Title: "Select Workspace Directory",
})
}
// BeforeClose is called when the application is about to close.
// It returns true to prevent closing, or false to allow it.
func (a *App) BeforeClose(ctx context.Context) bool {
// Save window state before shutdown
width, height := wailsRuntime.WindowGetSize(ctx)
x, y := wailsRuntime.WindowGetPosition(ctx)
isMaximized := wailsRuntime.WindowIsMaximised(ctx)
// Avoid saving zero sizes
if width > 0 && height > 0 {
prefs := a.GetPreferences()
prefs.WindowWidth = width
prefs.WindowHeight = height
prefs.WindowX = x
prefs.WindowY = y
prefs.IsMaximized = isMaximized
if err := a.SavePreferences(prefs); err != nil {
fmt.Printf("Hub: Failed to save window preferences: %v\n", err)
}
}
return false // allow close
}
func (a *App) Shutdown(ctx context.Context) {
a.localDBMu.Lock()
for p, db := range a.localDBs {
fmt.Printf("Hub: Closing local database: %s\n", p)
_ = db.Close()
}
// Clear the map to allow garbage collection and prevent re-use of closed handles
a.localDBs = make(map[string]*database.DB)
a.localDBMu.Unlock()
if a.isHub {
lockPath := mcp.GetHubLockPath()
_ = os.Remove(lockPath)
fmt.Println("Hub: Released hub.lock")
}
}
func (a *App) startHubServer() {
http.HandleFunc("/workspaces", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(a.workspaces)
return
}
if r.Method != http.MethodPut {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var ws Workspace
if err := json.NewDecoder(r.Body).Decode(&ws); err != nil {
http.Error(w, "Invalid payload", http.StatusBadRequest)
return
}
ws.Root = a.normalizePath(ws.Root)
// Check if we already have this workspace (match by Root only)
found := false
for i, existing := range a.workspaces {
// Case-insensitive comparison on Windows
match := false
if runtime.GOOS == "windows" {
match = strings.EqualFold(existing.Root, ws.Root)
} else {
match = (existing.Root == ws.Root)
}
if match {
// Update existing entry
a.workspaces[i].PID = ws.PID
a.workspaces[i].Client = ws.Client
a.workspaces[i].LastSeen = time.Now().Format(time.RFC3339)
a.workspaces[i].State = "active"
// Keep current IsManaged flag
ws = a.workspaces[i] // Use updated existing for DB persist
found = true
break
}
}
if !found {
ws.LastSeen = time.Now().Format(time.RFC3339)
ws.State = "active"
a.workspaces = append(a.workspaces, ws)
}
// Persist to database
if a.db != nil {
_, err := a.db.Exec(`
INSERT INTO workspaces (root, client, last_seen, is_managed)
VALUES (?, ?, ?, 0)
ON CONFLICT(root) DO UPDATE SET
client = excluded.client,
last_seen = excluded.last_seen
`, ws.Root, ws.Client, ws.LastSeen)
if err != nil {
fmt.Printf("Hub: Failed to persist workspace to DB: %v\n", err)
}
}
fmt.Printf("Hub: Workspace registered/updated: %s (PID: %d, Client: %s)\n", ws.Root, ws.PID, ws.Client)
// Emit event to frontend for real-time updates
wailsRuntime.EventsEmit(a.ctx, "workspace-updated", a.workspaces)
w.WriteHeader(http.StatusNoContent)
})
http.HandleFunc("/api/v1/inference", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req inference.InferenceRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid payload", http.StatusBadRequest)
return
}
res, err := a.inference.Execute(r.Context(), req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
})
http.HandleFunc("/api/v1/models", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
models, err := a.ListLocalModels()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(models)
})
http.HandleFunc("/api/v1/models/load", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
ModelID string `json:"modelId"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid payload", http.StatusBadRequest)
return
}
// Trigger model load by calling Execute with empty prompt (or a dedicated Load method if we add it)
// For now, Execute handles loading if modelID is provided.
_, err := a.inference.Execute(r.Context(), inference.InferenceRequest{
ModelID: req.ModelID,
Prompt: "", // Empty prompt just triggers load/switch
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
})
fmt.Println("Hub: Workspace registration server listening on http://localhost:9000")
if err := http.ListenAndServe(":9000", nil); err != nil {
fmt.Printf("Hub: Server failed: %v\n", err)
}
}
// GetAstGrepStatus checks if ast-grep is installed and returns its version
func (a *App) GetAstGrepStatus() map[string]interface{} {
result := map[string]interface{}{
"installed": false,
"version": "",
"path": "",
}
// Determine install path based on OS
osStr := runtime.GOOS
var homeDir string
var err error
if osStr == "windows" {
homeDir = os.Getenv("LOCALAPPDATA")
if homeDir == "" {
homeDir, err = os.UserHomeDir()
}
} else {
homeDir, err = os.UserHomeDir()
}
if err != nil {
return result
}
binDir := filepath.Join(homeDir, "context-sherpa", "bin")
if osStr != "windows" {
binDir = filepath.Join(homeDir, ".context-sherpa", "bin")
}
binName := "ast-grep"
if osStr == "windows" {
binName = "ast-grep.exe"
}
targetPath := filepath.Join(binDir, binName)
if _, err := os.Stat(targetPath); err == nil {
result["installed"] = true
result["path"] = targetPath
cmd := sysutils.SilentCommand(targetPath, "--version")
if output, err := cmd.CombinedOutput(); err == nil {
// Take the first line and trim
v := strings.Split(strings.TrimSpace(string(output)), "\n")[0]
result["version"] = v
}
} else {
// Fallback to checking system PATH
if path, err := exec.LookPath(binName); err == nil {
result["installed"] = true
result["path"] = path
cmd := sysutils.SilentCommand(path, "--version")
if output, err := cmd.CombinedOutput(); err == nil {
v := strings.Split(strings.TrimSpace(string(output)), "\n")[0]
result["version"] = v
}