Repository navigation
Expand file tree
/
Copy pathapp.go
More file actions
1366 lines (1234 loc) · 38.6 KB
/
Copy pathapp.go
File metadata and controls
1366 lines (1234 loc) · 38.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"
"errors"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
wailsrt "github.com/wailsapp/wails/v2/pkg/runtime"
"github.com/znsoftm/RapidProxy/internal/applog"
"github.com/znsoftm/RapidProxy/internal/autostart"
"github.com/znsoftm/RapidProxy/internal/config"
"github.com/znsoftm/RapidProxy/internal/locale"
"github.com/znsoftm/RapidProxy/internal/proxysrv"
"github.com/znsoftm/RapidProxy/internal/store"
"github.com/znsoftm/RapidProxy/internal/tray"
"github.com/znsoftm/RapidProxy/internal/update"
"github.com/znsoftm/RapidProxy/internal/upstream"
"github.com/znsoftm/RapidProxy/internal/winfit"
)
// 事件名(前端通过 window.runtime.EventsOn 订阅)。
const (
eventState = "state"
eventLogin = "login"
eventLog = "log"
eventUpdate = "update"
)
// Version 是程序版本号。
const Version = "1.2.4"
// 窗口尺寸(逻辑像素,与 Wails 的屏幕尺寸单位一致)。
//
// 这只是「期望值」,实际尺寸会在启动时按当前屏幕收敛,见 App.fitWindow。
const (
windowDefaultWidth = 1080
windowDefaultHeight = 740
windowMinWidth = 940
windowMinHeight = 600
)
// -----------------------------------------------------------------------------
// 前端视图模型
// -----------------------------------------------------------------------------
// AccessView 是给用户复制到其它软件的接入信息。
type AccessView struct {
BaseURL string `json:"baseUrl"`
OpenAIURL string `json:"openaiUrl"`
APIKeys []string `json:"apiKeys"`
RequireKey bool `json:"requireKey"`
Models []string `json:"models"`
Running bool `json:"running"`
Sample string `json:"sample"`
}
// AccountView 是账号列表项。
type AccountView struct {
ID string `json:"id"`
Provider string `json:"provider"`
ProviderName string `json:"providerName"`
Nickname string `json:"nickname"`
UID string `json:"uid"`
EnterpriseID string `json:"enterpriseId"`
ExpiresAt string `json:"expiresAt"`
ExpiresIn string `json:"expiresIn"`
Expired bool `json:"expired"`
CreatedAt string `json:"createdAt"`
}
// ProviderView 是上游配置项。
type ProviderView struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
BaseURL string `json:"baseUrl"`
Origin string `json:"origin"`
Proxy string `json:"proxy"`
AccountCount int `json:"accountCount"`
ModelCount int `json:"modelCount"`
NeedsProxy bool `json:"needsProxy"`
}
// ModelView 是模型列表项。
type ModelView struct {
ID string `json:"id"`
Name string `json:"name"`
Provider string `json:"provider"`
Context int64 `json:"context"`
MaxOut int64 `json:"maxOut"`
Images bool `json:"images"`
}
// SettingsView 是设置面板数据。
type SettingsView struct {
Listen string `json:"listen"`
ModelSyncHours int `json:"modelSyncHours"`
CORS bool `json:"cors"`
Sanitize bool `json:"sanitize"`
MaxThinking bool `json:"maxThinking"`
AutoStart bool `json:"autoStart"`
LaunchAtLogin bool `json:"launchAtLogin"`
// Language 是界面语言偏好:system / zh / en(前端据此渲染界面)。
Language string `json:"language"`
ConfigPath string `json:"configPath"`
DataDir string `json:"dataDir"`
LogPath string `json:"logPath"`
AccountDir string `json:"accountDir"`
Version string `json:"version"`
Platform string `json:"platform"`
}
// StateView 是界面一次拉取的全部状态。
type StateView struct {
Running bool `json:"running"`
Listen string `json:"listen"`
BaseURL string `json:"baseUrl"`
OpenAIURL string `json:"openaiUrl"`
RequireKey bool `json:"requireKey"`
APIKeys []string `json:"apiKeys"`
Providers []ProviderView `json:"providers"`
Accounts []AccountView `json:"accounts"`
Models []ModelView `json:"models"`
Settings SettingsView `json:"settings"`
Logs []string `json:"logs"`
Login LoginView `json:"login"`
}
// LoginView 是登录流程状态。
type LoginView struct {
Active bool `json:"active"`
Provider string `json:"provider"`
URL string `json:"url"`
EmbedURL string `json:"embedUrl"`
State string `json:"state"`
Status string `json:"status"`
Message string `json:"message"`
ExpiresAt string `json:"expiresAt"`
AccountID string `json:"accountId"`
}
// UpdateView 是在线更新的检查结果与安装进度。
type UpdateView struct {
Phase string `json:"phase"` // idle / checking / available / none / downloading / installing / done / failed
Current string `json:"current"`
Latest string `json:"latest"`
HasUpdate bool `json:"hasUpdate"`
Page string `json:"page"` // Release 页面
AssetName string `json:"assetName"` // 将下载的安装包
Notes string `json:"notes"` // Release 说明
Progress int `json:"progress"` // 0-100(下载时)
Message string `json:"message"` // 给用户看的提示
}
// ProfileInput 是保存设置时的上游开关。
type ProfileInput struct {
ID string `json:"id"`
Enabled bool `json:"enabled"`
Proxy string `json:"proxy"`
}
// SettingsInput 是保存设置的入参。
type SettingsInput struct {
Listen string `json:"listen"`
ModelSyncHours int `json:"modelSyncHours"`
CORS bool `json:"cors"`
Sanitize bool `json:"sanitize"`
MaxThinking bool `json:"maxThinking"`
AutoStart bool `json:"autoStart"`
LaunchAtLogin bool `json:"launchAtLogin"`
Profiles []ProfileInput `json:"profiles"`
}
// -----------------------------------------------------------------------------
// App
// -----------------------------------------------------------------------------
type loginRun struct {
provider string
session *upstream.LoginSession
cancel context.CancelFunc
status string
message string
accountID string
parentOrigin string
}
// App 是绑定给前端的应用对象。
type App struct {
dataDir string
ctx context.Context
ctxMu sync.RWMutex
log *applog.Logger
store *store.Store
srv *proxysrv.Server
tray *tray.Tray
cfgMu sync.RWMutex
cfg *config.Config
quitting atomic.Bool
headless atomic.Bool
trayHint atomic.Bool
pendingShow atomic.Bool // 窗口就绪前收到的显示请求,startup 末尾补显
unsubLog func()
loginMu sync.Mutex
login *loginRun
updMu sync.Mutex
upd *update.Release // 最近一次检查到的可用更新
}
// NewApp 初始化应用。
func NewApp() *App {
dataDir := config.DefaultDataDir()
if custom := strings.TrimSpace(os.Getenv("RAPIDPROXY_DATA_DIR")); custom != "" {
dataDir = custom
}
logger := applog.New(dataDir, 800)
cfgPath := config.DefaultPath(dataDir)
cfg, err := config.Load(cfgPath)
if err != nil {
logger.Errorf("加载配置失败,使用默认配置: %v", err)
// 带上路径,否则界面上的「配置文件路径」会是空的,保存时也会写到别处。
cfg = config.DefaultAt(cfgPath)
}
// 界面语言尽早定下来:托盘菜单、更新提示等 Go 侧文案在窗口出现前后都会用到。
locale.Set(locale.FromPref(cfg.Language))
credStore, err := store.New(dataDir)
if err != nil {
logger.Errorf("初始化凭据仓库失败: %v", err)
}
app := &App{
dataDir: dataDir,
log: logger,
store: credStore,
cfg: cfg,
}
app.srv = proxysrv.New(cfg, credStore, logger)
return app
}
// startup 在窗口创建后调用。
func (a *App) startup(ctx context.Context) {
a.ctxMu.Lock()
a.ctx = ctx
a.ctxMu.Unlock()
a.log.Infof("RapidProxy %s 已启动(数据目录 %s)", Version, a.dataDir)
a.unsubLog = a.log.Subscribe(func(line string) {
a.emit(eventLog, line)
})
// 按配置同步系统自启动条目:既是首次启用的默认值落位,
// 也是程序升级(安装路径变化)后自动修正自启动指向。
a.applyLaunchAtLogin(a.cfg.LaunchAtLoginEnabled())
// 在界面真正显示出来之前收敛窗口尺寸(见 fitWindow 的注释)。
a.fitWindow(ctx)
if a.cfg.AutoStartEnabled() {
if err := a.StartService(); err != nil {
a.log.Errorf("自动启动失败: %v", err)
}
}
a.pushState()
// 启动期间收到的激活请求(第二份程序抢在窗口就绪前启动了本实例)
// 在这里补上:窗口几何已在 fitWindow 收敛完毕,直接显示即可。
if a.pendingShow.CompareAndSwap(true, false) {
wailsrt.WindowShow(ctx)
}
// 后台静默检查一次更新(失败不打扰用户,结果通过 update 事件推送)
go func() {
time.Sleep(4 * time.Second)
if a.quitting.Load() {
return
}
client := &http.Client{Timeout: 20 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
if rel, has, err := update.Check(ctx, client, "", update.DefaultRepo, Version); err == nil && has {
a.updMu.Lock()
a.upd = rel
a.updMu.Unlock()
a.emitUpdate(UpdateView{
Phase: "available", Current: Version, Latest: rel.Version,
HasUpdate: true, Page: rel.Page, AssetName: rel.Asset.Name, Notes: rel.Notes,
Message: locale.T("upd.availableSettings", rel.Version),
})
}
}()
}
func (a *App) context() context.Context {
a.ctxMu.RLock()
defer a.ctxMu.RUnlock()
return a.ctx
}
func (a *App) emit(name string, payload any) {
ctx := a.context()
if ctx == nil {
return
}
wailsrt.EventsEmit(ctx, name, payload)
}
func (a *App) pushState() { a.emit(eventState, a.GetState()) }
func (a *App) pushLogin() { a.emit(eventLogin, a.loginState()) }
func (a *App) settings() *config.Config {
a.cfgMu.RLock()
defer a.cfgMu.RUnlock()
return a.cfg
}
// startTray 初始化托盘图标(必须在 wails.Run 之前调用)。
func (a *App) startTray() {
a.tray = tray.Start(tray.Callbacks{
OnShow: a.ShowWindow,
OnResetWindow: a.ResetWindow,
OnToggle: a.ToggleService,
OnCopyURL: func() {
ctx := a.context()
if ctx == nil {
return
}
url := a.settings().OpenAIBaseURL()
wailsrt.ClipboardSetText(ctx, url)
a.log.Infof("已复制接口地址: %s", url)
},
OnQuit: a.QuitApp,
})
a.syncTray()
}
func (a *App) syncTray() {
if a.tray == nil {
return
}
running := false
addr := a.settings().Listen
if a.srv != nil {
running = a.srv.Running()
addr = a.srv.Addr()
}
a.tray.SetState(running, addr)
}
// beforeClose 拦截窗口关闭:默认只最小化到托盘,退出只能通过托盘菜单。
func (a *App) beforeClose(ctx context.Context) bool {
if a.quitting.Load() {
return false
}
wailsrt.WindowHide(ctx)
a.log.Infof("窗口已最小化到系统托盘(右键托盘图标可退出)")
go a.hintTrayOnce(ctx)
return true
}
func (a *App) hintTrayOnce(ctx context.Context) {
if !a.trayHint.CompareAndSwap(false, true) {
return
}
_, _ = wailsrt.MessageDialog(ctx, wailsrt.MessageDialogOptions{
Type: wailsrt.InfoDialog,
Title: locale.T("dlg.minimized.title"),
Message: locale.T("dlg.minimized.msg"),
Buttons: []string{locale.T("dlg.minimized.ok")},
})
}
// -----------------------------------------------------------------------------
// 窗口尺寸自适应
// -----------------------------------------------------------------------------
// fitWindow 在启动时把主窗口收敛到当前屏幕的可见范围内。
//
// 为什么需要:Wails 窗口的宽高是「逻辑像素」,创建窗口时会按屏幕 DPI 换算成
// 物理像素。系统缩放 150% 时,逻辑高度 740 会被放大成 1110 物理像素,在
// 1920x1080 的屏幕上就超出了屏幕高度,窗口上下都会跑到屏幕外看不到。所以在
// 窗口显示之前按屏幕(逻辑)尺寸重新算一遍尺寸并居中。
func (a *App) fitWindow(ctx context.Context) {
preferred := winfit.Size{Width: windowDefaultWidth, Height: windowDefaultHeight}
floorMin := winfit.Size{Width: windowMinWidth, Height: windowMinHeight}
screen, physical, ok := currentScreenSize(ctx)
if !ok {
a.log.Warnf("未能读取屏幕尺寸,窗口保持默认尺寸 %dx%d", preferred.Width, preferred.Height)
wailsrt.WindowSetMinSize(ctx, floorMin.Width, floorMin.Height)
wailsrt.WindowSetSize(ctx, preferred.Width, preferred.Height)
wailsrt.WindowCenter(ctx)
return
}
size, min := winfit.Fit(preferred, floorMin, screen)
// 先设最小尺寸再设实际尺寸:Wails 在设置尺寸时会用最小尺寸做钳制,
// 屏幕比默认最小尺寸还小时必须先放宽下限,否则窗口压不下去。
wailsrt.WindowSetMinSize(ctx, min.Width, min.Height)
wailsrt.WindowSetSize(ctx, size.Width, size.Height)
wailsrt.WindowCenter(ctx)
desc := screenDesc(screen, physical)
if size != preferred {
a.log.Infof("屏幕 %s,窗口尺寸收敛为 %dx%d(最小 %dx%d)",
desc, size.Width, size.Height, min.Width, min.Height)
return
}
a.log.Infof("屏幕 %s,窗口尺寸 %dx%d", desc, size.Width, size.Height)
}
// currentScreenSize 返回主窗口所在屏幕的逻辑尺寸(含任务栏区域)。
//
// 优先取「窗口所在屏幕」,其次主屏,最后任意一块可用屏幕。取不到时返回 false,
// 调用方保持默认尺寸。第二个返回值是屏幕的物理尺寸,仅用于日志。
func currentScreenSize(ctx context.Context) (winfit.Size, winfit.Size, bool) {
empty := winfit.Size{}
screens, err := wailsrt.ScreenGetAll(ctx)
if err != nil || len(screens) == 0 {
return empty, empty, false
}
usable := func(i int) bool {
return screens[i].Size.Width > 0 && screens[i].Size.Height > 0
}
pick := -1
for i := range screens {
if usable(i) && screens[i].IsCurrent {
pick = i
break
}
}
if pick < 0 {
for i := range screens {
if usable(i) && screens[i].IsPrimary {
pick = i
break
}
}
}
if pick < 0 {
for i := range screens {
if usable(i) {
pick = i
break
}
}
}
if pick < 0 {
return empty, empty, false
}
s := screens[pick]
return winfit.Size{Width: s.Size.Width, Height: s.Size.Height},
winfit.Size{Width: s.PhysicalSize.Width, Height: s.PhysicalSize.Height},
true
}
// screenDesc 生成形如「2560x1440(物理 3840x2160,缩放 150%)」的描述,仅用于日志。
func screenDesc(logical, physical winfit.Size) string {
desc := fmt.Sprintf("%dx%d", logical.Width, logical.Height)
if physical.Width <= 0 || physical.Height <= 0 || logical.Width <= 0 {
return desc
}
scale := float64(physical.Width) / float64(logical.Width) * 100
if int(scale+0.5) == 100 {
return desc
}
return fmt.Sprintf("%s(物理 %dx%d,缩放 %d%%)", desc, physical.Width, physical.Height, int(scale+0.5))
}
// ResetWindow 把窗口重新收敛到当前屏幕并居中。
//
// 用途:窗口被拖到已拔掉的显示器上、或系统改过缩放比例后跑到屏幕外时,
// 从托盘菜单一键恢复。前端也可以直接调用。
func (a *App) ResetWindow() {
ctx := a.context()
if ctx == nil {
return
}
go func() {
a.fitWindow(ctx)
a.ShowWindow()
}()
}
// -----------------------------------------------------------------------------
// 窗口 / 生命周期(供前端调用)
// -----------------------------------------------------------------------------
// ShowWindow 显示主窗口。
func (a *App) ShowWindow() {
ctx := a.context()
if ctx == nil {
return
}
wailsrt.WindowUnminimise(ctx)
wailsrt.WindowShow(ctx)
a.pendingShow.Store(false)
}
// HandleSecondInstance 处理后续实例的激活请求:把主窗口带到前台。
//
// 第二份程序启动时发现已有实例,会通过 singleton 包通知本实例。若通知到达
// 时窗口尚未创建完(ctx 为空),请求会被记住,startup 末尾再补一次显示。
func (a *App) HandleSecondInstance() {
a.pendingShow.Store(true)
a.ShowWindow()
}
// HideWindow 隐藏主窗口到托盘。
func (a *App) HideWindow() {
ctx := a.context()
if ctx == nil {
return
}
wailsrt.WindowHide(ctx)
}
// QuitApp 完全退出程序。
func (a *App) QuitApp() {
a.quitting.Store(true)
a.log.Infof("正在退出 RapidProxy")
if err := a.StopService(); err != nil {
a.log.Warnf("停止服务时出错: %v", err)
}
a.cancelLogin()
a.log.Close()
if a.tray != nil {
a.tray.Quit()
}
if a.headless.Load() {
// 后台模式下没有 Wails 事件循环,直接结束进程。
os.Exit(0)
}
if ctx := a.context(); ctx != nil {
wailsrt.Quit(ctx)
return
}
os.Exit(0)
}
// runHeadless 在界面不可用时退化为后台服务,仅保留托盘与 OpenAI 接口。
func (a *App) runHeadless() {
a.headless.Store(true)
if err := a.StartService(); err != nil {
a.log.Errorf("后台模式启动代理服务失败: %v", err)
os.Exit(1)
}
a.log.Infof("已进入后台模式(无界面):接口地址 %s,可从托盘图标退出", a.settings().OpenAIBaseURL())
select {}
}
// -----------------------------------------------------------------------------
// 状态
// -----------------------------------------------------------------------------
// GetState 返回界面所需的完整状态。
func (a *App) GetState() StateView {
cfg := a.settings()
view := StateView{
Running: a.srv.Running(),
Listen: cfg.Listen,
BaseURL: cfg.BaseURL(),
OpenAIURL: cfg.OpenAIBaseURL(),
RequireKey: cfg.RequiresAPIKey(),
APIKeys: append([]string(nil), cfg.APIKeys...),
Logs: a.log.Tail(200),
Login: a.loginState(),
}
if addr := a.srv.Addr(); addr != "" {
view.Listen = addr
}
// 凭据目录只读一次,供上游列表与账号列表共用(每次 GetState 都会被调用)。
creds, _ := a.store.List("")
view.Providers = a.providerViews(creds)
view.Accounts = a.accountViews(creds)
view.Models = a.modelViews()
view.Settings = SettingsView{
Listen: cfg.Listen,
ModelSyncHours: cfg.ModelSyncHours,
CORS: cfg.CORSEnabled(),
Sanitize: cfg.SanitizeEnabled(),
MaxThinking: cfg.MaxThinkingEnabled(),
AutoStart: cfg.AutoStartEnabled(),
LaunchAtLogin: cfg.LaunchAtLoginEnabled(),
Language: cfg.Language,
ConfigPath: cfg.Path(),
DataDir: a.dataDir,
LogPath: a.log.FilePath(),
AccountDir: a.store.Root(),
Version: Version,
Platform: runtime.GOOS + "/" + runtime.GOARCH,
}
return view
}
// GetAccessInfo 返回给用户复制到其它软件的接入信息。
func (a *App) GetAccessInfo() AccessView {
cfg := a.settings()
models := a.srv.ModelIDs()
requireKey := cfg.RequiresAPIKey()
key := "<你的 API Key>"
if !requireKey {
key = "sk-any"
} else if len(cfg.APIKeys) > 0 {
key = cfg.APIKeys[0]
}
sample := fmt.Sprintf(
"curl %s/chat/completions \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer %s\" \\\n -d '{\"model\":\"%s\",\"messages\":[{\"role\":\"user\",\"content\":\"你好\"}],\"stream\":true}'",
cfg.OpenAIBaseURL(), key, firstModel(models),
)
return AccessView{
BaseURL: cfg.BaseURL(),
OpenAIURL: cfg.OpenAIBaseURL(),
APIKeys: append([]string(nil), cfg.APIKeys...),
RequireKey: requireKey,
Models: models,
Running: a.srv.Running(),
Sample: sample,
}
}
func firstModel(models []string) string {
if len(models) == 0 {
return "gpt-5.4"
}
return models[0]
}
func (a *App) providerViews(creds []*upstream.Credential) []ProviderView {
cfg := a.settings()
counts := map[string]int{}
for _, c := range creds {
counts[c.Provider]++
}
out := make([]ProviderView, 0, len(cfg.Profiles))
for _, p := range cfg.Profiles {
out = append(out, ProviderView{
ID: p.ID,
Name: p.Name,
Enabled: p.Enabled,
BaseURL: p.BaseURL,
Origin: p.Origin,
Proxy: p.Proxy,
AccountCount: counts[p.ID],
ModelCount: len(a.srv.ModelsFor(p.ID)),
NeedsProxy: strings.Contains(p.BaseURL, "workbuddy.ai"),
})
}
return out
}
func (a *App) accountViews(creds []*upstream.Credential) []AccountView {
cfg := a.settings()
names := map[string]string{}
for _, p := range cfg.Profiles {
names[p.ID] = p.Name
}
out := make([]AccountView, 0, len(creds))
for _, c := range creds {
expiresAt := c.ExpiresAtTime()
view := AccountView{
ID: c.ID,
Provider: c.Provider,
ProviderName: names[c.Provider],
Nickname: c.DisplayName(),
UID: c.Account.UID,
EnterpriseID: c.Account.EnterpriseID,
Expired: c.Expired(),
}
if view.ProviderName == "" {
view.ProviderName = c.Provider
}
if !expiresAt.IsZero() {
view.ExpiresAt = expiresAt.Format("2006-01-02 15:04")
view.ExpiresIn = humanDuration(time.Until(expiresAt))
}
if !c.CreatedAt.IsZero() {
view.CreatedAt = c.CreatedAt.Format("2006-01-02 15:04")
}
out = append(out, view)
}
sort.SliceStable(out, func(i, j int) bool {
if out[i].Provider != out[j].Provider {
return out[i].Provider < out[j].Provider
}
return out[i].CreatedAt < out[j].CreatedAt
})
return out
}
func (a *App) modelViews() []ModelView {
cfg := a.settings()
names := map[string]string{}
for _, p := range cfg.Profiles {
names[p.ID] = p.Name
}
models := a.srv.AllModels()
out := make([]ModelView, 0, len(models))
for _, m := range models {
out = append(out, ModelView{
ID: m.ID,
Name: m.DisplayName,
Provider: names[m.Provider],
Context: m.ContextLength,
MaxOut: m.MaxOutputTokens,
Images: m.SupportsImages,
})
}
return out
}
// GetLogs 返回最近日志。
func (a *App) GetLogs() []string { return a.log.Tail(300) }
// ClearLogs 清空界面上的日志。
func (a *App) ClearLogs() {
a.log.Clear()
a.pushState()
}
// -----------------------------------------------------------------------------
// 服务控制
// -----------------------------------------------------------------------------
// StartService 启动代理服务。
func (a *App) StartService() error {
if err := a.srv.Start(); err != nil {
a.log.Errorf("启动服务失败: %v", err)
a.syncTray()
a.pushState()
return err
}
a.syncTray()
a.pushState()
return nil
}
// StopService 停止代理服务。
func (a *App) StopService() error {
err := a.srv.Stop()
a.syncTray()
a.pushState()
return err
}
// ToggleService 切换服务启停,返回切换后的状态。
func (a *App) ToggleService() bool {
if a.srv.Running() {
_ = a.StopService()
} else {
_ = a.StartService()
}
return a.srv.Running()
}
// RestartService 重启服务(监听地址变更后使用)。
func (a *App) RestartService() error {
if err := a.StopService(); err != nil {
a.log.Warnf("停止服务失败: %v", err)
}
return a.StartService()
}
// RefreshModels 立即从上游同步模型列表。
func (a *App) RefreshModels() error {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
a.srv.RefreshModels(ctx)
a.pushState()
return nil
}
// -----------------------------------------------------------------------------
// API Key
// -----------------------------------------------------------------------------
// GenerateAPIKey 生成并保存一个新的 API Key。
func (a *App) GenerateAPIKey() (string, error) {
key := config.GenerateAPIKey()
if err := a.AddAPIKey(key); err != nil {
return "", err
}
return key, nil
}
// AddAPIKey 添加一个自定义 API Key。
func (a *App) AddAPIKey(key string) error {
key = strings.TrimSpace(key)
if key == "" {
return errors.New(locale.T("key.empty"))
}
cfg := a.settings().Clone()
if !cfg.AddAPIKey(key) {
return errors.New(locale.T("key.duplicate"))
}
if err := cfg.Save(); err != nil {
return err
}
a.cfgMu.Lock()
a.cfg = cfg
a.cfgMu.Unlock()
a.srv.SetConfig(cfg)
a.log.Infof("已设置 API Key(%s)", maskKey(key))
a.pushState()
return nil
}
// RemoveAPIKey 删除一个 API Key。
func (a *App) RemoveAPIKey(key string) error {
cfg := a.settings().Clone()
if !cfg.RemoveAPIKey(key) {
return errors.New(locale.T("key.notFound"))
}
if err := cfg.Save(); err != nil {
return err
}
a.cfgMu.Lock()
a.cfg = cfg
a.cfgMu.Unlock()
a.srv.SetConfig(cfg)
a.log.Infof("已删除 API Key(%s)", maskKey(key))
a.pushState()
return nil
}
func maskKey(key string) string {
// 注意:key 由用户在界面上输入,长度不可信,短 key 不能越界切片。
switch {
case len(key) <= 2:
return "****"
case len(key) <= 12:
return key[:2] + "****"
default:
return key[:10] + "****" + key[len(key)-4:]
}
}
// -----------------------------------------------------------------------------
// 账号与登录
// -----------------------------------------------------------------------------
// StartLogin 发起某个上游的登录流程。parentOrigin 是前端页面自己的 origin
// (如 http://wails.localhost),用于构造应用内 iframe 授权链接;传空则只返回外部浏览器链接。
func (a *App) StartLogin(provider, parentOrigin string) (LoginView, error) {
cfg := a.settings()
profile, ok := cfg.ProfileByID(provider)
if !ok {
return LoginView{}, fmt.Errorf("%s", locale.T("login.unknownProvider", provider))
}
client, err := a.srv.ClientFor(provider)
if err != nil {
return LoginView{}, err
}
a.cancelLogin()
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Minute)
session, err := client.StartLogin(ctx)
if err != nil {
cancel()
a.log.Errorf("[%s] 发起登录失败: %v", profile.Name, err)
return LoginView{}, err
}
run := &loginRun{
provider: provider,
session: session,
cancel: cancel,
status: "pending",
message: locale.T("login.browserOpened"),
parentOrigin: strings.TrimSpace(parentOrigin),
}
a.loginMu.Lock()
a.login = run
a.loginMu.Unlock()
// 内嵌 iframe 授权页会被上游安全策略(X-Frame-Options / CSP frame-ancestors)
// 拦截,无法在应用内显示;统一改用系统浏览器完成登录。
// 登录结果仍由后端轮询自动感知,不依赖浏览器回调。
if ctx := a.context(); ctx != nil {
wailsrt.BrowserOpenURL(ctx, session.AuthURL)
a.log.Infof("[%s] 已在系统浏览器打开登录页", profile.Name)
} else {
a.log.Warnf("[%s] 无法自动打开浏览器,请复制登录链接手动访问", profile.Name)
}
a.pushLogin()
go a.pollLogin(ctx, run)
return a.loginState(), nil
}
func (a *App) pollLogin(ctx context.Context, run *loginRun) {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
a.finishLogin(run, "failed", locale.T("login.timeout"), "")
return
case <-ticker.C:
cred, err := run.session.Poll(ctx)
if err != nil {
if errors.Is(err, upstream.ErrLoginTimeout) {
a.finishLogin(run, "failed", locale.T("login.expired"), "")
return
}
a.finishLogin(run, "failed", err.Error(), "")
return
}
if cred == nil {
continue
}
if err := a.store.Save(cred); err != nil {
a.finishLogin(run, "failed", locale.T("login.saveFailed", err.Error()), "")
return
}
a.log.Infof("登录成功: %s(%s)", cred.DisplayName(), cred.ID)
a.finishLogin(run, "success", locale.T("login.success"), cred.ID)
go func() {
refreshCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
a.srv.RefreshModels(refreshCtx)
a.pushState()
}()
return
}
}
}
func (a *App) finishLogin(run *loginRun, status, message, accountID string) {
a.loginMu.Lock()
if a.login == run {
run.status = status
run.message = message
run.accountID = accountID
if status != "pending" {
run.cancel()
}
}
a.loginMu.Unlock()
a.log.Infof("登录流程结束: %s", message)
a.pushLogin()
a.pushState()
}
func (a *App) cancelLogin() {
a.loginMu.Lock()
run := a.login
a.login = nil
a.loginMu.Unlock()
if run != nil && run.cancel != nil {
run.cancel()
}
}
// CancelLogin 取消当前登录流程。
func (a *App) CancelLogin() {
a.cancelLogin()
a.log.Infof("已取消登录")
a.pushLogin()
}
func (a *App) loginState() LoginView {
a.loginMu.Lock()
defer a.loginMu.Unlock()
if a.login == nil {
return LoginView{Status: "idle"}
}
run := a.login
view := LoginView{
Active: run.status == "pending",
Provider: run.provider,
URL: run.session.AuthURL,
EmbedURL: run.session.EmbeddedAuthURL(run.parentOrigin),
State: run.session.State,
Status: run.status,
Message: run.message,