🤯 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: add PostHog LobeHub skill integration (#16210)
AmAzing-dd37fe7c9987
diff --git a/apps/server/src/routers/tools/market.test.ts b/apps/server/src/routers/tools/market.test.tsnew file mode 100644index 00000000000..04967e7b2d4--- /dev/null+++ b/apps/server/src/routers/tools/market.test.ts@@ -0,0 +1,95 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { marketRouter } from './market';++const mockMarketSDK = vi.hoisted(() => ({+ skills: {+ callTool: vi.fn(),+ listLiveTools: vi.fn(),+ listTools: vi.fn(),+ },+}));++vi.mock('@/libs/trpc/lambda/middleware', () => ({+ marketUserInfo: vi.fn((opts: any) => opts.next({ ctx: opts.ctx })),+ serverDatabase: vi.fn((opts: any) => opts.next({ ctx: opts.ctx })),+ telemetry: vi.fn((opts: any) => opts.next({ ctx: opts.ctx })),+}));++vi.mock('@/libs/trpc/lambda/middleware/marketSDK', () => ({+ marketSDK: vi.fn((opts: any) =>+ opts.next({+ ctx: {+ ...opts.ctx,+ marketSDK: mockMarketSDK,+ },+ }),+ ),+ requireMarketAuth: vi.fn((opts: any) => opts.next({ ctx: opts.ctx })),+}));++vi.mock('debug', () => ({+ default: vi.fn(() => vi.fn()),+}));++describe('tools marketRouter', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should fall back to static tools when live discovery fails', async () => {+ const caller = marketRouter.createCaller({ userId: 'user-1' } as any);+ mockMarketSDK.skills.listLiveTools.mockRejectedValue(new Error('Live discovery failed'));+ mockMarketSDK.skills.listTools.mockResolvedValue({+ tools: [+ {+ description: 'Run a PostHog query',+ inputSchema: { properties: { query: { type: 'string' } }, type: 'object' },+ name: 'query',+ },+ ],+ });++ await expect(caller.connectListTools({ provider: 'posthog' })).resolves.toEqual({+ provider: 'posthog',+ tools: [+ {+ description: 'Run a PostHog query',+ inputSchema: { properties: { query: { type: 'string' } }, type: 'object' },+ name: 'query',+ },+ ],+ });++ expect(mockMarketSDK.skills.listLiveTools).toHaveBeenCalledWith('posthog');+ expect(mockMarketSDK.skills.listTools).toHaveBeenCalledWith('posthog');+ });++ it('should preserve failed tool call error payloads', async () => {+ const caller = marketRouter.createCaller({ userId: 'user-1' } as any);+ mockMarketSDK.skills.callTool.mockResolvedValue({+ data: null,+ error: { code: 'POSTHOG_QUERY_FAILED', message: 'Query failed' },+ success: false,+ });++ await expect(+ caller.connectCallTool({+ args: { query: 'select * from events' },+ provider: 'posthog',+ toolName: 'query',+ }),+ ).resolves.toEqual({+ data: null,+ error: { code: 'POSTHOG_QUERY_FAILED', message: 'Query failed' },+ success: false,+ });++ expect(mockMarketSDK.skills.callTool).toHaveBeenCalledWith('posthog', {+ args: { query: 'select * from events' },+ tool: 'query',+ topicId: undefined,+ });+ });+});diff --git a/apps/server/src/routers/tools/market.ts b/apps/server/src/routers/tools/market.tsindex 12fda36ed95..56bcac9d47c 100644--- a/apps/server/src/routers/tools/market.ts+++ b/apps/server/src/routers/tools/market.ts@@ -14,6 +14,7 @@ import { isTrustedClientEnabled } from '@/libs/trusted-client';import { DiscoverService } from '@/server/services/discover';import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';+import { listSkillToolsWithLiveFallback } from '@/server/services/market/listSkillToolsWithLiveFallback';import {contentBlocksToString,processContentBlocks,@@ -425,6 +426,7 @@ export const marketRouter = router({return {data: response.data,+ error: (response as any).error,success: response.success,};} catch (error) {@@ -594,7 +596,17 @@ export const marketRouter = router({log('connectListTools: provider=%s', input.provider);try {- const response = await ctx.marketSDK.skills.listTools(input.provider);+ const response = await listSkillToolsWithLiveFallback(+ ctx.marketSDK.skills,+ input.provider,+ (error) => {+ log(+ 'listSkillToolsWithLiveFallback: live discovery failed for %s, falling back to static tools: %O',+ input.provider,+ error,+ );+ },+ );return {provider: input.provider,tools: response.tools || [],diff --git a/apps/server/src/services/market/index.test.ts b/apps/server/src/services/market/index.test.tsindex ee92125803e..b7d999a13b3 100644--- a/apps/server/src/services/market/index.test.ts+++ b/apps/server/src/services/market/index.test.ts@@ -49,6 +49,7 @@ vi.mock('@lobehub/market-sdk', () => {},skills: {callTool: vi.fn(),+ listLiveTools: vi.fn(),listTools: vi.fn(),},user: {@@ -300,6 +301,149 @@ describe('MarketService', () => {success: false,});});++ it('should return error result when the skill call response is unsuccessful', async () => {+ const service = new MarketService();+ const mockCallTool = vi.fn().mockResolvedValue({+ data: null,+ error: { code: 'POSTHOG_QUERY_FAILED', message: 'Query failed' },+ success: false,+ });+ (service as any).market.skills.callTool = mockCallTool;++ const result = await service.executeLobehubSkill({+ args: { query: 'select * from events' },+ provider: 'posthog',+ toolName: 'query',+ });++ expect(result).toEqual({+ content: 'Query failed',+ error: { code: 'POSTHOG_QUERY_FAILED', message: 'Query failed' },+ success: false,+ });+ });++ it('should use response data as the failure message when no structured error is provided', async () => {+ const service = new MarketService();+ const mockCallTool = vi.fn().mockResolvedValue({+ data: 'PostHog query timed out',+ success: false,+ });+ (service as any).market.skills.callTool = mockCallTool;++ const result = await service.executeLobehubSkill({+ args: { query: 'select * from events' },+ provider: 'posthog',+ toolName: 'query',+ });++ expect(result).toEqual({+ content: 'PostHog query timed out',+ error: { code: 'LOBEHUB_SKILL_ERROR', message: 'PostHog query timed out' },+ success: false,+ });+ });++ it('should stringify response data objects as the failure message', async () => {+ const service = new MarketService();+ const mockCallTool = vi.fn().mockResolvedValue({+ data: { detail: 'PostHog query timed out', status: 504 },+ success: false,+ });+ (service as any).market.skills.callTool = mockCallTool;++ const result = await service.executeLobehubSkill({+ args: { query: 'select * from events' },+ provider: 'posthog',+ toolName: 'query',+ });++ const message = JSON.stringify({ detail: 'PostHog query timed out', status: 504 });+ expect(result).toEqual({+ content: message,+ error: { code: 'LOBEHUB_SKILL_ERROR', message },+ success: false,+ });+ });++ it('should use a generic failure message when an unsuccessful response has no detail', async () => {+ const service = new MarketService();+ const mockCallTool = vi.fn().mockResolvedValue({+ data: null,+ success: false,+ });+ (service as any).market.skills.callTool = mockCallTool;++ const result = await service.executeLobehubSkill({+ args: {},+ provider: 'posthog',+ toolName: 'query',+ });++ expect(result).toEqual({+ content: 'LobeHub Skill call failed',+ error: { code: 'LOBEHUB_SKILL_ERROR', message: 'LobeHub Skill call failed' },+ success: false,+ });+ });+ });++ describe('listSkillTools', () => {+ it('should use live tool discovery when available', async () => {+ const service = new MarketService();+ const liveResponse = {+ instruction: 'Use live PostHog tools.',+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ (service as any).market.skills.listLiveTools = vi.fn().mockResolvedValue(liveResponse);+ (service as any).market.skills.listTools = vi.fn().mockResolvedValue({ tools: [] });++ await expect(service.listSkillTools('posthog')).resolves.toBe(liveResponse);++ expect((service as any).market.skills.listLiveTools).toHaveBeenCalledWith('posthog');+ expect((service as any).market.skills.listTools).not.toHaveBeenCalled();+ });++ it('should fall back to static tools when live discovery throws', async () => {+ const service = new MarketService();+ const staticResponse = {+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ (service as any).market.skills.listLiveTools = vi.fn().mockRejectedValue(new Error('boom'));+ (service as any).market.skills.listTools = vi.fn().mockResolvedValue(staticResponse);++ await expect(service.listSkillTools('posthog')).resolves.toBe(staticResponse);++ expect((service as any).market.skills.listLiveTools).toHaveBeenCalledWith('posthog');+ expect((service as any).market.skills.listTools).toHaveBeenCalledWith('posthog');+ });++ it('should fall back to static tools when live discovery returns no tools', async () => {+ const service = new MarketService();+ const staticResponse = {+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ (service as any).market.skills.listLiveTools = vi.fn().mockResolvedValue({ tools: [] });+ (service as any).market.skills.listTools = vi.fn().mockResolvedValue(staticResponse);++ await expect(service.listSkillTools('posthog')).resolves.toBe(staticResponse);++ expect((service as any).market.skills.listTools).toHaveBeenCalledWith('posthog');+ });++ it('should fall back to static tools when live discovery returns no response', async () => {+ const service = new MarketService();+ const staticResponse = {+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ (service as any).market.skills.listLiveTools = vi.fn().mockResolvedValue(null);+ (service as any).market.skills.listTools = vi.fn().mockResolvedValue(staticResponse);++ await expect(service.listSkillTools('posthog')).resolves.toBe(staticResponse);++ expect((service as any).market.skills.listTools).toHaveBeenCalledWith('posthog');+ });});describe('getLobehubSkillManifests', () => {@@ -414,6 +558,45 @@ describe('MarketService', () => {});});+ it('should build PostHog manifests from live tool discovery', async () => {+ const service = new MarketService();+ (service as any).market.connect.listConnections = vi.fn().mockResolvedValue({+ connections: [{ icon: 'posthog-icon', providerId: 'posthog', providerName: 'Workspace' }],+ });+ (service as any).market.skills.listLiveTools = vi.fn().mockResolvedValue({+ instruction: 'Use PostHog analytics tools with the connected workspace.',+ tools: [+ {+ description: 'Run a PostHog query',+ inputSchema: { properties: { query: { type: 'string' } }, type: 'object' },+ name: 'query',+ },+ ],+ });+ (service as any).market.skills.listTools = vi.fn().mockResolvedValue({ tools: [] });++ const manifests = await service.getLobehubSkillManifests();++ expect((service as any).market.skills.listLiveTools).toHaveBeenCalledWith('posthog');+ expect((service as any).market.skills.listTools).not.toHaveBeenCalled();+ expect(manifests).toHaveLength(1);+ expect(manifests[0]).toMatchObject({+ identifier: 'posthog',+ meta: {+ avatar: 'posthog-icon',+ description: 'LobeHub Skill: PostHog',+ tags: ['lobehub-skill', 'posthog'],+ title: 'PostHog',+ },+ systemRole: 'Use PostHog analytics tools with the connected workspace.',+ });+ expect(manifests[0].api[0]).toEqual({+ description: 'Run a PostHog query',+ name: 'query',+ parameters: { properties: { query: { type: 'string' } }, type: 'object' },+ });+ });+it('should skip connections where listTools returns empty', async () => {const service = new MarketService();(service as any).market.connect.listConnections = vi.fn().mockResolvedValue({diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.tsindex 573c2d722af..150b177f250 100644--- a/apps/server/src/services/market/index.ts+++ b/apps/server/src/services/market/index.ts@@ -6,6 +6,8 @@ import { type NextRequest } from 'next/server';import { type TrustedClientUserInfo } from '@/libs/trusted-client';import { generateTrustedClientToken, getTrustedClientTokenForSession } from '@/libs/trusted-client';+import { listSkillToolsWithLiveFallback } from './listSkillToolsWithLiveFallback';+const log = debug('lobe-server:market-service');const MARKET_BASE_URL = process.env.MARKET_BASE_URL || 'https://market.lobehub.com';@@ -257,7 +259,20 @@ export class MarketService {* List available tools for a provider*/async listSkillTools(providerId: string) {- return this.market.skills.listTools(providerId);+ return listSkillToolsWithLiveFallback(+ this.market.skills as {+ listLiveTools?: (providerId: string) => Promise<any>;+ listTools: (providerId: string) => Promise<any>;+ },+ providerId,+ (error) => {+ log(+ 'listSkillToolsWithLiveFallback: live discovery failed for %s, falling back to static tools: %O',+ providerId,+ error,+ );+ },+ );}/**@@ -489,9 +504,31 @@ export class MarketService {log('executeLobehubSkill: response: %O', response);+ if (!response.success) {+ const responseError = (response as any).error;+ let dataMessage: string | undefined;++ if (typeof response.data === 'string') {+ dataMessage = response.data;+ } else if (response.data !== undefined && response.data !== null) {+ dataMessage = JSON.stringify(response.data);+ }++ const message = responseError?.message || dataMessage || 'LobeHub Skill call failed';++ return {+ content: message,+ error: {+ code: responseError?.code || 'LOBEHUB_SKILL_ERROR',+ message,+ },+ success: false,+ };+ }+return {content: typeof response.data === 'string' ? response.data : JSON.stringify(response.data),- success: response.success,+ success: true,};} catch (error) {const err = error as Error;@@ -555,12 +592,13 @@ export class MarketService {linear: 'Linear',microsoft: 'Outlook Calendar',notion: 'Notion',+ posthog: 'PostHog',twitter: 'X (Twitter)',vercel: 'Vercel',};const providerLabel = PROVIDER_LABELS[providerId] || providerId;- const { tools, instruction } = await this.market.skills.listTools(providerId);+ const { tools, instruction } = await this.listSkillTools(providerId);if (!tools || tools.length === 0) continue;const manifest: LobeToolManifest = {diff --git a/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.ts b/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.tsnew file mode 100644index 00000000000..a975319c513--- /dev/null+++ b/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.ts@@ -0,0 +1,82 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { listSkillToolsWithLiveFallback } from './listSkillToolsWithLiveFallback';++describe('listSkillToolsWithLiveFallback', () => {+ it('should return live tools when live discovery succeeds', async () => {+ const liveResponse = {+ instruction: 'Use live PostHog tools.',+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ const skills = {+ listLiveTools: vi.fn().mockResolvedValue(liveResponse),+ listTools: vi.fn().mockResolvedValue({ tools: [] }),+ };++ await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toBe(liveResponse);++ expect(skills.listLiveTools).toHaveBeenCalledWith('posthog');+ expect(skills.listTools).not.toHaveBeenCalled();+ });++ it('should fall back to static tools when live discovery throws', async () => {+ const error = new Error('Live discovery failed');+ const staticResponse = {+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ const onLiveDiscoveryError = vi.fn();+ const skills = {+ listLiveTools: vi.fn().mockRejectedValue(error),+ listTools: vi.fn().mockResolvedValue(staticResponse),+ };++ await expect(+ listSkillToolsWithLiveFallback(skills, 'posthog', onLiveDiscoveryError),+ ).resolves.toBe(staticResponse);++ expect(onLiveDiscoveryError).toHaveBeenCalledWith(error);+ expect(skills.listTools).toHaveBeenCalledWith('posthog');+ });++ it('should fall back to static tools when live discovery returns no response', async () => {+ const staticResponse = {+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ const skills = {+ listLiveTools: vi.fn().mockResolvedValue(undefined),+ listTools: vi.fn().mockResolvedValue(staticResponse),+ };++ await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toBe(staticResponse);++ expect(skills.listTools).toHaveBeenCalledWith('posthog');+ });++ it('should fall back to static tools when live discovery returns no tools', async () => {+ const staticResponse = {+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ const skills = {+ listLiveTools: vi.fn().mockResolvedValue({ instruction: 'No live tools yet.', tools: [] }),+ listTools: vi.fn().mockResolvedValue(staticResponse),+ };++ await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toBe(staticResponse);++ expect(skills.listTools).toHaveBeenCalledWith('posthog');+ });++ it('should use static tools when live discovery is unavailable', async () => {+ const staticResponse = {+ tools: [{ inputSchema: { type: 'object' }, name: 'query' }],+ };+ const skills = {+ listTools: vi.fn().mockResolvedValue(staticResponse),+ };++ await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toBe(staticResponse);++ expect(skills.listTools).toHaveBeenCalledWith('posthog');+ });+});diff --git a/apps/server/src/services/market/listSkillToolsWithLiveFallback.ts b/apps/server/src/services/market/listSkillToolsWithLiveFallback.tsnew file mode 100644index 00000000000..cc41073067b--- /dev/null+++ b/apps/server/src/services/market/listSkillToolsWithLiveFallback.ts@@ -0,0 +1,21 @@+export interface SkillToolsClient {+ listLiveTools?: (providerId: string) => Promise<any>;+ listTools: (providerId: string) => Promise<any>;+}++export const listSkillToolsWithLiveFallback = async (+ skills: SkillToolsClient,+ providerId: string,+ onLiveDiscoveryError?: (error: unknown) => void,+) => {+ if (typeof skills.listLiveTools === 'function') {+ try {+ const response = await skills.listLiveTools(providerId);+ if (Array.isArray(response?.tools) && response.tools.length > 0) return response;+ } catch (error) {+ onLiveDiscoveryError?.(error);+ }+ }++ return skills.listTools(providerId);+};diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 579dce83fb0..d141334bf88 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1215,6 +1215,8 @@"tools.lobehubSkill.providers.microsoft.readme": "Integrate with Outlook Calendar to view, create, and manage your events seamlessly. Schedule meetings, check availability, set reminders, and coordinate your time—all through natural language commands.","tools.lobehubSkill.providers.notion.description": "Notion is a collaborative productivity and note-taking application.","tools.lobehubSkill.providers.notion.readme": "Connect to Notion to access and manage your workspace. Create pages, search content, update databases, and organize your knowledge base—all through natural conversation with your AI assistant.",+ "tools.lobehubSkill.providers.posthog.description": "PostHog is an open-source product analytics platform for analyzing events, funnels, cohorts, feature flags, experiments, and user behavior.",+ "tools.lobehubSkill.providers.posthog.readme": "Connect to PostHog to query product analytics, inspect dashboards, review feature flags and experiments, and understand user behavior through natural conversation with your AI assistant.","tools.lobehubSkill.providers.twitter.description": "X (Twitter) is a social media platform for sharing real-time updates, news, and engaging with your audience through posts, replies, and direct messages.","tools.lobehubSkill.providers.twitter.readme": "Connect to X (Twitter) to post tweets, manage your timeline, and engage with your audience. Create content, schedule posts, monitor mentions, and build your social media presence through conversational AI.","tools.lobehubSkill.providers.vercel.description": "Vercel is a cloud platform for frontend developers, providing hosting and serverless functions to deploy web applications with ease.",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 18f3a9e4e99..a89e223dc2c 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1215,6 +1215,8 @@"tools.lobehubSkill.providers.microsoft.readme": "集成 Outlook 日历以无缝查看、创建和管理事件。安排会议、查看可用时间、设置提醒,并通过自然语言指令协调时间。","tools.lobehubSkill.providers.notion.description": "Notion 是一款协作型效率与笔记应用。","tools.lobehubSkill.providers.notion.readme": "连接 Notion 以访问和管理您的工作区。创建页面、搜索内容、更新数据库,并通过与 AI 助手的自然对话组织知识库。",+ "tools.lobehubSkill.providers.posthog.description": "PostHog 是一个开源产品分析平台,可用于分析事件、漏斗、用户群组、功能开关、实验和用户行为。",+ "tools.lobehubSkill.providers.posthog.readme": "连接 PostHog 以查询产品分析、查看仪表盘、审查功能开关和实验,并通过与 AI 助手的自然对话理解用户行为。","tools.lobehubSkill.providers.twitter.description": "X(原 Twitter)是一个社交媒体平台,用于分享实时动态、新闻,并通过推文、回复和私信与受众互动。","tools.lobehubSkill.providers.twitter.readme": "连接 X(原 Twitter)以发布推文、管理时间线并与受众互动。创建内容、安排发布、监控提及,并通过对话式 AI 构建社交媒体影响力。","tools.lobehubSkill.providers.vercel.description": "Vercel 是一个面向前端开发者的云平台,提供托管服务和无服务器函数,可轻松部署 Web 应用。",diff --git a/packages/const/src/lobehubSkill.ts b/packages/const/src/lobehubSkill.tsindex b0972506398..52f39ba6c2a 100644--- a/packages/const/src/lobehubSkill.ts+++ b/packages/const/src/lobehubSkill.ts@@ -1,5 +1,5 @@import type { IconType } from '@icons-pack/react-simple-icons';-import { SiGithub, SiLinear, SiVercel, SiX } from '@icons-pack/react-simple-icons';+import { SiGithub, SiLinear, SiPosthog, SiVercel, SiX } from '@icons-pack/react-simple-icons';export interface LobehubSkillProviderType {/**@@ -94,6 +94,18 @@ export const LOBEHUB_SKILL_PROVIDERS: LobehubSkillProviderType[] = ['Connect to Notion to access and manage your workspace. Create pages, search content, update databases, and organize your knowledge base—all through natural conversation with your AI assistant.',label: 'Notion',},+ {+ author: 'LobeHub',+ authorUrl: 'https://lobehub.com',+ defaultVisible: true,+ description:+ 'PostHog is an open-source product analytics platform for analyzing events, funnels, cohorts, feature flags, experiments, and user behavior.',+ icon: SiPosthog,+ id: 'posthog',+ label: 'PostHog',+ readme:+ 'Connect to PostHog to query product analytics, inspect dashboards, review feature flags and experiments, and understand user behavior through natural conversation with your AI assistant.',+ },{author: 'LobeHub',authorUrl: 'https://lobehub.com',diff --git a/packages/const/src/recommendedSkill.ts b/packages/const/src/recommendedSkill.tsindex c7d3eef2968..ddc4b88825f 100644--- a/packages/const/src/recommendedSkill.ts+++ b/packages/const/src/recommendedSkill.ts@@ -19,6 +19,7 @@ export const RECOMMENDED_SKILLS: RecommendedSkillItem[] = [{ id: 'lobe-message', type: RecommendedSkillType.Builtin },// LobeHub skills{ id: 'notion', type: RecommendedSkillType.Lobehub },+ { id: 'posthog', type: RecommendedSkillType.Lobehub },{ id: 'twitter', type: RecommendedSkillType.Lobehub },// Composio skills{ id: 'gmail', type: RecommendedSkillType.Composio },diff --git a/packages/const/src/taskTemplate.test.ts b/packages/const/src/taskTemplate.test.tsindex df8fffcebad..806e555cd9e 100644--- a/packages/const/src/taskTemplate.test.ts+++ b/packages/const/src/taskTemplate.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';+import { RECOMMENDED_SKILLS, RecommendedSkillType } from './recommendedSkill';import {TASK_TEMPLATE_ICONS,TASK_TEMPLATE_RECOMMEND_COUNT,@@ -18,4 +19,11 @@ describe('taskTemplate constants', () => {it('keeps icon identifiers stable for renderers', () => {expect(TASK_TEMPLATE_ICONS).toEqual(['github']);});++ it('keeps PostHog visible in recommended LobeHub skills', () => {+ expect(RECOMMENDED_SKILLS).toContainEqual({+ id: 'posthog',+ type: RecommendedSkillType.Lobehub,+ });+ });});diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 7785c0006de..f9d2c1cbe96 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -2481,6 +2481,10 @@ When I am ___, I need ___'Notion is a collaborative productivity and note-taking application.','tools.lobehubSkill.providers.notion.readme':'Connect to Notion to access and manage your workspace. Create pages, search content, update databases, and organize your knowledge base—all through natural conversation with your AI assistant.',+ 'tools.lobehubSkill.providers.posthog.description':+ 'PostHog is an open-source product analytics platform for analyzing events, funnels, cohorts, feature flags, experiments, and user behavior.',+ 'tools.lobehubSkill.providers.posthog.readme':+ 'Connect to PostHog to query product analytics, inspect dashboards, review feature flags and experiments, and understand user behavior through natural conversation with your AI assistant.','tools.lobehubSkill.providers.twitter.description':'X (Twitter) is a social media platform for sharing real-time updates, news, and engaging with your audience through posts, replies, and direct messages.','tools.lobehubSkill.providers.twitter.readme':diff --git a/src/features/RecommendTaskTemplates/providerMeta.test.ts b/src/features/RecommendTaskTemplates/providerMeta.test.tsindex c3850268a0a..d288c02df84 100644--- a/src/features/RecommendTaskTemplates/providerMeta.test.ts+++ b/src/features/RecommendTaskTemplates/providerMeta.test.ts@@ -16,6 +16,12 @@ describe('getProviderMeta', () => {expect(meta?.icon).toBeDefined();});+ it('resolves posthog as a lobehub source provider', () => {+ const meta = getProviderMeta({ identifier: 'posthog', source: 'lobehub' });+ expect(meta).toMatchObject({ identifier: 'posthog', label: 'PostHog', source: 'lobehub' });+ expect(meta?.icon).toBeDefined();+ });+it('resolves composio source via COMPOSIO_APP_TYPES', () => {const meta = getProviderMeta({ identifier: 'gmail', source: 'composio' });expect(meta).toMatchObject({ identifier: 'gmail', label: 'Gmail', source: 'composio' });diff --git a/src/store/tool/slices/lobehubSkillStore/action.test.ts b/src/store/tool/slices/lobehubSkillStore/action.test.tsindex 2af726232d4..bafa5a1d265 100644--- a/src/store/tool/slices/lobehubSkillStore/action.test.ts+++ b/src/store/tool/slices/lobehubSkillStore/action.test.ts@@ -1,5 +1,7 @@import type * as LobechatConstModule from '@lobechat/const';import { act, renderHook, waitFor } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { SWRConfig } from 'swr';import { beforeEach, describe, expect, it, vi } from 'vitest';import { toolsClient } from '@/libs/trpc/client';@@ -39,6 +41,14 @@ vi.mock('@/libs/trpc/client', () => ({},}));+const createSWRWrapper = () => {+ const value = { dedupingInterval: 0, provider: () => new Map() };++ return function SWRTestWrapper({ children }: { children: ReactNode }) {+ return createElement(SWRConfig, { value }, children);+ };+};+describe('lobehubSkillStore actions', () => {describe('callLobehubSkillTool', () => {it('should call tool successfully and return result', async () => {@@ -75,6 +85,141 @@ describe('lobehubSkillStore actions', () => {});});+ it('should return failure when the tool response is unsuccessful', async () => {+ const { result } = renderHook(() => useToolStore());++ act(() => {+ useToolStore.setState({+ lobehubSkillExecutingToolIds: new Set(),+ lobehubSkillLoadingIds: new Set(),+ lobehubSkillServers: [],+ });+ });++ vi.mocked(toolsClient.market.connectCallTool.mutate).mockResolvedValue({+ data: null,+ error: { code: 'POSTHOG_QUERY_FAILED', message: 'Query failed' },+ success: false,+ } as any);++ let callResult;+ await act(async () => {+ callResult = await result.current.callLobehubSkillTool({+ args: { query: 'select * from events' },+ provider: 'posthog',+ toolName: 'query',+ });+ });++ expect(callResult).toEqual({+ data: null,+ error: 'Query failed',+ errorCode: 'POSTHOG_QUERY_FAILED',+ success: false,+ });+ expect(result.current.lobehubSkillExecutingToolIds.has('posthog:query')).toBe(false);+ });++ it('should use string response data as the failure message when no structured error is provided', async () => {+ const { result } = renderHook(() => useToolStore());++ act(() => {+ useToolStore.setState({+ lobehubSkillExecutingToolIds: new Set(),+ lobehubSkillLoadingIds: new Set(),+ lobehubSkillServers: [],+ });+ });++ vi.mocked(toolsClient.market.connectCallTool.mutate).mockResolvedValue({+ data: 'PostHog query timed out',+ success: false,+ } as any);++ let callResult;+ await act(async () => {+ callResult = await result.current.callLobehubSkillTool({+ args: { query: 'select * from events' },+ provider: 'posthog',+ toolName: 'query',+ });+ });++ expect(callResult).toEqual({+ data: 'PostHog query timed out',+ error: 'PostHog query timed out',+ errorCode: undefined,+ success: false,+ });+ expect(result.current.lobehubSkillExecutingToolIds.has('posthog:query')).toBe(false);+ });++ it('should stringify response data objects as the failure message', async () => {+ const { result } = renderHook(() => useToolStore());++ act(() => {+ useToolStore.setState({+ lobehubSkillExecutingToolIds: new Set(),+ lobehubSkillLoadingIds: new Set(),+ lobehubSkillServers: [],+ });+ });++ vi.mocked(toolsClient.market.connectCallTool.mutate).mockResolvedValue({+ data: { detail: 'PostHog query timed out', status: 504 },+ success: false,+ } as any);++ let callResult;+ await act(async () => {+ callResult = await result.current.callLobehubSkillTool({+ args: { query: 'select * from events' },+ provider: 'posthog',+ toolName: 'query',+ });+ });++ expect(callResult).toEqual({+ data: { detail: 'PostHog query timed out', status: 504 },+ error: JSON.stringify({ detail: 'PostHog query timed out', status: 504 }),+ errorCode: undefined,+ success: false,+ });+ });++ it('should use a generic failure message when an unsuccessful response has no detail', async () => {+ const { result } = renderHook(() => useToolStore());++ act(() => {+ useToolStore.setState({+ lobehubSkillExecutingToolIds: new Set(),+ lobehubSkillLoadingIds: new Set(),+ lobehubSkillServers: [],+ });+ });++ vi.mocked(toolsClient.market.connectCallTool.mutate).mockResolvedValue({+ data: null,+ success: false,+ } as any);++ let callResult;+ await act(async () => {+ callResult = await result.current.callLobehubSkillTool({+ args: {},+ provider: 'posthog',+ toolName: 'query',+ });+ });++ expect(callResult).toEqual({+ data: null,+ error: 'LobeHub Skill call failed',+ errorCode: undefined,+ success: false,+ });+ });+it('should track executing state during tool call', async () => {const { result } = renderHook(() => useToolStore());@@ -834,6 +979,56 @@ describe('lobehubSkillStore actions', () => {});});+ describe('useFetchProviderTools', () => {+ it('should fetch and normalize provider tools', async () => {+ vi.mocked(toolsClient.market.connectListTools.query).mockResolvedValue({+ provider: 'posthog',+ tools: [+ {+ description: 'Run a PostHog query',+ inputSchema: { properties: { query: { type: 'string' } }, type: 'object' },+ name: 'query',+ },+ ],+ } as any);++ const { result } = renderHook(+ () => useToolStore.getState().useFetchProviderTools('posthog'),+ { wrapper: createSWRWrapper() },+ );++ await waitFor(() => {+ expect(toolsClient.market.connectListTools.query).toHaveBeenCalledWith({+ provider: 'posthog',+ });+ });++ const normalized = await result.current.mutate();++ expect(normalized).toEqual([+ {+ description: 'Run a PostHog query',+ inputSchema: { properties: { query: { type: 'string' } }, type: 'object' },+ name: 'query',+ },+ ]);+ });++ it('should not fetch tools when provider is undefined', () => {+ vi.mocked(toolsClient.market.connectListTools.query).mockClear();++ const { result } = renderHook(+ () => useToolStore.getState().useFetchProviderTools(undefined),+ {+ wrapper: createSWRWrapper(),+ },+ );++ expect(result.current.data).toEqual([]);+ expect(toolsClient.market.connectListTools.query).not.toHaveBeenCalled();+ });+ });+describe('server deduplication logic', () => {it('should deduplicate servers by identifier when adding new servers', () => {act(() => {diff --git a/src/store/tool/slices/lobehubSkillStore/action.ts b/src/store/tool/slices/lobehubSkillStore/action.tsindex 577d71c79a2..ee795d863f6 100644--- a/src/store/tool/slices/lobehubSkillStore/action.ts+++ b/src/store/tool/slices/lobehubSkillStore/action.ts@@ -68,6 +68,24 @@ export class LobehubSkillStoreActionImpl {n('callLobehubSkillTool/success'),);+ if (response.success === false) {+ const responseError = (response as any).error;+ let dataMessage: string | undefined;++ if (typeof response.data === 'string') {+ dataMessage = response.data;+ } else if (response.data !== undefined && response.data !== null) {+ dataMessage = JSON.stringify(response.data);+ }++ return {+ data: response.data,+ error: responseError?.message || dataMessage || 'LobeHub Skill call failed',+ errorCode: responseError?.code,+ success: false,+ };+ }+return { data: response.data, success: true };} catch (error) {console.error('[LobehubSkill] Failed to call tool:', error);