diff --git a/.agents/notes/implemented/feature/2026-11-18-plugin-auto-updates.md b/.agents/notes/implemented/feature/2026-11-18-plugin-auto-updates.md index c2060c70c..1b3c91e1f 100644 --- a/.agents/notes/implemented/feature/2026-11-18-plugin-auto-updates.md +++ b/.agents/notes/implemented/feature/2026-11-18-plugin-auto-updates.md @@ -21,21 +21,36 @@ 不要这样做:只看插件 ID 相同就从另一个源替换,或把新增的终端权限和可执行程序视作旧审批覆盖;也不能以卸载旧插件的方式完成自动升级。 +### 手动与后台共享增量下载 + +市场可在同一索引提交发布独立的补丁索引。旧客户端仍能读取主索引,新客户端先确定完整包,再看是否有与原审批中的旧包摘要匹配的补丁。用 Zstandard(zstd)将旧的原始 ZIP 作为参考,在平台临时目录重建目标 ZIP,并验证旧包、补丁和目标包的 SHA-256。缺少可用基线或重建失败时走完整包,取消会结束下载并清理临时数据。下载完成的 ZIP 可在用户缓存保留,以便后续生成精确基线。 + +桌面进程共享 ZIP 缓存。写入方从检查容量、淘汰旧归档到发布新归档持有同一把原生锁,避免两个进程按同一份旧容量各自写入。获取锁最多等待一秒。锁不可用时记录失败,已下载的包仍可用于本次安装。 + +同一进程内使用同一个插件数据根的工作台共享更新轮次。手动安装和后台暂存在提交阶段争用同一个插件安装入口。后台将包与审批一起准备完成后再提交到待激活目录。下次启动 Lithe 进程时在后台验包,读取启动项目和插件语言清单前复核原版本和审批,只有仍然符合的包才进入已安装目录。例如后台暂存 2.0.0 后再禁用 1.0.0,重启时丢弃待更新包。运行中的会话读取的仍是旧目录。 + +不同进程共享插件数据根。激活、手动安装、后台暂存、禁用和卸载使用同一个原生文件锁。卸载先取消并等待进程内的安装任务,再加锁让 Core 读取安装快照。这样即使另一个窗口刚刚激活新版,卸载计划也会包含它。锁文件保留在可写的插件数据根,进程退出时由操作系统释放锁。 + ## 考虑过的备选方案 - 默认无条件自动更新:用户没有同意后台下载或插件执行代码更换,拒绝。 - 只比较版本号,不检查来源、权限和程序:会让第三方源或新版程序跨越信任边界,拒绝。 +- 在主索引加入可选补丁字段会让当前旧 Core 拒绝未知字段。重新压缩已安装目录也无法保证得到与旧 ZIP 一致的字节。独立索引与有界原包缓存让两条下载路径共享既有校验。 - 立即重启已运行语言服务器和插件后端:影响正在编辑/调试的工作区,也可能丢失临时状态;选择不在后台更新时强制重启。 ## 后果 - 收益:用户明确开启后,符合旧审批范围的更新无需反复点击,也不会重复下载安装相同已装版本;托管运行时按现有复用策略避免重复下载。 -- 代价:旧版市场插件需要一次手动更新以记录来源;权限/程序变化必须手动审核,后台没有弹窗。后台安装后需重启才能确保旧插件会话切换到新版本。 +- 代价:符合补丁格式的原始 ZIP 占用有限的用户缓存。无精确缓存基线时走全包,大包是否发布补丁由实际体积决定。 +- 旧版市场插件需要一次手动更新以记录来源;权限/程序变化必须手动审核,后台没有弹窗。后台安装后需重启才能确保旧插件会话切换到新版本。 - 仍需原生跨平台验收:macOS 与 Windows 的窗口无头/真实插件更新、关窗取消与慢网络处理。未完成时功能矩阵保留 pending。 ## 验证 - `./scripts/desktop/desktop-go.sh test ./internal/plugintrust ./internal/marketplace ./internal/workbench -run 'TestMayAutoUpdate|TestNewerOffered|TestAutoUpdateCandidates' -count=1` +- `./scripts/desktop/desktop-go.sh test ./internal/marketplace -run TestMarketplaceDelta` 覆盖补丁命中、损坏、取消和已安装包只读。 +- `./scripts/desktop/desktop-go.sh test ./internal/marketplace -run 'TestArchiveCacheKeepsBudgetAcrossProcesses|TestMarketplaceDeltaTransport'` 覆盖两个进程同时写入时的归档条数和字节上限,以及缓存锁不可用时继续交付已校验的 ZIP。 +- `TestUninstallWaitsForPackagePublicationInAnotherProcess` 用两个进程验证卸载等待发布,并在重试后删除新旧两个版本。测试同时核验发行包内容未改变。 - `node scripts/i18n/generate-i18n.mjs --check`、`./scripts/platform-feature-matrix/verify-platform-feature-matrix.sh`、`./scripts/agent-notes/verify-agent-notes.sh`。 - 在合成插件市场的自动更新场景,观察安装文件、批准记录、运行中的旧进程和重启后新版本;拒绝案例不得提交任何安装。 @@ -47,3 +62,6 @@ - `desktop/internal/plugintrust/auto_update.go` - `desktop/internal/plugininstall/plugininstall.go` - `desktop/internal/marketplace/service.go` +- `desktop/internal/marketplace/delta.go` +- `desktop/internal/marketplace/archive_cache.go` +- `desktop/internal/plugininstall/pending.go` diff --git a/desktop/internal/core/marketplace.go b/desktop/internal/core/marketplace.go index 2d182bcf6..9d96739da 100644 --- a/desktop/internal/core/marketplace.go +++ b/desktop/internal/core/marketplace.go @@ -47,6 +47,7 @@ func (o marketplaceOutcome) failure(command string) error { type MarketplaceSource struct { IndexURL string `json:"indexURL"` RecommendationsURL string `json:"recommendationsURL"` + DeltasURL string `json:"deltasURL"` Repository *string `json:"repository"` DisplayName string `json:"displayName"` // Revision is the GitHub repository and ref a GitHub-hosted index follows; nil for any @@ -69,6 +70,7 @@ type MarketplacePinned struct { Commit string `json:"commit"` IndexURL string `json:"indexURL"` RecommendationsURL string `json:"recommendationsURL"` + DeltasURL string `json:"deltasURL"` } // MarketplaceAvailability is Core's platform and capability decision. @@ -110,9 +112,11 @@ type MarketplacePlugin struct { LatestReleaseDate string `json:"latestReleaseDate"` // MarketplaceIndexURL identifies the validated source of a fetched listing. It is // native-only provenance and must never appear in the Core JSON contract. - MarketplaceIndexURL string `json:"-"` - Availability MarketplaceAvailability `json:"availability"` - Versions []MarketplaceVersion `json:"versions"` + MarketplaceIndexURL string `json:"-"` + // MarketplaceDeltasURL comes from the same index revision as Availability. + MarketplaceDeltasURL string `json:"-"` + Availability MarketplaceAvailability `json:"availability"` + Versions []MarketplaceVersion `json:"versions"` } // MarketplaceEntryRejection describes one rejected entry without hiding accepted entries. diff --git a/desktop/internal/core/marketplace_delta.go b/desktop/internal/core/marketplace_delta.go new file mode 100644 index 000000000..dfa1bef8c --- /dev/null +++ b/desktop/internal/core/marketplace_delta.go @@ -0,0 +1,76 @@ +package core + +import ( + "context" + "encoding/json" +) + +// MarketplaceDeltaRequest binds a companion index to the approved local base and +// the full archive already selected from the main index. +type MarketplaceDeltaRequest struct { + Index json.RawMessage `json:"index"` + PluginID string `json:"pluginID"` + Platform string `json:"platform"` + Repository string `json:"repository"` + FromVersion string `json:"fromVersion"` + FromSHA256 string `json:"fromSHA256"` + ToVersion string `json:"toVersion"` + ToSHA256 string `json:"toSHA256"` + ArchiveURL string `json:"archiveURL"` +} + +// MarketplaceDelta is the optional patch accepted by Core for the exact input. +type MarketplaceDelta struct { + PluginID string `json:"pluginID"` + Platform string `json:"platform"` + FromVersion string `json:"fromVersion"` + FromSHA256 string `json:"fromSHA256"` + ToVersion string `json:"toVersion"` + ToSHA256 string `json:"toSHA256"` + ToSize int64 `json:"toSize"` + Format string `json:"format"` + DownloadURL string `json:"downloadURL"` + SHA256 string `json:"sha256"` + Size int64 `json:"size"` +} + +func (c *Client) SelectMarketplaceDelta(ctx context.Context, request MarketplaceDeltaRequest) (*MarketplaceDelta, error) { + const command = "plugins.marketplace.selectDelta" + var result struct { + marketplaceOutcome + Patch *MarketplaceDelta `json:"patch"` + } + if err := c.Execute(ctx, command, request, &result); err != nil { + return nil, err + } + if err := result.failure(command); err != nil { + return nil, err + } + return result.Patch, nil +} + +// ApplyMarketplaceDelta writes a verified ZIP to an empty path owned by the caller. +// The caller removes the staging directory on failure or cancellation. +func (c *Client) ApplyMarketplaceDelta(ctx context.Context, patch MarketplaceDelta, basePath, patchPath, outputPath string) error { + const command = "plugins.marketplace.applyDelta" + var result struct { + marketplaceOutcome + Applied bool `json:"applied"` + } + request := struct { + Patch MarketplaceDelta `json:"patch"` + BasePath string `json:"basePath"` + PatchPath string `json:"patchPath"` + OutputPath string `json:"outputPath"` + }{patch, basePath, patchPath, outputPath} + if err := c.Execute(ctx, command, request, &result); err != nil { + return err + } + if err := result.failure(command); err != nil { + return err + } + if !result.Applied { + return newParseError(command, "marketplace returned no reconstructed archive", "") + } + return nil +} diff --git a/desktop/internal/pluginruntime/lock.go b/desktop/internal/filelock/lock.go similarity index 78% rename from desktop/internal/pluginruntime/lock.go rename to desktop/internal/filelock/lock.go index ac28bc2f5..db6b6dfb6 100644 --- a/desktop/internal/pluginruntime/lock.go +++ b/desktop/internal/filelock/lock.go @@ -1,4 +1,5 @@ -package pluginruntime +// Package filelock coordinates access to writable files across processes. +package filelock import ( "context" @@ -8,10 +9,15 @@ import ( "time" ) -// acquire uses an OS lock, not a pid or timestamp lease: process death releases +var ( + ErrInvalid = errors.New("lock path must name a regular file") + ErrBusy = errors.New("file lock is busy") +) + +// Acquire uses an OS lock, not a pid or timestamp lease: process death releases // ownership automatically. The file stays in place so another opener cannot // lock a different inode while a previous waiter still holds the old one. -func acquire(ctx context.Context, name string) (unlock func() error, err error) { +func Acquire(ctx context.Context, name string) (unlock func() error, err error) { defer func() { if err != nil && unlock != nil { err = errors.Join(err, unlock()) @@ -46,7 +52,7 @@ func acquire(ctx context.Context, name string) (unlock func() error, err error) return nil, err } if !info.Mode().IsRegular() || !os.SameFile(info, opened) { - return nil, ErrArtifact + return nil, ErrInvalid } bounded, cancel := context.WithTimeout(ctx, 5*time.Minute) defer cancel() @@ -56,6 +62,9 @@ func acquire(ctx context.Context, name string) (unlock func() error, err error) return nil, err } if locked { + if err := ctx.Err(); err != nil { + return nil, err + } owned = true return file.Close, nil } diff --git a/desktop/internal/pluginruntime/lock_unix.go b/desktop/internal/filelock/lock_unix.go similarity index 93% rename from desktop/internal/pluginruntime/lock_unix.go rename to desktop/internal/filelock/lock_unix.go index 4eae6187d..4ce41a8f2 100644 --- a/desktop/internal/pluginruntime/lock_unix.go +++ b/desktop/internal/filelock/lock_unix.go @@ -1,6 +1,6 @@ //go:build darwin || linux -package pluginruntime +package filelock import ( "errors" diff --git a/desktop/internal/pluginruntime/lock_windows.go b/desktop/internal/filelock/lock_windows.go similarity index 94% rename from desktop/internal/pluginruntime/lock_windows.go rename to desktop/internal/filelock/lock_windows.go index ef7fbb7c8..659e7ac8b 100644 --- a/desktop/internal/pluginruntime/lock_windows.go +++ b/desktop/internal/filelock/lock_windows.go @@ -1,6 +1,6 @@ //go:build windows -package pluginruntime +package filelock import ( "errors" diff --git a/desktop/internal/marketplace/archive_cache.go b/desktop/internal/marketplace/archive_cache.go new file mode 100644 index 000000000..ff2aa7c85 --- /dev/null +++ b/desktop/internal/marketplace/archive_cache.go @@ -0,0 +1,204 @@ +package marketplace + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/filelock" +) + +const ( + // The maximum base size mirrors the Core delta contract. Larger ZIPs still install normally. + maxDeltaZIPBytes = 64 << 20 + archiveCacheBudget = 256 << 20 + archiveCacheEntries = 128 + archiveCacheLockFile = ".archive-cache.lock" + archiveCacheLockWait = time.Second + cacheStagingLifetime = 24 * time.Hour +) + +// ArchiveCache holds disposable, content-addressed marketplace ZIPs in the user cache. +// A cache hit still needs Core to verify the base against the approval before patching. +type ArchiveCache struct{ directory string } + +// UserArchiveCache resolves the writable platform cache independently of the plugin or app bundle. +func UserArchiveCache() (ArchiveCache, error) { + root, err := os.UserCacheDir() + if err != nil { + return ArchiveCache{}, err + } + return ArchiveCache{directory: filepath.Join(root, "Lithe", "PluginArchives")}, nil +} + +func (c ArchiveCache) path(digest string) (string, error) { + if len(digest) != 64 { + return "", errors.New("invalid plugin archive cache digest") + } + if _, err := hex.DecodeString(digest); err != nil { + return "", fmt.Errorf("invalid plugin archive cache digest: %w", err) + } + return filepath.Join(c.directory, digest+".zip"), nil +} + +func (c ArchiveCache) base(digest string) (string, error) { + path, err := c.path(digest) + if err != nil { + return "", err + } + info, err := os.Lstat(path) + // log-exempt: 预期的缺失:新安装、系统清理及淘汰可能使基线不存在。 + if errors.Is(err, fs.ErrNotExist) { + return "", nil + } + if err != nil { + return "", err + } + if !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > maxDeltaZIPBytes { + return "", errors.New("plugin delta base is not a supported cache file") + } + return path, nil +} + +func (c ArchiveCache) remember(ctx context.Context, digest string, archive *DownloadedArchive) (err error) { + target, err := c.path(digest) + if err != nil { + return err + } + source, err := os.Open(archive.Path()) + if err != nil { + return err + } + defer func() { err = errors.Join(err, source.Close()) }() + info, err := source.Stat() + if err != nil { + return err + } + if info.Size() > maxDeltaZIPBytes { + return nil + } + if err := ctx.Err(); err != nil { + return err + } + if err := os.MkdirAll(c.directory, 0o700); err != nil { + return err + } + return c.publish(ctx, source, info.Size(), target) +} + +func (c ArchiveCache) publish(ctx context.Context, source io.Reader, size int64, target string) (err error) { + // The cache is optional for the current install. Bound the wait, then + // use the caller's context for the copy once we own the lock. + acquireCtx, cancel := context.WithTimeout(ctx, archiveCacheLockWait) + unlock, err := filelock.Acquire(acquireCtx, filepath.Join(c.directory, archiveCacheLockFile)) + cancel() + if err != nil { + return fmt.Errorf("lock plugin archive cache: %w", err) + } + defer func() { err = errors.Join(err, unlock()) }() + + if err := c.prune(size, filepath.Base(target)); err != nil { + return err + } + temp, err := os.CreateTemp(c.directory, ".incoming-") + if err != nil { + return err + } + name := temp.Name() + defer func() { + removeErr := os.Remove(name) + // log-exempt: 预期的缺失:原子发布已经将临时文件移动到目标文件名。 + if removeErr != nil && !errors.Is(removeErr, fs.ErrNotExist) { + err = errors.Join(err, removeErr) + } + }() + written, err := io.Copy(temp, io.LimitReader(cacheReader{ctx, source}, size+1)) + if err == nil && written != size { + err = errors.New("plugin archive cache input changed while copying") + } + if err = errors.Join(err, temp.Close()); err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + return os.Rename(name, target) +} + +type cacheReader struct { + context.Context + io.Reader +} + +func (r cacheReader) Read(buffer []byte) (int, error) { + if err := r.Err(); err != nil { + return 0, err + } + return r.Reader.Read(buffer) +} + +type cachedArchive struct { + name string + size int64 + modified time.Time +} + +func (c ArchiveCache) prune(incoming int64, target string) error { + entries, err := os.ReadDir(c.directory) + if err != nil { + return err + } + var archives []cachedArchive + staleBefore := time.Now().Add(-cacheStagingLifetime) + for _, entry := range entries { + name := entry.Name() + incomingTemp := strings.HasPrefix(name, ".incoming-") + if name == target || entry.Type() != 0 || (!incomingTemp && filepath.Ext(name) != ".zip") { + continue + } + info, err := entry.Info() + // log-exempt: 预期的缺失:系统可能已清理此缓存文件。 + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + return err + } + if incomingTemp { + // log-exempt: 预期的缺失:系统可能已清理此临时文件。 + if info.ModTime().Before(staleBefore) { + if err := os.Remove(filepath.Join(c.directory, name)); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + } + continue + } + incoming += info.Size() + archives = append(archives, cachedArchive{name, info.Size(), info.ModTime()}) + } + sort.Slice(archives, func(i, j int) bool { + if archives[i].modified.Equal(archives[j].modified) { + return archives[i].name < archives[j].name + } + return archives[i].modified.Before(archives[j].modified) + }) + for i, archive := range archives { + if incoming <= archiveCacheBudget && len(archives)-i < archiveCacheEntries { + break + } + // log-exempt: 预期的缺失:系统可能已清理此缓存文件。 + if err := os.Remove(filepath.Join(c.directory, archive.name)); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + incoming -= archive.size + } + return nil +} diff --git a/desktop/internal/marketplace/archive_cache_test.go b/desktop/internal/marketplace/archive_cache_test.go new file mode 100644 index 000000000..e9aacdc58 --- /dev/null +++ b/desktop/internal/marketplace/archive_cache_test.go @@ -0,0 +1,191 @@ +package marketplace + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +const ( + cacheTestFirstArchive = "one" + cacheTestSecondArchive = "two" +) + +func TestArchiveCacheKeepsBudgetAcrossProcesses(t *testing.T) { + for _, scenario := range []struct { + name string + count int + size int64 + }{ + {"entries", archiveCacheEntries - 1, 1}, + {"bytes", 4, archiveCacheBudget/4 - 1}, + } { + t.Run(scenario.name, func(t *testing.T) { + cache := ArchiveCache{directory: t.TempDir()} + for index := range scenario.count { + path := filepath.Join(cache.directory, fmt.Sprintf("%064x.zip", index+1)) + file, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + if err := errors.Join(file.Truncate(scenario.size), file.Close()); err != nil { + t.Fatal(err) + } + } + source := filepath.Join(t.TempDir(), "archive.zip") + if err := os.WriteFile(source, []byte(cacheTestSecondArchive), 0o600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + writer := func(role string) *exec.Cmd { + cmd := exec.CommandContext(ctx, executable, "-test.run=^TestArchiveCacheWriterProcess$", "-test.timeout=7s") + cmd.Env = append(os.Environ(), "LITHE_TEST_ARCHIVE_CACHE_ROLE="+role, + "LITHE_TEST_ARCHIVE_CACHE_DIRECTORY="+cache.directory, "LITHE_TEST_ARCHIVE_CACHE_SOURCE="+source) + cmd.WaitDelay = time.Second + return cmd + } + first := writer("hold") + release, err := first.StdinPipe() + if err != nil { + t.Fatal(err) + } + output, err := first.StdoutPipe() + if err != nil { + t.Fatal(err) + } + var stderr bytes.Buffer + first.Stderr = &stderr + if err := first.Start(); err != nil { + t.Fatal(err) + } + waited := false + defer func() { + if !waited { + cancel() + _ = first.Wait() + } + }() + reader := bufio.NewReader(output) + // The first writer has finished pruning and is paused inside the copy. + if line, err := reader.ReadString('\n'); line != "copying\n" || err != nil { + t.Fatalf("first writer ready signal = %q, %v", line, err) + } + second, err := writer("write").CombinedOutput() + if err != nil { + t.Fatalf("second writer: %v\n%s", err, second) + } + if err := release.Close(); err != nil { + t.Fatal(err) + } + remaining, readErr := io.ReadAll(reader) + waitErr := first.Wait() + waited = true + if err := errors.Join(readErr, waitErr); err != nil { + t.Fatalf("first writer: %v\n%s\n%s", err, remaining, stderr.String()) + } + // A writer that could not get the lock can retry after publication. + if bytes.HasPrefix(second, []byte("unavailable\n")) { + second, err = writer("write").CombinedOutput() + if err != nil { + t.Fatalf("second writer retry: %v\n%s", err, second) + } + } + if !bytes.HasPrefix(second, []byte("published\n")) { + t.Fatalf("second writer result = %q", second) + } + for _, body := range []string{cacheTestFirstArchive, cacheTestSecondArchive} { + path, err := cache.base(deltaDigest([]byte(body))) + if err != nil || path == "" { + t.Fatalf("published archive %q missing: %v", body, err) + } + } + entries, err := os.ReadDir(cache.directory) + if err != nil { + t.Fatal(err) + } + var count int + var size int64 + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), ".incoming-") { + t.Fatalf("temporary archive left behind: %q", entry.Name()) + } + if filepath.Ext(entry.Name()) != ".zip" { + continue + } + info, err := entry.Info() + if err != nil { + t.Fatal(err) + } + count++ + size += info.Size() + } + if count > archiveCacheEntries || size > archiveCacheBudget { + t.Fatalf("cache contains %d archives and %d bytes, limits are %d and %d", count, size, archiveCacheEntries, archiveCacheBudget) + } + }) + } +} + +func TestArchiveCacheWriterProcess(t *testing.T) { + role := os.Getenv("LITHE_TEST_ARCHIVE_CACHE_ROLE") + if role == "" { + t.Skip("archive cache subprocess") + } + cache := ArchiveCache{directory: os.Getenv("LITHE_TEST_ARCHIVE_CACHE_DIRECTORY")} + switch role { + case "hold": + target, err := cache.path(deltaDigest([]byte(cacheTestFirstArchive))) + if err != nil { + t.Fatal(err) + } + reader := &pausedArchiveCopy{Reader: strings.NewReader(cacheTestFirstArchive)} + if err := cache.publish(t.Context(), reader, int64(len(cacheTestFirstArchive)), target); err != nil { + t.Fatal(err) + } + case "write": + archive := &DownloadedArchive{file: &archiveFile{path: os.Getenv("LITHE_TEST_ARCHIVE_CACHE_SOURCE")}} + err := cache.remember(t.Context(), deltaDigest([]byte(cacheTestSecondArchive)), archive) + if errors.Is(err, context.DeadlineExceeded) { + fmt.Println("unavailable") + return + } + if err != nil { + t.Fatal(err) + } + fmt.Println("published") + default: + t.Fatalf("unknown archive cache subprocess role %q", role) + } +} + +type pausedArchiveCopy struct { + io.Reader + released bool +} + +func (c *pausedArchiveCopy) Read(p []byte) (int, error) { + if !c.released { + if _, err := fmt.Fprintln(os.Stdout, "copying"); err != nil { + return 0, err + } + if _, err := io.Copy(io.Discard, os.Stdin); err != nil { + return 0, err + } + c.released = true + } + return c.Reader.Read(p) +} diff --git a/desktop/internal/marketplace/delta.go b/desktop/internal/marketplace/delta.go new file mode 100644 index 000000000..2a0b4a60f --- /dev/null +++ b/desktop/internal/marketplace/delta.go @@ -0,0 +1,108 @@ +package marketplace + +import ( + "context" + "errors" + "net/http" + "os" + "path/filepath" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// DeltaCore selects an exact-base patch and verifies the reconstruction. +type DeltaCore interface { + SelectMarketplaceDelta(context.Context, core.MarketplaceDeltaRequest) (*core.MarketplaceDelta, error) + ApplyMarketplaceDelta(context.Context, core.MarketplaceDelta, string, string, string) error +} + +// DeltaBase describes an installed version with a matching marketplace approval. +type DeltaBase struct{ Version, SHA256 string } + +// DownloadUpdate serves both interactive and automatic marketplace installers. +// The full download callback retains its normal resume and progress behavior. +func (s *Service) DownloadUpdate(ctx context.Context, kernel DeltaCore, cache ArchiveCache, downloader *ArchiveDownloader, plugin core.MarketplacePlugin, platform string, base DeltaBase, full func() (*DownloadedArchive, error), progress func(ArchiveProgress), report func(error)) (*DownloadedArchive, error) { + if cache.directory == "" || kernel == nil || plugin.MarketplaceDeltasURL == "" { + return full() + } + archive, err := s.tryDelta(ctx, kernel, cache, downloader, plugin, platform, base, progress) + if ctx.Err() != nil { + // The caller cancelled the transfer. A joined cleanup error still needs a log. + if err != nil && !errors.Is(err, ctx.Err()) { + report(err) + } + if archive != nil { + if err := archive.Discard(); err != nil { + report(err) + } + } + return nil, ctx.Err() + } + if err != nil { + report(err) + } + if archive == nil { + if progress != nil && err != nil { + progress(ArchiveProgress{Total: -1}) + } + archive, err = full() + if err != nil { + return nil, err + } + } + if err := cache.remember(ctx, plugin.Availability.SHA256, archive); err != nil && !errors.Is(err, context.Canceled) { + report(err) + } + return archive, nil +} + +func (s *Service) tryDelta(ctx context.Context, kernel DeltaCore, cache ArchiveCache, downloader *ArchiveDownloader, plugin core.MarketplacePlugin, platform string, base DeltaBase, progress func(ArchiveProgress)) (archive *DownloadedArchive, err error) { + if plugin.MarketplaceDeltasURL == "" || base.SHA256 == "" || base.Version == plugin.Availability.Version { + return nil, nil + } + path, err := cache.base(base.SHA256) + if err != nil || path == "" { + return nil, err + } + deltas, _, err := s.fetchJSON(ctx, plugin.MarketplaceDeltasURL) + // log-exempt: 预期的缺失:市场可只提供完整包,不发布可选增量索引。 + if err == httpStatusError(http.StatusNotFound) { + return nil, nil + } + if err != nil { + return nil, err + } + patch, err := kernel.SelectMarketplaceDelta(ctx, core.MarketplaceDeltaRequest{ + Index: deltas, PluginID: plugin.ID, Platform: platform, Repository: plugin.Repository, + FromVersion: base.Version, FromSHA256: base.SHA256, + ToVersion: plugin.Availability.Version, ToSHA256: plugin.Availability.SHA256, ArchiveURL: plugin.Availability.DownloadURL, + }) + if err != nil || patch == nil { + return nil, err + } + transfer := *downloader + transfer.maximumBytes = min(transfer.maximumBytes, patch.Size) + data, partial, err := transfer.download(ctx, core.MarketplaceAvailability{ + Status: "available", DownloadURL: patch.DownloadURL, SHA256: patch.SHA256, + }, nil, progress) + if partial != nil { + err = errors.Join(err, partial.remove()) + } + if err != nil { + return nil, err + } + defer func() { + if cleanup := data.Discard(); cleanup != nil { + err = errors.Join(err, cleanup) + } + }() + staging, err := os.MkdirTemp(downloader.temporaryRoot, "lithe-plugin-delta-") + if err != nil { + return nil, err + } + output := filepath.Join(staging, "archive.zip") + if err := kernel.ApplyMarketplaceDelta(ctx, *patch, path, data.Path(), output); err != nil { + return nil, errors.Join(err, os.RemoveAll(staging)) + } + return &DownloadedArchive{file: &archiveFile{directory: staging, path: output, owners: 1}}, nil +} diff --git a/desktop/internal/marketplace/delta_test.go b/desktop/internal/marketplace/delta_test.go new file mode 100644 index 000000000..787718e2c --- /dev/null +++ b/desktop/internal/marketplace/delta_test.go @@ -0,0 +1,194 @@ +package marketplace + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/installedpackagetest" +) + +func deltaDigest(body []byte) string { + hash := sha256.Sum256(body) + return hex.EncodeToString(hash[:]) +} + +// The patch was produced by the publisher's zstd --patch-from command. The +// input is deliberately incompressible without the exact 16 KiB reference. +func deltaFixture(t *testing.T) (base, target, patch []byte) { + t.Helper() + for i := range 512 { + hash := sha256.Sum256(binary.LittleEndian.AppendUint16(nil, uint16(i))) + base = append(base, hash[:]...) + } + target = bytes.Clone(base) + copy(target[2048:], "Lithe delta fixture target bytes!") + patch, err := hex.DecodeString("28b52ffd64003f7d010014024c697468652064656c7461206669787475726520746172676574206279746573210200e1be80fffe07809f01016d14474a") + if err != nil { + t.Fatal(err) + } + return base, target, patch +} + +func TestMarketplaceDeltaTransport(t *testing.T) { + for _, scenario := range []string{"exact", "no base", "corrupt base", "corrupt patch", "wrong output", "no companion", "cancel", "cache unavailable"} { + t.Run(scenario, func(t *testing.T) { + verifyMarketplaceDelta(t, ArchiveCache{directory: t.TempDir()}, scenario) + }) + } +} + +func TestMarketplaceDeltaLeavesInstalledPackageUnchanged(t *testing.T) { + if !installedpackagetest.Run(t) { + return + } + cache, err := UserArchiveCache() + if err != nil { + t.Fatal(err) + } + installedpackagetest.Outside(t, cache.directory) + verifyMarketplaceDelta(t, cache, "exact") +} + +func verifyMarketplaceDelta(t *testing.T, cache ArchiveCache, scenario string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + base, target, patch := deltaFixture(t) + if scenario == "wrong output" { + target[0] ^= 1 + } + const repo = "https://github.com/example/delta" + const zipURL = repo + "/releases/download/v2.0.0/delta.zip" + const patchURL = repo + "/releases/download/v2.0.0/delta.from-1.0.0.zip.zst" + const companion = "https://example.test/lithe-plugin-deltas.json" + offer := core.MarketplacePlugin{ + ID: "io.example.delta", Repository: repo, MarketplaceDeltasURL: companion, + Availability: core.MarketplaceAvailability{ + Status: "available", Version: "2.0.0", DownloadURL: zipURL, SHA256: deltaDigest(target), + }, + } + delta := core.MarketplaceDelta{ + PluginID: offer.ID, Platform: "darwin-arm64", FromVersion: "1.0.0", FromSHA256: deltaDigest(base), + ToVersion: offer.Availability.Version, ToSHA256: offer.Availability.SHA256, ToSize: int64(len(target)), + Format: "zstd-prefix", DownloadURL: patchURL, SHA256: deltaDigest(patch), Size: int64(len(patch)), + } + raw, err := json.Marshal(map[string]any{"schemaVersion": 0, "patches": []core.MarketplaceDelta{delta}}) + if err != nil { + t.Fatal(err) + } + if scenario != "no base" { + if err := os.MkdirAll(cache.directory, 0o700); err != nil { + t.Fatal(err) + } + path, err := cache.path(delta.FromSHA256) + if err != nil { + t.Fatal(err) + } + if scenario == "corrupt base" { + base[0] ^= 1 + } + if err := os.WriteFile(path, base, 0o600); err != nil { + t.Fatal(err) + } + } + if scenario == "cache unavailable" { + if err := os.Mkdir(filepath.Join(cache.directory, archiveCacheLockFile), 0o700); err != nil { + t.Fatal(err) + } + } + if scenario == "corrupt patch" { + patch[0] ^= 1 + } + var requests []string + client := &http.Client{Transport: transportFunc(func(request *http.Request) (*http.Response, error) { + location := request.URL.String() + requests = append(requests, location) + var body []byte + status := http.StatusOK + switch location { + case companion: + body = raw + if scenario == "no companion" { + status, body = http.StatusNotFound, nil + } + case patchURL: + body = patch + if scenario == "cancel" { + cancel() + return nil, ctx.Err() + } + case zipURL: + body = target + default: + t.Errorf("unexpected request %s", request.URL) + status = http.StatusNotFound + } + return &http.Response{ + StatusCode: status, Header: make(http.Header), Body: io.NopCloser(bytes.NewReader(body)), + ContentLength: int64(len(body)), Request: request, + }, nil + })} + var notices []error + root := t.TempDir() + kernel := core.NewClient() + downloader := newArchiveDownloader(client, root) + archive, err := New(kernel, client).DownloadUpdate(ctx, kernel, cache, downloader, offer, delta.Platform, + DeltaBase{delta.FromVersion, delta.FromSHA256}, func() (*DownloadedArchive, error) { + return downloader.Download(ctx, offer.Availability) + }, nil, func(err error) { notices = append(notices, err) }) + if scenario == "cancel" { + if err != context.Canceled || archive != nil || len(requests) != 2 { + t.Fatalf("cancel = %v, archive = %v, requests = %v", err, archive, requests) + } + assertArchiveRootEmpty(t, root) + return + } + if err != nil { + t.Fatal(err) + } + if got, err := os.ReadFile(archive.Path()); err != nil || !bytes.Equal(got, target) { + t.Fatalf("target ZIP did not match: %v", err) + } + switch scenario { + case "exact": + if len(notices) != 0 || strings.Join(requests, " ") != companion+" "+patchURL { + t.Fatalf("exact patch requested %v, reports %v", requests, notices) + } + case "no base": + if len(notices) != 0 || strings.Join(requests, " ") != zipURL { + t.Fatalf("no-base update requested %v, reports %v", requests, notices) + } + case "no companion": + if len(notices) != 0 || strings.Join(requests, " ") != companion+" "+zipURL { + t.Fatalf("no-companion update requested %v, reports %v", requests, notices) + } + case "cache unavailable": + if len(notices) != 1 || strings.Join(requests, " ") != companion+" "+patchURL { + t.Fatalf("unavailable cache update requested %v, reports %v", requests, notices) + } + default: + if len(notices) != 1 || strings.Join(requests, " ") != companion+" "+patchURL+" "+zipURL { + t.Fatalf("fallback requested %v, reports %v", requests, notices) + } + } + wantCached := scenario != "cache unavailable" + if cached, err := cache.base(delta.ToSHA256); (cached != "") != wantCached || err != nil { + t.Fatalf("target cache = %q, %v", cached, err) + } + if err := archive.Discard(); err != nil { + t.Fatal(err) + } + assertArchiveRootEmpty(t, root) +} diff --git a/desktop/internal/marketplace/service.go b/desktop/internal/marketplace/service.go index f7224879b..66019a53d 100644 --- a/desktop/internal/marketplace/service.go +++ b/desktop/internal/marketplace/service.go @@ -125,7 +125,7 @@ func (s *Service) Fetch(ctx context.Context, input string, kind core.Marketplace return Snapshot{}, err } pinned := s.pin(ctx, input, source) - data, err := s.fetchPinned(ctx, source.IndexURL, pinnedIndex(pinned)) + data, atCommit, err := s.fetchPinnedVersion(ctx, source.IndexURL, pinnedIndex(pinned)) if err != nil { return Snapshot{}, err } @@ -133,8 +133,13 @@ func (s *Service) Fetch(ctx context.Context, input string, kind core.Marketplace if err != nil { return Snapshot{}, err } + deltasURL := source.DeltasURL + if atCommit { + deltasURL = pinned.DeltasURL + } for i := range index.Plugins { index.Plugins[i].MarketplaceIndexURL = source.IndexURL + index.Plugins[i].MarketplaceDeltasURL = deltasURL } return Snapshot{Source: source, Index: index}, nil } @@ -198,15 +203,22 @@ func (s *Service) pin(ctx context.Context, input string, source core.Marketplace // read that fails is reported and retried at canonical, except a 404: the commit is the // repository's newest, so the file is absent from it. func (s *Service) fetchPinned(ctx context.Context, canonical, pinnedURL string) ([]byte, error) { + data, _, err := s.fetchPinnedVersion(ctx, canonical, pinnedURL) + return data, err +} + +// fetchPinnedVersion identifies the revision actually read, so optional companions +// can use that exact revision without falling back independently. +func (s *Service) fetchPinnedVersion(ctx context.Context, canonical, pinnedURL string) ([]byte, bool, error) { if pinnedURL != "" { data, _, err := s.fetchJSON(ctx, pinnedURL) if err == nil || err == httpStatusError(http.StatusNotFound) || ctx.Err() != nil { - return data, err + return data, true, err } s.reportFallback(ctx, fmt.Errorf("read %s: %w", pinnedURL, err)) } data, _, err := s.fetchJSON(ctx, canonical) - return data, err + return data, false, err } func (s *Service) reportFallback(ctx context.Context, err error) { diff --git a/desktop/internal/plugininstall/pending.go b/desktop/internal/plugininstall/pending.go new file mode 100644 index 000000000..b6e21b059 --- /dev/null +++ b/desktop/internal/plugininstall/pending.go @@ -0,0 +1,251 @@ +package plugininstall + +import ( + "context" + "encoding/json" + "errors" + "io/fs" + "os" + "path/filepath" + "sort" + + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" +) + +// pendingDirectory is private to the plugin data root. Inventory skips dot +// directories, so running windows keep using the old version until next startup. +const pendingDirectory = ".pending-updates" + +const pendingReceiptFile = "selection.json" +const pendingPackageDirectory = "package" + +type pendingReceipt struct { + BaseVersion string `json:"baseVersion"` + BaseSHA256 string `json:"baseSHA256"` + Target plugintrust.Record `json:"target"` +} + +// HasPending avoids downloading a second update for a plugin until restart. +func (s *Service) HasPending(root, id string) (bool, error) { + if !filepath.IsAbs(root) { + return false, ErrRequest + } + if err := pluginpkg.CheckIdentity("plugin ID", id); err != nil { + return false, err + } + _, err := os.Lstat(filepath.Join(root, pendingDirectory, id)) + // log-exempt: 预期的缺失:没有为此插件暂存自动更新。 + if errors.Is(err, fs.ErrNotExist) { + return false, nil + } + return err == nil, err +} + +// DiscardPending clears the unactivated package and its receipt on uninstall. +func (s *Service) DiscardPending(root, id string) error { + pending, err := s.HasPending(root, id) + if err != nil || !pending { + return err + } + return os.RemoveAll(filepath.Join(root, pendingDirectory, id)) +} + +// StageAutomatic publishes a prepared package into the hidden pending inventory. +// The package and its approval receipt are published by one directory rename. +func (s *Service) StageAutomatic(plan Plan, previous plugintrust.Record) (err error) { + if plan.Staging == "" || previous.PluginID != plan.ID || previous.Version == plan.Version || + plan.Source != plugintrust.Marketplace || + !plugintrust.MayAutoUpdate(previous, true, plan.MarketplaceIndexURL, plan.Review) { + return ErrNotPrepared + } + pending, err := s.HasPending(plan.Root, plan.ID) + if err != nil { + return err + } + if pending { + return pluginpkg.ErrPackageExists + } + targetRoot := filepath.Join(plan.Root, pendingDirectory) + if err := os.MkdirAll(targetRoot, 0o700); err != nil { + return err + } + candidate, err := pluginpkg.NewStaging(plan.Root) + if err != nil { + return err + } + defer func() { err = errors.Join(err, os.RemoveAll(candidate)) }() + receipt := pendingReceipt{previous.Version, previous.ArchiveSHA256, approvalFor(plan)} + data, err := json.Marshal(receipt) + if err != nil { + return err + } + if err := os.WriteFile(filepath.Join(candidate, pendingReceiptFile), data, 0o600); err != nil { + return err + } + if err := os.Rename(plan.Staging, filepath.Join(candidate, pendingPackageDirectory)); err != nil { + return err + } + return os.Rename(candidate, filepath.Join(targetRoot, plan.ID)) +} + +// ActivatePending is called once before a new process exposes plugin inventory. +// An intervening manual upgrade, uninstall or disable abandons the pending update. +func (s *Service) ActivatePending(ctx context.Context, root string, begin func(context.Context, string) (context.Context, func() error, error), active func(context.Context, string) (string, error)) error { + dir := filepath.Join(root, pendingDirectory) + entries, err := os.ReadDir(dir) + // log-exempt: 预期的缺失:用户从未暂存过自动更新。 + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil || len(entries) == 0 { + return err + } + var failures []error + for _, entry := range entries { + if err := ctx.Err(); err != nil { + return errors.Join(append(failures, err)...) + } + if !entry.IsDir() { + continue + } + if err := s.activatePending(ctx, root, entry.Name(), begin, active); err != nil { + failures = append(failures, err) + } + } + return errors.Join(failures...) +} + +func (s *Service) activatePending(ctx context.Context, root, id string, begin func(context.Context, string) (context.Context, func() error, error), current func(context.Context, string) (string, error)) (err error) { + if err := pluginpkg.CheckIdentity("plugin ID", id); err != nil { + return err + } + work, finish, err := begin(ctx, id) + if err != nil { + return err + } + defer func() { err = errors.Join(err, finish()) }() + ctx = work + pending, err := s.HasPending(root, id) + if err != nil || !pending { + return err + } + dir := filepath.Join(root, pendingDirectory, id) + raw, err := pluginpkg.ReadFile(dir, []string{pendingReceiptFile}, MaxManifestBytes) + if err != nil { + return errors.Join(err, os.RemoveAll(dir)) + } + var receipt pendingReceipt + if err := json.Unmarshal(raw, &receipt); err != nil { + return errors.Join(err, os.RemoveAll(dir)) + } + active, err := current(ctx, id) + if err != nil { + return err + } + if active == "" || active != receipt.BaseVersion || active == receipt.Target.Version { + return os.RemoveAll(dir) + } + base, found, err := s.approvals.Record(id, active) + if err != nil { + return err + } + target := receipt.Target + if target.PluginID != id || target.Validate() != nil || base.ArchiveSHA256 != receipt.BaseSHA256 || + target.Source != plugintrust.Marketplace || target.ContentDigest == "" || + !plugintrust.MayAutoUpdate(base, found, target.MarketplaceIndexURL, plugintrust.Review{ + Permissions: target.Permissions, Programs: target.ApprovedPrograms, + }) { + return errors.Join(errors.New("pending plugin update no longer matches its approval"), os.RemoveAll(dir)) + } + packageDir := filepath.Join(dir, pendingPackageDirectory) + digest, err := pendingContentDigest(ctx, packageDir) + if ctx.Err() != nil { + return ctx.Err() + } + if err != nil || digest != target.ContentDigest { + return errors.Join(ErrArchiveDigest, err, os.RemoveAll(dir)) + } + if err := ctx.Err(); err != nil { + return err + } + manifest, err := readManifest(packageDir) + if err != nil { + return errors.Join(err, os.RemoveAll(dir)) + } + if _, err := pluginhost.Validate(ctx, s.validator, manifest, s.capabilities); err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return errors.Join(err, os.RemoveAll(dir)) + } + if err := ctx.Err(); err != nil { + return err + } + if err := s.approvals.Approve(target); err != nil { + return err + } + if _, err := pluginpkg.Install(root, id, target.Version, packageDir); err != nil { + return err + } + return os.RemoveAll(dir) +} + +// pendingContentDigest checks what will actually execute after a restart. It +// walks only the staging tree and applies the same input and size limits as a ZIP. +func pendingContentDigest(ctx context.Context, root string) (string, error) { + var files []pluginpkg.File + var total int64 + entries := 0 + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + if path == root { + if !entry.IsDir() { + return pluginpkg.ErrUnsafePath + } + return nil + } + entries++ + if entries > pluginpkg.MaxEntries*pluginpkg.MaxPathDepth || len(files) == pluginpkg.MaxEntries { + return pluginpkg.ErrTooManyEntries + } + if entry.IsDir() { + return nil + } + if !entry.Type().IsRegular() { + return pluginpkg.ErrSpecialFile + } + info, err := entry.Info() + if err != nil { + return err + } + if info.Size() > pluginpkg.MaxFileBytes { + return pluginpkg.ErrFileTooLarge + } + total += info.Size() + if total > pluginpkg.MaxExtractedBytes { + return pluginpkg.ErrArchiveTooLarge + } + relative, err := filepath.Rel(root, path) + if err != nil { + return err + } + relative = filepath.ToSlash(relative) + if _, err := pluginpkg.ValidatePath(relative); err != nil { + return err + } + files = append(files, pluginpkg.File{Path: relative, Size: info.Size()}) + return nil + }) + if err != nil { + return "", err + } + sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path }) + return contentDigest(ctx, root, files) +} diff --git a/desktop/internal/plugininstall/pending_test.go b/desktop/internal/plugininstall/pending_test.go new file mode 100644 index 000000000..373f40f40 --- /dev/null +++ b/desktop/internal/plugininstall/pending_test.go @@ -0,0 +1,41 @@ +package plugininstall + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/installedpackagetest" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" +) + +func TestStageUpdateLeavesInstalledPackageUnchanged(t *testing.T) { + if !installedpackagetest.Run(t) { + return + } + root, err := pluginpkg.DefaultRoot() + if err != nil { + t.Fatal(err) + } + staging, err := pluginpkg.NewStaging(root) + if err != nil { + t.Fatal(err) + } + installedpackagetest.Outside(t, staging) + const id = "dev.lithe.test.pending" + const source = "https://example.test/lithe-plugin-index.json" + if err := os.WriteFile(filepath.Join(staging, pluginpkg.ManifestFile), []byte(`{"id":"dev.lithe.test.pending","version":"2.0.0"}`), 0o600); err != nil { + t.Fatal(err) + } + service := &Service{} + previous := plugintrust.Record{PluginID: id, Version: "1.0.0", Source: plugintrust.Marketplace, MarketplaceIndexURL: source} + if err := service.StageAutomatic(Plan{Root: root, Staging: staging, ID: id, Version: "2.0.0", + Source: plugintrust.Marketplace, MarketplaceIndexURL: source}, previous); err != nil { + t.Fatal(err) + } + installedpackagetest.Outside(t, filepath.Join(root, pendingDirectory, id)) + if err := service.DiscardPending(root, id); err != nil { + t.Fatal(err) + } +} diff --git a/desktop/internal/plugininstall/plugininstall.go b/desktop/internal/plugininstall/plugininstall.go index 98d303574..faa007fd6 100644 --- a/desktop/internal/plugininstall/plugininstall.go +++ b/desktop/internal/plugininstall/plugininstall.go @@ -172,7 +172,7 @@ func (s *Service) Prepare(ctx context.Context, request Request) (plan Plan, err if err := checkContentRoot(extracted.ContentRoot, identity.ID); err != nil { return Plan{}, err } - digest, err := ContentDigest(staging, extracted.Files) + digest, err := contentDigest(ctx, staging, extracted.Files) if err != nil { return Plan{}, err } @@ -221,17 +221,20 @@ func (s *Service) Commit(plan Plan) (pluginpkg.Installed, error) { if err != nil { return pluginpkg.Installed{}, err } - record := plugintrust.RecordFor(plan.ID, plan.Version, plugintrust.Request{ + if err := s.approvals.Approve(approvalFor(plan)); err != nil { + return installed, &ApprovalError{Installed: installed, Err: err} + } + return installed, nil +} + +func approvalFor(plan Plan) plugintrust.Record { + return plugintrust.RecordFor(plan.ID, plan.Version, plugintrust.Request{ Source: plan.Source, ArchiveSHA256: plan.ArchiveSHA256, MarketplaceIndexURL: plan.MarketplaceIndexURL, ContentDigest: plan.ContentDigest, Review: plan.Review, }) - if err := s.approvals.Approve(record); err != nil { - return installed, &ApprovalError{Installed: installed, Err: err} - } - return installed, nil } // Discard removes a prepared package that will not be installed. @@ -242,18 +245,18 @@ func (s *Service) Discard(plan Plan) error { return os.RemoveAll(plan.Staging) } -// ContentDigest hashes an extracted tree: for every file, in path order, the +// contentDigest hashes an extracted tree: for every file, in path order, the // path, a NUL, the file's bytes, and a NUL. // // It is the provenance value the contract records alongside the archive digest. // The path order comes from Extract, so the same package always digests the same // way. -func ContentDigest(directory string, files []pluginpkg.File) (string, error) { +func contentDigest(ctx context.Context, directory string, files []pluginpkg.File) (string, error) { hash := sha256.New() for _, file := range files { hash.Write([]byte(file.Path)) hash.Write([]byte{0}) - if err := hashPath(hash, filepath.Join(directory, filepath.FromSlash(file.Path))); err != nil { + if err := hashPath(ctx, hash, filepath.Join(directory, filepath.FromSlash(file.Path)), file.Size); err != nil { return "", err } hash.Write([]byte{0}) @@ -262,16 +265,32 @@ func ContentDigest(directory string, files []pluginpkg.File) (string, error) { } // hashPath streams one file into writer. -func hashPath(writer io.Writer, path string) error { +func hashPath(ctx context.Context, writer io.Writer, path string, size int64) error { file, err := os.Open(path) if err != nil { return err } - copyErr := hashFile(writer, file) + checked := io.LimitReader(contextReader{ctx: ctx, reader: file}, size+1) + copied, copyErr := io.Copy(writer, checked) + if copyErr == nil && copied != size { + copyErr = ErrArchiveDigest + } closeErr := file.Close() return errors.Join(copyErr, closeErr) } +type contextReader struct { + ctx context.Context + reader io.Reader +} + +func (r contextReader) Read(p []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.reader.Read(p) +} + func hashFile(writer io.Writer, source io.Reader) error { copied, copyErr := io.Copy(writer, source) if copyErr != nil { diff --git a/desktop/internal/pluginruntime/runtime.go b/desktop/internal/pluginruntime/runtime.go index d4fb9a6c3..5b36ac56a 100644 --- a/desktop/internal/pluginruntime/runtime.go +++ b/desktop/internal/pluginruntime/runtime.go @@ -17,6 +17,7 @@ import ( "strings" "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/filelock" "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" ) @@ -169,8 +170,14 @@ func (m *Manager) Prepare(ctx context.Context, artifact Artifact, validate func( if err != nil { return result, err } - unlock, err := acquire(ctx, filepath.Join(base, ".lock")) + unlock, err := filelock.Acquire(ctx, filepath.Join(base, ".lock")) if err != nil { + switch { + case errors.Is(err, filelock.ErrInvalid): + err = fmt.Errorf("%w: %w", ErrArtifact, err) + case errors.Is(err, filelock.ErrBusy): + err = fmt.Errorf("%w: %w", ErrBusy, err) + } return result, err } defer func() { err = errors.Join(err, unlock()) }() diff --git a/desktop/internal/pluginservice/lifecycle.go b/desktop/internal/pluginservice/lifecycle.go index 5a0676d7c..5f88e4453 100644 --- a/desktop/internal/pluginservice/lifecycle.go +++ b/desktop/internal/pluginservice/lifecycle.go @@ -18,7 +18,7 @@ import ( // move the directory of a program that runs. stopNative waits for the window's // other native owners, including other project tabs, before stopping the language // server and backend. A failed stop preserves the package and state for retry. -func (s *Service) Uninstall(ctx context.Context, id string, server *LanguageSession, stopNative ...func(context.Context) error) error { +func (s *Service) Uninstall(ctx context.Context, id string, server *LanguageSession, stopNative ...func(context.Context) error) (err error) { release := s.holdRuntimeStop(id) defer release() // A commit already past its cancellation check may finish while stopping. @@ -26,20 +26,33 @@ func (s *Service) Uninstall(ctx context.Context, id string, server *LanguageSess if err := s.stopRuntimePreparations(ctx, id); err != nil { return err } - _, err := s.Manager.Apply(ctx, core.PluginUninstall, id, func() error { return s.stopWithNativePrograms(ctx, id, server, stopNative) }) - return err + unlock, err := s.lockPackageChanges(ctx) + if err != nil { + return err + } + defer func() { err = errors.Join(err, unlock()) }() + _, err = s.Manager.Apply(ctx, core.PluginUninstall, id, func() error { return s.stopWithNativePrograms(ctx, id, server, stopNative) }) + if err != nil { + return err + } + return s.Installer.DiscardPending(s.Root, id) } // Disable records that the user turned plugin id off and stops what it runs, // as Uninstall does, so a disabled plugin keeps no process. Core plans the // choice before the stop, so nothing starts the plugin again while it stops. -func (s *Service) Disable(ctx context.Context, id string, server *LanguageSession, stopNative ...func(context.Context) error) error { +func (s *Service) Disable(ctx context.Context, id string, server *LanguageSession, stopNative ...func(context.Context) error) (err error) { release := s.holdRuntimeStop(id) defer release() if err := s.stopRuntimePreparations(ctx, id); err != nil { return err } - _, err := s.Manager.Apply(ctx, core.PluginDisable, id, func() error { return s.stopWithNativePrograms(ctx, id, server, stopNative) }) + unlock, err := s.lockPackageChanges(ctx) + if err != nil { + return err + } + defer func() { err = errors.Join(err, unlock()) }() + _, err = s.Manager.Apply(ctx, core.PluginDisable, id, func() error { return s.stopWithNativePrograms(ctx, id, server, stopNative) }) return err } diff --git a/desktop/internal/pluginservice/package_lifecycle_test.go b/desktop/internal/pluginservice/package_lifecycle_test.go new file mode 100644 index 000000000..b6cd42fa0 --- /dev/null +++ b/desktop/internal/pluginservice/package_lifecycle_test.go @@ -0,0 +1,111 @@ +package pluginservice + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/installedpackagetest" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +func TestUninstallWaitsForPackagePublicationInAnotherProcess(t *testing.T) { + const pluginID = "dev.lithe.test.publication" + if !installedpackagetest.Run(t) { + return + } + pluginRoot, err := pluginpkg.DefaultRoot() + if err != nil { + t.Fatal(err) + } + if root := os.Getenv("LITHE_TEST_PACKAGE_PUBLICATION_ROOT"); root != "" { + service, err := OpenAnother(core.NewClient(), store.At(filepath.Join(root, "preferences")), pluginRoot) + if err != nil { + t.Fatal(err) + } + if os.Getenv("LITHE_TEST_PACKAGE_PUBLICATION_STEP") == "busy" { + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + err := service.Uninstall(ctx, pluginID, nil, func(context.Context) error { + t.Fatal("uninstall planned removal while the other process held publication") + return nil + }) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("contended uninstall = %v, want deadline exceeded", err) + } + return + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err := service.Uninstall(ctx, pluginID, nil); err != nil { + t.Fatal(err) + } + return + } + + root := t.TempDir() + service, err := Open(core.NewClient(), store.At(filepath.Join(root, "preferences")), pluginRoot) + if err != nil { + t.Fatal(err) + } + installedpackagetest.Outside(t, filepath.Join(pluginRoot, packageChangesLockFile)) + publish := func(version string) { + t.Helper() + staging, err := pluginpkg.NewStaging(service.Root) + if err != nil { + t.Fatal(err) + } + if _, err := pluginpkg.Install(service.Root, pluginID, version, staging); err != nil { + t.Fatal(err) + } + } + child := func(step string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + binary, err := os.Executable() + if err != nil { + t.Fatal(err) + } + command := exec.CommandContext(ctx, binary, "-test.run=^TestUninstallWaitsForPackagePublicationInAnotherProcess$") + command.Env = append(os.Environ(), "LITHE_TEST_PACKAGE_PUBLICATION_ROOT="+root, "LITHE_TEST_PACKAGE_PUBLICATION_STEP="+step) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("uninstall child %s: %v\n%s", step, err, output) + } + } + + publish("1.0.0") + ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + defer cancel() + _, finish, err := service.BeginRuntimeInstallation(ctx, pluginID) + if err != nil { + t.Fatal(err) + } + defer func() { + if finish != nil { + if err := finish(); err != nil { + t.Error(err) + } + } + }() + // The second process cannot take an uninstall snapshot while publication + // owns the files. After it retries, its snapshot includes the new version. + child("busy") + publish("2.0.0") + err = finish() + finish = nil + if err != nil { + t.Fatal(err) + } + child("released") + entries, err := pluginpkg.List(service.Root) + if err != nil || len(entries) != 0 { + t.Fatalf("installed after uninstall = %v, error = %v", entries, err) + } +} diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index df499026e..585047cb9 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -147,6 +147,22 @@ type Service struct { lsGenerations map[languageKey]uint64 } +// ActivatePendingUpdates moves fully approved packages into the installed inventory at startup. +func (s *Service) ActivatePendingUpdates(ctx context.Context) error { + return s.Installer.ActivatePending(ctx, s.Root, s.BeginRuntimeInstallation, func(ctx context.Context, id string) (string, error) { + entries, err := s.CurrentInstalled(ctx) + if err != nil { + return "", err + } + for _, entry := range entries { + if entry.Installed.ID == id && entry.Enabled { + return entry.Installed.Version, nil + } + } + return "", nil + }) +} + // Open assembles the stack over one plugin root and one set of preferences. func Open(kernel Kernel, preferences *store.Store, root string) (*Service, error) { return open(kernel, preferences, root, true) diff --git a/desktop/internal/pluginservice/runtime_lifecycle.go b/desktop/internal/pluginservice/runtime_lifecycle.go index 73dbfe058..dc370d102 100644 --- a/desktop/internal/pluginservice/runtime_lifecycle.go +++ b/desktop/internal/pluginservice/runtime_lifecycle.go @@ -3,14 +3,20 @@ package pluginservice import ( "context" "errors" + "os" "path/filepath" "sync" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/filelock" ) // ErrRuntimeBusy reports a stop still owning a plugin's files. A new approved // installation can retry after that operation finishes; it cannot reopen admission. var ErrRuntimeBusy = errors.New("plugin runtime preparation is stopping") +const packageChangesLockFile = ".package-changes.lock" + type runtimePreparationKey struct{ root, plugin string } // Preparations from different workbenches share the same package and runtime files. @@ -18,9 +24,10 @@ type runtimePreparationKey struct{ root, plugin string } // each Service owns its persistent admission choices. var runtimePreparationCoordinator = struct { sync.Mutex - active map[runtimePreparationKey]map[*runtimePreparation]struct{} - stops map[runtimePreparationKey]int -}{active: make(map[runtimePreparationKey]map[*runtimePreparation]struct{}), stops: make(map[runtimePreparationKey]int)} + active map[runtimePreparationKey]map[*runtimePreparation]struct{} + stops map[runtimePreparationKey]int + installing map[runtimePreparationKey]bool +}{active: make(map[runtimePreparationKey]map[*runtimePreparation]struct{}), stops: make(map[runtimePreparationKey]int), installing: make(map[runtimePreparationKey]bool)} type runtimePreparation struct { service *Service @@ -119,20 +126,60 @@ func (s *Service) allowRuntimePreparationLocked(id string) error { return nil } -// BeginRuntimeInstallation belongs after package approval. Its lifetime includes -// preparation and publication, so an uninstall either refuses this start or waits -// until it can no longer publish a package or recreate the removed state. -func (s *Service) BeginRuntimeInstallation(ctx context.Context, id string) (context.Context, func(), error) { +// lockPackageChanges serializes package and approval writes from desktop +// processes sharing a plugin root. Its pathname stays outside installed versions. +func (s *Service) lockPackageChanges(ctx context.Context) (func() error, error) { + const wait = 30 * time.Second + if err := ctx.Err(); err != nil { + return nil, err + } + if err := os.MkdirAll(s.Root, 0o700); err != nil { + return nil, err + } + bounded, cancel := context.WithTimeout(ctx, wait) + defer cancel() + return filelock.Acquire(bounded, filepath.Join(s.Root, packageChangesLockFile)) +} + +// BeginRuntimeInstallation keeps local cancellation and process-wide package +// publication under the same admission, from rechecking approvals to writing files. +func (s *Service) BeginRuntimeInstallation(ctx context.Context, id string) (context.Context, func() error, error) { + work, finish, err := s.beginRuntimeInstallation(ctx, id) + if err != nil { + return nil, nil, err + } + unlock, err := s.lockPackageChanges(work) + if err != nil { + finish() + return nil, nil, err + } + return work, func() error { + defer finish() + return unlock() + }, nil +} + +func (s *Service) beginRuntimeInstallation(ctx context.Context, id string) (context.Context, func(), error) { runtimePreparationCoordinator.Lock() defer runtimePreparationCoordinator.Unlock() if err := ctx.Err(); err != nil { return nil, nil, err } + key := s.preparationKey(id) + if runtimePreparationCoordinator.installing[key] { + return nil, nil, ErrRuntimeBusy + } if err := s.allowRuntimePreparationLocked(id); err != nil { return nil, nil, err } - ctx, preparation := s.newRuntimePreparationLocked(ctx, s.preparationKey(id)) - return ctx, func() { preparation.finish(nil) }, nil + runtimePreparationCoordinator.installing[key] = true + ctx, preparation := s.newRuntimePreparationLocked(ctx, key) + return ctx, func() { + runtimePreparationCoordinator.Lock() + delete(runtimePreparationCoordinator.installing, key) + runtimePreparationCoordinator.Unlock() + preparation.finish(nil) + }, nil } func (s *Service) stopRuntimePreparations(ctx context.Context, id string) error { diff --git a/desktop/internal/pluginservice/runtimes_test.go b/desktop/internal/pluginservice/runtimes_test.go index e8c792696..827fca9d3 100644 --- a/desktop/internal/pluginservice/runtimes_test.go +++ b/desktop/internal/pluginservice/runtimes_test.go @@ -585,8 +585,12 @@ func TestRuntimeInstallationAdmissionCoversPublicationAfterPreparation(t *testin if err != nil { t.Fatal(err) } - var finishOnce sync.Once - release := func() { finishOnce.Do(finish) } + finishOnce := sync.OnceValue(finish) + release := func() { + if err := finishOnce(); err != nil { + t.Error(err) + } + } t.Cleanup(release) // Preparation has finished, but the approved operation still owns publication. uninstallDone := make(chan struct{}) diff --git a/desktop/internal/plugintrust/store.go b/desktop/internal/plugintrust/store.go index dc1441577..7d002cbd1 100644 --- a/desktop/internal/plugintrust/store.go +++ b/desktop/internal/plugintrust/store.go @@ -22,13 +22,12 @@ type file struct { Plugins map[string]map[string]Record `json:"plugins"` } +// Each workbench opens a Store. The approval file is shared, so its entire +// read-modify-write transaction needs the same process-wide mutex. +var approvalsMu sync.Mutex + // Store keeps approval records in one preference file. -// -// Every method is a whole read-modify-write of that file, and the workbench runs -// each plugin action on its own goroutine, so the mutex is what stops two -// concurrent approvals from overwriting each other. type Store struct { - mu sync.Mutex preferences *store.Store } @@ -39,8 +38,8 @@ func New(preferences *store.Store) *Store { // Record returns the approval stored for one plugin version. func (s *Store) Record(id, version string) (Record, bool, error) { - s.mu.Lock() - defer s.mu.Unlock() + approvalsMu.Lock() + defer approvalsMu.Unlock() contents, err := s.load() if err != nil { return Record{}, false, err @@ -58,8 +57,8 @@ func (s *Store) Record(id, version string) (Record, bool, error) { // Approve stores record, replacing any earlier approval of the same version. func (s *Store) Approve(record Record) error { - s.mu.Lock() - defer s.mu.Unlock() + approvalsMu.Lock() + defer approvalsMu.Unlock() if err := record.Validate(); err != nil { return err } @@ -79,8 +78,8 @@ func (s *Store) Approve(record Record) error { // Forget drops the approval of one plugin version. Removing a version that was // never approved is not an error. func (s *Store) Forget(id, version string) error { - s.mu.Lock() - defer s.mu.Unlock() + approvalsMu.Lock() + defer approvalsMu.Unlock() contents, err := s.load() if err != nil { return err @@ -101,8 +100,8 @@ func (s *Store) Forget(id, version string) error { // List reports every stored approval, ordered by plugin ID then version. func (s *Store) List() ([]Record, error) { - s.mu.Lock() - defer s.mu.Unlock() + approvalsMu.Lock() + defer approvalsMu.Unlock() contents, err := s.load() if err != nil { return nil, err diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 74d4aa568..0c8f5f032 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -751,7 +751,9 @@ type App struct { // buildOptionTexts keeps the build option translation files read per plugin package and language. buildOptionTexts buildOptionTextCache // pluginDownloads holds native temporary file leases for the open settings window. - pluginDownloads *marketplace.ArchiveSession + pluginDownloads *marketplace.ArchiveSession + pluginArchiveCache marketplace.ArchiveCache + pluginStartupCancel context.CancelFunc // prompts are the questions plugins ask the user, one sheet at a time. prompts pluginPrompts // web opens the pages of plugin web tool windows; webReady is set once it can. @@ -1114,6 +1116,11 @@ func (a *App) openPlugins(options Options) { return } a.plugins = service + cache, cacheErr := marketplace.UserArchiveCache() + if cacheErr != nil { + a.backgroundFailed("plugin_archive_cache", cacheErr) + } + a.pluginArchiveCache = cache service.Backend.SetInitializeTimeout(options.PluginInitializeTimeout) service.Backend.SetToolResolver(a.resolveBackendTool) service.Backend.SetToolEntryResolver(a.resolveBackendToolEntry) @@ -1162,18 +1169,7 @@ func (a *App) Run() error { a.post(func(a *App) { a.openSystemDocument(path) }) }) a.startUpdates() - a.startPluginAutoUpdates() - if path := a.startupPath; path != "" { - a.startupPath = "" - a.post(func(a *App) { a.openProject(path) }) - } - if path := a.startupFile; path != "" { - a.startupFile = "" - a.post(func(a *App) { a.openStandaloneFile(path) }) - } - // The plugin stack is assembled before the window exists, because opening a - // window is what installs the invalidator its background work needs. - a.reloadPluginLanguages() + a.startPluginInventory() if !a.documentOnly { a.loadGitHubAccount() } @@ -1190,6 +1186,9 @@ func (a *App) Run() error { } return nil }) + if a.pluginStartupCancel != nil { + a.pluginStartupCancel() + } a.stopPluginAutoUpdates() a.windowLoopEnded(err, faulted.Load()) a.shutdownSessions() diff --git a/desktop/internal/workbench/plugin_auto_update.go b/desktop/internal/workbench/plugin_auto_update.go index 0098bd6cf..60c3e7168 100644 --- a/desktop/internal/workbench/plugin_auto_update.go +++ b/desktop/internal/workbench/plugin_auto_update.go @@ -5,6 +5,7 @@ import ( "errors" "runtime" "strconv" + "sync" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -17,10 +18,11 @@ import ( ) const ( - pluginAutoFirstCheck = 30 * time.Second - pluginAutoInterval = 24 * time.Hour - pluginAutoFetchLimit = 30 * time.Second - pluginAutoMaxSources = 32 + pluginAutoFirstCheck = 30 * time.Second + pluginAutoInterval = 24 * time.Hour + pluginAutoFetchLimit = 30 * time.Second + pluginAutoDownloadLimit = 5 * time.Minute + pluginAutoMaxSources = 32 ) // pluginAutoUpdater is one window's auto-update scheduler, shared by its tabs. @@ -121,12 +123,57 @@ func (a *App) stopPluginAutoUpdates() { } } +// One window owns each check for a plugin root. Other windows wait for the +// shared interval, or retry after an owner was cancelled. +var pluginAutoRounds = struct { + sync.Mutex + roots map[string]*pluginAutoRound +}{roots: make(map[string]*pluginAutoRound)} + +type pluginAutoRound struct { + checking bool + next time.Time +} + +func beginPluginAutoRound(root string, now time.Time) (func(bool), time.Duration) { + pluginAutoRounds.Lock() + defer pluginAutoRounds.Unlock() + for key, round := range pluginAutoRounds.roots { + if !round.checking && !round.next.After(now) { + delete(pluginAutoRounds.roots, key) + } + } + if round := pluginAutoRounds.roots[root]; round != nil { + if round.checking { + return nil, pluginAutoFirstCheck + } + return nil, round.next.Sub(now) + } + round := &pluginAutoRound{checking: true} + pluginAutoRounds.roots[root] = round + return func(cancelled bool) { + pluginAutoRounds.Lock() + defer pluginAutoRounds.Unlock() + if cancelled { + delete(pluginAutoRounds.roots, root) + return + } + round.checking = false + round.next = time.Now().Add(pluginAutoInterval) + }, 0 +} + func (a *App) checkPluginAutoUpdates() { u := a.pluginAuto if u == nil || u.checking || !u.enabled || u.stopped || a.plugins == nil { return } - ctx, cancel := context.WithCancel(context.Background()) + finish, delay := beginPluginAutoRound(a.plugins.Root, time.Now()) + if finish == nil { + a.schedulePluginAutoUpdate(delay) + return + } + ctx, cancel := context.WithCancel(a.operationContext(context.Background())) u.checking, u.cancel = true, cancel sources := a.marketplaceSources() platform := marketplaceHostPlatform() @@ -134,6 +181,7 @@ func (a *App) checkPluginAutoUpdates() { a.background(nil, 0, func(context.Context) func(*App) { defer cancel() count, err := a.performPluginAutoUpdates(ctx, sources, platform, capabilities) + finish(ctx.Err() != nil && count == 0) return func(a *App) { u.checking, u.cancel = false, nil if err != nil && !errors.Is(err, context.Canceled) { @@ -287,7 +335,15 @@ func (a *App) performPluginAutoUpdates(ctx context.Context, sources []PluginReco // set with an existing approved version, and installs without interrupting live // plugin sessions. Permission changes still need manual review. func (a *App) applyPluginAutoUpdate(ctx context.Context, downloader *marketplace.ArchiveDownloader, plugin core.MarketplacePlugin, previous plugintrust.Record) (bool, error) { - archive, err := downloader.Download(ctx, plugin.Availability) + pending, err := a.plugins.Installer.HasPending(a.plugins.Root, plugin.ID) + if err != nil || pending { + return false, err + } + downloadCtx, cancel := context.WithTimeout(ctx, pluginAutoDownloadLimit) + archive, err := a.downloadMarketplacePlugin(downloadCtx, downloader, plugin, previous, func() (*marketplace.DownloadedArchive, error) { + return downloader.Download(downloadCtx, plugin.Availability) + }, nil) + cancel() if err != nil { return false, err } @@ -310,7 +366,7 @@ func (a *App) applyPluginAutoUpdate(ctx context.Context, downloader *marketplace if err != nil { return false, err } - defer finish() + defer func() { a.recordPluginInstallCleanup(work, finish()) }() // A manual change may occur while bytes are downloading; recheck the current // plugin and the approval before publishing, under the runtime coordinator. current, err := a.plugins.CurrentInstalled(work) @@ -336,6 +392,6 @@ func (a *App) applyPluginAutoUpdate(ctx context.Context, downloader *marketplace if err := work.Err(); err != nil { return false, err } - _, err = a.plugins.Installer.Commit(plan) + err = a.plugins.Installer.StageAutomatic(plan, previous) return err == nil, err } diff --git a/desktop/internal/workbench/plugin_auto_update_test.go b/desktop/internal/workbench/plugin_auto_update_test.go index 8cf3ae01e..34cafe8a4 100644 --- a/desktop/internal/workbench/plugin_auto_update_test.go +++ b/desktop/internal/workbench/plugin_auto_update_test.go @@ -6,6 +6,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "io" "net/http" "os" @@ -73,7 +74,14 @@ func TestApprovedPluginAutoSourceOnlyMatchesSavedOrigins(t *testing.T) { // A marketplace update uses the same verified archive and approval path as a // manual install. The previous approved version remains on disk while the next // version is selected, without any real plugin, network, or toolchain. -func TestPluginAutoUpdateInstallsAnApprovedNewVersion(t *testing.T) { +func TestPluginAutoUpdateStagesAnApprovedNewVersionUntilRestart(t *testing.T) { + for _, scenario := range []string{"activate", "disabled before restart", "damaged package"} { + t.Run(scenario, func(t *testing.T) { verifyPendingPluginUpdate(t, scenario) }) + } +} + +func verifyPendingPluginUpdate(t *testing.T, scenario string) { + t.Helper() const id = "io.github.example.output-links" const origin = "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json" const archiveURL = "https://plugins.example.test/auto-update.zip" @@ -160,8 +168,44 @@ func TestPluginAutoUpdateInstallsAnApprovedNewVersion(t *testing.T) { t.Fatalf("auto-updated = %v, request count = %d, error = %v", applied, requests, err) } versions, err := pluginpkg.List(service.Root) + if err != nil || len(versions) != 1 || versions[0].Version != "1.0.0" { + t.Fatalf("installed versions before restart = %+v, error = %v", versions, err) + } + if _, approved, err := service.Manager.Approval(id, "2.0.0"); err != nil || approved { + t.Fatalf("pending approval became active before restart: %v, %v", approved, err) + } + if scenario == "disabled before restart" { + if _, err := service.Manager.Apply(ctx, core.PluginDisable, id, nil); err != nil { + t.Fatal(err) + } + } + if scenario == "damaged package" { + pending := filepath.Join(service.Root, ".pending-updates", id, "package", pluginpkg.ManifestFile) + if err := os.WriteFile(pending, []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + } + activationErr := service.ActivatePendingUpdates(ctx) + if scenario == "damaged package" { + if !errors.Is(activationErr, plugininstall.ErrArchiveDigest) { + t.Fatalf("expected a digest rejection, got %v", activationErr) + } + } else if activationErr != nil { + t.Fatal(activationErr) + } + versions, err = pluginpkg.List(service.Root) + if scenario != "activate" { + if err != nil || len(versions) != 1 || versions[0].Version != "1.0.0" { + t.Fatalf("ineligible plugin was updated: %+v, %v", versions, err) + } + pending, err := service.Installer.HasPending(service.Root, id) + if err != nil || pending { + t.Fatalf("ineligible plugin still has pending update: %v, %v", pending, err) + } + return + } if err != nil || len(versions) != 2 { - t.Fatalf("retained installed versions = %+v, error = %v", versions, err) + t.Fatalf("retained installed versions after restart = %+v, error = %v", versions, err) } selected, err := service.CurrentInstalled(ctx) if err != nil || len(selected) != 1 || selected[0].Installed.Version != "2.0.0" { diff --git a/desktop/internal/workbench/plugin_delta.go b/desktop/internal/workbench/plugin_delta.go new file mode 100644 index 000000000..c85484410 --- /dev/null +++ b/desktop/internal/workbench/plugin_delta.go @@ -0,0 +1,70 @@ +package workbench + +import ( + "context" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" +) + +func (a *App) installedMarketplaceApproval(ctx context.Context, id string) (plugintrust.Record, error) { + entries, err := a.plugins.CurrentInstalled(ctx) + if err != nil { + return plugintrust.Record{}, err + } + for _, entry := range entries { + if entry.Installed.ID == id { + record, _, err := a.plugins.Manager.Approval(id, entry.Installed.Version) + return record, err + } + } + return plugintrust.Record{}, nil +} + +func (a *App) downloadMarketplacePlugin(ctx context.Context, downloader *marketplace.ArchiveDownloader, plugin core.MarketplacePlugin, previous plugintrust.Record, full func() (*marketplace.DownloadedArchive, error), progress func(marketplace.ArchiveProgress)) (*marketplace.DownloadedArchive, error) { + var base marketplace.DeltaBase + if previous.Source == plugintrust.Marketplace && previous.MarketplaceIndexURL != "" && + previous.MarketplaceIndexURL == plugin.MarketplaceIndexURL { + base = marketplace.DeltaBase{Version: previous.Version, SHA256: previous.ArchiveSHA256} + } + kernel, _ := a.kernel.(marketplace.DeltaCore) + return marketplace.New(a.kernel, downloader.HTTPClient()).DownloadUpdate(ctx, kernel, a.pluginArchiveCache, downloader, plugin, + marketplaceHostPlatform(), base, full, progress, func(err error) { + a.backgroundFailedIn(ctx, "plugin_delta", err) + }) +} + +// startPluginInventory runs pending verification off the window thread. The +// startup project and ordinary plugin discovery use the settled inventory. +func (a *App) startPluginInventory() { + service := a.plugins + if service == nil { + a.openStartupDocuments() + return + } + a.pluginStartupCancel = a.background(nil, pluginPrepareTimeout, func(ctx context.Context) func(*App) { + err := service.ActivatePendingUpdates(ctx) + return func(a *App) { + a.pluginStartupCancel = nil + if err != nil && !errors.Is(err, context.Canceled) { + a.backgroundFailed("plugin_activate_pending", err) + } + a.reloadPluginLanguages() + a.startPluginAutoUpdates() + a.openStartupDocuments() + } + }) +} + +func (a *App) openStartupDocuments() { + if path := a.startupPath; path != "" { + a.startupPath = "" + a.post(func(a *App) { a.openProject(path) }) + } + if path := a.startupFile; path != "" { + a.startupFile = "" + a.post(func(a *App) { a.openStandaloneFile(path) }) + } +} diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index b9e725440..12a390114 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -84,7 +84,18 @@ func (a *App) installPlugin(plugin core.MarketplacePlugin, feedback settingswind downloads := a.pluginDownloads a.performed("plugin.install.marketplace", surfaceButton) a.preparePluginInstall(feedback, func(ctx context.Context) (plugininstall.Plan, error) { - archive, err := downloads.Download(ctx, availability, feedback.Progress) + downloader := marketplace.NewArchiveDownloader(nil) + var previous plugintrust.Record + if plugin.MarketplaceDeltasURL != "" { + var err error + previous, err = a.installedMarketplaceApproval(ctx, plugin.ID) + if err != nil && ctx.Err() == nil { + a.backgroundFailedIn(ctx, "plugin_delta_base", err) + } + } + archive, err := a.downloadMarketplacePlugin(ctx, downloader, plugin, previous, func() (*marketplace.DownloadedArchive, error) { + return downloads.Download(ctx, availability, feedback.Progress) + }, feedback.Progress) if err != nil { return plugininstall.Plan{}, err } @@ -198,7 +209,7 @@ func (a *App) recordPluginInstallCleanup(ctx context.Context, err error) { func (a *App) commitPluginInstall(ctx context.Context, plan plugininstall.Plan, feedback settingswindow.PluginInstallFeedback) func(*App) { work, finish, err := a.plugins.BeginRuntimeInstallation(ctx, plan.ID) if err == nil { - defer finish() + defer func() { a.recordPluginInstallCleanup(work, finish()) }() ctx = work err = ctx.Err() } diff --git a/docs/ci-builds.md b/docs/ci-builds.md index e6416fb7b..2ae502d8c 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -72,6 +72,12 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 插件市场 SVG 由网络适配器有界读取,在后台编译为 Viva 图标;下载字节只活到本次编译结束,编译结果与失败仅保存在当前市场页的内存缓存中(最多64项、同时读取最多4个、每次最多256 KiB和10秒)。滚动离屏取消未完成的读取,刷新索引、离开市场标签或关闭设置窗口释放缓存;没有磁盘缓存,不跨工作树复制,不写安装目录,也不影响代码签名或增量更新基线。`TestVisualMarketplaceSVG` 的中英文、明暗主题及加载前后截图写入本工作树的 `.artifacts/marketplace-icons-visual/`,绑定当前源码、固定 Viva/Core 修订、语言、主题和渲染环境,不跨工作树复制,由开发者清理,不进入发行包。 +插件市场的增量基线存放在 `/Lithe/PluginArchives/.zip`。缓存由桌面市场下载层持有,只保留已校验的原始 ZIP,单包最多 64 MiB,总预算 256 MiB 和 128 项,按最早写入淘汰。删除缓存后下一次更新会下载完整包。补丁和重建 ZIP 位于平台临时目录的独占目录,操作结束即清理。批准的后台更新暂存在平台插件数据根的 `.pending-updates/`,启动时复核当前版本和审批后发布进版本目录。下载缓存和暂存属于用户运行时状态,均不跨工作树复制。所有写入都在应用安装目录之外,安装包签名和桌面增量更新基线保持完整。 + +同一缓存目录内的 `.archive-cache.lock` 串行化各进程的淘汰、临时写入和发布。退出临界区时关闭文件句柄,进程退出时由操作系统释放锁。空锁文件留在缓存目录供其他进程使用。锁不可用时跳过归档缓存写入并保留已下载的包。锁属于用户缓存,与缓存一起清理,不跨工作树复制,也不影响代码签名或桌面增量更新基线。 + +插件数据根下的 `.package-changes.lock` 由插件服务持有。激活、发布、禁用和卸载结束后关闭文件句柄,操作系统也会在进程退出时释放锁。空锁文件留在插件数据根供其他进程使用。它属于用户运行时状态,位置在发行目录外,无需在工作树间复制,也不影响代码签名或桌面增量更新基线。 + CLI 用户启动器由 `desktop/internal/cli` 在明确注册时生成到 `/Lithe/cli/bin/lithe`(Windows 为 `lithe.cmd`)。它绑定用户机器与当前应用可执行路径,随用户移除注册删除;它不是编译缓存,不跨工作树复制,不写安装目录,也不影响代码签名和增量更新基线。CLI 与单文件模式的无头截图可写入当前检出的 `.artifacts/cli-single-file/`;它们绑定本次源码、语言、主题、Viva/Core 修订和渲染环境,不跨工作树复制,由开发者或 CI 清理,不进入发行包。 TextMate 首行元数据随各插件归档发布,从已安装版本目录只读加载。宿主的匹配缓存只保留当前进程内的编译结果,没有可跨工作树复用的状态。加载过程不写入应用或插件包,不改变签名和增量更新基线。 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 9e585f183..f067db7fd 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -369,7 +369,10 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # workspace.createEntry, renameEntry, copyEntry and resolveEntry with the codes entry_not_found # and entry_exists, which the desktop calls for a plugin's create, rename, copy, trash and # saveAs (workbench/pluginfilechanges.go). -PINNED_CORE_REVISION="bb0ad53f9100954306fcd139bf0e5003e6a515fe" +# The plugin delta branch (#187) includes current Core main, including the +# built-in file association catalog and plans (#186). It adds the pinned +# companion index and verifies and reconstructs ZIPs for marketplace updates. +PINNED_CORE_REVISION="076ce04e314ecdde790b36ee3f374becb11951a0" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/scripts/desktop/verify/test-runtime-bundle-immutability.mjs b/scripts/desktop/verify/test-runtime-bundle-immutability.mjs index 7f5e62064..9deac5f59 100644 --- a/scripts/desktop/verify/test-runtime-bundle-immutability.mjs +++ b/scripts/desktop/verify/test-runtime-bundle-immutability.mjs @@ -12,6 +12,9 @@ const installedPackageWorkflows = [ ["desktop/internal/idehelp/idehelp_test.go", "TestInstallLeavesTheInstalledPackageUnchanged"], ["desktop/internal/localshell/conpty/conpty_test.go", "TestInstallLeavesTheInstalledPackageUnchanged"], ["desktop/internal/pluginpkg/install_test.go", "TestInstallLeavesTheInstalledPackageUnchanged"], + ["desktop/internal/marketplace/delta_test.go", "TestMarketplaceDeltaLeavesInstalledPackageUnchanged"], + ["desktop/internal/plugininstall/pending_test.go", "TestStageUpdateLeavesInstalledPackageUnchanged"], + ["desktop/internal/pluginservice/package_lifecycle_test.go", "TestUninstallWaitsForPackagePublicationInAnotherProcess"], ]; function workflowTest(name, body = "\tif !installedpackagetest.Run(t) {\n\t\treturn\n\t}\n") { diff --git a/scripts/desktop/verify/verify-runtime-bundle-immutability.sh b/scripts/desktop/verify/verify-runtime-bundle-immutability.sh index 787694f82..0177834d7 100755 --- a/scripts/desktop/verify/verify-runtime-bundle-immutability.sh +++ b/scripts/desktop/verify/verify-runtime-bundle-immutability.sh @@ -65,6 +65,9 @@ installed_package_workflows=( desktop/internal/idehelp/idehelp_test.go:TestInstallLeavesTheInstalledPackageUnchanged desktop/internal/localshell/conpty/conpty_test.go:TestInstallLeavesTheInstalledPackageUnchanged desktop/internal/pluginpkg/install_test.go:TestInstallLeavesTheInstalledPackageUnchanged + desktop/internal/marketplace/delta_test.go:TestMarketplaceDeltaLeavesInstalledPackageUnchanged + desktop/internal/plugininstall/pending_test.go:TestStageUpdateLeavesInstalledPackageUnchanged + desktop/internal/pluginservice/package_lifecycle_test.go:TestUninstallWaitsForPackagePublicationInAnotherProcess ) for workflow in $installed_package_workflows; do workflow_file=${workflow%%:*} diff --git a/shared/platform-feature-matrix/features/plugin-auto-update.json b/shared/platform-feature-matrix/features/plugin-auto-update.json index 30d3d2a0b..f16880264 100644 --- a/shared/platform-feature-matrix/features/plugin-auto-update.json +++ b/shared/platform-feature-matrix/features/plugin-auto-update.json @@ -2,10 +2,10 @@ "id": "plugin-auto-update", "area": "扩展", "group": "插件与主题", - "capability": "插件管理页面可以主动启用或关闭自动更新;宿主在窗口前台定期检查经过 Core 验证的订阅源,只对已启用、来源匹配、发布版本更高且权限和程序声明完全保持已授权范围的插件自动安装,不中断当前插件会话;需新授权的更新仍由用户手动审批,关闭窗口或关闭选项取消后台任务。", + "capability": "插件管理页面可以主动启用或关闭自动更新。宿主在窗口前台定期检查同源且保持已批准权限与程序声明的新版,完整验包与保存批准后暂存在插件数据目录,重启 Lithe 时复核并激活。手动与后台的市场更新共用增量下载,精确基线与补丁均可用时重建并校验完整 ZIP,缺失或失败回退到完整包。", "owner": "Extensions", - "notes": "Viva Go 跨平台实现,默认关闭;首次开启后 30 秒检查,此后每 24 小时检查,窗口不活跃时暂缓。审批来源必须是首次经市场安装时记录的 Core 规范化 IndexURL;旧版本无来源记录的插件需要手动通过商城更新一次以建立来源。下载经市场 SHA-256 验证与安装审查,安装前再次核对启用状态和此前审批;不会通过切换/重启运行中的插件加载新版本。", - "verification": "自动化:desktop/internal/plugintrust/auto_update_test.go 检查同源/同权限/同程序集合,desktop/internal/marketplace/version_test.go 验证 Core 已排序版本判定,desktop/internal/workbench/plugin_auto_update_test.go 检查禁用/换源和版本过滤。手动:在插件设置齿轮开启自动更新,用合成测试市场和两版合成插件验证旧版有来源记录且权限相同时会后台下载、校验并安装;更改权限、程序声明或市场地址时不安装;后台中断/关闭开关后无临时文件与遗留子进程;重启应用后加载最新版本。macOS 和 Windows 真实原生测试及无头截图待执行。", + "notes": "Viva Go 跨平台实现,默认关闭;首次开启后 30 秒检查,此后每 24 小时检查,窗口不活跃时暂缓。审批来源必须是首次经市场安装时记录的 Core 规范化 IndexURL;旧版本无来源记录的插件需要手动通过商城更新一次以建立来源。下载经市场 SHA-256 验证与安装审查,安装前再次核对启用状态和此前审批;不会通过切换/重启运行中的插件加载新版本。同一进程内使用同一个插件数据根的工作台共享更新轮次。可选补丁索引与实际读取的主索引来自同一市场修订,基线从限额缓存读取;批准记录和待激活包都准备完成后才进入下一次启动的候选。共享插件数据根的桌面进程串行发布、禁用和卸载,卸载在加锁后读取安装版本。", + "verification": "自动化:desktop/internal/plugintrust/auto_update_test.go 检查同源/同权限/同程序集合,desktop/internal/marketplace/version_test.go 验证 Core 已排序版本判定,desktop/internal/workbench/plugin_auto_update_test.go 检查禁用/换源和版本过滤。手动:在插件设置齿轮开启自动更新,用合成测试市场和两版合成插件验证旧版有来源记录且权限相同时会后台下载、校验并安装;更改权限、程序声明或市场地址时不安装;后台中断/关闭开关后无临时文件与遗留子进程;重启应用后加载最新版本。macOS 和 Windows 真实原生测试及无头截图待执行。增量运输测试覆盖精确匹配、缺失索引或基线、损坏补丁或基线、目标重建不一致和取消,以及缓存锁不可用时仍交付已验包。安装包只读用例使用实际用户缓存路径。后台验证覆盖重启激活以及在重启前禁用后放弃待更新包。双进程测试覆盖共享缓存的 128 项和 256 MiB 上限、发布期间卸载等待、重试后移除新旧版本及发行包目录只读。", "macos": { "implementationStatus": "implemented", "verificationStatus": "pending", @@ -18,7 +18,12 @@ "desktop/internal/plugintrust/auto_update_test.go", "desktop/internal/plugininstall/plugininstall.go", "desktop/internal/settingswindow/marketplace_view_test.go", - "desktop/internal/settingswindow/visual_capture_test.go" + "desktop/internal/settingswindow/visual_capture_test.go", + "desktop/internal/marketplace/delta.go", + "desktop/internal/marketplace/delta_test.go", + "desktop/internal/marketplace/archive_cache_test.go", + "desktop/internal/plugininstall/pending.go", + "desktop/internal/pluginservice/package_lifecycle_test.go" ] }, "windows": { @@ -33,7 +38,12 @@ "desktop/internal/plugintrust/auto_update_test.go", "desktop/internal/plugininstall/plugininstall.go", "desktop/internal/settingswindow/marketplace_view_test.go", - "desktop/internal/settingswindow/visual_capture_test.go" + "desktop/internal/settingswindow/visual_capture_test.go", + "desktop/internal/marketplace/delta.go", + "desktop/internal/marketplace/delta_test.go", + "desktop/internal/marketplace/archive_cache_test.go", + "desktop/internal/plugininstall/pending.go", + "desktop/internal/pluginservice/package_lifecycle_test.go" ] } } diff --git a/shared/platform-feature-matrix/features/plugin-managed-runtimes.json b/shared/platform-feature-matrix/features/plugin-managed-runtimes.json index 54b23c8a6..f1322f2d7 100644 --- a/shared/platform-feature-matrix/features/plugin-managed-runtimes.json +++ b/shared/platform-feature-matrix/features/plugin-managed-runtimes.json @@ -35,7 +35,7 @@ "evidence": [ "desktop/internal/core/managed_runtimes.go", "desktop/internal/pluginruntime/", - "desktop/internal/pluginruntime/lock_windows.go", + "desktop/internal/filelock/lock_windows.go", "desktop/internal/pluginservice/runtimes.go", "desktop/internal/pluginservice/runtime_lifecycle.go", "desktop/internal/pluginbackend/pluginbackend_test.go",