🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
💄 style(marketplace): Skills in the Lobot Market design — catalog, skill page, GitHub search/import/updates (#23698)
Lobehub Coder517903e80b2d
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex b78193d328c..0d4b221a9f2 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -170,6 +170,7 @@"olderMessages": "Older messages","openAgent": "Open Agent","openAgentNamed": "Open {{name}}",+ "openDirect.unavailable": "This Agent's conversation can't be opened right now.","openThread": "Open thread","openThreadPage": "Open as page","otherAgents": "Other Agents",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 9703a4ba1e7..740f4083b1c 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1364,6 +1364,94 @@"llm.proxyUrl.title": "API proxy URL","llm.waitingForMore": "More models are <1>planned to be added</1>, stay tuned","llm.waitingForMoreLinkAriaLabel": "Open the Provider request form",+ "market.apps.viewAll": "View all",+ "market.back": "Back",+ "market.detail.category": "Category",+ "market.detail.developer": "Developer",+ "market.detail.info": "Information",+ "market.detail.website": "Website",+ "market.skills.addToAgent": "Add to assistant",+ "market.skills.agents.empty": "No assistant has this skill yet",+ "market.skills.agents.emptyHint": "Use \"Add to assistant\" above to turn it on for one.",+ "market.skills.agents.enabledOn": "On for {{on}}/{{total}} assistants",+ "market.skills.agents.failed": "Couldn't update the assistant. Try again.",+ "market.skills.agents.noneToAdd": "No assistant to add it to",+ "market.skills.agents.notAdded": "Not added to an assistant",+ "market.skills.agents.remove": "Remove",+ "market.skills.agents.removeAll": "Remove all",+ "market.skills.agents.title": "Assistants · {{count}}",+ "market.skills.copyPrompt": "Copy this message",+ "market.skills.desc": "Reusable ways of working for your assistants. Install one, then turn it on in an assistant.",+ "market.skills.empty": "No matching skills",+ "market.skills.github.add": "Add selected ({{count}})",+ "market.skills.github.addressHint": "Find the skills in this repository",+ "market.skills.github.desc": "Paste a repository or folder link. Every SKILL.md in it is found — at the root, in skills/, .claude/skills/, plugin folders or deeper.",+ "market.skills.github.entry": "Add from GitHub",+ "market.skills.github.failed.find": "Couldn't read this repository.",+ "market.skills.github.failed.import": "Couldn't add the skills.",+ "market.skills.github.failed.refresh": "The skills were added, but the list didn't refresh.",+ "market.skills.github.find": "Find skills",+ "market.skills.github.found": "{{count}} skills in {{repo}}",+ "market.skills.github.group": "GitHub",+ "market.skills.github.installedGroup": "From GitHub",+ "market.skills.github.invalid": "That isn't a GitHub repository link.",+ "market.skills.github.localChanges.cancel": "Cancel",+ "market.skills.github.localChanges.content": "This skill was edited here after it was installed. Updating replaces it with the version on GitHub.",+ "market.skills.github.localChanges.ok": "Update and replace",+ "market.skills.github.localChanges.title": "Replace your changes?",+ "market.skills.github.none": "No SKILL.md found in {{repo}}",+ "market.skills.github.openOnGithub": "Open on GitHub",+ "market.skills.github.outcome.conflict": "Name taken",+ "market.skills.github.outcome.created": "Added",+ "market.skills.github.outcome.failed": "Failed",+ "market.skills.github.outcome.forbidden": "No permission",+ "market.skills.github.outcome.unchanged": "Already installed",+ "market.skills.github.outcome.updated": "Updated",+ "market.skills.github.placeholder": "owner/repo, or a github.com link to a repository or folder",+ "market.skills.github.recovery.accessTitle": "GitHub won't share this repository",+ "market.skills.github.recovery.addToken": "Add a token to the Vault",+ "market.skills.github.recovery.connect": "Connect GitHub",+ "market.skills.github.recovery.connectTitle": "Connect GitHub to read this repository",+ "market.skills.github.recovery.desc": "It may be private, or the link may be wrong. Connect GitHub, or save a personal access token (GITHUB_TOKEN) in the Vault; the repository is scanned again right after.",+ "market.skills.github.recovery.tokenDescription": "Read private GitHub repositories when adding skills from GitHub.",+ "market.skills.github.retry": "Try again",+ "market.skills.github.searchEmpty": "No matching repositories on GitHub",+ "market.skills.github.searchFailed": "Couldn't search GitHub.",+ "market.skills.github.searchLimited": "GitHub search is busy. Try again in a minute, or paste a repository link.",+ "market.skills.github.selectAll": "Select all",+ "market.skills.github.status.conflict": "Name taken",+ "market.skills.github.status.forbidden": "No permission",+ "market.skills.github.status.invalid": "Invalid SKILL.md",+ "market.skills.github.status.new": "New",+ "market.skills.github.status.unchanged": "Installed",+ "market.skills.github.status.update": "Update available",+ "market.skills.github.title": "Add skills from GitHub",+ "market.skills.github.update": "Update ({{count}})",+ "market.skills.github.updateFailed": "Couldn't update. Try again later.",+ "market.skills.github.updateOne": "Update",+ "market.skills.install": "Install",+ "market.skills.installFailed": "Couldn't install. Try again later.",+ "market.skills.installed": "Installed",+ "market.skills.installedGroup": "Installed",+ "market.skills.mockPrompt": "Help me use this skill.",+ "market.skills.more": "Load more",+ "market.skills.results": "Results",+ "market.skills.reviews.anonymous": "Anonymous",+ "market.skills.reviews.outOf": "out of 5",+ "market.skills.reviews.title": "Ratings & Reviews",+ "market.skills.reviews.total": "{{count}} reviews",+ "market.skills.search": "Search skills, or paste a GitHub link",+ "market.skills.sendFailed": "Couldn't send it. Try again.",+ "market.skills.sendPick": "Send to an assistant",+ "market.skills.sendTo": "Send to {{name}}",+ "market.skills.stats.installs": "Installs",+ "market.skills.stats.latest": "Latest",+ "market.skills.stats.ratings": "{{count}} ratings",+ "market.skills.stats.reviews": "Reviews",+ "market.skills.stats.stars": "GitHub stars",+ "market.skills.title": "Skills",+ "market.skills.uninstall": "Uninstall",+ "market.skills.version": "Version","marketPublish.status.archived": "Archived","marketPublish.status.deprecated": "Deprecated","marketPublish.status.published": "Published",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 4b472eb9a78..95add6073a3 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -170,6 +170,7 @@"olderMessages": "更早的消息","openAgent": "打开 Agent","openAgentNamed": "打开 {{name}}",+ "openDirect.unavailable": "这个助手的对话暂时无法打开。","openThread": "打开线程","openThreadPage": "在页面中打开","otherAgents": "其他 Agent",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex ea9dd537f56..a239bc9613a 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1364,6 +1364,94 @@"llm.proxyUrl.title": "API 代理地址","llm.waitingForMore": "更多模型正在 <1>计划接入</1> 中,敬请期待","llm.waitingForMoreLinkAriaLabel": "打开模型服务商接入需求表单",+ "market.apps.viewAll": "查看全部",+ "market.back": "返回",+ "market.detail.category": "分类",+ "market.detail.developer": "开发者",+ "market.detail.info": "信息",+ "market.detail.website": "网站",+ "market.skills.addToAgent": "添加到助手",+ "market.skills.agents.empty": "还没有助手使用这个技能",+ "market.skills.agents.emptyHint": "点上方「添加到助手」,给助手开启它。",+ "market.skills.agents.enabledOn": "已在 {{on}}/{{total}} 个助手上开启",+ "market.skills.agents.failed": "没能更新助手,请重试",+ "market.skills.agents.noneToAdd": "没有可添加的助手",+ "market.skills.agents.notAdded": "未添加到助手",+ "market.skills.agents.remove": "移除",+ "market.skills.agents.removeAll": "全部移除",+ "market.skills.agents.title": "助手 · {{count}}",+ "market.skills.copyPrompt": "复制这条消息",+ "market.skills.desc": "给助手装上可复用的工作方法,安装后在助手里开启即可使用。",+ "market.skills.empty": "没有匹配的技能",+ "market.skills.github.add": "添加所选({{count}})",+ "market.skills.github.addressHint": "查找这个仓库里的技能",+ "market.skills.github.desc": "粘贴仓库或文件夹链接,会找出其中所有 SKILL.md:根目录、skills/、.claude/skills/、插件目录,或更深的位置。",+ "market.skills.github.entry": "从 GitHub 添加",+ "market.skills.github.failed.find": "无法读取这个仓库。",+ "market.skills.github.failed.import": "技能添加失败。",+ "market.skills.github.failed.refresh": "技能已添加,但列表没有刷新。",+ "market.skills.github.find": "查找技能",+ "market.skills.github.found": "{{repo}} 中有 {{count}} 个技能",+ "market.skills.github.group": "GitHub",+ "market.skills.github.installedGroup": "来自 GitHub",+ "market.skills.github.invalid": "这不是 GitHub 仓库链接。",+ "market.skills.github.localChanges.cancel": "取消",+ "market.skills.github.localChanges.content": "这个技能安装后在本地改过。更新会用 GitHub 上的版本替换它。",+ "market.skills.github.localChanges.ok": "更新并替换",+ "market.skills.github.localChanges.title": "替换本地修改?",+ "market.skills.github.none": "{{repo}} 中没有找到 SKILL.md",+ "market.skills.github.openOnGithub": "在 GitHub 打开",+ "market.skills.github.outcome.conflict": "名称已被占用",+ "market.skills.github.outcome.created": "已添加",+ "market.skills.github.outcome.failed": "失败",+ "market.skills.github.outcome.forbidden": "无权限",+ "market.skills.github.outcome.unchanged": "已安装",+ "market.skills.github.outcome.updated": "已更新",+ "market.skills.github.placeholder": "owner/repo,或指向仓库、文件夹的 github.com 链接",+ "market.skills.github.recovery.accessTitle": "GitHub 没有开放这个仓库",+ "market.skills.github.recovery.addToken": "在保险库添加 Token",+ "market.skills.github.recovery.connect": "连接 GitHub",+ "market.skills.github.recovery.connectTitle": "连接 GitHub 后才能读取这个仓库",+ "market.skills.github.recovery.desc": "仓库可能是私有的,或链接有误。连接 GitHub,或在保险库保存一个个人访问令牌(GITHUB_TOKEN),完成后会自动重新扫描。",+ "market.skills.github.recovery.tokenDescription": "从 GitHub 添加技能时,用于读取私有仓库。",+ "market.skills.github.retry": "重试",+ "market.skills.github.searchEmpty": "GitHub 上没有匹配的仓库",+ "market.skills.github.searchFailed": "搜索 GitHub 失败。",+ "market.skills.github.searchLimited": "GitHub 搜索太频繁,请一分钟后再试,或直接粘贴仓库链接。",+ "market.skills.github.selectAll": "全选",+ "market.skills.github.status.conflict": "名称已被占用",+ "market.skills.github.status.forbidden": "无权限",+ "market.skills.github.status.invalid": "SKILL.md 无效",+ "market.skills.github.status.new": "新",+ "market.skills.github.status.unchanged": "已安装",+ "market.skills.github.status.update": "有更新",+ "market.skills.github.title": "从 GitHub 添加技能",+ "market.skills.github.update": "更新({{count}})",+ "market.skills.github.updateFailed": "更新失败,请稍后再试。",+ "market.skills.github.updateOne": "更新",+ "market.skills.install": "安装",+ "market.skills.installFailed": "安装失败,请稍后重试",+ "market.skills.installed": "已安装",+ "market.skills.installedGroup": "已安装",+ "market.skills.mockPrompt": "帮我使用这个技能。",+ "market.skills.more": "加载更多",+ "market.skills.results": "搜索结果",+ "market.skills.reviews.anonymous": "匿名用户",+ "market.skills.reviews.outOf": "满分 5 分",+ "market.skills.reviews.title": "评分与评论",+ "market.skills.reviews.total": "共 {{count}} 条评论",+ "market.skills.search": "搜索技能,或粘贴 GitHub 链接",+ "market.skills.sendFailed": "没发出去,请重试",+ "market.skills.sendPick": "发给助手",+ "market.skills.sendTo": "发给 {{name}}",+ "market.skills.stats.installs": "安装",+ "market.skills.stats.latest": "最新版本",+ "market.skills.stats.ratings": "{{count}} 个评分",+ "market.skills.stats.reviews": "评论",+ "market.skills.stats.stars": "GitHub Star",+ "market.skills.title": "技能",+ "market.skills.uninstall": "卸载",+ "market.skills.version": "版本","marketPublish.status.archived": "已归档","marketPublish.status.deprecated": "已弃用","marketPublish.status.published": "已发布",diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex 4327dc26042..18426274cb6 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -360,4 +360,5 @@ export default {'mentionInvite.confirmAgentProject':'It is not in the project “{{project}}” yet: it joins the project first, then this channel.','mentionInvite.confirmOk': 'Invite and mention',+ 'openDirect.unavailable': "This Agent's conversation can't be opened right now.",};diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex c354efc9cbb..6db0cd954e7 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -5479,4 +5479,98 @@ When I am ___, I need ___'environments.form.duplicateFolder': 'Another repository already uses this folder.','workspaceSetting.devices.enrollPrivateDesc':'Run this on the machine you want to connect. It starts private to you; publish it to the workspace from its card menu.',+ 'market.apps.viewAll': 'View all',+ 'market.back': 'Back',+ 'market.detail.category': 'Category',+ 'market.detail.developer': 'Developer',+ 'market.detail.info': 'Information',+ 'market.detail.website': 'Website',+ 'market.skills.addToAgent': 'Add to assistant',+ 'market.skills.agents.empty': 'No assistant has this skill yet',+ 'market.skills.agents.emptyHint': 'Use "Add to assistant" above to turn it on for one.',+ 'market.skills.agents.enabledOn': 'On for {{on}}/{{total}} assistants',+ 'market.skills.agents.failed': "Couldn't update the assistant. Try again.",+ 'market.skills.agents.noneToAdd': 'No assistant to add it to',+ 'market.skills.agents.notAdded': 'Not added to an assistant',+ 'market.skills.agents.remove': 'Remove',+ 'market.skills.agents.removeAll': 'Remove all',+ 'market.skills.agents.title': 'Assistants · {{count}}',+ 'market.skills.copyPrompt': 'Copy this message',+ 'market.skills.desc':+ 'Reusable ways of working for your assistants. Install one, then turn it on in an assistant.',+ 'market.skills.empty': 'No matching skills',+ 'market.skills.github.add': 'Add selected ({{count}})',+ 'market.skills.github.addressHint': 'Find the skills in this repository',+ 'market.skills.github.desc':+ 'Paste a repository or folder link. Every SKILL.md in it is found — at the root, in skills/, .claude/skills/, plugin folders or deeper.',+ 'market.skills.github.entry': 'Add from GitHub',+ 'market.skills.github.failed.find': "Couldn't read this repository.",+ 'market.skills.github.failed.import': "Couldn't add the skills.",+ 'market.skills.github.failed.refresh': "The skills were added, but the list didn't refresh.",+ 'market.skills.github.find': 'Find skills',+ 'market.skills.github.found': '{{count}} skills in {{repo}}',+ 'market.skills.github.group': 'GitHub',+ 'market.skills.github.installedGroup': 'From GitHub',+ 'market.skills.github.invalid': "That isn't a GitHub repository link.",+ 'market.skills.github.localChanges.cancel': 'Cancel',+ 'market.skills.github.localChanges.content':+ 'This skill was edited here after it was installed. Updating replaces it with the version on GitHub.',+ 'market.skills.github.localChanges.ok': 'Update and replace',+ 'market.skills.github.localChanges.title': 'Replace your changes?',+ 'market.skills.github.none': 'No SKILL.md found in {{repo}}',+ 'market.skills.github.openOnGithub': 'Open on GitHub',+ 'market.skills.github.outcome.conflict': 'Name taken',+ 'market.skills.github.outcome.created': 'Added',+ 'market.skills.github.outcome.failed': 'Failed',+ 'market.skills.github.outcome.forbidden': 'No permission',+ 'market.skills.github.outcome.unchanged': 'Already installed',+ 'market.skills.github.outcome.updated': 'Updated',+ 'market.skills.github.placeholder': 'owner/repo, or a github.com link to a repository or folder',+ 'market.skills.github.recovery.accessTitle': "GitHub won't share this repository",+ 'market.skills.github.recovery.addToken': 'Add a token to the Vault',+ 'market.skills.github.recovery.connect': 'Connect GitHub',+ 'market.skills.github.recovery.connectTitle': 'Connect GitHub to read this repository',+ 'market.skills.github.recovery.desc':+ 'It may be private, or the link may be wrong. Connect GitHub, or save a personal access token (GITHUB_TOKEN) in the Vault; the repository is scanned again right after.',+ 'market.skills.github.recovery.tokenDescription':+ 'Read private GitHub repositories when adding skills from GitHub.',+ 'market.skills.github.retry': 'Try again',+ 'market.skills.github.searchEmpty': 'No matching repositories on GitHub',+ 'market.skills.github.searchFailed': "Couldn't search GitHub.",+ 'market.skills.github.searchLimited':+ 'GitHub search is busy. Try again in a minute, or paste a repository link.',+ 'market.skills.github.selectAll': 'Select all',+ 'market.skills.github.status.conflict': 'Name taken',+ 'market.skills.github.status.forbidden': 'No permission',+ 'market.skills.github.status.invalid': 'Invalid SKILL.md',+ 'market.skills.github.status.new': 'New',+ 'market.skills.github.status.unchanged': 'Installed',+ 'market.skills.github.status.update': 'Update available',+ 'market.skills.github.title': 'Add skills from GitHub',+ 'market.skills.github.update': 'Update ({{count}})',+ 'market.skills.github.updateFailed': "Couldn't update. Try again later.",+ 'market.skills.github.updateOne': 'Update',+ 'market.skills.install': 'Install',+ 'market.skills.installFailed': "Couldn't install. Try again later.",+ 'market.skills.installed': 'Installed',+ 'market.skills.installedGroup': 'Installed',+ 'market.skills.mockPrompt': 'Help me use this skill.',+ 'market.skills.more': 'Load more',+ 'market.skills.results': 'Results',+ 'market.skills.reviews.anonymous': 'Anonymous',+ 'market.skills.reviews.outOf': 'out of 5',+ 'market.skills.reviews.title': 'Ratings & Reviews',+ 'market.skills.reviews.total': '{{count}} reviews',+ 'market.skills.search': 'Search skills, or paste a GitHub link',+ 'market.skills.sendFailed': "Couldn't send it. Try again.",+ 'market.skills.sendPick': 'Send to an assistant',+ 'market.skills.sendTo': 'Send to {{name}}',+ 'market.skills.stats.installs': 'Installs',+ 'market.skills.stats.latest': 'Latest',+ 'market.skills.stats.ratings': '{{count}} ratings',+ 'market.skills.stats.reviews': 'Reviews',+ 'market.skills.stats.stars': 'GitHub stars',+ 'market.skills.title': 'Skills',+ 'market.skills.uninstall': 'Uninstall',+ 'market.skills.version': 'Version',};diff --git a/src/features/Marketplace/Skills/BackLink.tsx b/src/features/Marketplace/Skills/BackLink.tsxnew file mode 100644index 00000000000..18c4fbef22f--- /dev/null+++ b/src/features/Marketplace/Skills/BackLink.tsx@@ -0,0 +1,44 @@+import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ChevronLeft } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++const styles = stylex.create({+ link: {+ display: 'inline-flex',+ alignItems: 'center',+ alignSelf: 'flex-start',+ gap: 2,+ height: 24,+ paddingInlineStart: 0,+ paddingInlineEnd: 6,+ marginInlineStart: -4,+ borderWidth: 0,+ borderRadius: cssVar.borderRadiusSM,+ font: 'inherit',+ fontSize: 13,+ color: {+ 'default': cssVar.colorTextSecondary,+ ':hover': cssVar.colorText,+ },+ backgroundColor: 'transparent',+ cursor: 'pointer',+ },+});++/** "‹ Back" at the top of every Market sub-page (a detail, a category, a skill group). */+const BackLink = memo<{ onClick: () => void }>(({ onClick }) => {+ const { t } = useTranslation('setting');+ return (+ <button type={'button'} {...stylex.props(styles.link)} onClick={onClick}>+ <Icon icon={ChevronLeft} size={16} />+ {t('market.back')}+ </button>+ );+});++BackLink.displayName = 'MarketBackLink';++export default BackLink;diff --git a/src/features/Marketplace/Skills/IconTile.tsx b/src/features/Marketplace/Skills/IconTile.tsxnew file mode 100644index 00000000000..b646ec4d3e9--- /dev/null+++ b/src/features/Marketplace/Skills/IconTile.tsx@@ -0,0 +1,27 @@+import { Center } from '@lobehub/ui';+import { Surface } from '@lobehub/ui/dashboard';+import { memo, type ReactNode } from 'react';++/**+ * The Surface tile every Market row and detail header puts its icon on:+ * connectors, skills without a category, and Agents.+ */+const IconTile = memo<{ children: ReactNode; size: number }>(({ children, size }) => (+ <Surface+ style={{+ borderRadius: Math.round(size * 0.25),+ flex: 'none',+ height: size,+ overflow: 'hidden',+ width: size,+ }}+ >+ <Center height={'100%'} width={'100%'}>+ {children}+ </Center>+ </Surface>+));++IconTile.displayName = 'MarketIconTile';++export default IconTile;diff --git a/src/features/Marketplace/Skills/MarketCard.tsx b/src/features/Marketplace/Skills/MarketCard.tsxnew file mode 100644index 00000000000..c5e3d03fecf--- /dev/null+++ b/src/features/Marketplace/Skills/MarketCard.tsx@@ -0,0 +1,26 @@+import { Surface } from '@lobehub/ui/dashboard';+import * as stylex from '@stylexjs/stylex';+import { memo, type ReactNode } from 'react';++const styles = stylex.create({+ body: (gap: number) => ({+ display: 'flex',+ flexDirection: 'column',+ gap,+ minWidth: 0,+ padding: 16,+ }),+});++/** Every content block on a Market page (account, info, repositories, reviews, SKILL.md): a Surface. */+const MarketCard = memo<{ children: ReactNode; gap?: number; onClick?: () => void }>(+ ({ children, gap = 12, onClick }) => (+ <Surface style={onClick ? { cursor: 'pointer' } : undefined} onClick={onClick}>+ <div {...stylex.props(styles.body(gap))}>{children}</div>+ </Surface>+ ),+);++MarketCard.displayName = 'MarketCard';++export default MarketCard;diff --git a/src/features/Marketplace/Skills/MarketSkeleton.tsx b/src/features/Marketplace/Skills/MarketSkeleton.tsxnew file mode 100644index 00000000000..068faa24968--- /dev/null+++ b/src/features/Marketplace/Skills/MarketSkeleton.tsx@@ -0,0 +1,140 @@+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++import { SkeletonBar } from '@/components/Skeleton';++import MarketCard from './MarketCard';++const styles = stylex.create({+ cards: {+ display: 'grid',+ gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',+ gap: 12,+ },+ divider: {+ height: 1,+ backgroundColor: cssVar.colorBorderSecondary,+ },+ grid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',+ columnGap: 16,+ rowGap: 4,+ },+ row: {+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ minWidth: 0,+ paddingBlock: 8,+ paddingInline: 8,+ },+ text: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ gap: 6,+ minWidth: 0,+ },+});++/** Text widths vary per row so a column of skeletons does not read as one block. */+const NAME_WIDTHS = ['46%', '58%', '38%', '52%'];+const BLURB_WIDTHS = ['82%', '70%', '90%', '64%'];++/** One list row: icon tile, name and blurb lines, and the "+" at the end. */+export const RowSkeleton = memo<{ index?: number }>(({ index = 0 }) => (+ <div {...stylex.props(styles.row)}>+ <SkeletonBar height={40} radius={10} width={40} />+ <span {...stylex.props(styles.text)}>+ <SkeletonBar height={14} width={NAME_WIDTHS[index % NAME_WIDTHS.length]} />+ <SkeletonBar height={12} width={BLURB_WIDTHS[index % BLURB_WIDTHS.length]} />+ </span>+ <SkeletonBar height={24} radius={6} width={24} />+ </div>+));++RowSkeleton.displayName = 'MarketRowSkeleton';++/** Rows in the two-column grid every Market list uses. */+export const RowGridSkeleton = memo<{ count?: number }>(({ count = 4 }) => (+ <div {...stylex.props(styles.grid)}>+ {Array.from({ length: count }, (_, index) => (+ <RowSkeleton index={index} key={index} />+ ))}+ </div>+));++RowGridSkeleton.displayName = 'MarketRowGridSkeleton';++/** A category block: its rule, a title, and its rows. */+export const SectionSkeleton = memo<{ count?: number }>(({ count = 4 }) => (+ <Flexbox gap={8}>+ <div {...stylex.props(styles.divider)} />+ <Flexbox horizontal align={'center'} justify={'space-between'} paddingBlock={8}>+ <SkeletonBar height={16} width={96} />+ <SkeletonBar height={14} width={56} />+ </Flexbox>+ <RowGridSkeleton count={count} />+ </Flexbox>+));++SectionSkeleton.displayName = 'MarketSectionSkeleton';++/** The featured cards: picture, name, author and a two-line blurb. */+export const FeaturedSkeleton = memo(() => (+ <Flexbox gap={8}>+ <div {...stylex.props(styles.divider)} />+ <Flexbox paddingBlock={8}>+ <SkeletonBar height={16} width={64} />+ </Flexbox>+ <div {...stylex.props(styles.cards)}>+ {Array.from({ length: 3 }, (_, index) => (+ <MarketCard gap={8} key={index}>+ <Flexbox horizontal justify={'space-between'} style={{ marginBlockEnd: 4 }}>+ <SkeletonBar height={48} radius={12} width={48} />+ <SkeletonBar height={24} radius={6} width={24} />+ </Flexbox>+ <SkeletonBar height={14} width={NAME_WIDTHS[index]} />+ <SkeletonBar height={12} width={'32%'} />+ <SkeletonBar height={12} width={'92%'} />+ <SkeletonBar height={12} width={BLURB_WIDTHS[index]} />+ </MarketCard>+ ))}+ </div>+ </Flexbox>+));++FeaturedSkeleton.displayName = 'MarketFeaturedSkeleton';++/** A detail page below its header: the figures strip and the information card. */+export const DetailBodySkeleton = memo(() => (+ <Flexbox gap={24}>+ <MarketCard>+ <Flexbox horizontal gap={16} justify={'space-around'}>+ {Array.from({ length: 4 }, (_, index) => (+ <Flexbox align={'center'} gap={8} key={index}>+ <SkeletonBar height={12} width={48} />+ <SkeletonBar height={22} width={56} />+ <SkeletonBar height={12} width={40} />+ </Flexbox>+ ))}+ </Flexbox>+ </MarketCard>+ <Flexbox gap={8}>+ <SkeletonBar height={16} width={64} />+ <MarketCard>+ {[0, 1, 2].map((index) => (+ <Flexbox horizontal gap={24} key={index}>+ <SkeletonBar height={14} width={72} />+ <SkeletonBar height={14} width={BLURB_WIDTHS[index]} />+ </Flexbox>+ ))}+ </MarketCard>+ </Flexbox>+ </Flexbox>+));++DetailBodySkeleton.displayName = 'MarketDetailBodySkeleton';diff --git a/src/features/Marketplace/Skills/RowAddAction.tsx b/src/features/Marketplace/Skills/RowAddAction.tsxnew file mode 100644index 00000000000..2dc75e988ba--- /dev/null+++ b/src/features/Marketplace/Skills/RowAddAction.tsx@@ -0,0 +1,20 @@+import { ActionIcon } from '@lobehub/ui';+import { PlusIcon } from 'lucide-react';+import { memo } from 'react';++/** The "+" at the end of every Market row (apps, skills, Agents): one style for all three. */+const RowAddAction = memo<{ loading?: boolean; onClick: () => void; title: string }>(+ ({ loading, onClick, title }) => (+ <ActionIcon+ aria-label={title}+ icon={PlusIcon}+ loading={loading}+ title={title}+ onClick={onClick}+ />+ ),+);++RowAddAction.displayName = 'MarketRowAddAction';++export default RowAddAction;diff --git a/src/features/Marketplace/Skills/SkillAgentList.tsx b/src/features/Marketplace/Skills/SkillAgentList.tsxnew file mode 100644index 00000000000..b884d208990--- /dev/null+++ b/src/features/Marketplace/Skills/SkillAgentList.tsx@@ -0,0 +1,125 @@+import { agentDisplayName } from '@lobechat/types';+import { Button, Center, Flexbox, Switch, Text } from '@lobehub/ui';+import { Surface } from '@lobehub/ui/dashboard';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AgentAvatar from '@/components/AgentAvatar';+import { SkeletonBar } from '@/components/Skeleton';++import type { SkillAgent } from './useSkillAgents';++const styles = stylex.create({+ row: {+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ minWidth: 0,+ paddingBlock: 12,+ paddingInline: 16,+ borderBlockStartWidth: {+ 'default': 1,+ ':first-child': 0,+ },+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: `var(--lobe-fill-border, ${cssVar.colorFillSecondary})`,+ },+ text: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ minWidth: 0,+ },+});++interface SkillAgentListProps {+ agents: SkillAgent[];+ /** My assistants' configs are still loading, so the list may be incomplete. */+ loading?: boolean;+ onRemove: (agentId: string) => void;+ onRemoveAll: () => void;+ onToggle: (agentId: string, on: boolean) => void;+ pendingIds: string[];+}++/**+ * An installed skill's assistants: each one can switch it off or drop it, and+ * "Remove all" takes it off every one of them. With none yet, it points at+ * "Add to assistant" in the header.+ */+const SkillAgentList = memo<SkillAgentListProps>(+ ({ agents, loading, onRemove, onRemoveAll, onToggle, pendingIds }) => {+ const { t } = useTranslation(['setting', 'common']);+ const removingAll =+ agents.length > 0 && agents.every(({ agent }) => pendingIds.includes(agent.id));++ return (+ <Flexbox gap={8}>+ <Flexbox horizontal align={'center'} justify={'space-between'}>+ <Text weight={600}>{t('market.skills.agents.title', { count: agents.length })}</Text>+ {agents.length > 0 && (+ <Button loading={removingAll} type={'fill'} onClick={onRemoveAll}>+ {t('market.skills.agents.removeAll')}+ </Button>+ )}+ </Flexbox>+ <Surface>+ {agents.length === 0 &&+ (loading ? (+ <div {...stylex.props(styles.row)}>+ <SkeletonBar height={32} radius={16} width={32} />+ <SkeletonBar height={14} width={160} />+ </div>+ ) : (+ <Center gap={4} paddingBlock={24} paddingInline={16}>+ <Text type={'secondary'}>{t('market.skills.agents.empty')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('market.skills.agents.emptyHint')}+ </Text>+ </Center>+ ))}+ {agents.map(({ agent, enabled }) => {+ const pending = pendingIds.includes(agent.id);+ const name = agentDisplayName(agent, t('defaultSession', { ns: 'common' }));+ return (+ <div key={agent.id} {...stylex.props(styles.row)}>+ <AgentAvatar+ agentId={agent.id}+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}+ background={agent.backgroundColor || undefined}+ name={name}+ size={32}+ />+ <span {...stylex.props(styles.text)}>+ <Text ellipsis weight={500}>+ {name}+ </Text>+ {agent.description && (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {agent.description}+ </Text>+ )}+ </span>+ <Switch+ checked={enabled}+ disabled={pending}+ size={'small'}+ onChange={(on) => onToggle(agent.id, on)}+ />+ <Button disabled={pending} type={'fill'} onClick={() => onRemove(agent.id)}>+ {t('market.skills.agents.remove')}+ </Button>+ </div>+ );+ })}+ </Surface>+ </Flexbox>+ );+ },+);++SkillAgentList.displayName = 'MarketSkillAgentList';++export default SkillAgentList;diff --git a/src/features/Marketplace/Skills/SkillAgentStatus.tsx b/src/features/Marketplace/Skills/SkillAgentStatus.tsxnew file mode 100644index 00000000000..22ab4acab73--- /dev/null+++ b/src/features/Marketplace/Skills/SkillAgentStatus.tsx@@ -0,0 +1,63 @@+import { agentDisplayName } from '@lobechat/types';+import { Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AgentAvatar from '@/components/AgentAvatar';++import type { SkillAgent } from './useSkillAgents';++/** Faces shown before the count; more would only crowd the row. */+const MAX_FACES = 3;++/**+ * An installed skill's row status: the faces of the assistants it is on for,+ * and "On for 1/2 assistants" (of those it was added to).+ */+const SkillAgentStatus = memo<{ agents: SkillAgent[] }>(({ agents }) => {+ const { t } = useTranslation('setting');+ const on = agents.filter((item) => item.enabled);++ if (agents.length === 0)+ return (+ <Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>+ {t('market.skills.agents.notAdded')}+ </Text>+ );++ return (+ <Flexbox horizontal align={'center'} flex={'none'} gap={6}>+ {on.length > 0 && (+ <Flexbox horizontal>+ {on.slice(0, MAX_FACES).map(({ agent }, index) => (+ <span+ key={agent.id}+ style={{+ borderRadius: '50%',+ boxShadow: `0 0 0 2px ${cssVar.colorBgContainer}`,+ display: 'flex',+ marginInlineStart: index === 0 ? 0 : -6,+ }}+ >+ <AgentAvatar+ agentId={agent.id}+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}+ background={agent.backgroundColor || undefined}+ name={agentDisplayName(agent)}+ size={18}+ />+ </span>+ ))}+ </Flexbox>+ )}+ <Text fontSize={12} type={'secondary'}>+ {t('market.skills.agents.enabledOn', { on: on.length, total: agents.length })}+ </Text>+ </Flexbox>+ );+});++SkillAgentStatus.displayName = 'MarketSkillAgentStatus';++export default SkillAgentStatus;diff --git a/src/features/Marketplace/Skills/SkillDetail.tsx b/src/features/Marketplace/Skills/SkillDetail.tsxnew file mode 100644index 00000000000..3f668d2e832--- /dev/null+++ b/src/features/Marketplace/Skills/SkillDetail.tsx@@ -0,0 +1,266 @@+import { agentDisplayName } from '@lobechat/types';+import { ActionIcon, Button, DropdownMenu, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ExternalLink, MoreHorizontalIcon, Trash2Icon } from 'lucide-react';+import { memo, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import AgentAvatar from '@/components/AgentAvatar';+import { useDiscoverStore } from '@/store/discover';+import { skillSelectors } from '@/store/discover/selectors';+import { useToolStore } from '@/store/tool';+import { agentSkillsSelectors } from '@/store/tool/selectors';++import BackLink from './BackLink';+import MarketCard from './MarketCard';+import { DetailBodySkeleton } from './MarketSkeleton';+import SkillAgentList from './SkillAgentList';+import SkillIcon from './SkillIcon';+import SkillPromptMock from './SkillPromptMock';+import SkillReviews from './SkillReviews';+import SkillStats from './SkillStats';+import { useMarketSkillInstall } from './useMarketSkillInstall';+import { useSkillAgents } from './useSkillAgents';++const styles = stylex.create({+ facts: {+ display: 'grid',+ gridTemplateColumns: '120px minmax(0, 1fr)',+ rowGap: 10,+ },+ link: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: 6,+ minWidth: 0,+ color: {+ 'default': cssVar.colorText,+ ':hover': cssVar.colorPrimary,+ },+ },+ status: {+ display: 'inline-flex',+ flex: 'none',+ alignItems: 'center',+ gap: 6,+ paddingBlock: 2,+ paddingInline: 8,+ borderRadius: 999,+ fontSize: 12,+ lineHeight: '18px',+ color: cssVar.colorSuccess,+ backgroundColor: cssVar.colorSuccessBg,+ },+});++const Section = ({ children, title }: { children: ReactNode; title: string }) => (+ <Flexbox gap={8}>+ <Text weight={600}>{title}</Text>+ <MarketCard>{children}</MarketCard>+ </Flexbox>+);++const ExternalLinkText = ({ href, label }: { href: string; label: string }) => (+ <a href={href} rel={'noreferrer'} target={'_blank'} {...stylex.props(styles.link)}>+ <Text ellipsis>{label}</Text>+ <Icon icon={ExternalLink} size={14} />+ </a>+);++/**+ * A market skill's own page. The header carries the install state and, once+ * installed, "Add to assistant"; under it a mock of the skill in use. Until an+ * assistant has it, the figures, facts and reviews follow; after that, the list+ * of assistants that have it. The SKILL.md the assistant follows closes the page.+ */+/** `onBack` draws an in-page back link; leave it out where the page header already has one. */+const SkillDetail = memo<{ identifier: string; onBack?: () => void }>(({ identifier, onBack }) => {+ const { t } = useTranslation('setting');+ const useFetchSkillDetail = useDiscoverStore((s) => s.useFetchSkillDetail);+ const { isLoading, queryKey } = useFetchSkillDetail({ identifier });+ const detail = useDiscoverStore(skillSelectors.skillDetail(queryKey));+ // Installed skills open here too; the library copy names them until the market answers.+ const local = useToolStore((s) =>+ agentSkillsSelectors.getMarketAgentSkills(s).find((skill) => skill.identifier === identifier),+ );+ const { error, install, installed, pending, uninstall } = useMarketSkillInstall(identifier);+ // The reviews section asks for the same page; its total is the strip's review count.+ const useFetchSkillComments = useDiscoverStore((s) => s.useFetchSkillComments);+ const { queryKey: commentsKey } = useFetchSkillComments({ identifier, pageSize: 6 });+ const commentCount = useDiscoverStore(skillSelectors.skillComments(commentsKey))?.totalCount;++ const name = detail?.name ?? local?.name ?? identifier;+ const description = detail?.description ?? local?.description ?? '';+ const github = detail?.github?.url;+ const skillAgents = useSkillAgents(identifier, installed);++ return (+ <Flexbox gap={12}>+ {onBack && <BackLink onClick={onBack} />}+ <Flexbox gap={24}>+ <Flexbox horizontal align={'center'} gap={16}>+ <SkillIcon category={detail?.category} size={56} />+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text ellipsis fontSize={18} weight={600}>+ {name}+ </Text>+ {installed && (+ <span {...stylex.props(styles.status)}>{t('market.skills.installed')}</span>+ )}+ </Flexbox>+ <Text ellipsis={{ rows: 2 }} type={'secondary'}>+ {description}+ </Text>+ </Flexbox>+ {installed ? (+ <Flexbox horizontal align={'center'} gap={8}>+ <DropdownMenu+ placement={'bottomRight'}+ items={+ skillAgents.available.length > 0+ ? skillAgents.available.map((agent) => {+ const agentName = agentDisplayName(+ agent,+ t('defaultSession', { ns: 'common' }),+ );+ return {+ icon: (+ <AgentAvatar+ agentId={agent.id}+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}+ background={agent.backgroundColor || undefined}+ name={agentName}+ size={20}+ />+ ),+ key: agent.id,+ label: agentName,+ onClick: () => void skillAgents.add(agent.id),+ };+ })+ : [+ {+ disabled: true,+ key: 'empty',+ label: t('market.skills.agents.noneToAdd'),+ },+ ]+ }+ popupProps={{+ // One row per assistant: keep it a narrow, scrolling list beside the button.+ style: { maxHeight: 360, maxWidth: 280, minWidth: 200, overflowY: 'auto' },+ }}+ >+ <Button type={'fill'}>{t('market.skills.addToAgent')}</Button>+ </DropdownMenu>+ <DropdownMenu+ placement={'bottomRight'}+ items={[+ {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'uninstall',+ label: t('market.skills.uninstall'),+ onClick: () => void uninstall(),+ },+ ]}+ >+ <ActionIcon icon={MoreHorizontalIcon} loading={pending} variant={'filled'} />+ </DropdownMenu>+ </Flexbox>+ ) : (+ <Button loading={pending} type={'fill'} onClick={() => void install()}>+ {t('market.skills.install')}+ </Button>+ )}+ </Flexbox>+ {error && <Text type={'danger'}>{t('market.skills.installFailed')}</Text>}+ <SkillPromptMock+ agents={installed ? skillAgents.added.filter((item) => item.enabled) : []}+ category={detail?.category}+ identifier={identifier}+ name={name}+ />+ {isLoading && !detail ? (+ <DetailBodySkeleton />+ ) : (+ detail && (+ <>+ {installed ? (+ <SkillAgentList+ agents={skillAgents.added}+ loading={skillAgents.loading}+ pendingIds={skillAgents.pendingIds}+ onRemove={(agentId) => void skillAgents.remove(agentId)}+ onRemoveAll={() => void skillAgents.removeAll()}+ onToggle={(agentId, on) => void skillAgents.toggle(agentId, on)}+ />+ ) : (+ <>+ <SkillStats+ data={{+ category: detail.category,+ commentCount,+ installCount: detail.installCount,+ ratingAverage: detail.ratingAverage,+ ratingCount: detail.ratingCount,+ stars: detail.github?.stars,+ version: detail.version,+ }}+ />+ <Section title={t('market.detail.info')}>+ <div {...stylex.props(styles.facts)}>+ {detail.author?.name && (+ <>+ <Text type={'secondary'}>{t('market.detail.developer')}</Text>+ {detail.author.url ? (+ <ExternalLinkText href={detail.author.url} label={detail.author.name} />+ ) : (+ <Text>{detail.author.name}</Text>+ )}+ </>+ )}+ {github && (+ <>+ <Text type={'secondary'}>GitHub</Text>+ <ExternalLinkText+ href={github}+ label={github.replace(/^https?:\/\/github\.com\//, '')}+ />+ </>+ )}+ {detail.homepage && detail.homepage !== github && (+ <>+ <Text type={'secondary'}>{t('market.detail.website')}</Text>+ <ExternalLinkText href={detail.homepage} label={detail.homepage} />+ </>+ )}+ </div>+ </Section>+ <SkillReviews+ identifier={identifier}+ ratingAverage={detail.ratingAverage}+ ratingCount={detail.ratingCount}+ />+ </>+ )}+ {detail.content && (+ <Section title={'SKILL.md'}>+ <Markdown fontSize={14} variant={'chat'}>+ {detail.content}+ </Markdown>+ </Section>+ )}+ </>+ )+ )}+ </Flexbox>+ </Flexbox>+ );+});++SkillDetail.displayName = 'MarketSkillDetail';++export default SkillDetail;diff --git a/src/features/Marketplace/Skills/SkillIcon.tsx b/src/features/Marketplace/Skills/SkillIcon.tsxnew file mode 100644index 00000000000..41af1e99b7e--- /dev/null+++ b/src/features/Marketplace/Skills/SkillIcon.tsx@@ -0,0 +1,39 @@+import { Center, Icon } from '@lobehub/ui';+import { SkillsIcon } from '@lobehub/ui/icons';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { memo } from 'react';++import IconTile from './IconTile';+import { getSkillCategoryStyle } from './skillCategoryStyle';++/**+ * A skill's icon, drawn from its category: the category's color with its lucide+ * glyph in white. A skill without a known category (an installed one the library+ * lists without it) gets the skill glyph on the plain Surface tile.+ */+const SkillIcon = memo<{ category?: string | null; size: number }>(({ category, size }) => {+ const style = getSkillCategoryStyle(category);+ const glyph = Math.round(size * 0.5);++ if (!style)+ return (+ <IconTile size={size}>+ <SkillsIcon color={cssVar.colorText} size={glyph} />+ </IconTile>+ );++ return (+ <Center+ flex={'none'}+ height={size}+ style={{ background: style.tile, borderRadius: Math.round(size * 0.25) }}+ width={size}+ >+ <Icon color={'#fff'} icon={style.icon} size={glyph} />+ </Center>+ );+});++SkillIcon.displayName = 'MarketSkillIcon';++export default SkillIcon;diff --git a/src/features/Marketplace/Skills/SkillPromptMock.tsx b/src/features/Marketplace/Skills/SkillPromptMock.tsxnew file mode 100644index 00000000000..5c647edbafe--- /dev/null+++ b/src/features/Marketplace/Skills/SkillPromptMock.tsx@@ -0,0 +1,112 @@+import { Text } from '@lobehub/ui';+import { Grainient } from '@lobehub/ui/awesome';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { DEFAULT_SKILL_GRADIENT, getSkillCategoryStyle } from './skillCategoryStyle';+import SkillIcon from './SkillIcon';+import SkillPromptSend from './SkillPromptSend';+import type { SkillAgent } from './useSkillAgents';++const styles = stylex.create({+ backdrop: {+ position: 'absolute',+ inset: 0,+ },+ chip: {+ display: 'inline-flex',+ flex: 'none',+ alignItems: 'center',+ gap: 6,+ maxWidth: '50%',+ paddingBlock: 2,+ paddingInlineStart: 4,+ paddingInlineEnd: 8,+ borderRadius: 6,+ backgroundColor: cssVar.colorFillSecondary,+ },+ input: {+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ width: 'min(100%, 560px)',+ paddingBlock: 8,+ paddingInlineStart: 12,+ paddingInlineEnd: 8,+ borderRadius: 14,+ backgroundColor: cssVar.colorBgElevated,+ boxShadow: '0 8px 24px rgb(0 0 0 / 18%)',+ },+ root: {+ position: 'relative',+ overflow: 'hidden',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ height: 168,+ paddingInline: 32,+ borderRadius: 16,+ userSelect: 'none',+ },+ send: {+ display: 'flex',+ flex: 'none',+ },+});++interface SkillPromptMockProps {+ /** Assistants that have the skill on; they decide what the end button does. */+ agents: SkillAgent[];+ category?: string | null;+ identifier: string;+ name: string;+}++/**+ * A picture of the skill in use: the chat box with the skill tagged and a+ * one-line ask, over a grain gradient in the skill category's colors (full+ * colors in the light theme too; washed toward white they read grey). Only the+ * end button acts: copy the message, or send it to an assistant.+ */+const SkillPromptMock = memo<SkillPromptMockProps>(({ agents, category, identifier, name }) => {+ const { t } = useTranslation('setting');+ const [color1, color2, color3] =+ getSkillCategoryStyle(category)?.gradient ?? DEFAULT_SKILL_GRADIENT;++ return (+ <div {...stylex.props(styles.root)}>+ <Grainient+ aria-hidden+ color1={color1}+ color2={color2}+ color3={color3}+ contrast={1.2}+ grainAmount={0.06}+ lightMode={false}+ timeSpeed={0.15}+ {...stylex.props(styles.backdrop)}+ />+ <div {...stylex.props(styles.input)}>+ <span {...stylex.props(styles.chip)}>+ <SkillIcon category={category} size={18} />+ <Text ellipsis fontSize={13} weight={500}>+ {name}+ </Text>+ </span>+ <Text ellipsis style={{ flex: 1 }}>+ {t('market.skills.mockPrompt')}+ </Text>+ <span {...stylex.props(styles.send)}>+ <SkillPromptSend agents={agents} identifier={identifier} name={name} />+ </span>+ </div>+ </div>+ );+});++SkillPromptMock.displayName = 'MarketSkillPromptMock';++export default SkillPromptMock;diff --git a/src/features/Marketplace/Skills/SkillPromptSend.test.ts b/src/features/Marketplace/Skills/SkillPromptSend.test.tsnew file mode 100644index 00000000000..949f8748415--- /dev/null+++ b/src/features/Marketplace/Skills/SkillPromptSend.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('@/store/channel', () => ({ channelActions: {} }));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: vi.fn(),+}));++const { skillPrompt } = await import('./SkillPromptSend');++describe('skillPrompt', () => {+ it('puts the skill as a composer chip before the ask', () => {+ expect(skillPrompt('pptx', 'pptx', '帮我使用这个技能。')).toBe(+ '<skill name="pptx" label="pptx" /> 帮我使用这个技能。',+ );+ });++ it('keeps a quote in the name from closing the label attribute', () => {+ expect(skillPrompt('x', 'say "hi"', 'go')).toBe('<skill name="x" label="say \'hi\'" /> go');+ });+});diff --git a/src/features/Marketplace/Skills/SkillPromptSend.tsx b/src/features/Marketplace/Skills/SkillPromptSend.tsxnew file mode 100644index 00000000000..05b5f084be7--- /dev/null+++ b/src/features/Marketplace/Skills/SkillPromptSend.tsx@@ -0,0 +1,120 @@+import { CHANNEL_URL } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';+import { ActionIcon, copyToClipboard, DropdownMenu, toast } from '@lobehub/ui';+import { ArrowRight, Copy } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AgentAvatar from '@/components/AgentAvatar';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { channelActions } from '@/store/channel';++import type { SkillAgent } from './useSkillAgents';++/** The message: the skill as a composer chip (`<skill … />`), then the ask. */+export const skillPrompt = (identifier: string, name: string, ask: string) =>+ `<skill name="${identifier}" label="${name.replaceAll('"', "'")}" /> ${ask}`;++interface SkillPromptSendProps {+ /** Assistants that have the skill switched on. */+ agents: SkillAgent[];+ identifier: string;+ name: string;+}++/**+ * The button at the end of the skill page's mock chat box. With no assistant+ * running the skill it copies the message; with one it sends it to that+ * assistant's conversation; with several it asks which one first.+ */+const SkillPromptSend = memo<SkillPromptSendProps>(({ agents, identifier, name }) => {+ const { t } = useTranslation(['setting', 'common', 'channel']);+ const navigate = useWorkspaceAwareNavigate();+ const [pending, setPending] = useState(false);+ const content = skillPrompt(identifier, name, t('market.skills.mockPrompt'));++ const send = async (agentId: string) => {+ setPending(true);+ try {+ const channelId = await channelActions.openDirect(agentId);+ if (!channelId) {+ toast.error(t('openDirect.unavailable', { ns: 'channel' }));+ return;+ }+ await channelActions.send({+ channelId,+ content,+ mentions: [],+ requestKey: crypto.randomUUID(),+ });+ navigate(CHANNEL_URL(channelId));+ } catch (error) {+ console.error('[Market] Failed to send the skill prompt', error);+ toast.error(t('market.skills.sendFailed'));+ } finally {+ setPending(false);+ }+ };++ if (agents.length === 0)+ return (+ <ActionIcon+ aria-label={t('market.skills.copyPrompt')}+ icon={Copy}+ title={t('market.skills.copyPrompt')}+ variant={'filled'}+ onClick={async () => {+ await copyToClipboard(content);+ toast.success(t('copySuccess', { ns: 'common' }));+ }}+ />+ );++ if (agents.length === 1)+ return (+ <ActionIcon+ aria-label={t('market.skills.sendTo', { name: agentDisplayName(agents[0].agent) })}+ icon={ArrowRight}+ loading={pending}+ title={t('market.skills.sendTo', { name: agentDisplayName(agents[0].agent) })}+ variant={'filled'}+ onClick={() => void send(agents[0].agent.id)}+ />+ );++ return (+ <DropdownMenu+ placement={'bottomRight'}+ popupProps={{ style: { maxHeight: 320, maxWidth: 260, minWidth: 180, overflowY: 'auto' } }}+ items={agents.map(({ agent }) => {+ const agentName = agentDisplayName(agent, t('defaultSession', { ns: 'common' }));+ return {+ icon: (+ <AgentAvatar+ agentId={agent.id}+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}+ background={agent.backgroundColor || undefined}+ name={agentName}+ size={20}+ />+ ),+ key: agent.id,+ label: agentName,+ onClick: () => void send(agent.id),+ };+ })}+ >+ <ActionIcon+ aria-label={t('market.skills.sendPick')}+ icon={ArrowRight}+ loading={pending}+ title={t('market.skills.sendPick')}+ variant={'filled'}+ />+ </DropdownMenu>+ );+});++SkillPromptSend.displayName = 'MarketSkillPromptSend';++export default SkillPromptSend;diff --git a/src/features/Marketplace/Skills/SkillReviews.tsx b/src/features/Marketplace/Skills/SkillReviews.tsxnew file mode 100644index 00000000000..1c896a9e6b5--- /dev/null+++ b/src/features/Marketplace/Skills/SkillReviews.tsx@@ -0,0 +1,164 @@+import { AgentIcon } from '@lobehub/icons';+import { Avatar, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useDiscoverStore } from '@/store/discover';+import { skillSelectors } from '@/store/discover/selectors';++import MarketCard from './MarketCard';+import { useCompactNumber } from './SkillStats';+import Stars from './Stars';++const REVIEW_COUNT = 6;++const styles = stylex.create({+ bar: {+ flex: '1',+ height: 4,+ overflow: 'hidden',+ borderRadius: 2,+ backgroundColor: cssVar.colorFillSecondary,+ },+ barFill: (width: string) => ({+ width,+ height: '100%',+ borderRadius: 2,+ backgroundColor: cssVar.colorTextSecondary,+ }),+ content: {+ display: '-webkit-box',+ overflow: 'hidden',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: 4,+ fontSize: 13,+ lineHeight: 1.6,+ color: cssVar.colorTextSecondary,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ },+ grid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',+ gap: 12,+ },+ score: {+ fontSize: 56,+ fontWeight: 700,+ lineHeight: 1,+ letterSpacing: -1,+ },+});++/**+ * Ratings & Reviews, App Store style: the average beside a five-to-one star+ * histogram, then the latest reviews as cards.+ */+const SkillReviews = memo<{ identifier: string; ratingAverage?: number; ratingCount?: number }>(+ ({ identifier, ratingAverage, ratingCount }) => {+ const { i18n, t } = useTranslation('setting');+ const compact = useCompactNumber();+ const useFetchComments = useDiscoverStore((s) => s.useFetchSkillComments);+ const useFetchDistribution = useDiscoverStore((s) => s.useFetchSkillRatingDistribution);+ const { queryKey: commentsKey } = useFetchComments({ identifier, pageSize: REVIEW_COUNT });+ const { queryKey: distributionKey } = useFetchDistribution(identifier);+ const comments = useDiscoverStore(skillSelectors.skillComments(commentsKey));+ const distribution = useDiscoverStore(skillSelectors.skillRatingDistribution(distributionKey));++ const total = distribution?.totalCount ?? ratingCount ?? 0;+ const reviews = (comments?.items ?? []).filter((item) => item.content.trim());+ const date = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium' });++ if (!total && reviews.length === 0) return null;++ return (+ <Flexbox gap={12}>+ <Flexbox horizontal align={'baseline'} justify={'space-between'}>+ <Text weight={600}>{t('market.skills.reviews.title')}</Text>+ {comments && comments.totalCount > reviews.length && (+ <Text fontSize={12} type={'secondary'}>+ {t('market.skills.reviews.total', { count: comments.totalCount })}+ </Text>+ )}+ </Flexbox>+ {total > 0 && (+ <Flexbox horizontal align={'center'} gap={32}>+ <Flexbox align={'center'} gap={4} style={{ flex: 'none' }}>+ <span {...stylex.props(styles.score)}>{(ratingAverage ?? 0).toFixed(1)}</span>+ <Text fontSize={12} type={'secondary'}>+ {t('market.skills.reviews.outOf')}+ </Text>+ </Flexbox>+ <Flexbox flex={1} gap={4}>+ {([5, 4, 3, 2, 1] as const).map((star) => {+ const count = distribution?.[star] ?? 0;+ return (+ <Flexbox horizontal align={'center'} gap={8} key={star}>+ <span style={{ display: 'inline-flex', justifyContent: 'flex-end', width: 64 }}>+ <Stars size={9} value={star} />+ </span>+ <div {...stylex.props(styles.bar)}>+ <div+ {...stylex.props(styles.barFill(`${total ? (count / total) * 100 : 0}%`))}+ />+ </div>+ </Flexbox>+ );+ })}+ <Text fontSize={12} style={{ alignSelf: 'flex-end' }} type={'secondary'}>+ {t('market.skills.stats.ratings', { count: compact(total) })}+ </Text>+ </Flexbox>+ </Flexbox>+ )}+ {reviews.length > 0 && (+ <div {...stylex.props(styles.grid)}>+ {reviews.map((review) => {+ const author =+ review.author?.displayName ||+ review.author?.identifier ||+ t('market.skills.reviews.anonymous');+ return (+ <MarketCard gap={8} key={review.id}>+ <Flexbox horizontal align={'center'} gap={8}>+ {/* A review an agent wrote wears its client's mark (Codex, Claude Code, …). */}+ {review.author?.type === 'agent' && review.author.sourceType ? (+ <AgentIcon+ agent={review.author.sourceType}+ shape={'circle'}+ size={24}+ type={'avatar'}+ />+ ) : (+ <Avatar+ avatar={review.author?.avatar || author.slice(0, 1).toUpperCase()}+ background={review.author?.background ?? undefined}+ size={24}+ />+ )}+ <Text ellipsis style={{ flex: 1 }} weight={500}>+ {author}+ </Text>+ <Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>+ {date.format(new Date(review.createdAt))}+ </Text>+ </Flexbox>+ {review.rating !== undefined && review.rating > 0 && (+ <Stars value={review.rating} />+ )}+ <div {...stylex.props(styles.content)}>{review.content}</div>+ </MarketCard>+ );+ })}+ </div>+ )}+ </Flexbox>+ );+ },+);++SkillReviews.displayName = 'MarketSkillReviews';++export default SkillReviews;diff --git a/src/features/Marketplace/Skills/SkillRow.tsx b/src/features/Marketplace/Skills/SkillRow.tsxnew file mode 100644index 00000000000..14cb9264dd5--- /dev/null+++ b/src/features/Marketplace/Skills/SkillRow.tsx@@ -0,0 +1,130 @@+import { ActionIcon, DropdownMenu, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { MoreHorizontalIcon, Trash2Icon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useDiscoverStore } from '@/store/discover';+import { skillSelectors } from '@/store/discover/selectors';++import RowAddAction from './RowAddAction';+import SkillAgentStatus from './SkillAgentStatus';+import SkillIcon from './SkillIcon';+import { useMarketSkillInstall } from './useMarketSkillInstall';+import { useSkillAgentStatus } from './useSkillAgents';++const styles = stylex.create({+ action: {+ display: 'flex',+ flex: 'none',+ },+ row: {+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ minWidth: 0,+ paddingBlock: 8,+ paddingInline: 8,+ borderRadius: cssVar.borderRadiusLG,+ cursor: 'pointer',+ backgroundColor: {+ 'default': 'transparent',+ ':hover': cssVar.colorFillQuaternary,+ },+ },+ text: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ minWidth: 0,+ },+});++/**+ * The skill's market category. Installed skills come without one, so their+ * (cached) market detail supplies it and the icon keeps its color.+ */+const useSkillCategory = (skill: SkillSummary) => {+ const useFetchSkillDetail = useDiscoverStore((s) => s.useFetchSkillDetail);+ const { queryKey } = useFetchSkillDetail(+ { identifier: skill.identifier },+ { enabled: !skill.category },+ );+ const detail = useDiscoverStore(skillSelectors.skillDetail(queryKey));+ return skill.category ?? detail?.category;+};++/** What a skill cell shows; both market rows and installed skills map onto it. */+export interface SkillSummary {+ /** Market category; it picks the icon's color and glyph. Installed skills have none. */+ category?: string;+ description?: string | null;+ identifier: string;+ name: string;+}++/**+ * One skill cell: icon, name and blurb. A "+" installs it; an installed one has a "…" menu.+ * In "Installed" (`showAgents`), how many assistants have it on replaces the menu once+ * known; uninstalling lives on the skill's page there. Installing from a row opens the page.+ */+const SkillRow = memo<{ onOpen: () => void; showAgents?: boolean; skill: SkillSummary }>(+ ({ onOpen, showAgents = false, skill }) => {+ const agents = useSkillAgentStatus(skill.identifier, showAgents);+ const category = useSkillCategory(skill);+ const { t } = useTranslation('setting');+ const { error, install, installed, pending, uninstall } = useMarketSkillInstall(+ skill.identifier,+ );++ return (+ <div {...stylex.props(styles.row)} onClick={onOpen}>+ <SkillIcon category={category} size={40} />+ <span {...stylex.props(styles.text)}>+ <Text ellipsis weight={500}>+ {skill.name}+ </Text>+ <Text ellipsis fontSize={12} type={error ? 'danger' : 'secondary'}>+ {error ? t('market.skills.installFailed') : skill.description}+ </Text>+ </span>+ {showAgents && agents ? (+ <SkillAgentStatus agents={agents} />+ ) : (+ <span {...stylex.props(styles.action)} onClick={(event) => event.stopPropagation()}>+ {installed ? (+ <DropdownMenu+ placement={'bottomRight'}+ items={[+ {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'uninstall',+ label: t('market.skills.uninstall'),+ onClick: () => void uninstall(),+ },+ ]}+ >+ <ActionIcon icon={MoreHorizontalIcon} loading={pending} />+ </DropdownMenu>+ ) : (+ <RowAddAction+ loading={pending}+ title={t('market.skills.install')}+ onClick={async () => {+ // A skill added from the list opens its page, where it goes onto assistants.+ if (await install()) onOpen();+ }}+ />+ )}+ </span>+ )}+ </div>+ );+ },+);++SkillRow.displayName = 'MarketSkillRow';++export default SkillRow;diff --git a/src/features/Marketplace/Skills/SkillStats.test.ts b/src/features/Marketplace/Skills/SkillStats.test.tsnew file mode 100644index 00000000000..dc0e8e5f220--- /dev/null+++ b/src/features/Marketplace/Skills/SkillStats.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { skillStatKeys } from './SkillStats';++describe('skillStatKeys', () => {+ it('leaves out every figure that is zero or missing', () => {+ expect(+ skillStatKeys({+ commentCount: 0,+ installCount: 78,+ ratingAverage: 0,+ ratingCount: 0,+ stars: 0,+ }),+ ).toEqual(['installs']);+ });++ it('shows the rating only once the skill has one', () => {+ expect(skillStatKeys({ ratingAverage: 4.5, ratingCount: 2 })).toEqual(['rating']);+ expect(skillStatKeys({ ratingAverage: 4.5, ratingCount: 0 })).toEqual([]);+ });++ it('keeps the strip order: rating, installs, stars, reviews, category, version', () => {+ expect(+ skillStatKeys({+ category: 'productivity',+ commentCount: 3,+ installCount: 9,+ ratingAverage: 4,+ ratingCount: 3,+ stars: 12,+ version: '1.0.0',+ }),+ ).toEqual(['rating', 'installs', 'stars', 'reviews', 'category', 'version']);+ });+});diff --git a/src/features/Marketplace/Skills/SkillStats.tsx b/src/features/Marketplace/Skills/SkillStats.tsxnew file mode 100644index 00000000000..41b56e10b77--- /dev/null+++ b/src/features/Marketplace/Skills/SkillStats.tsx@@ -0,0 +1,101 @@+import { type MetricItem, MetricStrip } from '@lobehub/ui/dashboard';+import { SkillsIcon } from '@lobehub/ui/icons';+import { Download, MessageSquare, Star } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { getSkillCategoryStyle } from './skillCategoryStyle';+import Stars from './Stars';++/** 2.6k, 1.2M: App Store-style short counts in the UI language. */+export const useCompactNumber = () => {+ const { i18n } = useTranslation();+ const format = new Intl.NumberFormat(i18n.language, {+ maximumFractionDigits: 1,+ notation: 'compact',+ });+ return (value: number) => format.format(value);+};++export interface SkillStatsData {+ category?: string;+ commentCount?: number;+ installCount?: number;+ ratingAverage?: number;+ ratingCount?: number;+ stars?: number;+ version?: string;+}++/** A count worth a cell: present and above zero. */+const shown = (value?: number): value is number => !!value && value > 0;++export type SkillStatKey = 'category' | 'installs' | 'rating' | 'reviews' | 'stars' | 'version';++/** Which figures a skill has worth showing, in strip order. */+export const skillStatKeys = (data: SkillStatsData): SkillStatKey[] => {+ const keys: SkillStatKey[] = [];+ if (shown(data.ratingCount) && shown(data.ratingAverage)) keys.push('rating');+ if (shown(data.installCount)) keys.push('installs');+ if (shown(data.stars)) keys.push('stars');+ if (shown(data.commentCount)) keys.push('reviews');+ if (data.category) keys.push('category');+ if (data.version) keys.push('version');+ return keys;+};++/**+ * The figures under a skill's header, as a lobe-ui MetricStrip: rating,+ * installs, GitHub stars, reviews, category and version.+ * A figure the market does not have, or that is still zero, is left out; with+ * nothing to show the strip is gone too.+ */+const SkillStats = memo<{ data: SkillStatsData }>(({ data }) => {+ const { t } = useTranslation(['setting', 'discover']);+ const compact = useCompactNumber();+ const { category, commentCount, installCount, ratingAverage, ratingCount, stars, version } = data;+ const keys = new Set(skillStatKeys(data));++ const items: MetricItem[] = [];+ if (keys.has('rating') && ratingAverage && ratingCount)+ items.push({+ hint: <Stars value={ratingAverage} />,+ label: t('market.skills.stats.ratings', { count: ratingCount }),+ mark: Star,+ value: ratingAverage.toFixed(1),+ });+ if (keys.has('installs') && installCount)+ items.push({+ label: t('market.skills.stats.installs'),+ mark: Download,+ value: compact(installCount),+ });+ if (keys.has('stars') && stars)+ items.push({ label: t('market.skills.stats.stars'), mark: Star, value: compact(stars) });+ if (keys.has('reviews') && commentCount)+ items.push({+ label: t('market.skills.stats.reviews'),+ mark: MessageSquare,+ value: compact(commentCount),+ });+ if (keys.has('category') && category)+ items.push({+ label: t('market.detail.category'),+ mark: getSkillCategoryStyle(category)?.icon ?? SkillsIcon,+ value: t(`skills.categories.${category}.name`, { defaultValue: category, ns: 'discover' }),+ });+ if (keys.has('version') && version)+ items.push({+ hint: t('market.skills.stats.latest'),+ label: t('market.skills.version'),+ value: version,+ });++ if (items.length === 0) return null;++ return <MetricStrip items={items} />;+});++SkillStats.displayName = 'MarketSkillStats';++export default SkillStats;diff --git a/src/features/Marketplace/Skills/SkillsPage.tsx b/src/features/Marketplace/Skills/SkillsPage.tsxnew file mode 100644index 00000000000..d7afb570bea--- /dev/null+++ b/src/features/Marketplace/Skills/SkillsPage.tsx@@ -0,0 +1,395 @@+import { ActionIcon, Button, Center, Flexbox, SearchBar, Text } from '@lobehub/ui';+import { GithubIcon } from '@lobehub/ui/icons';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { useDebounce, useInViewport } from 'ahooks';+import { ChevronRight } from 'lucide-react';+import { memo, type ReactNode, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useDiscoverStore } from '@/store/discover';+import { skillSelectors } from '@/store/discover/selectors';+import { useToolStore } from '@/store/tool';+import { agentSkillsSelectors } from '@/store/tool/selectors';+import { SkillCategory, SkillSorts } from '@/types/discover';++import BackLink from './BackLink';+import GithubImportPage from './github/GithubImportPage';+import { GithubAddressRow } from './github/GithubRows';+import {+ GithubSearchResults,+ InstalledGithubSkills,+ useInstalledGithubSkills,+} from './github/GithubSkillGroups';+import { parseGithubSource } from './github/githubSource';+import { RowGridSkeleton, SectionSkeleton } from './MarketSkeleton';+import SkillRow, { type SkillSummary } from './SkillRow';+import { useSkillsNav } from './useSkillsNav';++/** Rows a group previews before its "all" arrow. */+const PREVIEW_COUNT = 6;+const PAGE_SIZE = 40;+/** The `skillGroup` of the installed skills' own page. */+const INSTALLED_GROUP = 'installed';++const styles = stylex.create({+ divider: {+ height: 1,+ backgroundColor: cssVar.colorBorderSecondary,+ },+ grid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',+ columnGap: 16,+ rowGap: 4,+ },+ header: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ paddingBlock: 8,+ },+ headerLink: {+ cursor: 'pointer',+ },+});++const matches = (skill: SkillSummary, query: string) => {+ const q = query.trim().toLowerCase();+ if (!q) return true;+ return [skill.name, skill.identifier, skill.description ?? ''].some((text) =>+ text.toLowerCase().includes(q),+ );+};++/** The market skills already in the library, as rows. */+const useInstalledSkills = () => {+ const useFetchAgentSkills = useToolStore((s) => s.useFetchAgentSkills);+ useFetchAgentSkills(true);+ const installed = useToolStore(agentSkillsSelectors.getMarketAgentSkills);+ return useMemo<SkillSummary[]>(+ () =>+ installed.map((skill) => ({+ description: skill.description,+ identifier: skill.identifier,+ name: skill.name,+ })),+ [installed],+ );+};++/** A market query's rows, its total and the paging flags. */+const useMarketSkills = (+ params: { category?: string; q?: string },+ pageSize: number,+ enabled = true,+) => {+ const useSkillList = useDiscoverStore((s) => s.useFetchSkillList);+ const { isLoading, queryKey } = useSkillList(+ {+ page: 1,+ pageSize,+ ...params,+ sort: params.q ? SkillSorts.Relevance : SkillSorts.InstallCount,+ },+ { enabled },+ );+ const list = useDiscoverStore(skillSelectors.skillList(queryKey));+ return { isLoading, items: list?.items ?? [], total: list?.totalCount ?? 0 };+};++/** Rows in two columns; `withAgents` (the installed skills) shows how many assistants have each on. */+const SkillGrid = memo<{ skills: SkillSummary[]; withAgents?: boolean }>(+ ({ skills, withAgents = false }) => {+ const { openSkill } = useSkillsNav();+ return (+ <div {...stylex.props(styles.grid)}>+ {skills.map((skill) => (+ <SkillRow+ key={skill.identifier}+ showAgents={withAgents}+ skill={skill}+ onOpen={() => openSkill(skill.identifier)}+ />+ ))}+ </div>+ );+ },+);++SkillGrid.displayName = 'MarketSkillGrid';++const GridSkeleton = () => <RowGridSkeleton count={PREVIEW_COUNT} />;++/** A titled block of rows; with `onMore`, the header carries the arrow to the group's page. */+const Group = ({+ children,+ onMore,+ title,+}: {+ children: ReactNode;+ onMore?: () => void;+ title: string;+}) => {+ const { t } = useTranslation('setting');+ return (+ <Flexbox gap={8}>+ <div {...stylex.props(styles.divider)} />+ <div {...stylex.props(styles.header, onMore && styles.headerLink)} onClick={onMore}>+ <Text weight={600}>{title}</Text>+ {onMore && (+ <ActionIcon icon={ChevronRight} size={'small'} title={t('market.apps.viewAll')} />+ )}+ </div>+ {children}+ </Flexbox>+ );+};++const useCategoryName = () => {+ const { t } = useTranslation('discover');+ return (category: string) =>+ t(`skills.categories.${category}.name`, { defaultValue: category }) as string;+};++/** Categories already scrolled to while the app is open. */+const seenCategories = new Set<string>();++/**+ * One market category's preview. It asks for its rows only once scrolled near,+ * so the page does not fire a request per category up front.+ */+const CategoryGroup = memo<{ category: string; count: number }>(({ category, count }) => {+ const ref = useRef<HTMLDivElement>(null);+ const [inViewport] = useInViewport(ref, { rootMargin: '200px' });+ // Remembered across visits, so coming back paints the cached rows instead of a skeleton.+ const [seen, setSeen] = useState(() => seenCategories.has(category));+ if (inViewport && !seen) {+ seenCategories.add(category);+ setSeen(true);+ }+ const { isLoading, items } = useMarketSkills({ category }, PREVIEW_COUNT, seen);+ const { setGroup: setSkillGroup } = useSkillsNav();+ const categoryName = useCategoryName();++ return (+ <div ref={ref}>+ <Group+ title={categoryName(category)}+ onMore={count > PREVIEW_COUNT ? () => setSkillGroup(category) : undefined}+ >+ {!seen || (isLoading && items.length === 0) ? (+ <GridSkeleton />+ ) : (+ <SkillGrid skills={items.slice(0, PREVIEW_COUNT)} />+ )}+ </Group>+ </div>+ );+});++CategoryGroup.displayName = 'MarketSkillCategoryGroup';++/** The grouped catalog: my skills, then each market category, all previews. */+const Catalog = memo(() => {+ const { t } = useTranslation('setting');+ const installed = useInstalledSkills();+ const fromGithub = useInstalledGithubSkills();+ const { setGroup: setSkillGroup } = useSkillsNav();+ const useSkillCategories = useDiscoverStore((s) => s.useSkillCategories);+ const { isLoading, queryKey } = useSkillCategories();+ const categories = useDiscoverStore(skillSelectors.skillCategories(queryKey));+ const groups = useMemo(+ () =>+ (categories ?? [])+ .filter((item) => item.category !== SkillCategory.All && item.count > 0)+ .toSorted((a, b) => b.count - a.count),+ [categories],+ );++ return (+ <>+ {installed.length > 0 && (+ <Group+ title={t('market.skills.installedGroup')}+ onMore={+ installed.length > PREVIEW_COUNT ? () => setSkillGroup(INSTALLED_GROUP) : undefined+ }+ >+ <SkillGrid withAgents skills={installed.slice(0, PREVIEW_COUNT)} />+ </Group>+ )}+ {fromGithub.length > 0 && (+ <Group title={t('market.skills.github.installedGroup')}>+ <InstalledGithubSkills items={fromGithub} />+ </Group>+ )}+ {isLoading && !categories ? (+ <>+ <SectionSkeleton count={PREVIEW_COUNT} />+ <SectionSkeleton count={PREVIEW_COUNT} />+ </>+ ) : (+ groups.map(({ category, count }) => (+ <CategoryGroup category={category} count={count} key={category} />+ ))+ )}+ </>+ );+});++Catalog.displayName = 'MarketSkillCatalog';++/** Search results: matching installed skills first, then the market's. */+const SearchResults = memo<{ query: string }>(({ query }) => {+ const { t } = useTranslation('setting');+ const [pageSize, setPageSize] = useState(PAGE_SIZE);+ const installed = useInstalledSkills().filter((skill) => matches(skill, query));+ const fromGithub = useInstalledGithubSkills(query);+ const address = parseGithubSource(query);+ const { setGithubUrl } = useSkillsNav();+ const { isLoading, items, total } = useMarketSkills({ q: query }, pageSize, !address);++ // A pasted GitHub address is a repository to add, not words to search for.+ if (address)+ return (+ <Group title={t('market.skills.github.group')}>+ <GithubAddressRow+ repo={[address.owner, address.repo, address.path].filter(Boolean).join('/')}+ onOpen={() => setGithubUrl(address.url)}+ />+ </Group>+ );++ return (+ <>+ {installed.length > 0 && (+ <Group title={t('market.skills.installedGroup')}>+ <SkillGrid withAgents skills={installed} />+ </Group>+ )}+ {fromGithub.length > 0 && (+ <Group title={t('market.skills.github.installedGroup')}>+ <InstalledGithubSkills items={fromGithub} />+ </Group>+ )}+ <Group title={t('market.skills.results')}>+ {isLoading && items.length === 0 ? (+ <GridSkeleton />+ ) : items.length === 0 ? (+ <Center paddingBlock={48}>+ <Text type={'secondary'}>{t('market.skills.empty')}</Text>+ </Center>+ ) : (+ <SkillGrid skills={items} />+ )}+ {items.length > 0 && items.length < total && (+ <Center paddingBlock={8}>+ <Button+ loading={isLoading}+ type={'fill'}+ onClick={() => setPageSize((size) => size + PAGE_SIZE)}+ >+ {t('market.skills.more')}+ </Button>+ </Center>+ )}+ </Group>+ <Group title={t('market.skills.github.group')}>+ <GithubSearchResults query={query} />+ </Group>+ </>+ );+});++SearchResults.displayName = 'MarketSkillSearchResults';++/** A group's own page: every installed skill, or a whole market category with paging. */+const GroupPage = memo<{ group: string }>(({ group }) => {+ const { t } = useTranslation('setting');+ const { setGroup: setSkillGroup } = useSkillsNav();+ const categoryName = useCategoryName();+ const installedGroup = group === INSTALLED_GROUP;+ const installed = useInstalledSkills();+ const [pageSize, setPageSize] = useState(PAGE_SIZE);+ const market = useMarketSkills({ category: group }, pageSize, !installedGroup);++ const skills = installedGroup ? installed : market.items;++ return (+ <Flexbox gap={20}>+ <Flexbox gap={12}>+ <BackLink onClick={() => setSkillGroup(null)} />+ <Text fontSize={20} weight={600}>+ {installedGroup ? t('market.skills.installedGroup') : categoryName(group)}+ </Text>+ </Flexbox>+ {!installedGroup && market.isLoading && skills.length === 0 ? (+ <GridSkeleton />+ ) : (+ <SkillGrid skills={skills} withAgents={installedGroup} />+ )}+ {!installedGroup && skills.length > 0 && skills.length < market.total && (+ <Center paddingBlock={8}>+ <Button+ loading={market.isLoading}+ type={'fill'}+ onClick={() => setPageSize((size) => size + PAGE_SIZE)}+ >+ {t('market.skills.more')}+ </Button>+ </Center>+ )}+ </Flexbox>+ );+});++GroupPage.displayName = 'MarketSkillGroupPage';++/**+ * The Skills page: my skills (from the Market, then from GitHub), then the LobeHub+ * Market's skills by category, each a short preview whose arrow opens the whole+ * group. Searching lists every match, then public GitHub repositories; a pasted+ * GitHub address offers that repository instead. "Add from GitHub" opens the+ * GitHub import page with an empty address.+ */+const SkillsPage = memo(() => {+ const { t } = useTranslation('setting');+ const [query, setQuery] = useState('');+ const q = useDebounce(query.trim(), { wait: 300 });+ const { githubUrl, group: skillGroup, setGithubUrl } = useSkillsNav();++ if (githubUrl !== null)+ return (+ <GithubImportPage initialUrl={githubUrl} key={githubUrl} onBack={() => setGithubUrl(null)} />+ );+ if (skillGroup) return <GroupPage group={skillGroup} />;++ return (+ <Flexbox gap={20}>+ <Flexbox horizontal align={'flex-start'} gap={16} justify={'space-between'}>+ <Flexbox gap={4}>+ <Text fontSize={20} weight={600}>+ {t('market.skills.title')}+ </Text>+ <Text type={'secondary'}>{t('market.skills.desc')}</Text>+ </Flexbox>+ <Button icon={GithubIcon} type={'fill'} onClick={() => setGithubUrl('')}>+ {t('market.skills.github.entry')}+ </Button>+ </Flexbox>+ <SearchBar+ allowClear+ placeholder={t('market.skills.search')}+ value={query}+ variant={'filled'}+ onChange={(event) => setQuery(event.target.value)}+ />+ {q ? <SearchResults query={q} /> : <Catalog />}+ </Flexbox>+ );+});++SkillsPage.displayName = 'MarketSkillsPage';++export default SkillsPage;diff --git a/src/features/Marketplace/Skills/Stars.tsx b/src/features/Marketplace/Skills/Stars.tsxnew file mode 100644index 00000000000..c755257141a--- /dev/null+++ b/src/features/Marketplace/Skills/Stars.tsx@@ -0,0 +1,44 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { Star } from 'lucide-react';+import { memo } from 'react';++/** `value` out of five stars, filled to the nearest half. */+const Stars = memo<{ size?: number; value: number }>(({ size = 12, value }) => {+ const rounded = Math.round(value * 2) / 2;+ return (+ <span style={{ display: 'inline-flex', gap: Math.max(1, size / 8) }}>+ {[1, 2, 3, 4, 5].map((index) => {+ const fill = rounded >= index ? 1 : rounded >= index - 0.5 ? 0.5 : 0;+ return (+ <span key={index} style={{ display: 'inline-flex', position: 'relative' }}>+ <Star color={cssVar.colorFillSecondary} fill={cssVar.colorFillSecondary} size={size} />+ {fill > 0 && (+ <span+ style={{+ // A flex box, not a line box: an inline SVG sits on the text+ // baseline and drops below the grey star underneath it.+ display: 'flex',+ inset: 0,+ overflow: 'hidden',+ position: 'absolute',+ width: `${fill * 100}%`,+ }}+ >+ <Star+ color={cssVar.colorWarning}+ fill={cssVar.colorWarning}+ size={size}+ style={{ flex: 'none' }}+ />+ </span>+ )}+ </span>+ );+ })}+ </span>+ );+});++Stars.displayName = 'MarketStars';++export default Stars;diff --git a/src/features/Marketplace/Skills/github/GithubAccessRecovery.tsx b/src/features/Marketplace/Skills/github/GithubAccessRecovery.tsxnew file mode 100644index 00000000000..48282d85396--- /dev/null+++ b/src/features/Marketplace/Skills/github/GithubAccessRecovery.tsx@@ -0,0 +1,108 @@+import type { TaskTemplateConnectorReference } from '@lobechat/const';+import { Alert, Button, Flexbox, toast } from '@lobehub/ui';+import { KeyRound, LockKeyhole } from 'lucide-react';+import { memo, useCallback, useEffect, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import {+ ConnectorConnectionMarketAuthRequiredError,+ ConnectorConnectionPopupBlockedError,+ useConnectorConnection,+} from '@/features/RecommendTaskTemplates/useConnectorConnection';+import { createCreateCredModal } from '@/features/Settings/creds/features/CreateCredModal';+import { personalCredsApi } from '@/features/Settings/creds/features/useCredsApi';+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';++const GITHUB: TaskTemplateConnectorReference[] = [{ identifier: 'github', source: 'lobehub' }];++/** The Vault entry the server reads a GitHub token from; the person pastes only the value. */+export const GITHUB_TOKEN_PRESET = {+ key: 'github',+ keys: ['GITHUB_TOKEN'],+ name: 'GitHub',+};++/**+ * Shown when GitHub won't hand a repository over: it is private, gone, or the+ * address is wrong. Two ways to grant access, then the same scan again:+ * connect GitHub, or save a personal access token in the Vault.+ */+const GithubAccessRecovery = memo<{ onResolved: () => void; recovery: 'access' | 'connect' }>(+ ({ onResolved, recovery }) => {+ const { t } = useTranslation(['setting', 'common']);+ const { connect, isAllConnected, isConnecting } = useConnectorConnection(GITHUB);+ const { isAuthenticated, signIn } = useMarketAuth();+ const startedHere = useRef(false);++ // Scan again once a connect started here lands.+ useEffect(() => {+ if (startedHere.current && isAllConnected) {+ startedHere.current = false;+ onResolved();+ }+ }, [isAllConnected, onResolved]);++ const connectGithub = async () => {+ startedHere.current = true;+ try {+ await connect();+ } catch (error) {+ startedHere.current = false;+ if (error instanceof ConnectorConnectionMarketAuthRequiredError) return;+ toast.error(+ t(+ error instanceof ConnectorConnectionPopupBlockedError+ ? 'common:taskTemplate.action.connect.popupBlocked'+ : 'common:taskTemplate.action.connect.error',+ ),+ );+ }+ };++ const addToken = useCallback(async () => {+ // The Vault lives in the Market account.+ if (!isAuthenticated && !(await signIn())) return;+ createCreateCredModal({+ credsApi: personalCredsApi,+ type: 'kv-env',+ kvPreset: {+ ...GITHUB_TOKEN_PRESET,+ description: t('market.skills.github.recovery.tokenDescription'),+ },+ onSuccess: onResolved,+ });+ }, [isAuthenticated, onResolved, signIn, t]);++ return (+ <Alert+ showIcon+ icon={LockKeyhole}+ type={'warning'}+ description={+ <Flexbox gap={12}>+ {t('market.skills.github.recovery.desc')}+ <Flexbox horizontal gap={8} wrap={'wrap'}>+ {!isAllConnected && (+ <Button loading={isConnecting} type={'fill'} onClick={() => void connectGithub()}>+ {t('market.skills.github.recovery.connect')}+ </Button>+ )}+ <Button icon={KeyRound} type={'fill'} onClick={() => void addToken()}>+ {t('market.skills.github.recovery.addToken')}+ </Button>+ </Flexbox>+ </Flexbox>+ }+ title={t(+ recovery === 'connect'+ ? 'market.skills.github.recovery.connectTitle'+ : 'market.skills.github.recovery.accessTitle',+ )}+ />+ );+ },+);++GithubAccessRecovery.displayName = 'MarketplaceGithubAccessRecovery';++export default GithubAccessRecovery;diff --git a/src/features/Marketplace/Skills/github/GithubImportPage.tsx b/src/features/Marketplace/Skills/github/GithubImportPage.tsxnew file mode 100644index 00000000000..970769dda41--- /dev/null+++ b/src/features/Marketplace/Skills/github/GithubImportPage.tsx@@ -0,0 +1,274 @@+import type { GitHubSkillCandidate, GitHubSkillOutcome } from '@lobechat/types';+import { Button, Checkbox, Empty, Flexbox, Icon, Input, Skeleton, Tag, Text } from '@lobehub/ui';+import { GithubIcon } from '@lobehub/ui/icons';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import BackLink from '../BackLink';+import MarketCard from '../MarketCard';+import GithubAccessRecovery from './GithubAccessRecovery';+import {+ canImportCandidate,+ type GithubSkillImportState,+ useGithubSkillImport,+} from './useGithubSkillImport';++const styles = stylex.create({+ // The card's title row: count, Select all and Add. It never scrolls away,+ // because the list below scrolls inside the card instead of the page.+ header: {+ display: 'flex',+ flexWrap: 'wrap',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 12,+ paddingBlockEnd: 12,+ borderBlockEndWidth: 1,+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ },+ list: {+ display: 'flex',+ flexDirection: 'column',+ maxHeight: 'min(48vh, 440px)',+ overflowY: 'auto',+ overscrollBehavior: 'contain',+ },+ row: {+ display: 'flex',+ alignItems: 'flex-start',+ gap: 10,+ paddingBlock: 10,+ borderBlockStartWidth: { 'default': 1, ':first-child': 0 },+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+ text: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ gap: 2,+ minWidth: 0,+ },+});++/** What became of a picked skill once the batch ran, as a tag. */+const OUTCOME_COLOR: Record<GitHubSkillOutcome['status'], string | undefined> = {+ conflict: 'warning',+ created: 'success',+ failed: 'error',+ forbidden: 'warning',+ unchanged: undefined,+ updated: 'success',+};++const CandidateRow = memo<{+ checked: boolean;+ disabled: boolean;+ item: GitHubSkillCandidate;+ onChange: (checked: boolean) => void;+ outcome?: GitHubSkillOutcome['status'];+}>(({ checked, disabled, item, onChange, outcome }) => {+ const { t } = useTranslation('setting');+ const importable = canImportCandidate(item) && !outcome;+ return (+ <div {...stylex.props(styles.row)}>+ <Checkbox+ aria-label={item.name}+ checked={importable && checked}+ disabled={disabled || !importable}+ onChange={onChange}+ />+ <span {...stylex.props(styles.text)}>+ <Flexbox horizontal align={'center'} gap={6} wrap={'wrap'}>+ <Text weight={500}>{item.name}</Text>+ {outcome ? (+ <Tag color={OUTCOME_COLOR[outcome]} size={'small'}>+ {t(`market.skills.github.outcome.${outcome}`)}+ </Tag>+ ) : (+ item.status !== 'new' && (+ <Tag color={item.status === 'update' ? 'processing' : undefined} size={'small'}>+ {t(`market.skills.github.status.${item.status}`)}+ </Tag>+ )+ )}+ </Flexbox>+ {item.description && (+ <Text fontSize={12} lineClamp={2} title={item.description} type={'secondary'}>+ {item.description}+ </Text>+ )}+ <Text fontSize={12} style={{ wordBreak: 'break-all' }} type={'secondary'}>+ {item.path || '/'}+ </Text>+ </span>+ </div>+ );+});++CandidateRow.displayName = 'MarketGithubCandidateRow';++/** The skills one scan found, with the picks and the install button. */+const ScanResult = memo<{ state: GithubSkillImportState }>(({ state }) => {+ const { t } = useTranslation('setting');+ const { candidates, install, loading, pending, results, scan, selected, setSelected, source } =+ state;+ const outcomes = new Map(results.map((item) => [item.path, item.status]));+ const open = candidates.filter((item) => canImportCandidate(item) && !outcomes.has(item.path));+ const picked = open.filter((item) => selected.includes(item.path));+ const updates = picked.filter((item) => item.status === 'update').length;+ const all = open.length > 0 && picked.length === open.length;+ const repo = source ? `${source.owner}/${source.repo}` : '';++ if (!scan) return null;+ if (candidates.length === 0)+ return (+ <MarketCard>+ <Empty description={t('market.skills.github.none', { repo })} />+ </MarketCard>+ );++ return (+ <MarketCard gap={4}>+ <div {...stylex.props(styles.header)}>+ <Text weight={600}>+ {t('market.skills.github.found', { count: candidates.length, repo })}+ </Text>+ {open.length > 0 && (+ <Flexbox horizontal align={'center'} gap={12}>+ {open.length > 1 && (+ <Checkbox+ checked={all}+ disabled={loading}+ indeterminate={picked.length > 0 && !all}+ onChange={(checked) => setSelected(checked ? open.map((item) => item.path) : [])}+ >+ {t('market.skills.github.selectAll')}+ </Checkbox>+ )}+ <Button+ disabled={!picked.length}+ loading={pending === 'import' || pending === 'refresh'}+ type={'primary'}+ onClick={() => void install(picked.map((item) => item.path))}+ >+ {updates === picked.length && updates > 0+ ? t('market.skills.github.update', { count: updates })+ : t('market.skills.github.add', { count: picked.length })}+ </Button>+ </Flexbox>+ )}+ </div>+ <div {...stylex.props(styles.list)}>+ {candidates.map((item) => (+ <CandidateRow+ checked={selected.includes(item.path)}+ disabled={loading}+ item={item}+ key={item.path}+ outcome={outcomes.get(item.path)}+ onChange={(checked) =>+ setSelected((prev) =>+ checked ? [...prev, item.path] : prev.filter((path) => path !== item.path),+ )+ }+ />+ ))}+ </div>+ </MarketCard>+ );+});++ScanResult.displayName = 'MarketGithubScanResult';++/**+ * Add skills from a GitHub repository: the address (from search, from an+ * installed skill, or typed here) is scanned for every `SKILL.md` — at the+ * root, under `skills/`, `.claude/skills/`, plugin folders, anywhere — and the+ * picked ones install at the scanned commit. Installed ones show as+ * up to date or with an update to take. A private repository offers to+ * connect GitHub or save a token in the Vault, then scans again.+ */+const GithubImportPage = memo<{ initialUrl: string; onBack: () => void }>(+ ({ initialUrl, onBack }) => {+ const { t } = useTranslation('setting');+ const state = useGithubSkillImport(initialUrl);+ const { discover, failure, input, loading, pending, scan, setInput, source } = state;+ const invalid = !!input.trim() && !source;++ return (+ <Flexbox gap={20}>+ <Flexbox gap={12}>+ <BackLink onClick={onBack} />+ <Flexbox gap={4}>+ <Text fontSize={20} weight={600}>+ {t('market.skills.github.title')}+ </Text>+ <Text type={'secondary'}>{t('market.skills.github.desc')}</Text>+ </Flexbox>+ </Flexbox>+ <Flexbox gap={6}>+ <Flexbox horizontal gap={8}>+ <Input+ autoFocus={!initialUrl}+ placeholder={t('market.skills.github.placeholder')}+ prefix={<Icon icon={GithubIcon} />}+ value={input}+ variant={'filled'}+ onChange={(event) => setInput(event.target.value)}+ onPressEnter={() => void discover()}+ />+ <Button+ disabled={!source}+ loading={pending === 'find'}+ type={scan ? 'fill' : 'primary'}+ onClick={() => void discover()}+ >+ {t('market.skills.github.find')}+ </Button>+ </Flexbox>+ {invalid && (+ <Text fontSize={12} type={'danger'}>+ {t('market.skills.github.invalid')}+ </Text>+ )}+ </Flexbox>+ {failure?.recovery ? (+ <GithubAccessRecovery recovery={failure.recovery} onResolved={() => void discover()} />+ ) : (+ failure && (+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>+ <Text type={'danger'}>+ {t(`market.skills.github.failed.${failure.stage}`)}+ {failure.details ? ` ${failure.details}` : ''}+ </Text>+ <Button+ loading={loading}+ type={'fill'}+ onClick={() =>+ void (failure.stage === 'refresh' ? state.refreshLibrary() : discover())+ }+ >+ {t('market.skills.github.retry')}+ </Button>+ </Flexbox>+ )+ )}+ {pending === 'find' ? (+ <MarketCard>+ <Skeleton.Text rows={4} />+ </MarketCard>+ ) : (+ <ScanResult state={state} />+ )}+ </Flexbox>+ );+ },+);++GithubImportPage.displayName = 'MarketGithubImportPage';++export default GithubImportPage;diff --git a/src/features/Marketplace/Skills/github/GithubRows.tsx b/src/features/Marketplace/Skills/github/GithubRows.tsxnew file mode 100644index 00000000000..360cc6bd651--- /dev/null+++ b/src/features/Marketplace/Skills/github/GithubRows.tsx@@ -0,0 +1,209 @@+import type { GitHubSkillCheck } from '@lobechat/types';+import { ActionIcon, Avatar, Button, DropdownMenu, Icon, Text } from '@lobehub/ui';+import { GithubIcon } from '@lobehub/ui/icons';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ExternalLinkIcon, MoreHorizontalIcon, StarIcon, Trash2Icon } from 'lucide-react';+import { memo, type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useToolStore } from '@/store/tool';+import type { AgentSkillListItem } from '@/store/tool/slices/agentSkills/projection';++import IconTile from '../IconTile';+import SkillIcon from '../SkillIcon';+import { githubSkillRepo } from './githubInstalled';+import type { GithubRepoHit } from './searchGithubRepos';+import { useApplyGithubUpdate } from './useGithubSkillUpdates';++const styles = stylex.create({+ action: {+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ gap: 4,+ },+ row: {+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ minWidth: 0,+ paddingBlock: 8,+ paddingInline: 8,+ borderRadius: cssVar.borderRadiusLG,+ cursor: 'pointer',+ backgroundColor: {+ 'default': 'transparent',+ ':hover': cssVar.colorFillQuaternary,+ },+ },+ text: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ minWidth: 0,+ },+});++/** The cell every GitHub row shares with the Market's skill rows: icon, two lines, an action. */+const Row = ({+ action,+ icon,+ onOpen,+ subtitle,+ title,+}: {+ action?: ReactNode;+ icon: ReactNode;+ onOpen: () => void;+ subtitle: ReactNode;+ title: ReactNode;+}) => (+ <div {...stylex.props(styles.row)} onClick={onOpen}>+ {icon}+ <span {...stylex.props(styles.text)}>+ <Text ellipsis weight={500}>+ {title}+ </Text>+ {subtitle}+ </span>+ {action && (+ <span {...stylex.props(styles.action)} onClick={(event) => event.stopPropagation()}>+ {action}+ </span>+ )}+ </div>+);++const GithubTile = memo<{ avatar?: string; size: number }>(({ avatar, size }) => (+ <IconTile size={size}>+ {avatar ? (+ <Avatar avatar={avatar} shape={'square'} size={size} />+ ) : (+ <GithubIcon size={Math.round(size * 0.5)} />+ )}+ </IconTile>+));++GithubTile.displayName = 'MarketGithubTile';++/** A typed or pasted GitHub address, offered as the first search result. */+export const GithubAddressRow = memo<{ onOpen: () => void; repo: string }>(({ onOpen, repo }) => {+ const { t } = useTranslation('setting');+ return (+ <Row+ icon={<GithubTile size={40} />}+ title={repo}+ subtitle={+ <Text ellipsis fontSize={12} type={'secondary'}>+ {t('market.skills.github.addressHint')}+ </Text>+ }+ onOpen={onOpen}+ />+ );+});++GithubAddressRow.displayName = 'MarketGithubAddressRow';++/** A public repository from GitHub search; opening it scans it for skills. */+export const GithubRepoRow = memo<{ hit: GithubRepoHit; onOpen: () => void }>(({ hit, onOpen }) => (+ <Row+ icon={<GithubTile avatar={hit.avatar} size={40} />}+ title={hit.fullName}+ action={+ <Text fontSize={12} type={'secondary'}>+ <Icon icon={StarIcon} size={12} /> {hit.stars.toLocaleString()}+ </Text>+ }+ subtitle={+ hit.description ? (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {hit.description}+ </Text>+ ) : undefined+ }+ onOpen={onOpen}+ />+));++GithubRepoRow.displayName = 'MarketGithubRepoRow';++/**+ * A skill installed from GitHub: its repository under the name, and an Update+ * button when GitHub has a newer version. Its menu opens it on GitHub or+ * uninstalls it; the row itself opens its repository page to rescan.+ */+export const GithubSkillRow = memo<{+ check?: GitHubSkillCheck;+ onOpen: () => void;+ skill: AgentSkillListItem;+}>(({ check, onOpen, skill }) => {+ const { t } = useTranslation('setting');+ const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);+ const { error, pending, update } = useApplyGithubUpdate(skill.id, check);+ const [removing, setRemoving] = useState(false);+ const repo = githubSkillRepo(skill);+ const sourceUrl = skill.manifest?.sourceUrl ?? (repo ? `https://github.com/${repo}` : undefined);++ const uninstall = async () => {+ setRemoving(true);+ try {+ await deleteAgentSkill(skill.id);+ } catch (cause) {+ console.warn('[Market] Failed to uninstall skill:', cause);+ } finally {+ setRemoving(false);+ }+ };++ return (+ <Row+ icon={<SkillIcon size={40} />}+ title={skill.name}+ action={+ <>+ {check?.status === 'update' && (+ <Button loading={pending} type={'fill'} onClick={update}>+ {t('market.skills.github.updateOne')}+ </Button>+ )}+ <DropdownMenu+ placement={'bottomRight'}+ items={[+ ...(sourceUrl+ ? [+ {+ icon: <Icon icon={ExternalLinkIcon} />,+ key: 'open',+ label: t('market.skills.github.openOnGithub'),+ onClick: () => window.open(sourceUrl, '_blank', 'noopener,noreferrer'),+ },+ ]+ : []),+ {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'uninstall',+ label: t('market.skills.uninstall'),+ onClick: () => void uninstall(),+ },+ ]}+ >+ <ActionIcon icon={MoreHorizontalIcon} loading={removing} />+ </DropdownMenu>+ </>+ }+ subtitle={+ <Text ellipsis fontSize={12} type={error ? 'danger' : 'secondary'}>+ {error+ ? t('market.skills.github.updateFailed')+ : [repo, skill.description].filter(Boolean).join(' · ')}+ </Text>+ }+ onOpen={onOpen}+ />+ );+});++GithubSkillRow.displayName = 'MarketGithubSkillRow';diff --git a/src/features/Marketplace/Skills/github/GithubSkillGroups.tsx b/src/features/Marketplace/Skills/github/GithubSkillGroups.tsxnew file mode 100644index 00000000000..db37fca411a--- /dev/null+++ b/src/features/Marketplace/Skills/github/GithubSkillGroups.tsx@@ -0,0 +1,103 @@+import { Skeleton, Text } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { useQuery } from '@tanstack/react-query';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useToolStore } from '@/store/tool';+import { agentSkillsSelectors } from '@/store/tool/selectors';++import { useSkillsNav } from '../useSkillsNav';+import { githubSkillUrl } from './githubInstalled';+import { GithubRepoRow, GithubSkillRow } from './GithubRows';+import { GithubSearchLimitError, searchGithubRepos } from './searchGithubRepos';+import { useGithubSkillUpdates } from './useGithubSkillUpdates';++const styles = stylex.create({+ grid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',+ columnGap: 16,+ rowGap: 4,+ },+});++/** Skills in the library that were installed from GitHub, with the address each tracks. */+export const useInstalledGithubSkills = (query = '') => {+ const skills = useToolStore(agentSkillsSelectors.getUserAgentSkills);+ return useMemo(() => {+ const q = query.trim().toLowerCase();+ return skills.flatMap((skill) => {+ const url = githubSkillUrl(skill);+ if (!url) return [];+ if (q && ![skill.name, skill.description ?? '', url].some((v) => v.toLowerCase().includes(q)))+ return [];+ return [{ skill, url }];+ });+ }, [query, skills]);+};++/**+ * The installed GitHub skills as rows. Opening the group checks GitHub once for+ * newer versions; a row with one offers Update.+ */+export const InstalledGithubSkills = memo<{ items: ReturnType<typeof useInstalledGithubSkills> }>(+ ({ items }) => {+ const { setGithubUrl } = useSkillsNav();+ const { data: checks } = useGithubSkillUpdates(items.length > 0);+ return (+ <div {...stylex.props(styles.grid)}>+ {items.map(({ skill, url }) => (+ <GithubSkillRow+ check={checks?.[skill.id]}+ key={skill.id}+ skill={skill}+ onOpen={() => setGithubUrl(url)}+ />+ ))}+ </div>+ );+ },+);++InstalledGithubSkills.displayName = 'MarketInstalledGithubSkills';++/**+ * Public GitHub repositories matching a search, each opening its import page.+ * GitHub allows ten anonymous searches a minute, so the query is the debounced+ * one and an answer is kept for five minutes.+ */+export const GithubSearchResults = memo<{ query: string }>(({ query }) => {+ const { t } = useTranslation('setting');+ const { setGithubUrl } = useSkillsNav();+ const { data, error, isLoading } = useQuery({+ enabled: query.trim().length >= 2,+ queryFn: ({ signal }) => searchGithubRepos(query, { signal }),+ queryKey: ['market', 'githubSkillRepos', query.trim().toLowerCase()],+ retry: false,+ staleTime: 5 * 60 * 1000,+ });++ if (isLoading) return <Skeleton.Text rows={2} />;+ if (error)+ return (+ <Text type={'secondary'}>+ {t(+ error instanceof GithubSearchLimitError+ ? 'market.skills.github.searchLimited'+ : 'market.skills.github.searchFailed',+ )}+ </Text>+ );+ if (!data?.length) return <Text type={'secondary'}>{t('market.skills.github.searchEmpty')}</Text>;++ return (+ <div {...stylex.props(styles.grid)}>+ {data.map((hit) => (+ <GithubRepoRow hit={hit} key={hit.fullName} onOpen={() => setGithubUrl(hit.url)} />+ ))}+ </div>+ );+});++GithubSearchResults.displayName = 'MarketGithubSearchResults';diff --git a/src/features/Marketplace/Skills/github/githubInstalled.test.ts b/src/features/Marketplace/Skills/github/githubInstalled.test.tsnew file mode 100644index 00000000000..fbf6d62b316--- /dev/null+++ b/src/features/Marketplace/Skills/github/githubInstalled.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';++import { githubSkillRepo, githubSkillUrl } from './githubInstalled';++const manifest = { name: 'pdf' } as any;++describe('githubSkillUrl', () => {+ it('points at the tracked folder and ref', () => {+ const skill = {+ manifest,+ source: 'user' as const,+ upstream: { owner: 'o', path: 'skills/pdf', ref: 'main', repo: 'r' },+ };+ expect(githubSkillUrl(skill)).toBe('https://github.com/o/r/tree/main/skills/pdf');+ expect(githubSkillRepo(skill)).toBe('o/r');+ });++ it('points at the repository for a skill at its root', () => {+ expect(+ githubSkillUrl({+ manifest,+ source: 'user',+ upstream: { owner: 'o', path: '', ref: 'HEAD', repo: 'r' },+ }),+ ).toBe('https://github.com/o/r');+ });++ it('falls back to the address an untracked import came from', () => {+ expect(+ githubSkillUrl({+ manifest: { ...manifest, sourceUrl: 'https://github.com/o/r/tree/dev/a' },+ source: 'user',+ }),+ ).toBe('https://github.com/o/r/tree/dev/a');+ });++ it('is null for market skills and skills written by hand', () => {+ expect(githubSkillUrl({ manifest, source: 'market' })).toBeNull();+ expect(githubSkillUrl({ manifest, source: 'user' })).toBeNull();+ });+});diff --git a/src/features/Marketplace/Skills/github/githubInstalled.ts b/src/features/Marketplace/Skills/github/githubInstalled.tsnew file mode 100644index 00000000000..4a4f7a10009--- /dev/null+++ b/src/features/Marketplace/Skills/github/githubInstalled.ts@@ -0,0 +1,25 @@+import type { GitHubSkillUpstream, SkillListItem } from '@lobechat/types';++import { parseGithubSource } from './githubSource';++type InstalledSkill = Pick<SkillListItem, 'manifest' | 'source' | 'upstream'>;++/** The `https://github.com/…` folder a skill installed from GitHub tracks, or `null`. */+export const githubSkillUrl = (skill: InstalledSkill): string | null => {+ if (skill.source !== 'user') return null;+ const upstream: GitHubSkillUpstream | null | undefined = skill.upstream;+ if (upstream) {+ const base = `https://github.com/${upstream.owner}/${upstream.repo}`;+ return upstream.path ? `${base}/tree/${upstream.ref || 'HEAD'}/${upstream.path}` : base;+ }+ // Imports from before tracking only kept the address they came from.+ const sourceUrl = skill.manifest?.sourceUrl;+ return sourceUrl ? (parseGithubSource(sourceUrl)?.url ?? null) : null;+};++/** `owner/repo` of a skill installed from GitHub, for its row. */+export const githubSkillRepo = (skill: InstalledSkill): string | null => {+ const url = githubSkillUrl(skill);+ const source = url && parseGithubSource(url);+ return source ? `${source.owner}/${source.repo}` : null;+};diff --git a/src/features/Marketplace/Skills/github/githubSource.test.ts b/src/features/Marketplace/Skills/github/githubSource.test.tsnew file mode 100644index 00000000000..a8071922275--- /dev/null+++ b/src/features/Marketplace/Skills/github/githubSource.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest';++import { parseGithubSource } from './githubSource';++describe('parseGithubSource', () => {+ it('reads owner/repo as the whole repository', () => {+ expect(parseGithubSource('anthropics/skills')).toEqual({+ owner: 'anthropics',+ repo: 'skills',+ url: 'https://github.com/anthropics/skills',+ });+ });++ it('reads a GitHub address with or without its scheme', () => {+ expect(parseGithubSource('github.com/anthropics/skills.git')?.url).toBe(+ 'https://github.com/anthropics/skills',+ );+ expect(parseGithubSource('https://www.github.com/anthropics/skills/')?.url).toBe(+ 'https://github.com/anthropics/skills',+ );+ });++ it('keeps the ref and folder of a tree URL', () => {+ expect(+ parseGithubSource('https://github.com/anthropics/skills/tree/main/skills/pdf'),+ ).toMatchObject({+ path: 'skills/pdf',+ ref: 'main',+ url: 'https://github.com/anthropics/skills/tree/main/skills/pdf',+ });+ });++ it('turns a SKILL.md blob link into its folder', () => {+ expect(+ parseGithubSource('https://github.com/o/r/blob/dev/.claude/skills/x/SKILL.md'),+ ).toMatchObject({ path: '.claude/skills/x', ref: 'dev' });+ });++ it('follows the default branch for a HEAD folder link', () => {+ expect(parseGithubSource('https://github.com/o/r/tree/HEAD/skills/a')).toMatchObject({+ path: 'skills/a',+ ref: undefined,+ url: 'https://github.com/o/r/tree/HEAD/skills/a',+ });+ });++ it('reads an SSH clone address', () => {+ expect(parseGithubSource('[email protected]:o/r.git')?.url).toBe('https://github.com/o/r');+ });++ it('takes the source out of an `npx skills add` command', () => {+ expect(parseGithubSource('npx skills add vercel-labs/agent-skills --skill react')?.url).toBe(+ 'https://github.com/vercel-labs/agent-skills',+ );+ expect(parseGithubSource('pnpm dlx skills add https://github.com/o/r')?.url).toBe(+ 'https://github.com/o/r',+ );+ });++ it('leaves search words and other hosts alone', () => {+ expect(parseGithubSource('pdf')).toBeNull();+ expect(parseGithubSource('pdf tools')).toBeNull();+ expect(parseGithubSource('https://gitlab.com/o/r')).toBeNull();+ expect(parseGithubSource('https://github.com/o')).toBeNull();+ expect(parseGithubSource('a/b/c')).toBeNull();+ });+});diff --git a/src/features/Marketplace/Skills/github/githubSource.ts b/src/features/Marketplace/Skills/github/githubSource.tsnew file mode 100644index 00000000000..da196a8984e--- /dev/null+++ b/src/features/Marketplace/Skills/github/githubSource.ts@@ -0,0 +1,71 @@+/** A GitHub repository, optionally narrowed to a ref and a folder, as the importer reads it. */+export interface GithubSource {+ owner: string;+ /** Folder inside the repository; absent for the whole repository. */+ path?: string;+ /** Branch, tag or commit; absent for the default branch. */+ ref?: string;+ repo: string;+ /** The `https://github.com/…` address the server's GitHub importer takes. */+ url: string;+}++const NAME = /^[\w.-]+$/;++/** `npx skills add owner/repo --skill x`, and the same through bunx, pnpm dlx, yarn dlx. */+const SKILLS_COMMAND =+ /^(?:npx|bunx|pnpx|pnpm\s+dlx|yarn\s+dlx|bun\s+x)\s+(?:-y\s+)?skills(?:@\S+)?\s+add\s+(\S+)/i;++const build = (owner: string, repo: string, ref?: string, path?: string): GithubSource | null => {+ const name = repo.replace(/\.git$/i, '');+ if (!NAME.test(owner) || !NAME.test(name) || name === '.' || name === '..') return null;+ const folder = path?.replace(/\/SKILL\.md$/i, '').replaceAll(/^\/+|\/+$/g, '') || undefined;+ const branch = ref && ref !== 'HEAD' ? ref : undefined;+ const base = `https://github.com/${owner}/${name}`;+ const url = folder+ ? `${base}/tree/${branch ?? 'HEAD'}/${folder}`+ : branch+ ? `${base}/tree/${branch}`+ : base;+ return { owner, path: folder, ref: branch, repo: name, url };+};++/**+ * Reads what a person pastes or types as a GitHub skill source: `owner/repo`,+ * `github.com/owner/repo`, a full URL down to a `/tree/<ref>/<folder>` or a+ * `/blob/<ref>/<folder>/SKILL.md`, `[email protected]:owner/repo.git`, or an+ * `npx skills add owner/repo` command. Anything else (a plain search word,+ * another host) is `null`.+ */+export const parseGithubSource = (input: string): GithubSource | null => {+ let text = input.trim();+ if (!text) return null;++ const command = text.match(SKILLS_COMMAND);+ if (command) text = command[1];++ const ssh = text.match(/^git@github\.com:([^/\s]+)\/([^/\s]+?)\/?$/i);+ if (ssh) return build(ssh[1], ssh[2]);++ // Bare `owner/repo`. A third segment would be ambiguous with a search phrase.+ const short = text.match(/^([\w.-]+)\/([\w.-]+)$/);+ if (short) return build(short[1], short[2]);++ let address = text;+ if (/^(?:www\.)?github\.com\//i.test(address)) address = 'https://' + address;+ let url: URL;+ try {+ url = new URL(address);+ } catch {+ return null;+ }+ if (!/^https?:$/.test(url.protocol)) return null;+ if (!/^(?:www\.)?github\.com$/i.test(url.hostname)) return null;++ const parts = url.pathname.split('/').filter(Boolean).map(decodeURIComponent);+ if (parts.length < 2) return null;+ const [owner, repo, kind, ref, ...rest] = parts;+ if (kind === 'tree' || kind === 'blob')+ return ref ? build(owner, repo, ref, rest.join('/')) : null;+ return build(owner, repo);+};diff --git a/src/features/Marketplace/Skills/github/searchGithubRepos.test.ts b/src/features/Marketplace/Skills/github/searchGithubRepos.test.tsnew file mode 100644index 00000000000..b02657694ef--- /dev/null+++ b/src/features/Marketplace/Skills/github/searchGithubRepos.test.ts@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { GithubSearchLimitError, searchGithubRepos } from './searchGithubRepos';++const respond = (body: unknown, init?: ResponseInit) =>+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify(body), init));++afterEach(() => {+ vi.restoreAllMocks();+});++describe('searchGithubRepos', () => {+ it('searches skill repositories, without forks or archived ones', async () => {+ const fetch = respond({+ items: [+ {+ description: 'PDF skills',+ full_name: 'o/pdf-skills',+ html_url: 'https://github.com/o/pdf-skills',+ owner: { avatar_url: 'https://avatars/o' },+ stargazers_count: 42,+ },+ ],+ });++ const hits = await searchGithubRepos(' pdf ', { limit: 3 });++ const url = new URL(String(fetch.mock.calls[0][0]));+ expect(url.origin + url.pathname).toBe('https://api.github.com/search/repositories');+ expect(url.searchParams.get('q')).toBe('pdf skill fork:false archived:false');+ expect(url.searchParams.get('per_page')).toBe('3');+ expect(hits).toEqual([+ {+ avatar: 'https://avatars/o',+ description: 'PDF skills',+ fullName: 'o/pdf-skills',+ stars: 42,+ url: 'https://github.com/o/pdf-skills',+ },+ ]);+ });++ it('tells a rate limit apart from other failures', async () => {+ respond({}, { headers: { 'x-ratelimit-remaining': '0' }, status: 403 });+ await expect(searchGithubRepos('pdf')).rejects.toBeInstanceOf(GithubSearchLimitError);++ respond({}, { status: 500 });+ await expect(searchGithubRepos('pdf')).rejects.not.toBeInstanceOf(GithubSearchLimitError);+ });+});diff --git a/src/features/Marketplace/Skills/github/searchGithubRepos.ts b/src/features/Marketplace/Skills/github/searchGithubRepos.tsnew file mode 100644index 00000000000..f70fb061f1e--- /dev/null+++ b/src/features/Marketplace/Skills/github/searchGithubRepos.ts@@ -0,0 +1,57 @@+/** One public repository from GitHub's repository search. */+export interface GithubRepoHit {+ avatar: string;+ description: string | null;+ fullName: string;+ stars: number;+ url: string;+}++/** GitHub allows ten anonymous searches a minute; past that it answers 403/429. */+export class GithubSearchLimitError extends Error {+ constructor() {+ super('GitHub search rate limit reached');+ this.name = 'GithubSearchLimitError';+ }+}++interface SearchResponse {+ items?: Array<{+ description: string | null;+ full_name: string;+ html_url: string;+ owner?: { avatar_url?: string };+ stargazers_count: number;+ }>;+}++/**+ * Public GitHub repositories that look like they hold skills for `query`. The+ * word "skill" narrows the search to repositories that call themselves one+ * (GitHub matches "skills" too); forks and archived repositories are left out.+ * Private repositories are added by address, not found here.+ */+export const searchGithubRepos = async (+ query: string,+ { limit = 6, signal }: { limit?: number; signal?: AbortSignal } = {},+): Promise<GithubRepoHit[]> => {+ const q = `${query.trim()} skill fork:false archived:false`;+ const response = await fetch(+ `https://api.github.com/search/repositories?q=${encodeURIComponent(q)}&per_page=${limit}`,+ { headers: { Accept: 'application/vnd.github+json' }, signal },+ );+ if (+ response.status === 429 ||+ (response.status === 403 && response.headers.get('x-ratelimit-remaining') === '0')+ )+ throw new GithubSearchLimitError();+ if (!response.ok) throw new Error(`GitHub search failed: ${response.status}`);+ const data = (await response.json()) as SearchResponse;+ return (data.items ?? []).map((item) => ({+ avatar: item.owner?.avatar_url ?? '',+ description: item.description,+ fullName: item.full_name,+ stars: item.stargazers_count,+ url: item.html_url,+ }));+};diff --git a/src/features/Marketplace/Skills/github/useGithubSkillImport.ts b/src/features/Marketplace/Skills/github/useGithubSkillImport.tsnew file mode 100644index 00000000000..635d9973bcc--- /dev/null+++ b/src/features/Marketplace/Skills/github/useGithubSkillImport.ts@@ -0,0 +1,152 @@+import type {+ GitHubSkillCandidate,+ GitHubSkillDiscovery,+ GitHubSkillOutcome,+} from '@lobechat/types';+import { useCallback, useEffect, useRef, useState } from 'react';++import { normalizeAsyncError } from '@/libs/swr/normalizeError';+import { agentSkillService } from '@/services/skill';+import { useToolStore } from '@/store/tool';++import { parseGithubSource } from './githubSource';++export interface GithubSkillImportFailure {+ /** The server's own message, for anything without a recovery. */+ details?: string;+ /**+ * `access`: the repository is private or missing for the GitHub access we+ * have, so it needs GitHub connected or a token in the Vault.+ * `connect`: GitHub is not connected at all.+ */+ recovery?: 'access' | 'connect';+ stage: 'find' | 'import' | 'refresh';+}++/** Skills a scan can install: new ones, and newer versions of installed ones. */+export const canImportCandidate = ({ status }: Pick<GitHubSkillCandidate, 'status'>) =>+ status === 'new' || status === 'update';++const importFailure = (error: unknown, stage: 'find' | 'import'): GithubSkillImportFailure => {+ const { code } = normalizeAsyncError(error);+ if (code === 'PRECONDITION_FAILED') return { recovery: 'connect', stage };+ if (code === 'NOT_FOUND') return { recovery: 'access', stage };+ return { details: error instanceof Error ? error.message : String(error), stage };+};++/**+ * The scan → pick → install state of one GitHub repository page. The scan+ * pins a commit, so what is installed is what was listed; one request runs at+ * a time, and a failure stays apart from the per-skill outcomes of a batch.+ */+export const useGithubSkillImport = (initialUrl: string) => {+ const refresh = useToolStore((s) => s.refreshAgentSkills);+ const [pending, setPending] = useState<GithubSkillImportFailure['stage']>();+ const [failure, setFailure] = useState<GithubSkillImportFailure>();+ const [input, setInputValue] = useState(initialUrl);+ const [scan, setScan] = useState<GitHubSkillDiscovery & { url: string }>();+ const [selected, setSelected] = useState<string[]>([]);+ const [results, setResults] = useState<GitHubSkillOutcome[]>([]);+ const busy = useRef(false);++ const source = parseGithubSource(input);+ const candidates = scan?.candidates ?? [];++ /** A scan belongs to the address it was read from, so editing the address drops it. */+ const setInput = (value: string) => {+ setInputValue(value);+ setScan(undefined);+ setResults([]);+ setFailure(undefined);+ };++ const discover = useCallback(async () => {+ const url = parseGithubSource(input)?.url;+ if (!url || busy.current) return;+ busy.current = true;+ setPending('find');+ setFailure(undefined);+ try {+ const next = await agentSkillService.discoverGitHubSkills(url);+ const found = next.candidates ?? [];+ setScan({ ...next, candidates: found, url });+ setResults([]);+ // Everything installable starts picked: adding a repository usually means all of it.+ setSelected(found.filter(canImportCandidate).map((item) => item.path));+ } catch (error) {+ setScan(undefined);+ setFailure(importFailure(error, 'find'));+ } finally {+ busy.current = false;+ setPending(undefined);+ }+ }, [input]);++ // A repository opened from search or from an installed skill scans right away.+ const started = useRef(false);+ useEffect(() => {+ if (started.current || !parseGithubSource(initialUrl)) return;+ started.current = true;+ void discover();+ }, [discover, initialUrl]);++ const refreshLibrary = async () => {+ setPending('refresh');+ setFailure(undefined);+ try {+ await refresh();+ } catch (error) {+ setFailure({+ details: error instanceof Error ? error.message : String(error),+ stage: 'refresh',+ });+ } finally {+ setPending(undefined);+ }+ };++ const install = async (paths: string[]) => {+ if (!scan || !paths.length || busy.current) return;+ busy.current = true;+ setPending('import');+ setFailure(undefined);+ try {+ const batch = await agentSkillService.importGitHubSkills({+ commit: scan.commit,+ gitUrl: scan.url,+ scope: scan.scope,+ selections: candidates+ .filter((item) => paths.includes(item.path))+ .map(({ path, revision }) => ({ path, revision })),+ });+ setResults((prev) => [...prev.filter((item) => !paths.includes(item.path)), ...batch]);+ setSelected((prev) => prev.filter((path) => !paths.includes(path)));+ } catch (error) {+ setFailure(importFailure(error, 'import'));+ busy.current = false;+ setPending(undefined);+ return;+ }+ busy.current = false;+ await refreshLibrary();+ };++ return {+ candidates,+ discover,+ failure,+ input,+ install,+ loading: !!pending,+ pending,+ refreshLibrary,+ results,+ scan,+ selected,+ setInput,+ setSelected,+ source,+ };+};++export type GithubSkillImportState = ReturnType<typeof useGithubSkillImport>;diff --git a/src/features/Marketplace/Skills/github/useGithubSkillUpdates.ts b/src/features/Marketplace/Skills/github/useGithubSkillUpdates.tsnew file mode 100644index 00000000000..50aa6170a30--- /dev/null+++ b/src/features/Marketplace/Skills/github/useGithubSkillUpdates.ts@@ -0,0 +1,76 @@+import type { GitHubSkillCheck } from '@lobechat/types';+import { confirmModal } from '@lobehub/ui';+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { agentSkillService } from '@/services/skill';+import { useToolStore } from '@/store/tool';++const QUERY_KEY = ['market', 'githubSkillUpdates'];++/**+ * Whether each skill installed from GitHub has a newer version there, by skill+ * id. One check covers the whole library (the server groups skills by repository+ * and ref), so it runs only while a list of GitHub skills is on screen, and+ * stays fresh for ten minutes.+ */+export const useGithubSkillUpdates = (enabled: boolean) =>+ useQuery({+ enabled,+ queryFn: () => agentSkillService.checkGitHubUpdates(),+ queryKey: QUERY_KEY,+ retry: false,+ staleTime: 10 * 60 * 1000,+ });++/**+ * Take the update a check found for one skill. A skill changed here since it+ * was installed asks before GitHub's version replaces those changes.+ */+export const useApplyGithubUpdate = (id: string, check: GitHubSkillCheck | undefined) => {+ const { t } = useTranslation('setting');+ const queryClient = useQueryClient();+ const refresh = useToolStore((s) => s.refreshAgentSkills);+ const [pending, setPending] = useState(false);+ const [error, setError] = useState(false);++ const run = useCallback(+ async (overwriteLocal: boolean) => {+ if (check?.status !== 'update') return;+ setPending(true);+ setError(false);+ try {+ await agentSkillService.applyGitHubUpdate({+ commit: check.commit,+ id,+ overwriteLocal,+ revision: check.revision,+ });+ await refresh();+ await queryClient.invalidateQueries({ queryKey: QUERY_KEY });+ } catch (cause) {+ console.warn('[Market] Failed to update GitHub skill:', cause);+ setError(true);+ } finally {+ setPending(false);+ }+ },+ [check, id, queryClient, refresh],+ );++ const update = useCallback(() => {+ if (check?.status !== 'update') return;+ if (!check.localChanges) return void run(false);+ confirmModal({+ cancelText: t('market.skills.github.localChanges.cancel'),+ content: t('market.skills.github.localChanges.content'),+ okButtonProps: { danger: true },+ okText: t('market.skills.github.localChanges.ok'),+ onOk: () => run(true),+ title: t('market.skills.github.localChanges.title'),+ });+ }, [check, run, t]);++ return { error, pending, update };+};diff --git a/src/features/Marketplace/Skills/skillCategoryStyle.test.ts b/src/features/Marketplace/Skills/skillCategoryStyle.test.tsnew file mode 100644index 00000000000..7b2c424667e--- /dev/null+++ b/src/features/Marketplace/Skills/skillCategoryStyle.test.ts@@ -0,0 +1,25 @@+import { SkillCategory } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { getSkillCategoryStyle } from './skillCategoryStyle';++describe('getSkillCategoryStyle', () => {+ it('gives every market category a tile color, a three-stop gradient and an icon', () => {+ const categories = Object.values(SkillCategory).filter((value) => value !== SkillCategory.All);++ for (const category of categories) {+ const style = getSkillCategoryStyle(category);+ expect(style, category).toBeDefined();+ expect(style!.tile).toMatch(/^#[\dA-F]{6}$/i);+ expect(style!.gradient).toHaveLength(3);+ style!.gradient.forEach((stop) => expect(stop).toMatch(/^#[\dA-F]{6}$/i));+ expect(style!.icon).toBeTruthy();+ }+ });++ it('has no style for a missing or unknown category, so the plain Surface tile shows', () => {+ expect(getSkillCategoryStyle()).toBeUndefined();+ expect(getSkillCategoryStyle(null)).toBeUndefined();+ expect(getSkillCategoryStyle('not-a-category')).toBeUndefined();+ });+});diff --git a/src/features/Marketplace/Skills/skillCategoryStyle.ts b/src/features/Marketplace/Skills/skillCategoryStyle.tsnew file mode 100644index 00000000000..e7a2c7c0177--- /dev/null+++ b/src/features/Marketplace/Skills/skillCategoryStyle.ts@@ -0,0 +1,112 @@+import {+ Apple,+ AudioLines,+ BookOpen,+ CalendarDays,+ Car,+ ChartColumn,+ CircleCheck,+ Clapperboard,+ Cloud,+ Code,+ FileText,+ Gamepad2,+ GitBranch,+ Globe,+ HeartPulse,+ House,+ Image,+ type LucideIcon,+ Megaphone,+ MessagesSquare,+ Network,+ NotebookPen,+ PanelsTopLeft,+ Search,+ ShieldCheck,+ ShoppingBag,+ Smartphone,+ Sparkles,+ Sprout,+ SquareTerminal,+ Wallet,+ Workflow,+ Wrench,+} from 'lucide-react';++/** Grainient takes hex stops, so a hue is three of them plus the solid tile color. */+interface Hue {+ /**+ * Stops for the gradient behind a skill's preview: two neighboring shades of+ * the hue around its base, so the blend stays calm rather than two-toned.+ */+ gradient: [string, string, string];+ /** Solid background of the skill's icon tile; the glyph on it is white. */+ tile: string;+}++const HUES = {+ amber: { gradient: ['#FCC53A', '#F59E0B', '#F7A21B'], tile: '#D9930D' },+ blue: { gradient: ['#60A5FA', '#3B82F6', '#4F7CF7'], tile: '#3B7BEA' },+ cyan: { gradient: ['#22D3EE', '#06B6D4', '#0EA5E9'], tile: '#0E9EBF' },+ green: { gradient: ['#4ADE80', '#22C55E', '#16A34A'], tile: '#2E9A57' },+ indigo: { gradient: ['#818CF8', '#6366F1', '#7C6CF2'], tile: '#5B5BD6' },+ orange: { gradient: ['#FB923C', '#F97316', '#F05A28'], tile: '#EE8530' },+ pink: { gradient: ['#F472B6', '#EC4899', '#F0508A'], tile: '#C94B85' },+ purple: { gradient: ['#A78BFA', '#8B5CF6', '#9F5CF0'], tile: '#7C5CDB' },+ red: { gradient: ['#F87171', '#EF4444', '#F2553C'], tile: '#DC4A4F' },+ slate: { gradient: ['#94A3B8', '#64748B', '#6B7A90'], tile: '#5F6B7A' },+ teal: { gradient: ['#2DD4BF', '#14B8A6', '#10B981'], tile: '#13998A' },+} satisfies Record<string, Hue>;++type HueName = keyof typeof HUES;++/** Each Market skill category's hue and glyph, keyed by `SkillCategory` value. */+const CATEGORY_STYLE: Record<string, { hue: HueName; icon: LucideIcon }> = {+ 'agent-to-agent-protocols': { hue: 'indigo', icon: Network },+ 'ai-llms': { hue: 'purple', icon: Sparkles },+ 'apple-apps-services': { hue: 'slate', icon: Apple },+ 'browser-automation': { hue: 'blue', icon: Globe },+ 'calendar-scheduling': { hue: 'orange', icon: CalendarDays },+ 'cli-utilities': { hue: 'slate', icon: SquareTerminal },+ 'clawdbot-tools': { hue: 'red', icon: Wrench },+ 'coding-agents-ides': { hue: 'indigo', icon: Code },+ 'communication': { hue: 'teal', icon: MessagesSquare },+ 'data-analytics': { hue: 'blue', icon: ChartColumn },+ 'devops-cloud': { hue: 'cyan', icon: Cloud },+ 'finance': { hue: 'green', icon: Wallet },+ 'gaming': { hue: 'pink', icon: Gamepad2 },+ 'git-github': { hue: 'orange', icon: GitBranch },+ 'health-fitness': { hue: 'green', icon: HeartPulse },+ 'image-video-generation': { hue: 'pink', icon: Image },+ 'ios-macos-development': { hue: 'blue', icon: Smartphone },+ 'marketing-sales': { hue: 'amber', icon: Megaphone },+ 'media-streaming': { hue: 'red', icon: Clapperboard },+ 'moltbook': { hue: 'amber', icon: BookOpen },+ 'notes-pkm': { hue: 'amber', icon: NotebookPen },+ 'pdf-documents': { hue: 'purple', icon: FileText },+ 'personal-development': { hue: 'teal', icon: Sprout },+ 'productivity-tasks': { hue: 'orange', icon: CircleCheck },+ 'search-research': { hue: 'blue', icon: Search },+ 'security-passwords': { hue: 'green', icon: ShieldCheck },+ 'self-hosted-automation': { hue: 'cyan', icon: Workflow },+ 'shopping-ecommerce': { hue: 'pink', icon: ShoppingBag },+ 'smart-home-iot': { hue: 'teal', icon: House },+ 'speech-transcription': { hue: 'purple', icon: AudioLines },+ 'transportation': { hue: 'blue', icon: Car },+ 'web-frontend-development': { hue: 'cyan', icon: PanelsTopLeft },+};++export interface SkillCategoryStyle extends Hue {+ icon: LucideIcon;+}++/** A category's tile color, gradient and glyph; `undefined` for none or an unknown one. */+export const getSkillCategoryStyle = (category?: string | null): SkillCategoryStyle | undefined => {+ const style = category ? CATEGORY_STYLE[category] : undefined;+ if (!style) return undefined;+ return { ...HUES[style.hue], icon: style.icon };+};++/** The gradient behind a skill that has no category to color it. */+export const DEFAULT_SKILL_GRADIENT: Hue['gradient'] = HUES.slate.gradient;diff --git a/src/features/Marketplace/Skills/useMarketSkillInstall.ts b/src/features/Marketplace/Skills/useMarketSkillInstall.tsnew file mode 100644index 00000000000..0cd45c29762--- /dev/null+++ b/src/features/Marketplace/Skills/useMarketSkillInstall.ts@@ -0,0 +1,58 @@+import { useCallback, useState } from 'react';++import { agentSkillService } from '@/services/skill';+import { useToolStore } from '@/store/tool';+import { agentSkillsSelectors } from '@/store/tool/selectors';++/**+ * Whether a market skill is installed in the active scope, and the actions that+ * install and uninstall it. Installing only adds it to the skill library;+ * assistants still enable it themselves.+ */+export const useMarketSkillInstall = (identifier: string) => {+ // The library row, whose id the uninstall needs.+ const installedId = useToolStore(+ (s) =>+ agentSkillsSelectors.getMarketAgentSkills(s).find((skill) => skill.identifier === identifier)+ ?.id,+ );+ const installed = !!installedId;+ const refreshAgentSkills = useToolStore((s) => s.refreshAgentSkills);+ const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);+ const [pending, setPending] = useState(false);+ const [error, setError] = useState(false);++ /** Resolves `true` once the skill is in the library. */+ const install = useCallback(async () => {+ if (pending || installed) return installed;+ setPending(true);+ setError(false);+ try {+ await agentSkillService.importFromMarket(identifier);+ await refreshAgentSkills();+ return true;+ } catch (cause) {+ console.warn('[Market] Failed to install skill:', cause);+ setError(true);+ return false;+ } finally {+ setPending(false);+ }+ }, [identifier, installed, pending, refreshAgentSkills]);++ const uninstall = useCallback(async () => {+ if (pending || !installedId) return;+ setPending(true);+ setError(false);+ try {+ await deleteAgentSkill(installedId);+ } catch (cause) {+ console.warn('[Market] Failed to uninstall skill:', cause);+ setError(true);+ } finally {+ setPending(false);+ }+ }, [deleteAgentSkill, installedId, pending]);++ return { error, install, installed, pending, uninstall };+};diff --git a/src/features/Marketplace/Skills/useSkillAgents.test.ts b/src/features/Marketplace/Skills/useSkillAgents.test.tsnew file mode 100644index 00000000000..292f03cf74c--- /dev/null+++ b/src/features/Marketplace/Skills/useSkillAgents.test.ts@@ -0,0 +1,138 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useSkillAgents } from './useSkillAgents';++const service = vi.hoisted(() => ({+ getPluginAgentModes: vi.fn(),+ setPluginMode: vi.fn(),+}));+const agentStore = vi.hoisted(() => ({+ agentMap: {} as Record<string, object>,+ internal_dispatchAgentMap: vi.fn(),+}));+const toastError = vi.hoisted(() => vi.fn());++const agents = [+ { id: 'agt_a', title: 'A', type: 'agent' },+ { id: 'agt_b', title: 'B', type: 'agent' },+ { id: 'agt_c', title: 'C', type: 'agent' },+ { heterogeneousType: 'claude-code', id: 'agt_cc', title: 'CC', type: 'agent' },+ { id: 'grp_1', title: 'G', type: 'group' },+];++vi.mock('@lobehub/ui', () => ({ toast: { error: toastError } }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/services/agent', () => ({ agentService: service }));+vi.mock('@/store/agent', () => ({ useAgentStore: { getState: () => agentStore } }));+vi.mock('@/store/home', () => ({+ useHomeStore: (selector: (state: object) => unknown) =>+ selector({ useFetchAgentList: () => undefined }),+}));+vi.mock('@/store/home/selectors', () => ({+ homeAgentListSelectors: { allAgents: () => agents },+}));+vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: object) => unknown) => selector({}),+}));+vi.mock('@/store/user/selectors', () => ({+ authSelectors: { isLogin: () => true },+ userProfileSelectors: { userId: () => 'user_1' },+}));++const ids = (list: { agent?: { id: string }; id?: string }[]) =>+ list.map((item) => item.agent?.id ?? item.id);++beforeEach(() => {+ service.getPluginAgentModes.mockReset();+ service.setPluginMode.mockReset();+ agentStore.agentMap = {};+ agentStore.internal_dispatchAgentMap.mockReset();+ toastError.mockReset();+});++describe('useSkillAgents', () => {+ it('splits my assistants by the modes the server reports, in one query', async () => {+ service.getPluginAgentModes.mockResolvedValue([+ { agentId: 'agt_a', mode: 'pinned' },+ { agentId: 'agt_b', mode: 'disabled' },+ ]);++ const { result } = renderHook(() => useSkillAgents('pptx', true));++ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(service.getPluginAgentModes).toHaveBeenCalledTimes(1);+ expect(service.getPluginAgentModes).toHaveBeenCalledWith('pptx');+ expect(result.current.added).toEqual([+ { agent: agents[0], enabled: true },+ { agent: agents[1], enabled: false },+ ]);+ expect(ids(result.current.available)).toEqual(['agt_c']);+ });++ it('does not query until the skill is installed', () => {+ renderHook(() => useSkillAgents('pptx', false));+ expect(service.getPluginAgentModes).not.toHaveBeenCalled();+ });++ it('toggles through one server write and patches a loaded config', async () => {+ service.getPluginAgentModes.mockResolvedValue([{ agentId: 'agt_a', mode: 'pinned' }]);+ agentStore.agentMap = { agt_a: {} };+ const plugins = ['web', { identifier: 'pptx', mode: 'disabled' }];+ service.setPluginMode.mockResolvedValue([{ id: 'agt_a', plugins }]);++ const { result } = renderHook(() => useSkillAgents('pptx', true));+ await waitFor(() => expect(result.current.added).toHaveLength(1));++ await act(() => result.current.toggle('agt_a', false));++ expect(service.setPluginMode).toHaveBeenCalledWith({+ agentIds: ['agt_a'],+ identifier: 'pptx',+ mode: 'disabled',+ });+ expect(result.current.added).toEqual([{ agent: agents[0], enabled: false }]);+ expect(agentStore.internal_dispatchAgentMap).toHaveBeenCalledWith('agt_a', { plugins });+ expect(result.current.pendingIds).toEqual([]);+ });++ it('removes from all assistants in a single atomic write', async () => {+ service.getPluginAgentModes.mockResolvedValue([+ { agentId: 'agt_a', mode: 'pinned' },+ { agentId: 'agt_b', mode: 'disabled' },+ ]);+ service.setPluginMode.mockResolvedValue([+ { id: 'agt_a', plugins: [] },+ { id: 'agt_b', plugins: ['web'] },+ ]);++ const { result } = renderHook(() => useSkillAgents('pptx', true));+ await waitFor(() => expect(result.current.added).toHaveLength(2));++ await act(() => result.current.removeAll());++ expect(service.setPluginMode).toHaveBeenCalledTimes(1);+ expect(service.setPluginMode).toHaveBeenCalledWith({+ agentIds: undefined,+ identifier: 'pptx',+ mode: 'auto',+ });+ expect(result.current.added).toEqual([]);+ expect(ids(result.current.available)).toEqual(['agt_a', 'agt_b', 'agt_c']);+ });++ it('reads the server state back and tells the user when a write fails', async () => {+ service.getPluginAgentModes.mockResolvedValue([]);+ service.setPluginMode.mockRejectedValue(new Error('boom'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ const { result } = renderHook(() => useSkillAgents('pptx', true));+ await waitFor(() => expect(result.current.loading).toBe(false));++ await act(() => result.current.add('agt_c'));++ expect(toastError).toHaveBeenCalledWith('market.skills.agents.failed');+ await waitFor(() => expect(service.getPluginAgentModes).toHaveBeenCalledTimes(2));+ expect(result.current.added).toEqual([]);+ });+});diff --git a/src/features/Marketplace/Skills/useSkillAgents.ts b/src/features/Marketplace/Skills/useSkillAgents.tsnew file mode 100644index 00000000000..b1f7c5efe9f--- /dev/null+++ b/src/features/Marketplace/Skills/useSkillAgents.ts@@ -0,0 +1,246 @@+import {+ type AgentPluginEntry,+ type AgentPluginMode,+ getPluginMode,+ type SidebarAgentItem,+} from '@lobechat/types';+import { toast } from '@lobehub/ui';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useShallow } from 'zustand/react/shallow';++import { agentService } from '@/services/agent';+import { useAgentStore } from '@/store/agent';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';+import { useUserStore } from '@/store/user';+import { authSelectors, userProfileSelectors } from '@/store/user/selectors';++export interface SkillAgent {+ agent: SidebarAgentItem;+ /** On (`pinned`) or switched off (`disabled`); an assistant without the skill is not listed. */+ enabled: boolean;+}++type ExplicitMode = Exclude<AgentPluginMode, 'auto'>;++const isAbort = (error: unknown) =>+ error instanceof Error && (error.name === 'AbortError' || error.message.includes('aborted'));++/** Applies a mode to a local agentId → mode map; `auto` drops the entry. */+const withMode = (+ modes: Record<string, ExplicitMode>,+ agentIds: string[],+ mode: AgentPluginMode,+): Record<string, ExplicitMode> => {+ const next = { ...modes };+ for (const id of agentIds) {+ if (mode === 'auto') delete next[id];+ else next[id] = mode;+ }+ return next;+};++/**+ * Last answer per skill (agentId → mode), shared by the skill page and the list+ * rows, so coming back to either paints at once while it refreshes.+ */+const modesCache = new Map<string, Record<string, ExplicitMode>>();++const toModes = (rows: { agentId: string; mode: ExplicitMode }[]) =>+ Object.fromEntries(rows.map(({ agentId, mode }) => [agentId, mode]));++/** My own LobeHub assistants; external runtimes and other people's agents are left out. */+export const useMyAgentCandidates = (enabled: boolean) => {+ const isLogin = useUserStore(authSelectors.isLogin);+ const userId = useUserStore(userProfileSelectors.userId);+ const useFetchAgentList = useHomeStore((s) => s.useFetchAgentList);+ useFetchAgentList(enabled && isLogin);++ return useHomeStore(+ useShallow((s) =>+ homeAgentListSelectors+ .allAgents(s)+ .filter(+ (item) =>+ item.type === 'agent' &&+ !item.heterogeneousType &&+ (!item.userId || item.userId === userId),+ ),+ ),+ );+};++/**+ * The assistants an installed skill was added to, for its row in the list:+ * the cached answer first, refreshed once on mount. `null` until there is one.+ */+export const useSkillAgentStatus = (identifier: string, enabled: boolean) => {+ const isLogin = useUserStore(authSelectors.isLogin);+ const candidates = useMyAgentCandidates(enabled);+ const [modes, setModes] = useState(() => modesCache.get(identifier));++ useEffect(() => {+ if (!enabled || !isLogin) return;+ let cancelled = false;+ agentService+ .getPluginAgentModes(identifier)+ .then((rows) => {+ const next = toModes(rows);+ modesCache.set(identifier, next);+ if (!cancelled) setModes(next);+ })+ .catch((error) => {+ if (!isAbort(error)) console.warn("[Market] Failed to load a skill's assistants", error);+ });+ return () => {+ cancelled = true;+ };+ }, [enabled, identifier, isLogin]);++ return useMemo<SkillAgent[] | null>(+ () =>+ modes+ ? candidates+ .filter((agent) => modes[agent.id])+ .map((agent) => ({ agent, enabled: modes[agent.id] === 'pinned' }))+ : null,+ [candidates, modes],+ );+};++/**+ * My assistants and a market skill: which of them carry it (on or switched off),+ * which could take it, and the writes that add, switch and remove it.+ *+ * A skill sits in an agent's `plugins` list: `pinned` is on, `disabled` is+ * off, and removing it drops the entry. The server answers which agents carry+ * it in one query and applies every write atomically on its side, so no agent's+ * full config is loaded here. Only my own LobeHub assistants count; external+ * runtimes (Claude Code, Codex, …) do not run market skills.+ */+export const useSkillAgents = (identifier: string, enabled: boolean) => {+ const { t } = useTranslation('setting');+ const isLogin = useUserStore(authSelectors.isLogin);+ const candidates = useMyAgentCandidates(enabled);++ const [modes, setModes] = useState<Record<string, ExplicitMode>>(+ () => modesCache.get(identifier) ?? {},+ );+ const [loading, setLoading] = useState(false);+ const [pendingIds, setPendingIds] = useState<string[]>([]);+ // A reply for an earlier skill or sign-in is dropped.+ const generation = useRef(0);++ const load = useCallback(async () => {+ const current = ++generation.current;+ setLoading(true);+ try {+ const rows = await agentService.getPluginAgentModes(identifier);+ if (current !== generation.current) return;+ answered.current = true;+ setModes(toModes(rows));+ } catch (error) {+ if (current === generation.current && !isAbort(error))+ console.warn('[Market] Failed to load the assistants carrying a skill', error);+ } finally {+ if (current === generation.current) setLoading(false);+ }+ }, [identifier]);++ // Writes reach the shared cache too, so the list rows show them.+ // Set by the effect below once the cache or the server has answered for this skill.+ const answered = useRef(false);+ useEffect(() => {+ if (answered.current) modesCache.set(identifier, modes);+ }, [identifier, modes]);++ useEffect(() => {+ answered.current = modesCache.has(identifier);+ setModes(modesCache.get(identifier) ?? {});+ if (!enabled || !isLogin) {+ generation.current++;+ setLoading(false);+ return;+ }+ void load();+ }, [enabled, isLogin, load]);++ const { added, available } = useMemo(() => {+ const added: SkillAgent[] = [];+ const available: SidebarAgentItem[] = [];+ for (const agent of candidates) {+ const mode = modes[agent.id];+ if (mode) added.push({ agent, enabled: mode === 'pinned' });+ else available.push(agent);+ }+ return { added, available };+ }, [candidates, modes]);++ /**+ * Writes a mode on the server, then settles the list and any loaded agent+ * config from the `plugins` it returns. Without `agentIds`, `auto` removes the+ * skill from every agent carrying it; `pendingIds` names who is shown busy.+ */+ const setMode = useCallback(+ async (mode: AgentPluginMode, agentIds: string[] | undefined, busyIds: string[]) => {+ setPendingIds((ids) => [...ids, ...busyIds]);+ // Optimistic, so the switch and the list answer at once.+ setModes((current) => withMode(current, agentIds ?? busyIds, mode));+ try {+ const rows = await agentService.setPluginMode({ agentIds, identifier, mode });+ const { agentMap, internal_dispatchAgentMap } = useAgentStore.getState();+ setModes((current) => {+ const next = { ...current };+ for (const { id, plugins } of rows) {+ const written = getPluginMode(plugins as AgentPluginEntry[], identifier);+ if (written === 'auto') delete next[id];+ else next[id] = written;+ // Chat input and settings read `plugins` from the loaded config.+ if (agentMap[id]) internal_dispatchAgentMap(id, { plugins: plugins as string[] });+ }+ return next;+ });+ return true;+ } catch (error) {+ // Nothing was written: read back what the server holds.+ void load();+ if (!isAbort(error)) {+ console.error('[Market] Failed to update the skill on assistants', error);+ toast.error(t('market.skills.agents.failed'));+ }+ return false;+ } finally {+ setPendingIds((ids) => ids.filter((id) => !busyIds.includes(id)));+ }+ },+ [identifier, load, t],+ );++ const add = useCallback((agentId: string) => setMode('pinned', [agentId], [agentId]), [setMode]);+ const toggle = useCallback(+ (agentId: string, on: boolean) => setMode(on ? 'pinned' : 'disabled', [agentId], [agentId]),+ [setMode],+ );+ const remove = useCallback((agentId: string) => setMode('auto', [agentId], [agentId]), [setMode]);+ const removeAll = useCallback(+ () =>+ setMode(+ 'auto',+ undefined,+ added.map(({ agent }) => agent.id),+ ),+ [added, setMode],+ );++ return {+ add,+ added,+ available,+ loading,+ pendingIds,+ remove,+ removeAll,+ toggle,+ };+};diff --git a/src/features/Marketplace/Skills/useSkillsNav.ts b/src/features/Marketplace/Skills/useSkillsNav.tsnew file mode 100644index 00000000000..94c3b1aae83--- /dev/null+++ b/src/features/Marketplace/Skills/useSkillsNav.ts@@ -0,0 +1,41 @@+import { useCallback } from 'react';+import { useSearchParams } from 'react-router';+import urlJoin from 'url-join';++import { useCatalogDetailNavigate } from '../Catalog/useCatalogDetailNavigate';+import { MARKETPLACE_SKILL_PATH } from '../paths';++/** A group's "all" page: `installed` or a market category. */+const GROUP_PARAM = 'group';+/** The GitHub import page; an empty value opens it with an empty address. */+const GITHUB_PARAM = 'github';++/**+ * Where the Skills pages are, kept in the URL so Back, reload and shared links+ * work: `?group=<category|installed>` is a group's page, `?github=<address>` the+ * GitHub import page, and `/marketplace/skill/<identifier>` a skill's page.+ */+export const useSkillsNav = () => {+ const [params, setParams] = useSearchParams();+ const openDetail = useCatalogDetailNavigate();++ const setParam = useCallback(+ (key: string, value: string | null) =>+ setParams((prev) => {+ const next = new URLSearchParams(prev);+ if (value === null) next.delete(key);+ else next.set(key, value);+ return next;+ }),+ [setParams],+ );++ return {+ githubUrl: params.get(GITHUB_PARAM),+ group: params.get(GROUP_PARAM),+ openSkill: (identifier: string) =>+ openDetail(urlJoin(MARKETPLACE_SKILL_PATH, encodeURIComponent(identifier))),+ setGithubUrl: (url: string | null) => setParam(GITHUB_PARAM, url),+ setGroup: (group: string | null) => setParam(GROUP_PARAM, group),+ };+};diff --git a/src/features/Settings/creds/features/CreateCredModal/Content.tsx b/src/features/Settings/creds/features/CreateCredModal/Content.tsxindex a86d2ad295e..8c3926d373c 100644--- a/src/features/Settings/creds/features/CreateCredModal/Content.tsx+++ b/src/features/Settings/creds/features/CreateCredModal/Content.tsx@@ -6,17 +6,24 @@ import { type FC } from 'react';import { type CredsApi } from '../useCredsApi';import FileCredForm from './FileCredForm';-import KVCredForm from './KVCredForm';+import KVCredForm, { type KVCredPreset } from './KVCredForm';import OAuthCredForm from './OAuthCredForm';export interface CreateCredModalContentProps {credsApi: CredsApi;+ /** Fields of the key-value form filled in ahead; only used with a `kv-*` type. */+ kvPreset?: KVCredPreset;onSuccess?: () => void;/** Picked from the "New credential" menu before the modal opens. */type: CredType;}-const CreateCredModalContent: FC<CreateCredModalContentProps> = ({ credsApi, onSuccess, type }) => {+const CreateCredModalContent: FC<CreateCredModalContentProps> = ({+ credsApi,+ kvPreset,+ onSuccess,+ type,+}) => {const { close } = useModalContext();const handleSuccess = () => {@@ -28,7 +35,13 @@ const CreateCredModalContent: FC<CreateCredModalContentProps> = ({ credsApi, onScase 'kv-env':case 'kv-header': {return (- <KVCredForm credsApi={credsApi} type={type} onCancel={close} onSuccess={handleSuccess} />+ <KVCredForm+ credsApi={credsApi}+ preset={kvPreset}+ type={type}+ onCancel={close}+ onSuccess={handleSuccess}+ />);}case 'oauth': {diff --git a/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsxindex 3c81edb44c1..7016b420d0e 100644--- a/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx+++ b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx@@ -11,11 +11,21 @@ import CredFormFooter from '../CredFormFooter';import KVPairsField from '../KVPairsField';import { createExtras, type CredsApi } from '../useCredsApi';+/** Fields a caller can fill in ahead, e.g. a GitHub token's key and variable name. */+export interface KVCredPreset {+ description?: string;+ key: string;+ /** Variable names; their values stay for the person to paste. */+ keys: string[];+ name: string;+}+interface KVCredFormProps {credsApi: CredsApi;disabled?: boolean;onCancel: () => void;onSuccess: () => void;+ preset?: KVCredPreset;type: 'kv-env' | 'kv-header';}@@ -26,10 +36,24 @@ interface FormValues {name: string;}-const KVCredForm: FC<KVCredFormProps> = ({ credsApi, type, disabled, onCancel, onSuccess }) => {+const KVCredForm: FC<KVCredFormProps> = ({+ credsApi,+ type,+ disabled,+ onCancel,+ onSuccess,+ preset,+}) => {const { t } = useTranslation('setting');const form = useForm<FormValues>({- initialValues: { kvPairs: [{ key: '', value: '' }] } as FormValues,+ initialValues: (preset+ ? {+ description: preset.description,+ key: preset.key,+ kvPairs: preset.keys.map((key) => ({ key, value: '' })),+ name: preset.name,+ }+ : { kvPairs: [{ key: '', value: '' }] }) as FormValues,onSubmit: (values) => handleSubmit(values),});diff --git a/src/routes/(main)/community/(detail)/skill/index.tsx b/src/routes/(main)/community/(detail)/skill/index.tsxindex bf15f967a98..11a257b791a 100644--- a/src/routes/(main)/community/(detail)/skill/index.tsx+++ b/src/routes/(main)/community/(detail)/skill/index.tsx@@ -7,6 +7,7 @@ import { useLocation, useParams, useSearchParams } from 'react-router';import AsyncError from '@/components/AsyncError';import { RouteLoading } from '@/components/Skeleton/RouteSegment';import { SkillDetailView, SkillNavKey } from '@/features/CommunitySkillDetail';+import MarketplaceSkillDetail from '@/features/Marketplace/Skills/SkillDetail';import { useQuery } from '@/hooks/useQuery';import { useDiscoverStore } from '@/store/discover';import { skillSelectors } from '@/store/discover/selectors';@@ -76,4 +77,20 @@ export const MobileSkillPage = (_props: { mobile?: boolean }) => {return <SkillDetailPage mobile={true} />;};-export default SkillDetailPage;+/**+ * Desktop: the skill's page from the Marketplace's Skills design — install,+ * ratings, the mock chat, which of my assistants have it on, and SKILL.md.+ */+const DesktopSkillPage = memo(() => {+ const { slug = '' } = useParams<{ slug: string }>();+ // The detail layout's header already carries the back arrow.+ return (+ <Flexbox data-testid="skill-detail-content" gap={16}>+ <MarketplaceSkillDetail identifier={slug} key={slug} />+ </Flexbox>+ );+});++DesktopSkillPage.displayName = 'DesktopSkillPage';++export default DesktopSkillPage;diff --git a/src/routes/(main)/community/(list)/skill/index.tsx b/src/routes/(main)/community/(list)/skill/index.tsxindex 94f867a5e0c..971a3dcef42 100644--- a/src/routes/(main)/community/(list)/skill/index.tsx+++ b/src/routes/(main)/community/(list)/skill/index.tsx@@ -1 +1 @@-export { default } from '@/features/Marketplace/Catalog/SkillCatalog';+export { default } from '@/features/Marketplace/Skills/SkillsPage';diff --git a/src/services/agent.ts b/src/services/agent.tsindex 21e28bef34e..1d8017f5851 100644--- a/src/services/agent.ts+++ b/src/services/agent.ts@@ -1,6 +1,8 @@import {type AgentDeleteImpact,type AgentItem,+ type AgentPluginEntry,+ type AgentPluginMode,type AgentRankItem,type LobeAgentConfig,} from '@lobechat/types';@@ -8,6 +10,12 @@ import { type PartialDeep } from 'type-fest';import { lambdaClient } from '@/libs/trpc/client';+/** One of my agents that carries a plugin or skill explicitly, and how. */+export interface PluginAgentMode {+ agentId: string;+ mode: Exclude<AgentPluginMode, 'auto'>;+}+export const AVAILABLE_AGENTS_CONTEXT_LIMIT = 10;export const AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT = AVAILABLE_AGENTS_CONTEXT_LIMIT + 2;@@ -257,6 +265,26 @@ class AgentService {/*** Update agent config and return the updated agent data*/+ /** Which of my own agents carry a plugin or skill, in one query over their `plugins`. */+ getPluginAgentModes = async (identifier: string): Promise<PluginAgentMode[]> => {+ return lambdaClient.agent.getPluginAgentModes.query({ identifier });+ };++ /**+ * Sets a plugin or skill's mode on my own agents in one atomic server write.+ * `auto` removes it; `auto` without `agentIds` removes it from every agent+ * carrying it. Returns each written agent's new `plugins`.+ */+ setPluginMode = async (params: {+ agentIds?: string[];+ identifier: string;+ mode: AgentPluginMode;+ }): Promise<{ id: string; plugins: AgentPluginEntry[] }[]> => {+ return lambdaClient.agent.setPluginMode.mutate(params, {+ context: { showNotification: false },+ });+ };+updateAgentConfig = async (agentId: string,config: PartialDeep<LobeAgentConfig>,diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsxindex 1b868fc8a75..0bfff83abb5 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -178,7 +178,8 @@ export const sharedMainAreaChildren: RouteObject[] = [...marketplaceAppAndMcpRoutes,{element: dynamicElement(- () => import('@/routes/(main)/community/(list)/skill'),+ // Mobile keeps the one-column catalog; the desktop route has the two-column Skills page.+ () => import('@/features/Marketplace/Catalog/SkillCatalog'),'Mobile > Discover > List > Skill',),handle: {