package app import ( "context" "strconv" "sync" "time" "mygoland/internal/ai" "mygoland/internal/godoc" ) // preheatWorkers 是预热时的并发翻译数:免费接口也扛得住,太猛会限流。 const preheatWorkers = 6 // preheatState 是标准库文档预热的进度。 type preheatState struct { running bool done int total int pkg string } // PreheatDocs 是预热的线程安全入口:菜单点击(主线程)与定时器 // (任意 goroutine)都能调,UI 状态操作统一投递到主线程执行。 // 直接在非主线程改 a.out/a.panel 会跟主线程竞争——闪退就是这么来的。 func (a *App) PreheatDocs() { if a.win == nil { return } a.win.Update(a.startPreheat) } // startPreheat 预热主流程,假定已在主线程。 func (a *App) startPreheat() { if !a.translateOn() { a.out = append(a.out, OutLine{Text: "AI 预热:请先在设置里配好「文档翻译」接口", Kind: OutWarn}) a.panel, a.panelTab = true, 0 a.refresh() return } if a.preheat.running { return } a.preheat.running = true a.panel, a.panelTab = true, 0 a.out = append(a.out, OutLine{Text: "AI 预热:开始翻译标准库文档(已缓存的自动跳过)", Kind: OutWarn}) a.refresh() cfg := a.aiConfig() start := time.Now() jobs := make(chan string, 64) var wg sync.WaitGroup for i := 0; i < preheatWorkers; i++ { wg.Add(1) go func() { defer wg.Done() for text := range jobs { a.preheatOne(cfg, text) } }() } go func() { defer close(jobs) pkgs := 0 for _, p := range godoc.CommonPkgs { docs, err := godoc.Docs(p) if err != nil { a.win.Update(func() { a.out = append(a.out, OutLine{Text: "AI 预热:跳过 " + p + "(" + firstLine(err.Error()) + ")", Kind: OutWarn}) a.refresh() }) continue } pkgs++ // 读 a.trans(过滤已缓存)只能在主线程;过滤结果经 channel // 交给本 goroutine 再灌 worker 队列——主线程绝不阻塞等 LLM。 listCh := make(chan []string, 1) a.win.Update(func() { a.preheat.pkg = p var list []string for _, d := range docs { k := normDocKey(d) if _, ok := a.trans[k]; ok { continue } if a.preheatInflight == nil { a.preheatInflight = map[string]bool{} } if a.preheatInflight[k] { continue } a.preheatInflight[k] = true a.preheat.total++ list = append(list, d) } a.refresh() listCh <- list }) for _, d := range <-listCh { jobs <- d } } wg.Wait() a.win.Update(func() { a.preheat.running = false a.saveTranslations() a.out = append(a.out, OutLine{ Text: "✔ AI 预热完成:新增 " + strconv.Itoa(a.preheat.done) + " 条译文,覆盖 " + strconv.Itoa(pkgs) + " 个包,耗时 " + time.Since(start).Round(time.Second).String(), Kind: OutSuccess, }) a.preheat = preheatState{} a.refresh() }) }() } // preheatOne 翻译一条并回主线程入缓存。 func (a *App) preheatOne(cfg ai.Config, text string) { ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) defer cancel() tr, err := ai.TranslateDoc(ctx, cfg, text) a.win.Update(func() { k := normDocKey(text) delete(a.preheatInflight, k) a.preheat.done++ if err != nil || tr == "" { // 失败不写哨兵:预热是尽力而为,下次预热还能重试。 return } if a.trans == nil { a.trans = map[string]string{} } a.trans[k] = tr if a.preheat.done%40 == 0 { a.saveTranslations() // 阶段落盘,中途退出也不白翻。 } a.refresh() }) }