diff --git a/desktop/internal/core/marketplace.go b/desktop/internal/core/marketplace.go index 6bd788b55..5bd30270a 100644 --- a/desktop/internal/core/marketplace.go +++ b/desktop/internal/core/marketplace.go @@ -24,11 +24,12 @@ type MarketplaceRejection struct { func (r *MarketplaceRejection) Error() string { return fmt.Sprintf("%s: %s", r.Code, r.Message) } type marketplaceOutcome struct { - Status string `json:"status"` - Error *MarketplaceRejection `json:"error"` - Index *MarketplaceIndex `json:"index"` - Source *MarketplaceSource `json:"source"` - Review *MarketplaceReview `json:"review"` + Status string `json:"status"` + Error *MarketplaceRejection `json:"error"` + Index *MarketplaceIndex `json:"index"` + Source *MarketplaceSource `json:"source"` + Review *MarketplaceReview `json:"review"` + Recommendation *MarketplaceRecommendationResult `json:"recommendation"` } func (o marketplaceOutcome) failure(command string) error { @@ -43,9 +44,10 @@ func (o marketplaceOutcome) failure(command string) error { // MarketplaceSource is Core's canonical index location and its optional repository. type MarketplaceSource struct { - IndexURL string `json:"indexURL"` - Repository *string `json:"repository"` - DisplayName string `json:"displayName"` + IndexURL string `json:"indexURL"` + RecommendationsURL string `json:"recommendationsURL"` + Repository *string `json:"repository"` + DisplayName string `json:"displayName"` } // MarketplaceAvailability is Core's platform and capability decision. @@ -177,3 +179,81 @@ func (c *Client) ReviewMarketplaceInstall(ctx context.Context, manifest json.Raw } return *result.Review, nil } + +// MarketplaceRecommendationCatalog pairs one marketplace index with its companion recommendations catalog. +type MarketplaceRecommendationCatalog struct { + Index json.RawMessage `json:"index"` + SourceKind MarketplaceSourceKind `json:"sourceKind"` + IndexURL string `json:"indexURL,omitempty"` + Recommendations json.RawMessage `json:"recommendations"` +} + +// MarketplaceRecommendation is one validated plugin recommendation matched against the workspace. +type MarketplaceRecommendation struct { + Plugin MarketplacePlugin `json:"plugin"` + MatchedMarkers []string `json:"matchedMarkers"` + MatchedExtensions []string `json:"matchedExtensions"` + MarketplaceIndexURL string `json:"marketplaceIndexURL,omitempty"` +} + +// MarketplaceRecommendationResult holds accepted recommendations and isolated catalog/entry rejections. +type MarketplaceRecommendationResult struct { + Plugins []MarketplaceRecommendation `json:"plugins"` + Rejected []MarketplaceEntryRejection `json:"rejected"` +} + +// RecommendMarketplacePlugins asks Core to match workspace signals against recommendation catalogs. +func (c *Client) RecommendMarketplacePlugins( + ctx context.Context, + platform string, + workspaceFiles []string, + catalogs []MarketplaceRecommendationCatalog, + hostCapabilities map[string][]int, + installedPluginIDs []string, + dismissedPluginIDs []string, +) (MarketplaceRecommendationResult, error) { + const command = "plugins.marketplace.recommendForWorkspace" + if workspaceFiles == nil { + workspaceFiles = []string{} + } + if catalogs == nil { + catalogs = []MarketplaceRecommendationCatalog{} + } + if installedPluginIDs == nil { + installedPluginIDs = []string{} + } + if dismissedPluginIDs == nil { + dismissedPluginIDs = []string{} + } + request := struct { + Platform string `json:"platform"` + WorkspaceFiles []string `json:"workspaceFiles"` + Catalogs []MarketplaceRecommendationCatalog `json:"catalogs"` + HostCapabilities map[string][]int `json:"hostCapabilities,omitempty"` + InstalledPluginIDs []string `json:"installedPluginIDs"` + DismissedPluginIDs []string `json:"dismissedPluginIDs"` + }{ + Platform: platform, + WorkspaceFiles: workspaceFiles, + Catalogs: catalogs, + HostCapabilities: hostCapabilities, + InstalledPluginIDs: installedPluginIDs, + DismissedPluginIDs: dismissedPluginIDs, + } + var result marketplaceOutcome + if err := c.Execute(ctx, command, request, &result); err != nil { + return MarketplaceRecommendationResult{}, err + } + if err := result.failure(command); err != nil { + return MarketplaceRecommendationResult{}, err + } + if result.Recommendation == nil { + return MarketplaceRecommendationResult{}, newParseError(command, "marketplace returned no recommendations", "") + } + for i := range result.Recommendation.Plugins { + if result.Recommendation.Plugins[i].MarketplaceIndexURL != "" { + result.Recommendation.Plugins[i].Plugin.MarketplaceIndexURL = result.Recommendation.Plugins[i].MarketplaceIndexURL + } + } + return *result.Recommendation, nil +} diff --git a/desktop/internal/core/marketplace_test.go b/desktop/internal/core/marketplace_test.go index 390b3cb81..f61b6ef4f 100644 --- a/desktop/internal/core/marketplace_test.go +++ b/desktop/internal/core/marketplace_test.go @@ -2,10 +2,12 @@ package core import ( "encoding/json" - "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" "os" "path/filepath" + "slices" "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" ) // readMarketFixture uses the shared fixtures of the pinned Core contract. @@ -25,8 +27,9 @@ func TestMarketplaceSourceFixture(t *testing.T) { Cases []struct { Input string `json:"input"` Expected struct { - IndexURL string `json:"indexURL"` - DisplayName string `json:"displayName"` + IndexURL string `json:"indexURL"` + RecommendationsURL string `json:"recommendationsURL"` + DisplayName string `json:"displayName"` } `json:"expected"` ExpectedCode string `json:"expectedCode"` } `json:"cases"` @@ -43,7 +46,10 @@ func TestMarketplaceSourceFixture(t *testing.T) { } return } - if err != nil || source.IndexURL != item.Expected.IndexURL || source.DisplayName != item.Expected.DisplayName { + if err != nil || + source.IndexURL != item.Expected.IndexURL || + source.RecommendationsURL != item.Expected.RecommendationsURL || + source.DisplayName != item.Expected.DisplayName { t.Fatalf("source = %#v, error = %v", source, err) } }) @@ -136,3 +142,66 @@ func TestMarketplaceValidatesCommunityStore(t *testing.T) { } } } + +func TestMarketplaceRecommendationFixture(t *testing.T) { + var index json.RawMessage + readMarketFixture(t, "marketplace/index.json", &index) + var recommendations json.RawMessage + readMarketFixture(t, "marketplace/recommendations.json", &recommendations) + var fixture struct { + Cases []struct { + Name string `json:"name"` + SourceKind MarketplaceSourceKind `json:"sourceKind"` + Platform string `json:"platform"` + HostCapabilities map[string][]int `json:"hostCapabilities"` + WorkspaceFiles []string `json:"workspaceFiles"` + InstalledPluginIDs []string `json:"installedPluginIDs"` + DismissedPluginIDs []string `json:"dismissedPluginIDs"` + ExpectedPlugins []struct { + ID string `json:"id"` + MatchedMarkers []string `json:"matchedMarkers"` + MatchedExtensions []string `json:"matchedExtensions"` + } `json:"expectedPlugins"` + } `json:"cases"` + } + readMarketFixture(t, "marketplace/recommendations-cases.json", &fixture) + client := NewClient() + const indexURL = "https://example.com/lithe-plugin-index.json" + for _, tc := range fixture.Cases { + t.Run(tc.Name, func(t *testing.T) { + result, err := client.RecommendMarketplacePlugins( + testContext(t), + tc.Platform, + tc.WorkspaceFiles, + []MarketplaceRecommendationCatalog{{ + Index: index, + SourceKind: tc.SourceKind, + IndexURL: indexURL, + Recommendations: recommendations, + }}, + tc.HostCapabilities, + tc.InstalledPluginIDs, + tc.DismissedPluginIDs, + ) + if err != nil { + t.Fatalf("RecommendMarketplacePlugins: %v", err) + } + if len(result.Rejected) != 0 { + t.Fatalf("rejected = %#v, want empty", result.Rejected) + } + if len(result.Plugins) != len(tc.ExpectedPlugins) { + t.Fatalf("plugins = %#v, want %d entries", result.Plugins, len(tc.ExpectedPlugins)) + } + for i, got := range result.Plugins { + want := tc.ExpectedPlugins[i] + if got.Plugin.ID != want.ID || + !slices.Equal(got.MatchedMarkers, want.MatchedMarkers) || + !slices.Equal(got.MatchedExtensions, want.MatchedExtensions) || + got.MarketplaceIndexURL != indexURL || + got.Plugin.MarketplaceIndexURL != indexURL { + t.Fatalf("plugin[%d] = %#v, want %#v", i, got, want) + } + } + }) + } +} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index c4feb96d4..9a5aadfca 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1226,6 +1226,10 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.permissionRuntimesInstall": "Download and install the plugin’s declared runtime dependencies. Existing verified installations are reused across plugin updates.", "desktop.marketplace.programDetails": "Program declarations ({count}) — show / hide details", "desktop.marketplace.queryTooLong": "Search query is too long", + "desktop.marketplace.recommendedAction": "View Plugins", + "desktop.marketplace.recommendedDismiss": "Don't Show Again", + "desktop.marketplace.recommendedPlugins": "Suggested for this project: {plugins}", + "desktop.marketplace.recommendedTitle": "Recommended Plugins", "desktop.marketplace.reviewConsent": "Install only if you trust this source. Installing approves the permissions and programs declared by this package.", "desktop.marketplace.reviewEmpty": "This plugin asks for no permissions and starts no programs.", "desktop.marketplace.reviewPermissions": "Permissions", @@ -4486,6 +4490,10 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.permissionRuntimesInstall": "下载并安装插件声明的运行依赖。插件更新时会复用已有且验证合格的环境。", "desktop.marketplace.programDetails": "程序声明({count} 项)· 展开/收起详情", "desktop.marketplace.queryTooLong": "搜索内容过长", + "desktop.marketplace.recommendedAction": "查看插件", + "desktop.marketplace.recommendedDismiss": "不再提示", + "desktop.marketplace.recommendedPlugins": "检测到当前项目可能需要:{plugins}", + "desktop.marketplace.recommendedTitle": "推荐安装插件", "desktop.marketplace.reviewConsent": "请仅安装可信来源的插件。确认安装将批准这个包所声明的权限和程序。", "desktop.marketplace.reviewEmpty": "该插件不申请权限,也不启动任何程序。", "desktop.marketplace.reviewPermissions": "权限", diff --git a/desktop/internal/marketplace/service.go b/desktop/internal/marketplace/service.go index f105e2b89..2cab99d72 100644 --- a/desktop/internal/marketplace/service.go +++ b/desktop/internal/marketplace/service.go @@ -82,47 +82,102 @@ type Snapshot struct { Index core.MarketplaceIndex } +// RecommendationBundle holds a raw marketplace index and its companion workspace recommendations catalog. +type RecommendationBundle struct { + Source core.MarketplaceSource + SourceKind core.MarketplaceSourceKind + Index json.RawMessage + Recommendations json.RawMessage +} + +type httpStatusError int + +func (e httpStatusError) Error() string { + return fmt.Sprintf("marketplace HTTP status %d", int(e)) +} + // Fetch resolves a source, downloads a bounded index, and asks Core to validate it. // Caller supplies the actual host capabilities; Core alone determines availability. -func (s *Service) Fetch(ctx context.Context, input string, kind core.MarketplaceSourceKind, platform string, capabilities map[string][]int) (snapshot Snapshot, err error) { +func (s *Service) Fetch(ctx context.Context, input string, kind core.MarketplaceSourceKind, platform string, capabilities map[string][]int) (Snapshot, error) { source, err := s.core.ResolveMarketplaceSource(ctx, input) if err != nil { return Snapshot{}, err } - request, err := http.NewRequestWithContext(ctx, http.MethodGet, source.IndexURL, nil) + data, _, err := s.fetchJSON(ctx, source.IndexURL) if err != nil { return Snapshot{}, err } + index, err := s.core.ValidateMarketplaceIndex(ctx, json.RawMessage(data), kind, platform, capabilities) + if err != nil { + return Snapshot{}, err + } + for i := range index.Plugins { + index.Plugins[i].MarketplaceIndexURL = source.IndexURL + } + return Snapshot{Source: source, Index: index}, nil +} + +// FetchRecommendationBundle downloads the companion recommendations file first and returns +// ok=false without fetching the index when the marketplace publishes no recommendations (HTTP 404). +func (s *Service) FetchRecommendationBundle(ctx context.Context, input string, kind core.MarketplaceSourceKind) (RecommendationBundle, bool, error) { + source, err := s.core.ResolveMarketplaceSource(ctx, input) + if err != nil { + return RecommendationBundle{}, false, err + } + if source.RecommendationsURL == "" { + return RecommendationBundle{}, false, nil + } + recBody, _, err := s.fetchJSON(ctx, source.RecommendationsURL) + if err != nil { + if err == httpStatusError(http.StatusNotFound) { + return RecommendationBundle{}, false, nil + } + return RecommendationBundle{}, false, err + } + indexBody, _, err := s.fetchJSON(ctx, source.IndexURL) + if err != nil { + return RecommendationBundle{}, false, err + } + return RecommendationBundle{ + Source: source, + SourceKind: kind, + Index: json.RawMessage(indexBody), + Recommendations: json.RawMessage(recBody), + }, true, nil +} + +func (s *Service) fetchJSON(ctx context.Context, rawURL string) (data []byte, status int, err error) { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, 0, err + } if !strings.EqualFold(request.URL.Scheme, "https") || request.URL.Host == "" || request.URL.User != nil { - return Snapshot{}, ErrUnsafeRedirect + return nil, 0, ErrUnsafeRedirect } response, err := s.http.Do(request) if err != nil { - return Snapshot{}, err + return nil, 0, err } - defer func() { err = errors.Join(err, response.Body.Close()) }() + defer func() { + if closeErr := response.Body.Close(); closeErr != nil { + err = errors.Join(err, closeErr) + } + }() if response.StatusCode < 200 || response.StatusCode >= 300 { - return Snapshot{}, fmt.Errorf("marketplace HTTP status %d", response.StatusCode) + return nil, response.StatusCode, httpStatusError(response.StatusCode) } if response.ContentLength > MaxIndexBytes { - return Snapshot{}, ErrIndexTooLarge + return nil, response.StatusCode, ErrIndexTooLarge } - data, err := io.ReadAll(io.LimitReader(response.Body, MaxIndexBytes+1)) + data, err = io.ReadAll(io.LimitReader(response.Body, MaxIndexBytes+1)) if err != nil { - return Snapshot{}, err + return nil, response.StatusCode, err } if len(data) > MaxIndexBytes { - return Snapshot{}, ErrIndexTooLarge + return nil, response.StatusCode, ErrIndexTooLarge } if !json.Valid(data) { - return Snapshot{}, ErrInvalidJSON - } - index, err := s.core.ValidateMarketplaceIndex(ctx, json.RawMessage(data), kind, platform, capabilities) - if err != nil { - return Snapshot{}, err + return nil, response.StatusCode, ErrInvalidJSON } - for i := range index.Plugins { - index.Plugins[i].MarketplaceIndexURL = source.IndexURL - } - return Snapshot{Source: source, Index: index}, nil + return data, response.StatusCode, nil } diff --git a/desktop/internal/marketplace/service_test.go b/desktop/internal/marketplace/service_test.go index e54ae90c0..88e392008 100644 --- a/desktop/internal/marketplace/service_test.go +++ b/desktop/internal/marketplace/service_test.go @@ -195,3 +195,77 @@ func TestFetchStopsWhenRequestIsCancelled(t *testing.T) { t.Fatalf("error = %v, want context cancellation", err) } } + +func TestFetchRecommendationBundle(t *testing.T) { + index, err := os.ReadFile(contractfixture.Path("fixtures/marketplace/index.json")) + if err != nil { + t.Fatal(err) + } + recommendations, err := os.ReadFile(contractfixture.Path("fixtures/marketplace/recommendations.json")) + if err != nil { + t.Fatal(err) + } + + t.Run("downloads companion recommendations and index", func(t *testing.T) { + var requested []string + client := &http.Client{Transport: transportFunc(func(r *http.Request) (*http.Response, error) { + requested = append(requested, r.URL.String()) + switch r.URL.String() { + case "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json": + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(recommendations))), Request: r}, nil + case "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json": + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(index))), Request: r}, nil + default: + return &http.Response{StatusCode: 404, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("")), Request: r}, nil + } + })} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + bundle, ok, fetchErr := New(core.NewClient(), client).FetchRecommendationBundle(ctx, "https://github.com/example/lithe-plugins", core.MarketplaceThirdParty) + if fetchErr != nil || !ok { + t.Fatalf("FetchRecommendationBundle = (%v, %v)", ok, fetchErr) + } + if len(requested) != 2 || len(bundle.Recommendations) == 0 || len(bundle.Index) == 0 { + t.Fatalf("requested = %v, bundle sizes = (%d, %d)", requested, len(bundle.Recommendations), len(bundle.Index)) + } + }) + + t.Run("skips silently on 404 recommendations without fetching index", func(t *testing.T) { + var requested []string + client := &http.Client{Transport: transportFunc(func(r *http.Request) (*http.Response, error) { + requested = append(requested, r.URL.String()) + return &http.Response{StatusCode: 404, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("")), Request: r}, nil + })} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, ok, fetchErr := New(core.NewClient(), client).FetchRecommendationBundle(ctx, "https://github.com/example/lithe-plugins", core.MarketplaceThirdParty) + if fetchErr != nil || ok { + t.Fatalf("FetchRecommendationBundle on 404 = (%v, %v), want (false, nil)", ok, fetchErr) + } + if len(requested) != 1 || !strings.HasSuffix(requested[0], "/lithe-plugin-recommendations.json") { + t.Fatalf("requested = %v, expected only recommendations URL", requested) + } + }) + + t.Run("rejects invalid JSON or oversized recommendations", func(t *testing.T) { + for _, tc := range []struct { + name, body string + want error + }{ + {"invalid", "not-json", ErrInvalidJSON}, + {"oversized", strings.Repeat("x", MaxIndexBytes+1), ErrIndexTooLarge}, + } { + t.Run(tc.name, func(t *testing.T) { + client := &http.Client{Transport: transportFunc(func(r *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(tc.body)), Request: r}, nil + })} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, _, fetchErr := New(core.NewClient(), client).FetchRecommendationBundle(ctx, "https://plugins.example.com/index.json", core.MarketplaceThirdParty) + if !errors.Is(fetchErr, tc.want) { + t.Fatalf("error = %v, want %v", fetchErr, tc.want) + } + }) + } + }) +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 2877cf947..006c5ecfe 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -242,6 +242,7 @@ type Kernel interface { ReferenceLines(ctx context.Context, request core.ReferenceLinesRequest) ([]core.ReferenceLine, error) ResolveMarketplaceSource(context.Context, string) (core.MarketplaceSource, error) ValidateMarketplaceIndex(context.Context, json.RawMessage, core.MarketplaceSourceKind, string, map[string][]int) (core.MarketplaceIndex, error) + RecommendMarketplacePlugins(ctx context.Context, platform string, workspaceFiles []string, catalogs []core.MarketplaceRecommendationCatalog, hostCapabilities map[string][]int, installedPluginIDs []string, dismissedPluginIDs []string) (core.MarketplaceRecommendationResult, error) } // Options configure a window. @@ -284,6 +285,11 @@ type Options struct { // instrumented test binary raise it so scheduler load cannot masquerade as // a provider failure. PluginInitializeTimeout time.Duration + // DisablePluginRecommendations suppresses background workspace plugin detection when + // opening a project (used by default in test harnesses unless a fetcher is supplied). + DisablePluginRecommendations bool + // PluginRecommendationFetcher overrides marketplace recommendation catalog fetches in tests. + PluginRecommendationFetcher func(ctx context.Context, sources []PluginRecommendationSource) ([]core.MarketplaceRecommendationCatalog, error) // first is the window's first workbench when this one is another project tab of its // window; nil for the first (window_sessions.go). first *App @@ -335,6 +341,8 @@ type settings struct { MarketplaceSources []string `json:"marketplaceSources,omitempty"` // AutoUpdatePlugins lets approved marketplace plugins update with unchanged grants. AutoUpdatePlugins bool `json:"autoUpdatePlugins,omitempty"` + // DismissedPluginRecommendations lists plugin IDs the user dismissed from workspace prompts. + DismissedPluginRecommendations []string `json:"dismissedPluginRecommendations,omitempty"` // HideMinimap hides the minimap of every editor; the editors show it by default. HideMinimap bool `json:"hideMinimap,omitempty"` // HideGitGutter hides the Git change markers of the editor gutter; they show by default. @@ -614,8 +622,11 @@ type App struct { shownTitle string // updates is the update check, download and install, which every tab of the window // shares (updates.go). - updates *updater - pluginAuto *pluginAutoUpdater + updates *updater + pluginAuto *pluginAutoUpdater + pluginRecommendations *pluginRecommendationState + disableRecommendations bool + recommendationFetcher func(ctx context.Context, sources []PluginRecommendationSource) ([]core.MarketplaceRecommendationCatalog, error) tasks taskQueue // languages are the languages the editor knows, made when the first file is opened. languages *syntax.Registry @@ -923,12 +934,16 @@ func New(options Options) *App { a.logSink, a.logs = first.logSink, first.logs a.updates = first.updates a.pluginAuto = first.pluginAuto + a.pluginRecommendations = first.pluginRecommendations } else { a.sessions = newWindowSessions(a, options) a.updates = newUpdater(a.settings) a.pluginAuto = &pluginAutoUpdater{enabled: a.settings.AutoUpdatePlugins} + a.pluginRecommendations = newPluginRecommendationState() a.invalidator = windowWake{invalidator: new(app.Invalidator)} } + a.disableRecommendations = options.DisablePluginRecommendations + a.recommendationFetcher = options.PluginRecommendationFetcher if options.Logs != nil && options.first == nil { a.logSink = options.Logs version := options.Version @@ -1606,6 +1621,7 @@ func (a *App) openProjectWithTrust(root string, trusted bool) { // a model runs the plugin's model command, such as mvn, which runs the project's build // extensions, so in safe mode the models stay unloaded until the user trusts the project. a.loadTitleRunConfigs(p) + a.checkPluginRecommendations(p) a.restoreEditorSession(p) a.restoreCheckpoints(p) a.openPendingFiles(p) diff --git a/desktop/internal/workbench/app_test.go b/desktop/internal/workbench/app_test.go index 5663cb929..5215841d5 100644 --- a/desktop/internal/workbench/app_test.go +++ b/desktop/internal/workbench/app_test.go @@ -102,6 +102,9 @@ func newHarnessWithDriver(t testing.TB, options Options, open func(app.Config) ( // Tests open their folders trusted, as IDEA's unit-test mode does; the trust flow's own tests // clear it before they open one. options.trustEveryWorkspace = true + if options.PluginRecommendationFetcher == nil && !options.DisablePluginRecommendations { + options.DisablePluginRecommendations = true + } h.app = New(options) h.config = h.app.Config() driver, closeDriver, err := open(h.config) diff --git a/desktop/internal/workbench/notifications.go b/desktop/internal/workbench/notifications.go index 1482ac328..109689d86 100644 --- a/desktop/internal/workbench/notifications.go +++ b/desktop/internal/workbench/notifications.go @@ -24,9 +24,10 @@ const ( // notification is one notice of the history. Notices with the same text and kind are one // entry that counts how often it came. type notification struct { - id int - text string - kind ui.ToastKind + id int + text string + detail string + kind ui.ToastKind count int // at is when it came last. at time.Time @@ -39,9 +40,11 @@ type notification struct { // on that action's records. op string // act is what the notice's own button does, labeled actLabel, nil for a notice without - // one; it runs on the workbench the notice is on. A notice with act offers no View Logs. - act func(*App) - actLabel string + // one; it runs on the workbench the notice is on. A notice with an action offers no View Logs. + act func(*App) + actLabel string + secondaryAct func(*App) + secondaryActLabel string } // notificationCenter owns the history shared by the tool window and the status popover. @@ -110,11 +113,21 @@ func (a *App) notifyKind(message string, kind ui.ToastKind) { // notifyAction is notifyKind with a button of the notice's own, label, which runs act. A // repeat of the notice keeps the latest button. func (a *App) notifyAction(message string, kind ui.ToastKind, label string, act func(*App)) { - a.notice = message + a.notifyActions(message, "", kind, label, act, "", nil) +} + +// notifyActions is notifyKind with optional wrapped detail text and up to two notice-specific +// buttons. The floating toast shows the primary button while the notification history shows both. +func (a *App) notifyActions(title, detail string, kind ui.ToastKind, label string, act func(*App), secondaryLabel string, secondaryAct func(*App)) { + if detail != "" { + a.notice = detail + } else { + a.notice = title + } center := &a.notifications var entry *notification for i, existing := range center.list { - if existing.text == message && existing.kind == kind { + if existing.text == title && existing.detail == detail && existing.kind == kind { entry = existing center.list = append(center.list[:i], center.list[i+1:]...) a.overlay.toaster.Close(existing.toast) @@ -122,11 +135,12 @@ func (a *App) notifyAction(message string, kind ui.ToastKind, label string, act } } if entry == nil { - entry = ¬ification{text: message, kind: kind} + entry = ¬ification{text: title, detail: detail, kind: kind} } entry.count++ entry.at = a.now() entry.act, entry.actLabel = act, label + entry.secondaryAct, entry.secondaryActLabel = secondaryAct, secondaryLabel entry.unread = !center.open if kind == ui.ToastError && a.op.id != "" { entry.op = a.op.id @@ -142,7 +156,7 @@ func (a *App) notifyAction(message string, kind ui.ToastKind, label string, act case a.viewsLogs(entry): action = i18n.Shared(a.language(), "desktop.notifications.viewLogs") } - entry.toast = a.overlay.toaster.ShowAction(a.notificationText(entry), "", kind, action) + entry.toast = a.overlay.toaster.ShowAction(a.notificationText(entry), entry.detail, kind, action) if entry.id == 0 { // Keep the first toast's identity when a repeat replaces the current toast. entry.id = int(entry.toast) @@ -152,7 +166,7 @@ func (a *App) notifyAction(message string, kind ui.ToastKind, label string, act // viewsLogs says the notice offers View Logs: it refers to an action's records and there is a // log window to show them in. func (a *App) viewsLogs(entry *notification) bool { - return entry.act == nil && entry.op != "" && a.logs != nil + return entry.act == nil && entry.secondaryAct == nil && entry.op != "" && a.logs != nil } // notificationActed runs the button of the notice whose toast this paint delivered a press on: @@ -228,7 +242,13 @@ func (a *App) notificationsToolBody(c ui.C) { list := ¢er.toolList if list.Key == nil { list.Key = func(i int) int { return center.list[i].id } - list.Label = func(i int) string { return center.list[i].text } + list.Label = func(i int) string { + entry := center.list[i] + if entry.detail != "" { + return entry.text + " — " + entry.detail + } + return entry.text + } } label := i18n.Shared(a.language(), "desktop.notifications.title") ui.List(c, list, len(center.list), func(row ui.ListRow) { @@ -312,18 +332,27 @@ func (a *App) notificationRow(c ui.C, row ui.Box, entry *notification) { // often, and View Logs when it refers to an action's records. func (a *App) notificationEntry(k ui.C, entry *notification) { language := a.language() - ui.Wrap(k, entry.text).FontSize(a.theme.Metrics.FontSizeS) + 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) + } else { + ui.Wrap(k, entry.text).FontSize(a.theme.Metrics.FontSizeS) + } meta := entry.at.Format("15:04:05") if entry.count > 1 { meta = i18n.SharedFormat(language, "desktop.notifications.meta", map[string]string{"time": meta, "count": strconv.Itoa(entry.count)}) } ui.Row(k).FillWidth().Items(ui.Center).Gap(8).Children(func() { ui.Text(k, meta).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Grow(1).Ellipsis() - if entry.act != nil && ui.Button(k.Part("act"), entry.actLabel).Ghost().Small().Clicked() { + if entry.act != nil && ui.Button(k.Part("act"), entry.actLabel).Ghost().Small().Shrink(0).Clicked() { act := entry.act k.After(func() { a.notificationAct(act) }) } - if a.viewsLogs(entry) && ui.Button(k.Part("logs"), i18n.Shared(language, "desktop.notifications.viewLogs")).Ghost().Small().Clicked() { + if entry.secondaryAct != nil && ui.Button(k.Part("secondary"), entry.secondaryActLabel).Ghost().Small().Shrink(0).Clicked() { + act := entry.secondaryAct + k.After(func() { a.notificationAct(act) }) + } + if a.viewsLogs(entry) && ui.Button(k.Part("logs"), i18n.Shared(language, "desktop.notifications.viewLogs")).Ghost().Small().Shrink(0).Clicked() { op := entry.op k.After(func() { a.viewNotificationLogs(op) }) } diff --git a/desktop/internal/workbench/notifications_test.go b/desktop/internal/workbench/notifications_test.go index a02532e8d..5194a633b 100644 --- a/desktop/internal/workbench/notifications_test.go +++ b/desktop/internal/workbench/notifications_test.go @@ -295,3 +295,53 @@ func TestNoticesKeepTheirKindAndShowAtMostThreeToasts(t *testing.T) { t.Fatal("the welcome page has no bell") } } + +func TestNotificationSupportsPrimaryAndSecondaryActions(t *testing.T) { + h := newHarnessWithLanguages(t, &testKernel{Client: core.NewClient()}, []string{"en-US"}) + h.open(t.TempDir()) + clock := time.Date(2026, 11, 11, 10, 0, 0, 0, time.Local) + h.app.now = func() time.Time { return clock } + + var primaryCalls, secondaryCalls int + h.app.notifyActions( + "Recommended plugins", + "Suggested for this project: Demo Lang", + ui.ToastInfo, + "View Plugins", func(*App) { primaryCalls++ }, + "Don't Show Again", func(*App) { secondaryCalls++ }, + ) + h.app.invalidator.Invalidate() + h.settle() + + if len(h.app.notifications.list) != 1 { + t.Fatalf("notifications = %d, want 1", len(h.app.notifications.list)) + } + if h.pageControls("View Plugins") != 1 { + t.Fatalf("floating toast View Plugins count = %d, want 1", h.pageControls("View Plugins")) + } + h.clickNamed("View Plugins") + h.settle() + if primaryCalls != 1 { + t.Fatalf("primaryCalls = %d, want 1", primaryCalls) + } + + // Open the notification bell history where both primary and secondary actions appear. + for _, entry := range h.app.notifications.list { + h.app.overlay.toaster.Close(entry.toast) + } + h.app.invalidator.Invalidate() + h.settle() + h.clickNamed("Notifications, 1 unread") + h.settle() + if n := h.pageControls("View Plugins"); n != 1 { + t.Fatalf("history View Plugins count = %d, want 1", n) + } + if n := h.pageControls("Don't Show Again"); n != 1 { + t.Fatalf("history Don't Show Again count = %d, want 1", n) + } + h.clickNamed("Don't Show Again") + h.settle() + if secondaryCalls != 1 || h.app.notifications.open { + t.Fatalf("secondaryCalls = %d, open = %v; want 1, false", secondaryCalls, h.app.notifications.open) + } +} diff --git a/desktop/internal/workbench/plugin_auto_update.go b/desktop/internal/workbench/plugin_auto_update.go index ae1ab34f9..57dbe0334 100644 --- a/desktop/internal/workbench/plugin_auto_update.go +++ b/desktop/internal/workbench/plugin_auto_update.go @@ -128,21 +128,8 @@ func (a *App) checkPluginAutoUpdates() { } ctx, cancel := context.WithCancel(context.Background()) u.checking, u.cancel = true, cancel - sources := []pluginAutoSource{ - {marketplace.CommunityRepositoryURL, core.MarketplaceThirdParty}, - {marketplace.OfficialIndexURL, core.MarketplaceOfficial}, - } - for _, url := range a.settings.MarketplaceSources { - if len(sources) >= pluginAutoMaxSources { - break - } - sources = append(sources, pluginAutoSource{url, core.MarketplaceThirdParty}) - } - arch := runtime.GOARCH - if arch == "amd64" { - arch = "x64" - } - platform := runtime.GOOS + "-" + arch + sources := a.marketplaceSources() + platform := marketplaceHostPlatform() capabilities := pluginhost.Declared().Clone() a.background(nil, 0, func(context.Context) func(*App) { defer cancel() @@ -167,9 +154,26 @@ func (a *App) checkPluginAutoUpdates() { }) } -type pluginAutoSource struct { - input string - kind core.MarketplaceSourceKind +func (a *App) marketplaceSources() []PluginRecommendationSource { + sources := []PluginRecommendationSource{ + {Input: marketplace.CommunityRepositoryURL, Kind: core.MarketplaceThirdParty}, + {Input: marketplace.OfficialIndexURL, Kind: core.MarketplaceOfficial}, + } + for _, url := range a.settings.MarketplaceSources { + if len(sources) >= pluginAutoMaxSources { + break + } + sources = append(sources, PluginRecommendationSource{Input: url, Kind: core.MarketplaceThirdParty}) + } + return sources +} + +func marketplaceHostPlatform() string { + arch := runtime.GOARCH + if arch == "amd64" { + arch = "x64" + } + return runtime.GOOS + "-" + arch } // autoUpdateCandidates uses only Core-validated availability and release order. @@ -210,7 +214,7 @@ func approvedPluginAutoSource(indexURL string, approvals map[string]plugintrust. return false } -func (a *App) performPluginAutoUpdates(ctx context.Context, sources []pluginAutoSource, platform string, capabilities map[string][]int) (int, error) { +func (a *App) performPluginAutoUpdates(ctx context.Context, sources []PluginRecommendationSource, platform string, capabilities map[string][]int) (int, error) { entries, err := a.plugins.CurrentInstalled(ctx) if err != nil { return 0, err @@ -244,7 +248,7 @@ func (a *App) performPluginAutoUpdates(ctx context.Context, sources []pluginAuto } // Resolve sources locally before any HTTP request: only an index the // user already installed from can trigger an automatic fetch. - origin, resolveErr := a.kernel.ResolveMarketplaceSource(ctx, source.input) + origin, resolveErr := a.kernel.ResolveMarketplaceSource(ctx, source.Input) if resolveErr != nil { failures = append(failures, resolveErr) continue @@ -254,7 +258,7 @@ func (a *App) performPluginAutoUpdates(ctx context.Context, sources []pluginAuto } triedOrigins[origin.IndexURL] = true fetchCtx, end := context.WithTimeout(ctx, pluginAutoFetchLimit) - snapshot, fetchErr := service.Fetch(fetchCtx, source.input, source.kind, platform, capabilities) + snapshot, fetchErr := service.Fetch(fetchCtx, source.Input, source.Kind, platform, capabilities) end() if fetchErr != nil { failures = append(failures, fetchErr) diff --git a/desktop/internal/workbench/plugin_recommendations.go b/desktop/internal/workbench/plugin_recommendations.go new file mode 100644 index 000000000..ce2f4acf7 --- /dev/null +++ b/desktop/internal/workbench/plugin_recommendations.go @@ -0,0 +1,408 @@ +package workbench + +import ( + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "slices" + "sort" + "strings" + "sync" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/vivaui/viva/ui" +) + +const ( + pluginRecommendationScanDepth = 3 + pluginRecommendationScanLimit = 4000 + pluginRecommendationFetchTimeout = 15 * time.Second + pluginRecommendationCacheTTL = 15 * time.Minute +) + +var ignoredRecommendationDirs = map[string]struct{}{ + ".cache": {}, + ".git": {}, + ".gradle": {}, + ".hg": {}, + ".idea": {}, + ".lithe": {}, + ".next": {}, + ".nuxt": {}, + ".svn": {}, + ".venv": {}, + ".vscode": {}, + "__pycache__": {}, + "bin": {}, + "build": {}, + "dist": {}, + "node_modules": {}, + "obj": {}, + "out": {}, + "target": {}, + "vendor": {}, + "venv": {}, +} + +// PluginRecommendationSource identifies one marketplace source URL and policy +// tier checked by marketplace background tasks. +type PluginRecommendationSource struct { + Input string + Kind core.MarketplaceSourceKind +} + +type pluginRecommendationState struct { + mu sync.Mutex + cached []core.MarketplaceRecommendationCatalog + cachedSources string + cachedAt time.Time + hasCache bool + notifiedRoots map[string]string +} + +func newPluginRecommendationState() *pluginRecommendationState { + return &pluginRecommendationState{ + notifiedRoots: map[string]string{}, + } +} + +func (s *pluginRecommendationState) cachedFor(sourcesKey string, now time.Time) ([]core.MarketplaceRecommendationCatalog, bool) { + s.mu.Lock() + defer s.mu.Unlock() + if !s.hasCache || s.cachedSources != sourcesKey || now.Sub(s.cachedAt) >= pluginRecommendationCacheTTL { + return nil, false + } + out := make([]core.MarketplaceRecommendationCatalog, len(s.cached)) + copy(out, s.cached) + return out, true +} + +func (s *pluginRecommendationState) storeCache(sourcesKey string, now time.Time, catalogs []core.MarketplaceRecommendationCatalog) { + s.mu.Lock() + defer s.mu.Unlock() + s.cachedSources = sourcesKey + s.cachedAt = now + s.hasCache = true + s.cached = make([]core.MarketplaceRecommendationCatalog, len(catalogs)) + copy(s.cached, catalogs) +} + +func (s *pluginRecommendationState) markNotified(root string, ids []string) bool { + key := strings.Join(ids, ",") + s.mu.Lock() + defer s.mu.Unlock() + if s.notifiedRoots[root] == key { + return false + } + s.notifiedRoots[root] = key + return true +} + +func (s *pluginRecommendationState) clearRoot(root string) { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.notifiedRoots, root) +} + +func (a *App) checkPluginRecommendations(p *project) { + if p == nil || a.documentOnly || a.disableRecommendations || a.kernel == nil || a.pluginRecommendations == nil { + return + } + root := p.root + sources := a.marketplaceSources() + platform := marketplaceHostPlatform() + capabilities := pluginhost.Declared().Clone() + dismissed := append([]string(nil), a.settings.DismissedPluginRecommendations...) + fetcher := a.recommendationFetcher + pluginsService := a.plugins + nowFn := a.now + state := a.pluginRecommendations + kernel := a.kernel + + a.background(p, 0, func(ctx context.Context) func(*App) { + files, scanWarnings, scanErr := scanWorkspaceRecommendationFiles(ctx, root, pluginRecommendationScanDepth, pluginRecommendationScanLimit) + if scanErr != nil { + return func(a *App) { + if !errors.Is(scanErr, context.Canceled) { + a.backgroundFailed("plugin_recommendations", scanErr) + } + } + } + if len(scanWarnings) > 0 { + warningErr := errors.Join(scanWarnings...) + // Best-effort diagnostics for partially unreadable subdirs without blocking valid matches. + a.backgroundFailedIn(ctx, "plugin_recommendations_scan", warningErr) + } + if len(files) == 0 || ctx.Err() != nil { + return nil + } + + var installedIDs []string + if pluginsService != nil { + entries, err := pluginsService.CurrentInstalled(ctx) + if err != nil { + return func(a *App) { + if !errors.Is(err, context.Canceled) { + a.backgroundFailed("plugin_recommendations", err) + } + } + } + installedIDs = make([]string, 0, len(entries)) + for _, entry := range entries { + if entry.Installed.ID != "" { + installedIDs = append(installedIDs, entry.Installed.ID) + } + } + } + + catalogs, fetchErr := loadRecommendationCatalogs(ctx, kernel, state, sources, nowFn(), fetcher) + if len(catalogs) == 0 { + if fetchErr == nil || errors.Is(fetchErr, context.Canceled) { + return nil + } + return func(a *App) { + a.backgroundFailed("plugin_recommendations", fetchErr) + } + } + + result, recErr := kernel.RecommendMarketplacePlugins(ctx, platform, files, catalogs, capabilities, installedIDs, dismissed) + return func(a *App) { + if fetchErr != nil && !errors.Is(fetchErr, context.Canceled) { + a.backgroundFailed("plugin_recommendations", fetchErr) + } + if recErr != nil { + if !errors.Is(recErr, context.Canceled) { + a.backgroundFailed("plugin_recommendations", recErr) + } + return + } + a.notifyPluginRecommendations(root, result.Plugins) + } + }) +} + +func loadRecommendationCatalogs( + ctx context.Context, + kernel Kernel, + state *pluginRecommendationState, + sources []PluginRecommendationSource, + now time.Time, + fetcher func(context.Context, []PluginRecommendationSource) ([]core.MarketplaceRecommendationCatalog, error), +) ([]core.MarketplaceRecommendationCatalog, error) { + if fetcher != nil { + return fetcher(ctx, sources) + } + sourcesKey := recommendationSourcesKey(sources) + if cached, ok := state.cachedFor(sourcesKey, now); ok { + return cached, nil + } + service := marketplace.New(kernel, nil) + var catalogs []core.MarketplaceRecommendationCatalog + var failures []error + for _, src := range sources { + if ctx.Err() != nil { + return catalogs, ctx.Err() + } + fetchCtx, cancel := context.WithTimeout(ctx, pluginRecommendationFetchTimeout) + bundle, ok, err := service.FetchRecommendationBundle(fetchCtx, src.Input, src.Kind) + cancel() + if err != nil { + failures = append(failures, err) + continue + } + if ok { + catalogs = append(catalogs, core.MarketplaceRecommendationCatalog{ + Index: bundle.Index, + SourceKind: bundle.SourceKind, + IndexURL: bundle.Source.IndexURL, + Recommendations: bundle.Recommendations, + }) + } + } + if len(failures) == 0 { + state.storeCache(sourcesKey, now, catalogs) + } + return catalogs, errors.Join(failures...) +} + +func recommendationSourcesKey(sources []PluginRecommendationSource) string { + var b strings.Builder + for i, src := range sources { + if i > 0 { + b.WriteByte('\n') + } + b.WriteString(string(src.Kind)) + b.WriteByte(':') + b.WriteString(src.Input) + } + return b.String() +} + +// scanWorkspaceRecommendationFiles runs a bounded breadth-first scan of workspace files up to +// maxDepth directory levels and maxEntries filesystem entries without following directory symlinks. +func scanWorkspaceRecommendationFiles(ctx context.Context, root string, maxDepth, maxEntries int) ([]string, []error, error) { + type queueItem struct { + abs string + rel string + depth int + } + if maxDepth < 0 || maxEntries <= 0 { + return nil, nil, nil + } + queue := []queueItem{{abs: root, rel: "", depth: 0}} + visited := 0 + var files []string + var warnings []error + for len(queue) > 0 && visited < maxEntries { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + item := queue[0] + queue = queue[1:] + entries, err := os.ReadDir(item.abs) + if err != nil { + if item.depth == 0 { + return nil, nil, err + } + if errors.Is(err, fs.ErrNotExist) { + // log-exempt: 预期的缺失:并发扫描期间子目录已被删除或移动。 + continue + } + warnings = append(warnings, err) + continue + } + for _, entry := range entries { + if visited >= maxEntries { + break + } + visited++ + name := entry.Name() + if entry.Type()&os.ModeSymlink != 0 { + continue + } + rel := name + if item.rel != "" { + rel = item.rel + "/" + name + } + if entry.IsDir() { + if _, ignored := ignoredRecommendationDirs[name]; ignored { + continue + } + if item.depth < maxDepth { + queue = append(queue, queueItem{ + abs: filepath.Join(item.abs, name), + rel: rel, + depth: item.depth + 1, + }) + } + continue + } + files = append(files, rel) + } + } + return files, warnings, nil +} + +func (a *App) notifyPluginRecommendations(root string, recommendations []core.MarketplaceRecommendation) { + if len(recommendations) == 0 { + return + } + dismissed := make(map[string]struct{}, len(a.settings.DismissedPluginRecommendations)) + for _, id := range a.settings.DismissedPluginRecommendations { + dismissed[id] = struct{}{} + } + filtered := make([]core.MarketplaceRecommendation, 0, len(recommendations)) + matchedIDs := make([]string, 0, len(recommendations)) + for _, rec := range recommendations { + if _, skip := dismissed[rec.Plugin.ID]; skip { + continue + } + filtered = append(filtered, rec) + matchedIDs = append(matchedIDs, rec.Plugin.ID) + } + if len(filtered) == 0 { + return + } + sortedIDs := append([]string(nil), matchedIDs...) + sort.Strings(sortedIDs) + if !a.pluginRecommendations.markNotified(root, sortedIDs) { + return + } + + language := a.language() + names := make([]string, 0, len(filtered)) + for _, rec := range filtered { + name := rec.Plugin.Name + if name == "" { + name = rec.Plugin.ID + } + names = append(names, name) + } + separator := ", " + if strings.HasPrefix(language.Code(), "zh") { + separator = "、" + } + title := i18n.Shared(language, "desktop.marketplace.recommendedTitle") + detail := i18n.SharedFormat(language, "desktop.marketplace.recommendedPlugins", map[string]string{ + "plugins": strings.Join(names, separator), + }) + primaryLabel := i18n.Shared(language, "desktop.marketplace.recommendedAction") + secondaryLabel := i18n.Shared(language, "desktop.marketplace.recommendedDismiss") + firstQuery := names[0] + multiple := len(filtered) > 1 + a.shownTab().notifyActions( + title, + detail, + ui.ToastInfo, + primaryLabel, + func(target *App) { + if multiple { + target.openPluginSettings(surfaceNotification) + return + } + target.openPluginSettingsSearch(surfaceNotification, firstQuery) + }, + secondaryLabel, + func(target *App) { + target.dismissPluginRecommendations(root, matchedIDs, title, detail) + }, + ) +} + +func (a *App) dismissPluginRecommendations(root string, ids []string, title, detail string) { + if len(ids) == 0 { + return + } + seen := make(map[string]struct{}, len(a.settings.DismissedPluginRecommendations)+len(ids)) + for _, existing := range a.settings.DismissedPluginRecommendations { + seen[existing] = struct{}{} + } + for _, id := range ids { + if id != "" { + seen[id] = struct{}{} + } + } + merged := make([]string, 0, len(seen)) + for id := range seen { + merged = append(merged, id) + } + slices.Sort(merged) + for _, tab := range a.everyTab() { + tab.settings.DismissedPluginRecommendations = append([]string(nil), merged...) + } + a.saveSettings() + if a.pluginRecommendations != nil && root != "" { + a.pluginRecommendations.clearRoot(root) + } + for _, entry := range a.notifications.list { + if entry.text == title && entry.detail == detail && entry.kind == ui.ToastInfo { + a.overlay.toaster.Close(entry.toast) + } + } +} diff --git a/desktop/internal/workbench/plugin_recommendations_test.go b/desktop/internal/workbench/plugin_recommendations_test.go new file mode 100644 index 000000000..40c2c96b8 --- /dev/null +++ b/desktop/internal/workbench/plugin_recommendations_test.go @@ -0,0 +1,408 @@ +package workbench + +import ( + "archive/zip" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +func recommendationTestStore(t *testing.T) *store.Store { + t.Helper() + prefs := store.At(t.TempDir()) + // An explicit theme avoids calling app.SystemAppearance() without an active NSApplication loop. + if err := prefs.Save(settingsFile, settings{Theme: themeDark}); err != nil { + t.Fatal(err) + } + return prefs +} + +func syntheticRecommendationCatalog(t *testing.T, recommendationsJSON string) core.MarketplaceRecommendationCatalog { + t.Helper() + platform := marketplaceHostPlatform() + shaA := strings.Repeat("a", 64) + shaB := strings.Repeat("b", 64) + indexPayload, err := json.Marshal(map[string]any{ + "schemaVersion": 0, + "plugins": []map[string]any{ + { + "id": "io.example.demo-lang", + "name": "Demo Lang", + "author": "Example Authors", + "repository": "https://github.com/example/demo-lang", + "description": "Synthetic language support fixture for workspace recommendations.", + "tags": []string{"language"}, + "license": "MIT", + "versions": []map[string]any{ + { + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": map[string]any{"languages": 0}, + "releaseDate": "2026-10-01", + "downloads": []map[string]any{ + { + "platforms": []string{platform}, + "downloadURL": "https://github.com/example/demo-lang/releases/download/v1.0.0/demo-lang.zip", + "sha256": shaA, + }, + }, + }, + }, + }, + { + "id": "io.example.demo-build", + "name": "Demo Build", + "author": "Example Authors", + "repository": "https://github.com/example/demo-build", + "description": "Synthetic build system fixture for workspace recommendations.", + "tags": []string{"build"}, + "license": "MIT", + "versions": []map[string]any{ + { + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": map[string]any{"languages": 0}, + "releaseDate": "2026-10-01", + "downloads": []map[string]any{ + { + "platforms": []string{platform}, + "downloadURL": "https://github.com/example/demo-build/releases/download/v1.0.0/demo-build.zip", + "sha256": shaB, + }, + }, + }, + }, + }, + }, + }) + if err != nil { + t.Fatal(err) + } + return core.MarketplaceRecommendationCatalog{ + Index: indexPayload, + SourceKind: core.MarketplaceThirdParty, + IndexURL: "https://example.com/lithe-plugin-index.json", + Recommendations: []byte(recommendationsJSON), + } +} + +func performedAction(logger *actionFieldLog, action string) bool { + logger.mu.Lock() + defer logger.mu.Unlock() + return slices.Contains(logger.actions, action) +} + +func TestPluginRecommendationsNotifyOpenSettingsAndDismiss(t *testing.T) { + const recCatalog = `{ + "schemaVersion": 0, + "recommendations": [ + { "pluginID": "io.example.demo-lang", "markers": ["demo.toml"] } + ] + }` + workspace := t.TempDir() + if err := os.WriteFile(filepath.Join(workspace, "demo.toml"), []byte("[project]\n"), 0o644); err != nil { + t.Fatal(err) + } + + logger := &actionFieldLog{} + prefs := recommendationTestStore(t) + var fetches atomic.Int32 + catalog := syntheticRecommendationCatalog(t, recCatalog) + h := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + Store: prefs, + Logs: logger, + Languages: []string{"en-US"}, + PluginRecommendationFetcher: func(context.Context, []PluginRecommendationSource) ([]core.MarketplaceRecommendationCatalog, error) { + fetches.Add(1) + return []core.MarketplaceRecommendationCatalog{catalog}, nil + }, + }) + h.open(workspace) + + wantMsg := i18n.SharedFormat(h.app.language(), "desktop.marketplace.recommendedPlugins", map[string]string{ + "plugins": "Demo Lang", + }) + awaitStateWithin(t, h, 5*time.Second, "plugin recommendation notification", func() bool { + return h.app.notice == wantMsg && len(h.app.notifications.list) == 1 + }) + if fetches.Load() != 1 { + t.Fatalf("fetches = %d, want 1", fetches.Load()) + } + + // Primary action opens plugin settings under surfaceNotification. + actionLabel := i18n.Shared(h.app.language(), "desktop.marketplace.recommendedAction") + if n := h.pageControls(actionLabel); n != 1 { + t.Fatalf("toast primary button count = %d, want 1", n) + } + h.clickNamed(actionLabel) + h.settle() + if !performedAction(logger, "settings.open") { + t.Fatal("expected settings.open performed action on primary notification click") + } + + // Secondary action from notification drawer persists dismissal across restarts. + for _, entry := range h.app.notifications.list { + h.app.overlay.toaster.Close(entry.toast) + } + h.app.invalidator.Invalidate() + h.settle() + h.clickNamed("Notifications, 1 unread") + h.settle() + + dismissLabel := i18n.Shared(h.app.language(), "desktop.marketplace.recommendedDismiss") + if n := h.pageControls(dismissLabel); n != 1 { + t.Fatalf("drawer dismiss button count = %d, want 1", n) + } + h.clickNamed(dismissLabel) + h.settle() + + var saved settings + if ok, err := prefs.Load(settingsFile, &saved); err != nil || !ok { + t.Fatalf("Load settings = (%v, %v)", ok, err) + } + if !slices.Equal(saved.DismissedPluginRecommendations, []string{"io.example.demo-lang"}) { + t.Fatalf("saved.DismissedPluginRecommendations = %v", saved.DismissedPluginRecommendations) + } + + // Reopening in a new window with the same Store settles all background tasks and verifies + // the dismissed plugin is not notified again. + var fetches2 atomic.Int32 + h2 := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + Store: prefs, + Languages: []string{"en-US"}, + PluginRecommendationFetcher: func(context.Context, []PluginRecommendationSource) ([]core.MarketplaceRecommendationCatalog, error) { + fetches2.Add(1) + return []core.MarketplaceRecommendationCatalog{catalog}, nil + }, + }) + h2.open(workspace) + h2.settle() + if fetches2.Load() != 1 || len(h2.app.notifications.list) != 0 { + t.Fatalf("reopened dismissed workspace fetches=%d notices=%d, want 1, 0", fetches2.Load(), len(h2.app.notifications.list)) + } +} + +func TestPluginRecommendationsCombinesMultipleMatches(t *testing.T) { + const recCatalog = `{ + "schemaVersion": 0, + "recommendations": [ + { "pluginID": "io.example.demo-build", "markers": ["demo.toml"] }, + { "pluginID": "io.example.demo-lang", "extensions": ["demo"] } + ] + }` + workspace := t.TempDir() + if err := os.WriteFile(filepath.Join(workspace, "demo.toml"), []byte("[build]\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(workspace, "src"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(workspace, "src", "main.demo"), []byte("fn main() {}\n"), 0o644); err != nil { + t.Fatal(err) + } + + logger := &actionFieldLog{} + catalog := syntheticRecommendationCatalog(t, recCatalog) + h := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + Store: recommendationTestStore(t), + Logs: logger, + Languages: []string{"en-US"}, + PluginRecommendationFetcher: func(context.Context, []PluginRecommendationSource) ([]core.MarketplaceRecommendationCatalog, error) { + return []core.MarketplaceRecommendationCatalog{catalog}, nil + }, + }) + h.open(workspace) + + wantMsg := i18n.SharedFormat(h.app.language(), "desktop.marketplace.recommendedPlugins", map[string]string{ + "plugins": "Demo Build, Demo Lang", + }) + awaitStateWithin(t, h, 5*time.Second, "combined recommendation notification", func() bool { + return h.app.notice == wantMsg && len(h.app.notifications.list) == 1 + }) + + h.clickNamed(i18n.Shared(h.app.language(), "desktop.marketplace.recommendedAction")) + h.settle() + if !performedAction(logger, "settings.open") { + t.Fatal("expected settings.open on multiple-plugin primary action") + } +} + +func TestPluginRecommendationsEmptyOr404StaySilent(t *testing.T) { + workspace := t.TempDir() + if err := os.WriteFile(filepath.Join(workspace, "README.md"), []byte("hi"), 0o644); err != nil { + t.Fatal(err) + } + h := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + Store: recommendationTestStore(t), + Languages: []string{"en-US"}, + PluginRecommendationFetcher: func(context.Context, []PluginRecommendationSource) ([]core.MarketplaceRecommendationCatalog, error) { + return nil, nil + }, + }) + h.open(workspace) + h.settle() + if len(h.app.notifications.list) != 0 || h.app.notice != "" { + t.Fatalf("unexpected activity: notices=%d notice=%q", len(h.app.notifications.list), h.app.notice) + } +} + +func TestPluginRecommendationsExcludeInstalledOrCoveredByPlugins(t *testing.T) { + const recCatalog = `{ + "schemaVersion": 0, + "recommendations": [ + { + "pluginID": "io.example.demo-lang", + "markers": ["demo.toml"], + "coveredBy": ["io.github.example.output-links"] + } + ] + }` + workspace := t.TempDir() + if err := os.WriteFile(filepath.Join(workspace, "demo.toml"), []byte("[project]\n"), 0o644); err != nil { + t.Fatal(err) + } + + h := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + Store: recommendationTestStore(t), + Languages: []string{"en-US"}, + PluginRecommendationFetcher: func(context.Context, []PluginRecommendationSource) ([]core.MarketplaceRecommendationCatalog, error) { + return []core.MarketplaceRecommendationCatalog{syntheticRecommendationCatalog(t, recCatalog)}, nil + }, + }) + service, err := pluginservice.Open(core.NewClient(), h.store, t.TempDir()) + if err != nil { + t.Fatal(err) + } + h.app.plugins = service + + // Install the covering plugin io.github.example.output-links into service.Root. + archivePath, digest := writeTestPluginZip(t, t.TempDir(), "io.github.example.output-links", installablePluginManifest) + plan, err := h.app.preparePlugin(context.Background(), plugininstall.Request{ + ArchivePath: archivePath, + Root: service.Root, + Source: plugintrust.Marketplace, + ArchiveSHA256: digest, + MarketplaceIndexURL: "https://example.com/lithe-plugin-index.json", + ExpectedID: "io.github.example.output-links", + ExpectedVersion: "1.0.0", + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = service.Installer.Discard(plan) }) + if _, err := service.Installer.Commit(plan); err != nil { + t.Fatal(err) + } + + h.open(workspace) + h.settle() + if len(h.app.notifications.list) != 0 { + t.Fatalf("expected coveredBy plugin not to notify, got %d notices", len(h.app.notifications.list)) + } +} + +func TestScanWorkspaceRecommendationFilesRespectsBoundsAndSkipsSymlinks(t *testing.T) { + root := t.TempDir() + for _, dir := range []string{ + "a/b/c", // depth 3: scanned + "a/b/c/d", // depth 4: skipped + ".git", // ignored + "node_modules", // ignored + } { + if err := os.MkdirAll(filepath.Join(root, dir), 0o755); err != nil { + t.Fatal(err) + } + } + mustWrite := func(rel string) { + t.Helper() + if err := os.WriteFile(filepath.Join(root, rel), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + } + mustWrite("pom.xml") + mustWrite("a/b/c/inside.java") + mustWrite("a/b/c/d/too_deep.go") + mustWrite(".git/HEAD") + mustWrite("node_modules/ignored.go") + + outside := t.TempDir() + if err := os.WriteFile(filepath.Join(outside, "escape.go"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(root, "symlink-dir")); err != nil && !errors.Is(err, os.ErrPermission) { + t.Fatal(err) + } + + files, warnings, err := scanWorkspaceRecommendationFiles(context.Background(), root, 3, 4000) + if err != nil || len(warnings) != 0 { + t.Fatalf("scan = (%v, %v), want nil error/warnings", warnings, err) + } + if !slices.Contains(files, "pom.xml") || !slices.Contains(files, "a/b/c/inside.java") { + t.Fatalf("missing expected files in %v", files) + } + for _, unexpected := range []string{"a/b/c/d/too_deep.go", ".git/HEAD", "node_modules/ignored.go", "symlink-dir/escape.go"} { + if slices.Contains(files, unexpected) { + t.Fatalf("unexpected file %q in %v", unexpected, files) + } + } + + // Enforce strict entry limit. + manyRoot := t.TempDir() + for i := range 25 { + if err := os.WriteFile(filepath.Join(manyRoot, "file_"+string(rune('a'+i))+".txt"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + } + bounded, _, err := scanWorkspaceRecommendationFiles(context.Background(), manyRoot, 3, 5) + if err != nil { + t.Fatal(err) + } + if len(bounded) != 5 { + t.Fatalf("bounded len = %d, want 5", len(bounded)) + } +} + +func writeTestPluginZip(t *testing.T, dir, pluginID, manifest string) (string, string) { + t.Helper() + var payload bytes.Buffer + writer := zip.NewWriter(&payload) + entry, err := writer.Create(pluginID + "/plugin.json") + if err != nil { + t.Fatal(err) + } + if _, err := entry.Write([]byte(manifest)); err != nil { + t.Fatal(err) + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + archiveBytes := payload.Bytes() + sum := sha256.Sum256(archiveBytes) + zipPath := filepath.Join(dir, "plugin.zip") + if err := os.WriteFile(zipPath, archiveBytes, 0o600); err != nil { + t.Fatal(err) + } + return zipPath, hex.EncodeToString(sum[:]) +} diff --git a/desktop/internal/workbench/plugin_recommendations_visual_test.go b/desktop/internal/workbench/plugin_recommendations_visual_test.go new file mode 100644 index 000000000..c94564281 --- /dev/null +++ b/desktop/internal/workbench/plugin_recommendations_visual_test.go @@ -0,0 +1,119 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualPluginWorkspaceRecommendations captures dark/light and Chinese/English frames of +// workspace plugin recommendations in the floating toast and the notification history popover. +func TestVisualPluginWorkspaceRecommendations(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + + const recCatalog = `{ + "schemaVersion": 0, + "recommendations": [ + { "pluginID": "io.example.demo-build", "markers": ["demo.toml"] }, + { "pluginID": "io.example.demo-lang", "extensions": ["demo"] } + ] + }` + + for _, look := range []struct{ theme, language, langTag string }{ + {"dark", "zh-Hans", "zh"}, + {"light", "zh-Hans", "zh"}, + {"dark", "en", "en"}, + {"light", "en", "en"}, + } { + t.Run(look.theme+"-"+look.langTag, func(t *testing.T) { + workspace := t.TempDir() + if err := os.WriteFile(filepath.Join(workspace, "demo.toml"), []byte("[build]\nname = \"demo\"\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(workspace, "src"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(workspace, "src", "main.demo"), []byte("fn main() {}\n"), 0o644); err != nil { + t.Fatal(err) + } + + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{ + Theme: themeChoice(look.theme), + Language: look.language, + DisableAutoSave: true, + }); err != nil { + t.Fatal(err) + } + + catalog := syntheticRecommendationCatalog(t, recCatalog) + var session *headless.Session + h := newHarnessWithDriver(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + Store: prefs, + Languages: []string{look.language}, + PluginRecommendationFetcher: func(context.Context, []PluginRecommendationSource) ([]core.MarketplaceRecommendationCatalog, error) { + return []core.MarketplaceRecommendationCatalog{catalog}, nil + }, + }, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.app.now = func() time.Time { return time.Date(2026, 11, 20, 14, 30, 0, 0, time.Local) } + h.open(workspace) + + want := i18n.SharedFormat(h.app.language(), "desktop.marketplace.recommendedPlugins", map[string]string{ + "plugins": separatorJoinedDemo(h.app.language()), + }) + awaitStateWithin(t, h, 5*time.Second, "recommendation notice", func() bool { + return h.app.notice == want && len(h.app.notifications.list) == 1 + }) + h.settleChain() + if (look.theme == "dark" && look.langTag == "zh") || (look.theme == "light" && look.langTag == "en") { + if err := session.Screenshot(filepath.Join(out, "toast-"+look.theme+"-"+look.langTag+".png")); err != nil { + t.Fatal(err) + } + } + + for _, entry := range h.app.notifications.list { + h.app.overlay.toaster.Close(entry.toast) + } + h.app.invalidator.Invalidate() + h.settleChain() + bell := i18n.SharedFormat(h.app.language(), "desktop.notifications.unread", map[string]string{"count": "1"}) + h.clickNamed(bell) + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "notifications-popover-"+look.theme+"-"+look.langTag+".png")); err != nil { + t.Fatal(err) + } + }) + } +} + +func separatorJoinedDemo(lang i18n.Language) string { + if lang.Code() == "zh-Hans" || lang.Code() == "zh-CN" { + return "Demo Build、Demo Lang" + } + return "Demo Build, Demo Lang" +} diff --git a/docs/assets/plugin-workspace-recommendations/README.md b/docs/assets/plugin-workspace-recommendations/README.md new file mode 100644 index 000000000..b656475f8 --- /dev/null +++ b/docs/assets/plugin-workspace-recommendations/README.md @@ -0,0 +1,12 @@ +# 工作区插件推荐无头测试截图 + +来自生产 Viva Page 的无头渲染。工作区由测试在临时目录中创建(含合成标记文件 `demo.toml` 与源码 `src/main.demo`),插件推荐由注入的合成测试市场索引与推荐目录驱动,不包含任何具体插件或真实插件市场依赖。截图覆盖深色与浅色主题、中文与英文界面,用于确认通知横幅和通知抽屉中主按钮与“不再提示”次级按钮的排版与可读性。截图不代表 macOS/Windows 原生窗口验收。 + +| 场景 | 深色主题 | 浅色主题 | +| --- | --- | --- | +| 浮动通知横幅(英文 / 中文主操作按钮) | [深色中文 Toast](toast-dark-zh.png) | [浅色英文 Toast](toast-light-en.png) | +| 通知抽屉历史条目(中文:查看插件 + 不再提示) | [深色中文](notifications-popover-dark-zh.png) | [浅色中文](notifications-popover-light-zh.png) | +| 通知抽屉历史条目(英文:View Plugins + Don't Show Again) | [深色英文](notifications-popover-dark-en.png) | [浅色英文](notifications-popover-light-en.png) | + +复验:从仓库根目录设置绝对路径 `LITHE_VISUAL_OUTPUT_DIR="$(pwd)/docs/assets/plugin-workspace-recommendations"`,通过 +`scripts/desktop/desktop-go.sh test -tags vivahead,lithevisual ./internal/workbench -run '^TestVisualPluginWorkspaceRecommendations$' -count=1 -timeout 180s` 生成。 diff --git a/docs/assets/plugin-workspace-recommendations/notifications-popover-dark-en.png b/docs/assets/plugin-workspace-recommendations/notifications-popover-dark-en.png new file mode 100644 index 000000000..857ab8678 Binary files /dev/null and b/docs/assets/plugin-workspace-recommendations/notifications-popover-dark-en.png differ diff --git a/docs/assets/plugin-workspace-recommendations/notifications-popover-dark-zh.png b/docs/assets/plugin-workspace-recommendations/notifications-popover-dark-zh.png new file mode 100644 index 000000000..2704d4a12 Binary files /dev/null and b/docs/assets/plugin-workspace-recommendations/notifications-popover-dark-zh.png differ diff --git a/docs/assets/plugin-workspace-recommendations/notifications-popover-light-en.png b/docs/assets/plugin-workspace-recommendations/notifications-popover-light-en.png new file mode 100644 index 000000000..e5617d5fa Binary files /dev/null and b/docs/assets/plugin-workspace-recommendations/notifications-popover-light-en.png differ diff --git a/docs/assets/plugin-workspace-recommendations/notifications-popover-light-zh.png b/docs/assets/plugin-workspace-recommendations/notifications-popover-light-zh.png new file mode 100644 index 000000000..d844e1670 Binary files /dev/null and b/docs/assets/plugin-workspace-recommendations/notifications-popover-light-zh.png differ diff --git a/docs/assets/plugin-workspace-recommendations/toast-dark-zh.png b/docs/assets/plugin-workspace-recommendations/toast-dark-zh.png new file mode 100644 index 000000000..6e4290bc4 Binary files /dev/null and b/docs/assets/plugin-workspace-recommendations/toast-dark-zh.png differ diff --git a/docs/assets/plugin-workspace-recommendations/toast-light-en.png b/docs/assets/plugin-workspace-recommendations/toast-light-en.png new file mode 100644 index 000000000..34bfe8f5c Binary files /dev/null and b/docs/assets/plugin-workspace-recommendations/toast-light-en.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index fbe0849e5..86f7bb372 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -290,7 +290,9 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # Search pages, unsaved snapshots, source identities and budgets from Core #125, # merged on top of the build-option changes through Core #124. # CLI launch policy, isolated document command policy and opt-in shell registration from Core #129. -PINNED_CORE_REVISION="6c84d32d4b82e358b41f5a7edf78f2a0ca7a3695" +# Lithe-core-rust main at d630938 (#130 squash-merged): companion marketplace recommendations +# contract, resolveSource.recommendationsURL, and plugins.marketplace.recommendForWorkspace (#2228). +PINNED_CORE_REVISION="d6309386cbc164ed82eb8728cf6b7d90db12fc61" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 26df27621..fdc3ea278 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -1255,6 +1255,10 @@ "desktop.markdown.preview": "Rendered Markdown", "desktop.markdown.tooLarge": "This file is too large to preview.", "desktop.marketplace.autoUpdated": "Automatically updated {count} plugins. Restart Lithe to activate the updates.", + "desktop.marketplace.recommendedTitle": "Recommended Plugins", + "desktop.marketplace.recommendedPlugins": "Suggested for this project: {plugins}", + "desktop.marketplace.recommendedAction": "View Plugins", + "desktop.marketplace.recommendedDismiss": "Don't Show Again", "desktop.marketplace.disableAutoUpdates": "Turn off automatic plugin updates", "desktop.marketplace.enableAutoUpdates": "Automatically update previously approved plugins", "desktop.marketplace.cancel": "Cancel", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 45322a06a..cc56af167 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -1255,6 +1255,10 @@ "desktop.markdown.preview": "渲染后的 Markdown", "desktop.markdown.tooLarge": "此文件过大,无法预览。", "desktop.marketplace.autoUpdated": "已自动更新 {count} 个插件。重启 Lithe 后生效。", + "desktop.marketplace.recommendedTitle": "推荐安装插件", + "desktop.marketplace.recommendedPlugins": "检测到当前项目可能需要:{plugins}", + "desktop.marketplace.recommendedAction": "查看插件", + "desktop.marketplace.recommendedDismiss": "不再提示", "desktop.marketplace.disableAutoUpdates": "关闭插件自动更新", "desktop.marketplace.enableAutoUpdates": "自动更新已授权的插件", "desktop.marketplace.cancel": "取消", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 3a238339f..2ab0a501b 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -13058,6 +13058,37 @@ "count": "string" } }, + { + "id": "desktop.marketplace.recommendedTitle", + "description": "Short notification title for workspace-matched marketplace plugin suggestions.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.recommendedPlugins", + "description": "Notification body listing workspace-matched marketplace plugins to install for the opened project.", + "platforms": [ + "desktop" + ], + "parameters": { + "plugins": "string" + } + }, + { + "id": "desktop.marketplace.recommendedAction", + "description": "Primary notification action button opening plugin settings for workspace plugin recommendations.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.recommendedDismiss", + "description": "Secondary notification action button dismissing future recommendations for the listed plugins.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.marketplace.disableAutoUpdates", "description": "Menu option to disable automatic updates of approved marketplace plugins.", diff --git a/shared/platform-feature-matrix/features/plugin-workspace-recommendations.json b/shared/platform-feature-matrix/features/plugin-workspace-recommendations.json new file mode 100644 index 000000000..9c3b65771 --- /dev/null +++ b/shared/platform-feature-matrix/features/plugin-workspace-recommendations.json @@ -0,0 +1,39 @@ +{ + "id": "plugin-workspace-recommendations", + "area": "扩展", + "group": "插件与主题", + "capability": "打开工作区时对项目根及浅层子目录执行有界非阻塞扫描,结合插件市场发布的独立推荐索引与 Core 匹配规则筛选尚未安装或未被替代插件覆盖的可安装插件,并在应用内发出一条汇总通知,支持一键跳转到对应插件市场页面或永久不再提示。", + "owner": "Extensions", + "notes": "Viva Go 跨平台实现;桌面端仅保留协议与通用算法,具体插件与语言映射规则完全由外部插件市场同级索引提供,向后兼容旧版市场客户端。同一会话对市场目录缓存 15 分钟且按工作区根目录去重;选择不再提示后将插件 ID 持久化到设置文件中。macOS 与 Windows 原生真实环境均共享该逻辑。", + "verification": "自动化:Lithe-core-rust 契约单测(marketplace_plugins)、desktop/internal/core/marketplace_test.go 契约 fixture 测试、desktop/internal/marketplace/service_test.go HTTP 404/200/校验测试、desktop/internal/workbench/plugin_recommendations_test.go 与 notifications_test.go 覆盖深度与条目上限/符号链接跳过/多插件合并/覆盖插件过滤/查看插件与不再提示持久化,以及 -race 并发测试与无头 Viva 暗亮/中英截图验证。Windows 原生实机验证待 CI/VM 执行。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "verified", + "evidence": [ + "desktop/internal/core/marketplace.go", + "desktop/internal/core/marketplace_test.go", + "desktop/internal/marketplace/service.go", + "desktop/internal/marketplace/service_test.go", + "desktop/internal/workbench/notifications.go", + "desktop/internal/workbench/notifications_test.go", + "desktop/internal/workbench/plugin_recommendations.go", + "desktop/internal/workbench/plugin_recommendations_test.go", + "desktop/internal/workbench/plugin_recommendations_visual_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/marketplace.go", + "desktop/internal/core/marketplace_test.go", + "desktop/internal/marketplace/service.go", + "desktop/internal/marketplace/service_test.go", + "desktop/internal/workbench/notifications.go", + "desktop/internal/workbench/notifications_test.go", + "desktop/internal/workbench/plugin_recommendations.go", + "desktop/internal/workbench/plugin_recommendations_test.go", + "desktop/internal/workbench/plugin_recommendations_visual_test.go" + ] + } +}