🤯 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
✨ feat(skill): add market comments & rating distribution APIs, enrich skill detail (#17258)
AmAzing-0f41398369b0
diff --git a/apps/server/src/routers/lambda/market/skill.test.ts b/apps/server/src/routers/lambda/market/skill.test.tsnew file mode 100644index 00000000000..47259aeb4ac--- /dev/null+++ b/apps/server/src/routers/lambda/market/skill.test.ts@@ -0,0 +1,179 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++const {+ mockGetSkillComments,+ mockGetSkillDetail,+ mockGetSkillDownloadUrl,+ mockGetSkillRatingDistribution,+ mockSearchSkill,+} = vi.hoisted(() => ({+ mockGetSkillComments: vi.fn(),+ mockGetSkillDetail: vi.fn(),+ mockGetSkillDownloadUrl: vi.fn(),+ mockGetSkillRatingDistribution: vi.fn(),+ mockSearchSkill: vi.fn(),+}));++vi.mock('@/libs/trpc/lambda/middleware', () => ({+ marketUserInfo: vi.fn((opts: any) =>+ opts.next({+ ctx: {+ ...opts.ctx,+ marketUserInfo: { email: '[email protected]', name: 'Actor', userId: 'user-1' },+ },+ }),+ ),+ serverDatabase: vi.fn((opts: any) => opts.next(opts)),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn(() => ({+ getSkillComments: mockGetSkillComments,+ getSkillDetail: mockGetSkillDetail,+ getSkillDownloadUrl: mockGetSkillDownloadUrl,+ getSkillRatingDistribution: mockGetSkillRatingDistribution,+ searchSkill: mockSearchSkill,+ })),+}));++const createCaller = async () => {+ const { skillRouter } = await import('./skill');+ return skillRouter.createCaller({ userId: 'user-1' } as any);+};++const rawDetail = {+ category: 'productivity-tasks',+ content: '# SKILL.md',+ identifier: 'github.acme.skill-a',+ name: 'Skill A',+};++describe('skillRouter.getSkillDetail', () => {+ beforeEach(() => {+ vi.clearAllMocks();++ mockGetSkillDetail.mockResolvedValue(rawDetail);+ mockGetSkillDownloadUrl.mockReturnValue('https://market.example/skills/skill-a/download');+ });++ it('enriches the raw detail with downloadUrl', async () => {+ const caller = await createCaller();++ const result = await caller.getSkillDetail({+ identifier: 'github.acme.skill-a',+ locale: 'en-US',+ });++ expect(mockGetSkillDetail).toHaveBeenCalledWith('github.acme.skill-a', {+ locale: 'en-US',+ version: undefined,+ });+ expect(result.downloadUrl).toBe('https://market.example/skills/skill-a/download');+ expect(result.name).toBe('Skill A');+ });++ it('stays a single upstream request — never fans out to the skill list', async () => {+ // The detail query also backs per-skill icon/metadata lookups (one per+ // installed skill in the chat tools panel). Related skills must be+ // composed client-side from getSkillList, not aggregated here.+ const caller = await createCaller();++ await caller.getSkillDetail({ identifier: 'github.acme.skill-a' });++ expect(mockGetSkillDetail).toHaveBeenCalledTimes(1);+ expect(mockSearchSkill).not.toHaveBeenCalled();+ });++ it('passes the requested version through to detail and download URL', async () => {+ const caller = await createCaller();++ await caller.getSkillDetail({ identifier: 'github.acme.skill-a', version: '1.2.0' });++ expect(mockGetSkillDetail).toHaveBeenCalledWith('github.acme.skill-a', {+ locale: undefined,+ version: '1.2.0',+ });+ expect(mockGetSkillDownloadUrl).toHaveBeenCalledWith('github.acme.skill-a', '1.2.0');+ });++ it('wraps detail failures into an internal server error', async () => {+ mockGetSkillDetail.mockRejectedValue(new Error('boom'));+ const caller = await createCaller();++ await expect(caller.getSkillDetail({ identifier: 'github.acme.skill-a' })).rejects.toThrow(+ 'Failed to fetch skill detail',+ );+ });+});++describe('skillRouter.getSkillComments', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('forwards pagination params and returns the comment page', async () => {+ const response = {+ currentPage: 2,+ items: [{ content: 'Great skill', id: 1 }],+ pageSize: 10,+ totalCount: 11,+ totalPages: 2,+ };+ mockGetSkillComments.mockResolvedValue(response);+ const caller = await createCaller();++ const result = await caller.getSkillComments({+ identifier: 'github.acme.skill-a',+ order: 'desc',+ page: 2,+ pageSize: 10,+ sort: 'createdAt',+ });++ expect(mockGetSkillComments).toHaveBeenCalledWith('github.acme.skill-a', {+ order: 'desc',+ page: 2,+ pageSize: 10,+ sort: 'createdAt',+ });+ expect(result).toEqual(response);+ });++ it('wraps comment failures into an internal server error', async () => {+ mockGetSkillComments.mockRejectedValue(new Error('boom'));+ const caller = await createCaller();++ await expect(caller.getSkillComments({ identifier: 'github.acme.skill-a' })).rejects.toThrow(+ 'Failed to fetch skill comments',+ );+ });+});++describe('skillRouter.getSkillRatingDistribution', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('returns the rating distribution for a skill', async () => {+ const distribution = { 1: 0, 2: 1, 3: 2, 4: 10, 5: 30, totalCount: 43 };+ mockGetSkillRatingDistribution.mockResolvedValue(distribution);+ const caller = await createCaller();++ const result = await caller.getSkillRatingDistribution({+ identifier: 'github.acme.skill-a',+ });++ expect(mockGetSkillRatingDistribution).toHaveBeenCalledWith('github.acme.skill-a');+ expect(result).toEqual(distribution);+ });++ it('wraps distribution failures into an internal server error', async () => {+ mockGetSkillRatingDistribution.mockRejectedValue(new Error('boom'));+ const caller = await createCaller();++ await expect(+ caller.getSkillRatingDistribution({ identifier: 'github.acme.skill-a' }),+ ).rejects.toThrow('Failed to fetch skill rating distribution');+ });+});diff --git a/apps/server/src/routers/lambda/market/skill.ts b/apps/server/src/routers/lambda/market/skill.tsindex 5f6bce80f1f..1925f7726a7 100644--- a/apps/server/src/routers/lambda/market/skill.ts+++ b/apps/server/src/routers/lambda/market/skill.ts@@ -48,6 +48,31 @@ export const skillRouter = router({}}),+ getSkillComments: marketProcedure+ .input(+ z.object({+ identifier: z.string(),+ order: z.enum(['asc', 'desc']).optional(),+ page: z.number().optional(),+ pageSize: z.number().optional(),+ sort: z.enum(['createdAt', 'upvotes']).optional(),+ }),+ )+ .query(async ({ input, ctx }) => {+ log('getSkillComments input: %O', input);++ try {+ const { identifier, ...params } = input;+ return await ctx.marketService.getSkillComments(identifier, params);+ } catch (error) {+ log('Error fetching skill comments: %O', error);+ throw new TRPCError({+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to fetch skill comments',+ });+ }+ }),+getSkillDetail: marketProcedure.input(z.object({@@ -60,10 +85,19 @@ export const skillRouter = router({log('getSkillDetail input: %O', input);try {- return await ctx.marketService.getSkillDetail(input.identifier, {+ // Keep this path lean: it also backs per-skill icon/metadata lookups+ // (e.g. the chat tools panel renders one detail query per installed+ // skill), so it must stay a single upstream request. Related skills+ // are composed client-side from getSkillList (useFetchRelatedSkills).+ const detail = await ctx.marketService.getSkillDetail(input.identifier, {locale: input.locale,version: input.version,});++ return {+ ...detail,+ downloadUrl: ctx.marketService.getSkillDownloadUrl(input.identifier, input.version),+ };} catch (error) {log('Error fetching skill detail: %O', error);throw new TRPCError({@@ -100,4 +134,20 @@ export const skillRouter = router({});}}),++ getSkillRatingDistribution: marketProcedure+ .input(z.object({ identifier: z.string() }))+ .query(async ({ input, ctx }) => {+ log('getSkillRatingDistribution input: %O', input);++ try {+ return await ctx.marketService.getSkillRatingDistribution(input.identifier);+ } catch (error) {+ log('Error fetching skill rating distribution: %O', error);+ throw new TRPCError({+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to fetch skill rating distribution',+ });+ }+ }),});diff --git a/apps/server/src/services/market/index.test.ts b/apps/server/src/services/market/index.test.tsindex 292cc657cb6..f11be8b3234 100644--- a/apps/server/src/services/market/index.test.ts+++ b/apps/server/src/services/market/index.test.ts@@ -35,7 +35,9 @@ vi.mock('@lobehub/market-sdk', () => {marketSkills: {downloadSkill: vi.fn(),getCategories: vi.fn(),+ getComments: vi.fn(),getDownloadUrl: vi.fn(),+ getRatingDistribution: vi.fn(),getSkillDetail: vi.fn(),getSkillList: vi.fn(),},@@ -671,6 +673,38 @@ describe('MarketService', () => {});});+ describe('skill comments & ratings', () => {+ it('getSkillComments delegates to marketSkills.getComments with params', async () => {+ const service = new MarketService();+ const response = { currentPage: 1, items: [], pageSize: 10, totalCount: 0, totalPages: 0 };+ (service.market.marketSkills.getComments as any).mockResolvedValue(response);++ const result = await service.getSkillComments('github.acme.skill-a', {+ page: 2,+ sort: 'upvotes',+ });++ expect(service.market.marketSkills.getComments).toHaveBeenCalledWith('github.acme.skill-a', {+ page: 2,+ sort: 'upvotes',+ });+ expect(result).toEqual(response);+ });++ it('getSkillRatingDistribution delegates to marketSkills.getRatingDistribution', async () => {+ const service = new MarketService();+ const distribution = { 1: 0, 2: 0, 3: 1, 4: 2, 5: 3, totalCount: 6 };+ (service.market.marketSkills.getRatingDistribution as any).mockResolvedValue(distribution);++ const result = await service.getSkillRatingDistribution('github.acme.skill-a');++ expect(service.market.marketSkills.getRatingDistribution).toHaveBeenCalledWith(+ 'github.acme.skill-a',+ );+ expect(result).toEqual(distribution);+ });+ });+describe('getSDK', () => {it('should return the underlying MarketSDK instance', () => {const service = new MarketService();diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.tsindex c20b67a7be3..87927bd280e 100644--- a/apps/server/src/services/market/index.ts+++ b/apps/server/src/services/market/index.ts@@ -433,6 +433,7 @@ export class MarketService {| 'forks'| 'installCount'| 'name'+ | 'recommended'| 'relevance'| 'stars'| 'updatedAt'@@ -460,6 +461,32 @@ export class MarketService {return result;}+ /**+ * Get skill comments from market+ */+ async getSkillComments(+ identifier: string,+ params?: {+ order?: 'asc' | 'desc';+ page?: number;+ pageSize?: number;+ sort?: 'createdAt' | 'upvotes';+ },+ ) {+ log('getSkillComments: %s, params: %O', identifier, params);++ return this.market.marketSkills.getComments(identifier, params);+ }++ /**+ * Get skill rating distribution from market+ */+ async getSkillRatingDistribution(identifier: string) {+ log('getSkillRatingDistribution: %s', identifier);++ return this.market.marketSkills.getRatingDistribution(identifier);+ }+/*** Get skill download URL from market*/diff --git a/packages/types/src/discover/skills.ts b/packages/types/src/discover/skills.tsindex 6ff5d4e33aa..054ca6165d4 100644--- a/packages/types/src/discover/skills.ts+++ b/packages/types/src/discover/skills.ts@@ -47,6 +47,7 @@ export enum SkillSorts {CreatedAt = 'createdAt',InstallCount = 'installCount',Name = 'name',+ Recommended = 'recommended',Relevance = 'relevance',Stars = 'stars',UpdatedAt = 'updatedAt',@@ -77,6 +78,14 @@ export interface SkillQueryParams {sort?: SkillSorts;}+export interface SkillCommentsQueryParams {+ identifier: string;+ order?: 'asc' | 'desc';+ page?: number;+ pageSize?: number;+ sort?: 'createdAt' | 'upvotes';+}+export interface SkillListResponse extends MarketSkillListResponse {categories?: SkillCategoryItem[];}@@ -94,3 +103,9 @@ export interface DiscoverSkillDetail extends MarketSkillDetail {}export type SkillCategoryItem = MarketSkillCategory;++export type {+ SkillCommentItem,+ SkillCommentListResponse,+ SkillRatingDistribution,+} from '@lobehub/market-sdk';diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 5cbe73659ff..008c5976d7e 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -406,6 +406,11 @@ export const discoverKeys = {locale,params,]),+ skillComments: def('discover:skillComments', (identifier: string, params: unknown) => [+ 'discover:skillComments',+ identifier,+ params,+ ]),skillDetail: def('discover:skillDetail',(locale: string, identifier: string, version?: string) => [@@ -420,6 +425,19 @@ export const discoverKeys = {locale,params,]),+ skillRatingDistribution: def('discover:skillRatingDistribution', (identifier: string) => [+ 'discover:skillRatingDistribution',+ identifier,+ ]),+ skillRelated: def(+ 'discover:skillRelated',+ (locale: string, category: string, identifier: string) => [+ 'discover:skillRelated',+ locale,+ category,+ identifier,+ ],+ ),userProfile: def('discover:userProfile', (locale: string, username: string) => ['discover:userProfile',locale,diff --git a/src/services/discover.ts b/src/services/discover.tsindex 2775ad7bd87..71a62813d49 100644--- a/src/services/discover.ts+++ b/src/services/discover.ts@@ -36,8 +36,11 @@ import {type ProviderListResponse,type ProviderQueryParams,type SkillCategoryItem,+ type SkillCommentListResponse,+ type SkillCommentsQueryParams,type SkillListResponse,type SkillQueryParams,+ type SkillRatingDistribution,} from '@/types/discover';import { type MCPPluginListParams } from '@/types/plugins';import { cleanObject } from '@/utils/object';@@ -542,6 +545,9 @@ class DiscoverService {});};+ getSkillComments = async (params: SkillCommentsQueryParams): Promise<SkillCommentListResponse> =>+ lambdaClient.market.skill.getSkillComments.query(params);+getSkillDetail = async (params: {identifier: string;locale?: string;@@ -564,6 +570,9 @@ class DiscoverService {});};+ getSkillRatingDistribution = async (identifier: string): Promise<SkillRatingDistribution> =>+ lambdaClient.market.skill.getSkillRatingDistribution.query({ identifier });+reportSkillEvent = async (eventData: { event: string; identifier: string; source?: string }) => {const allow = userGeneralSettingsSelectors.telemetry(useUserStore.getState());if (!allow) return;diff --git a/src/store/discover/slices/skill/action.test.ts b/src/store/discover/slices/skill/action.test.tsnew file mode 100644index 00000000000..f7e2d8b5a17--- /dev/null+++ b/src/store/discover/slices/skill/action.test.ts@@ -0,0 +1,89 @@+import { renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { discoverService } from '@/services/discover';+import { globalHelpers } from '@/store/global/helpers';+import { SkillSorts } from '@/types/discover';++import { useDiscoverStore as useStore } from '../../store';++vi.mock('zustand/traditional');++beforeEach(() => {+ vi.clearAllMocks();+});++const listItem = (identifier: string) => ({ identifier, name: identifier }) as any;++describe('SkillAction', () => {+ describe('useFetchRelatedSkills', () => {+ it('fetches same-category recommended skills, dropping the skill itself and capping at 6', async () => {+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');+ vi.spyOn(discoverService, 'getSkillList').mockResolvedValue({+ items: [+ listItem('github.acme.skill-a'),+ ...Array.from({ length: 6 }, (_, i) => listItem(`github.acme.other-${i}`)),+ ],+ } as any);++ const { result } = renderHook(() =>+ useStore.getState().useFetchRelatedSkills({+ category: 'productivity-tasks',+ identifier: 'github.acme.skill-a',+ }),+ );++ await waitFor(() => {+ expect(result.current.data).toHaveLength(6);+ });++ expect(discoverService.getSkillList).toHaveBeenCalledWith({+ category: 'productivity-tasks',+ page: 1,+ pageSize: 7,+ sort: SkillSorts.Recommended,+ });+ expect(result.current.data?.map((i) => i.identifier)).not.toContain('github.acme.skill-a');+ });++ it('caps at 6 even when the skill itself is not in the page', async () => {+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');+ vi.spyOn(discoverService, 'getSkillList').mockResolvedValue({+ items: Array.from({ length: 7 }, (_, i) => listItem(`github.acme.other-${i}`)),+ } as any);++ const { result } = renderHook(() =>+ useStore.getState().useFetchRelatedSkills({+ category: 'productivity-tasks',+ identifier: 'github.acme.skill-a',+ }),+ );++ await waitFor(() => {+ expect(result.current.data).toHaveLength(6);+ });+ });++ it('does not fetch without a category', async () => {+ const getSkillList = vi.spyOn(discoverService, 'getSkillList');++ renderHook(() =>+ useStore.getState().useFetchRelatedSkills({ identifier: 'github.acme.skill-a' }),+ );++ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(getSkillList).not.toHaveBeenCalled();+ });++ it('does not fetch without an identifier', async () => {+ const getSkillList = vi.spyOn(discoverService, 'getSkillList');++ renderHook(() =>+ useStore.getState().useFetchRelatedSkills({ category: 'productivity-tasks' }),+ );++ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(getSkillList).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/store/discover/slices/skill/action.ts b/src/store/discover/slices/skill/action.tsindex 056abec9ef4..04769c1d59c 100644--- a/src/store/discover/slices/skill/action.ts+++ b/src/store/discover/slices/skill/action.ts@@ -9,13 +9,21 @@ import { globalHelpers } from '@/store/global/helpers';import { type StoreSetter } from '@/store/types';import {type DiscoverSkillDetail,+ type DiscoverSkillItem,type SkillCategoryItem,+ type SkillCommentListResponse,+ type SkillCommentsQueryParams,type SkillListResponse,type SkillQueryParams,+ type SkillRatingDistribution,+ SkillSorts,} from '@/types/discover';type Setter = StoreSetter<DiscoverStore>;+/** How many related skills the detail view shows alongside the skill itself */+const RELATED_SKILLS_COUNT = 6;+export const createSkillSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>new SkillActionImpl(set, get, _api);@@ -48,6 +56,47 @@ export class SkillActionImpl {);};+ /**+ * Related skills for the detail view, composed client-side from the list+ * endpoint. Kept out of `getSkillDetail` on purpose: that query also backs+ * per-skill icon/metadata lookups (one per installed skill in the chat tools+ * panel), which must not pay for an extra upstream list request.+ */+ useFetchRelatedSkills = ({+ category,+ identifier,+ }: {+ category?: string;+ identifier?: string;+ }): SWRResponse<DiscoverSkillItem[]> => {+ const locale = globalHelpers.getCurrentLanguage();+ return useClientDataSWR(+ category && identifier ? discoverKeys.skillRelated(locale, category, identifier) : null,+ async (): Promise<DiscoverSkillItem[]> => {+ const list = await discoverService.getSkillList({+ category,+ page: 1,+ // Fetch one extra so the cap still holds after dropping the skill itself+ pageSize: RELATED_SKILLS_COUNT + 1,+ sort: SkillSorts.Recommended,+ });+ return list.items+ .filter((item) => item.identifier !== identifier)+ .slice(0, RELATED_SKILLS_COUNT);+ },+ );+ };++ useFetchSkillComments = ({+ identifier,+ ...params+ }: Partial<SkillCommentsQueryParams>): SWRResponse<SkillCommentListResponse> => {+ return useClientDataSWR(+ identifier ? discoverKeys.skillComments(identifier, params) : null,+ async () => discoverService.getSkillComments({ identifier: identifier!, ...params }),+ );+ };+useFetchSkillList = (params: SkillQueryParams): SWRResponse<SkillListResponse> => {const locale = globalHelpers.getCurrentLanguage();return useClientDataSWR(discoverKeys.skillList(locale, params), async () =>@@ -59,6 +108,13 @@ export class SkillActionImpl {);};+ useFetchSkillRatingDistribution = (identifier?: string): SWRResponse<SkillRatingDistribution> => {+ return useClientDataSWR(+ identifier ? discoverKeys.skillRatingDistribution(identifier) : null,+ async () => discoverService.getSkillRatingDistribution(identifier!),+ );+ };+useSkillCategories = (params: CategoryListQuery = {}): SWRResponse<SkillCategoryItem[]> => {const locale = globalHelpers.getCurrentLanguage();return useClientDataSWR(