An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Improve cleanup of outdated installer packages https://github.com/siyuan-note/siyuan/issues/19731
Danielf63c8110ee52
diff --git a/kernel/model/assets_test.go b/kernel/model/assets_test.goindex 939a253d93..b91d1c8a70 100644--- a/kernel/model/assets_test.go+++ b/kernel/model/assets_test.go@@ -156,7 +156,7 @@ func TestClearWorkspaceTempRemovesImageOperations(t *testing.T) {t.Fatal(err)}- clearWorkspaceTemp(false)+ clearWorkspaceTemp("")if _, err := os.Stat(operationDir); !os.IsNotExist(err) {t.Fatalf("image operation directory was not removed: %v", err)}@@ -171,7 +171,7 @@ func TestClearWorkspaceTempPreservesInstallPackages(t *testing.T) {util.DataDir = filepath.Join(root, "data")util.TempDir = filepath.Join(root, "temp")util.WorkspaceDir = root- installPkgPath := filepath.Join(util.TempDir, "install", "siyuan-test-win.exe")+ installPkgPath := filepath.Join(util.TempDir, "install", "siyuan-0.0.1-win.exe")if err := os.MkdirAll(filepath.Dir(installPkgPath), 0755); err != nil {t.Fatal(err)}@@ -183,11 +183,11 @@ func TestClearWorkspaceTempPreservesInstallPackages(t *testing.T) {t.Fatal(err)}- clearWorkspaceTemp(true)+ clearWorkspaceTemp(installPkgPath)if _, err := os.Stat(installPkgPath); err != nil {t.Fatalf("install package should be preserved during update: %v", err)}- clearWorkspaceTemp(false)+ clearWorkspaceTemp("")if _, err := os.Stat(installPkgPath); !os.IsNotExist(err) {t.Fatalf("old install package should be removed during normal exit: %v", err)}diff --git a/kernel/model/box_temp_test.go b/kernel/model/box_temp_test.goindex 010a148358..c4f48c14bc 100644--- a/kernel/model/box_temp_test.go+++ b/kernel/model/box_temp_test.go@@ -71,7 +71,7 @@ func TestClearWorkspaceTempRemovesLegacyPandoc(t *testing.T) {t.Fatal(err)}- clearWorkspaceTemp(false)+ clearWorkspaceTemp("")if _, err := os.Stat(pandocDir); !os.IsNotExist(err) {t.Fatalf("legacy Pandoc temporary directory was not removed on exit: %v", err)diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 5d19a3ab4b..2a88f071f0 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -241,6 +241,7 @@ func InitConf() {Conf = NewAppConf()clearEncryptedExportTempOnBoot()+ clearOldInstallPackages("")confPath := filepath.Join(util.ConfDir, "conf.json")confFileExists := gulu.File.IsExist(confPath)entryVisibilityConfigured := false@@ -1086,7 +1087,7 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, isql.CloseDatabase()closePushQueue()util.SaveAssetsTexts()- clearWorkspaceTemp("" != installPkgPath)+ clearWorkspaceTemp(installPkgPath)clearCorruptedNotebooks()clearPortJSON()@@ -1504,7 +1505,7 @@ func clearCorruptedNotebooks() {}}-func clearWorkspaceTemp(preserveInstallPkgs bool) {+func clearWorkspaceTemp(preserveInstallPkgPath string) {heif.ClearMemoryCache("")os.RemoveAll(filepath.Join(util.TempDir, "assets-cache"))os.RemoveAll(filepath.Join(util.TempDir, "bazaar"))@@ -1518,25 +1519,7 @@ func clearWorkspaceTemp(preserveInstallPkgs bool) {os.RemoveAll(filepath.Join(util.TempDir, "base64"))os.RemoveAll(filepath.Join(util.TempDir, "ai"))- // 退出时自动删除超过 7 天的安装包 https://github.com/siyuan-note/siyuan/issues/6128- install := filepath.Join(util.TempDir, "install")- if !preserveInstallPkgs && gulu.File.IsDir(install) {- monthAgo := time.Now().Add(-time.Hour * 24 * 7)- entries, err := os.ReadDir(install)- if err != nil {- logging.LogErrorf("read dir [%s] failed: %s", install, err)- } else {- for _, entry := range entries {- info, _ := entry.Info()- if nil != info && !info.IsDir() && info.ModTime().Before(monthAgo) {- installPkgPath := filepath.Join(install, entry.Name())- if err = os.RemoveAll(installPkgPath); err != nil {- logging.LogErrorf("remove old install pkg [%s] failed: %s", installPkgPath, err)- }- }- }- }- }+ clearOldInstallPackages(preserveInstallPkgPath)tmps, err := filepath.Glob(filepath.Join(util.TempDir, "*.tmp"))if err != nil {diff --git a/kernel/model/updater.go b/kernel/model/updater.goindex 8a39a626b1..c639c0e3bc 100644--- a/kernel/model/updater.go+++ b/kernel/model/updater.go@@ -83,6 +83,7 @@ func checkDownloadInstallPkg(notifyPackageUnavailable bool) {existingPkgPath := getNewVerInstallPkgPath()if "" != existingPkgPath {// 存在经过 sha256Hash 检查的安装包+ clearOldInstallPackagesLocked(installPackageVersion(filepath.Base(existingPkgPath)), existingPkgPath)util.PushUpdateMsg("update-pkg-ready", Conf.Language(62), 15*1000)return}@@ -92,6 +93,8 @@ func checkDownloadInstallPkg(notifyPackageUnavailable bool) {for _, downloadPkgURL := range downloadPkgURLs {err = downloadInstallPkg(downloadPkgURL, checksum)if err == nil {+ pkgPath := filepath.Join(util.TempDir, "install", path.Base(downloadPkgURL))+ clearOldInstallPackagesLocked(installPackageVersion(filepath.Base(pkgPath)), pkgPath)success = truebreak}diff --git a/kernel/model/updater_cleanup.go b/kernel/model/updater_cleanup.gonew file mode 100644index 0000000000..a02aab0d20--- /dev/null+++ b/kernel/model/updater_cleanup.go@@ -0,0 +1,63 @@+package model++import (+ "os"+ "path/filepath"+ "strings"++ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/util"+ "golang.org/x/mod/semver"+)++// installPackageVersion 仅识别桌面端自动下载的安装包名称。+func installPackageVersion(name string) string {+ if !strings.HasPrefix(name, "siyuan-") {+ return ""+ }+ for _, suffix := range []string{"-win.exe", "-win-arm64.exe", "-mac.dmg", "-mac-arm64.dmg"} {+ if strings.HasSuffix(name, suffix) {+ version := "v" + strings.TrimSuffix(strings.TrimPrefix(name, "siyuan-"), suffix)+ if semver.IsValid(version) {+ return version+ }+ }+ }+ return ""+}++func clearOldInstallPackages(preservePath string) {+ checkDownloadInstallPkgLock.Lock()+ defer checkDownloadInstallPkgLock.Unlock()+ clearOldInstallPackagesLocked("v"+util.Ver, preservePath)+}++// clearOldInstallPackagesLocked 与下载共用互斥锁,保留当前版本及交给桌面宿主的安装包。+func clearOldInstallPackagesLocked(beforeVersion, preservePath string) {+ clearInstallPackagesBefore(filepath.Join(util.TempDir, "install"), "v"+util.Ver, beforeVersion, preservePath)+}++func clearInstallPackagesBefore(installDir, currentVersion, beforeVersion, preservePath string) {+ if !semver.IsValid(beforeVersion) || !semver.IsValid(currentVersion) {+ return+ }+ entries, err := os.ReadDir(installDir)+ if os.IsNotExist(err) {+ return+ }+ if err != nil {+ logging.LogErrorf("read install directory [%s] failed: %s", installDir, err)+ return+ }+ for _, entry := range entries {+ version := installPackageVersion(entry.Name())+ pkgPath := filepath.Join(installDir, entry.Name())+ if version == "" || !entry.Type().IsRegular() || pkgPath == preservePath ||+ semver.Compare(version, currentVersion) == 0 || semver.Compare(version, beforeVersion) >= 0 {+ continue+ }+ if err = os.Remove(pkgPath); err != nil && !os.IsNotExist(err) {+ logging.LogErrorf("remove old install package [%s] failed: %s", pkgPath, err)+ }+ }+}diff --git a/kernel/model/updater_cleanup_test.go b/kernel/model/updater_cleanup_test.gonew file mode 100644index 0000000000..4530274bc0--- /dev/null+++ b/kernel/model/updater_cleanup_test.go@@ -0,0 +1,91 @@+package model++import (+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestInstallPackageVersion(t *testing.T) {+ for name, want := range map[string]string{+ "siyuan-3.8.5-win.exe": "v3.8.5",+ "siyuan-3.8.5-alpha.10-win-arm64.exe": "v3.8.5-alpha.10",+ "siyuan-3.8.5-beta.2-mac.dmg": "v3.8.5-beta.2",+ "siyuan-3.8.5-mac-arm64.dmg": "v3.8.5",+ "siyuan-test-win.exe": "",+ "siyuan-3.8.5-linux.AppImage": "",+ "siyuan-3.8.5-win.exe.part": "",+ "other-3.8.5-win.exe": "",+ } {+ if got := installPackageVersion(name); got != want {+ t.Errorf("%s: got %q, want %q", name, got, want)+ }+ }+}++func TestClearOldInstallPackages(t *testing.T) {+ originalTempDir := util.TempDir+ t.Cleanup(func() { util.TempDir = originalTempDir })+ util.TempDir = t.TempDir()+ currentVersion := "v3.8.5-alpha.2"+ installDir := filepath.Join(util.TempDir, "install")+ if err := os.MkdirAll(installDir, 0755); err != nil {+ t.Fatal(err)+ }+ names := []string{+ "siyuan-3.8.4-win.exe", "siyuan-3.8.5-alpha.1-win.exe",+ "siyuan-3.8.5-alpha.2-win.exe", "siyuan-3.8.5-alpha.3-win.exe",+ "siyuan-3.8.5-alpha.10-win.exe", "siyuan-3.8.5-beta.1-mac-arm64.dmg",+ "siyuan-3.8.5-win.exe", "notes.txt",+ }+ for _, name := range names {+ if err := os.WriteFile(filepath.Join(installDir, name), []byte("package"), 0644); err != nil {+ t.Fatal(err)+ }+ }+ directory := filepath.Join(installDir, "siyuan-3.8.3-win.exe")+ if err := os.Mkdir(directory, 0755); err != nil {+ t.Fatal(err)+ }+ assertExists := func(name string, want bool) {+ t.Helper()+ _, err := os.Stat(filepath.Join(installDir, name))+ if want && err != nil || !want && !os.IsNotExist(err) {+ t.Fatalf("%s: want existence %v, err %v", name, want, err)+ }+ }+ // 启动清理保留当前版本、未来版本、未知文件及目录。+ clearInstallPackagesBefore(installDir, currentVersion, currentVersion, "")+ for i, name := range names {+ assertExists(name, i >= 2)+ }+ assertExists(filepath.Base(directory), true)+ // 下载较新版本后仅清理被替代的包,当前版本和指定包始终保留。+ clearInstallPackagesBefore(installDir, currentVersion, "v3.8.5-alpha.10", filepath.Join(installDir, names[3]))+ assertExists(names[3], true)+ clearInstallPackagesBefore(installDir, currentVersion, "v3.8.5-alpha.10", "")+ assertExists(names[3], false)+ for _, name := range names[4:] {+ assertExists(name, true)+ }+ assertExists(names[2], true)+ // 清理等待下载释放互斥锁。+ checkDownloadInstallPkgLock.Lock()+ done := make(chan struct{})+ go func() { clearOldInstallPackages(""); close(done) }()+ select {+ case <-done:+ checkDownloadInstallPkgLock.Unlock()+ t.Fatal("cleanup did not wait for download lock")+ case <-time.After(20 * time.Millisecond):+ }+ checkDownloadInstallPkgLock.Unlock()+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ t.Fatal("cleanup did not finish after download lock was released")+ }+}