An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Poll kernel plugin sources on macOS https://github.com/siyuan-note/siyuan/issues/18387
Daniel1ac346312438
diff --git a/kernel/plugin/manager.go b/kernel/plugin/manager.goindex f1585b5f50..a35b8e8e0a 100644--- a/kernel/plugin/manager.go+++ b/kernel/plugin/manager.go@@ -21,6 +21,7 @@ import ("path/filepath""sync""sync/atomic"+ "time""github.com/fsnotify/fsnotify""github.com/siyuan-note/logging"@@ -45,7 +46,8 @@ type PluginManager struct {context context.Context // Context for managing plugin manager lifecyclewatcher *fsnotify.Watcher // watcher for kernel plugin source file changes, to trigger hot reload- sourceWatch pluginSourceWatchState+ sourceWatch pluginSourceWatchState+ sourceWatchMode pluginSourceWatchModeplugins sync.Map // map[string]*KernelPluginpluginsMu sync.Map // map[string]*sync.Mutex, one per plugin name, to serialize start/stop of the same plugin while allowing concurrent start/stop of different plugins@@ -81,9 +83,10 @@ func InitManager() {func GetManager() *PluginManager {managerOnce.Do(func() {context := context.Background()+ sourceWatchMode := currentPluginSourceWatchMode()var watcher *fsnotify.Watcher- if isPluginFileWatchSupported() {+ if sourceWatchMode == pluginSourceWatchEvents {var err errorwatcher, err = fsnotify.NewWatcher()if err != nil {@@ -96,8 +99,9 @@ func GetManager() *PluginManager {pluginsDir: filepath.Join(util.DataDir, "plugins"),- context: context,- watcher: watcher,+ context: context,+ watcher: watcher,+ sourceWatchMode: sourceWatchMode,}manager.sourceWatch = newPluginSourceWatchState(func(name string) {petal := model.GetPetalByName(name)@@ -108,7 +112,11 @@ func GetManager() *PluginManager {model.SetPetalEnabled(petal.Name, petal.Enabled)})- if watcher != nil {+ switch sourceWatchMode {+ case pluginSourceWatchEvents:+ if watcher == nil {+ return+ }go func() {defer watcher.Close()@@ -129,6 +137,8 @@ func GetManager() *PluginManager {}}}()+ case pluginSourceWatchPolling:+ go manager.pollPluginSources(context)}})return manager@@ -345,26 +355,46 @@ func (m *PluginManager) GetLoadedPluginsInfo() (plugins []*PluginInfo) {return plugins}-// addPluginSourceWatch adds the plugin's base directory to the fsnotify watcher to watch for source file changes for hot reload.+// addPluginSourceWatch 注册插件源码监听,用于 kernel.js 热重载。func (m *PluginManager) addPluginSourceWatch(name, source string) {- if m.watcher == nil {+ if m.sourceWatchMode == pluginSourceWatchDisabled {return}path := filepath.Join(m.pluginsDir, name)- if err := m.watcher.Add(path); err != nil {- logging.LogErrorf("failed to add kernel plugin source path [%s] to watcher: %s", path, err)- return+ if m.sourceWatchMode == pluginSourceWatchEvents {+ if m.watcher == nil {+ return+ }+ if err := m.watcher.Add(path); err != nil {+ logging.LogErrorf("failed to add kernel plugin source path [%s] to watcher: %s", path, err)+ return+ }}m.sourceWatch.register(name, filepath.Join(path, "kernel.js"), source)}-// removePluginSourceWatch removes the plugin's base directory from the fsnotify watcher when the plugin is stopped.+// removePluginSourceWatch 在插件停止时移除源码监听。func (m *PluginManager) removePluginSourceWatch(name string) (err error) {m.sourceWatch.unregister(name)- if m.watcher == nil {+ if m.sourceWatchMode != pluginSourceWatchEvents || m.watcher == nil {return}path := filepath.Join(m.pluginsDir, name)err = m.watcher.Remove(path)return}++// pollPluginSources 在 macOS 上集中轮询已注册的 kernel.js。+func (m *PluginManager) pollPluginSources(ctx context.Context) {+ ticker := time.NewTicker(pluginSourcePollInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ m.sourceWatch.scan()+ }+ }+}diff --git a/kernel/plugin/source_watcher.go b/kernel/plugin/source_watcher.goindex 78e3b92506..502517b1d2 100644--- a/kernel/plugin/source_watcher.go+++ b/kernel/plugin/source_watcher.go@@ -21,6 +21,7 @@ import ("errors""os""path/filepath"+ "runtime""sync""time"@@ -29,22 +30,42 @@ import ("github.com/siyuan-note/siyuan/kernel/util")-const pluginSourceReloadDelay = 300 * time.Millisecond+const (+ pluginSourceReloadDelay = 300 * time.Millisecond+ pluginSourcePollInterval = time.Second+)var errPluginFileWatchUnsupported = errors.New("plugin file watcher is not supported on mobile")+type pluginSourceWatchMode uint8++const (+ pluginSourceWatchDisabled pluginSourceWatchMode = iota+ pluginSourceWatchEvents+ pluginSourceWatchPolling+)+type pluginSourceWatchEntry struct {path stringsignature [sha256.Size]byte+ fileState pluginSourceFileState+ lastError stringgeneration uint64timer *time.Timer}+type pluginSourceFileState struct {+ exists bool+ size int64+ modTime int64+}+type pluginSourceWatchState struct {- mu sync.Mutex- entries map[string]*pluginSourceWatchEntry- delay time.Duration- reload func(name string)+ mu sync.Mutex+ entries map[string]*pluginSourceWatchEntry+ generation uint64+ delay time.Duration+ reload func(name string)}func newPluginSourceWatchState(reload func(name string)) pluginSourceWatchState {@@ -59,16 +80,35 @@ func isPluginFileWatchSupported() bool {return !util.IsMobileContainer()}+func currentPluginSourceWatchMode() pluginSourceWatchMode {+ return selectPluginSourceWatchMode(runtime.GOOS, util.IsMobileContainer())+}++func selectPluginSourceWatchMode(goos string, mobile bool) pluginSourceWatchMode {+ if mobile {+ return pluginSourceWatchDisabled+ }+ if goos == "darwin" {+ return pluginSourceWatchPolling+ }+ return pluginSourceWatchEvents+}+func (s *pluginSourceWatchState) register(name, path, source string) {+ fileState, _ := readPluginSourceFileState(path)+s.mu.Lock()defer s.mu.Unlock()if old := s.entries[name]; old != nil && old.timer != nil {old.timer.Stop()}+ s.generation++s.entries[name] = &pluginSourceWatchEntry{- path: path,- signature: sha256.Sum256([]byte(source)),+ path: path,+ signature: sha256.Sum256([]byte(source)),+ fileState: fileState,+ generation: s.generation,}}@@ -82,6 +122,32 @@ func (s *pluginSourceWatchState) unregister(name string) {delete(s.entries, name)}+func (s *pluginSourceWatchState) scan() {+ s.mu.Lock()+ entries := make(map[string]pluginSourceWatchSnapshot, len(s.entries))+ for name, entry := range s.entries {+ entries[name] = pluginSourceWatchSnapshot{+ path: entry.path,+ generation: entry.generation,+ fileState: entry.fileState,+ }+ }+ s.mu.Unlock()++ for name, snapshot := range entries {+ fileState, err := readPluginSourceFileState(snapshot.path)+ if err != nil {+ s.logReadError(name, snapshot.generation, snapshot.path, err)+ continue+ }+ if fileState == snapshot.fileState {+ s.clearReadError(name, snapshot.generation)+ continue+ }+ s.scheduleIfCurrent(name, snapshot.generation, &fileState)+ }+}+func (s *pluginSourceWatchState) schedule(name string) {s.mu.Lock()defer s.mu.Unlock()@@ -90,17 +156,33 @@ func (s *pluginSourceWatchState) schedule(name string) {if entry == nil {return}- entry.generation+++ s.scheduleLocked(name, entry, nil)+}++func (s *pluginSourceWatchState) scheduleIfCurrent(name string, generation uint64, expected *pluginSourceFileState) {+ s.mu.Lock()+ defer s.mu.Unlock()++ entry := s.entries[name]+ if entry == nil || entry.generation != generation {+ return+ }+ s.scheduleLocked(name, entry, expected)+}++func (s *pluginSourceWatchState) scheduleLocked(name string, entry *pluginSourceWatchEntry, expected *pluginSourceFileState) {+ s.generation+++ entry.generation = s.generationgeneration := entry.generationif entry.timer != nil {entry.timer.Stop()}entry.timer = time.AfterFunc(s.delay, func() {- s.reloadIfChanged(name, generation)+ s.reloadIfChanged(name, generation, expected)})}-func (s *pluginSourceWatchState) reloadIfChanged(name string, generation uint64) {+func (s *pluginSourceWatchState) reloadIfChanged(name string, generation uint64, expected *pluginSourceFileState) {s.mu.Lock()entry := s.entries[name]if entry == nil || entry.generation != generation {@@ -111,34 +193,134 @@ func (s *pluginSourceWatchState) reloadIfChanged(name string, generation uint64)previous := entry.signatures.mu.Unlock()+ fileState, err := readPluginSourceFileState(path)+ if err != nil {+ s.finishReadError(name, generation, path, err)+ return+ }+ if expected != nil && fileState != *expected {+ s.scheduleIfCurrent(name, generation, &fileState)+ return+ }+ if !fileState.exists {+ s.finishPluginSourceCheck(name, generation, fileState, previous, false)+ return+ }+data, err := os.ReadFile(path)if err != nil {- if !os.IsNotExist(err) {- logging.LogWarnf("read kernel plugin source file [%s] failed: %s", path, err)- }+ s.finishReadError(name, generation, path, err)return}- signature := sha256.Sum256(data)- if signature == previous {+ latestFileState, err := readPluginSourceFileState(path)+ if err != nil {+ s.finishReadError(name, generation, path, err)+ return+ }+ if latestFileState != fileState {+ s.scheduleIfCurrent(name, generation, &latestFileState)return}+ signature := sha256.Sum256(data)+ s.finishPluginSourceCheck(name, generation, latestFileState, signature, signature != previous)+}++func (s *pluginSourceWatchState) finishPluginSourceCheck(+ name string,+ generation uint64,+ fileState pluginSourceFileState,+ signature [sha256.Size]byte,+ changed bool,+) {s.mu.Lock()- entry = s.entries[name]+ entry := s.entries[name]if entry == nil || entry.generation != generation {s.mu.Unlock()return}+ entry.fileState = fileState+ entry.lastError = ""entry.signature = signatureentry.timer = nilreload := s.reloads.mu.Unlock()- if reload != nil {+ if changed && reload != nil {reload(name)}}+func (s *pluginSourceWatchState) finishReadError(name string, generation uint64, path string, err error) {+ s.mu.Lock()+ entry := s.entries[name]+ if entry == nil || entry.generation != generation {+ s.mu.Unlock()+ return+ }+ entry.timer = nil+ message := err.Error()+ if entry.lastError == message {+ s.mu.Unlock()+ return+ }+ entry.lastError = message+ s.mu.Unlock()++ if !os.IsNotExist(err) {+ logging.LogWarnf("read kernel plugin source file [%s] failed: %s", path, err)+ }+}++func (s *pluginSourceWatchState) logReadError(name string, generation uint64, path string, err error) {+ s.mu.Lock()+ entry := s.entries[name]+ if entry == nil || entry.generation != generation {+ s.mu.Unlock()+ return+ }+ message := err.Error()+ if entry.lastError == message {+ s.mu.Unlock()+ return+ }+ entry.lastError = message+ s.mu.Unlock()++ logging.LogWarnf("read kernel plugin source file [%s] failed: %s", path, err)+}++func (s *pluginSourceWatchState) clearReadError(name string, generation uint64) {+ s.mu.Lock()+ defer s.mu.Unlock()++ entry := s.entries[name]+ if entry != nil && entry.generation == generation {+ entry.lastError = ""+ }+}++type pluginSourceWatchSnapshot struct {+ path string+ generation uint64+ fileState pluginSourceFileState+}++func readPluginSourceFileState(path string) (pluginSourceFileState, error) {+ info, err := os.Stat(path)+ if os.IsNotExist(err) {+ return pluginSourceFileState{}, nil+ }+ if err != nil {+ return pluginSourceFileState{}, err+ }+ return pluginSourceFileState{+ exists: true,+ size: info.Size(),+ modTime: info.ModTime().UnixNano(),+ }, nil+}+func (m *PluginManager) handlePluginSourceEvent(event fsnotify.Event) {if filepath.Base(event.Name) != "kernel.js" {returndiff --git a/kernel/plugin/watcher_test.go b/kernel/plugin/watcher_test.goindex 09c6a0478b..c429605908 100644--- a/kernel/plugin/watcher_test.go+++ b/kernel/plugin/watcher_test.go@@ -18,6 +18,7 @@ package pluginimport ("context"+ "crypto/sha256""errors""os""path/filepath"@@ -113,6 +114,122 @@ func TestHandlePluginSourceEventSupportsCombinedOperations(t *testing.T) {waitForPluginReload(t, reloaded, name)}+func TestPluginSourceWatchStateScansChangedContent(t *testing.T) {+ pluginsDir := t.TempDir()+ name := "test-plugin"+ pluginDir := filepath.Join(pluginsDir, name)+ if err := os.MkdirAll(pluginDir, 0755); err != nil {+ t.Fatal(err)+ }+ sourcePath := filepath.Join(pluginDir, "kernel.js")+ if err := os.WriteFile(sourcePath, []byte("initial"), 0644); err != nil {+ t.Fatal(err)+ }++ reloaded := make(chan string, 2)+ state := newPluginSourceWatchState(func(pluginName string) {+ reloaded <- pluginName+ })+ state.delay = 20 * time.Millisecond+ state.register(name, sourcePath, "initial")+ t.Cleanup(func() {+ state.unregister(name)+ })++ state.scan()+ state.mu.Lock()+ timer := state.entries[name].timer+ state.mu.Unlock()+ if timer != nil {+ t.Fatal("unchanged source must not schedule a content read")+ }+ expectNoPluginReload(t, reloaded)++ if err := os.WriteFile(sourcePath, []byte("changed-content"), 0644); err != nil {+ t.Fatal(err)+ }+ state.scan()+ if err := os.WriteFile(sourcePath, []byte("final-content"), 0644); err != nil {+ t.Fatal(err)+ }+ waitForPluginReload(t, reloaded, name)++ state.mu.Lock()+ signature := state.entries[name].signature+ state.mu.Unlock()+ if want := sha256.Sum256([]byte("final-content")); signature != want {+ t.Fatalf("polled source signature = %x, want %x", signature, want)+ }++ state.scan()+ expectNoPluginReload(t, reloaded)++ if err := os.Remove(sourcePath); err != nil {+ t.Fatal(err)+ }+ state.scan()+ expectNoPluginReload(t, reloaded)++ if err := os.WriteFile(sourcePath, []byte("recreated"), 0644); err != nil {+ t.Fatal(err)+ }+ state.scan()+ waitForPluginReload(t, reloaded, name)+}++func TestPluginSourceWatchStateIgnoresStaleRegistration(t *testing.T) {+ pluginsDir := t.TempDir()+ name := "test-plugin"+ sourcePath := filepath.Join(pluginsDir, "kernel.js")+ if err := os.WriteFile(sourcePath, []byte("initial"), 0644); err != nil {+ t.Fatal(err)+ }++ reloaded := make(chan string, 1)+ state := newPluginSourceWatchState(func(pluginName string) {+ reloaded <- pluginName+ })+ state.register(name, sourcePath, "initial")+ state.mu.Lock()+ staleGeneration := state.entries[name].generation+ state.mu.Unlock()++ state.unregister(name)+ state.register(name, sourcePath, "initial")+ t.Cleanup(func() {+ state.unregister(name)+ })++ if err := os.WriteFile(sourcePath, []byte("changed"), 0644); err != nil {+ t.Fatal(err)+ }+ state.reloadIfChanged(name, staleGeneration, nil)+ expectNoPluginReload(t, reloaded)+}++func TestSelectPluginSourceWatchMode(t *testing.T) {+ tests := []struct {+ name string+ goos string+ mobile bool+ want pluginSourceWatchMode+ }{+ {name: "windows", goos: "windows", want: pluginSourceWatchEvents},+ {name: "linux", goos: "linux", want: pluginSourceWatchEvents},+ {name: "darwin", goos: "darwin", want: pluginSourceWatchPolling},+ {name: "darwin mobile", goos: "darwin", mobile: true, want: pluginSourceWatchDisabled},+ {name: "android", goos: "android", mobile: true, want: pluginSourceWatchDisabled},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if got := selectPluginSourceWatchMode(test.goos, test.mobile); got != test.want {+ t.Fatalf("selectPluginSourceWatchMode(%q, %t) = %d, want %d", test.goos, test.mobile, got, test.want)+ }+ })+ }+}+func TestStorageWatcherIsCreatedLazilyAndClosedIdempotently(t *testing.T) {ctx, cancel := context.WithCancel(context.Background())storageDir := t.TempDir()