25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(plugin): 增加安装量统计功能,并支持按安装量排序 (#13083)
Yifeng Xu18415f3111bd
diff --git a/apps/desktop/src/components/plugins/PluginContributionsPanel.vue b/apps/desktop/src/components/plugins/PluginContributionsPanel.vueindex 13c05c8683..d05ad34b25 100644--- a/apps/desktop/src/components/plugins/PluginContributionsPanel.vue+++ b/apps/desktop/src/components/plugins/PluginContributionsPanel.vue@@ -59,6 +59,7 @@ import {buildInstalledUpdateIndex,buildMarketplacePluginListings,compareVersions,+ fetchPluginInstallCounts,filterMarketplacePluginListings,formatMarketplaceReleasedDate,marketplaceHomepageUrl,@@ -68,6 +69,7 @@ import {type InstalledPluginUpdateEntry,type MarketplacePluginListing,type MarketplacePluginSortMode,+ type PluginInstallCounts,type PluginSourceChange,} from "@/lib/plugins/pluginMarketplace";import { isBatchSelectableListing, runBatch, type BatchOutcome } from "@/lib/plugins/pluginBatch";@@ -184,7 +186,7 @@ const marketplaceRepositoryId = ref("all");const marketplaceDetailKey = ref("");const marketplaceDetailOpen = ref(false);const marketplaceViewMode = ref<"grid" | "list">(safeLocalStorageGet(MARKETPLACE_VIEW_MODE_STORAGE_KEY) === "list" ? "list" : "grid");-const MARKETPLACE_SORT_MODES: MarketplacePluginSortMode[] = ["name", "recently-updated", "recently-listed", "updates-first"];+const MARKETPLACE_SORT_MODES: MarketplacePluginSortMode[] = ["name", "installs", "recently-updated", "recently-listed", "updates-first"];// "name" stays the default: the batch specs select listings positionally, so a persisted// value must be re-validated against the known modes before it may change the order.const marketplaceSortMode = ref<MarketplacePluginSortMode>(@@ -229,7 +231,9 @@ const selectedConnection = computed(() => providerConnections.value.find((connecconst marketplaceListings = computed(() => buildMarketplacePluginListings(catalogResults.value, installedPlugins.value, appLocale.value));const filteredMarketplaceListings = computed(() => filterMarketplacePluginListings(marketplaceListings.value, marketplaceQuery.value, marketplaceRepositoryId.value).filter((listing) => !marketplacePublisher.value || listing.plugin.publisher === marketplacePublisher.value));// Render order only: batch selection and update execution keep the builder's name order.-const sortedMarketplaceListings = computed(() => sortMarketplacePluginListings(filteredMarketplaceListings.value, marketplaceSortMode.value));+const pluginInstallCounts = ref<PluginInstallCounts>({});+let installCountRequest = 0;+const sortedMarketplaceListings = computed(() => sortMarketplacePluginListings(filteredMarketplaceListings.value, marketplaceSortMode.value, pluginInstallCounts.value));const selectedMarketplaceListing = computed(() => marketplaceListings.value.find((listing) => listing.key === marketplaceDetailKey.value) || null);const detailOpening = ref(false);const detailChooseEntry = ref(false);@@ -555,8 +559,31 @@ async function refresh(preferredPluginId = props.focusTarget?.pluginId || select}}+function listingInstallCount(pluginId: string): number {+ const value = pluginInstallCounts.value[pluginId];+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;+}++function formatInstallCount(count: number): string {+ try {+ return new Intl.NumberFormat(appLocale.value).format(count);+ } catch {+ return String(count);+ }+}++// Stats stay decorative: a slow or failed request must not hold the catalog,+// and a newer refresh or unmount drops the stale response.+function loadPluginInstallCounts() {+ const request = ++installCountRequest;+ void fetchPluginInstallCounts().then((counts) => {+ if (request === installCountRequest && counts) pluginInstallCounts.value = counts;+ });+}+async function refreshMarketplace() {marketplaceLoading.value = true;+ loadPluginInstallCounts();let loaded = false;try {catalogResults.value = await api.fetchPluginMarketplaceCatalogs();@@ -1368,6 +1395,7 @@ onMounted(() => {watch(marketplaceViewMode, (mode) => safeLocalStorageSet(MARKETPLACE_VIEW_MODE_STORAGE_KEY, mode));watch(marketplaceSortMode, (mode) => safeLocalStorageSet(MARKETPLACE_SORT_MODE_STORAGE_KEY, mode));onBeforeUnmount(() => {+ installCountRequest += 1;detailSessionGeneration += 1;window.clearTimeout(recentlyCompletedTimer);window.removeEventListener(COMPONENT_PLUGINS_UPDATED_EVENT, handleComponentPluginsUpdated);@@ -1437,6 +1465,7 @@ onBeforeUnmount(() => {<SelectTrigger data-plugin-marketplace-sort class="h-8 min-w-0 flex-1 text-xs @min-[54rem]:w-32 @min-[54rem]:flex-none" :aria-label="t('pluginPlatform.sortBy')"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="name">{{ t("pluginPlatform.sortByName") }}</SelectItem>+ <SelectItem value="installs">{{ t("pluginPlatform.sortByInstalls") }}</SelectItem><SelectItem value="recently-updated">{{ t("pluginPlatform.sortByRecentlyUpdated") }}</SelectItem><SelectItem value="recently-listed">{{ t("pluginPlatform.sortByRecentlyListed") }}</SelectItem><SelectItem value="updates-first">{{ t("pluginPlatform.sortByUpdatesFirst") }}</SelectItem>@@ -1585,20 +1614,23 @@ onBeforeUnmount(() => {<TooltipContent side="bottom" class="max-w-md whitespace-pre-wrap break-words">{{ listing.description || t("pluginPlatform.noDescription") }}</TooltipContent></Tooltip><div class="marketplace-footer mt-auto flex items-center justify-between gap-3 pt-4">- <div class="flex min-w-0 flex-1 items-baseline gap-1.5 text-[11px] text-muted-foreground">- <span v-if="listing.status === 'unsupported'" class="min-w-0 truncate">{{ t("pluginPlatform.unsupportedTarget", { target: listing.target }) }}</span>- <!-- Versions are stated only in this footer (no separate badge above): the update case- keeps installed and catalog latest in one sentence so neither reads as the other,- and the plain install state leads with the full catalog version that never shrinks- while license and release date absorb the truncation. -->- <span v-else-if="listing.installed && listing.status === 'update'" class="min-w-0 truncate">{{ t("pluginPlatform.installedVersionUpdatable", { installed: listing.installed.manifest.version, latest: listing.plugin.latestVersion }) }}</span>- <span v-else-if="listing.installed" class="min-w-0 truncate">{{ t("pluginPlatform.installedVersion", { version: listing.installed.manifest.version }) }}</span>- <template v-else>- <span class="shrink-0 font-medium">v{{ listing.plugin.latestVersion }}</span>- <span class="min-w-0 truncate"- >{{ listing.plugin.license || t("pluginPlatform.licenseUnknown") }}<span v-if="listing.latestVersionReleasedAt"> · {{ formatMarketplaceReleasedDate(listing.latestVersionReleasedAt, appLocale) }}</span></span- >- </template>+ <div class="flex min-w-0 flex-1 flex-col gap-0.5">+ <div class="flex min-w-0 items-baseline gap-1.5 text-[11px] text-muted-foreground">+ <span v-if="listing.status === 'unsupported'" class="min-w-0 truncate">{{ t("pluginPlatform.unsupportedTarget", { target: listing.target }) }}</span>+ <!-- Versions are stated only in this footer (no separate badge above): the update case+ keeps installed and catalog latest in one sentence so neither reads as the other,+ and the plain install state leads with the full catalog version that never shrinks+ while license and release date absorb the truncation. -->+ <span v-else-if="listing.installed && listing.status === 'update'" class="min-w-0 truncate">{{ t("pluginPlatform.installedVersionUpdatable", { installed: listing.installed.manifest.version, latest: listing.plugin.latestVersion }) }}</span>+ <span v-else-if="listing.installed" class="min-w-0 truncate">{{ t("pluginPlatform.installedVersion", { version: listing.installed.manifest.version }) }}</span>+ <template v-else>+ <span class="shrink-0 font-medium">v{{ listing.plugin.latestVersion }}</span>+ <span class="min-w-0 truncate"+ >{{ listing.plugin.license || t("pluginPlatform.licenseUnknown") }}<span v-if="listing.latestVersionReleasedAt"> · {{ formatMarketplaceReleasedDate(listing.latestVersionReleasedAt, appLocale) }}</span></span+ >+ </template>+ </div>+ <div v-if="listingInstallCount(listing.plugin.id)" class="text-[11px] tabular-nums text-muted-foreground">{{ t("pluginPlatform.installCount", { count: formatInstallCount(listingInstallCount(listing.plugin.id)) }) }}</div></div><buttontype="button"@@ -1650,6 +1682,7 @@ onBeforeUnmount(() => {><span class="shrink-0">· v{{ listing.plugin.latestVersion }}</span><span v-if="listing.latestVersionReleasedAt" class="shrink-0">· {{ formatMarketplaceReleasedDate(listing.latestVersionReleasedAt, appLocale) }}</span>+ <span v-if="listingInstallCount(listing.plugin.id)" class="shrink-0 tabular-nums">· {{ t("pluginPlatform.installCount", { count: formatInstallCount(listingInstallCount(listing.plugin.id)) }) }}</span><buttonv-if="listing.plugin.source"type="button"@@ -2129,7 +2162,7 @@ onBeforeUnmount(() => {<h3 class="text-sm font-semibold">{{ t("pluginPlatform.pluginDetailsIntroduction") }}</h3><p class="whitespace-pre-wrap text-sm leading-6 text-muted-foreground">{{ selectedMarketplaceListing.description || t("pluginPlatform.noDescription") }}</p></section>- <div class="grid gap-3 text-xs @min-[40rem]:grid-cols-3">+ <div class="grid grid-cols-2 gap-3 text-xs @min-[40rem]:grid-cols-4"><div class="rounded-lg border p-3"><div class="text-muted-foreground">{{ t("pluginPlatform.pluginDetailsVersion") }}</div><div class="mt-1 font-medium">v{{ selectedMarketplaceListing.plugin.latestVersion }}</div>@@ -2142,6 +2175,10 @@ onBeforeUnmount(() => {<div class="text-muted-foreground">{{ t("pluginPlatform.pluginDetailsReleaseDate") }}</div><div class="mt-1 font-medium">{{ formatMarketplaceReleasedDate(selectedMarketplaceListing.latestVersionReleasedAt, appLocale) || "—" }}</div></div>+ <div class="rounded-lg border p-3">+ <div class="text-muted-foreground">{{ t("pluginPlatform.sortByInstalls") }}</div>+ <div class="mt-1 font-medium tabular-nums">{{ listingInstallCount(selectedMarketplaceListing.plugin.id) ? formatInstallCount(listingInstallCount(selectedMarketplaceListing.plugin.id)) : "—" }}</div>+ </div></div><div v-if="selectedMarketplaceListing.plugin.tags.length" class="flex flex-wrap gap-1.5"><Badge v-for="tag in selectedMarketplaceListing.plugin.tags" :key="tag" variant="outline" class="text-[11px]">{{ tag }}</Badge>diff --git a/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts b/apps/desktop/src/i18n/__tests__/featureMessages.spec.tsindex ad89416719..be5d0f22b7 100644--- a/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts+++ b/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts@@ -95,7 +95,7 @@ const FEATURE_MESSAGES: FeatureMessages[] = [{ feature: "SunDB bundled JDBC driver (#10732)", keys: ["connection.sundbCustomDriverHint"], translated: true },{ feature: "user administration Host change", keys: ["userAdmin.changeHost", "userAdmin.newHost"], translated: true },{ feature: "plugin batch actions", keys: ["pluginPlatform.batchDuplicateSources", "pluginPlatform.batchRefreshFailed"], locales: EXCEPT_AZ_TR },- { feature: "plugin marketplace sorting (#10078)", keys: under("pluginPlatform", ["sortBy", "sortByName", "sortByRecentlyUpdated", "sortByRecentlyListed", "sortByUpdatesFirst"]), locales: EXCEPT_AZ_TR, translated: true },+ { feature: "plugin marketplace sorting (#10078)", keys: under("pluginPlatform", ["sortBy", "sortByName", "sortByRecentlyUpdated", "sortByRecentlyListed", "sortByUpdatesFirst", "sortByInstalls", "installCount"]), locales: EXCEPT_AZ_TR, translated: true },{ feature: "shared refresh action (#8768)", keys: ["common.refresh"] },{feature: "Xugu field lineage scope and coverage",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 53f11a7470..13a2626990 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -547,6 +547,8 @@ export default {sortByRecentlyUpdated: "Recently updated",sortByRecentlyListed: "Recently published",sortByUpdatesFirst: "Updates first",+ sortByInstalls: "Installs",+ installCount: "{count} installs",allRepositories: "All repositories",marketplaceGuideTitle: "Plugins are maintained by community developers",marketplaceGuideDescription: "For plugin issues or feature requests, please open an issue in the plugin's own repository (use the source repository link on the plugin card); the main DBX repository only handles issues with the app itself.",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex c8b558239b..7ebfdebcd9 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -405,6 +405,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "Actualizados recientemente",sortByRecentlyListed: "Publicados recientemente",sortByUpdatesFirst: "Actualizaciones primero",+ sortByInstalls: "Instalaciones",+ installCount: "{count} instalaciones",allRepositories: "Todos los repositorios",marketplaceGuideTitle: "Los plugins los mantienen desarrolladores de la comunidad",marketplaceGuideDescription: "Para problemas o sugerencias sobre un plugin, abre una issue en el repositorio del propio plugin (usa el enlace del repositorio de origen en la tarjeta); el repositorio principal de DBX solo atiende problemas de la propia aplicación.",diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex f0157a30fd..dfed7a9142 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -180,6 +180,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "Baru diperbarui",sortByRecentlyListed: "Baru dipublikasikan",sortByUpdatesFirst: "Pembaruan lebih dulu",+ sortByInstalls: "Instalasi",+ installCount: "{count} instalasi",allRepositories: "Semua repositori",marketplaceGuideTitle: "Plugin dikelola oleh pengembang komunitas",marketplaceGuideDescription: "Untuk masalah plugin atau permintaan fitur, silakan buka issue di repositori plugin itu sendiri (gunakan tautan repositori sumber pada kartu plugin); repositori utama DBX hanya menangani masalah aplikasinya sendiri.",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 56800e80ba..e935faaa07 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -403,6 +403,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "Aggiornati di recente",sortByRecentlyListed: "Pubblicati di recente",sortByUpdatesFirst: "Prima gli aggiornamenti",+ sortByInstalls: "Installazioni",+ installCount: "{count} installazioni",allRepositories: "Tutti i repository",marketplaceGuideTitle: "I plugin sono mantenuti dagli sviluppatori della community",marketplaceGuideDescription: "Per problemi o suggerimenti su un plugin, apri una issue nel repository del plugin stesso (usa il link del repository sorgente sulla scheda); il repository principale di DBX gestisce solo i problemi dell'applicazione.",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex c3bcb3cb45..3b1ebe9790 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -404,6 +404,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "最近の更新",sortByRecentlyListed: "最近の公開",sortByUpdatesFirst: "更新ありを優先",+ sortByInstalls: "インストール数",+ installCount: "{count} 回インストール",allRepositories: "すべてのリポジトリ",marketplaceGuideTitle: "プラグインはコミュニティ開発者がメンテナンスしています",marketplaceGuideDescription: "プラグインの問題や機能要望は、プラグインカードのソースリポジトリリンクから該当リポジトリに Issue を投稿してください。DBX メインリポジトリはアプリ本体の問題のみを受け付けています。",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex d9d2d212fe..08ec61786d 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -402,6 +402,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "최근 업데이트",sortByRecentlyListed: "최근 등록",sortByUpdatesFirst: "업데이트 우선",+ sortByInstalls: "설치 수",+ installCount: "설치 {count}회",allRepositories: "모든 저장소",marketplaceGuideTitle: "플러그인은 커뮤니티 개발자가 유지 관리합니다",marketplaceGuideDescription: "플러그인 문제나 기능 제안은 플러그인 카드의 소스 저장소 링크를 통해 해당 저장소에 Issue를 등록해 주세요. DBX 메인 저장소는 앱 자체의 문제만 처리합니다.",diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.tsindex f6fa5862f5..f187bf3ab5 100644--- a/apps/desktop/src/i18n/locales/pl.ts+++ b/apps/desktop/src/i18n/locales/pl.ts@@ -270,6 +270,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "Ostatnio aktualizowane",sortByRecentlyListed: "Ostatnio opublikowane",sortByUpdatesFirst: "Najpierw aktualizacje",+ sortByInstalls: "Instalacje",+ installCount: "{count} instalacji",allRepositories: "Wszystkie repozytoria",marketplaceGuideTitle: "Wtyczki są rozwijane przez społeczność",marketplaceGuideDescription: "Błędy i propozycje zmian wtyczek zgłaszaj w repozytorium danej wtyczki (link na jej karcie). Główne repozytorium DBX służy do zgłoszeń dotyczących samej aplikacji.",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 6382ae9ae4..9ceb6d4daf 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -404,6 +404,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "Atualizados recentemente",sortByRecentlyListed: "Publicados recentemente",sortByUpdatesFirst: "Atualizações primeiro",+ sortByInstalls: "Instalações",+ installCount: "{count} instalações",allRepositories: "Todos os repositórios",marketplaceGuideTitle: "Os plugins são mantidos por desenvolvedores da comunidade",marketplaceGuideDescription: "Para problemas ou sugestões sobre um plugin, abra uma issue no repositório do próprio plugin (use o link do repositório de origem no cartão); o repositório principal do DBX trata apenas de problemas do próprio aplicativo.",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex b0134f479e..f05d46df3e 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -372,6 +372,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "Недавно обновлённые",sortByRecentlyListed: "Недавно опубликованные",sortByUpdatesFirst: "Сначала с обновлениями",+ sortByInstalls: "По установкам",+ installCount: "{count} установок",allRepositories: "Все репозитории",marketplaceGuideTitle: "Плагины поддерживаются сообществом разработчиков",marketplaceGuideDescription: "По вопросам о плагинах или для запроса функций создайте issue в собственном репозитории плагина (ссылка на исходный репозиторий есть на карточке плагина); основной репозиторий DBX принимает только вопросы о самом приложении.",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex 222815d1cd..898a2c364a 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -507,6 +507,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "อัปเดตล่าสุด",sortByRecentlyListed: "เผยแพร่ล่าสุด",sortByUpdatesFirst: "อัปเดตก่อน",+ sortByInstalls: "จำนวนการติดตั้ง",+ installCount: "ติดตั้ง {count} ครั้ง",allRepositories: "Repository ทั้งหมด",marketplaceGuideTitle: "Plugin ดูแลโดยนักพัฒนาชุมชน",marketplaceGuideDescription: "สำหรับปัญหาหรือคำขอฟีเจอร์ของ Plugin โปรดเปิด issue ใน Repository ของ Plugin เอง (ใช้ลิงก์ Source repository บนการ์ด Plugin) Repository หลักของ DBX รับเฉพาะปัญหาที่ตัวแอปเอง",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex e1d426866b..942946a946 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -492,6 +492,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "最近更新",sortByRecentlyListed: "最近上架",sortByUpdatesFirst: "有更新优先",+ sortByInstalls: "安装量",+ installCount: "{count} 次安装",allRepositories: "全部仓库",marketplaceGuideTitle: "插件由社区开发者维护",marketplaceGuideDescription: "插件问题或功能建议请通过插件卡片上的源码仓库入口,前往对应插件仓库提交 Issue;DBX 主仓库仅受理应用本身的问题。",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex af8435bf4b..3e822f6d86 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -405,6 +405,8 @@ export default withEnglishFallback({sortByRecentlyUpdated: "最近更新",sortByRecentlyListed: "最近上架",sortByUpdatesFirst: "有更新優先",+ sortByInstalls: "安裝量",+ installCount: "{count} 次安裝",allRepositories: "全部倉庫",marketplaceGuideTitle: "外掛由社群開發者維護",marketplaceGuideDescription: "外掛問題或功能建議請透過外掛卡片上的原始碼倉庫入口,前往對應外掛倉庫提交 Issue;DBX 主倉庫僅受理應用程式本身的問題。",diff --git a/apps/desktop/src/lib/plugins/pluginMarketplace.spec.ts b/apps/desktop/src/lib/plugins/pluginMarketplace.spec.tsindex 1c5f80c4a4..eb1de27122 100644--- a/apps/desktop/src/lib/plugins/pluginMarketplace.spec.ts+++ b/apps/desktop/src/lib/plugins/pluginMarketplace.spec.ts@@ -1,9 +1,10 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import {buildInstalledUpdateIndex,buildMarketplacePluginListings,compareVersions,extractRepositoryBaseUrl,+ fetchPluginInstallCounts,filterMarketplacePluginListings,formatMarketplaceReleasedDate,marketplaceHomepageUrl,@@ -422,4 +423,44 @@ describe("sortMarketplacePluginListings", () => {expect(displayedTimes(updatesFirst)).toEqual([Date.parse("2025-01-01T00:00:00Z"), Date.parse("2026-06-01T00:00:00Z")]);expect(ids(sortMarketplacePluginListings(listings, "name"))).toEqual(["a.alpha", "b.zulu"]);});++ it("sorts by install count descending and sinks plugins with no positive count", () => {+ const catalog = datedCatalog([+ { id: "c.none", name: "Gamma", latestVersion: "1.0.0", versions: [{ version: "1.0.0" }] },+ { id: "a.few", name: "Alpha", latestVersion: "1.0.0", versions: [{ version: "1.0.0" }] },+ { id: "b.many", name: "Beta", latestVersion: "1.0.0", versions: [{ version: "1.0.0" }] },+ { id: "d.tie", name: "Delta", latestVersion: "1.0.0", versions: [{ version: "1.0.0" }] },+ ]);+ const listings = buildMarketplacePluginListings([catalog], [], "en");++ expect(ids(sortMarketplacePluginListings(listings, "installs", { "b.many": 40, "a.few": 3, "d.tie": 3, "c.none": 0 }))).toEqual(["b.many", "a.few", "d.tie", "c.none"]);+ expect(ids(sortMarketplacePluginListings(listings, "installs"))).toEqual(["a.few", "b.many", "d.tie", "c.none"]);+ });+});++describe("fetchPluginInstallCounts", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("keeps positive finite counts for valid plugin ids", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ installs: { "io.dbx.ssh": 12, "not an id": 4, "io.dbx.zero": 0, "io.dbx.nan": Number.NaN, "io.dbx.text": "9" } }),+ }),+ );++ await expect(fetchPluginInstallCounts()).resolves.toEqual({ "io.dbx.ssh": 12 });+ });++ it("returns null when the endpoint fails or the payload is malformed", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: false }));+ await expect(fetchPluginInstallCounts()).resolves.toBeNull();++ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }));+ await expect(fetchPluginInstallCounts()).resolves.toBeNull();++ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("offline")));+ await expect(fetchPluginInstallCounts()).resolves.toBeNull();+ });});diff --git a/apps/desktop/src/lib/plugins/pluginMarketplace.ts b/apps/desktop/src/lib/plugins/pluginMarketplace.tsindex 90917a575f..f4a1050d1c 100644--- a/apps/desktop/src/lib/plugins/pluginMarketplace.ts+++ b/apps/desktop/src/lib/plugins/pluginMarketplace.ts@@ -3,7 +3,34 @@ import { uuid } from "@/lib/common/utils";export type MarketplacePluginStatus = "install" | "installed" | "update" | "unsupported";-export type MarketplacePluginSortMode = "name" | "recently-updated" | "recently-listed" | "updates-first";+export type MarketplacePluginSortMode = "name" | "installs" | "recently-updated" | "recently-listed" | "updates-first";++const PLUGIN_STATS_URL = "https://dbxio.com/api/plugins/stats";+const PLUGIN_STATS_ID_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;++export type PluginInstallCounts = Record<string, number>;++// Public install counters from the marketplace stats worker (install beacons,+// not raw artifact downloads). Failure is decorative: the store still renders.+export async function fetchPluginInstallCounts(init?: RequestInit): Promise<PluginInstallCounts | null> {+ try {+ const response = await fetch(PLUGIN_STATS_URL, {+ headers: { Accept: "application/json" },+ signal: AbortSignal.timeout(8000),+ ...init,+ });+ if (!response.ok) return null;+ const payload = (await response.json()) as { installs?: unknown };+ if (typeof payload !== "object" || payload === null || typeof payload.installs !== "object" || payload.installs === null) return null;+ const installs: PluginInstallCounts = {};+ for (const [id, value] of Object.entries(payload.installs as Record<string, unknown>)) {+ if (PLUGIN_STATS_ID_PATTERN.test(id) && typeof value === "number" && Number.isFinite(value) && value > 0) installs[id] = value;+ }+ return installs;+ } catch {+ return null;+ }+}export const UNIVERSAL_PLUGIN_TARGET = "universal";@@ -288,11 +315,20 @@ function firstReleaseTime(listing: MarketplacePluginListing): number {return times.length ? Math.min(...times) : Number.NEGATIVE_INFINITY;}+function listingInstallCount(listing: MarketplacePluginListing, installs: Readonly<Record<string, number>> | undefined): number {+ const value = installs?.[listing.plugin.id];+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;+}+// Copies before sorting: the builder output is also consumed elsewhere (batch selection,// the installed-tab update index) and must keep its name order there.-export function sortMarketplacePluginListings(listings: readonly MarketplacePluginListing[], mode: MarketplacePluginSortMode): MarketplacePluginListing[] {+// `installs` is the public stats map keyed by plugin id; missing counts sort last.+export function sortMarketplacePluginListings(listings: readonly MarketplacePluginListing[], mode: MarketplacePluginSortMode, installs?: Readonly<Record<string, number>>): MarketplacePluginListing[] {const byName = (left: MarketplacePluginListing, right: MarketplacePluginListing) => left.name.localeCompare(right.name);if (mode === "name") return [...listings].sort(byName);+ if (mode === "installs") {+ return [...listings].sort((left, right) => listingInstallCount(right, installs) - listingInstallCount(left, installs) || byName(left, right));+ }const releaseTimeFor = mode === "recently-listed" ? firstReleaseTime : latestVersionReleaseTime;if (mode === "updates-first") {return [...listings].sort((left, right) => {