-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
4390 lines (4072 loc) · 116 KB
/
app.go
File metadata and controls
4390 lines (4072 loc) · 116 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/zip"
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"net"
"net/url"
"os"
"path"
"path/filepath"
goruntime "runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unicode"
"asktg/internal/autostart"
"asktg/internal/buildinfo"
"asktg/internal/config"
"asktg/internal/domain"
"asktg/internal/embeddings"
"asktg/internal/mcpserver"
"asktg/internal/pdfextract"
"asktg/internal/security"
"asktg/internal/store/sqlite"
"asktg/internal/telegram"
"asktg/internal/tray"
"asktg/internal/urlfetch"
"asktg/internal/vector"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
const (
syncInterval = 90 * time.Second
syncMaxMessagesPerRun = 400
realtimeChatRefreshInterval = 5 * time.Minute
realtimeReadAckInterval = 2 * time.Second
realtimeReconnectBase = 1 * time.Second
realtimeReconnectMax = 30 * time.Second
urlCandidateScanLimit = 40
urlTaskMaxAttempts = 7
pdfTaskMaxAttempts = 3
embedTaskMaxAttempts = 4
embedCandidateLimit = 60
backupFilenamePrefix = "asktg-backup-"
hnswM = 16
hnswEfConstruction = 200
hnswEfSearch = 64
windowStateNormal = "normal"
windowStateMaximised = "maximised"
windowStateFullscreen = "fullscreen"
reactionModeOff = "off"
reactionModeEyes = "eyes_reaction"
eyesReactionEmoji = "👀"
)
type semanticProfile struct {
MaxDistance float64
Slack float64
}
var semanticProfiles = map[string]semanticProfile{
// Embeddings returned by the OpenAI-compatible API are unit-normalized (||v|| ~= 1),
// and we use squared L2 distance: d^2 = 2 - 2*cos(theta).
//
// Note: with short 1-word queries, we commonly observe best distances around ~1.3 in real data,
// so the defaults must be permissive enough to return *some* semantic candidates, while still
// allowing users to tighten it.
//
// very: max 1.40 ~= cos >= 0.30
// similar max 1.70 ~= cos >= 0.15
// weak: max 1.90 ~= cos >= 0.05
"very": {MaxDistance: 1.40, Slack: 0.25},
"similar": {MaxDistance: 1.70, Slack: 0.35},
"weak": {MaxDistance: 1.90, Slack: 0.45},
}
// App struct
type App struct {
ctx context.Context
cfg config.Config
store *sqlite.Store
telegramSvc *telegram.Service
mcpServer *mcpserver.Server
mcpEndpoint string
mcpStatus string
mcpPort int
trayManager *tray.Manager
trayStatus string
windowState string
embedClient *embeddings.HTTPClient
vectorIndex *vector.HNSW
mu sync.RWMutex
maintenance sync.Mutex
translateMu sync.RWMutex
translates map[string]queryTranslationCacheEntry
paused bool
quitNow bool
syncCancel context.CancelFunc
syncWG sync.WaitGroup
syncRunMu sync.Mutex
syncState string
syncBackfillProgress int
syncLastUnix int64
tgSyncMetrics telegram.SyncMetrics
realtimeReconnects int64
realtimeLastError string
realtimeLastErrorUnix int64
realtimeRefreshCh chan struct{}
realtimeWG sync.WaitGroup
urlWG sync.WaitGroup
embedWG sync.WaitGroup
pdfWG sync.WaitGroup
pdfBackfillMu sync.Mutex
pdfBackfillRunning bool
urlHostBackoff map[string]time.Time
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{
trayStatus: "initializing",
realtimeRefreshCh: make(chan struct{}, 1),
urlHostBackoff: make(map[string]time.Time),
translates: make(map[string]queryTranslationCacheEntry),
}
}
// 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
a.setTrayStatus("initializing")
a.cfg = config.Load()
if err := os.MkdirAll(a.cfg.DataDir, 0o755); err != nil {
panic(err)
}
dbStore, err := sqlite.Open(a.cfg.DBPath())
if err != nil {
panic(err)
}
a.store = dbStore
if err := a.store.Migrate(ctx); err != nil {
panic(err)
}
a.telegramSvc = telegram.NewService(filepath.Join(a.cfg.DataDir, "telegram", "session.json"))
a.seedTelegramCredentials(ctx)
a.configureTelegramFromStore(ctx)
a.configureEmbeddingsFromStore(ctx)
a.bootstrapVectorIndex(ctx)
a.setSyncStatus("idle", 0, 0)
paused, pausedErr := a.store.GetSettingBool(ctx, "sync_paused", false)
if pausedErr == nil {
a.paused = paused
}
if a.paused {
a.setSyncStatus("paused", 0, 0)
}
a.startTray()
if err := a.startMCP(ctx); err != nil {
runtime.LogWarningf(ctx, "MCP start warning: %v", err)
}
if !a.paused {
a.startWorkers()
}
}
func (a *App) seedTelegramCredentials(ctx context.Context) {
if a.store == nil || a.telegramSvc == nil {
return
}
existingID, _ := a.store.GetSettingInt(ctx, "telegram_api_id", 0)
existingHash, _ := a.readSecretSetting(ctx, "telegram_api_hash")
if existingID > 0 && strings.TrimSpace(existingHash) != "" {
return
}
apiID, apiHash, ok := telegramSeedCredentials()
if !ok {
return
}
if err := a.telegramSetCredentials(apiID, apiHash); err != nil {
runtime.LogWarningf(ctx, "Telegram credential seed failed: %v", err)
return
}
runtime.LogInfo(ctx, "Telegram credentials loaded from local environment/build defaults.")
}
func telegramSeedCredentials() (int, string, bool) {
// Prefer runtime env vars so users can set secrets without baking them into source control.
idRaw := strings.TrimSpace(os.Getenv("ASKTG_TG_API_ID"))
hashRaw := strings.TrimSpace(os.Getenv("ASKTG_TG_API_HASH"))
if idRaw != "" || hashRaw != "" {
if idRaw == "" || hashRaw == "" {
return 0, "", false
}
apiID, err := strconv.Atoi(idRaw)
if err != nil || apiID <= 0 {
return 0, "", false
}
return apiID, hashRaw, true
}
return embeddedTelegramCredentials()
}
func (a *App) shutdown(ctx context.Context) {
a.stopWorkers()
_ = a.stopMCP(ctx)
a.stopTray()
if a.store != nil {
_ = a.store.Close()
}
}
func (a *App) configureTelegramFromStore(ctx context.Context) {
if a.store == nil || a.telegramSvc == nil {
return
}
apiID, apiIDErr := a.store.GetSettingInt(ctx, "telegram_api_id", 0)
if apiIDErr != nil {
return
}
apiHash, hashErr := a.readSecretSetting(ctx, "telegram_api_hash")
if hashErr != nil || apiID <= 0 || strings.TrimSpace(apiHash) == "" {
return
}
if err := a.telegramSvc.Configure(apiID, apiHash); err != nil {
runtime.LogWarningf(ctx, "Telegram credentials are present but invalid: %v", err)
}
}
func (a *App) configureEmbeddingsFromStore(ctx context.Context) {
if a.store == nil {
a.embedClient = nil
return
}
apiKey, err := a.readSecretSetting(ctx, "embeddings_api_key")
if err != nil || strings.TrimSpace(apiKey) == "" {
a.embedClient = nil
return
}
baseURL, _ := a.store.GetSetting(ctx, "embeddings_base_url", "https://api.openai.com/v1")
model, _ := a.store.GetSetting(ctx, "embeddings_model", "text-embedding-3-large")
dims, _ := a.store.GetSettingInt(ctx, "embeddings_dims", 3072)
a.embedClient = embeddings.NewHTTPClient(baseURL, apiKey, model, dims)
if a.vectorIndex == nil || a.vectorIndex.Dimensions() != dims {
a.vectorIndex = vector.NewHNSW(dims, hnswM, hnswEfConstruction, hnswEfSearch)
}
// If the user has set History=Backfill, semantic embeddings should include the full history.
// Ensure embeddings_since_unix is corrected without requiring an explicit rebuild click.
if _, err := a.store.BackfillEmbeddingsForEnabledChats(ctx); err != nil {
runtime.LogWarningf(ctx, "embeddings backfill scope update failed: %v", err)
}
}
func (a *App) readSecretSetting(ctx context.Context, key string) (string, error) {
raw, err := a.store.GetSetting(ctx, key, "")
if err != nil {
return "", err
}
if strings.TrimSpace(raw) == "" {
return "", nil
}
decoded, decodeErr := security.UnprotectString(raw)
if decodeErr == nil {
return decoded, nil
}
if security.IsProtectedSecret(raw) {
return "", decodeErr
}
return raw, nil
}
func (a *App) writeSecretSetting(ctx context.Context, key string, value string) error {
clean := strings.TrimSpace(value)
if clean == "" {
return a.store.SetSetting(ctx, key, "")
}
protected, err := security.ProtectString(clean)
if err != nil {
return err
}
return a.store.SetSetting(ctx, key, protected)
}
func (a *App) vectorGraphPath() string {
return filepath.Join(a.cfg.DataDir, "vectors.graph")
}
func (a *App) bootstrapVectorIndex(ctx context.Context) {
if a.vectorIndex == nil {
dims, _ := a.store.GetSettingInt(ctx, "embeddings_dims", 3072)
a.vectorIndex = vector.NewHNSW(dims, hnswM, hnswEfConstruction, hnswEfSearch)
}
graphPath := a.vectorGraphPath()
if _, err := os.Stat(graphPath); err == nil {
if loadErr := a.vectorIndex.Load(graphPath); loadErr != nil {
runtime.LogWarningf(ctx, "Vector graph load failed, rebuilding: %v", loadErr)
}
}
if a.vectorIndex.Len() > 0 {
return
}
rebuildCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
if err := a.rebuildVectorIndexFromStore(rebuildCtx, true); err != nil {
runtime.LogWarningf(ctx, "Vector graph rebuild on startup failed: %v", err)
}
}
func (a *App) rebuildVectorIndexFromStore(ctx context.Context, persist bool) error {
if a.vectorIndex == nil {
dims, _ := a.store.GetSettingInt(ctx, "embeddings_dims", 3072)
a.vectorIndex = vector.NewHNSW(dims, hnswM, hnswEfConstruction, hnswEfSearch)
}
records, err := a.store.ListEmbeddings(ctx, 0)
if err != nil {
return err
}
urlRecords, err := a.store.ListURLEmbeddings(ctx, 0)
if err != nil {
return err
}
fileRecords, err := a.store.ListFileEmbeddings(ctx, 0)
if err != nil {
return err
}
items := make([]vector.Item, 0, len(records)+len(urlRecords)+len(fileRecords))
for _, record := range records {
items = append(items, vector.Item{
ChunkID: record.ChunkID,
Vector: record.Vector,
})
}
for _, record := range urlRecords {
nodeID := vectorNodeIDForURL(record.ChunkID)
if nodeID == 0 {
continue
}
items = append(items, vector.Item{
ChunkID: nodeID,
Vector: record.Vector,
})
}
for _, record := range fileRecords {
nodeID := vectorNodeIDForFileDoc(record.ChunkID)
if nodeID == 0 {
continue
}
items = append(items, vector.Item{
ChunkID: nodeID,
Vector: record.Vector,
})
}
if err := a.vectorIndex.Rebuild(items); err != nil {
return err
}
if persist {
return a.vectorIndex.Save(a.vectorGraphPath())
}
return nil
}
func (a *App) startWorkers() {
loopCtx, cancel := context.WithCancel(context.Background())
a.syncCancel = cancel
if a.store != nil {
if reset, err := a.store.ResetRunningEmbeddingTasks(a.ctx, time.Now().Unix()); err != nil {
runtime.LogWarningf(a.ctx, "Embedding task reset failed: %v", err)
} else if reset > 0 {
runtime.LogInfof(a.ctx, "Reset %d stuck embedding tasks", reset)
}
}
a.syncWG.Add(1)
go func() {
defer a.syncWG.Done()
a.runBackgroundSyncLoop(loopCtx)
}()
a.realtimeWG.Add(1)
go func() {
defer a.realtimeWG.Done()
a.runRealtimeLoop(loopCtx)
}()
a.urlWG.Add(1)
go func() {
defer a.urlWG.Done()
a.runURLFetchLoop(loopCtx)
}()
a.embedWG.Add(1)
go func() {
defer a.embedWG.Done()
a.runEmbeddingsLoop(loopCtx)
}()
a.pdfWG.Add(1)
go func() {
defer a.pdfWG.Done()
a.runPDFFetchLoop(loopCtx)
}()
}
func (a *App) stopWorkers() {
if a.syncCancel == nil {
return
}
a.syncCancel()
a.syncWG.Wait()
a.realtimeWG.Wait()
a.urlWG.Wait()
a.embedWG.Wait()
a.pdfWG.Wait()
a.syncCancel = nil
}
func (a *App) startTray() {
a.trayManager = tray.New(trayIcon, func() {
a.showMainWindow()
}, func() {
a.hideMainWindow()
}, func() {
a.ExitApp()
})
if err := a.trayManager.Start(); err != nil {
a.setTrayStatus("unavailable")
runtime.LogWarningf(a.ctx, "System tray unavailable: %v", err)
return
}
a.setTrayStatus("running")
a.trayManager.SetWindowVisible(true)
}
func (a *App) stopTray() {
if a.trayManager == nil {
return
}
a.trayManager.Stop()
a.setTrayStatus("stopped")
}
func (a *App) showMainWindow() {
if a.ctx == nil {
return
}
runtime.WindowShow(a.ctx)
runtime.WindowUnminimise(a.ctx)
a.restoreWindowState()
state := a.windowStateSnapshot()
if state != windowStateNormal {
go func(savedState string) {
time.Sleep(140 * time.Millisecond)
if a.ctx == nil {
return
}
a.applyWindowState(savedState)
}(state)
}
if a.trayManager != nil {
a.trayManager.SetWindowVisible(true)
}
}
func (a *App) hideMainWindow() {
if a.ctx == nil {
return
}
a.captureWindowState()
runtime.WindowHide(a.ctx)
if a.trayManager != nil {
a.trayManager.SetWindowVisible(false)
}
}
func (a *App) beforeClose(_ context.Context) (prevent bool) {
a.mu.RLock()
quitNow := a.quitNow
a.mu.RUnlock()
if quitNow {
return false
}
a.hideMainWindow()
return true
}
func (a *App) setTrayStatus(status string) {
a.mu.Lock()
defer a.mu.Unlock()
a.trayStatus = status
}
func (a *App) TrayStatus() string {
a.mu.RLock()
defer a.mu.RUnlock()
if strings.TrimSpace(a.trayStatus) == "" {
return "unknown"
}
return a.trayStatus
}
func (a *App) captureWindowState() {
state := windowStateNormal
if runtime.WindowIsFullscreen(a.ctx) {
state = windowStateFullscreen
} else if runtime.WindowIsMaximised(a.ctx) {
state = windowStateMaximised
}
a.mu.Lock()
a.windowState = state
a.mu.Unlock()
}
func (a *App) windowStateSnapshot() string {
a.mu.RLock()
defer a.mu.RUnlock()
if strings.TrimSpace(a.windowState) == "" {
return windowStateNormal
}
return a.windowState
}
func (a *App) restoreWindowState() {
a.applyWindowState(a.windowStateSnapshot())
}
func (a *App) applyWindowState(state string) {
switch state {
case windowStateFullscreen:
runtime.WindowFullscreen(a.ctx)
case windowStateMaximised:
runtime.WindowMaximise(a.ctx)
}
}
func (a *App) startMCP(ctx context.Context) error {
if a.store == nil {
a.setMCPRuntime("unavailable", 0)
return errors.New("store is not initialized")
}
enabled, err := a.store.GetSettingBool(ctx, "mcp_enabled", true)
if err != nil {
a.setMCPRuntime("failed (settings read error)", 0)
return err
}
if !enabled {
port, _ := a.store.GetSettingInt(ctx, "mcp_port", 0)
a.setMCPRuntime("disabled", port)
return nil
}
port, err := a.store.GetSettingInt(ctx, "mcp_port", 0)
if err != nil {
a.setMCPRuntime("failed (settings read error)", 0)
return err
}
if a.mcpServer != nil {
activePort := port
if parsed, parseErr := url.Parse(a.mcpEndpoint); parseErr == nil {
if p, convErr := strconv.Atoi(parsed.Port()); convErr == nil {
activePort = p
}
}
a.setMCPRuntime("running", activePort)
return nil
}
mcpSrv := mcpserver.New(&queryService{app: a})
if err := mcpSrv.Start(port); err != nil {
a.setMCPRuntime(mcpFailureStatus(err, port), port)
return err
}
a.mcpServer = mcpSrv
a.mcpEndpoint = mcpSrv.Endpoint()
activePort := port
if parsed, parseErr := url.Parse(a.mcpEndpoint); parseErr == nil {
if p, convErr := strconv.Atoi(parsed.Port()); convErr == nil {
activePort = p
_ = a.store.SetSetting(ctx, "mcp_port", strconv.Itoa(p))
}
}
a.setMCPRuntime("running", activePort)
return nil
}
func (a *App) stopMCP(ctx context.Context) error {
if a.mcpServer == nil {
return nil
}
err := a.mcpServer.Stop(ctx)
a.mcpServer = nil
a.mcpEndpoint = ""
return err
}
func (a *App) setMCPRuntime(status string, port int) {
a.mu.Lock()
defer a.mu.Unlock()
if strings.TrimSpace(status) != "" {
a.mcpStatus = status
}
if port >= 0 {
a.mcpPort = port
}
}
func (a *App) mcpRuntimeSnapshot() (string, int) {
a.mu.RLock()
defer a.mu.RUnlock()
status := a.mcpStatus
if strings.TrimSpace(status) == "" {
status = "unknown"
}
return status, a.mcpPort
}
func mcpFailureStatus(err error, configuredPort int) string {
if configuredPort > 0 && isAddressInUse(err) {
return "failed (port in use)"
}
return "failed"
}
func isAddressInUse(err error) bool {
if err == nil {
return false
}
if errors.Is(err, syscall.EADDRINUSE) {
return true
}
var opErr *net.OpError
if errors.As(err, &opErr) {
return errors.Is(opErr.Err, syscall.EADDRINUSE)
}
return false
}
func (a *App) DataDir() string {
return a.cfg.DataDir
}
func (a *App) BrowseDataDir() (string, error) {
if a.ctx == nil {
return "", errors.New("app context is not initialized")
}
defaultDir := a.cfg.DataDir
if _, err := os.Stat(defaultDir); err != nil {
defaultDir = filepath.Dir(defaultDir)
}
return runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select asktg data directory",
DefaultDirectory: defaultDir,
CanCreateDirectories: true,
})
}
func (a *App) SetDataDir(path string) (string, error) {
clean := strings.TrimSpace(path)
if clean == "" {
return "", errors.New("data directory is required")
}
abs, err := filepath.Abs(clean)
if err != nil {
return "", err
}
if err := config.PersistDataDir(abs); err != nil {
return "", err
}
if filepath.Clean(abs) == filepath.Clean(a.cfg.DataDir) {
return "Data directory is already active", nil
}
return fmt.Sprintf("Data directory saved: %s. Restart app to apply.", abs), nil
}
func (a *App) AutostartEnabled() (bool, error) {
return autostart.Enabled()
}
func (a *App) SetAutostartEnabled(enable bool) (bool, error) {
if err := autostart.SetEnabled(enable); err != nil {
return false, err
}
return autostart.Enabled()
}
func (a *App) BackgroundPaused() bool {
a.mu.RLock()
defer a.mu.RUnlock()
return a.paused
}
func (a *App) PauseBackground() (domain.IndexStatus, error) {
a.maintenance.Lock()
defer a.maintenance.Unlock()
if a.store == nil {
return domain.IndexStatus{}, errors.New("store is not initialized")
}
if a.BackgroundPaused() {
return a.getStatus(a.ctx)
}
a.stopWorkers()
a.mu.Lock()
a.paused = true
a.mu.Unlock()
a.setSyncStatus("paused", -1, 0)
if err := a.store.SetSetting(a.ctx, "sync_paused", "1"); err != nil {
return domain.IndexStatus{}, err
}
return a.getStatus(a.ctx)
}
func (a *App) ResumeBackground() (domain.IndexStatus, error) {
a.maintenance.Lock()
defer a.maintenance.Unlock()
if a.store == nil {
return domain.IndexStatus{}, errors.New("store is not initialized")
}
if !a.BackgroundPaused() {
return a.getStatus(a.ctx)
}
a.mu.Lock()
a.paused = false
a.mu.Unlock()
if err := a.store.SetSetting(a.ctx, "sync_paused", "0"); err != nil {
return domain.IndexStatus{}, err
}
a.setSyncStatus("idle", -1, time.Now().Unix())
a.startWorkers()
return a.getStatus(a.ctx)
}
func (a *App) ListChats() ([]domain.ChatPolicy, error) {
if a.store == nil {
return nil, errors.New("store is not initialized")
}
return a.store.ListChats(a.ctx)
}
func (a *App) SetChatPolicy(chatID int64, enabled bool, historyMode string, allowEmbeddings bool, urlsMode string, reactionMode string) error {
if a.store == nil {
return errors.New("store is not initialized")
}
historyMode = strings.TrimSpace(historyMode)
if historyMode == "" {
historyMode = "full"
}
urlsMode = strings.TrimSpace(urlsMode)
if urlsMode == "" {
urlsMode = "off"
}
reactionMode = normalizeReactionMode(reactionMode)
if err := a.store.SetChatPolicy(a.ctx, chatID, enabled, historyMode, allowEmbeddings, urlsMode, reactionMode); err != nil {
return err
}
a.requestRealtimeChatRefresh()
go func() {
scanCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
a.enqueueURLCandidates(scanCtx)
}()
return nil
}
func (a *App) telegramSetCredentials(apiID int, apiHash string) error {
if a.store == nil {
return errors.New("store is not initialized")
}
if a.telegramSvc == nil {
return errors.New("telegram service is not initialized")
}
if err := a.telegramSvc.Configure(apiID, apiHash); err != nil {
return err
}
if err := a.store.SetSetting(a.ctx, "telegram_api_id", strconv.Itoa(apiID)); err != nil {
return err
}
return a.writeSecretSetting(a.ctx, "telegram_api_hash", apiHash)
}
func (a *App) EmbeddingsConfig() (domain.EmbeddingsConfig, error) {
if a.store == nil {
return domain.EmbeddingsConfig{}, errors.New("store is not initialized")
}
baseURL, err := a.store.GetSetting(a.ctx, "embeddings_base_url", "https://api.openai.com/v1")
if err != nil {
return domain.EmbeddingsConfig{}, err
}
model, err := a.store.GetSetting(a.ctx, "embeddings_model", "text-embedding-3-large")
if err != nil {
return domain.EmbeddingsConfig{}, err
}
dims, err := a.store.GetSettingInt(a.ctx, "embeddings_dims", 3072)
if err != nil {
return domain.EmbeddingsConfig{}, err
}
apiKey, err := a.readSecretSetting(a.ctx, "embeddings_api_key")
if err != nil {
return domain.EmbeddingsConfig{}, err
}
return domain.EmbeddingsConfig{
BaseURL: baseURL,
Model: model,
Dimensions: dims,
Configured: strings.TrimSpace(apiKey) != "",
}, nil
}
func (a *App) SetEmbeddingsConfig(baseURL, model, apiKey string, dimensions int) error {
if a.store == nil {
return errors.New("store is not initialized")
}
prevKey, _ := a.readSecretSetting(a.ctx, "embeddings_api_key")
cleanBase := strings.TrimSpace(baseURL)
if cleanBase == "" {
cleanBase = "https://api.openai.com/v1"
}
cleanModel := strings.TrimSpace(model)
if cleanModel == "" {
cleanModel = "text-embedding-3-large"
}
if dimensions <= 0 {
dimensions = 3072
}
prevDims, _ := a.store.GetSettingInt(a.ctx, "embeddings_dims", 3072)
if err := a.store.SetSetting(a.ctx, "embeddings_base_url", cleanBase); err != nil {
return err
}
if err := a.store.SetSetting(a.ctx, "embeddings_model", cleanModel); err != nil {
return err
}
if err := a.store.SetSetting(a.ctx, "embeddings_dims", strconv.Itoa(dimensions)); err != nil {
return err
}
if strings.TrimSpace(apiKey) != "" {
if err := a.writeSecretSetting(a.ctx, "embeddings_api_key", apiKey); err != nil {
return err
}
}
a.configureEmbeddingsFromStore(a.ctx)
if strings.TrimSpace(prevKey) == "" && a.embedClient != nil && a.embedClient.Configured() {
ctx, cancel := context.WithTimeout(a.ctx, 20*time.Second)
defer cancel()
_, _ = a.store.EnableEmbeddingsForEnabledChats(ctx)
}
if prevDims != dimensions {
ctx, cancel := context.WithTimeout(a.ctx, 45*time.Second)
defer cancel()
if err := a.store.ResetEmbeddings(ctx); err != nil {
return err
}
if a.vectorIndex != nil {
if err := a.vectorIndex.Rebuild(nil); err != nil {
return err
}
if err := a.vectorIndex.Save(a.vectorGraphPath()); err != nil {
runtime.LogWarningf(a.ctx, "vector graph save after dimensions update failed: %v", err)
}
}
}
go func() {
scanCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
a.enqueueEmbeddingCandidates(scanCtx)
}()
return nil
}
func (a *App) QueryTranslationConfig() (domain.QueryTranslationConfig, error) {
if a.store == nil {
return domain.QueryTranslationConfig{}, errors.New("store is not initialized")
}
cfg := a.queryTranslateConfig(a.ctx)
return domain.QueryTranslationConfig{
BaseURL: cfg.BaseURL,
Model: cfg.Model,
Configured: strings.TrimSpace(cfg.APIKey) != "",
}, nil
}
func (a *App) SetQueryTranslationConfig(baseURL, model, apiKey string) error {
if a.store == nil {
return errors.New("store is not initialized")
}
cleanBase := strings.TrimSpace(baseURL)
if err := a.store.SetSetting(a.ctx, "query_translation_base_url", cleanBase); err != nil {
return err
}
cleanModel := strings.TrimSpace(model)
if cleanModel == "" {
cleanModel = queryTranslateModelDefault
}
if err := a.store.SetSetting(a.ctx, "query_translation_model", cleanModel); err != nil {
return err
}
if strings.TrimSpace(apiKey) != "" {
if err := a.writeSecretSetting(a.ctx, "query_translation_api_key", apiKey); err != nil {
return err
}
}
return nil
}
func (a *App) TestEmbeddings() (domain.EmbeddingsTestResult, error) {
if a.store == nil {
return domain.EmbeddingsTestResult{}, errors.New("store is not initialized")
}
ctx, cancel := context.WithTimeout(a.ctx, 25*time.Second)
defer cancel()
baseURL, _ := a.store.GetSetting(ctx, "embeddings_base_url", "https://api.openai.com/v1")
model, _ := a.store.GetSetting(ctx, "embeddings_model", "text-embedding-3-large")
dims, _ := a.store.GetSettingInt(ctx, "embeddings_dims", 3072)
if a.embedClient == nil {
a.configureEmbeddingsFromStore(ctx)
}
if a.embedClient == nil {
return domain.EmbeddingsTestResult{
OK: false,
BaseURL: baseURL,
Model: model,
Dimensions: dims,
Error: "embeddings client is not configured",
}, nil
}
start := time.Now()
vectors, err := a.embedClient.Embed(ctx, []string{"ping"})
took := time.Since(start)
if err != nil {
return domain.EmbeddingsTestResult{
OK: false,
BaseURL: baseURL,
Model: model,
Dimensions: dims,
TookMs: took.Milliseconds(),
Error: err.Error(),
}, nil
}
vectorLen := 0
if len(vectors) > 0 {
vectorLen = len(vectors[0])
}
return domain.EmbeddingsTestResult{
OK: true,
BaseURL: baseURL,
Model: model,
Dimensions: dims,
VectorLen: vectorLen,
TookMs: took.Milliseconds(),
}, nil
}
func (a *App) TestQueryTranslation() (domain.QueryTranslationTestResult, error) {
if a.store == nil {
return domain.QueryTranslationTestResult{}, errors.New("store is not initialized")
}
ctx, cancel := context.WithTimeout(a.ctx, 12*time.Second)
defer cancel()
cfg := a.queryTranslateConfig(ctx)
if !cfg.Configured() {
return domain.QueryTranslationTestResult{
OK: false,
BaseURL: cfg.BaseURL,
Model: cfg.Model,
Error: "query translation client is not configured",
}, nil
}