From e9f733da5cead881474219eeff08f1058e3939bb Mon Sep 17 00:00:00 2001 From: Mucheen <145200703+Mucheen@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:22:30 +0800 Subject: [PATCH 1/5] feat(plugins): add incremental marketplace updates --- .../feature/2026-11-18-plugin-auto-updates.md | 13 +- desktop/internal/core/marketplace.go | 10 +- desktop/internal/core/marketplace_delta.go | 76 ++++++ desktop/internal/marketplace/archive_cache.go | 195 ++++++++++++++ desktop/internal/marketplace/delta.go | 108 ++++++++ desktop/internal/marketplace/delta_test.go | 183 +++++++++++++ desktop/internal/marketplace/service.go | 18 +- desktop/internal/plugininstall/pending.go | 251 ++++++++++++++++++ .../internal/plugininstall/pending_test.go | 41 +++ .../internal/plugininstall/plugininstall.go | 41 ++- desktop/internal/pluginservice/lifecycle.go | 5 +- .../internal/pluginservice/pluginservice.go | 16 ++ .../pluginservice/runtime_lifecycle.go | 21 +- desktop/internal/plugintrust/store.go | 25 +- desktop/internal/toolchain/storage_test.go | 2 +- desktop/internal/workbench/app.go | 25 +- .../internal/workbench/plugin_auto_update.go | 70 ++++- .../workbench/plugin_auto_update_test.go | 48 +++- desktop/internal/workbench/plugin_delta.go | 70 +++++ desktop/internal/workbench/plugins.go | 13 +- docs/ci-builds.md | 2 + scripts/desktop/build-desktop-core.sh | 4 +- .../verify-runtime-bundle-immutability.sh | 2 + .../features/plugin-auto-update.json | 16 +- 24 files changed, 1188 insertions(+), 67 deletions(-) create mode 100644 desktop/internal/core/marketplace_delta.go create mode 100644 desktop/internal/marketplace/archive_cache.go create mode 100644 desktop/internal/marketplace/delta.go create mode 100644 desktop/internal/marketplace/delta_test.go create mode 100644 desktop/internal/plugininstall/pending.go create mode 100644 desktop/internal/plugininstall/pending_test.go create mode 100644 desktop/internal/workbench/plugin_delta.go 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 c2060c70c2..090e2e53d7 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,30 @@ 不要这样做:只看插件 ID 相同就从另一个源替换,或把新增的终端权限和可执行程序视作旧审批覆盖;也不能以卸载旧插件的方式完成自动升级。 +### 手动与后台共享增量下载 + +市场可在同一索引提交发布独立的补丁索引。旧客户端仍能读取主索引,新客户端先确定完整包,再看是否有与原审批中的旧包摘要匹配的补丁。用 Zstandard(zstd)将旧的原始 ZIP 作为参考,在平台临时目录重建目标 ZIP,并验证旧包、补丁和目标包的 SHA-256。缺少可用基线或重建失败时走完整包,取消会结束下载并清理临时数据。下载完成的 ZIP 可在用户缓存保留,以便后续生成精确基线。 + +同一进程内使用同一个插件数据根的工作台共享更新轮次。手动安装和后台暂存在提交阶段争用同一个插件安装入口。后台将包与审批一起准备完成后再提交到待激活目录。下次启动 Lithe 进程时在后台验包,读取启动项目和插件语言清单前复核原版本和审批,只有仍然符合的包才进入已安装目录。例如后台暂存 2.0.0 后再禁用 1.0.0,重启时丢弃待更新包。运行中的会话读取的仍是旧目录。 + ## 考虑过的备选方案 - 默认无条件自动更新:用户没有同意后台下载或插件执行代码更换,拒绝。 - 只比较版本号,不检查来源、权限和程序:会让第三方源或新版程序跨越信任边界,拒绝。 +- 在主索引加入可选补丁字段会让当前旧 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` 覆盖补丁命中、损坏、取消和已安装包只读。 - `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 +56,5 @@ - `desktop/internal/plugintrust/auto_update.go` - `desktop/internal/plugininstall/plugininstall.go` - `desktop/internal/marketplace/service.go` +- `desktop/internal/marketplace/delta.go` +- `desktop/internal/plugininstall/pending.go` diff --git a/desktop/internal/core/marketplace.go b/desktop/internal/core/marketplace.go index 2d182bcf67..9d96739da7 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 0000000000..dfa1bef8c1 --- /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/marketplace/archive_cache.go b/desktop/internal/marketplace/archive_cache.go new file mode 100644 index 0000000000..39d5caae1a --- /dev/null +++ b/desktop/internal/marketplace/archive_cache.go @@ -0,0 +1,195 @@ +package marketplace + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" +) + +const ( + // The maximum base size mirrors the Core delta contract. Larger ZIPs still install normally. + maxDeltaZIPBytes = 64 << 20 + archiveCacheBudget = 256 << 20 + archiveCacheEntries = 128 + cacheStagingLifetime = 24 * time.Hour +) + +var archiveCacheMu sync.Mutex + +// 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) error { + target, err := c.path(digest) + if err != nil { + return err + } + source, err := os.Open(archive.Path()) + if err != nil { + return err + } + defer source.Close() + info, err := source.Stat() + if err != nil { + return err + } + if info.Size() > maxDeltaZIPBytes { + return nil + } + archiveCacheMu.Lock() + defer archiveCacheMu.Unlock() + 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) { + 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/delta.go b/desktop/internal/marketplace/delta.go new file mode 100644 index 0000000000..2a0b4a60f9 --- /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 0000000000..08feea13a3 --- /dev/null +++ b/desktop/internal/marketplace/delta_test.go @@ -0,0 +1,183 @@ +package marketplace + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "os" + "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"} { + 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 == "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) + } + default: + if len(notices) != 1 || strings.Join(requests, " ") != companion+" "+patchURL+" "+zipURL { + t.Fatalf("fallback requested %v, reports %v", requests, notices) + } + } + if cached, err := cache.base(delta.ToSHA256); cached == "" || 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 f7224879be..66019a53de 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 0000000000..6f642e423b --- /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), 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), current func(context.Context, string) (string, error)) error { + if err := pluginpkg.CheckIdentity("plugin ID", id); err != nil { + return err + } + work, finish, err := begin(ctx, id) + if err != nil { + return err + } + defer 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 0000000000..373f40f402 --- /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 98d3035746..faa007fd64 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/pluginservice/lifecycle.go b/desktop/internal/pluginservice/lifecycle.go index 5a0676d7cb..c0633252d2 100644 --- a/desktop/internal/pluginservice/lifecycle.go +++ b/desktop/internal/pluginservice/lifecycle.go @@ -27,7 +27,10 @@ func (s *Service) Uninstall(ctx context.Context, id string, server *LanguageSess return err } _, err := s.Manager.Apply(ctx, core.PluginUninstall, id, func() error { return s.stopWithNativePrograms(ctx, id, server, stopNative) }) - return err + 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, diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index df499026e0..585047cb95 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 73dbfe058d..f9dd0f0700 100644 --- a/desktop/internal/pluginservice/runtime_lifecycle.go +++ b/desktop/internal/pluginservice/runtime_lifecycle.go @@ -18,9 +18,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 @@ -128,11 +129,21 @@ func (s *Service) BeginRuntimeInstallation(ctx context.Context, id string) (cont 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/plugintrust/store.go b/desktop/internal/plugintrust/store.go index dc1441577c..7d002cbd1a 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/toolchain/storage_test.go b/desktop/internal/toolchain/storage_test.go index fbffcb3421..afb23b639d 100644 --- a/desktop/internal/toolchain/storage_test.go +++ b/desktop/internal/toolchain/storage_test.go @@ -99,7 +99,7 @@ func TestSavePinPreservesIgnoreTextAndOvercomesLaterNegation(t *testing.T) { if _, _, err := SavePin(ctx, core.NewClient(), root, ".", "dev.example:compiler", &core.ToolchainPin{Home: "/fixture/tool", Version: "1.0", Provider: "host:system"}, nil); err != nil { t.Fatal(err) } - if got := string(readExactly(t, ignore)); got != before+"\r\n/toolchains/local.json\r\n" { + if got := string(readExactly(t, ignore)); got != before+"\r\n/.gitignore\r\n/toolchains/local.json\r\n" { t.Fatalf("ignore source = %q", got) } if runtime.GOOS != "windows" { diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index f8833a2f7b..dda72c89d1 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) @@ -1157,18 +1164,7 @@ func (a *App) Run() error { } a.window = window 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() } @@ -1185,6 +1181,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 0098bd6cf4..e52118067b 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 } @@ -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 8cf3ae01e7..34cafe8a4f 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 0000000000..c854844103 --- /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 b9e7254401..279d23b3a6 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 } diff --git a/docs/ci-builds.md b/docs/ci-builds.md index c8a364bd25..932f699dcf 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -70,6 +70,8 @@ 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/`,启动时复核当前版本和审批后发布进版本目录。下载缓存和暂存属于用户运行时状态,均不跨工作树复制。所有写入都在应用安装目录之外,安装包签名和桌面增量更新基线保持完整。 + 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 0b2fdef155..44e99677b1 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -369,7 +369,9 @@ 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="aadf63d7f69e762a3b2aac44cb6429f57ca5b880" +# The plugin delta branch exposes the pinned companion index and verifies and +# reconstructs marketplace ZIPs for the desktop's manual and background updates. +PINNED_CORE_REVISION="87c92033b3905d501252139b96543cf9888a89e2" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/scripts/desktop/verify/verify-runtime-bundle-immutability.sh b/scripts/desktop/verify/verify-runtime-bundle-immutability.sh index 787694f82e..4aa1b23f44 100755 --- a/scripts/desktop/verify/verify-runtime-bundle-immutability.sh +++ b/scripts/desktop/verify/verify-runtime-bundle-immutability.sh @@ -65,6 +65,8 @@ 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 ) 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 30d3d2a0ba..44732aef26 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 真实原生测试及无头截图待执行。增量运输测试覆盖精确匹配、缺失索引或基线、损坏补丁或基线、目标重建不一致和取消;安装包只读用例使用实际用户缓存路径。后台验证覆盖重启激活以及在重启前禁用后放弃待更新包。", "macos": { "implementationStatus": "implemented", "verificationStatus": "pending", @@ -18,7 +18,10 @@ "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/plugininstall/pending.go" ] }, "windows": { @@ -33,7 +36,10 @@ "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/plugininstall/pending.go" ] } } From 694216560ceae7ba153514de81db3f22042b87f7 Mon Sep 17 00:00:00 2001 From: Mucheen <145200703+Mucheen@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:23:28 +0800 Subject: [PATCH 2/5] fix(plugins): serialize package changes across processes --- .../feature/2026-11-18-plugin-auto-updates.md | 3 + .../{pluginruntime => filelock}/lock.go | 17 ++- .../{pluginruntime => filelock}/lock_unix.go | 2 +- .../lock_windows.go | 2 +- desktop/internal/plugininstall/pending.go | 6 +- desktop/internal/pluginruntime/runtime.go | 9 +- desktop/internal/pluginservice/lifecycle.go | 18 ++- .../pluginservice/package_lifecycle_test.go | 111 ++++++++++++++++++ .../pluginservice/runtime_lifecycle.go | 44 ++++++- .../internal/pluginservice/runtimes_test.go | 8 +- .../internal/workbench/plugin_auto_update.go | 2 +- desktop/internal/workbench/plugins.go | 2 +- docs/ci-builds.md | 2 + .../verify-runtime-bundle-immutability.sh | 1 + .../features/plugin-auto-update.json | 10 +- .../features/plugin-managed-runtimes.json | 2 +- 16 files changed, 212 insertions(+), 27 deletions(-) rename desktop/internal/{pluginruntime => filelock}/lock.go (78%) rename desktop/internal/{pluginruntime => filelock}/lock_unix.go (93%) rename desktop/internal/{pluginruntime => filelock}/lock_windows.go (94%) create mode 100644 desktop/internal/pluginservice/package_lifecycle_test.go 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 090e2e53d7..ddb32050fa 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 @@ -27,6 +27,8 @@ 同一进程内使用同一个插件数据根的工作台共享更新轮次。手动安装和后台暂存在提交阶段争用同一个插件安装入口。后台将包与审批一起准备完成后再提交到待激活目录。下次启动 Lithe 进程时在后台验包,读取启动项目和插件语言清单前复核原版本和审批,只有仍然符合的包才进入已安装目录。例如后台暂存 2.0.0 后再禁用 1.0.0,重启时丢弃待更新包。运行中的会话读取的仍是旧目录。 +不同进程共享插件数据根。激活、手动安装、后台暂存、禁用和卸载使用同一个原生文件锁。卸载先取消并等待进程内的安装任务,再加锁让 Core 读取安装快照。这样即使另一个窗口刚刚激活新版,卸载计划也会包含它。锁文件保留在可写的插件数据根,进程退出时由操作系统释放锁。 + ## 考虑过的备选方案 - 默认无条件自动更新:用户没有同意后台下载或插件执行代码更换,拒绝。 @@ -45,6 +47,7 @@ - `./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` 覆盖补丁命中、损坏、取消和已安装包只读。 +- `TestUninstallWaitsForPackagePublicationInAnotherProcess` 用两个进程验证卸载等待发布,并在重试后删除新旧两个版本。测试同时核验发行包内容未改变。 - `node scripts/i18n/generate-i18n.mjs --check`、`./scripts/platform-feature-matrix/verify-platform-feature-matrix.sh`、`./scripts/agent-notes/verify-agent-notes.sh`。 - 在合成插件市场的自动更新场景,观察安装文件、批准记录、运行中的旧进程和重启后新版本;拒绝案例不得提交任何安装。 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 ac28bc2f5f..db6b6dfb69 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 4eae6187d8..4ce41a8f2a 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 ef7fbb7c85..659e7ac8ba 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/plugininstall/pending.go b/desktop/internal/plugininstall/pending.go index 6f642e423b..b6e21b0595 100644 --- a/desktop/internal/plugininstall/pending.go +++ b/desktop/internal/plugininstall/pending.go @@ -92,7 +92,7 @@ func (s *Service) StageAutomatic(plan Plan, previous plugintrust.Record) (err er // 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), active func(context.Context, string) (string, error)) error { +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: 预期的缺失:用户从未暂存过自动更新。 @@ -117,7 +117,7 @@ func (s *Service) ActivatePending(ctx context.Context, root string, begin func(c return errors.Join(failures...) } -func (s *Service) activatePending(ctx context.Context, root, id string, begin func(context.Context, string) (context.Context, func(), error), current func(context.Context, string) (string, error)) error { +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 } @@ -125,7 +125,7 @@ func (s *Service) activatePending(ctx context.Context, root, id string, begin fu if err != nil { return err } - defer finish() + defer func() { err = errors.Join(err, finish()) }() ctx = work pending, err := s.HasPending(root, id) if err != nil || !pending { diff --git a/desktop/internal/pluginruntime/runtime.go b/desktop/internal/pluginruntime/runtime.go index d4fb9a6c38..5b36ac56a0 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 c0633252d2..5f88e4453f 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,7 +26,12 @@ 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) }) + 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 } @@ -36,13 +41,18 @@ func (s *Service) Uninstall(ctx context.Context, id string, server *LanguageSess // 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 0000000000..b6cd42fa08 --- /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/runtime_lifecycle.go b/desktop/internal/pluginservice/runtime_lifecycle.go index f9dd0f0700..dc370d102a 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. @@ -120,10 +126,40 @@ 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 { diff --git a/desktop/internal/pluginservice/runtimes_test.go b/desktop/internal/pluginservice/runtimes_test.go index e8c7926963..827fca9d3e 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/workbench/plugin_auto_update.go b/desktop/internal/workbench/plugin_auto_update.go index e52118067b..60c3e71681 100644 --- a/desktop/internal/workbench/plugin_auto_update.go +++ b/desktop/internal/workbench/plugin_auto_update.go @@ -366,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) diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index 279d23b3a6..12a390114c 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -209,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 932f699dcf..7b4a305fc8 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -72,6 +72,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 插件市场的增量基线存放在 `/Lithe/PluginArchives/.zip`。缓存由桌面市场下载层持有,只保留已校验的原始 ZIP,单包最多 64 MiB,总预算 256 MiB 和 128 项,按最早写入淘汰。删除缓存后下一次更新会下载完整包。补丁和重建 ZIP 位于平台临时目录的独占目录,操作结束即清理。批准的后台更新暂存在平台插件数据根的 `.pending-updates/`,启动时复核当前版本和审批后发布进版本目录。下载缓存和暂存属于用户运行时状态,均不跨工作树复制。所有写入都在应用安装目录之外,安装包签名和桌面增量更新基线保持完整。 +插件数据根下的 `.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/verify/verify-runtime-bundle-immutability.sh b/scripts/desktop/verify/verify-runtime-bundle-immutability.sh index 4aa1b23f44..0177834d7d 100755 --- a/scripts/desktop/verify/verify-runtime-bundle-immutability.sh +++ b/scripts/desktop/verify/verify-runtime-bundle-immutability.sh @@ -67,6 +67,7 @@ installed_package_workflows=( 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 44732aef26..3889ddbcda 100644 --- a/shared/platform-feature-matrix/features/plugin-auto-update.json +++ b/shared/platform-feature-matrix/features/plugin-auto-update.json @@ -4,8 +4,8 @@ "group": "插件与主题", "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 真实原生测试及无头截图待执行。增量运输测试覆盖精确匹配、缺失索引或基线、损坏补丁或基线、目标重建不一致和取消;安装包只读用例使用实际用户缓存路径。后台验证覆盖重启激活以及在重启前禁用后放弃待更新包。双进程测试覆盖发布期间卸载等待、重试后移除新旧版本及发行包目录只读。", "macos": { "implementationStatus": "implemented", "verificationStatus": "pending", @@ -21,7 +21,8 @@ "desktop/internal/settingswindow/visual_capture_test.go", "desktop/internal/marketplace/delta.go", "desktop/internal/marketplace/delta_test.go", - "desktop/internal/plugininstall/pending.go" + "desktop/internal/plugininstall/pending.go", + "desktop/internal/pluginservice/package_lifecycle_test.go" ] }, "windows": { @@ -39,7 +40,8 @@ "desktop/internal/settingswindow/visual_capture_test.go", "desktop/internal/marketplace/delta.go", "desktop/internal/marketplace/delta_test.go", - "desktop/internal/plugininstall/pending.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 54b23c8a60..f1322f2d79 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", From 0b904e2a644603ceed5e0fafd5e5a0aea6116b35 Mon Sep 17 00:00:00 2001 From: Mucheen <145200703+Mucheen@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:33:59 +0800 Subject: [PATCH 3/5] test(desktop): cover new bundle checks in the gate fixture --- scripts/desktop/verify/test-runtime-bundle-immutability.mjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/desktop/verify/test-runtime-bundle-immutability.mjs b/scripts/desktop/verify/test-runtime-bundle-immutability.mjs index 7f5e620647..9deac5f598 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") { From 650d0d03a59d1c86793b17d8b950af4eb5d2b5ea Mon Sep 17 00:00:00 2001 From: Mucheen <145200703+Mucheen@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:17:45 +0800 Subject: [PATCH 4/5] fix(desktop): resolve Viva dev identity check failures Keep keys on the containers and controls that use them, and let context menus inherit their trigger identity. Start from the relevant changes in 1lck/Lithe-IDEA#2355 and cover the other failures found by the complete dev suite. Pin the fork main revision from Lithe-IDEA/Lithe-viva#58 for the upstream textview menu fix. --- ...2026-11-23-viva-element-identity-checks.md | 37 ++++++++++++++++ desktop/go.mod | 4 +- desktop/go.sum | 4 +- .../settingswindow/ai_generation_view.go | 2 +- .../settingswindow/build_directory_view.go | 22 +++++----- .../settingswindow/command_install.go | 14 +++--- .../internal/settingswindow/installed_view.go | 34 +++++++------- .../settingswindow/plugin_settings_view.go | 4 +- .../settingswindow/remote_workspace_view.go | 8 ++-- .../source_settings_entries_view.go | 15 +++---- .../internal/settingswindow/stepping_view.go | 10 ++--- .../settingswindow/trusted_locations_view.go | 4 +- .../settingswindow/version_control_view.go | 2 +- .../internal/settingswindow/window_view.go | 12 ++--- desktop/internal/workbench/aicommit_view.go | 2 +- desktop/internal/workbench/branch_view.go | 2 +- desktop/internal/workbench/build_options.go | 10 ++--- .../workbench/build_options_runtime.go | 14 +++--- desktop/internal/workbench/build_tree_view.go | 12 ++--- desktop/internal/workbench/chrome_view.go | 34 +++++++------- desktop/internal/workbench/commit_view.go | 2 +- desktop/internal/workbench/debug_view.go | 4 +- desktop/internal/workbench/debug_watch.go | 4 +- desktop/internal/workbench/difftab_view.go | 3 ++ desktop/internal/workbench/editor_view.go | 14 +++--- desktop/internal/workbench/git_gutter.go | 2 +- .../internal/workbench/gitlog_popover_view.go | 2 +- .../workbench/gitpush_workspace_view.go | 6 +-- .../internal/workbench/gitreview_diff_view.go | 2 +- desktop/internal/workbench/inlineedit_view.go | 4 +- .../internal/workbench/local_history_view.go | 4 +- desktop/internal/workbench/memory_monitor.go | 2 +- .../internal/workbench/new_project_view.go | 4 +- desktop/internal/workbench/notifications.go | 2 +- .../workbench/pluginsemantics_hover.go | 2 +- desktop/internal/workbench/problems_view.go | 5 ++- desktop/internal/workbench/recent_files.go | 4 +- .../internal/workbench/remote_browse_view.go | 2 +- .../internal/workbench/remote_container.go | 2 +- .../internal/workbench/remote_detail_view.go | 30 ++++++------- .../internal/workbench/remote_devcontainer.go | 8 ++-- .../workbench/remote_host_containers.go | 6 +-- desktop/internal/workbench/remote_import.go | 32 +++++++------- desktop/internal/workbench/remote_list.go | 12 ++--- .../workbench/remote_port_rules_view.go | 44 +++++++++---------- .../internal/workbench/remote_ports_view.go | 18 ++++---- desktop/internal/workbench/remote_steps.go | 8 ++-- desktop/internal/workbench/remote_trust.go | 2 +- desktop/internal/workbench/remote_view.go | 2 +- desktop/internal/workbench/remote_wsl.go | 2 +- desktop/internal/workbench/run_view.go | 19 ++++---- .../workbench/runconfig_before_launch.go | 6 +-- .../workbench/runconfig_dialog_view.go | 36 ++++++++------- desktop/internal/workbench/runconfig_steps.go | 8 ++-- desktop/internal/workbench/runconfig_view.go | 23 +++++----- .../internal/workbench/search_replace_view.go | 4 +- desktop/internal/workbench/signature_help.go | 2 +- desktop/internal/workbench/tabstrip.go | 8 ++-- desktop/internal/workbench/terminal_menu.go | 4 +- desktop/internal/workbench/vcs_view.go | 2 +- desktop/internal/workbench/viewer_view.go | 4 +- desktop/internal/workbench/window_sessions.go | 8 ++-- .../features/settings-about-page.json | 8 ++-- .../features/workbench-tool-stripe-icons.json | 2 +- 64 files changed, 331 insertions(+), 283 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-11-23-viva-element-identity-checks.md diff --git a/.agents/notes/implemented/bug-fix/2026-11-23-viva-element-identity-checks.md b/.agents/notes/implemented/bug-fix/2026-11-23-viva-element-identity-checks.md new file mode 100644 index 0000000000..f5f5f43daa --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-23-viva-element-identity-checks.md @@ -0,0 +1,37 @@ +# Agent 笔记:Viva 控件的身份键 + +状态:已实现 + +## 先说结论 + +Viva 用 `Key` 和 `Part` 给接下来声明的控件或容器指定身份,以便跨帧识别它。把键放在实际接收它的控件上,并在确定控件会显示时才设置。桌面 CI 的 `dev` 测试会把未被接收的键报为错误。 + +## 问题 + +关于页的面包屑给静态文本设置了键,工作台工具条的上下文菜单也设置了键。菜单从锚点继承身份,遗留的键直到下一次绘制间距时才报错。跳过控件的条件分支也会留下键,例如没有调试适配器时直接返回的选择器。 + +旧版 Viva 的可选中文本视图(`textview`)也会在菜单关闭时遗留键。桌面固定到已收到上游修复的 fork 提交。参见 [Lithe-viva #58](https://github.com/Lithe-IDEA/Lithe-viva/pull/58)。 + +## 决策 + +文本、图标和间距等静态元素直接使用当前上下文。上下文菜单继续使用触发按钮的锚点。组件可能提前返回时,把键从调用组件的位置移到实际绘制控件的位置。例如,仅在有适配器时调用 `ui.Select(c.Part("adapter"), …)`。 + +## 考虑过的备选方案 + +在每段静态文本或间距外包一层容器也能让键有接收者,但会增加布局节点,并让静态标记参加身份管理。直接去掉这些键,继续使用原有布局元素。 + +## 后果 + +设置页和工作台继续使用原有的布局及菜单锚点。新组件增加空状态或提前返回的分支后,需检查键是否仍在同一分支被消费。 + +## 验证 + +- `scripts/desktop/desktop-go.sh test -tags dev ./internal/settingswindow ./internal/pluginview ./internal/workbench`。修复前,关于页和默认工作台在身份键检查处报错。既有回归测试覆盖这两条渲染路径和空适配器状态。 + +## 适用范围 + +- `desktop/internal/settingswindow/window_view.go` +- `desktop/internal/workbench/chrome_view.go` +- `desktop/internal/workbench/debug_view.go` +- `desktop/go.mod` +- `scripts/desktop/check.sh` diff --git a/desktop/go.mod b/desktop/go.mod index fecc5bea0d..a29aca8c7e 100644 --- a/desktop/go.mod +++ b/desktop/go.mod @@ -9,7 +9,7 @@ toolchain go1.27.4 require ( github.com/creack/pty v1.1.24 github.com/tailscale/hujson v0.0.0-20260727124030-b80ff77dac4f - github.com/vivaui/viva v0.6.7-0.20261121062827-3abb3dbb4259 + github.com/vivaui/viva v0.6.8-0.20261123124712-471ea7ab5f81 github.com/zalando/go-keyring v0.2.8 golang.org/x/sys v0.50.0 ) @@ -21,4 +21,4 @@ require ( github.com/pelletier/go-toml/v2 v2.4.3 // indirect ) -replace github.com/vivaui/viva => github.com/Lithe-IDEA/viva v0.6.7-0.20261123062230-3c6c46081fe6 +replace github.com/vivaui/viva => github.com/Lithe-IDEA/viva v0.6.8-0.20261123134538-bb85256c8ffa diff --git a/desktop/go.sum b/desktop/go.sum index ab1b5e2136..98177a3124 100644 --- a/desktop/go.sum +++ b/desktop/go.sum @@ -1,5 +1,5 @@ -github.com/Lithe-IDEA/viva v0.6.7-0.20261123062230-3c6c46081fe6 h1:w1ZfpHUsHEdY/rlQspiZcAAHsNcIEDH0iQ/NvPzVTJ4= -github.com/Lithe-IDEA/viva v0.6.7-0.20261123062230-3c6c46081fe6/go.mod h1:e9In6+J77G7B9ow4enZ2FSOFh7U3q4cQ5iJr3Qn/Olk= +github.com/Lithe-IDEA/viva v0.6.8-0.20261123134538-bb85256c8ffa h1:lNYl2wt5F84gu3b3DiDcjq86T+p0oeN0DZHSkdkbAlA= +github.com/Lithe-IDEA/viva v0.6.8-0.20261123134538-bb85256c8ffa/go.mod h1:e9In6+J77G7B9ow4enZ2FSOFh7U3q4cQ5iJr3Qn/Olk= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= diff --git a/desktop/internal/settingswindow/ai_generation_view.go b/desktop/internal/settingswindow/ai_generation_view.go index 0d97dc6b57..b870328211 100644 --- a/desktop/internal/settingswindow/ai_generation_view.go +++ b/desktop/internal/settingswindow/ai_generation_view.go @@ -30,7 +30,7 @@ func (w *window) generationCard(c ui.C) { ui.Text(c, i18n.Shared(w.marketLanguage(), "desktop.settings.aiGeneration.loading")).FontSize(12).Color(w.pal.muted) } for _, source := range []string{"codex", "claude"} { - ui.Wrap(c.Key("gen/"+source), w.generationSourceLine(w.marketLanguage(), source, st.providers, st.loaded)).FontSize(12).Color(w.pal.muted) + ui.Wrap(c, w.generationSourceLine(w.marketLanguage(), source, st.providers, st.loaded)).FontSize(12).Color(w.pal.muted) } provider := generationIndex(generationProviderChoices[:], current.Provider) providers := []int{0, 1, 2} diff --git a/desktop/internal/settingswindow/build_directory_view.go b/desktop/internal/settingswindow/build_directory_view.go index 2d9fe06fea..09d6415d70 100644 --- a/desktop/internal/settingswindow/build_directory_view.go +++ b/desktop/internal/settingswindow/build_directory_view.go @@ -40,8 +40,8 @@ func (w *window) buildPage(c ui.C) { ui.Column(c).FillWidth().MaxWidth(buildPageWidth).PadSides(buildPagePadTop, buildPagePadX, buildPagePadEnd, buildPagePadX).Children(func() { ui.Text(c, titleOf(&w.text.Settings, pageBuild)).FontSize(buildHeading).Weight(gfx.WeightBold).Color(b.text).Ellipsis() ui.Row(c).Height(12).Shrink(0) - w.buildIssues(c.Part("issues"), language) - w.buildDirectory(c.Part("directory"), language) + w.buildIssues(c, language) + w.buildDirectory(c, language) ui.Wrap(c, i18n.Shared(language, "desktop.buildSettings.directoryNote")).FontSize(11.5).Color(b.faint) }) }) @@ -69,7 +69,7 @@ func (w *window) buildIssues(c ui.C, language i18n.Language) { scope := t.current() var chosen *core.ToolchainSettingsIssue all := false - ui.Column(c).FillWidth().MinWidth(0).Shrink(0).PadX(10).PadY(8).Radius(8). + ui.Column(c.Part("issues")).FillWidth().MinWidth(0).Shrink(0).PadX(10).PadY(8).Radius(8). Border(1, colors.border).Background(colors.background).Children(func() { ui.Text(c, issuesTitle(language, view.Counts.Problems)). FontSize(buildSmall).Weight(gfx.WeightSemibold).Color(colors.text).Ellipsis() @@ -89,11 +89,11 @@ func (w *window) buildIssues(c ui.C, language i18n.Language) { } row.Children(func() { dot(k, 8, b.statusColor(issue.Status)) - ui.Text(k, name).FontSize(buildSmall).Weight(gfx.WeightSemibold).Color(colors.text).Shrink(0) - ui.Text(k, w.toolchainReasonText(language, scope, entry, toolchainReason(entry.tool))). + ui.Text(c, name).FontSize(buildSmall).Weight(gfx.WeightSemibold).Color(colors.text).Shrink(0) + ui.Text(c, w.toolchainReasonText(language, scope, entry, toolchainReason(entry.tool))). FontSize(buildSmall).Color(colors.text).Shrink(1).MinWidth(0).Ellipsis() - ui.Spacer(k) - ui.Text(k, "›").FontSize(buildSmall).Color(colors.text).Shrink(0) + ui.Spacer(c) + ui.Text(c, "›").FontSize(buildSmall).Color(colors.text).Shrink(0) }) } if view.Counts.Problems > len(view.Issues) { @@ -149,7 +149,7 @@ func (w *window) directory(c ui.C, entries []directoryEntry) { } b := &w.bp var open func() - ui.Column(c).FillWidth().MinWidth(0).Shrink(0).Pad(4).Radius(10).Border(1, b.line).Background(b.surface).Children(func() { + ui.Column(c.Part("directory")).FillWidth().MinWidth(0).Shrink(0).Pad(4).Radius(10).Border(1, b.line).Background(b.surface).Children(func() { for i := range entries { entry := &entries[i] k := c.Key(entry.key) @@ -165,14 +165,14 @@ func (w *window) directory(c ui.C, entries []directoryEntry) { row.Children(func() { w.glyphTile(k, entry.tile, entry.icon, 28) ui.Column(k).Grow(1).Shrink(1).MinWidth(0).Children(func() { - ui.Text(k, entry.title).FontSize(buildFont).Weight(gfx.WeightSemibold).Color(b.text).Ellipsis() + ui.Text(c, entry.title).FontSize(buildFont).Weight(gfx.WeightSemibold).Color(b.text).Ellipsis() ui.Row(k).Height(2).Shrink(0) - ui.Text(k, entry.desc).FontSize(buildSmall).Color(b.sub).Ellipsis() + ui.Text(c, entry.desc).FontSize(buildSmall).Color(b.sub).Ellipsis() }) if entry.problems > 0 { w.badge(k, entry.problems, false) } - ui.Text(k, "›").FontSize(buildFont).Color(b.faint).Shrink(0) + ui.Text(c, "›").FontSize(buildFont).Color(b.faint).Shrink(0) }) } }) diff --git a/desktop/internal/settingswindow/command_install.go b/desktop/internal/settingswindow/command_install.go index d1a184151d..9fcda447dc 100644 --- a/desktop/internal/settingswindow/command_install.go +++ b/desktop/internal/settingswindow/command_install.go @@ -341,7 +341,7 @@ func (w *window) commandMissingBanner(c ui.C, language i18n.Language, fact Plugi for index, entry := range missing { k := c.KeyInt(index) ui.Row(k).FillWidth().Gap(8).Pad(10).Radius(8).Items(ui.Center).Stroke(1, w.pal.line).Background(w.pal.card).Children(func() { - ui.Wrap(k, i18n.SharedFormat(language, "desktop.plugins.commandMissingBanner", map[string]string{"commands": commandList(entry.Commands)})). + ui.Wrap(c, i18n.SharedFormat(language, "desktop.plugins.commandMissingBanner", map[string]string{"commands": commandList(entry.Commands)})). FontSize(12).Color(w.pal.warning).Grow(1).Shrink(1).MinWidth(0) if entry.Installer == "" { w.infoButton(k, i18n.Shared(language, "desktop.plugins.commandMissingManual")) @@ -477,8 +477,8 @@ func (w *window) commandInstallOffer(c ui.C, language i18n.Language, dialog *com // and the digest are monospaced. labelled := func(k ui.C, label, value string) { ui.Row(k).FillWidth().Gap(6).Children(func() { - ui.Text(k, label).FontSize(11).Color(w.pal.muted).Shrink(0) - ui.Wrap(k, value).Mono().FontSize(11).Color(w.pal.muted).Grow(1).Shrink(1).MinWidth(0) + ui.Text(c, label).FontSize(11).Color(w.pal.muted).Shrink(0) + ui.Wrap(c, value).Mono().FontSize(11).Color(w.pal.muted).Grow(1).Shrink(1).MinWidth(0) }) } ui.Column(c).FillWidth().Gap(2).Pad(8).Radius(6).Background(w.pal.card).Stroke(1, w.pal.line).Children(func() { @@ -508,9 +508,9 @@ func (w *window) commandInstallOffer(c ui.C, language i18n.Language, dialog *com ui.Column(k).FillWidth().Gap(2).Children(func() { w.radio(k, &dialog.target, target.Target, label, target.Directory == "") ui.Column(k).FillWidth().Gap(2).PadLeft(radioSize + 8).Children(func() { - ui.Wrap(k, help).FontSize(11).Color(w.pal.muted) + ui.Wrap(c, help).FontSize(11).Color(w.pal.muted) if target.Directory != "" { - ui.Wrap(k, target.Directory).Mono().FontSize(11).Color(w.pal.subtle) + ui.Wrap(c, target.Directory).Mono().FontSize(11).Color(w.pal.subtle) } }) }) @@ -523,8 +523,8 @@ func (w *window) commandInstallOffer(c ui.C, language i18n.Language, dialog *com } ui.Text(c, i18n.Shared(language, "desktop.plugins.commandInstallCommand")).FontSize(13).Bold().PadTop(4) ui.Column(c).FillWidth().Gap(2).Pad(8).Radius(6).Background(w.pal.card).Stroke(1, w.pal.line).Children(func() { - for index, variable := range chosen.Environment { - ui.Wrap(c.KeyInt(index), variable).Mono().FontSize(11).Color(w.pal.muted) + for _, variable := range chosen.Environment { + ui.Wrap(c, variable).Mono().FontSize(11).Color(w.pal.muted) } ui.Wrap(c, chosen.CommandLine).Mono().FontSize(11).Color(w.pal.text) }) diff --git a/desktop/internal/settingswindow/installed_view.go b/desktop/internal/settingswindow/installed_view.go index 2ece9de7a8..e8f86eaa9d 100644 --- a/desktop/internal/settingswindow/installed_view.go +++ b/desktop/internal/settingswindow/installed_view.go @@ -371,7 +371,7 @@ func (w *window) installedChip(c ui.C, language i18n.Language, filter int) { chip = chip.Stroke(1, w.pal.border).Hover(ui.Look{}.Background(w.pal.hover)) } chip.Children(func() { - ui.Text(k, title).FontSize(11).Weight(weight).Color(w.pal.text) + ui.Text(c, title).FontSize(11).Weight(weight).Color(w.pal.text) }) if chip.Clicked() { s.filter = filter @@ -398,8 +398,8 @@ func (w *window) installedSlashMenu(c ui.C, language i18n.Language) { HitWith(ui.ID(k), title, gfx.HitOptions{Role: gfx.RoleMenuItem, Cursor: gfx.PointerCursorHand}). Hover(ui.Look{}.Background(w.pal.hover)) option.Children(func() { - ui.Text(k, "/"+token).Mono().FontSize(12).Color(w.pal.text).Width(92).Shrink(0) - ui.Text(k, title).FontSize(11).Color(w.pal.muted).Ellipsis() + ui.Text(c, "/"+token).Mono().FontSize(12).Color(w.pal.text).Width(92).Shrink(0) + ui.Text(c, title).FontSize(11).Color(w.pal.muted).Ellipsis() }) if option.Clicked() { s.filter, s.query = filter, "" @@ -450,7 +450,7 @@ func (w *window) installedList(c ui.C, language i18n.Language, facts []PluginFac available := i18n.Shared(language, "native.updateAvailable.variant2") ui.Row(k).Size(16, 16).Shrink(0).Radius(8).Background(w.pal.accent).Center(). HitWith(ui.ID(k), available, gfx.HitOptions{Role: gfx.RoleStatus}).Tooltip(available).Children(func() { - ui.Icon(k, icons.ArrowUp).Size(10, 10).Color(w.pal.white) + ui.Icon(c, icons.ArrowUp).Size(10, 10).Color(w.pal.white) }) } w.enabledMark(row.C, w.pluginState(fact.ID).Enabled) @@ -685,13 +685,13 @@ func (w *window) installedTabs(c ui.C, language i18n.Language, fact PluginFacts) HitWith(ui.ID(k), title, gfx.HitOptions{Role: gfx.RoleTab, Cursor: gfx.PointerCursorHand, Selected: chosen}) button.Children(func() { ui.Row(k).Gap(5).Items(ui.Center).Children(func() { - text := ui.Text(k, title).FontSize(13).Color(w.pal.muted) + text := ui.Text(c, title).FontSize(13).Color(w.pal.muted) if chosen { text.Weight(gfx.WeightSemibold).Color(w.pal.text) } if counts[tab] > 0 { ui.Row(k).PadX(5).PadY(1).Radius(100).Background(w.pal.selectionIdle).Children(func() { - ui.Text(k, strconv.Itoa(counts[tab])).FontSize(10).Weight(gfx.WeightMedium).Color(w.pal.muted) + ui.Text(c, strconv.Itoa(counts[tab])).FontSize(10).Weight(gfx.WeightMedium).Color(w.pal.muted) }) } }) @@ -842,9 +842,9 @@ func (w *window) configureInSettings(c ui.C, language i18n.Language, fact Plugin if entry.page.Kind == "buildSystem" { icon = icons.Play } - ui.Icon(k, icon).Size(14, 14).Color(w.pal.muted).Shrink(0) + ui.Icon(c, icon).Size(14, 14).Color(w.pal.muted).Shrink(0) if entry.subjects != "" { - ui.Text(k, entry.subjects).FontSize(12).Color(w.pal.muted).Shrink(1).MinWidth(0).Ellipsis() + ui.Text(c, entry.subjects).FontSize(12).Color(w.pal.muted).Shrink(1).MinWidth(0).Ellipsis() } if ui.Button(k, entry.page.Title).Link().Clicked() { key, pluginID := entry.page.Key, fact.ID @@ -923,24 +923,24 @@ func (w *window) installedFeatures(c ui.C, language i18n.Language, fact PluginFa for index, capability := range fact.Capabilities { k := c.KeyInt(index) ui.Column(k).FillWidth().Gap(5).Pad(12).Radius(8).Background(w.pal.card).Stroke(1, w.pal.line).Children(func() { - ui.Text(k, capabilityKindTitle(language, capability.Kind)).FontSize(11).Weight(gfx.WeightMedium).Color(w.pal.muted) + ui.Text(c, capabilityKindTitle(language, capability.Kind)).FontSize(11).Weight(gfx.WeightMedium).Color(w.pal.muted) title := capability.Title if title == "" { title = capability.ID } - ui.Text(k, title).FontSize(13).Color(w.pal.text).Ellipsis() + ui.Text(c, title).FontSize(13).Color(w.pal.text).Ellipsis() if detail := capabilityDetail(language, capability); detail != "" { - ui.Wrap(k, detail).FontSize(11).Color(w.pal.muted) + ui.Wrap(c, detail).FontSize(11).Color(w.pal.muted) } ui.Row(k).FillWidth().Gap(8).Items(ui.Center).Children(func() { if entry, ok := missingFor(missing, capability); enabled && ok { w.commandMissingStatus(k, language, fact, entry) } else if enabled { - ui.Text(k, i18n.Shared(language, "native.available")).FontSize(11).Color(w.pal.success) + ui.Text(c, i18n.Shared(language, "native.available")).FontSize(11).Color(w.pal.success) } else { - ui.Text(k, i18n.Shared(language, "native.pluginDisabled")).FontSize(11).Color(w.pal.muted) + ui.Text(c, i18n.Shared(language, "native.pluginDisabled")).FontSize(11).Color(w.pal.muted) } - ui.Spacer(k) + ui.Spacer(c) if key := capabilityPage(capability); enabled && key != "" && w.dynamic.selected(key) != nil { if ui.Button(k, i18n.Shared(language, "native.configure")+" →").Link().XSmall().Clicked() { pluginID := fact.ID @@ -1087,13 +1087,13 @@ func (w *window) installedPermissions(c ui.C, language i18n.Language, fact Plugi k := c.KeyInt(index) ui.Row(k).FillWidth().PadY(3).Gap(8).Items(ui.Start).Children(func() { ui.Row(k).Height(installedPermissionLine).Shrink(0).Items(ui.Center).Children(func() { - ui.Icon(k, icons.ShieldCheck).Size(14, 14).Color(w.pal.accent) + ui.Icon(c, icons.ShieldCheck).Size(14, 14).Color(w.pal.accent) }) ui.Row(k).Grow(1).Shrink(1).MinWidth(0).Gap(8).Items(ui.Baseline).Children(func() { if description := permissionDescription(language, permission); description != "" { - ui.Wrap(k, description).FontSize(12).LineHeight(installedPermissionLine).Color(w.pal.text).Shrink(1).MinWidth(0) + ui.Wrap(c, description).FontSize(12).LineHeight(installedPermissionLine).Color(w.pal.text).Shrink(1).MinWidth(0) } - ui.Text(k, permission).Mono().FontSize(11).Color(w.pal.subtle).Shrink(0) + ui.Text(c, permission).Mono().FontSize(11).Color(w.pal.subtle).Shrink(0) }) }) } diff --git a/desktop/internal/settingswindow/plugin_settings_view.go b/desktop/internal/settingswindow/plugin_settings_view.go index 29282f2066..a74b20d0c0 100644 --- a/desktop/internal/settingswindow/plugin_settings_view.go +++ b/desktop/internal/settingswindow/plugin_settings_view.go @@ -214,8 +214,8 @@ func (w *window) readOnlyList(c ui.C, label, value string) { ui.Column(c).FillWidth().MinWidth(0).PadX(10).PadY(6).Gap(2).Border(1, w.pal.line).Radius(6). HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleTextField, Value: value, ReadOnly: true, Disabled: true}). Children(func() { - for index, line := range strings.Split(value, "\n") { - ui.Text(c.Key(strconv.Itoa(index)), line).FontSize(13).Color(w.pal.muted).FillWidth().Ellipsis() + for _, line := range strings.Split(value, "\n") { + ui.Text(c, line).FontSize(13).Color(w.pal.muted).FillWidth().Ellipsis() } }) } diff --git a/desktop/internal/settingswindow/remote_workspace_view.go b/desktop/internal/settingswindow/remote_workspace_view.go index 55ff959a55..b8229623c3 100644 --- a/desktop/internal/settingswindow/remote_workspace_view.go +++ b/desktop/internal/settingswindow/remote_workspace_view.go @@ -114,9 +114,9 @@ func (w *window) remoteProgramRow(c ui.C, language i18n.Language, r *remotePrefe } switch ssh.Status { case core.RemoteProgramMissing: - ui.Wrap(c.Part("program-missing"), i18n.SharedFormat(language, "desktop.remoteSettings.programMissing", map[string]string{"path": *ssh.Path})).FontSize(12).Color(w.pal.danger) + ui.Wrap(c, i18n.SharedFormat(language, "desktop.remoteSettings.programMissing", map[string]string{"path": *ssh.Path})).FontSize(12).Color(w.pal.danger) case core.RemoteProgramNotExecutable: - ui.Wrap(c.Part("program-not-executable"), i18n.SharedFormat(language, "desktop.remoteSettings.programNotExecutable", map[string]string{"path": *ssh.Path})).FontSize(12).Color(w.pal.danger) + ui.Wrap(c, i18n.SharedFormat(language, "desktop.remoteSettings.programNotExecutable", map[string]string{"path": *ssh.Path})).FontSize(12).Color(w.pal.danger) } } @@ -268,7 +268,7 @@ func (w *window) remoteIdleTimeoutRow(c ui.C, language i18n.Language, r *remoteP return } w.settingsRow(c, i18n.Shared(language, "desktop.remoteSettings.idleTimeout"), i18n.Shared(language, "desktop.remoteSettings.idleTimeoutHelp"), func() { - ui.Text(c.Part("value"), remoteDuration(language, int(seconds))).FontSize(12).Color(w.pal.text) + ui.Text(c, remoteDuration(language, int(seconds))).FontSize(12).Color(w.pal.text) }) } @@ -287,7 +287,7 @@ func (w *window) remotePathText(c ui.C, path, note string) { HitWith(ui.ID(c), path, gfx.HitOptions{Role: gfx.RoleGroup}).Tooltip(path).Children(func() { ui.Text(c, path).FontSize(12).Mono().Color(w.pal.text).Shrink(1).MinWidth(0).Ellipsis() if note != "" { - ui.Text(c.Part("note"), note).FontSize(12).Color(w.pal.muted).Shrink(0) + ui.Text(c, note).FontSize(12).Color(w.pal.muted).Shrink(0) } }) } diff --git a/desktop/internal/settingswindow/source_settings_entries_view.go b/desktop/internal/settingswindow/source_settings_entries_view.go index ab480fbae9..bcd2d30b82 100644 --- a/desktop/internal/settingswindow/source_settings_entries_view.go +++ b/desktop/internal/settingswindow/source_settings_entries_view.go @@ -82,7 +82,7 @@ func (w *window) sourceEntryToolbar(c ui.C, p *sourceSettingsForm, source core.S ui.Spacer(c) if len(entries) > 0 { for _, attribute := range field.Attributes { - ui.Text(c.Key(attribute.ID), attribute.Title).FontSize(11).Color(w.pal.muted).Width(entryAttributeWidth(attribute)).Shrink(0).Ellipsis() + ui.Text(c, attribute.Title).FontSize(11).Color(w.pal.muted).Width(entryAttributeWidth(attribute)).Shrink(0).Ellipsis() } } }) @@ -123,19 +123,18 @@ func (w *window) sourceEntryRow(c ui.C, p *sourceSettingsForm, source core.Setti ui.Text(c, label).FontSize(12).Color(w.pal.text).Shrink(0).MaxWidthPercent(60).Ellipsis() ui.Text(c, entry.Detail).FontSize(11).Color(w.pal.muted).Grow(1).Shrink(1).MinWidth(0).Ellipsis() for column, attribute := range field.Attributes { - k := c.Key(attribute.ID) title := attribute.Title + " " + label if attribute.Kind == "boolean" { on := entryBool(entry, attribute.ID) - ui.Row(k).Width(entryFlagWidth).Shrink(0).Items(ui.Center).Children(func() { - box := ui.Row(k).Size(16, 16).Radius(4).Border(1, w.pal.border).Center(). - HitWith(ui.ID(k), title, gfx.HitOptions{Role: gfx.RoleCheckbox, Checked: on, Disabled: disabled}) + ui.Row(c.Key(attribute.ID)).Width(entryFlagWidth).Shrink(0).Items(ui.Center).Children(func() { + box := ui.Row(c).Size(16, 16).Radius(4).Border(1, w.pal.border).Center(). + HitWith(ui.ID(c), title, gfx.HitOptions{Role: gfx.RoleCheckbox, Checked: on, Disabled: disabled}) if on { box = box.Background(w.pal.accent) } box.Children(func() { if on { - ui.Icon(k, icons.Check).Size(12, 12).Color(w.pal.white) + ui.Icon(c, icons.Check).Size(12, 12).Color(w.pal.white) } }) if !disabled && box.Clicked() { @@ -156,10 +155,10 @@ func (w *window) sourceEntryRow(c ui.C, p *sourceSettingsForm, source core.Setti } optionTitle := func(option int) string { return attribute.Options[option].Title } if disabled { - ui.Text(k, optionTitle(*choice)).FontSize(12).Color(w.pal.muted).Width(entryChoiceWidth).Shrink(0).Ellipsis() + ui.Text(c, optionTitle(*choice)).FontSize(12).Color(w.pal.muted).Width(entryChoiceWidth).Shrink(0).Ellipsis() continue } - if ui.Select(k, choice, indices, optionTitle).Width(entryChoiceWidth).Shrink(0).Label(title).Changed() { + if ui.Select(c.Key(attribute.ID), choice, indices, optionTitle).Width(entryChoiceWidth).Shrink(0).Label(title).Changed() { value := attribute.Options[*choice].Value p.editEntries(source.ID, field, func(control *sourceSettingControl) { setEntryAttribute(&control.input.Entries[index], attribute.ID, value) diff --git a/desktop/internal/settingswindow/stepping_view.go b/desktop/internal/settingswindow/stepping_view.go index 3e903afc4a..86ca62152f 100644 --- a/desktop/internal/settingswindow/stepping_view.go +++ b/desktop/internal/settingswindow/stepping_view.go @@ -408,14 +408,14 @@ func (w *window) debuggerList(c ui.C, language i18n.Language) { w.pluginTile(k, steppingPluginName(adapter), 20) ui.Column(k).Grow(1).Shrink(1).MinWidth(0).Children(func() { ui.Row(k).FillWidth().Gap(6).Items(ui.Center).Children(func() { - ui.Text(k, adapter.Name).FontSize(buildFont).Weight(gfx.WeightSemibold).Color(b.text).Shrink(1).Ellipsis() - ui.Spacer(k) + ui.Text(c, adapter.Name).FontSize(buildFont).Weight(gfx.WeightSemibold).Color(b.text).Shrink(1).Ellipsis() + ui.Spacer(c) if stored || changed { w.tag(k, tagBlue, i18n.Shared(language, "desktop.settings.stepping.customized")) } }) ui.Row(k).FillWidth().Height(2).Shrink(0) - ui.Text(k, steppingPluginName(adapter)).FontSize(11).Color(b.faint).Ellipsis() + ui.Text(c, steppingPluginName(adapter)).FontSize(11).Color(b.faint).Ellipsis() }) }) }).Scrollbars().FillWidth().Grow(1).Shrink(1).MinHeight(0).Label(i18n.Shared(language, "desktop.buildSettings.debuggers")) @@ -489,7 +489,7 @@ func (w *window) debuggerDetail(c ui.C, language i18n.Language, adapter Stepping k := c.Part(feature.key) ui.Row(k).FillWidth().MinHeight(34).PadX(8).PadY(3).Gap(10).Radius(7).Items(ui.Center).Children(func() { ui.Row(k).Grow(1).Shrink(1).MinWidth(0).Gap(5).Items(ui.Center).Children(func() { - ui.Text(k, feature.label).FontSize(buildFont).Color(b.text).Shrink(1).Ellipsis() + ui.Text(c, feature.label).FontSize(buildFont).Color(b.text).Shrink(1).Ellipsis() w.infoButton(k.Part("help"), feature.help) }) ui.Switch(k.Part("switch"), feature.value, "").Label(feature.label).Disabled(s.saving) @@ -515,7 +515,7 @@ func (w *window) patternList(c ui.C, language i18n.Language, draft *steppingDraf for index, pattern := range draft.patterns { k := c.KeyInt(index) ui.Row(k).FillWidth().MinWidth(0).PadX(8).PadY(5).Gap(8).Items(ui.Center).Children(func() { - ui.Text(k, pattern).FontSize(buildMono).Mono().Color(b.text).Grow(1).Shrink(1).MinWidth(0).Ellipsis() + ui.Text(c, pattern).FontSize(buildMono).Mono().Color(b.text).Grow(1).Shrink(1).MinWidth(0).Ellipsis() if w.iconButton(k.Part("remove"), icons.X, i18n.Shared(language, "desktop.buildSettings.removePattern"), s.saving) { remove = index } diff --git a/desktop/internal/settingswindow/trusted_locations_view.go b/desktop/internal/settingswindow/trusted_locations_view.go index 70be4c3ada..b69185b068 100644 --- a/desktop/internal/settingswindow/trusted_locations_view.go +++ b/desktop/internal/settingswindow/trusted_locations_view.go @@ -75,7 +75,7 @@ func (w *window) remoteTrustList(c ui.C, language i18n.Language, r *remoteTrustS ui.Icon(g, icons.Server).Size(14, 14).Color(p.muted).Shrink(0) ui.Text(g, name).FontSize(12).Weight(gfx.WeightSemibold).Color(p.text).Shrink(1).MinWidth(0).Ellipsis() if place != "" { - ui.Text(g.Part("place"), place).FontSize(12).Mono().Color(p.muted).Grow(1).Shrink(1).MinWidth(0).Ellipsis() + ui.Text(g, place).FontSize(12).Mono().Color(p.muted).Grow(1).Shrink(1).MinWidth(0).Ellipsis() } }) for _, entry := range group.entries { @@ -173,7 +173,7 @@ func (w *window) trustedLocationsList(c ui.C, language i18n.Language, l *trusted if row.mark == locationRemoved { words = p.subtle } - ui.Icon(k, icons.Folder).Size(14, 14).Color(p.muted).Shrink(0) + ui.Icon(c, icons.Folder).Size(14, 14).Color(p.muted).Shrink(0) // The tooltip shows a path the row's width cuts; it needs an element with an identity. path := k.Part("path") ui.Row(path).Grow(1).Shrink(1).MinWidth(0).Items(ui.Center). diff --git a/desktop/internal/settingswindow/version_control_view.go b/desktop/internal/settingswindow/version_control_view.go index 3479266c2c..f18f119ad6 100644 --- a/desktop/internal/settingswindow/version_control_view.go +++ b/desktop/internal/settingswindow/version_control_view.go @@ -22,7 +22,7 @@ func (w *window) versionControlPage(c ui.C) { ui.Row(c).Height(4).Shrink(0) ui.Wrap(c, i18n.Shared(language, "desktop.versionControlSettings.intro")).FontSize(buildSmall).Color(b.sub) ui.Row(c).Height(12).Shrink(0) - w.directory(c.Part("directory"), []directoryEntry{{ + w.directory(c, []directoryEntry{{ key: "git", tile: gitTile, icon: icons.GitBranch, title: titleOf(&w.text.Settings, pageGit), desc: i18n.Shared(language, "desktop.versionControlSettings.directoryGit"), open: func() { w.selectSettingsPage(pageGit, "") }, diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index 10417cea13..74c5db56f3 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -429,27 +429,27 @@ func (w *window) breadcrumb(c ui.C) { w.crumbs = w.appendCrumbs(w.crumbs[:0]) var chosen *crumb ui.Row(c).FillWidth().Height(crumbHeight).Shrink(0).PadX(18).Gap(8).Items(ui.Center).Background(b.surface).Children(func() { + // Keys belong on interactive containers, not leaf Text elements. for i := range w.crumbs { crumb := &w.crumbs[i] - k := c.KeyInt(i) if i > 0 { - ui.Text(k.Part("sep"), "›").FontSize(buildFont).Color(b.faint).Shrink(0) + ui.Text(c, "›").FontSize(buildFont).Color(b.faint).Shrink(0) } last := i == len(w.crumbs)-1 switch { case last: - ui.Text(k, crumb.title).FontSize(buildFont).Weight(gfx.WeightSemibold).Color(b.text).Shrink(1).MinWidth(0).Ellipsis() + ui.Text(c, crumb.title).FontSize(buildFont).Weight(gfx.WeightSemibold).Color(b.text).Shrink(1).MinWidth(0).Ellipsis() case crumb.link: - button := ui.ButtonBase(k, crumb.title).Shrink(1).MinWidth(0).Items(ui.Center) + button := ui.ButtonBase(c.KeyInt(i), crumb.title).Shrink(1).MinWidth(0).Items(ui.Center) if button.Clicked() { chosen = crumb } button.Children(func() { - ui.Text(k, crumb.title).FontSize(buildFont).Color(b.sub).Shrink(1).MinWidth(0).Ellipsis(). + ui.Text(c, crumb.title).FontSize(buildFont).Color(b.sub).Shrink(1).MinWidth(0).Ellipsis(). StateFrom(button).Hover(ui.Look{}.Color(b.accent)) }) default: - ui.Text(k, crumb.title).FontSize(buildFont).Color(b.sub).Shrink(1).MinWidth(0).Ellipsis() + ui.Text(c, crumb.title).FontSize(buildFont).Color(b.sub).Shrink(1).MinWidth(0).Ellipsis() } } }) diff --git a/desktop/internal/workbench/aicommit_view.go b/desktop/internal/workbench/aicommit_view.go index c28ff73a2a..9dae83c950 100644 --- a/desktop/internal/workbench/aicommit_view.go +++ b/desktop/internal/workbench/aicommit_view.go @@ -10,7 +10,7 @@ func (a *App) drawGenerateCommitButton(c ui.C, p *project) { // The spinner shows the generation is still working, as the macOS client's progress // indicator does in place of its icon; Cancel stops it. ui.Row(c.Part("aiRunning")).Items(ui.Center).Gap(4).Children(func() { - ui.Spinner(c.Part("spinner")) + ui.Spinner(c) if ui.Button(c.Part("ai"), t.Cancel).Ghost().Clicked() { c.After(func() { a.cancelCommitGeneration(p) }) } diff --git a/desktop/internal/workbench/branch_view.go b/desktop/internal/workbench/branch_view.go index cc7093bf2c..dde8204fb5 100644 --- a/desktop/internal/workbench/branch_view.go +++ b/desktop/internal/workbench/branch_view.go @@ -668,7 +668,7 @@ func (a *App) drawBranchConflictDialog(c ui.C, p *project) { ui.Scroll(c).Scrollbars().FillWidth().MaxHeight(branchBlockingHeight).Children(func() { ui.Column(c).FillWidth().Gap(2).Children(func() { for _, path := range b.blocking { - ui.Text(c.Key(path), path).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Text).Ellipsis() + ui.Text(c, path).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Text).Ellipsis() } }) }) diff --git a/desktop/internal/workbench/build_options.go b/desktop/internal/workbench/build_options.go index a741d4c4e3..a4dc0426e2 100644 --- a/desktop/internal/workbench/build_options.go +++ b/desktop/internal/workbench/build_options.go @@ -421,20 +421,20 @@ func (a *App) buildOptionsDialog(c ui.C, p *project) { } closed := ui.ModalWith(c, &open, title, ui.ModalSpec{Width: 460}, func() { ui.Column(c.Part("build-options")).FillWidth().Gap(10).Children(func() { - a.buildIgnoredPathsSection(c.Part("detection"), p, ready) + a.buildIgnoredPathsSection(c, p, ready) if e.instance != "" { k := c.Part("instance") ui.Row(k).FillWidth().Items(ui.Center).Gap(6).MarginTop(6).Children(func() { a.buildOptionsHeading(k, e.name) if e.root != "" { - ui.Text(k, e.root).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) + ui.Text(c, e.root).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) } }) if len(e.fields) == 0 && !e.loading { - ui.Wrap(k, i18n.Shared(language, "desktop.build.noOptions")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Wrap(c, i18n.Shared(language, "desktop.build.noOptions")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) } for index := range e.fields { - a.drawRunOptionField(k.KeyInt(index), language, &e.fields[index], ready) + a.drawRunOptionField(c, index, language, &e.fields[index], ready) } a.buildRuntimeSection(c, language, e) a.buildDroppedOptionsSection(c, language, p, ready) @@ -478,7 +478,7 @@ func (a *App) buildIgnoredPathsSection(c ui.C, p *project, ready bool) { g, language := &p.build.options.ignored, a.language() label := i18n.Shared(language, "desktop.build.ignoredPaths") a.buildOptionsHeading(c, i18n.Shared(language, "desktop.build.detection")) - ui.Row(c).FillWidth().Items(ui.Center).Gap(4).Children(func() { + ui.Row(c.Part("detection")).FillWidth().Items(ui.Center).Gap(4).Children(func() { ui.Text(c, label).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Text).Shrink(0) ui.Button(c.Part("help"), i18n.Shared(language, "native.moreInformation")).Icon(icons.Info).IconOnly().Ghost().Size(18, 18). Tooltip(i18n.Shared(language, "desktop.build.ignoredPathsHelp")).TooltipOn(ui.TooltipRight) diff --git a/desktop/internal/workbench/build_options_runtime.go b/desktop/internal/workbench/build_options_runtime.go index aa02228bea..3a455d6b2f 100644 --- a/desktop/internal/workbench/build_options_runtime.go +++ b/desktop/internal/workbench/build_options_runtime.go @@ -257,14 +257,14 @@ func (a *App) buildRuntimeRows(c ui.C, language i18n.Language, e *buildOptionsEd for index, runtime := range e.runtimes { k := c.KeyInt(index) ui.Row(k).FillWidth().Items(ui.Center).Gap(8).Children(func() { - ui.Text(k, runtime.name).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Text).Ellipsis().Shrink(0).MaxWidth(120) + ui.Text(c, runtime.name).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Text).Ellipsis().Shrink(0).MaxWidth(120) if runtime.failure != "" { - ui.Text(k, runtime.failure).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger).Ellipsis().Shrink(1).MinWidth(0) + ui.Text(c, runtime.failure).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger).Ellipsis().Shrink(1).MinWidth(0) return } - ui.Text(k, runtime.executable).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Text).Ellipsis().Shrink(1).MinWidth(0) - ui.Spacer(k) - ui.Text(k, buildExecutionSourceLabel(language, runtime.source)).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(0).MaxWidth(160) + ui.Text(c, runtime.executable).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Text).Ellipsis().Shrink(1).MinWidth(0) + ui.Spacer(c) + ui.Text(c, buildExecutionSourceLabel(language, runtime.source)).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(0).MaxWidth(160) }) } ui.Wrap(c, i18n.Shared(language, "desktop.build.runtimeHelp")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) @@ -323,9 +323,9 @@ func (a *App) buildDroppedOptionRows(c ui.C, language i18n.Language, p *project, value = option.team } ui.Column(k).FillWidth().Gap(2).Children(func() { - ui.Text(k, option.id+" = "+value).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Text).Ellipsis() + ui.Text(c, option.id+" = "+value).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Text).Ellipsis() if option.hasTeam { - ui.Text(k, i18n.SharedFormat(language, "desktop.build.droppedInTeam", map[string]string{"file": buildTeamOptionsFile})). + ui.Text(c, i18n.SharedFormat(language, "desktop.build.droppedInTeam", map[string]string{"file": buildTeamOptionsFile})). FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() } }) diff --git a/desktop/internal/workbench/build_tree_view.go b/desktop/internal/workbench/build_tree_view.go index a03eb35032..dccf47b0a1 100644 --- a/desktop/internal/workbench/build_tree_view.go +++ b/desktop/internal/workbench/build_tree_view.go @@ -101,7 +101,7 @@ func (a *App) buildSystemsPane(c ui.C, p *project) { switch { case b.loading || !b.loaded: a.buildNotice(c, t.LoadingModel, "", func() { - ui.Spinner(c.Part("spinner")).Size(16, 16) + ui.Spinner(c).Size(16, 16) }) return case b.failed != "": @@ -237,7 +237,7 @@ func (a *App) buildArrow(c ui.C, title string, branch, open bool) bool { slot := ui.Row(k).Size(treelist.Disclosure, treelist.Icon).Shrink(0).Center(). HitWith(ui.ID(k), name+" "+title, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Expandable: true, Expanded: open, SkipFocus: true}) slot.Children(func() { - ui.Icon(k, fileicons.TreeChevron(open, a.colors.Dark)).Size(16, 16) + ui.Icon(c, fileicons.TreeChevron(open, a.colors.Dark)).Size(16, 16) }) return slot.Clicked() } @@ -296,7 +296,7 @@ func (a *App) buildGroupRow(row ui.ListRow, p *project, instance *buildInstance, } switch { case spec.loading: - ui.Spinner(c.Part("spinner")).Size(12, 12) + ui.Spinner(c).Size(12, 12) case spec.warning: ui.Icon(c, icons.CircleAlert).Size(14, 14).Shrink(0).Color(a.colors.Warning) } @@ -423,7 +423,7 @@ func (a *App) buildNoteRow(row ui.ListRow, p *project, instance *buildInstance, color := a.colors.Subtle switch { case spec.loading: - ui.Spinner(c.Part("spinner")).Size(12, 12) + ui.Spinner(c).Size(12, 12) case spec.warning: color = a.colors.Warning ui.Icon(c, icons.CircleAlert).Size(14, 14).Shrink(0).Color(color) @@ -482,13 +482,13 @@ func (a *App) buildRunMark(c ui.C, label string, disabled bool) bool { slot := ui.Row(k).Size(treelist.Icon, treelist.Icon).Shrink(0).Center() if disabled { slot.Children(func() { - ui.Icon(k, icons.Play).Size(14, 14).Color(a.colors.Subtle).Opacity(0.5) + ui.Icon(c, icons.Play).Size(14, 14).Color(a.colors.Subtle).Opacity(0.5) }) return false } slot = slot.HitWith(ui.ID(k), label, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, SkipFocus: true}).Tooltip(label) slot.Children(func() { - ui.Icon(k, icons.Play).Size(14, 14).Color(a.colors.Success) + ui.Icon(c, icons.Play).Size(14, 14).Color(a.colors.Success) }) return slot.Clicked() } diff --git a/desktop/internal/workbench/chrome_view.go b/desktop/internal/workbench/chrome_view.go index 46de23070b..dbeb57308f 100644 --- a/desktop/internal/workbench/chrome_view.go +++ b/desktop/internal/workbench/chrome_view.go @@ -117,7 +117,7 @@ func (a *App) chromeGlyph(c ui.C, i int, layout glyphLayout, rest, hover gfx.Col box := a.chromeBox(ui.Row(k).Size(layout.side, layout.side).Shrink(0).Center(), ui.ID(k), i, open, "", true). TooltipOn(layout.tooltip) box.Children(func() { - ui.Icon(k, *a.chrome.catalog[i].icon).Size(layout.icon, layout.icon).Color(rest). + ui.Icon(c, *a.chrome.catalog[i].icon).Size(layout.icon, layout.icon).Color(rest). StateFrom(box).Hover(ui.Look{}.Color(hover)) }) return box, box.Clicked() @@ -192,8 +192,8 @@ func (a *App) chromeProject(c ui.C) { } button.Children(func() { projectAvatar(k, row.identity, chromeAvatarTitle) - ui.Text(k, a.project.name).Bold().Color(a.colors.Text).LineHeight(chromeLineHeight).Ellipsis().MaxWidth(chromeProjectMax) - ui.Icon(k, icons.ChevronDown).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle) + ui.Text(c, a.project.name).Bold().Color(a.colors.Text).LineHeight(chromeLineHeight).Ellipsis().MaxWidth(chromeProjectMax) + ui.Icon(c, icons.ChevronDown).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle) }) clicked := button.Clicked() if a.title.projectOpen { @@ -214,9 +214,9 @@ func (a *App) chromeTitleButton(c ui.C, i int) bool { wasOpen := a.title.runConfigOpen box := a.chromeBox(ui.Row(k).Height(chromeIconButton).Shrink(0).Items(ui.Center).Gap(chromeGap).PadX(chromeEdge), ui.ID(k), i, wasOpen, "", false) box.Children(func() { - ui.Icon(k, *a.chrome.catalog[i].icon).Size(chromeIconSize, chromeIconSize).Color(a.colors.Subtle) - ui.Text(k, a.titleRunLabel()).Color(a.colors.Text).LineHeight(chromeLineHeight).Ellipsis().MaxWidth(chromeProjectMax) - ui.Icon(k, icons.ChevronDown).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle) + ui.Icon(c, *a.chrome.catalog[i].icon).Size(chromeIconSize, chromeIconSize).Color(a.colors.Subtle) + ui.Text(c, a.titleRunLabel()).Color(a.colors.Text).LineHeight(chromeLineHeight).Ellipsis().MaxWidth(chromeProjectMax) + ui.Icon(c, icons.ChevronDown).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle) }) clicked := box.Clicked() if wasOpen { @@ -268,7 +268,7 @@ func (a *App) titleButtonMenu(c ui.C, i int, box ui.Box) { if !a.chrome.catalog[i].stripes { return } - ui.ContextMenu(c.Part("menu").KeyInt(i), box, func(menu *ui.MenuItems) { + ui.ContextMenu(c, box, func(menu *ui.MenuItems) { a.stripeMoveMenu(c, menu, i, zoneTitle) }) } @@ -339,7 +339,7 @@ func (a *App) stripeZone(c ui.C, z zone, left, dragging bool) int { for _, i := range a.chrome.items[z] { if a.chrome.catalog[i].id == itemToolWindows { box := a.hiddenToolWindowsButton(c, i, z, layout) - ui.ContextMenu(c.Part("menu").KeyInt(i), box, a.stripeButtonMenu(c, i, z)) + ui.ContextMenu(c, box, a.stripeButtonMenu(c, i, z)) continue } // The background button opens a popover, not a tool window, and the settings @@ -384,7 +384,7 @@ func (a *App) stripeZone(c ui.C, z zone, left, dragging bool) int { case hit: clicked = i } - ui.ContextMenu(c.Part("menu").KeyInt(i), box, a.stripeButtonMenu(c, i, z)) + ui.ContextMenu(c, box, a.stripeButtonMenu(c, i, z)) } }) a.chrome.placeZone(z, column) @@ -412,7 +412,7 @@ func (a *App) hiddenToolWindowsButton(c ui.C, i int, z zone, layout glyphLayout) button = button.Background(a.colors.Active).Hover(ui.Look{}.Background(a.colors.Active)) } button.Children(func() { - ui.Icon(k, *a.chrome.catalog[i].icon).Size(layout.icon, layout.icon).Color(rest). + ui.Icon(c, *a.chrome.catalog[i].icon).Size(layout.icon, layout.icon).Color(rest). StateFrom(button).Hover(ui.Look{}.Color(hover)) }) clicked := button.Clicked() @@ -452,7 +452,7 @@ func (a *App) hiddenToolWindowList(c ui.C, anchor ui.Box, z zone) { if clicked { shown = i } - ui.ContextMenu(c.Part("unhide").KeyInt(i), row, func(menu *ui.MenuItems) { + ui.ContextMenu(c, row, func(menu *ui.MenuItems) { if menu.Item(unhide).Clicked() { restored = i } @@ -547,9 +547,9 @@ func (a *App) chromeStatusItem(c ui.C, i int) bool { if doc := a.selectedEditorDocument(); doc != nil && doc.view.ReadOnly() { icon = icons.Lock } - ui.Icon(k, icon).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle) + ui.Icon(c, icon).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle) case itemHealth: - ui.Icon(k, *a.chrome.catalog[i].icon).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Success) + ui.Icon(c, *a.chrome.catalog[i].icon).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Success) case itemMemory: a.memoryStatusItem(k) case itemLSP: @@ -603,9 +603,9 @@ func (a *App) chromeBranch(c ui.C) { button = button.Hover(ui.Look{}.Background(a.colors.Hover)) } button.Children(func() { - ui.Icon(k, icons.GitBranch).Size(chromeIconSize, chromeIconSize).Color(a.colors.Subtle) - ui.Text(k, name).Color(a.colors.Subtle).LineHeight(chromeLineHeight).Ellipsis().MaxWidth(chromeBranchMax) - ui.Icon(k, icons.ChevronDown).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle) + ui.Icon(c, icons.GitBranch).Size(chromeIconSize, chromeIconSize).Color(a.colors.Subtle) + ui.Text(c, name).Color(a.colors.Subtle).LineHeight(chromeLineHeight).Ellipsis().MaxWidth(chromeBranchMax) + ui.Icon(c, icons.ChevronDown).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle) }) clicked := button.Clicked() if open { @@ -776,7 +776,7 @@ func (a *App) menuProjectDismiss(c ui.C, label string) bool { Radius(a.theme.Metrics.RadiusItem()). HitWith(ui.ID(k), label, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand})).Tooltip(label) button.Children(func() { - ui.Icon(k, icons.X).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle). + ui.Icon(c, icons.X).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle). StateFrom(button).Hover(ui.Look{}.Color(a.colors.Text)) }) return button.Clicked() diff --git a/desktop/internal/workbench/commit_view.go b/desktop/internal/workbench/commit_view.go index cfc5b889e2..f10d183f2e 100644 --- a/desktop/internal/workbench/commit_view.go +++ b/desktop/internal/workbench/commit_view.go @@ -489,7 +489,7 @@ func (a *App) drawCommitResults(c ui.C, p *project, target commitTarget) { ui.Text(c, t.Result(target.repositoryName(id), a.commitStatusLabel(result.Status))).Color(tint).Ellipsis().Grow(1) }) if result.Detail != "" { - ui.Paragraph(c.Key(id+"/detail"), result.Detail, 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Paragraph(c, result.Detail, 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) } } ui.Row(c).FillWidth().Items(ui.Center).Gap(6).Children(func() { diff --git a/desktop/internal/workbench/debug_view.go b/desktop/internal/workbench/debug_view.go index 6e21af9558..2d6cf8e9e0 100644 --- a/desktop/internal/workbench/debug_view.go +++ b/desktop/internal/workbench/debug_view.go @@ -137,7 +137,7 @@ func (a *App) debugToolbar(c ui.C, p *project) { } ui.Text(c, status).Shrink(1).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() } - a.debugAdapterPicker(c.Part("adapter"), p) + a.debugAdapterPicker(c, p) }) } @@ -216,7 +216,7 @@ func (a *App) debugAdapterPicker(c ui.C, p *project) { for index := range indexes { indexes[index] = index } - ui.Select(c, &d.selectedAdapter, indexes, func(index int) string { + ui.Select(c.Part("adapter"), &d.selectedAdapter, indexes, func(index int) string { return d.adapters[index].Declaration.DisplayName }).Label(i18n.Shared(a.language(), "desktop.debug.adapter")).Width(debugAdapterPickerWidth).Height(24).Shrink(1) } diff --git a/desktop/internal/workbench/debug_watch.go b/desktop/internal/workbench/debug_watch.go index cd2f2c3091..4a77e5c2dc 100644 --- a/desktop/internal/workbench/debug_watch.go +++ b/desktop/internal/workbench/debug_watch.go @@ -340,9 +340,9 @@ func (a *App) debugWatchView(c ui.C, p *project) { Hover(ui.Look{}.Background(a.colors.Hover)). HitWith(ui.ID(k), entry.expression, gfx.HitOptions{SkipFocus: true}) row.Children(func() { - ui.Icon(k, icons.Eye).Size(treelist.Icon, treelist.Icon).Shrink(0).MarginTop(debugIconInset).Color(a.colors.Subtle) + ui.Icon(c, icons.Eye).Size(treelist.Icon, treelist.Icon).Shrink(0).MarginTop(debugIconInset).Color(a.colors.Subtle) a.debugWatchText(k, entry, false) - ui.Spacer(k) + ui.Spacer(c) i := index if _, clicked := a.toolIconButton(k.Key("remove"), t.RemoveWatch, icons.X, false, false); clicked { c.After(func() { a.removeDebugWatch(p, i) }) diff --git a/desktop/internal/workbench/difftab_view.go b/desktop/internal/workbench/difftab_view.go index e4892204c4..8b60c95b46 100644 --- a/desktop/internal/workbench/difftab_view.go +++ b/desktop/internal/workbench/difftab_view.go @@ -130,6 +130,9 @@ func (a *App) diffToolbar(c ui.C, p *project, t *diffTab) { if clicked { t.settingsOpen = !t.settingsOpen } + if !t.settingsOpen { + return + } ui.Menu(c.Part("diff-settings-menu"), gear, &t.settingsOpen, func(menu *ui.MenuItems) { menu.WidthRange(180, 260) if menu.Item(i18n.Shared(lang, "desktop.diff.keepWhitespace")).Checked(!t.ignoreSpace).Disabled(t.saved != nil).Clicked() { diff --git a/desktop/internal/workbench/editor_view.go b/desktop/internal/workbench/editor_view.go index 4f104ee725..85a45759ba 100644 --- a/desktop/internal/workbench/editor_view.go +++ b/desktop/internal/workbench/editor_view.go @@ -165,7 +165,7 @@ func (a *App) softWrapSwitch(c ui.C) { button = button.Hover(ui.Look{}.Background(a.colors.Hover)) } button.Children(func() { - ui.Icon(k, icons.WrapText).Size(shellIconSize, shellIconSize).Color(icon). + ui.Icon(c, icons.WrapText).Size(shellIconSize, shellIconSize).Color(icon). StateFrom(button).Hover(ui.Look{}.Color(a.colors.Text)) }) if button.Clicked() { @@ -191,13 +191,15 @@ func (a *App) documentView(c ui.C, group string, d *document) { } if p := a.project; p != nil && !d.virtual { items, shown := a.editorMenuItems(c, p, d), false - ui.ContextMenu(c.Key("menu"+name), box, func(menu *ui.MenuItems) { + ui.ContextMenu(c, box, func(menu *ui.MenuItems) { shown = true items(menu) }) a.referenceMenuPainted(d, shown) - at := d.actionPanel.menuAt - ui.ContextMenuAt(c.Key("lanemenu"+name), box, &d.actionPanel.menuOpen, gfx.Point{X: at.X, Y: at.Y + at.Height}, a.editorActionLaneMenu(c, p, d)) + if d.actionPanel.menuOpen { + at := d.actionPanel.menuAt + ui.ContextMenuAt(c.Key("lanemenu"+name), box, &d.actionPanel.menuOpen, gfx.Point{X: at.X, Y: at.Y + at.Height}, a.editorActionLaneMenu(c, p, d)) + } a.gitGutterPeek(c, p, d, box) } } @@ -335,7 +337,7 @@ func (a *App) terminalView(c ui.C, t *terminal) { box := ui.Control(c.Part(name), a.text.Terminal.Label, &t.input).Fill().Draw(t.draw) box.DropTarget(&a.dnd.tree, a.terminalTreeAccept, a.terminalTreeDrop) ui.FocusBind(box, &a.focus, focusTarget{term: t.id}) - a.terminalMenu(c, name, box, t) + a.terminalMenu(c, box, t) }) return } @@ -343,7 +345,7 @@ func (a *App) terminalView(c ui.C, t *terminal) { // A project tree row dropped on the terminal pastes its path (terminal_drop.go). box.DropTarget(&a.dnd.tree, a.terminalTreeAccept, a.terminalTreeDrop) ui.FocusBind(box, &a.focus, focusTarget{term: t.id}) - a.terminalMenu(c, name, box, t) + a.terminalMenu(c, box, t) } // terminalInput makes the handlers and the painter of terminal t, once, when it is opened. diff --git a/desktop/internal/workbench/git_gutter.go b/desktop/internal/workbench/git_gutter.go index fc2b756c46..c90c6d0e7e 100644 --- a/desktop/internal/workbench/git_gutter.go +++ b/desktop/internal/workbench/git_gutter.go @@ -294,7 +294,7 @@ func (a *App) gitGutterPeek(c ui.C, p *project, d *document, anchor ui.Box) { if i == maxLines { break } - ui.Text(c.KeyInt(i), line).Mono().FontSize(12).Color(a.colors.Text).Ellipsis() + ui.Text(c, line).Mono().FontSize(12).Color(a.colors.Text).Ellipsis() } ui.Row(c).Gap(6).Children(func() { if ui.Button(c.Key("previous"), i18n.Shared(a.language(), "desktop.git.gutter.previous")).Ghost().Clicked() { diff --git a/desktop/internal/workbench/gitlog_popover_view.go b/desktop/internal/workbench/gitlog_popover_view.go index b62a19422a..abcfef3201 100644 --- a/desktop/internal/workbench/gitlog_popover_view.go +++ b/desktop/internal/workbench/gitlog_popover_view.go @@ -135,7 +135,7 @@ func (a *App) drawLogBranchFilter(c ui.C, p *project) { if len(s.refs) == 0 { continue } - ui.Divider(c.Part(s.kind)).PadY(4) + ui.Divider(c).PadY(4) for _, r := range s.refs { if a.logMenuItem(c, r.FullName, r.ShortName, l.reference == r.FullName, false) { c.After(func() { diff --git a/desktop/internal/workbench/gitpush_workspace_view.go b/desktop/internal/workbench/gitpush_workspace_view.go index 4afbff2fc1..7a2ebd7e89 100644 --- a/desktop/internal/workbench/gitpush_workspace_view.go +++ b/desktop/internal/workbench/gitpush_workspace_view.go @@ -134,7 +134,7 @@ func (a *App) drawWorkspacePushRepository(c ui.C, p *project, repo core.Workspac // Git's own reason is shown as it words it. text, color = i18n.SharedFormat(lang, "desktop.git.pushAll.failed", map[string]string{"reason": outcome.err}), a.theme.Danger } - ui.Paragraph(c.Part("outcome"), text, 3).FontSize(size).Color(color).PadLeft(indent) + ui.Paragraph(c, text, 3).FontSize(size).Color(color).PadLeft(indent) } if s.folded[repo.ID] { return @@ -143,7 +143,7 @@ func (a *App) drawWorkspacePushRepository(c ui.C, p *project, repo core.Workspac a.drawWorkspacePushCommit(c.Key(commit.Hash), p, repo.ID, commit, indent+float32(treelist.Indent)) } if repo.Preview != nil && repo.Preview.HasMore { - ui.Text(c.Part("more"), i18n.Shared(lang, "git.pushDialog.moreCommits")).FontSize(size).Muted().PadLeft(indent + float32(treelist.Indent)) + ui.Text(c, i18n.Shared(lang, "git.pushDialog.moreCommits")).FontSize(size).Muted().PadLeft(indent + float32(treelist.Indent)) } } @@ -163,7 +163,7 @@ func (a *App) drawWorkspacePushFold(c ui.C, s *workspacePushState, id, name stri slot := ui.Row(k).Size(treelist.Disclosure, treelist.Icon).Shrink(0).Center(). HitWith(ui.ID(k), label+" "+name, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Expandable: true, Expanded: open, SkipFocus: true}) slot.Children(func() { - ui.Icon(k, chevron).Size(12, 12).Color(a.colors.Subtle) + ui.Icon(c, chevron).Size(12, 12).Color(a.colors.Subtle) }) if slot.Clicked() { c.After(func() { s.folded[id] = open }) diff --git a/desktop/internal/workbench/gitreview_diff_view.go b/desktop/internal/workbench/gitreview_diff_view.go index 1cb72dcc51..c4570ebe85 100644 --- a/desktop/internal/workbench/gitreview_diff_view.go +++ b/desktop/internal/workbench/gitreview_diff_view.go @@ -178,7 +178,7 @@ func (a *App) drawRollbackDialog(c ui.C, p *project) { ui.Column(c).FillWidth().Gap(8).Children(func() { ui.Paragraph(c, i18n.Shared(a.language(), "git.rollback.warning"), 4).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) for _, change := range r.changes { - ui.Text(c.Key(change.Path), change.Path).Ellipsis() + ui.Text(c, change.Path).Ellipsis() } ui.Checkbox(c, &r.deleteAdded, i18n.Shared(a.language(), "git.rollback.deleteAdded")).Disabled(r.busy) }) diff --git a/desktop/internal/workbench/inlineedit_view.go b/desktop/internal/workbench/inlineedit_view.go index ea89893d05..858bd9856f 100644 --- a/desktop/internal/workbench/inlineedit_view.go +++ b/desktop/internal/workbench/inlineedit_view.go @@ -43,7 +43,7 @@ func (a *App) inlineEditView(c ui.C, p *project) { ui.Text(c, t.Unchanged).Color(a.colors.Subtle) } ui.Scroll(c).Scrollbars().FillWidth().MaxHeight(360).Children(func() { - for i, line := range s.diff { + for _, line := range s.diff { color, mark := a.colors.Text, " " switch line.kind { case diffRemoved: @@ -51,7 +51,7 @@ func (a *App) inlineEditView(c ui.C, p *project) { case diffAdded: color, mark = a.colors.Success, "+ " } - ui.Text(c.KeyInt(i), mark+line.text).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(color) + ui.Text(c, mark+line.text).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(color) } }) } diff --git a/desktop/internal/workbench/local_history_view.go b/desktop/internal/workbench/local_history_view.go index b09927625c..46b90fd011 100644 --- a/desktop/internal/workbench/local_history_view.go +++ b/desktop/internal/workbench/local_history_view.go @@ -52,10 +52,10 @@ func (a *App) drawLocalHistory(c ui.C, p *project) { } for i, line := range strings.SplitN(h.preview, "\n", localHistoryPreviewLines+1) { if i == localHistoryPreviewLines { - ui.Text(c.KeyInt(i), "…").Muted() + ui.Text(c, "…").Muted() break } - ui.Text(c.KeyInt(i), line).Mono().FontSize(12).Color(a.colors.Text) + ui.Text(c, line).Mono().FontSize(12).Color(a.colors.Text) } }) }) diff --git a/desktop/internal/workbench/memory_monitor.go b/desktop/internal/workbench/memory_monitor.go index d9c05c7022..7dc6ff103f 100644 --- a/desktop/internal/workbench/memory_monitor.go +++ b/desktop/internal/workbench/memory_monitor.go @@ -448,7 +448,7 @@ func (a *App) memoryDetails(c ui.C, anchor ui.Box) { a.memoryBar(c.Part("bar"), parts) a.memoryLegend(c.Part("legend"), language, parts, columns) ui.Divider(c) - a.memoryEntries(c.Part("entries"), language, columns) + a.memoryEntries(c, language, columns) } }) }) diff --git a/desktop/internal/workbench/new_project_view.go b/desktop/internal/workbench/new_project_view.go index c4a2ea79cd..8b3246030e 100644 --- a/desktop/internal/workbench/new_project_view.go +++ b/desktop/internal/workbench/new_project_view.go @@ -531,8 +531,8 @@ func (a *App) projectOutput(c ui.C, language i18n.Language, lines []string) { } ui.Text(c, i18n.Shared(language, "desktop.newProject.output")).FontSize(12).Muted() ui.Column(c).FillWidth().Gap(2).Children(func() { - for index, line := range lines { - ui.Text(c.KeyInt(index), line).Mono().FontSize(11).Color(a.colors.Subtle) + for _, line := range lines { + ui.Text(c, line).Mono().FontSize(11).Color(a.colors.Subtle) } }) } diff --git a/desktop/internal/workbench/notifications.go b/desktop/internal/workbench/notifications.go index 246e5d5f48..cd8f67c5f9 100644 --- a/desktop/internal/workbench/notifications.go +++ b/desktop/internal/workbench/notifications.go @@ -346,7 +346,7 @@ func (a *App) notificationEntry(k ui.C, entry *notification) { language := a.language() if entry.detail != "" { ui.Wrap(k, entry.text).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightMedium) - ui.Wrap(k.Part("detail"), entry.detail).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Wrap(k, entry.detail).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) } else { ui.Wrap(k, entry.text).FontSize(a.theme.Metrics.FontSizeS) } diff --git a/desktop/internal/workbench/pluginsemantics_hover.go b/desktop/internal/workbench/pluginsemantics_hover.go index 1f456d8dcf..21d59daaeb 100644 --- a/desktop/internal/workbench/pluginsemantics_hover.go +++ b/desktop/internal/workbench/pluginsemantics_hover.go @@ -449,7 +449,7 @@ func (a *App) hoverPopup(c ui.C) { button := ui.Row(key).FillWidth().Height(28).PadX(8).Items(ui.Center). HitWith(ui.ID(key), label, gfx.HitOptions{Role: gfx.RoleButton, SkipFocus: true, Cursor: gfx.PointerCursorHand}). Hover(ui.Look{}.Background(a.colors.Hover)) - button.Children(func() { ui.Text(key, label).FontSize(12) }) + button.Children(func() { ui.Text(c, label).FontSize(12) }) if button.Clicked() { docID, span, anchor := state.documentID, *state.quickFix, state.anchor c.After(func() { diff --git a/desktop/internal/workbench/problems_view.go b/desktop/internal/workbench/problems_view.go index 1009def6d3..d39eabd97f 100644 --- a/desktop/internal/workbench/problems_view.go +++ b/desktop/internal/workbench/problems_view.go @@ -89,7 +89,10 @@ func (a *App) problemsToolbar(c ui.C, lang i18n.Language) { if clicked { v.optionsOpen = !v.optionsOpen } - ui.Menu(c.Part("problemsOptionsMenu"), eye, &v.optionsOpen, func(menu *ui.MenuItems) { + if v.optionsOpen { + c.Part("problemsOptionsMenu") + } + ui.Menu(c, eye, &v.optionsOpen, func(menu *ui.MenuItems) { menu.WidthRange(180, 260) menu.Label(i18n.Shared(lang, "desktop.problems.showHeading")) if menu.Item(i18n.Shared(lang, "desktop.problems.showErrors")).Checked(!v.hideErrors).Clicked() { diff --git a/desktop/internal/workbench/recent_files.go b/desktop/internal/workbench/recent_files.go index f0aceae58c..8d31985512 100644 --- a/desktop/internal/workbench/recent_files.go +++ b/desktop/internal/workbench/recent_files.go @@ -179,8 +179,8 @@ func (a *App) recentFilesPopup(c ui.C) { } if box.Children(func() { ui.Column(row).FillWidth().Children(func() { - ui.Text(row, entry.Name).FontSize(13).Color(a.colors.Text) - ui.Text(row, entry.Path).FontSize(11).Color(a.colors.Subtle).Ellipsis() + ui.Text(c, entry.Name).FontSize(13).Color(a.colors.Text) + ui.Text(c, entry.Path).FontSize(11).Color(a.colors.Subtle).Ellipsis() }) }).Clicked() { c.After(func() { open(entry) }) diff --git a/desktop/internal/workbench/remote_browse_view.go b/desktop/internal/workbench/remote_browse_view.go index 8d20e6a26a..71da17daa1 100644 --- a/desktop/internal/workbench/remote_browse_view.go +++ b/desktop/internal/workbench/remote_browse_view.go @@ -57,7 +57,7 @@ func (a *App) remoteBrowserView(c ui.C, b *remoteBrowser) { a.remoteFolderList(k.Part("folders"), b) }) if text := remoteSkippedText(language, b.skipped); text != "" { - ui.Paragraph(k.Part("skipped"), text, 2).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Paragraph(k, text, 2).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) } }) } diff --git a/desktop/internal/workbench/remote_container.go b/desktop/internal/workbench/remote_container.go index 9c9b7aa057..7f82a5f2d0 100644 --- a/desktop/internal/workbench/remote_container.go +++ b/desktop/internal/workbench/remote_container.go @@ -244,7 +244,7 @@ func (a *App) remoteContainerPage(c ui.C, language i18n.Language) { c.After(func() { a.connectRemote("") }) } }) - ui.Paragraph(c.Part("about"), i18n.SharedFormat(language, "desktop.remote.container.about", map[string]string{"engine": engine}), 5).FontSize(small).Color(a.colors.Subtle) + ui.Paragraph(c, i18n.SharedFormat(language, "desktop.remote.container.about", map[string]string{"engine": engine}), 5).FontSize(small).Color(a.colors.Subtle) label := i18n.Shared(language, "desktop.remote.container.user") a.remoteSection(c.Part("account"), label, i18n.Shared(language, "desktop.remote.container.userHelp"), nil, func() { ui.TextField(c.Part("user"), &r.containers.user, label, i18n.Shared(language, "desktop.remote.container.userPlaceholder")). diff --git a/desktop/internal/workbench/remote_detail_view.go b/desktop/internal/workbench/remote_detail_view.go index 47a2382236..0643e5b208 100644 --- a/desktop/internal/workbench/remote_detail_view.go +++ b/desktop/internal/workbench/remote_detail_view.go @@ -40,7 +40,7 @@ func (a *App) remotePage(c ui.C, language i18n.Language) { a.remoteOverview(c, language, *entry) case r.loading && !r.loaded: ui.Column(c).Fill().Center().Children(func() { - ui.Spinner(c.Part("loading")) + ui.Spinner(c) }) default: a.remoteEmptyPage(c, language) @@ -267,9 +267,9 @@ func (a *App) remoteRecentSection(c ui.C, language i18n.Language, entry core.Sav HitWith(ui.ID(k), folder, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Disabled: disabled}). Hover(ui.Look{}.Background(a.colors.Hover)).Pressed(ui.Look{}.Background(a.colors.Active)) row.Children(func() { - ui.Icon(k, icons.Folder).Size(14, 14).Shrink(0).Color(a.colors.Subtle) - ui.Text(k, folder).Mono().FontSize(small).Ellipsis().Grow(1).MinWidth(0) - ui.Icon(k, icons.ChevronRight).Size(12, 12).Shrink(0).Color(a.colors.Subtle) + ui.Icon(c, icons.Folder).Size(14, 14).Shrink(0).Color(a.colors.Subtle) + ui.Text(c, folder).Mono().FontSize(small).Ellipsis().Grow(1).MinWidth(0) + ui.Icon(c, icons.ChevronRight).Size(12, 12).Shrink(0).Color(a.colors.Subtle) }) if !disabled && row.Clicked() { folder := folder @@ -287,7 +287,7 @@ func (a *App) remoteHostSection(c ui.C, language i18n.Language, outcome *remoteP small := a.theme.Metrics.FontSizeS a.remoteSection(c, i18n.Shared(language, "desktop.remote.hostSection"), "", func() { if r.probe != nil { - ui.Spinner(c.Part("testing")).Size(12, 12) + ui.Spinner(c).Size(12, 12) ui.Text(c, i18n.Shared(language, "desktop.remote.testing")).FontSize(small).Color(a.colors.Subtle) if ui.Button(c.Part("stop"), i18n.Shared(language, "desktop.remote.stop")).Link().Clicked() { c.After(a.stopRemoteTest) @@ -355,10 +355,10 @@ func (a *App) remoteHostGrid(c ui.C, language i18n.Language, host core.RemotePro value = "—" } ui.Column(k).Grow(1).Basis(0).MinWidth(0).Gap(3).PadSides(10, 12, 10, 12).Children(func() { - ui.Text(k, item.label).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) - ui.Text(k, value).Weight(gfx.WeightMedium).Ellipsis().MinWidth(0) + ui.Text(c, item.label).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + ui.Text(c, value).Weight(gfx.WeightMedium).Ellipsis().MinWidth(0) if item.detail != "" { - ui.Text(k, item.detail).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + ui.Text(c, item.detail).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) } }) } @@ -383,7 +383,7 @@ func (a *App) remoteOutcomeBox(c ui.C, language i18n.Language, outcome *remotePr k := c.Part("box") ui.Column(k).FillWidth().Gap(6).PadSides(10, 14, 10, 12).Radius(6).Background(tint.WithAlpha(0.08)).Stroke(1, tint.WithAlpha(0.35)).Children(func() { ui.Row(k).FillWidth().Gap(8).Items(ui.Start).Children(func() { - ui.Icon(k, icon).Size(14, 14).Shrink(0).Color(tint).MarginTop(2) + ui.Icon(c, icon).Size(14, 14).Shrink(0).Color(tint).MarginTop(2) if connected { var system, machine string if host := outcome.result.Host; host != nil { @@ -396,7 +396,7 @@ func (a *App) remoteOutcomeBox(c ui.C, language i18n.Language, outcome *remotePr ui.Text(line, i18n.Shared(language, "desktop.remote.probe.usable")).Color(tint).Ellipsis().MinWidth(0) }) } else { - ui.Paragraph(k, remoteFailureText(language, outcome), 4).Weight(gfx.WeightMedium).Color(tint).Grow(1).MinWidth(0) + ui.Paragraph(c, remoteFailureText(language, outcome), 4).Weight(gfx.WeightMedium).Color(tint).Grow(1).MinWidth(0) } if diagnostics != "" { label := i18n.Shared(language, "desktop.remote.diagnostics") @@ -411,14 +411,14 @@ func (a *App) remoteOutcomeBox(c ui.C, language i18n.Language, outcome *remotePr if connected && outcome.result.Host != nil { a.remoteHostTags(k.Part("tags"), language, *outcome.result.Host) } else if hint := remoteFailureHint(language, outcome); hint != "" { - ui.Paragraph(k.Part("hint"), hint, 4).FontSize(small).Color(tint).MarginLeft(22) + ui.Paragraph(c, hint, 4).FontSize(small).Color(tint).MarginLeft(22) } }) if diagnostics != "" && r.log.Open { l := c.Part("log") ui.Scroll(l).FillWidth().MaxHeight(180).Children(func() { ui.Column(l).FillWidth().PadSides(10, 12, 10, 12).Radius(6).Background(a.colors.Hover).Stroke(1, a.colors.Line).Children(func() { - ui.Paragraph(l.Part("text"), diagnostics, 40).Mono().FontSize(small).Color(a.colors.Subtle) + ui.Paragraph(l, diagnostics, 40).Mono().FontSize(small).Color(a.colors.Subtle) }) }) } @@ -539,8 +539,8 @@ func (a *App) remoteEffectiveTable(c ui.C, language i18n.Language, settings core ui.Row(k.Part("line")).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) } ui.Row(k).FillWidth().Height(30).Items(ui.Center).Gap(10).PadX(12).Children(func() { - ui.Text(k, item.key).FontSize(small).Color(a.colors.Subtle).Width(140).Shrink(0).Ellipsis() - value := ui.Text(k, item.value).FontSize(small).Ellipsis().Grow(1).MinWidth(0) + ui.Text(c, item.key).FontSize(small).Color(a.colors.Subtle).Width(140).Shrink(0).Ellipsis() + value := ui.Text(c, item.value).FontSize(small).Ellipsis().Grow(1).MinWidth(0) if !item.words { value.Mono() } @@ -574,7 +574,7 @@ func (a *App) remoteFormPage(c ui.C, language i18n.Language) { switch { case r.probe != nil: ui.Row(c.Part("testing")).FillWidth().Items(ui.Center).Gap(8).Pad(12).Radius(6).Stroke(1, a.colors.Line).Children(func() { - ui.Spinner(c.Part("spinner")).Size(14, 14) + ui.Spinner(c).Size(14, 14) ui.Text(c, i18n.Shared(language, "desktop.remote.testing")).Color(a.colors.Subtle) }) case r.result != nil: diff --git a/desktop/internal/workbench/remote_devcontainer.go b/desktop/internal/workbench/remote_devcontainer.go index 500a078df5..39d66aa850 100644 --- a/desktop/internal/workbench/remote_devcontainer.go +++ b/desktop/internal/workbench/remote_devcontainer.go @@ -373,7 +373,7 @@ func (a *App) remoteDevcontainerView(c ui.C, language i18n.Language, d *remoteDe }) ui.Column(h).Grow(1).Basis(0).MinWidth(0).Gap(4).Children(func() { ui.Text(h, i18n.Shared(language, "desktop.remote.devcontainer.title")).FontSize(16).Weight(gfx.WeightSemibold).Ellipsis().MinWidth(0) - ui.Paragraph(h.Part("about"), i18n.Shared(language, "desktop.remote.devcontainer.about"), 3).FontSize(small).Color(a.colors.Subtle) + ui.Paragraph(h, i18n.Shared(language, "desktop.remote.devcontainer.about"), 3).FontSize(small).Color(a.colors.Subtle) }) }) label := i18n.Shared(language, "desktop.remote.devcontainer.folder") @@ -402,7 +402,7 @@ func (a *App) remoteDevcontainerView(c ui.C, language i18n.Language, d *remoteDe config := i18n.Shared(language, "desktop.remote.devcontainer.config") a.remoteSection(c, config, i18n.Shared(language, "desktop.remote.devcontainer.configHelp"), nil, func() { if len(d.configs) == 0 { - ui.Paragraph(c.Part("none"), i18n.Shared(language, "desktop.remote.devcontainer.none"), 3).FontSize(small).Color(a.colors.Warning) + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.devcontainer.none"), 3).FontSize(small).Color(a.colors.Warning) return } paths := make([]string, len(d.configs)) @@ -442,7 +442,7 @@ func (a *App) remoteDevcontainerView(c ui.C, language i18n.Language, d *remoteDe l := c.Part("diagnostics") ui.Scroll(l).FillWidth().MaxHeight(120).Children(func() { ui.Column(l).FillWidth().Pad(10).Radius(6).Background(a.colors.Hover).Stroke(1, a.colors.Line).Children(func() { - ui.Paragraph(l.Part("text"), d.diagnostics, 40).Mono().FontSize(small).Color(a.colors.Subtle) + ui.Paragraph(l, d.diagnostics, 40).Mono().FontSize(small).Color(a.colors.Subtle) }) }) } @@ -490,7 +490,7 @@ func (a *App) remoteDevcontainerLog(c ui.C, language i18n.Language, d *remoteDev }).Scrollbars().Label(title).Fill() }) if d.truncated { - ui.Text(c.Part("truncated"), i18n.Shared(language, "desktop.remote.devcontainer.truncated")).FontSize(small).Color(a.colors.Subtle) + ui.Text(c, i18n.Shared(language, "desktop.remote.devcontainer.truncated")).FontSize(small).Color(a.colors.Subtle) } }) } diff --git a/desktop/internal/workbench/remote_host_containers.go b/desktop/internal/workbench/remote_host_containers.go index e97b21c9ae..7e73119697 100644 --- a/desktop/internal/workbench/remote_host_containers.go +++ b/desktop/internal/workbench/remote_host_containers.go @@ -159,7 +159,7 @@ func (a *App) enterRemoteHostContainer() { // enter as, the list, and the engines' words when listing failed. func (a *App) remoteHostContainersView(c ui.C, language i18n.Language, list *remoteBrowserContainers) { small := a.theme.Metrics.FontSizeS - ui.Paragraph(c.Part("about"), i18n.Shared(language, "desktop.remote.hostContainers.about"), 4).FontSize(small).Color(a.colors.Subtle) + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.hostContainers.about"), 4).FontSize(small).Color(a.colors.Subtle) label := i18n.Shared(language, "desktop.remote.container.user") ui.Row(c.Part("account")).FillWidth().Gap(8).Items(ui.Center).Children(func() { ui.Text(c, label).FontSize(small).Shrink(0) @@ -180,8 +180,8 @@ func (a *App) remoteHostContainersView(c ui.C, language i18n.Language, list *rem } ui.Column(c.Part("empty")).FillWidth().Pad(12).Gap(8).Children(func() { ui.Paragraph(c, text, 3).FontSize(small).Color(a.colors.Subtle) - for i, words := range list.diagnostics { - ui.Paragraph(c.KeyInt(i), words, 6).Mono().FontSize(small).Color(a.colors.Subtle) + for _, words := range list.diagnostics { + ui.Paragraph(c, words, 6).Mono().FontSize(small).Color(a.colors.Subtle) } }) return diff --git a/desktop/internal/workbench/remote_import.go b/desktop/internal/workbench/remote_import.go index d2f6ed9361..a71bbc9101 100644 --- a/desktop/internal/workbench/remote_import.go +++ b/desktop/internal/workbench/remote_import.go @@ -292,7 +292,7 @@ func (a *App) remoteImportView(c ui.C, language i18n.Language, m *remoteImporter } switch { case m.loading: - ui.Column(c.Part("loading")).FillWidth().Grow(1).Center().Children(func() { ui.Spinner(c.Part("spinner")) }) + ui.Column(c.Part("loading")).FillWidth().Grow(1).Center().Children(func() { ui.Spinner(c) }) case m.source == remoteImportMotty && m.mottyErr != "": a.remoteNotice(c.Part("motty-error"), icons.CircleX, a.theme.Danger, m.mottyErr) case m.source == remoteImportMotty && m.motty.Unavailable != "": @@ -332,7 +332,7 @@ func (a *App) remoteImportHeader(c ui.C, lead, trail float32, columns []string, ui.Row(c).FillWidth().Height(30).Shrink(0).Items(ui.Center).Gap(10).PadX(10).Children(func() { ui.Row(c.Part("lead")).Width(lead).Shrink(0) for index, column := range columns { - cell := ui.Text(c.KeyInt(index), column).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + cell := ui.Text(c, column).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(a.colors.Subtle).Ellipsis().MinWidth(0) if widths[index] == 0 { cell.Grow(1).Basis(0) } else { @@ -391,18 +391,18 @@ func (a *App) remoteSSHImportTable(c ui.C, language i18n.Language, m *remoteImpo ui.Row(k.Part("pick")).Width(22).Shrink(0).Children(func() { ui.Checkbox(k.Part("box"), &m.sshChosen[index], "").Label(host.Alias).Disabled(!choosable || m.applying) }) - ui.Text(k, host.Alias).Mono().FontSize(small).Color(color).Width(widths[0]).Shrink(0).Ellipsis() + ui.Text(c, host.Alias).Mono().FontSize(small).Color(color).Width(widths[0]).Shrink(0).Ellipsis() ui.Column(k).Grow(1).Basis(0).MinWidth(0).Gap(2).Children(func() { switch { case host.Status == core.RemoteImportPattern: - ui.Text(k, i18n.Shared(language, "desktop.remote.import.patternNote")).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + ui.Text(c, i18n.Shared(language, "desktop.remote.import.patternNote")).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) case host.Resolved != nil: resolved := host.Resolved - ui.Text(k, remoteAddress(core.SSHConnection{Host: resolved.HostName, User: resolved.User, Port: resolved.Port})). + ui.Text(c, remoteAddress(core.SSHConnection{Host: resolved.HostName, User: resolved.User, Port: resolved.Port})). Mono().FontSize(small).Color(color).Ellipsis().MinWidth(0) } if len(host.UsedAsJumpBy) > 0 { - ui.Text(k, i18n.SharedFormat(language, "desktop.remote.import.jumpFor", map[string]string{"hosts": strings.Join(host.UsedAsJumpBy, ", ")})). + ui.Text(c, i18n.SharedFormat(language, "desktop.remote.import.jumpFor", map[string]string{"hosts": strings.Join(host.UsedAsJumpBy, ", ")})). Mono().FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) } }) @@ -457,20 +457,20 @@ func (a *App) remoteMottyImportTable(c ui.C, language i18n.Language, m *remoteIm } a.remoteTile(k.Part("tile"), mark, candidate.Name, candidate.Color, 26, 10) ui.Column(k).Grow(1).Basis(0).MinWidth(0).Gap(2).Children(func() { - ui.Text(k, candidate.Name).Weight(gfx.WeightMedium).Color(color).Ellipsis().MinWidth(0) + ui.Text(c, candidate.Name).Weight(gfx.WeightMedium).Color(color).Ellipsis().MinWidth(0) if candidate.Address != "" { - ui.Text(k, candidate.Address).Mono().FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + ui.Text(c, candidate.Address).Mono().FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) } }) group := candidate.Group if group == "" { group = "—" } - ui.Text(k, group).FontSize(small).Color(color).Width(widths[1]).Shrink(0).Ellipsis() + ui.Text(c, group).FontSize(small).Color(color).Width(widths[1]).Shrink(0).Ellipsis() ui.Row(k.Part("result")).Width(widths[2]).Shrink(0).Items(ui.Center).Gap(6).Children(func() { a.remoteImportTag(k.Part("status"), remoteImportStatusName(language, candidate.Status), candidate.Status) if candidate.Status == core.RemoteImportExists && m.mottyChosen[index] { - ui.Text(k, i18n.Shared(language, "desktop.remote.import.fill")).FontSize(small).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) + ui.Text(c, i18n.Shared(language, "desktop.remote.import.fill")).FontSize(small).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) } }) icon := icons.ChevronRight @@ -513,20 +513,20 @@ func (a *App) remoteMottyFields(c ui.C, language i18n.Language, fields []core.Re ui.Row(k.Part("line")).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) } ui.Row(k).FillWidth().MinHeight(26).Items(ui.Center).Gap(10).PadY(3).Children(func() { - ui.Text(k, field.Motty).Mono().FontSize(small).Color(a.colors.Subtle).Grow(1).Basis(0).MinWidth(0).Ellipsis() + ui.Text(c, field.Motty).Mono().FontSize(small).Color(a.colors.Subtle).Grow(1).Basis(0).MinWidth(0).Ellipsis() value := field.Value if value == "" { value = "—" } - ui.Text(k, value).Mono().FontSize(small).Grow(1).Basis(0).MinWidth(0).Ellipsis() - ui.Text(k, "→").FontSize(small).Color(a.colors.Subtle).Shrink(0) + ui.Text(c, value).Mono().FontSize(small).Grow(1).Basis(0).MinWidth(0).Ellipsis() + ui.Text(c, "→").FontSize(small).Color(a.colors.Subtle).Shrink(0) if field.Lithe != "" { - ui.Text(k, remoteMottyFieldName(language, field.Lithe)).FontSize(small).Grow(1.6).Basis(0).MinWidth(0).Ellipsis() + ui.Text(c, remoteMottyFieldName(language, field.Lithe)).FontSize(small).Grow(1.6).Basis(0).MinWidth(0).Ellipsis() } else { - ui.Text(k, remoteMottySkipText(language, field.Skip)).FontSize(small).Color(a.colors.Subtle).Grow(1.6).Basis(0).MinWidth(0).Ellipsis() + ui.Text(c, remoteMottySkipText(language, field.Skip)).FontSize(small).Color(a.colors.Subtle).Grow(1.6).Basis(0).MinWidth(0).Ellipsis() } ui.Row(k.Part("tag")).Width(110).Shrink(0).Children(func() { - ui.Spacer(k) + ui.Spacer(c) if field.Lithe != "" { a.remoteTag(k.Part("imported"), i18n.Shared(language, "desktop.remote.import.field.imported"), a.colors.Success) } else { diff --git a/desktop/internal/workbench/remote_list.go b/desktop/internal/workbench/remote_list.go index 8112de1610..33514e5706 100644 --- a/desktop/internal/workbench/remote_list.go +++ b/desktop/internal/workbench/remote_list.go @@ -423,20 +423,20 @@ func (a *App) remoteHops(c ui.C, language i18n.Language, disabled bool) { return } ui.Row(c.Part("route")).FillWidth().Gap(6).Items(ui.Center).Children(func() { - step := func(k ui.C, text string, color gfx.Color) { - ui.Icon(k, icons.ChevronRight).Size(12, 12).Shrink(0).Color(a.colors.Subtle) - ui.Text(k, text).Mono().FontSize(small).Color(color).Ellipsis().Shrink(1).MinWidth(0) + step := func(text string, color gfx.Color) { + ui.Icon(c, icons.ChevronRight).Size(12, 12).Shrink(0).Color(a.colors.Subtle) + ui.Text(c, text).Mono().FontSize(small).Color(color).Ellipsis().Shrink(1).MinWidth(0) } ui.Text(c, i18n.Shared(language, "desktop.remote.thisComputer")).FontSize(small).Color(a.colors.Subtle).Shrink(0) - for index, hop := range hops { - step(c.KeyInt(index), hop, a.colors.Subtle) + for _, hop := range hops { + step(hop, a.colors.Subtle) } target := strings.TrimSpace(f.host.Text()) if user := strings.TrimSpace(f.user.Text()); user != "" && target != "" { target = user + "@" + target } if target != "" { - step(c.Part("target"), target, a.colors.Accent) + step(target, a.colors.Accent) } }) }) diff --git a/desktop/internal/workbench/remote_port_rules_view.go b/desktop/internal/workbench/remote_port_rules_view.go index 4385fe5be0..9164e8de3f 100644 --- a/desktop/internal/workbench/remote_port_rules_view.go +++ b/desktop/internal/workbench/remote_port_rules_view.go @@ -27,7 +27,7 @@ func (a *App) remotePortRules(c ui.C, p *project, rules []core.RemoteForward, id language := a.language() k := c.Part("rules") ui.Row(k.Part("heading")).FillWidth().Height(remotePortsRowHeight).Shrink(0).Items(ui.Center).Gap(4).PadX(shellContentPad).Children(func() { - ui.Text(k.Part("heading-text"), i18n.Shared(language, "desktop.remote.ports.rulesHeading")).Color(a.colors.Text).Ellipsis() + ui.Text(k, i18n.Shared(language, "desktop.remote.ports.rulesHeading")).Color(a.colors.Text).Ellipsis() ui.Button(k.Part("help"), i18n.Shared(language, "native.moreInformation")).Icon(icons.Info).IconOnly().Ghost().Size(16, 16). Tooltip(i18n.Shared(language, "desktop.remote.ports.rulesHelp")) }) @@ -40,7 +40,7 @@ func (a *App) remotePortRules(c ui.C, p *project, rules []core.RemoteForward, id cell = cell.Grow(1).Shrink(1).MinWidth(0) } cell.Children(func() { - ui.Text(k.Part(key+"-text"), text).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() + ui.Text(k, text).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() }) } column("listen", i18n.Shared(language, "desktop.remote.ports.ruleColumnListen"), remotePortRulesListenWidth) @@ -102,16 +102,16 @@ func (a *App) remotePortIdleRuleRow(c ui.C, p *project, rule core.RemotePortRule HitWith(ui.ID(c), listen, gfx.HitOptions{Value: status, SkipFocus: true}) line.Children(func() { ui.Row(c.Part("listen")).Width(remotePortRulesListenWidth).Shrink(0).Items(ui.Center).Gap(6).Children(func() { - ui.Icon(c.Part("kind"), icon).Size(14, 14).Shrink(0).Color(a.colors.Subtle) - ui.Text(c.Part("listen-text"), listen).Color(a.colors.Subtle).Ellipsis() + ui.Icon(c, icon).Size(14, 14).Shrink(0).Color(a.colors.Subtle) + ui.Text(c, listen).Color(a.colors.Subtle).Ellipsis() }) a.remotePortsLabelCell(c, rule.Label) ui.Row(c.Part("target")).Grow(1).Shrink(1).MinWidth(0).Items(ui.Center).Children(func() { - ui.Text(c.Part("target-text"), remotePortIdleTarget(language, rule)).Color(a.colors.Subtle).Ellipsis() + ui.Text(c, remotePortIdleTarget(language, rule)).Color(a.colors.Subtle).Ellipsis() }) ui.Row(c.Part("connections")).Width(remotePortRulesConnectionsWidth).Shrink(0) ui.Row(c.Part("status")).Width(remotePortsStatusWidth).Shrink(0).Items(ui.Center).Children(func() { - ui.Text(c.Part("status-text"), status).Color(a.colors.Subtle).Ellipsis() + ui.Text(c, status).Color(a.colors.Subtle).Ellipsis() }) ui.Row(c.Part("actions")).Width(remotePortsActionWidth).Shrink(0).Items(ui.Center).Justify(ui.End).Gap(2).Children(func() { if _, clicked := a.toolIconButton(c.Part("start"), i18n.Shared(language, "desktop.remote.ports.ruleStart"), icons.Play, false, unavailable); clicked { @@ -122,7 +122,7 @@ func (a *App) remotePortIdleRuleRow(c ui.C, p *project, rule core.RemotePortRule } }) }) - ui.ContextMenu(c.Part("menu"), line, func(menu *ui.MenuItems) { + ui.ContextMenu(c, line, func(menu *ui.MenuItems) { menu.WidthRange(180, 280) if menu.Item(i18n.Shared(language, "desktop.remote.ports.ruleStart")).Icon(icons.Play).Disabled(unavailable).Clicked() { c.After(func() { a.startRememberedRule(p, rule, surfaceContextMenu) }) @@ -184,18 +184,18 @@ func (a *App) remotePortRuleRow(c ui.C, p *project, rule core.RemoteForward) { Tooltip(tip) } listenCell.Children(func() { - ui.Icon(c.Part("kind"), icon).Size(14, 14).Shrink(0).Color(color) - ui.Text(c.Part("listen-text"), listen).Color(color).Ellipsis() + ui.Icon(c, icon).Size(14, 14).Shrink(0).Color(color) + ui.Text(c, listen).Color(color).Ellipsis() }) a.remotePortsLabelCell(c, ports.ruleLabel(rule)) ui.Row(c.Part("target")).Grow(1).Shrink(1).MinWidth(0).Items(ui.Center).Children(func() { - ui.Text(c.Part("target-text"), remotePortRuleTarget(language, rule)).Color(a.colors.Text).Ellipsis() + ui.Text(c, remotePortRuleTarget(language, rule)).Color(a.colors.Text).Ellipsis() }) ui.Row(c.Part("connections")).Width(remotePortRulesConnectionsWidth).Shrink(0).Items(ui.Center).Children(func() { - ui.Text(c.Part("connections-text"), connections).Color(connectionsColor).Ellipsis() + ui.Text(c, connections).Color(connectionsColor).Ellipsis() }) ui.Row(c.Part("status")).Width(remotePortsStatusWidth).Shrink(0).Items(ui.Center).Children(func() { - ui.Text(c.Part("status-text"), status).Color(statusColor).Ellipsis() + ui.Text(c, status).Color(statusColor).Ellipsis() }) ui.Row(c.Part("actions")).Width(remotePortsActionWidth).Shrink(0).Items(ui.Center).Justify(ui.End).Gap(2).Children(func() { if _, clicked := a.toolIconButton(c.Part("stop"), i18n.Shared(language, "desktop.remote.ports.stop"), icons.Square, false, busy); clicked { @@ -203,7 +203,7 @@ func (a *App) remotePortRuleRow(c ui.C, p *project, rule core.RemoteForward) { } }) }) - ui.ContextMenu(c.Part("menu"), line, func(menu *ui.MenuItems) { + ui.ContextMenu(c, line, func(menu *ui.MenuItems) { menu.WidthRange(180, 280) record := remotePortRuleOf(rule) if menu.Item(i18n.Shared(language, "desktop.remote.ports.editLabel")).Icon(icons.Tag).Clicked() { @@ -243,7 +243,7 @@ func (a *App) remotePortRuleDialog(c ui.C, p *project) { unavailable := p.remote.session == "" || draft.starting closed := ui.Modal(c.Part("ports-rule"), &ports.ruleOpen, title, func() { if draft.confirm != remotePortRuleNoConfirm { - ui.Paragraph(c.Part("rule-question"), a.remotePortRuleQuestion(p, draft), 6).Color(a.colors.Warning) + ui.Paragraph(c, a.remotePortRuleQuestion(p, draft), 6).Color(a.colors.Warning) return } a.remotePortRuleFields(c, p, draft, unavailable) @@ -289,13 +289,13 @@ func (a *App) remotePortRuleFields(c ui.C, p *project, draft *remotePortRuleDraf return i18n.Shared(language, "desktop.remote.ports.ruleKindHost") } kindTitle := i18n.Shared(language, "desktop.remote.ports.ruleKind") - ui.Text(c.Part("rule-kind-title"), kindTitle).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Text(c, kindTitle).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) if ui.Select(c.Part("rule-kind"), &draft.kind, kinds, kindLabel).FillWidth().Label(kindTitle).Disabled(unavailable).Changed() { draft.message = "" draft.target.SetText("") } if !draft.reverseAllowed { - ui.Paragraph(c.Part("rule-reverse-off"), i18n.Shared(language, "desktop.remote.ports.ruleReverseOff"), 3). + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.ports.ruleReverseOff"), 3). FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) } reverse := draft.kind == remotePortRuleReverse @@ -307,25 +307,25 @@ func (a *App) remotePortRuleFields(c ui.C, p *project, draft *remotePortRuleDraf targetTitle = i18n.Shared(language, "desktop.remote.ports.ruleLocal") targetPlaceholder = i18n.Shared(language, "desktop.remote.ports.ruleLocalPlaceholder") } - ui.Paragraph(c.Part("rule-note"), note, 4).Color(a.colors.Text) + ui.Paragraph(c, note, 4).Color(a.colors.Text) listenTitle := i18n.Shared(language, "desktop.remote.ports.ruleListen") - ui.Text(c.Part("rule-listen-title"), listenTitle).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Text(c, listenTitle).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) listened := ui.TextField(c.Part("rule-listen"), &draft.listen, listenTitle, i18n.Shared(language, "desktop.remote.ports.ruleListenPlaceholder")).FillWidth().Submitted() - ui.Text(c.Part("rule-target-title"), targetTitle).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Text(c, targetTitle).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) targeted := ui.TextField(c.Part("rule-target"), &draft.target, targetTitle, targetPlaceholder).FillWidth().Submitted() if !reverse { ui.Checkbox(c.Part("rule-all"), &draft.allInterfaces, i18n.Shared(language, "desktop.remote.ports.ruleAllInterfaces")).Disabled(unavailable) if draft.allInterfaces { - ui.Paragraph(c.Part("rule-all-note"), i18n.Shared(language, "desktop.remote.ports.ruleAllInterfacesNote"), 3). + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.ports.ruleAllInterfacesNote"), 3). FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Warning) } } if draft.starting { - ui.Text(c.Part("rule-starting"), i18n.Shared(language, "desktop.remote.ports.statusForwarding")).FontSize(12).Color(a.colors.Subtle) + ui.Text(c, i18n.Shared(language, "desktop.remote.ports.statusForwarding")).FontSize(12).Color(a.colors.Subtle) } if draft.message != "" { - ui.Paragraph(c.Part("rule-message"), draft.message, 3).FontSize(12).Color(a.theme.Danger) + ui.Paragraph(c, draft.message, 3).FontSize(12).Color(a.theme.Danger) } if (listened || targeted) && !unavailable { c.After(func() { a.submitRemotePortRule(p, surfaceShortcut) }) diff --git a/desktop/internal/workbench/remote_ports_view.go b/desktop/internal/workbench/remote_ports_view.go index db3989b9ae..548bf7e0bb 100644 --- a/desktop/internal/workbench/remote_ports_view.go +++ b/desktop/internal/workbench/remote_ports_view.go @@ -150,7 +150,7 @@ func (a *App) remotePortsHeader(c ui.C) { cell = cell.Grow(1).Shrink(1).MinWidth(0) } cell.Children(func() { - ui.Text(k.Part(key+"-text"), text).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() + ui.Text(c, text).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() }) } column("remote", i18n.Shared(language, "desktop.remote.ports.columnRemote"), remotePortsRemoteWidth) @@ -276,7 +276,7 @@ func (a *App) remotePortsRow(c ui.C, p *project, row remotePortRow) { Tooltip(remoteTip) } remoteCell.Children(func() { - ui.Text(c.Part("remote-text"), remote).Color(a.colors.Text).Ellipsis() + ui.Text(c, remote).Color(a.colors.Text).Ellipsis() }) a.remotePortsLabelCell(c, ports.labels[row.key]) localCell := ui.Row(c.Part("local")).Width(remotePortsLocalWidth).Shrink(0).Items(ui.Center) @@ -288,22 +288,22 @@ func (a *App) remotePortsRow(c ui.C, p *project, row remotePortRow) { Tooltip(localTip) } localCell.Children(func() { - ui.Text(c.Part("local-text"), local).Color(color).Ellipsis() + ui.Text(c, local).Color(color).Ellipsis() }) ui.Row(c.Part("process")).Grow(1).Shrink(1).MinWidth(0).Items(ui.Center).Children(func() { - ui.Text(c.Part("process-text"), remotePortsProcess(language, row)).Color(a.colors.Subtle).Ellipsis() + ui.Text(c, remotePortsProcess(language, row)).Color(a.colors.Subtle).Ellipsis() }) ui.Row(c.Part("source")).Width(remotePortsSourceWidth).Shrink(0).Items(ui.Center).Children(func() { - ui.Text(c.Part("source-text"), source).Color(a.colors.Subtle).Ellipsis() + ui.Text(c, source).Color(a.colors.Subtle).Ellipsis() }) ui.Row(c.Part("status")).Width(remotePortsStatusWidth).Shrink(0).Items(ui.Center).Children(func() { - ui.Text(c.Part("status-text"), status).Color(statusColor).Ellipsis() + ui.Text(c, status).Color(statusColor).Ellipsis() }) ui.Row(c.Part("actions")).Width(remotePortsActionWidth).Shrink(0).Items(ui.Center).Justify(ui.End).Gap(2).Children(func() { a.remotePortsRowActions(c, p, row, busy) }) }) - ui.ContextMenu(c.Part("menu"), line, func(menu *ui.MenuItems) { + ui.ContextMenu(c, line, func(menu *ui.MenuItems) { menu.WidthRange(180, 280) if row.forward != nil { forward := *row.forward @@ -443,7 +443,7 @@ func (a *App) remotePortsLabelCell(c ui.C, label string) { cell = cell.HitWith(ui.ID(c.Part("label")), label, gfx.HitOptions{Role: gfx.RoleStatus, SkipFocus: true}).Tooltip(label) } cell.Children(func() { - ui.Text(c.Part("label-text"), label).Color(a.colors.Text).Ellipsis() + ui.Text(c, label).Color(a.colors.Text).Ellipsis() }) } @@ -499,7 +499,7 @@ func (a *App) remotePortsStatusItem(c ui.C) { }). Tooltip(i18n.SharedFormat(language, "desktop.remote.ports.statusTooltip", map[string]string{"count": count})) button.Children(func() { - ui.Icon(k, icons.ArrowLeftRight).Size(chromeMarkSize, chromeMarkSize).Shrink(0).Color(a.colors.Accent) + ui.Icon(c, icons.ArrowLeftRight).Size(chromeMarkSize, chromeMarkSize).Shrink(0).Color(a.colors.Accent) a.chromeStatusLabel(k, count) }) if button.Clicked() { diff --git a/desktop/internal/workbench/remote_steps.go b/desktop/internal/workbench/remote_steps.go index 2818a43dd4..5b6a19baeb 100644 --- a/desktop/internal/workbench/remote_steps.go +++ b/desktop/internal/workbench/remote_steps.go @@ -214,7 +214,7 @@ func (a *App) remoteStepRow(c ui.C, language i18n.Language, s *remoteSteps, step case current && s.failed: ui.Icon(c, icons.CircleX).Size(16, 16).Color(a.theme.Danger) case current: - ui.Spinner(c.Part("spinner")).Size(14, 14) + ui.Spinner(c).Size(14, 14) default: ui.Row(c.Part("todo")).Size(12, 12).Radius(6).Stroke(1, a.colors.TabIdleBorder) } @@ -233,7 +233,7 @@ func (a *App) remoteStepRow(c ui.C, language i18n.Language, s *remoteSteps, step }) if step == remoteStepInstall && current && !s.failed && s.total > 0 { ui.Column(c.Part("upload")).FillWidth().Gap(4).PadSides(0, 0, 0, 26).Children(func() { - ui.Progress(c.Part("progress"), float32(s.sent)/float32(s.total)).FillWidth() + ui.Progress(c, float32(s.sent)/float32(s.total)).FillWidth() ui.Text(c, i18n.SharedFormat(language, "desktop.remote.steps.upload", map[string]string{ "sent": memorySize(language, s.sent), "total": memorySize(language, s.total), })).Mono().FontSize(small).Color(a.colors.Subtle) @@ -285,8 +285,8 @@ func (a *App) remoteQuestionCard(c ui.C, language i18n.Language, s *remoteSteps, } k := c.KeyInt(index) ui.Row(k).FillWidth().Items(ui.Center).Gap(10).Children(func() { - ui.Text(k, item[0]).FontSize(small).Color(a.colors.Subtle).Width(80).Shrink(0) - ui.Text(k, item[1]).Mono().FontSize(small).Ellipsis().Grow(1).MinWidth(0) + ui.Text(c, item[0]).FontSize(small).Color(a.colors.Subtle).Width(80).Shrink(0) + ui.Text(c, item[1]).Mono().FontSize(small).Ellipsis().Grow(1).MinWidth(0) }) } ui.Paragraph(c, i18n.Shared(language, "desktop.remote.hostKey.hint"), 3).FontSize(small).Color(a.colors.Subtle) diff --git a/desktop/internal/workbench/remote_trust.go b/desktop/internal/workbench/remote_trust.go index e673e838a0..1b61fbdeb2 100644 --- a/desktop/internal/workbench/remote_trust.go +++ b/desktop/internal/workbench/remote_trust.go @@ -222,7 +222,7 @@ func (a *App) remoteTrustView(c ui.C, language i18n.Language, t *remoteTrustProm ui.Text(c, i18n.Shared(language, "desktop.remote.trust.title")).FontSize(16).Weight(gfx.WeightSemibold) ui.Text(c, t.browser.host.address()+" : "+t.dir).Mono().FontSize(small).Ellipsis().Shrink(1).MinWidth(0) }) - ui.Paragraph(c.Part("body"), i18n.Shared(language, "desktop.remote.trust.body"), 6).FontSize(small).Color(a.colors.Subtle) + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.trust.body"), 6).FontSize(small).Color(a.colors.Subtle) ui.Column(c.Part("choices")).FillWidth().Gap(4).Pad(12).Radius(8).Stroke(1, a.colors.Line).Children(func() { a.remoteTrustChoice(c.Part("full"), language, i18n.Shared(language, "desktop.remote.trust.trustOpen"), i18n.Shared(language, "desktop.remote.trust.full")) a.remoteTrustChoice(c.Part("safe"), language, i18n.Shared(language, "desktop.remote.trust.safeOpen"), i18n.Shared(language, "desktop.remote.trust.safe")) diff --git a/desktop/internal/workbench/remote_view.go b/desktop/internal/workbench/remote_view.go index e4455dc36e..7e8e493af0 100644 --- a/desktop/internal/workbench/remote_view.go +++ b/desktop/internal/workbench/remote_view.go @@ -308,7 +308,7 @@ func (a *App) remoteCell(c ui.C, field, label, help string, width float32, contr }) control(c) if field != "" && r.fieldErr.field == field { - ui.Paragraph(c.Part("error"), remoteRefusalText(a.language(), r.fieldErr), 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) + ui.Paragraph(c, remoteRefusalText(a.language(), r.fieldErr), 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) } }) } diff --git a/desktop/internal/workbench/remote_wsl.go b/desktop/internal/workbench/remote_wsl.go index d5338f66c0..78a1dca05c 100644 --- a/desktop/internal/workbench/remote_wsl.go +++ b/desktop/internal/workbench/remote_wsl.go @@ -276,7 +276,7 @@ func (a *App) remoteWSLPage(c ui.C, language i18n.Language) { c.After(func() { a.connectRemote("") }) } }) - ui.Paragraph(c.Part("about"), i18n.Shared(language, "desktop.remote.wsl.about"), 4).FontSize(small).Color(a.colors.Subtle) + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.wsl.about"), 4).FontSize(small).Color(a.colors.Subtle) label := i18n.Shared(language, "desktop.remote.wsl.user") a.remoteSection(c.Part("account"), label, i18n.Shared(language, "desktop.remote.wsl.userHelp"), nil, func() { ui.TextField(c.Part("user"), &r.wsl.user, label, i18n.Shared(language, "desktop.remote.wsl.userPlaceholder")). diff --git a/desktop/internal/workbench/run_view.go b/desktop/internal/workbench/run_view.go index 85f9014689..16ba307a18 100644 --- a/desktop/internal/workbench/run_view.go +++ b/desktop/internal/workbench/run_view.go @@ -78,7 +78,7 @@ func (a *App) runSessionTabs(c ui.C, p *project) { var closeButton ui.Box chip.Children(func() { a.runStatusMark(k, run, terminalChipIcon) - text := ui.Text(k, run.label).Ellipsis().Shrink(1) + text := ui.Text(c, run.label).Ellipsis().Shrink(1) if on { text.Color(a.colors.Text) } else { @@ -213,13 +213,13 @@ func (a *App) runTree(c ui.C, p *project, run *runEntry) { a.runStatusMark(k, run, runTreeIcon) // The start follows the name with no gap, since its words begin with the separator. ui.Row(k).Shrink(1).MinWidth(0).Items(ui.Center).Children(func() { - ui.Text(k, run.label).Color(a.colors.Text).Weight(gfx.WeightBold).Ellipsis().Shrink(1) - ui.Text(k, a.text.Run.StartedAt(run.started.Format(runStartedLayout))).Color(a.colors.Subtle). + ui.Text(c, run.label).Color(a.colors.Text).Weight(gfx.WeightBold).Ellipsis().Shrink(1) + ui.Text(c, a.text.Run.StartedAt(run.started.Format(runStartedLayout))).Color(a.colors.Subtle). Ellipsis().Shrink(buildDetailShrink) }) - ui.Spacer(k) + ui.Spacer(c) if duration != "" { - ui.Text(k, duration).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Shrink(0) + ui.Text(c, duration).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Shrink(0) } }) if run.running && len(run.ports) > 0 { @@ -298,7 +298,7 @@ func (a *App) runPortsRow(c ui.C, run *runEntry) { if pill.Clicked() { c.After(func() { a.openRunPort(port, surfaceButton) }) } - ui.ContextMenu(pk.Part("menu"), pill, func(menu *ui.MenuItems) { + ui.ContextMenu(c, pill, func(menu *ui.MenuItems) { if menu.Item(a.text.Run.Ports.Open).Clicked() { c.After(func() { a.openRunPort(port, surfaceContextMenu) }) } @@ -322,13 +322,12 @@ func (a *App) runPortsRow(c ui.C, run *runEntry) { // user stopped it. A service runs until it is stopped, so a spinner for as long as it runs would // never say it started. func (a *App) runStatusMark(c ui.C, run *runEntry, size float32) { - k := c.Part("status") if run.running && run.processRunning { - ui.Icon(k, icons.Play).Size(size, size).Shrink(0).Color(a.colors.Success) + ui.Icon(c, icons.Play).Size(size, size).Shrink(0).Color(a.colors.Success) return } if run.running { - ui.Spinner(k).Size(size, size).Shrink(0) + ui.Spinner(c).Size(size, size).Shrink(0) return } icon, tint := icons.CircleCheck, a.colors.Success @@ -338,7 +337,7 @@ func (a *App) runStatusMark(c ui.C, run *runEntry, size float32) { case runStopped: icon, tint = icons.CircleSlash, a.colors.Subtle } - ui.Icon(k, icon).Size(size, size).Shrink(0).Color(tint) + ui.Icon(c, icon).Size(size, size).Shrink(0).Color(tint) } // runStatusText names where an execution stands, the words its status icon stands for. diff --git a/desktop/internal/workbench/runconfig_before_launch.go b/desktop/internal/workbench/runconfig_before_launch.go index 8150932f0a..6d40fdd19e 100644 --- a/desktop/internal/workbench/runconfig_before_launch.go +++ b/desktop/internal/workbench/runconfig_before_launch.go @@ -327,13 +327,13 @@ func (a *App) drawBeforeLaunchConfirmation(c ui.C, p *project) { closed := ui.ModalWith(c, &open, title, ui.ModalSpec{Width: 520}, func() { k := c.Part("run-before-launch-confirm") ui.Column(k).FillWidth().Gap(8).Children(func() { - ui.Paragraph(k, i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.confirmBody", map[string]string{"name": ask.name}), 4).Color(a.colors.Text) + ui.Paragraph(c, i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.confirmBody", map[string]string{"name": ask.name}), 4).Color(a.colors.Text) for index, step := range ask.steps { row := k.Part(fmt.Sprint(index)) ui.Column(row).FillWidth().Gap(2).Children(func() { - ui.Text(row, fmt.Sprintf("%d. %s", index+1, step.Name)).Weight(gfx.WeightSemibold).Color(a.colors.Text).Ellipsis() + ui.Text(c, fmt.Sprintf("%d. %s", index+1, step.Name)).Weight(gfx.WeightSemibold).Color(a.colors.Text).Ellipsis() if step.Summary != "" { - ui.Text(row, step.Summary).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() + ui.Text(c, step.Summary).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() } }) } diff --git a/desktop/internal/workbench/runconfig_dialog_view.go b/desktop/internal/workbench/runconfig_dialog_view.go index 7879b63fd5..d7deacd00a 100644 --- a/desktop/internal/workbench/runconfig_dialog_view.go +++ b/desktop/internal/workbench/runconfig_dialog_view.go @@ -88,7 +88,7 @@ func (a *App) drawRunConfigDialogTree(c ui.C, p *project) { if clicked { c.After(func() { d.toggleNewMenu(runConfigNewMenuToolbar) }) } - a.drawRunConfigNewMenu(k.Part("add-menu"), p, add, runConfigNewMenuToolbar) + a.drawRunConfigNewMenu(c, p, add, runConfigNewMenuToolbar) if a.gitIconButton(k.Part("remove"), i18n.Shared(language, "desktop.runConfig.removeConfiguration"), icons.Minus, false, !p.runConfigDialogRemovable()) { c.After(func() { a.performed("run.configuration.remove", surfaceButton) @@ -122,8 +122,8 @@ func (a *App) drawRunConfigDialogTree(c ui.C, p *project) { if s.hidden > 0 { ui.Row(k).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) ui.Row(k.Part("hidden")).FillWidth().Shrink(0).Items(ui.Center).Gap(6).Pad(8).Children(func() { - ui.Icon(k, icons.Info).Size(12, 12).Shrink(0).Color(a.colors.Subtle) - ui.Paragraph(k, hiddenRunConfigurations(language, s.hidden), 2).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Grow(1).MinWidth(0) + ui.Icon(c, icons.Info).Size(12, 12).Shrink(0).Color(a.colors.Subtle) + ui.Paragraph(c, hiddenRunConfigurations(language, s.hidden), 2).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Grow(1).MinWidth(0) }) } }) @@ -144,8 +144,11 @@ func (d *runConfigDialog) toggleNewMenu(at runConfigNewMenu) { // drawRunConfigNewMenu declares the menu of kinds under anchor while it shows at at. func (a *App) drawRunConfigNewMenu(c ui.C, p *project, anchor ui.Box, at runConfigNewMenu) { d := &p.runConfigs.dialog - open := d.newMenu == at - ui.Menu(c, anchor, &open, func(menu *ui.MenuItems) { + if d.newMenu != at { + return + } + open := true + ui.Menu(c.Part("add-menu"), anchor, &open, func(menu *ui.MenuItems) { menu.WidthRange(200, 300) a.runConfigDialogTypeItems(c, menu, p) }) @@ -378,24 +381,23 @@ func (a *App) drawRunConfigDialogRow(c ui.C, p *project, i int) { return } row := d.rows[i] - k := c.KeyInt(i) if row.key == "" { icon := fileicons.ForDirectory("folder", a.colors.Dark) if row.node.folder == "" { icon = d.groups[row.group].icon } - ui.Icon(k, icon).Size(treelist.Icon, treelist.Icon).Shrink(0).Color(a.colors.Subtle) - ui.Text(k, a.runConfigDialogRowLabel(p, row)).FontSize(treeFontSize).Color(a.colors.Text).Shrink(1).MinWidth(0).Ellipsis() + ui.Icon(c, icon).Size(treelist.Icon, treelist.Icon).Shrink(0).Color(a.colors.Subtle) + ui.Text(c, a.runConfigDialogRowLabel(p, row)).FontSize(treeFontSize).Color(a.colors.Text).Shrink(1).MinWidth(0).Ellipsis() return } unavailable := a.runConfigDraftUnavailable(p, row.key) - ui.Row(k).Shrink(1).MinWidth(0).Items(ui.Center).Gap(c.Theme().Metrics.GapItem).PadLeft(treeChevron).Children(func() { + ui.Row(c.KeyInt(i)).Shrink(1).MinWidth(0).Items(ui.Center).Gap(c.Theme().Metrics.GapItem).PadLeft(treeChevron).Children(func() { icon, color := a.runConfigDraftIcon(p, row.key), a.colors.Subtle if unavailable != "" { icon, color = icons.CircleAlert, a.colors.Warning } - ui.Icon(k, icon).Size(treelist.Icon, treelist.Icon).Shrink(0).Color(color) - ui.Text(k, a.runConfigDraftLabel(p, row.key)).FontSize(treeFontSize).Color(a.colors.Text).Shrink(1).MinWidth(0).Ellipsis() + ui.Icon(c, icon).Size(treelist.Icon, treelist.Icon).Shrink(0).Color(color) + ui.Text(c, a.runConfigDraftLabel(p, row.key)).FontSize(treeFontSize).Color(a.colors.Text).Shrink(1).MinWidth(0).Ellipsis() }) } @@ -421,7 +423,7 @@ func (a *App) drawRunConfigDialogEmptyTree(c ui.C, p *project) { if link.Clicked() { c.After(func() { d.toggleNewMenu(runConfigNewMenuTree) }) } - a.drawRunConfigNewMenu(c.Part("add-menu"), p, link, runConfigNewMenuTree) + a.drawRunConfigNewMenu(c, p, link, runConfigNewMenuTree) modifiers, key := runConfigAddChord() if chord, ok := keymap.Parse(modifiers, key); ok { ui.Text(c, shortcuts.Keycaps(chord)).Color(a.colors.Subtle) @@ -454,7 +456,7 @@ func (a *App) drawRunConfigDialogPane(c ui.C, p *project) { a.drawRunConfigDraft(k, p, draft) } if d.failure != "" { - ui.Paragraph(k, d.failure, 4).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) + ui.Paragraph(c, d.failure, 4).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) } }) }) @@ -504,7 +506,7 @@ func (a *App) drawRunConfigFolderPane(c ui.C, p *project) { c.After(func() { a.renameRunConfigFolder(p) }) } if d.folderError != "" { - ui.Text(k, d.folderError).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) + ui.Text(c, d.folderError).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) } }) ui.Paragraph(c, i18n.Shared(language, "desktop.runConfig.folderHint"), 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) @@ -556,7 +558,7 @@ func (a *App) drawRunConfigDialogStart(c ui.C, p *project) { if link.Clicked() { c.After(func() { d.toggleNewMenu(runConfigNewMenuPane) }) } - a.drawRunConfigNewMenu(c.Part("add-menu"), p, link, runConfigNewMenuPane) + a.drawRunConfigNewMenu(c, p, link, runConfigNewMenuPane) ui.Text(c, i18n.Shared(language, "desktop.runConfig.orSelectToEdit")).Color(a.colors.Subtle) if d.failure != "" { ui.Paragraph(c, d.failure, 4).TextCenter().FillWidth().FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) @@ -569,8 +571,8 @@ func (a *App) drawRunConfigDialogStart(c ui.C, p *project) { func (a *App) drawRunConfigDialogBanner(c ui.C, text string) { k := c.Part("banner") ui.Row(k).FillWidth().Items(ui.Start).Gap(8).Pad(8).Radius(a.theme.Metrics.RadiusItem()).Border(1, a.colors.Warning).Children(func() { - ui.Icon(k, icons.CircleAlert).Size(14, 14).Shrink(0).Color(a.colors.Warning) - ui.Paragraph(k, text, 4).FontSize(a.theme.Metrics.FontSizeS).Grow(1).MinWidth(0) + ui.Icon(c, icons.CircleAlert).Size(14, 14).Shrink(0).Color(a.colors.Warning) + ui.Paragraph(c, text, 4).FontSize(a.theme.Metrics.FontSizeS).Grow(1).MinWidth(0) }) } diff --git a/desktop/internal/workbench/runconfig_steps.go b/desktop/internal/workbench/runconfig_steps.go index 9ce0d98913..ceb1a322b7 100644 --- a/desktop/internal/workbench/runconfig_steps.go +++ b/desktop/internal/workbench/runconfig_steps.go @@ -187,8 +187,8 @@ func (a *App) drawRunConfigStepsTitle(c ui.C, steps *runConfigSteps, title, help fold := ui.Row(k).Shrink(0).Items(ui.Center).Gap(4). HitWith(ui.ID(k), name+" "+title, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Expandable: true, Expanded: open}) fold.Children(func() { - ui.Icon(k, chevron).Size(12, 12).Shrink(0).Color(a.colors.Subtle) - ui.Text(k, title).Shrink(0) + ui.Icon(c, chevron).Size(12, 12).Shrink(0).Color(a.colors.Subtle) + ui.Text(c, title).Shrink(0) }) if fold.Clicked() { c.After(func() { steps.collapsed = !steps.collapsed }) @@ -339,7 +339,7 @@ func (a *App) drawRunConfigStepRow(row ui.ListRow, step runConfigStepRow, select ui.Icon(c, step.icon).Size(14, 14).Shrink(0).Color(a.colors.Subtle) ui.Text(c, step.name).Color(color).Ellipsis().Shrink(1).MinWidth(0) if step.summary != "" { - ui.Text(c.Part("summary"), step.summary).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) + ui.Text(c, step.summary).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) } }) } @@ -540,7 +540,7 @@ func (a *App) drawRunConfigTask(c ui.C, p *project) { ui.Column(k).FillWidth().Gap(10).Children(func() { a.drawRunConfigFormFields(k, p, t.form, !t.checking) if t.failure != "" { - ui.Paragraph(k.Part("failure"), t.failure, 4).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) + ui.Paragraph(c, t.failure, 4).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) } }) }, func() { diff --git a/desktop/internal/workbench/runconfig_view.go b/desktop/internal/workbench/runconfig_view.go index 41fa4b9ce4..f3e7e48795 100644 --- a/desktop/internal/workbench/runconfig_view.go +++ b/desktop/internal/workbench/runconfig_view.go @@ -34,12 +34,12 @@ func (a *App) runConfigList(c ui.C, p *project) { ui.Row(k.Part("empty")).Height(panelHeaderHeight).FillWidth().Items(ui.Center).PadX(8).Children(func() { switch { case s.failure != "": - ui.Text(k, i18n.SharedFormat(language, "desktop.runConfig.loadFailed", map[string]string{"reason": s.failure})). + ui.Text(c, i18n.SharedFormat(language, "desktop.runConfig.loadFailed", map[string]string{"reason": s.failure})). FontSize(small).Color(a.colors.Warning).Ellipsis().Grow(1).MinWidth(0) case s.loading: - ui.Text(k, i18n.Shared(language, "native.loading")).FontSize(small).Color(a.colors.Subtle).Ellipsis().Grow(1).MinWidth(0) + ui.Text(c, i18n.Shared(language, "native.loading")).FontSize(small).Color(a.colors.Subtle).Ellipsis().Grow(1).MinWidth(0) default: - ui.Text(k, i18n.Shared(language, "desktop.runConfig.emptyHint")).FontSize(small).Color(a.colors.Subtle).Ellipsis().Grow(1).MinWidth(0) + ui.Text(c, i18n.Shared(language, "desktop.runConfig.emptyHint")).FontSize(small).Color(a.colors.Subtle).Ellipsis().Grow(1).MinWidth(0) } }) }) @@ -244,7 +244,7 @@ func (a *App) drawRunConfigGroupArrow(c ui.C, s *runConfigState, group runConfig slot := ui.Row(k).Size(treelist.Disclosure, treelist.Icon).Shrink(0).Center(). HitWith(ui.ID(k), name+" "+group.title, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Expandable: true, Expanded: open, SkipFocus: true}) slot.Children(func() { - ui.Icon(k, chevron).Size(12, 12).Color(a.colors.Subtle) + ui.Icon(c, chevron).Size(12, 12).Color(a.colors.Subtle) }) if slot.Clicked() { key := group.key @@ -335,7 +335,7 @@ func (a *App) drawRunConfigEditorPane(c ui.C, p *project, e *runConfigEditor) { FillWidth().Disabled(!ready) } for index := range e.optionFields { - a.drawRunOptionField(c.Part("option-"+strconv.Itoa(index)), language, &e.optionFields[index], ready) + a.drawRunOptionField(c, index, language, &e.optionFields[index], ready) } } labels := map[string]string{"local": i18n.Shared(language, "desktop.runConfig.scopeLocal"), "project": i18n.Shared(language, "desktop.runConfig.scopeProject")} @@ -365,16 +365,17 @@ func indexRange(n int) []int { // drawRunOptionField declares one declared option: a checkbox, a picker, a text field or a list of // checkboxes by its kind. A kind the editor cannot edit shows its stored JSON read-only. -func (a *App) drawRunOptionField(c ui.C, language i18n.Language, field *runOptionField, ready bool) { +func (a *App) drawRunOptionField(c ui.C, index int, language i18n.Language, field *runOptionField, ready bool) { + name := "option-" + strconv.Itoa(index) switch field.kind { case "boolean": - ui.Row(c).FillWidth().Items(ui.Center).Gap(4).Children(func() { + ui.Row(c.Part(name)).FillWidth().Items(ui.Center).Gap(4).Children(func() { ui.Checkbox(c, &field.flag, field.title).Disabled(!ready) a.drawRunOptionHelp(c, field.description) }) case "singleSelect": values, labels := runOptionChoiceIDs(*field) - ui.Row(c).FillWidth().Items(ui.End).Gap(4).Children(func() { + ui.Row(c.Part(name)).FillWidth().Items(ui.End).Gap(4).Children(func() { ui.Select(c, &field.text, values, func(value string) string { if value == "" { return i18n.Shared(language, "desktop.runConfig.optionDefault") @@ -385,7 +386,7 @@ func (a *App) drawRunOptionField(c ui.C, language i18n.Language, field *runOptio }) case "text", "file", "directory": // A text field's label only names it to accessibility, so the option's name is a text above it. - ui.Column(c).FillWidth().Gap(6).Children(func() { + ui.Column(c.Part(name)).FillWidth().Gap(6).Children(func() { a.drawRunOptionTitle(c, field.title, field.description) ui.Row(c).FillWidth().Items(ui.Center).Gap(8).Children(func() { if field.implicit != "" { @@ -412,7 +413,7 @@ func (a *App) drawRunOptionField(c ui.C, language i18n.Language, field *runOptio case "multiSelect": // The choices are keyed inside the field's own column: c names only the next element, so // keyed as siblings of the other fields the first choice took the first field's key. - ui.Column(c).FillWidth().Gap(6).Children(func() { + ui.Column(c.Part(name)).FillWidth().Gap(6).Children(func() { a.drawRunOptionTitle(c, field.title, field.description) for index := range field.choices { title := field.choices[index].title @@ -465,7 +466,7 @@ func (a *App) drawRunConfigDelete(c ui.C, p *project) { open := true title := i18n.Shared(language, "desktop.runConfig.deleteTitle") closed := ui.ModalWith(c, &open, title, ui.ModalSpec{Width: 420}, func() { - ui.Paragraph(c.Part("run-config-delete"), i18n.SharedFormat(language, "desktop.runConfig.deleteBody", map[string]string{"name": d.name}), 4).Color(a.colors.Text) + ui.Paragraph(c, i18n.SharedFormat(language, "desktop.runConfig.deleteBody", map[string]string{"name": d.name}), 4).Color(a.colors.Text) }, func() { ui.Row(c.Part("run-config-delete-footer")).FillWidth().Items(ui.Center).Gap(8).Children(func() { ui.Spacer(c) diff --git a/desktop/internal/workbench/search_replace_view.go b/desktop/internal/workbench/search_replace_view.go index 7f37fe7164..5e1ce16625 100644 --- a/desktop/internal/workbench/search_replace_view.go +++ b/desktop/internal/workbench/search_replace_view.go @@ -134,8 +134,8 @@ func (a *App) replacePreviewFile(c ui.C, p *project, index int) { } ui.Column(c.KeyInt(i)).FillWidth().PadX(22).Children(func() { line := strconv.Itoa(match.Line) + " " - ui.Text(c.Key("before"), line+"- "+match.Before).Mono().FontSize(11.5).Color(a.theme.Danger).Ellipsis() - ui.Text(c.Key("after"), line+"+ "+match.After).Mono().FontSize(11.5).Color(a.theme.Success).Ellipsis() + ui.Text(c, line+"- "+match.Before).Mono().FontSize(11.5).Color(a.theme.Danger).Ellipsis() + ui.Text(c, line+"+ "+match.After).Mono().FontSize(11.5).Color(a.theme.Success).Ellipsis() }) } }) diff --git a/desktop/internal/workbench/signature_help.go b/desktop/internal/workbench/signature_help.go index 81f560fe04..0f7e227733 100644 --- a/desktop/internal/workbench/signature_help.go +++ b/desktop/internal/workbench/signature_help.go @@ -423,7 +423,7 @@ func (a *App) signatureHelpPopup(c ui.C, completion gfx.Rect) { if highlighted != "" { ui.Row(sc.Part("active-param")).PadX(3).PadY(1).Radius(3). Background(a.colors.Active).Shrink(0).Children(func() { - ui.Text(sc.Part("active-param-text"), highlighted).Mono().FontSize(12). + ui.Text(sc, highlighted).Mono().FontSize(12). Weight(gfx.WeightBold).Color(a.colors.Text) }) } diff --git a/desktop/internal/workbench/tabstrip.go b/desktop/internal/workbench/tabstrip.go index ab0f5ffba7..b03eb94f00 100644 --- a/desktop/internal/workbench/tabstrip.go +++ b/desktop/internal/workbench/tabstrip.go @@ -444,11 +444,11 @@ func (a *App) stripTab(c ui.C, place *groupPlace, t shownTab, current string, i } var closeButton ui.Box chip.Children(func() { - ui.Icon(k, icon).Size(terminalChipIcon, terminalChipIcon).Shrink(0).Color(a.colors.Subtle) + ui.Icon(c, icon).Size(terminalChipIcon, terminalChipIcon).Shrink(0).Color(a.colors.Subtle) if a.project.terms.bench.Group(place.id).IsPinned(member) { - ui.Icon(k.Part("pin"), icons.Pin).Size(terminalCloseIcon, terminalCloseIcon).Shrink(0).Color(a.colors.Subtle) + ui.Icon(c, icons.Pin).Size(terminalCloseIcon, terminalCloseIcon).Shrink(0).Color(a.colors.Subtle) } - text := ui.Text(k, label).Ellipsis().Grow(1) + text := ui.Text(c, label).Ellipsis().Grow(1) if selected { text.Color(a.colors.Text) } else { @@ -467,7 +467,7 @@ func (a *App) stripTab(c ui.C, place *groupPlace, t shownTab, current string, i StateFrom(closeButton).Hover(ui.Look{}.Color(a.colors.Text)) }) }) - ui.ContextMenu(k.Part("menu"), chip, a.tabMenuItems(c, place.id, t, tabs)) + ui.ContextMenu(c, chip, a.tabMenuItems(c, place.id, t, tabs)) switch { case closeButton.Clicked(): c.After(func() { a.closeTab(t) }) diff --git a/desktop/internal/workbench/terminal_menu.go b/desktop/internal/workbench/terminal_menu.go index 7310db35d1..cab4f62a98 100644 --- a/desktop/internal/workbench/terminal_menu.go +++ b/desktop/internal/workbench/terminal_menu.go @@ -9,13 +9,13 @@ import ( // terminalMenu declares the context menu of terminal t's control: copy the selection, paste // the clipboard, select everything, clear, start a new shell once the old one ended, and close // the tab, as the old client's terminal offered. -func (a *App) terminalMenu(c ui.C, name string, box ui.Box, t *terminal) { +func (a *App) terminalMenu(c ui.C, box ui.Box, t *terminal) { p := a.project if p == nil { return } lang := a.language() - ui.ContextMenu(c.Key("menu"+name), box, func(menu *ui.MenuItems) { + ui.ContextMenu(c, box, func(menu *ui.MenuItems) { menu.WidthRange(180, 260) if menu.Item(i18n.Shared(lang, "menu.copy")).Disabled(!t.view.HasSelection()).Clicked() { text := t.view.SelectionText() diff --git a/desktop/internal/workbench/vcs_view.go b/desktop/internal/workbench/vcs_view.go index e00222661e..131583fb54 100644 --- a/desktop/internal/workbench/vcs_view.go +++ b/desktop/internal/workbench/vcs_view.go @@ -602,7 +602,7 @@ func (a *App) drawVcsRollbackDialog(c ui.C, p *project, t vcsTarget) { ui.Text(c, i18n.SharedFormat(lang, "native.arg1FilesSelected", map[string]string{"arg1": strconv.Itoa(len(paths))})).Muted() break } - ui.Text(c.Key(path), path).Color(a.colors.Text).Ellipsis() + ui.Text(c, path).Color(a.colors.Text).Ellipsis() } }) }, func() { diff --git a/desktop/internal/workbench/viewer_view.go b/desktop/internal/workbench/viewer_view.go index aa9d4b9d71..441f84b78e 100644 --- a/desktop/internal/workbench/viewer_view.go +++ b/desktop/internal/workbench/viewer_view.go @@ -116,8 +116,8 @@ func (a *App) viewerHex(c ui.C, t *viewerTab) { language := a.language() ui.Scroll(c.Part("hex")).Scrollbars().Fill().PadX(12).PadY(8).Children(func() { ui.Text(c, i18n.Shared(language, "desktop.viewer.binaryHint")).FontSize(12).Color(a.colors.Subtle) - for i, line := range t.hex { - ui.Text(c.KeyInt(i), line).Mono().FontSize(12).Color(a.colors.Text) + for _, line := range t.hex { + ui.Text(c, line).Mono().FontSize(12).Color(a.colors.Text) } if t.truncated { ui.Text(c, i18n.Shared(language, "desktop.viewer.truncated")).FontSize(12).Color(a.colors.Subtle) diff --git a/desktop/internal/workbench/window_sessions.go b/desktop/internal/workbench/window_sessions.go index 7836719cbc..af06df013c 100644 --- a/desktop/internal/workbench/window_sessions.go +++ b/desktop/internal/workbench/window_sessions.go @@ -364,17 +364,17 @@ func (a *App) projectTab(c ui.C, tab *App, i, size int) { } var closeButton ui.Box chip.Children(func() { - ui.Icon(k, icons.Folder).Size(projectTabIcon, projectTabIcon).Shrink(0).Color(a.colors.Subtle) - name := ui.Text(k, p.name).Ellipsis().Shrink(0) + ui.Icon(c, icons.Folder).Size(projectTabIcon, projectTabIcon).Shrink(0).Color(a.colors.Subtle) + name := ui.Text(c, p.name).Ellipsis().Shrink(0) if shown { name.Color(a.colors.Text) } else { name.Color(a.colors.Subtle).StateFrom(chip).Hover(ui.Look{}.Color(a.colors.Text)) } if d := p.selectedDocument(p.terms.bench.FocusedGroup); d != nil && d.path != "" { - ui.Text(k.Part("file"), "· "+filepath.Base(d.path)).Color(a.colors.Subtle).Ellipsis() + ui.Text(c, "· "+filepath.Base(d.path)).Color(a.colors.Subtle).Ellipsis() } - ui.Spacer(k) + ui.Spacer(c) cc := k.Part("close") closeButton = ui.Row(cc).Size(terminalCloseSize, terminalCloseSize).Shrink(0).Center(). Radius(a.theme.Metrics.RadiusItem()). diff --git a/shared/platform-feature-matrix/features/settings-about-page.json b/shared/platform-feature-matrix/features/settings-about-page.json index 0e6d50d8ae..311e1629be 100644 --- a/shared/platform-feature-matrix/features/settings-about-page.json +++ b/shared/platform-feature-matrix/features/settings-about-page.json @@ -22,7 +22,8 @@ "desktop/internal/buildinfo/preview.go", "desktop/internal/workbench/welcome_view.go", "scripts/desktop/package-desktop.sh", - "scripts/ci/desktop-release/package-release.sh" + "scripts/ci/desktop-release/package-release.sh", + "desktop/internal/settingswindow/window_view.go" ] }, "windows": { @@ -44,11 +45,12 @@ "desktop/internal/buildinfo/preview.go", "desktop/internal/workbench/welcome_view.go", "scripts/desktop/package-desktop.sh", - "scripts/ci/desktop-release/package-release.sh" + "scripts/ci/desktop-release/package-release.sh", + "desktop/internal/settingswindow/window_view.go" ] }, "owner": "Settings", "releaseSource": "只有 Desktop Release 为 desktop-v<版本> 标签的提交打包时传 package-desktop.sh --stable(lithe_stable 构建标签),应用内显示不带“预览版”的版本号,package-release.sh 校验每个打包程序都带这个标签;desktop-AutoBuild、本地打包和 go run 都显示“<版本> 预览版”。", - "verification": "发布验收:在 macOS 和 Windows 的正式包中核对欢迎页、关于页和复制的版本信息均与对应桌面发布标签的版本号一致,且均无预览版标识;版本信息和复制内容里的 Go 运行时与 desktop/go.mod 的 toolchain 行一致;同版本的本地构建仍显示预览版。无头窗口测试覆盖:关于页排在 AI 之后、面包屑只有“关于”;预览版显示“0.7.0 预览版”;QQ 群、Issue、Rust Core 和 Viva 上游链接打开对应地址;复制成功与失败(失败时显示原因并上报);版本信息与更新卡片“已是最新”在正式版和预览版下的文字;复制内容与平台、构建、运行时的读取(打包写入的提交与时间优先,含未记录提交和时间不可读)。macOS 生成了中英文、浅色和深色的无头截图(36-settings-about,以及滚到项目卡片的 36-settings-about-projects)。运行 scripts/desktop/desktop-go.sh test -race ./internal/settingswindow ./internal/workbench -run 'TestAbout|TestUpdateLineSays|TestWelcomeTitleAndVersion'。真实窗口、Windows 实机和正式版安装包上的标识尚未验收。", + "verification": "发布验收:在 macOS 和 Windows 的正式包中核对欢迎页、关于页和复制的版本信息均与对应桌面发布标签的版本号一致,且均无预览版标识;版本信息和复制内容里的 Go 运行时与 desktop/go.mod 的 toolchain 行一致;同版本的本地构建仍显示预览版。无头窗口测试覆盖:关于页排在 AI 之后、面包屑只有“关于”;预览版显示“0.7.0 预览版”;QQ 群、Issue、Rust Core 和 Viva 上游链接打开对应地址;复制成功与失败(失败时显示原因并上报);版本信息与更新卡片“已是最新”在正式版和预览版下的文字;复制内容与平台、构建、运行时的读取(打包写入的提交与时间优先,含未记录提交和时间不可读)。macOS 生成了中英文、浅色和深色的无头截图(36-settings-about,以及滚到项目卡片的 36-settings-about-projects)。运行 scripts/desktop/desktop-go.sh test -race ./internal/settingswindow ./internal/workbench -run 'TestAbout|TestUpdateLineSays|TestWelcomeTitleAndVersion'。真实窗口、Windows 实机和正式版安装包上的标识尚未验收。 Viva 开发模式下用 TestAboutPageShowsThePreviewAndCopiesTheFacts 核对设置面包屑、关于页和复制动作。静态文字不接收控件身份。", "notes": "Viva 设置侧栏在 AI 之后增加一级页面“关于”:顶部是图标、名称、简介和复制按钮(复制版本、平台、构建与运行时,用于提交 Issue);“版本信息”显示版本、平台、构建(提交与日期)和 Go 运行时;“更新”是完整的更新设置:自动检查更新、更新渠道、发布源(保存与恢复默认)和立即检查,不再重复当前版本与构建;“加入交流”有 QQ 群 163027877 与微信群(飞书页面);“项目”有源码仓库、Issue、Rust Core(Lithe-IDEA/Lithe-core-rust)和 Viva 上游(vivaui/viva,图标是 Viva 标志,由 generate-desktop-icons.sh 从固定版本的 Viva 源码编译)。不显示 Core C ABI 版本。版本号来自 desktop/viva.toml;Go 运行时是 runtime.Version(),即构建所用的工具链,CI 的 setup-go 按 desktop/go.mod 的 toolchain 行安装;欢迎页、关于页和复制内容都按同一规则显示正式版或预览版。2026-11-18:外观与行为下的独立“更新”页删除,更新设置整体迁入关于页。" } diff --git a/shared/platform-feature-matrix/features/workbench-tool-stripe-icons.json b/shared/platform-feature-matrix/features/workbench-tool-stripe-icons.json index 020e734f45..3dce5e8c14 100644 --- a/shared/platform-feature-matrix/features/workbench-tool-stripe-icons.json +++ b/shared/platform-feature-matrix/features/workbench-tool-stripe-icons.json @@ -5,7 +5,7 @@ "capability": "工具窗口栏使用 IntelliJ New UI 的工具窗口图标和尺寸", "owner": "Workbench", "notes": "Viva 共享实现。项目、提交、结构、查找、Git、终端、问题、运行、调试、构建、通知、服务使用 IntelliJ Community(Apache-2.0,修订 c7f91397daa3a961b4e78bc634fe467a0a7d9ade)的 20×20 New UI 工具窗口图标,许可见 desktop/internal/toolicons/NOTICE;IDEA 没有对应图标的入口(引用、测试、安全、背景)和隐藏入口列表的“…”使用 Lucide 图标,描边减到 1.8 以接近 IDEA 的线宽;插件声明的通用工具图标名映射到同一套图标。icons.go 由 scripts/desktop/generate-desktop-file-icons.sh --tools-only 从 SVG 生成,运行时不读写文件。尺寸:40pt 工具栏、30pt 按钮、20pt 图标、10pt 间距。", - "verification": "打开工作区,对照 IntelliJ IDEA New UI 检查左右工具窗口栏:图标形状和大小一致,选中按钮为主题主色圆角底配反色图标;拖动按钮时拖动预览里的图标居中,插入线落在两个按钮正中。浅色和深色主题各看一次。自动化:stripe_test.go 的 TestToolStripeButtonsHaveTheToolWindowBarSizes。", + "verification": "打开工作区,对照 IntelliJ IDEA New UI 检查左右工具窗口栏:图标形状和大小一致,选中按钮为主题主色圆角底配反色图标;拖动按钮时拖动预览里的图标居中,插入线落在两个按钮正中。浅色和深色主题各看一次。自动化:stripe_test.go 的 TestToolStripeButtonsHaveTheToolWindowBarSizes。 Viva 开发模式下用 TestWorkbenchDefaultLayout 和 TestStripeButtonMenuMovesTheButtonWithinItsZone 核对工具栏布局和菜单动作。菜单沿用触发控件的身份,弹性占位保留原布局。", "macos": { "implementationStatus": "implemented", "verificationStatus": "pending", From 27c31af7e3e015abb250c011912042f93d275961 Mon Sep 17 00:00:00 2001 From: Mucheen <145200703+Mucheen@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:19:17 +0800 Subject: [PATCH 5/5] fix(marketplace): serialize shared plugin archive cache writes Reuse the native file lock for pruning, temporary copy and atomic publish. Limit acquisition to one second because a completed download can install without caching. Add a deterministic two-process regression for both limits and test update delivery when the cache lock is unavailable. --- .../feature/2026-11-18-plugin-auto-updates.md | 4 + desktop/internal/marketplace/archive_cache.go | 29 ++- .../marketplace/archive_cache_test.go | 191 ++++++++++++++++++ desktop/internal/marketplace/delta_test.go | 15 +- docs/ci-builds.md | 2 + .../features/plugin-auto-update.json | 4 +- 6 files changed, 232 insertions(+), 13 deletions(-) create mode 100644 desktop/internal/marketplace/archive_cache_test.go 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 ddb32050fa..1b3c91e1f8 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 @@ -25,6 +25,8 @@ 市场可在同一索引提交发布独立的补丁索引。旧客户端仍能读取主索引,新客户端先确定完整包,再看是否有与原审批中的旧包摘要匹配的补丁。用 Zstandard(zstd)将旧的原始 ZIP 作为参考,在平台临时目录重建目标 ZIP,并验证旧包、补丁和目标包的 SHA-256。缺少可用基线或重建失败时走完整包,取消会结束下载并清理临时数据。下载完成的 ZIP 可在用户缓存保留,以便后续生成精确基线。 +桌面进程共享 ZIP 缓存。写入方从检查容量、淘汰旧归档到发布新归档持有同一把原生锁,避免两个进程按同一份旧容量各自写入。获取锁最多等待一秒。锁不可用时记录失败,已下载的包仍可用于本次安装。 + 同一进程内使用同一个插件数据根的工作台共享更新轮次。手动安装和后台暂存在提交阶段争用同一个插件安装入口。后台将包与审批一起准备完成后再提交到待激活目录。下次启动 Lithe 进程时在后台验包,读取启动项目和插件语言清单前复核原版本和审批,只有仍然符合的包才进入已安装目录。例如后台暂存 2.0.0 后再禁用 1.0.0,重启时丢弃待更新包。运行中的会话读取的仍是旧目录。 不同进程共享插件数据根。激活、手动安装、后台暂存、禁用和卸载使用同一个原生文件锁。卸载先取消并等待进程内的安装任务,再加锁让 Core 读取安装快照。这样即使另一个窗口刚刚激活新版,卸载计划也会包含它。锁文件保留在可写的插件数据根,进程退出时由操作系统释放锁。 @@ -47,6 +49,7 @@ - `./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`。 - 在合成插件市场的自动更新场景,观察安装文件、批准记录、运行中的旧进程和重启后新版本;拒绝案例不得提交任何安装。 @@ -60,4 +63,5 @@ - `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/marketplace/archive_cache.go b/desktop/internal/marketplace/archive_cache.go index 39d5caae1a..ff2aa7c85e 100644 --- a/desktop/internal/marketplace/archive_cache.go +++ b/desktop/internal/marketplace/archive_cache.go @@ -11,8 +11,9 @@ import ( "path/filepath" "sort" "strings" - "sync" "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/filelock" ) const ( @@ -20,11 +21,11 @@ const ( maxDeltaZIPBytes = 64 << 20 archiveCacheBudget = 256 << 20 archiveCacheEntries = 128 + archiveCacheLockFile = ".archive-cache.lock" + archiveCacheLockWait = time.Second cacheStagingLifetime = 24 * time.Hour ) -var archiveCacheMu sync.Mutex - // 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 } @@ -67,7 +68,7 @@ func (c ArchiveCache) base(digest string) (string, error) { return path, nil } -func (c ArchiveCache) remember(ctx context.Context, digest string, archive *DownloadedArchive) error { +func (c ArchiveCache) remember(ctx context.Context, digest string, archive *DownloadedArchive) (err error) { target, err := c.path(digest) if err != nil { return err @@ -76,7 +77,7 @@ func (c ArchiveCache) remember(ctx context.Context, digest string, archive *Down if err != nil { return err } - defer source.Close() + defer func() { err = errors.Join(err, source.Close()) }() info, err := source.Stat() if err != nil { return err @@ -84,8 +85,6 @@ func (c ArchiveCache) remember(ctx context.Context, digest string, archive *Down if info.Size() > maxDeltaZIPBytes { return nil } - archiveCacheMu.Lock() - defer archiveCacheMu.Unlock() if err := ctx.Err(); err != nil { return err } @@ -96,6 +95,16 @@ func (c ArchiveCache) remember(ctx context.Context, digest string, archive *Down } 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 } @@ -156,7 +165,7 @@ func (c ArchiveCache) prune(incoming int64, target string) error { continue } info, err := entry.Info() - // log-exempt: 预期的缺失:另一个进程可能已淘汰此归档。 + // log-exempt: 预期的缺失:系统可能已清理此缓存文件。 if errors.Is(err, fs.ErrNotExist) { continue } @@ -164,7 +173,7 @@ func (c ArchiveCache) prune(incoming int64, target string) error { return err } if incomingTemp { - // log-exempt: 预期的缺失:另一进程可能刚完成或清理临时文件。 + // 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 @@ -185,7 +194,7 @@ func (c ArchiveCache) prune(incoming int64, target string) error { if incoming <= archiveCacheBudget && len(archives)-i < archiveCacheEntries { break } - // log-exempt: 预期的缺失:另一个进程可能已淘汰此归档。 + // log-exempt: 预期的缺失:系统可能已清理此缓存文件。 if err := os.Remove(filepath.Join(c.directory, archive.name)); err != nil && !errors.Is(err, fs.ErrNotExist) { return err } diff --git a/desktop/internal/marketplace/archive_cache_test.go b/desktop/internal/marketplace/archive_cache_test.go new file mode 100644 index 0000000000..e9aacdc580 --- /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_test.go b/desktop/internal/marketplace/delta_test.go index 08feea13a3..787718e2cc 100644 --- a/desktop/internal/marketplace/delta_test.go +++ b/desktop/internal/marketplace/delta_test.go @@ -10,6 +10,7 @@ import ( "io" "net/http" "os" + "path/filepath" "strings" "testing" "time" @@ -41,7 +42,7 @@ func deltaFixture(t *testing.T) (base, target, patch []byte) { } func TestMarketplaceDeltaTransport(t *testing.T) { - for _, scenario := range []string{"exact", "no base", "corrupt base", "corrupt patch", "wrong output", "no companion", "cancel"} { + 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) }) @@ -102,6 +103,11 @@ func verifyMarketplaceDelta(t *testing.T, cache ArchiveCache, scenario string) { 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 } @@ -168,12 +174,17 @@ func verifyMarketplaceDelta(t *testing.T, cache ArchiveCache, scenario string) { 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) } } - if cached, err := cache.base(delta.ToSHA256); cached == "" || err != nil { + 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 { diff --git a/docs/ci-builds.md b/docs/ci-builds.md index fb7f74ed1a..2ae502d8cd 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -74,6 +74,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 插件市场的增量基线存放在 `/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 清理,不进入发行包。 diff --git a/shared/platform-feature-matrix/features/plugin-auto-update.json b/shared/platform-feature-matrix/features/plugin-auto-update.json index 3889ddbcda..f168802645 100644 --- a/shared/platform-feature-matrix/features/plugin-auto-update.json +++ b/shared/platform-feature-matrix/features/plugin-auto-update.json @@ -5,7 +5,7 @@ "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 真实原生测试及无头截图待执行。增量运输测试覆盖精确匹配、缺失索引或基线、损坏补丁或基线、目标重建不一致和取消;安装包只读用例使用实际用户缓存路径。后台验证覆盖重启激活以及在重启前禁用后放弃待更新包。双进程测试覆盖发布期间卸载等待、重试后移除新旧版本及发行包目录只读。", + "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", @@ -21,6 +21,7 @@ "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" ] @@ -40,6 +41,7 @@ "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" ]