diff --git a/astrbot/core/star/plugin_categories.py b/astrbot/core/star/plugin_categories.py new file mode 100644 index 00000000000..27d946f25a4 --- /dev/null +++ b/astrbot/core/star/plugin_categories.py @@ -0,0 +1,51 @@ +"""Recommended plugin categories that plugins may declare in ``metadata.yaml``. + +A category is an optional, free-form hint. The values below are the ones the +plugin market, the WebUI and the runtime know how to label and order, and a +plugin may declare something else: the declared value is normalized to a slug +either way, so one typo or one niche category cannot block a plugin from loading, +installing or updating. Display code derives labels from the slug and falls back +to the words of the slug itself. +""" + +from __future__ import annotations + +import re + +RECOMMENDED_PLUGIN_CATEGORIES: tuple[str, ...] = ( + "utility", + "ai_context", + "entertainment", + "game", + "media", + "productivity", + "integration", + "platform_adapter", + "provider_adapter", + "other", +) +"""Recommended ``metadata.yaml`` ``category`` values, in display order.""" + + +def normalize_plugin_category(value: object) -> str | None: + """Normalize the optional category declared by plugin metadata. + + Any value is accepted. A value outside ``RECOMMENDED_PLUGIN_CATEGORIES`` is + kept as declared instead of being rejected or rewritten, because the + vocabulary is a recommendation for plugin authors rather than a constraint + the runtime enforces. + + Args: + value: Raw ``category`` value read from ``metadata.yaml``. + + Returns: + The normalized slug, or ``None`` when the plugin declares no category or + declares something that is not a string. + """ + if not isinstance(value, str): + return None + + # Collapse separator runs so that "AI - Context", "ai-context" and + # "ai_context" reach the WebUI as one slug. + slug = re.sub(r"[\s-]+", "_", value.strip().lower()) + return slug or None diff --git a/astrbot/core/star/star.py b/astrbot/core/star/star.py index 1fe3a48674f..1b8f10b3846 100644 --- a/astrbot/core/star/star.py +++ b/astrbot/core/star/star.py @@ -77,6 +77,15 @@ class StarMetadata: views: list[ViewSpec] = field(default_factory=list) """插件注册的 Views 元数据。""" + # Appended last on purpose: StarMetadata is constructed positionally by + # external consumers, so new fields must not shift existing ones. + category: str | None = None + """Optional marketplace category declared in metadata, normalized to a slug. + + Any declared value is kept as-is, so this is not limited to the recommended + vocabulary; ``None`` means the plugin declares no category. + """ + @property def plugin_id(self) -> str: p_name = (self.name or "unknown").lower().replace("/", "_") diff --git a/astrbot/core/star/star_manager.py b/astrbot/core/star/star_manager.py index 57d80efb659..0eeb67b809d 100644 --- a/astrbot/core/star/star_manager.py +++ b/astrbot/core/star/star_manager.py @@ -52,6 +52,7 @@ from .context import Context from .error_messages import format_plugin_error from .filter.permission import COMMAND_PERMISSION_TYPES, PermissionTypeFilter +from .plugin_categories import normalize_plugin_category from .star import star_map, star_registry from .star_handler import EventType, star_handlers_registry from .updater import PLUGIN_METADATA_FILENAMES, _PluginUpdater @@ -561,6 +562,9 @@ def _load_plugin_metadata(plugin_path: str, plugin_obj=None) -> StarMetadata | N if isinstance(metadata.get("astrbot_version"), str) else None ), + # The category is an optional, free-form hint. Declaring an + # unknown value is normalized but never rejected. + category=normalize_plugin_category(metadata.get("category")), views=views, i18n=PluginManager._load_plugin_i18n(plugin_path), ) @@ -1202,6 +1206,7 @@ async def load( metadata.display_name = metadata_yaml.display_name metadata.support_platforms = metadata_yaml.support_platforms metadata.astrbot_version = metadata_yaml.astrbot_version + metadata.category = metadata_yaml.category metadata.views = metadata_yaml.views metadata.i18n = metadata_yaml.i18n except Exception as e: diff --git a/astrbot/dashboard/api/plugins.py b/astrbot/dashboard/api/plugins.py index 47e2f65caa6..9a579230704 100644 --- a/astrbot/dashboard/api/plugins.py +++ b/astrbot/dashboard/api/plugins.py @@ -12,6 +12,7 @@ from astrbot.api.web import PluginRequest, bind_request_context from astrbot.core import logger from astrbot.core.log import LogManager +from astrbot.core.star.plugin_categories import RECOMMENDED_PLUGIN_CATEGORIES from astrbot.dashboard.asgi_runtime import ( DashboardRequestState, call_request_view, @@ -623,7 +624,10 @@ async def list_plugin_market( async def list_plugin_market_categories( _auth: AuthContext = Depends(require_plugin_scope), ): - return ok({"categories": []}) + # Slugs only: display labels stay in the dashboard i18n bundles. This is the + # recommended vocabulary used to order the filter and to keep shared labels; + # plugins may declare any other category and the WebUI shows it as declared. + return ok({"categories": list(RECOMMENDED_PLUGIN_CATEGORIES)}) @router.get("/plugin-sources") diff --git a/astrbot/dashboard/services/plugin_service.py b/astrbot/dashboard/services/plugin_service.py index f880489995c..b2693339a46 100644 --- a/astrbot/dashboard/services/plugin_service.py +++ b/astrbot/dashboard/services/plugin_service.py @@ -660,6 +660,7 @@ def serialize_plugin_base( "logo": logo_url, "support_platforms": plugin.support_platforms, "astrbot_version": plugin.astrbot_version, + "category": plugin.category, "installed_at": installed_at, "i18n": plugin.i18n, "root_dir_name": plugin.root_dir_name, diff --git a/changelogs/unreleased.md b/changelogs/unreleased.md index ca797ace82c..27dd32e360b 100644 --- a/changelogs/unreleased.md +++ b/changelogs/unreleased.md @@ -1,6 +1,7 @@ # Unreleased - QQ Official: failed image uploads no longer log base64 payloads, avoiding dashboard freezes from oversized log entries. Retry attempts decrease from five to three, with one summary warning. +- Plugin market: plugins can now declare an optional marketplace category in `metadata.yaml`. The plugin API serves a ten-value recommended vocabulary (`utility`, `ai_context`, `entertainment`, `game`, `media`, `productivity`, `integration`, `platform_adapter`, `provider_adapter`, `other`) that orders the filter and supplies translated labels, but any other value is accepted as written: nothing warns, nothing is rewritten, and installation and updates are never blocked. The WebUI category filter also moved from the toolbar dropdown to a chip row above the plugin list (old entry: Extensions → Plugin Market → toolbar "Category" dropdown; new entry: Extensions → Plugin Market → category row above the list). - 「插件 → 管理行为 → 函数工具」现在只列出插件工具。Agent 运行时工具由配置文件的 AI 功能设置控制,MCP 工具可在「插件 → MCP」查看。 - Extensions → Handlers → Function Tools now lists plugin tools. Configure Agent runtime tools in the profile's AI capability settings and view MCP tools under Extensions → MCP Servers. diff --git a/dashboard/src/api/v1.ts b/dashboard/src/api/v1.ts index 8863c904009..db290c16934 100644 --- a/dashboard/src/api/v1.ts +++ b/dashboard/src/api/v1.ts @@ -1398,6 +1398,11 @@ export const pluginApi = { sources() { return typed(openApiV1.listPluginSources()); }, + marketCategories() { + return typed<{ categories: string[] }>( + openApiV1.listPluginMarketCategories(), + ); + }, replaceSources(sources: OpenConfig[]) { return typed( openApiV1.replacePluginSources({ body: { sources: sources as any } }), diff --git a/dashboard/src/i18n/locales/en-US/features/extension.json b/dashboard/src/i18n/locales/en-US/features/extension.json index e17999203e1..42101a8cd8a 100644 --- a/dashboard/src/i18n/locales/en-US/features/extension.json +++ b/dashboard/src/i18n/locales/en-US/features/extension.json @@ -142,15 +142,20 @@ }, "market": { "recommended": "🥳 Recommended", - "allPlugins": "📦 All Extensions", - "category": "Category", + "expandCategories": "Show all categories", + "collapseCategories": "Collapse categories", + "refresh": "Refresh", "categories": { "all": "All", - "ai_tools": "AI Tools", + "utility": "Utility", + "ai_context": "AI Conversation", "entertainment": "Entertainment", + "game": "Game", + "media": "Media", "productivity": "Productivity", - "integrations": "Integrations", - "utilities": "Utilities", + "integration": "Integration", + "platform_adapter": "Platform Adapter", + "provider_adapter": "Provider Adapter", "other": "Other" }, "showFullName": "Full Name", diff --git a/dashboard/src/i18n/locales/ja-JP/features/extension.json b/dashboard/src/i18n/locales/ja-JP/features/extension.json index c8def6652db..ae3dabd9f15 100644 --- a/dashboard/src/i18n/locales/ja-JP/features/extension.json +++ b/dashboard/src/i18n/locales/ja-JP/features/extension.json @@ -142,15 +142,20 @@ }, "market": { "recommended": "🥳 おすすめ", - "allPlugins": "📦 すべてのプラグイン", - "category": "カテゴリ", + "expandCategories": "すべてのカテゴリを表示", + "collapseCategories": "カテゴリを折りたたむ", + "refresh": "更新", "categories": { "all": "すべて", - "ai_tools": "AI ツール", + "utility": "ユーティリティ", + "ai_context": "AI 会話", "entertainment": "エンターテインメント", + "game": "ゲーム", + "media": "メディア", "productivity": "生産性", - "integrations": "外部連携", - "utilities": "ユーティリティ", + "integration": "外部連携", + "platform_adapter": "プラットフォームアダプター", + "provider_adapter": "プロバイダーアダプター", "other": "その他" }, "showFullName": "正式名称", diff --git a/dashboard/src/i18n/locales/ru-RU/features/extension.json b/dashboard/src/i18n/locales/ru-RU/features/extension.json index e9467672400..48be31fecc7 100644 --- a/dashboard/src/i18n/locales/ru-RU/features/extension.json +++ b/dashboard/src/i18n/locales/ru-RU/features/extension.json @@ -142,15 +142,20 @@ }, "market": { "recommended": "🥳 Рекомендуем", - "allPlugins": "📦 Все плагины", - "category": "Категория", - "categories": { + "expandCategories": "Показать все категории", + "collapseCategories": "Свернуть категории", + "refresh": "Обновить", + "categories": { "all": "Все", - "ai_tools": "AI Tools", + "utility": "Утилиты", + "ai_context": "AI-диалог", "entertainment": "Развлечения", + "game": "Игры", + "media": "Медиа", "productivity": "Продуктивность", - "integrations": "Интеграции", - "utilities": "Утилиты", + "integration": "Интеграции", + "platform_adapter": "Адаптер платформы", + "provider_adapter": "Адаптер провайдера", "other": "Другое" }, "showFullName": "Полное имя", diff --git a/dashboard/src/i18n/locales/zh-CN/features/extension.json b/dashboard/src/i18n/locales/zh-CN/features/extension.json index dfd04a40c3f..fac1a23f6b6 100644 --- a/dashboard/src/i18n/locales/zh-CN/features/extension.json +++ b/dashboard/src/i18n/locales/zh-CN/features/extension.json @@ -142,15 +142,20 @@ }, "market": { "recommended": "🥳 推荐", - "allPlugins": "📦 全部插件", - "category": "分类", + "expandCategories": "展开全部分类", + "collapseCategories": "收起分类", + "refresh": "刷新", "categories": { "all": "全部", - "ai_tools": "AI 增强", + "utility": "实用工具", + "ai_context": "AI 对话", "entertainment": "娱乐", + "game": "游戏", + "media": "媒体", "productivity": "效率", - "integrations": "外部集成", - "utilities": "生活实用", + "integration": "外部集成", + "platform_adapter": "平台适配器", + "provider_adapter": "提供商适配器", "other": "其他" }, "showFullName": "完整名称", diff --git a/dashboard/src/views/extension/MarketPluginsTab.vue b/dashboard/src/views/extension/MarketPluginsTab.vue index f93f1a6277e..c8a59e4cab5 100644 --- a/dashboard/src/views/extension/MarketPluginsTab.vue +++ b/dashboard/src/views/extension/MarketPluginsTab.vue @@ -2,7 +2,14 @@ import MarketPluginCard from "@/components/extension/MarketPluginCard.vue"; import PluginSortControl from "@/components/extension/PluginSortControl.vue"; import defaultPluginIcon from "/favicon.svg"; -import { computed } from "vue"; +import { + computed, + nextTick, + onBeforeUnmount, + onMounted, + ref, + watchEffect, +} from "vue"; import { normalizeTextInput } from "@/utils/inputValue"; const props = defineProps({ @@ -168,11 +175,60 @@ const marketSortItems = computed(() => [ { title: tm("sort.updated"), value: "updated" }, ]); -const marketCategorySelectItems = computed(() => - marketCategoryItems.value.map((item) => ({ - title: `${item.label || ""} (${item.count || 0})`, - value: item.value, - })), +// One scrollable chip row at every width; a toggle expands it into wrapped rows +// when the categories do not fit on a single line. +const hasCategories = computed(() => marketCategoryItems.value.length > 0); + +const categoryChipsExpanded = ref(false); +const categoryChipsOverflow = ref(false); +const chipsRowEl = ref(null); + +const measureCategoryChips = () => { + const el = chipsRowEl.value; + if (!el) { + categoryChipsOverflow.value = false; + return; + } + // Only the collapsed row can overflow; keep the toggle visible while expanded. + if (categoryChipsExpanded.value) return; + categoryChipsOverflow.value = el.scrollWidth - el.clientWidth > 4; +}; + +const chipsToggleVisible = computed( + () => categoryChipsOverflow.value || categoryChipsExpanded.value, +); + +// The chip row hides its scrollbar, so a vertical wheel over it scrolls the row +// horizontally. While the row can scroll it also swallows the wheel, so reaching +// the end does not suddenly scroll the whole page; moving the pointer away gives +// the wheel back to the page. +const onCategoryChipsWheel = (event) => { + const el = chipsRowEl.value; + if (!el || categoryChipsExpanded.value) return; + const maxScroll = el.scrollWidth - el.clientWidth; + if (maxScroll <= 0) return; + if (Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return; + + const delta = event.deltaMode === 1 ? event.deltaY * 16 : event.deltaY; + el.scrollLeft = Math.max(0, Math.min(maxScroll, el.scrollLeft + delta)); + event.preventDefault(); +}; + +const toggleCategoryChips = () => { + categoryChipsExpanded.value = !categoryChipsExpanded.value; + if (!categoryChipsExpanded.value) void nextTick(measureCategoryChips); +}; + +watchEffect(() => { + // Re-measure when the vocabulary or the tab visibility changes. + void marketCategoryItems.value.length; + void activeTab.value; + if (hasCategories.value) void nextTick(measureCategoryChips); +}); + +onMounted(() => window.addEventListener("resize", measureCategoryChips)); +onBeforeUnmount(() => + window.removeEventListener("resize", measureCategoryChips), ); // Navigate with the unique market plugin key instead of the metadata name — @@ -233,6 +289,22 @@ const openMarketPluginDetail = (plugin) => { + + + + {
-
-
-

- {{ tm("market.allPlugins") }} -

+
+
+
+ +
- mdi-refresh + + {{ categoryChipsExpanded ? "mdi-chevron-up" : "mdi-chevron-down" }} +
-
- - +
{ } .market-header-row, -.market-header-primary, -.market-filter-group { +.market-header-primary { gap: 12px; } @@ -459,20 +539,76 @@ const openMarketPluginDetail = (plugin) => { min-width: 220px; } -.market-filter-group { +.market-category-row { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 10px; +} + +.market-category-row-sort { + flex: 0 0 auto; + margin-left: auto; +} + +.market-category-chips { + flex: 1 1 auto; + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.market-category-chips-scroll { + flex: 1 1 auto; + display: flex; + gap: 6px; + min-width: 0; + overflow-x: auto; + /* Pointer scrolling works through the wheel handler, so no scrollbar. */ + scrollbar-width: none; + -ms-overflow-style: none; +} + +.market-category-chips-scroll::-webkit-scrollbar { + display: none; +} + +.market-category-chips.is-expanded .market-category-chips-scroll { flex-wrap: wrap; + overflow: visible; } -.market-filter-control { - min-width: 190px; - max-width: 220px; +.market-category-chip { + flex: 0 0 auto; + padding: 4px 12px; + border: 1px solid rgba(var(--v-theme-on-surface), 0.16); + border-radius: 999px; + background: transparent; + color: rgba(var(--v-theme-on-surface), 0.75); + font-size: 0.8125rem; + white-space: nowrap; + cursor: pointer; +} + +.market-category-chip:hover { + background: rgba(var(--v-theme-on-surface), 0.05); +} + +.market-category-chip.is-active { + border-color: rgb(var(--v-theme-primary)); + background: rgb(var(--v-theme-primary)); + color: rgb(var(--v-theme-on-primary)); + font-weight: 600; +} + +.market-category-chip-count { + margin-left: 2px; + opacity: 0.7; } -.market-filter-control :deep(.v-field__input), -.market-filter-control :deep(.v-field-label), -.market-filter-control :deep(.v-select__selection-text), -.market-filter-control :deep(.v-field__prepend-inner) { - font-size: 0.875rem; +.market-category-chips-toggle { + flex: 0 0 auto; } @media (max-width: 700px) { @@ -494,28 +630,26 @@ const openMarketPluginDetail = (plugin) => { width: 100%; } - .market-filter-group { - align-items: stretch !important; - flex-direction: column; - width: 100%; + /* Small screens: categories keep the first line to themselves and the sort + control drops to a second line, keeping its natural width. */ + .market-category-row { + align-items: center; + flex-wrap: wrap; + column-gap: 6px; + row-gap: 12px; } - .market-filter-control { - max-width: none; - min-width: 0; - width: 100%; + .market-category-chips { + flex: 1 1 100%; } - .market-filter-group :deep(.plugin-sort-control) { - flex-wrap: nowrap; - width: 100%; + .market-category-row-sort { + flex: 0 0 auto; + margin-left: 0; } - .market-filter-group :deep(.plugin-sort-control__select) { - flex: 1; - max-width: none; - min-width: 0; - width: auto; + .market-category-row-sort :deep(.plugin-sort-control) { + flex-wrap: nowrap; } .plugin-view-tab { diff --git a/dashboard/src/views/extension/PluginDetailPage.vue b/dashboard/src/views/extension/PluginDetailPage.vue index c29619c13de..31a67647679 100644 --- a/dashboard/src/views/extension/PluginDetailPage.vue +++ b/dashboard/src/views/extension/PluginDetailPage.vue @@ -161,9 +161,13 @@ const categoryDisplay = computed(() => { const category = String(rawCategory || "").trim(); if (!category) return ""; - const normalized = category.toLowerCase().replace(/\s+/g, "_"); + // Match the backend normalization so a hyphen or an underscore spelling of a + // recommended category still resolves to its label. An unlisted value is + // allowed and has no label, so show it as the author declared it instead of + // the missing-translation marker. + const normalized = category.toLowerCase().replace(/[\s-]+/g, "_"); const label = tm(`market.categories.${normalized}`); - return label === `market.categories.${normalized}` ? category : label; + return label.includes("[MISSING:") ? category : label; }); const authorWebsite = computed(() => { diff --git a/dashboard/src/views/extension/useExtensionPage.js b/dashboard/src/views/extension/useExtensionPage.js index 6710c16c268..9cab5d530b1 100644 --- a/dashboard/src/views/extension/useExtensionPage.js +++ b/dashboard/src/views/extension/useExtensionPage.js @@ -213,9 +213,25 @@ export const useExtensionPage = (initialTab = "installed") => { const sortOrder = ref("desc"); // desc (降序) or asc (升序) const randomPluginNames = ref([]); const marketCategoryFilter = ref("all"); + // Recommended slug order served by the backend; empty until it loads. It + // only prioritizes and labels the filter, never validates a declared value. + const marketCategorySlugs = ref([]); // 插件市场拼音搜索 + const loadMarketCategories = async () => { + try { + const res = await pluginApi.marketCategories(); + const slugs = res.data?.data?.categories; + marketCategorySlugs.value = Array.isArray(slugs) + ? slugs.map((slug) => String(slug || "").trim()).filter(Boolean) + : []; + } catch (error) { + console.warn("Failed to load plugin market categories:", error); + marketCategorySlugs.value = []; + } + }; + const normalizeMarketCategory = (rawCategory) => { const normalized = String(rawCategory || "") .trim() @@ -223,31 +239,19 @@ export const useExtensionPage = (initialTab = "installed") => { if (!normalized) { return "other"; } + // The backend vocabulary is a recommendation, not a whitelist: a plugin may + // declare any category, so a discovered value keeps its own filter entry + // instead of being folded into "other". return normalized.replace(/[\s-]+/g, "_"); }; - const getMarketCategoryLabel = (key, rawCategory = "") => { - const fallbackMap = { - all: "All", - ai_tools: "AI Tools", - entertainment: "Entertainment", - productivity: "Productivity", - integrations: "Integrations", - utilities: "Utilities", - other: "Other", - }; - const i18nKey = `market.categories.${key}`; - const translated = tm(i18nKey); + const getMarketCategoryLabel = (key) => { + const translated = tm(`market.categories.${key}`); if (translated && !translated.includes("[MISSING:")) { return translated; } - if (fallbackMap[key]) { - return fallbackMap[key]; - } - const normalizedRaw = String(rawCategory || "").trim(); - if (normalizedRaw) { - return normalizedRaw; - } + // A missing label still renders as words instead of the raw identifier, so + // an ad-hoc marketplace category never shows up as a slug. return key .split(/[_-]+/) .filter(Boolean) @@ -265,10 +269,7 @@ export const useExtensionPage = (initialTab = "installed") => { categoryData.count += 1; continue; } - categories.set(categoryKey, { - count: 1, - rawLabel: String(plugin?.category || "").trim(), - }); + categories.set(categoryKey, { count: 1 }); } return categories; @@ -294,13 +295,24 @@ export const useExtensionPage = (initialTab = "installed") => { }, ]; - for (const [ - categoryKey, - categoryData, - ] of marketCategoryMeta.value.entries()) { + // Recommended categories lead in the backend order so the filter reads the + // same everywhere, then whatever else plugins declared follows in discovery + // order: a custom category must stay reachable, not disappear. + const orderedKeys = [...marketCategorySlugs.value]; + for (const categoryKey of marketCategoryMeta.value.keys()) { + if (!orderedKeys.includes(categoryKey)) { + orderedKeys.push(categoryKey); + } + } + + for (const categoryKey of orderedKeys) { + const categoryData = marketCategoryMeta.value.get(categoryKey); + if (!categoryData) { + continue; + } items.push({ value: categoryKey, - label: getMarketCategoryLabel(categoryKey, categoryData.rawLabel), + label: getMarketCategoryLabel(categoryKey), count: categoryData.count, }); } @@ -2366,6 +2378,10 @@ export const useExtensionPage = (initialTab = "installed") => { } loading_.value = true; try { + // Not awaited: the category vocabulary only refines ordering and the + // unknown-slug fallback, so a slow or stalled request must not hold back + // the plugin lists (the filter reacts to the ref once it arrives). + void loadMarketCategories(); await getExtensions({ withLoading: false }); // 检查是否有 open_config 参数 diff --git a/docs/en/dev/plugin-market/2026-06-27.md b/docs/en/dev/plugin-market/2026-06-27.md index 788b893c003..d046e252e23 100644 --- a/docs/en/dev/plugin-market/2026-06-27.md +++ b/docs/en/dev/plugin-market/2026-06-27.md @@ -158,6 +158,10 @@ Each `PluginRecord` MUST contain: | `stars` | integer | Non-negative star count or ranking signal. | | `download_count` | integer | Non-negative download count. | +The `category` value comes from the same field declared in the plugin repository's `metadata.yaml`. Recommended values are listed under [Declare Plugin Category](../star/plugin-new.md#declare-plugin-category-optional), but the field is optional and free-form: the marketplace copies the normalized declared value and leaves it empty when the plugin declares none. + +When adding or updating a plugin record, index maintainers read `category` from that plugin repository's `metadata.yaml` and write the normalized slug (underscore form, such as `platform_adapter`) into the index `category` field. `metadata.yaml` stays the single authoritative source: the index holds a snapshot copied when the record was collected, so a disagreement means the snapshot is stale and the marketplace keeps showing the previous category until the index is collected again. Installed plugins in the runtime and the WebUI always read `metadata.yaml` directly and ignore the index. + ### 7.1. Repository URL `repo` MUST be one of: diff --git a/docs/en/dev/star/plugin-new.md b/docs/en/dev/star/plugin-new.md index df6a03de68f..55dfd109939 100644 --- a/docs/en/dev/star/plugin-new.md +++ b/docs/en/dev/star/plugin-new.md @@ -1,5 +1,9 @@ --- outline: deep +head: + - - style + - {} + - '.vp-doc table:has(thead th:nth-child(3)) th:nth-child(-n + 2), .vp-doc table:has(thead th:nth-child(3)) td:nth-child(-n + 2) { white-space: nowrap; }' --- # AstrBot Plugin Development Guide 🌠 @@ -143,6 +147,29 @@ If you only want to declare a minimum version, use: If the current AstrBot version does not satisfy this range, the plugin will be blocked from loading with a compatibility error. In the WebUI installation flow, you can choose to "Ignore Warning and Install" to bypass this check. +### Declare Plugin Category (Optional) + +You can add a `category` field in `metadata.yaml` to declare the marketplace category of your plugin. The WebUI and the runtime read this field directly; the marketplace shows the category captured in the index snapshot. + +```yaml +category: platform_adapter +``` + +The identifiers below are the recommended categories. + +| Recommended identifier | English label | Use it for | +| --- | --- | --- | +| `utility` | Utility | General tools and everyday lookups | +| `ai_context` | AI Conversation | Enhancements around conversation and AI capabilities | +| `entertainment` | Entertainment | General fun and in-chat games | +| `game` | Game | Connecting to an external game | +| `media` | Media | Processing and generating images, audio and video | +| `productivity` | Productivity | To-dos, schedules, notes and personal workflows | +| `integration` | Integration | Wiring a third-party platform or account | +| `platform_adapter` | Platform Adapter | New messaging platforms or protocols | +| `provider_adapter` | Provider Adapter | New model, speech or embedding services | +| `other` | Other | Anything that does not fit the categories above | + ### Debugging Plugins AstrBot uses a runtime plugin injection mechanism. Therefore, when debugging plugins, you need to start the AstrBot main application. diff --git a/docs/en/dev/star/plugin-publish.md b/docs/en/dev/star/plugin-publish.md index e2fcd7126ea..2252150fff7 100644 --- a/docs/en/dev/star/plugin-publish.md +++ b/docs/en/dev/star/plugin-publish.md @@ -12,22 +12,25 @@ Here is a complete plugin metadata example (`metadata.yaml`) that the system wil ```yaml name: astrbot_plugin_example # Plugin identifier, English, unique -display_name: Plugin Display Name # Plugin display name +display_name: Plugin Display Name # (Optional) Plugin display name # short_desc: A one-line summary of your plugin # (Optional) Short description for compact UI desc: Detailed description of your plugin's features, usage, etc. # Detailed plugin description Supports multi-line text with Markdown formatting. version: 1.0.0 # Plugin version (follow semantic versioning) author: Author Name # Author name repo: https://github.com/your-name/repo # Plugin repository URL +# category: other # (Optional) Marketplace category # astrbot_version: ">=4.17.0" # (Optional) AstrBot version range # support_platforms: # (Optional) Supported platform adapter list # - aiocqhttp # - qq_official # social_link: https://github.com/your-web # (Optional) Your personal website, GitHub profile, etc. -# tags: # (Optional) Tag list for marketplace categorization and search +# tags: # (Optional) Tag list, matched by marketplace search # - example ``` +[Recommended marketplace categories](plugin-new.md#declare-plugin-category-optional) + [Supported platform adapters](plugin-new.md#declare-supported-platforms-optional) ::: warning Size Limit diff --git a/docs/en/use/plugin.md b/docs/en/use/plugin.md index 268876463f2..afdb9ee55df 100644 --- a/docs/en/use/plugin.md +++ b/docs/en/use/plugin.md @@ -43,7 +43,7 @@ The same workspace has **Skills**, **MCP Servers**, and **Handlers** tabs for sk ### 2. Choose a suitable plugin -Search by plugin name or a keyword describing the feature you want. You can also filter by categories such as AI enhancement, entertainment, productivity, integrations, utilities, and others. Open a plugin's details and check: +Search by plugin name or a keyword describing the feature you want. You can also filter by category: each entry in the category row comes from the category a plugin declares in its `metadata.yaml` (AI Conversation, Entertainment, Game, Media, Productivity, Integration, Utility and Other are the recommended ones; a plugin that declares another value appears under that value), and selecting one shows only that category. Use the arrow on the right when the categories overflow (the category dropdown that used to sit in the toolbar has moved to this row above the list). Open a plugin's details and check: - **Features and usage**: whether it meets your needs and whether you use it through commands, natural language, or another trigger. - **Supported platforms**: whether it works with your messaging platform. Some features depend on platform-specific APIs. diff --git a/docs/zh/dev/plugin-market/2026-06-27.md b/docs/zh/dev/plugin-market/2026-06-27.md index 0f2957c88fe..95b745b084b 100644 --- a/docs/zh/dev/plugin-market/2026-06-27.md +++ b/docs/zh/dev/plugin-market/2026-06-27.md @@ -158,6 +158,10 @@ metadata.author + "/" + metadata.name | `stars` | integer | 非负 star 数或排序信号。 | | `download_count` | integer | 非负下载数。 | +`category` 的来源是插件仓库 `metadata.yaml` 中的同名声明字段。推荐取值见[声明插件分类](../star/plugin-new.md#声明插件分类-可选),但字段本身是可选、自由填写的:市场收录时直接复制归一化后的值,未声明时为空。 + +索引维护者在收录或更新一条插件记录时,需要读取该插件仓库 `metadata.yaml` 中的 `category`,把归一化后的 slug(下划线形式,如 `platform_adapter`)写入索引的 `category` 字段。`metadata.yaml` 是分类的唯一权威来源,索引里的 `category` 只是收录时复制的快照;两者不一致说明索引尚未随声明更新(快照过期),此时市场会继续显示旧分类,直到索引重新收录。运行时与 WebUI 中的已安装插件始终直接读取 `metadata.yaml`,不受索引影响。 + ### 7.1. 仓库 URL `repo` 必须是以下之一: diff --git a/docs/zh/dev/star/plugin-new.md b/docs/zh/dev/star/plugin-new.md index cd052f6eaa4..3d68a457401 100644 --- a/docs/zh/dev/star/plugin-new.md +++ b/docs/zh/dev/star/plugin-new.md @@ -1,5 +1,9 @@ --- outline: deep +head: + - - style + - {} + - '.vp-doc table:has(thead th:nth-child(3)) th:nth-child(-n + 2), .vp-doc table:has(thead th:nth-child(3)) td:nth-child(-n + 2) { white-space: nowrap; }' --- # AstrBot 插件开发指南 🌠 @@ -90,7 +94,7 @@ your_plugin/ 这种情况下 Skill 名称会使用插件目录名。插件提供的 Skill 由插件管理,在 WebUI 的 `插件 → 技能` 页面中作为只读来源展示;可以启用或禁用,但不能从本地 Skills 页面删除或编辑。插件卸载或更新后,对应 Skill 会随插件文件变化。 -### 声明支持平台(Optional) +### 声明支持平台(可选) 你可以在 `metadata.yaml` 中新增 `support_platforms` 字段(`list[str]`),声明插件支持的平台适配器。WebUI 插件页会展示该字段。 @@ -122,7 +126,7 @@ support_platforms: - `matrix` - `mattermost` -### 声明 AstrBot 版本范围(Optional) +### 声明 AstrBot 版本范围(可选) 你可以在 `metadata.yaml` 中新增 `astrbot_version` 字段,声明插件要求的 AstrBot 版本范围。格式与 `pyproject.toml` 依赖版本约束一致(PEP 440),且不要加 `v` 前缀。 @@ -143,6 +147,29 @@ astrbot_version: ">=4.16,<5" 当当前 AstrBot 版本不满足该范围时,插件会被阻止加载并提示版本不兼容。 在 WebUI 安装插件时,你可以选择“无视警告,继续安装”来跳过这个检查。 +### 声明插件分类(可选) + +你可以在 `metadata.yaml` 中新增 `category` 字段,主动声明插件的市场分类。WebUI 与运行时直接读取该字段,市场里展示的分类取自索引快照。 + +```yaml +category: platform_adapter +``` + +下表是推荐使用的分类标识。 + +| 推荐标识 | 中文翻译 | 适用插件 | +| --- | --- | --- | +| `utility` | 实用工具 | 通用小工具与生活信息查询 | +| `ai_context` | AI 对话 | 围绕对话与 AI 能力的增强 | +| `entertainment` | 娱乐 | 泛娱乐与群内小游戏 | +| `game` | 游戏 | 连接外部游戏 | +| `media` | 媒体 | 图片、音频、视频的处理与生成 | +| `productivity` | 效率 | 待办、日程、笔记与个人工作流 | +| `integration` | 外部集成 | 打通第三方平台或服务账号 | +| `platform_adapter` | 平台适配器 | 接入新的消息平台或协议 | +| `provider_adapter` | 提供商适配器 | 接入新的模型、语音或向量服务 | +| `other` | 其他 | 无法归入以上任一类的插件 | + ### 调试插件 AstrBot 采用在运行时注入插件的机制。因此,在调试插件时,需要启动 AstrBot 本体。 diff --git a/docs/zh/dev/star/plugin-publish.md b/docs/zh/dev/star/plugin-publish.md index 2dc9c50fc46..db84bc45c65 100644 --- a/docs/zh/dev/star/plugin-publish.md +++ b/docs/zh/dev/star/plugin-publish.md @@ -12,23 +12,26 @@ AstrBot 使用 GitHub 托管插件,因此你需要先将插件代码推送到 ```yaml name: astrbot_plugin_example # 插件标识符,英文,唯一 -display_name: 示例插件名称 # 插件展示名称 +display_name: 示例插件名称 # (可选)插件展示名称 # short_desc: 一句话介绍你的插件功能 # (可选)紧凑 UI 使用的短描述 desc: 详细描述插件的功能、特性、使用方法等信息。 # 详细描述插件的信息 可以写多行文本,支持 Markdown 格式。 version: 1.0.0 # 插件版本号(遵循语义化版本规范) author: 作者名称 # 作者名称 repo: https://github.com/your-name/repo # 插件仓库地址 +# category: other # (可选)插件市场分类 # astrbot_version: ">=4.17.0" # (可选)支持的 AstrBot 版本范围 # support_platforms: # (可选)支持的平台适配器列表 # - aiocqhttp # - qq_official # social_link: https://github.com/your-web # (可选)你的个人网站、GitHub 主页等 -# tags: # (可选)标签列表,用于插件市场分类和搜索 +# tags: # (可选)标签列表,用于插件市场的搜索匹配 # - example ``` -[目前支持的平台适配器](plugin-new.md#声明支持平台-optional) +[推荐的插件市场分类](plugin-new.md#声明插件分类-可选) + +[目前支持的平台适配器](plugin-new.md#声明支持平台-可选) ::: warning 大小限制 发布到插件市场的插件压缩包(zip)大小**不得超过 16MB**。 diff --git a/docs/zh/dev/star/plugin.md b/docs/zh/dev/star/plugin.md index cb2bc8484fc..58a05a2e095 100644 --- a/docs/zh/dev/star/plugin.md +++ b/docs/zh/dev/star/plugin.md @@ -268,7 +268,7 @@ your_plugin/ 这种情况下 Skill 名称会使用插件目录名。插件提供的 Skill 由插件管理,在 WebUI 的 `插件 → 技能` 页面中作为只读来源展示;可以启用或禁用,但不能从本地 Skills 页面删除或编辑。插件卸载或更新后,对应 Skill 会随插件文件变化。 -### 声明支持平台(Optional) +### 声明支持平台(可选) 你可以在 `metadata.yaml` 中新增 `support_platforms` 字段(`list[str]`),声明插件支持的平台适配器。WebUI 插件页会展示该字段。 @@ -295,7 +295,7 @@ support_platforms: - `misskey` - `line` -### 声明 AstrBot 版本范围(Optional) +### 声明 AstrBot 版本范围(可选) 你可以在 `metadata.yaml` 中新增 `astrbot_version` 字段,声明插件要求的 AstrBot 版本范围。格式与 `pyproject.toml` 依赖版本约束一致(PEP 440),且不要加 `v` 前缀。 diff --git a/docs/zh/use/plugin.md b/docs/zh/use/plugin.md index e616d593b54..e51a29585ee 100644 --- a/docs/zh/use/plugin.md +++ b/docs/zh/use/plugin.md @@ -43,7 +43,7 @@ AstrBot 负责接收消息、连接模型、管理对话等基础工作;插件 ### 2. 找到合适的插件 -在市场搜索框中输入插件名称或功能关键词,也可以按 **AI 增强、娱乐、效率、外部集成、生活实用、其他** 分类筛选。点击感兴趣的插件查看详情,先确认: +在市场搜索框中输入插件名称或功能关键词,也可以按分类筛选:分类条上的每一项取自插件在 `metadata.yaml` 中声明的分类(推荐使用 AI 对话、娱乐、游戏、媒体、效率、外部集成、实用工具、其他;作者写别的值也会单独出现),点选其中一项即可只看该分类的插件,分类过多时可用右侧箭头展开(原先位于工具栏的「分类」下拉框,现已移到插件列表上方的分类条)。点击感兴趣的插件查看详情,先确认: - **功能和用法**:是否解决你的需求,安装后通过指令、自然语言还是其他方式使用。 - **支持平台**:是否支持你接入的消息平台。某些功能依赖特定平台的接口。 diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 8f61c3b7fd1..36d43dc0dc6 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -243,6 +243,7 @@ def registered_plugin_page(core_lifecycle_td: AstrBotCoreLifecycle, monkeypatch) display_name="Plugin Page Demo", root_dir_name=PLUGIN_PAGE_DEMO_NAME, activated=True, + category="tools", ) monkeypatch.setattr( @@ -1907,6 +1908,7 @@ async def test_plugin_get_excludes_scanned_pages( item for item in data["data"] if item["name"] == PLUGIN_PAGE_DEMO_NAME ) assert plugin["activated"] is True + assert plugin["category"] == "tools" assert "page" not in plugin assert "pages" in plugin assert isinstance(plugin["pages"], list) @@ -2573,6 +2575,7 @@ async def test_plugins( assert data["status"] == "ok" for plugin in data["data"]: assert "installed_at" in plugin + assert "category" in plugin assert "components" not in plugin installed_at = plugin["installed_at"] if installed_at is None: diff --git a/tests/test_fastapi_v1_dashboard.py b/tests/test_fastapi_v1_dashboard.py index e8232ffcec7..8f8abf8888a 100644 --- a/tests/test_fastapi_v1_dashboard.py +++ b/tests/test_fastapi_v1_dashboard.py @@ -23,6 +23,7 @@ import astrbot.dashboard.services.config_service as config_service import astrbot.dashboard.services.stat_service as stat_service from astrbot.core import file_token_service +from astrbot.core.star.plugin_categories import RECOMMENDED_PLUGIN_CATEGORIES from astrbot.core.utils import llm_metadata from astrbot.dashboard.api.app import create_dashboard_asgi_app from astrbot.dashboard.api.backups import download_backup as download_backup_route @@ -700,6 +701,7 @@ async def terminate_platform(platform_id: str) -> None: logo_path=None, support_platforms=[], astrbot_version="", + category=None, i18n={}, root_dir_name=None, star_handler_full_names=[], @@ -2361,6 +2363,25 @@ async def test_v1_plugins_accept_api_key( assert [item["name"] for item in data["data"]] == ["astrbot_plugin_demo"] +@pytest.mark.asyncio +async def test_v1_plugin_market_categories_lists_recommended_slugs( + asgi_client: httpx.AsyncClient, + fake_db: FakeDb, +): + raw_key = "abk_fastapi_v1_plugin_categories" + fake_db.add_api_key(raw_key, scopes=["plugin"]) + + response = await asgi_client.get( + "/api/v1/plugins/market/categories", + headers={"X-API-Key": raw_key}, + ) + + assert response.status_code == 200 + data = response.json() + assert data["status"] == "ok" + assert data["data"]["categories"] == list(RECOMMENDED_PLUGIN_CATEGORIES) + + @pytest.mark.asyncio async def test_v1_plugin_enabled_patch_calls_service( asgi_client: httpx.AsyncClient, diff --git a/tests/test_plugin_manager.py b/tests/test_plugin_manager.py index a580eebdbd2..74b1d71b296 100644 --- a/tests/test_plugin_manager.py +++ b/tests/test_plugin_manager.py @@ -2,6 +2,7 @@ import errno import functools import json +import logging import os import sys import tempfile @@ -199,6 +200,100 @@ def test_load_plugin_metadata_accepts_yml_suffix(tmp_path: Path): ) +def _write_plugin_category(plugin_path: Path, category: object) -> None: + metadata_path = plugin_path / "metadata.yaml" + metadata = yaml.safe_load(metadata_path.read_text(encoding="utf-8")) + metadata["category"] = category + metadata_path.write_text(yaml.dump(metadata), encoding="utf-8") + + +def test_load_plugin_metadata_includes_category(tmp_path: Path): + plugin_path = tmp_path / "helloworld" + _write_local_test_plugin(plugin_path, TEST_PLUGIN_REPO) + _write_plugin_category(plugin_path, "platform_adapter") + + loaded_metadata = PluginManager._load_plugin_metadata(str(plugin_path)) + + assert loaded_metadata is not None + assert loaded_metadata.category == "platform_adapter" + + +@pytest.mark.parametrize( + ("declared", "expected"), + [ + ("Platform Adapter", "platform_adapter"), + ("platform-adapter", "platform_adapter"), + # Repeated and mixed separators must normalize like the WebUI does. + ("AI - Context", "ai_context"), + (" provider adapter ", "provider_adapter"), + ], +) +def test_load_plugin_metadata_normalizes_category( + tmp_path: Path, declared: str, expected: str +): + plugin_path = tmp_path / "helloworld" + _write_local_test_plugin(plugin_path, TEST_PLUGIN_REPO) + _write_plugin_category(plugin_path, declared) + + loaded_metadata = PluginManager._load_plugin_metadata(str(plugin_path)) + + assert loaded_metadata is not None + assert loaded_metadata.category == expected + + +def test_load_plugin_metadata_keeps_unlisted_category(tmp_path: Path): + # The recommended vocabulary is a suggestion, so a plugin may declare a + # category that is not on the list; it must survive loading unchanged. + plugin_path = tmp_path / "helloworld" + _write_local_test_plugin(plugin_path, TEST_PLUGIN_REPO) + _write_plugin_category(plugin_path, "Not A Listed Category") + + loaded_metadata = PluginManager._load_plugin_metadata(str(plugin_path)) + + assert loaded_metadata is not None + assert loaded_metadata.category == "not_a_listed_category" + + +def test_load_plugin_metadata_without_category_is_none(tmp_path: Path): + plugin_path = tmp_path / "helloworld" + _write_local_test_plugin(plugin_path, TEST_PLUGIN_REPO) + + loaded_metadata = PluginManager._load_plugin_metadata(str(plugin_path)) + + assert loaded_metadata is not None + assert loaded_metadata.category is None + + +def test_validate_plugin_metadata_allows_unknown_category(caplog) -> None: + # A category typo must not warn or make a plugin uninstallable on update. + with caplog.at_level(logging.WARNING): + star_manager_module._PluginUpdater.validate_plugin_metadata( + { + "name": TEST_PLUGIN_NAME, + "author": "AstrBot Team", + "desc": "Local test plugin", + "version": "1.0.0", + "category": "not_a_category", + }, + "metadata.yaml", + ) + + assert "not_a_category" not in caplog.text + + +def test_load_plugin_metadata_does_not_warn_for_unknown_category(tmp_path, caplog): + plugin_path = tmp_path / "helloworld" + _write_local_test_plugin(plugin_path, TEST_PLUGIN_REPO) + _write_plugin_category(plugin_path, "not_a_category") + + with caplog.at_level(logging.WARNING): + loaded_metadata = PluginManager._load_plugin_metadata(str(plugin_path)) + + assert loaded_metadata is not None + assert loaded_metadata.category == "not_a_category" + assert "not_a_category" not in caplog.text + + def test_load_plugin_metadata_does_not_fallback_to_legacy_info( tmp_path: Path, ) -> None: @@ -935,6 +1030,62 @@ async def prepare(*args): terminate.assert_not_awaited() +@pytest.mark.asyncio +async def test_load_plugin_keeps_declared_category( + plugin_manager_pm: PluginManager, + local_updater: Path, + monkeypatch, + tmp_path: Path, +): + """Loading a plugin must keep the category declared in metadata.yaml.""" + _clear_star_runtime_state() + module_path = f"data.plugins.{TEST_PLUGIN_DIR}.main" + _write_plugin_category(local_updater, "entertainment") + (local_updater / "main.py").write_text( + "from astrbot.api.star import Star\nclass Main(Star):\n pass\n", + encoding="utf-8", + ) + monkeypatch.setattr( + plugin_manager_pm.context, "stars", star_manager_module.star_registry + ) + monkeypatch.setattr( + plugin_manager_pm, "reserved_plugin_path", str(tmp_path / "reserved") + ) + monkeypatch.setattr( + plugin_manager_pm, "plugin_config_path", str(tmp_path / "config") + ) + + async def global_get(key, default=None): + return default + + async def import_plugin(*, path, **kwargs): + if path not in sys.modules: + module = ModuleType(path) + sys.modules[path] = module + main_path = local_updater / "main.py" + exec( + compile(main_path.read_text(encoding="utf-8"), str(main_path), "exec"), + module.__dict__, + ) + return sys.modules[path] + + async def sync_command_configs(): + return None + + monkeypatch.setattr(star_manager_module.sp, "global_get", global_get) + monkeypatch.setattr( + star_manager_module, "sync_command_configs", sync_command_configs + ) + monkeypatch.setattr( + plugin_manager_pm, "_import_plugin_with_dependency_recovery", import_plugin + ) + + success, error = await plugin_manager_pm.load(specified_dir_name=TEST_PLUGIN_DIR) + + assert success, error + assert star_manager_module.star_map[module_path].category == "entertainment" + + @pytest.mark.asyncio @pytest.mark.parametrize("install_source", ["upload", "url"]) @pytest.mark.parametrize("disabled", [False, True])