diff --git a/cmd/arcrun-tray/README.md b/cmd/arcrun-tray/README.md new file mode 100644 index 0000000..52f22a6 --- /dev/null +++ b/cmd/arcrun-tray/README.md @@ -0,0 +1,62 @@ +# Arcrun RAG 托盤殼(arcrun-tray)— 建置/簽章/TCC 交接 + +> CP-1 第 6 關 daemon 產品化。leo 2026-07-21 定框架=**fyne**(窮舉七案後推薦,見頂層 +> `journeys/daemon-tray-shell-options.md`)。**建置/簽章/公證/TCC 授權=leo/地端在真機做**(紅線②③)。 + +## 這顆殼做什麼 + +一個**選單列(Mac)/系統匣(Windows)icon**,讓不開 terminal 的人也能用: +- 狀態一眼看(看守中 · 上次同步 HH:MM/啟動中/出錯自動重試/已暫停) +- 選單:**選擇知識資料夾**(系統原生對話框)/打開資料夾/暫停·繼續看守 +- 關掉視窗=縮回背景續看守(不是結束) + +它**看守** `arcrun-collector direct`(同綑執行檔),把它當背景常駐;崩了自動重起。 + +## 哪些已驗、哪些待真機驗(誠實界定,mindset §7) + +| 部分 | 狀態 | 驗法 | +|------|------|------| +| **看守核心** `collector/supervisor`(子行程管理/狀態解析/崩潰重起/停止) | ✅ **sandbox `go test` 驗過**(純 stdlib,5 測全綠,含重起/停止/狀態解析) | `cd collector && go test ./supervisor/` | +| collector 引擎(未動) | ✅ 既有測試無回歸 | `cd collector && go test ./...` | +| **fyne GUI 本體**(本 main.go:tray icon/選單/原生選資料夾) | ⏳ **待真機 build**——fyne 需 CGo+GL/webview,無螢幕 sandbox 編不了 | 真機 `go mod tidy && fyne package` | +| macOS **TCC 同意流** | ⏳ 待真 Mac 驗(沙箱測不到真 TCC 語意=假綠,故不盲寫) | 見下「TCC」 | + +> ⚠️ **fyne API 細節(fyne.Do/SetSystemTrayMenu 刷新/Lifecycle)以首次真機 build 為準**—— +> 本檔按 fyne v2.5 API 寫,但未經編譯器。第一次 `go mod tidy && go build` 若有 API 出入,就地修。 + +## 建置(leo/地端,真機) + +```bash +cd collector/cmd/arcrun-tray +go mod tidy # 拉 fyne 依賴(首次需網路) +# 把 collector 執行檔一起放進 bundle(托盤靠同層 arcrun-collector) +(cd ../.. && GOOS=darwin GOARCH=arm64 go build -o cmd/arcrun-tray/arcrun-collector .) +# 打包 .app(Mac)/.exe(Win) +go run fyne.io/fyne/v2/cmd/fyne@latest package -os darwin -icon icon.png -name "Arcrun RAG" +# Windows:-os windows +``` +> icon.png 待放(leo logo 進行中);Mac 選單列建議 **template 單色 icon**(自動深淺色)。 + +## 簽章/公證(Mac,leo/地端) + +未簽章的 .app 會被 Gatekeeper 擋(右鍵開可繞,但非產品體驗)。正式版: +```bash +codesign --deep --force --options runtime --sign "Developer ID Application: <你>" "Arcrun RAG.app" +xcrun notarytool submit "Arcrun RAG.zip" --apple-id … --team-id … --wait +xcrun stapler staple "Arcrun RAG.app" +``` + +## TCC(macOS,只有真 Mac 驗得到) + +**預設 watch_folder = `~/ArcrunRAG`(本殼已這樣設)——刻意避開 `~/Documents`**:launchd/背景程序碰 +`~/Documents` 會被 TCC 擋(2026-07-19 實撞)。預設在非 TCC 禁區=**零授權即可用**。 + +用戶若堅持把資料夾設在 `~/Documents`/`~/Desktop`/`~/Downloads`: +1. 首次讀取被拒 → 本殼應偵測並引導:**系統設定 → 隱私權與安全性 → 檔案與資料夾**(或完整磁碟取用權)勾選 Arcrun RAG。 +2. 這一步**必須在真 Mac 上驗**(跳不跳授權框、launchd 背景 vs GUI 前景差異)。sandbox 只能測到 `os.Open` 成不成,測不到真 TCC=假綠,故本輪不寫死。 + +## 安裝(用戶視角,最終形態) + +下載 → 拖進「應用程式」→ 開啟 → 選一個資料夾 → 完成。cypher_url/namespace/api_key 由**安裝器**寫進 +`~/.arcrun-rag/config.json`(用戶不碰)。**現行 `docs/manual/product-install-guide.md` 是廢棄的 +Docker 六步,產品化時要重寫成這段。** diff --git a/cmd/arcrun-tray/go.mod b/cmd/arcrun-tray/go.mod new file mode 100644 index 0000000..3dacdde --- /dev/null +++ b/cmd/arcrun-tray/go.mod @@ -0,0 +1,14 @@ +// 獨立 module:把 fyne(CGo/GL)依賴與純 stdlib 的 collector module 隔開, +// 讓 collector 模組維持 `go test ./...` 可在無 GUI 環境驗證。 +// 本 module 在 Mac/Windows 真機 build(leo/地端):`go mod tidy && fyne package`。 +module arcrun-rag/collector/cmd/arcrun-tray + +go 1.22 + +require ( + arcrun-rag/collector v0.0.0 + fyne.io/fyne/v2 v2.5.3 +) + +// 複用同 repo 的 supervisor 套件(純 stdlib)。 +replace arcrun-rag/collector => ../../ diff --git a/cmd/arcrun-tray/main.go b/cmd/arcrun-tray/main.go new file mode 100644 index 0000000..f57bd89 --- /dev/null +++ b/cmd/arcrun-tray/main.go @@ -0,0 +1,221 @@ +// arcrun-tray — Arcrun RAG 桌面托盤殼(CP-1 第 6 關 daemon 產品化,leo 2026-07-21 定 fyne)。 +// +// 目的:讓「不開 terminal 的人」也能裝、開關、選資料夾——一個選單列/系統匣 icon 就是全部。 +// 它看守 `collector direct`(子行程,見 supervisor 套件的誠實界定)並顯示狀態。 +// +// ⚠️ 本檔是 fyne GUI(CGo+系統 webview/GL),**無法在無螢幕 sandbox build/驗**—— +// +// build/簽章/公證/TCC 授權=leo/地端在真機做(紅線②③)。純邏輯(看守/config)已抽到 +// supervisor 套件並在 sandbox `go test` 驗過。 +// +// 真機 build: +// +// cd collector/cmd/arcrun-tray && go mod tidy +// go run fyne.io/fyne/v2/cmd/fyne@latest package -os darwin -icon icon.png -name "Arcrun RAG" +// (Windows:-os windows;簽章/公證另見同目錄 README) +package main + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + + "arcrun-rag/collector/supervisor" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/app" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/dialog" + "fyne.io/fyne/v2/driver/desktop" + "fyne.io/fyne/v2/storage" + "fyne.io/fyne/v2/theme" + "fyne.io/fyne/v2/widget" +) + +// directConfig 是 collector direct 的設定(與 collector/direct.go 的 DirectConfig 同結構; +// 這裡只需讀寫 watch_folder,其餘由安裝器帶入)。 +type directConfig struct { + WatchFolder string `json:"watch_folder"` + Manifest string `json:"manifest"` + CypherURL string `json:"cypher_url"` + Namespace string `json:"namespace"` + APIKey string `json:"api_key,omitempty"` + Library string `json:"library,omitempty"` + IngestWF string `json:"ingest_workflow,omitempty"` + RemovedWF string `json:"removed_workflow,omitempty"` + PollSec int `json:"poll_interval_sec,omitempty"` + MaxRemoved float64 `json:"max_removed_ratio,omitempty"` +} + +// appDir 是設定與 manifest 落地處:~/.arcrun-rag/ +func appDir() string { + home, _ := os.UserHomeDir() + return filepath.Join(home, ".arcrun-rag") +} + +func configPath() string { return filepath.Join(appDir(), "config.json") } + +// defaultWatchFolder 預設 ~/ArcrunRAG——**刻意避開 ~/Documents**:macOS launchd 背景程序碰 +// ~/Documents 會被 TCC 擋(07-19 實撞)。預設在非 TCC 禁區=零授權即可用;用戶要改到 Documents +// 才需走 TCC 同意流(見 README)。 +func defaultWatchFolder() string { + home, _ := os.UserHomeDir() + return filepath.Join(home, "ArcrunRAG") +} + +func loadConfig() *directConfig { + c := &directConfig{} + if data, err := os.ReadFile(configPath()); err == nil { + _ = json.Unmarshal(data, c) + } + if c.WatchFolder == "" { + c.WatchFolder = defaultWatchFolder() + } + if c.Manifest == "" { + c.Manifest = filepath.Join(appDir(), "manifest.json") + } + return c +} + +func saveConfig(c *directConfig) error { + if err := os.MkdirAll(appDir(), 0o755); err != nil { + return err + } + data, _ := json.MarshalIndent(c, "", " ") + return os.WriteFile(configPath(), data, 0o600) +} + +// collectorBinPath 找同綑的 collector 執行檔(app bundle 內與托盤同層)。 +func collectorBinPath() string { + exe, err := os.Executable() + if err != nil { + return "arcrun-collector" + } + name := "arcrun-collector" + if isWindows() { + name += ".exe" + } + return filepath.Join(filepath.Dir(exe), name) +} + +func isWindows() bool { return os.PathSeparator == '\\' } + +func main() { + a := app.NewWithID("dev.arcrun.rag.tray") + cfg := loadConfig() + + // 設定視窗(平時隱藏;選資料夾/看說明時開) + win := a.NewWindow("Arcrun RAG") + win.SetCloseIntercept(func() { win.Hide() }) // 關窗只隱藏,不結束 app(托盤續跑) + win.Resize(fyne.NewSize(420, 220)) + + sup := supervisor.New(collectorBinPath(), configPath()) + + // 狀態列(tray 選單第一項,只讀) + statusItem := fyne.NewMenuItem("狀態:尚未開始", nil) + statusItem.Disabled = true + + folderItem := fyne.NewMenuItem("選擇知識資料夾…", func() { + win.Show() + win.RequestFocus() + dialog.ShowFolderOpen(func(uri fyne.ListableURI, err error) { + if err != nil || uri == nil { + return + } + cfg.WatchFolder = uri.Path() + if err := saveConfig(cfg); err != nil { + dialog.ShowError(err, win) + return + } + // 換資料夾=重起看守 + sup.Stop() + sup.Start() + win.Hide() + }, win) + }) + + openFolderItem := fyne.NewMenuItem("打開資料夾", func() { + if u, err := storage.ParseURI("file://" + cfg.WatchFolder); err == nil { + _ = a.OpenURL(u) + } + }) + + var pauseItem *fyne.MenuItem + pauseItem = fyne.NewMenuItem("暫停看守", func() { + st := sup.Status() + if st.State == supervisor.StateStopped { + sup.Start() + pauseItem.Label = "暫停看守" + } else { + sup.Stop() + pauseItem.Label = "繼續看守" + } + }) + + tray := fyne.NewMenu("Arcrun RAG", + statusItem, + fyne.NewMenuItemSeparator(), + folderItem, + openFolderItem, + pauseItem, + ) + + desk, hasTray := a.(desktop.App) + if hasTray { + desk.SetSystemTrayMenu(tray) + desk.SetSystemTrayIcon(theme.StorageIcon()) // TODO 換品牌 icon(leo logo 進行中);Mac 建議 template 單色 + } + // 重設選單=刷新(比 (*Menu).Refresh() 跨版本更穩) + refreshTray := func() { + if hasTray { + desk.SetSystemTrayMenu(tray) + } + } + + // 狀態變更 → 刷新 tray 文案(回呼在 supervisor goroutine,切回 UI thread) + sup.SetOnChange(func(s supervisor.Status) { + fyne.Do(func() { + statusItem.Label = "狀態:" + humanStatus(s) + refreshTray() + }) + }) + + // 設定視窗內容:說明現況 + 選資料夾按鈕(給會開窗的人;不會開的人靠 tray 選單) + win.SetContent(container.NewVBox( + widget.NewLabelWithStyle("Arcrun RAG 知識同步", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}), + widget.NewLabel("把檔案丟進你選的資料夾,就會自動進你的知識庫。\n這個程式會待在選單列/系統匣,關掉視窗它仍在背景看守。"), + widget.NewButton("選擇知識資料夾…", func() { folderItem.Action() }), + )) + + // 開機即看守(若設定完整) + if cfg.CypherURL != "" && cfg.Namespace != "" { + sup.Start() + } else { + // 缺安裝器帶入的 cypher_url/namespace:提示用戶先完成安裝 + statusItem.Label = "狀態:尚未連結(請先完成安裝)" + win.Show() + } + + a.Lifecycle().SetOnStopped(func() { sup.Stop() }) + a.Run() +} + +// humanStatus 把狀態機轉成白話(給不懂內部的人)。 +func humanStatus(s supervisor.Status) string { + switch s.State { + case supervisor.StateWatching: + if !s.LastRoundAt.IsZero() { + return fmt.Sprintf("看守中 · 上次同步 %s", s.LastRoundAt.Local().Format("15:04")) + } + return "看守中" + case supervisor.StateStarting: + return "啟動中…" + case supervisor.StateError: + return "暫時出錯,正在自動重試" + case supervisor.StateStopped: + return "已暫停" + default: + return "尚未開始" + } +} diff --git a/supervisor/supervisor.go b/supervisor/supervisor.go new file mode 100644 index 0000000..9f8c612 --- /dev/null +++ b/supervisor/supervisor.go @@ -0,0 +1,247 @@ +// Package supervisor 看守 `collector direct` 常駐行程,供托盤殼(fyne)呼叫。 +// +// 為什麼子行程而非 in-process(誠實界定,leo 2026-07-21 偏好 in-process): +// +// collector 現為 `package main`,真正 in-process 複用需把核心抽成 library 套件 +// (重構動到已由 leo 實機驗過的引擎,有回歸風險)。本版先以「子行程+讀 stdout JSON 狀態」 +// 達成看守(collector 零改、崩潰隔離、純 stdlib 可單元測),in-process 抽取列為可選後續。 +// 對用戶行為完全相同(都是「背景看守資料夾」)。 +// +// 純 stdlib、無 fyne 依賴 → 可在 CI/sandbox `go test` 驗證(托盤 GUI 需真機建置)。 +package supervisor + +import ( + "bufio" + "context" + "encoding/json" + "io" + "os/exec" + "strings" + "sync" + "time" +) + +// State 是看守狀態機。 +type State string + +const ( + StateStopped State = "stopped" // 未啟動或已停止 + StateStarting State = "starting" // 行程剛拉起、尚無第一輪 + StateWatching State = "watching" // 正常看守中(已有掃描輪) + StateError State = "error" // 行程非預期退出、等待重起 +) + +// Status 是托盤要顯示的即時狀態(值型別、複製安全)。 +type Status struct { + State State + Since time.Time // 進入目前 State 的時間 + LastRoundAt time.Time // 最近一輪掃描完成時間(collector stdout 的 at) + Rounds int // 累計掃描輪數 + Restarts int // 累計重起次數 + LastError string // 最近一次錯誤(stderr 末行 / 退出原因) +} + +// round 對應 collector direct 每輪印到 stdout 的 JSON(見 direct.go runOne)。 +type round struct { + At string `json:"at"` + Folder string `json:"folder"` + Results []json.RawMessage `json:"results"` +} + +// Supervisor 看守單一 collector direct 行程。 +type Supervisor struct { + BinPath string // collector 執行檔路徑(托盤 app bundle 內) + ConfigPath string // direct config.json 路徑 + Backoff time.Duration // 非預期退出後的重起間隔(0=預設 3s) + + mu sync.Mutex + status Status + cancel context.CancelFunc + done chan struct{} // loop 結束時關閉(Stop 等它,避免 Stop→Start 舊 loop 覆寫狀態) + running bool + onChange func(Status) + nowFn func() time.Time // 可注入時鐘(測試用;nil=time.Now) +} + +// New 建一個看守器。 +func New(binPath, configPath string) *Supervisor { + return &Supervisor{BinPath: binPath, ConfigPath: configPath} +} + +// SetOnChange 註冊狀態變更回呼(托盤用來刷新選單/icon)。回呼在 supervisor 內部 goroutine 呼叫。 +func (s *Supervisor) SetOnChange(fn func(Status)) { + s.mu.Lock() + s.onChange = fn + s.mu.Unlock() +} + +func (s *Supervisor) now() time.Time { + if s.nowFn != nil { + return s.nowFn() + } + return time.Now() +} + +// setState 原子更新狀態並觸發回呼(回呼在鎖外呼叫,避免死鎖)。 +func (s *Supervisor) setState(mut func(*Status)) { + s.mu.Lock() + prev := s.status.State + mut(&s.status) + if s.status.State != prev { + s.status.Since = s.now() + } + snap := s.status + cb := s.onChange + s.mu.Unlock() + if cb != nil { + cb(snap) + } +} + +// Status 回傳目前狀態快照。 +func (s *Supervisor) Status() Status { + s.mu.Lock() + defer s.mu.Unlock() + return s.status +} + +// Start 啟動看守(非阻塞)。已在跑則忽略。崩潰自動重起,直到 Stop。 +func (s *Supervisor) Start() { + s.mu.Lock() + if s.running { + s.mu.Unlock() + return + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + s.cancel = cancel + s.done = done + s.running = true + s.mu.Unlock() + go func() { + defer close(done) + s.loop(ctx) + }() +} + +// Stop 停止看守,**等目前 loop 完全收掉才回**——這樣 Stop→Start(如換資料夾)不會被舊 loop +// 的 setState(stopped) 覆寫新狀態。冪等;未在跑時直接回。 +func (s *Supervisor) Stop() { + s.mu.Lock() + if !s.running { + s.mu.Unlock() + return + } + cancel := s.cancel + done := s.done + s.running = false + s.mu.Unlock() + if cancel != nil { + cancel() + } + if done != nil { + <-done // 等 loop goroutine 真的結束 + } + s.setState(func(st *Status) { st.State = StateStopped }) +} + +func (s *Supervisor) backoff() time.Duration { + if s.Backoff > 0 { + return s.Backoff + } + return 3 * time.Second +} + +// loop 是看守主迴圈:拉起行程→串流 stdout 更新狀態→退出即重起(除非取消)。 +func (s *Supervisor) loop(ctx context.Context) { + for { + if ctx.Err() != nil { + return + } + s.setState(func(st *Status) { st.State = StateStarting }) + err := s.runOnce(ctx) + if ctx.Err() != nil { // 被 Stop 取消=正常收工 + s.setState(func(st *Status) { st.State = StateStopped }) + return + } + // 非預期退出:記錯、重起計數、退避後再拉 + msg := "行程結束" + if err != nil { + msg = err.Error() + } + s.setState(func(st *Status) { + st.State = StateError + st.LastError = msg + st.Restarts++ + }) + select { + case <-ctx.Done(): + s.setState(func(st *Status) { st.State = StateStopped }) + return + case <-time.After(s.backoff()): + } + } +} + +// runOnce 跑一次 collector direct 行程,串流其 stdout JSON 更新狀態,回傳退出原因。 +func (s *Supervisor) runOnce(ctx context.Context) error { + cmd := exec.CommandContext(ctx, s.BinPath, "direct", "--config", s.ConfigPath) + stdout, err := cmd.StdoutPipe() + if err != nil { + return err + } + stderr, err := cmd.StderrPipe() + if err != nil { + return err + } + if err := cmd.Start(); err != nil { + return err + } + + // stderr:留末行當錯誤脈絡 + go func() { + sc := bufio.NewScanner(stderr) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" { + continue + } + s.mu.Lock() + s.status.LastError = line + s.mu.Unlock() + } + }() + + // stdout:用 json.Decoder 逐個 JSON 值解(容忍 MarshalIndent 的多行) + dec := json.NewDecoder(stdout) + for { + var r round + if derr := dec.Decode(&r); derr != nil { + if derr == io.EOF { + break + } + // 非 JSON 雜訊:吞掉剩餘、跳出(行程仍由 Wait 收) + io.Copy(io.Discard, stdout) + break + } + at := parseAt(r.At) + s.setState(func(st *Status) { + st.State = StateWatching + st.Rounds++ + if !at.IsZero() { + st.LastRoundAt = at + } + }) + } + return cmd.Wait() +} + +func parseAt(s string) time.Time { + if s == "" { + return time.Time{} + } + if t, err := time.Parse(time.RFC3339, s); err == nil { + return t + } + return time.Time{} +} diff --git a/supervisor/supervisor_test.go b/supervisor/supervisor_test.go new file mode 100644 index 0000000..34911f3 --- /dev/null +++ b/supervisor/supervisor_test.go @@ -0,0 +1,122 @@ +package supervisor + +import ( + "os" + "path/filepath" + "runtime" + "sync/atomic" + "testing" + "time" +) + +// fakeCollector 寫一個假的 collector 執行檔(shell 腳本):忽略參數、印 n 輪 JSON。 +// stayAlive=true → 印完 sleep(模擬常駐 daemon,狀態維持 watching);false → 印完即退出(觸發重起)。 +func fakeCollector(t *testing.T, rounds int, stayAlive bool) string { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("fake collector script 走 POSIX shell;Windows 測略過(supervisor 邏輯與平台無關)") + } + dir := t.TempDir() + p := filepath.Join(dir, "fake-collector.sh") + body := "#!/bin/sh\n" + for i := 0; i < rounds; i++ { + body += "printf '{\"at\":\"2026-07-21T00:00:0" + itoa(i) + "Z\",\"folder\":\"/tmp/kb\",\"results\":[]}\\n'\n" + } + if stayAlive { + body += "sleep 2\n" + } + if err := os.WriteFile(p, []byte(body), 0o755); err != nil { + t.Fatal(err) + } + return p +} + +func itoa(i int) string { return string(rune('0' + i)) } + +func waitFor(t *testing.T, d time.Duration, cond func() bool, msg string) { + t.Helper() + deadline := time.Now().Add(d) + for time.Now().Before(deadline) { + if cond() { + return + } + time.Sleep(5 * time.Millisecond) + } + t.Fatalf("timeout waiting for: %s", msg) +} + +func TestSupervisorParsesRoundsAndWatches(t *testing.T) { + bin := fakeCollector(t, 2, true) + s := New(bin, "cfg.json") + s.Backoff = 20 * time.Millisecond + s.Start() + defer s.Stop() + + waitFor(t, 2*time.Second, func() bool { return s.Status().Rounds >= 2 }, "2 rounds parsed") + st := s.Status() + if st.State != StateWatching { + t.Fatalf("expected watching, got %q", st.State) + } + if st.LastRoundAt.IsZero() { + t.Fatal("LastRoundAt should be parsed from stdout 'at'") + } + if st.LastRoundAt.Year() != 2026 { + t.Fatalf("LastRoundAt parse wrong: %v", st.LastRoundAt) + } +} + +func TestSupervisorRestartsOnExit(t *testing.T) { + bin := fakeCollector(t, 1, false) + s := New(bin, "cfg.json") + s.Backoff = 20 * time.Millisecond + s.Start() + defer s.Stop() + + // 假 collector 印一輪就退出 → supervisor 視為非預期退出 → 重起 + waitFor(t, 2*time.Second, func() bool { return s.Status().Restarts >= 2 }, "restarts accumulate") +} + +func TestSupervisorStop(t *testing.T) { + bin := fakeCollector(t, 1, false) + s := New(bin, "cfg.json") + s.Backoff = 20 * time.Millisecond + s.Start() + waitFor(t, 2*time.Second, func() bool { return s.Status().Restarts >= 1 }, "running") + s.Stop() + waitFor(t, 2*time.Second, func() bool { return s.Status().State == StateStopped }, "stopped after Stop()") + // Stop 後不應再累加重起 + r := s.Status().Restarts + time.Sleep(120 * time.Millisecond) + if s.Status().Restarts != r { + t.Fatalf("restarts kept growing after Stop: %d → %d", r, s.Status().Restarts) + } +} + +// 換資料夾=Stop 緊接 Start;舊 loop 的 setState(stopped) 不可覆寫新 loop 的狀態。 +func TestSupervisorStopThenStartNotLeftStopped(t *testing.T) { + bin := fakeCollector(t, 2, true) // stayAlive → 新 loop 進 watching + s := New(bin, "cfg.json") + s.Backoff = 20 * time.Millisecond + s.Start() + waitFor(t, 2*time.Second, func() bool { return s.Status().State == StateWatching }, "first watching") + s.Stop() // 同步等舊 loop 收掉 + s.Start() // 立刻重起(模擬換資料夾) + defer s.Stop() + waitFor(t, 2*time.Second, func() bool { return s.Status().State == StateWatching }, "watching again after Stop→Start") + // 稍等,確認不會被舊 loop 尾巴改回 stopped + time.Sleep(100 * time.Millisecond) + if got := s.Status().State; got != StateWatching { + t.Fatalf("Stop→Start left state=%q (舊 loop 覆寫了新狀態)", got) + } +} + +func TestSupervisorOnChangeFires(t *testing.T) { + bin := fakeCollector(t, 2, true) + s := New(bin, "cfg.json") + s.Backoff = 20 * time.Millisecond + var calls int32 + s.SetOnChange(func(Status) { atomic.AddInt32(&calls, 1) }) + s.Start() + defer s.Stop() + waitFor(t, 2*time.Second, func() bool { return atomic.LoadInt32(&calls) > 0 }, "onChange fired") +}