π€― 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
π fix(market): surface Market not-found / skill-connection errors and fix dead agent-group routes (#21037)
Mochaef06c9503515
diff --git a/apps/server/src/routers/lambda/market/agentGroup.test.ts b/apps/server/src/routers/lambda/market/agentGroup.test.tsindex 20bfa43bfbe..1216214adef 100644--- a/apps/server/src/routers/lambda/market/agentGroup.test.ts+++ b/apps/server/src/routers/lambda/market/agentGroup.test.ts@@ -1,4 +1,6 @@// @vitest-environment node+import { MarketAPIError } from '@lobehub/market-sdk';+import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';import { agentGroupRouter } from './agentGroup';@@ -6,6 +8,7 @@ import { agentGroupRouter } from './agentGroup';const { mockMarketSDK } = vi.hoisted(() => ({mockMarketSDK: {agentGroups: {+ deprecate: vi.fn(),getAgentGroupDetail: vi.fn(),},headers: {} as Record<string, string>,@@ -126,3 +129,29 @@ describe('agentGroupRouter.checkOwnership', () => {});});});++describe('agentGroupRouter.deprecateAgentGroup', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockMarketSDK.agentGroups.deprecate.mockResolvedValue({ success: true });+ });++ it('deprecates the requested group and returns the Market result', async () => {+ const caller = agentGroupRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);++ const result = await caller.deprecateAgentGroup({ identifier: 'group-1' });++ expect(mockMarketSDK.agentGroups.deprecate).toHaveBeenCalledWith('group-1');+ expect(result).toEqual({ success: true });+ });++ it('maps a Market 404 to NOT_FOUND', async () => {+ mockMarketSDK.agentGroups.deprecate.mockRejectedValue(new MarketAPIError(404, 'Not Found'));+ const caller = agentGroupRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);++ const error = await caller.deprecateAgentGroup({ identifier: 'missing' }).catch((e) => e);++ expect(error).toBeInstanceOf(TRPCError);+ expect(error.code).toBe('NOT_FOUND');+ });+});diff --git a/apps/server/src/routers/lambda/market/agentGroup.ts b/apps/server/src/routers/lambda/market/agentGroup.tsindex 52498d716f3..c9b46286d7d 100644--- a/apps/server/src/routers/lambda/market/agentGroup.ts+++ b/apps/server/src/routers/lambda/market/agentGroup.ts@@ -11,6 +11,8 @@ import { marketSDK, marketUserInfo, serverDatabase } from '@/libs/trpc/lambda/miimport { type TrustedClientUserInfo } from '@/libs/trusted-client';import { generateTrustedClientToken } from '@/libs/trusted-client';+import { mapMarketError } from './marketError';+const MARKET_BASE_URL = process.env.MARKET_BASE_URL || 'https://market.lobehub.com';interface MarketUserInfo {@@ -230,8 +232,8 @@ export const agentGroupRouter = router({}),/**- * Deprecate agent group- * POST /market/agent-group/:identifier/deprecate+ * Deprecate agent group (permanently hide, cannot be republished)+ * POST /api/v1/agent-groups/modify with { identifier, status: 'deprecated' }*/deprecateAgentGroup: agentGroupWriteProcedure.input(z.object({ identifier: z.string() }))@@ -239,51 +241,11 @@ export const agentGroupRouter = router({log('deprecateAgentGroup input: %O', input);try {- const deprecateUrl = `${MARKET_BASE_URL}/api/v1/agent-groups/${input.identifier}/deprecate`;-- const headers: Record<string, string> = {- 'Content-Type': 'application/json',- };-- const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;- const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;-- if (userInfo) {- const trustedClientToken = generateTrustedClientToken(userInfo);- if (trustedClientToken) {- headers['x-lobe-trust-token'] = trustedClientToken;- }- }-- if (!headers['x-lobe-trust-token'] && accessToken) {- headers['Authorization'] = `Bearer ${accessToken}`;- }-- const response = await fetch(deprecateUrl, {- headers,- method: 'POST',- });-- if (!response.ok) {- const errorText = await response.text();- log(- 'Deprecate agent group failed: %s %s - %s',- response.status,- response.statusText,- errorText,- );- throw new Error(`Failed to deprecate agent group: ${response.statusText}`);- }-- log('Deprecate agent group success');- return { success: true };+ const response = await ctx.marketSDK.agentGroups.deprecate(input.identifier);+ return response ?? { success: true };} catch (error) {log('Error deprecating agent group: %O', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: error instanceof Error ? error.message : 'Failed to deprecate agent group',- });+ throw mapMarketError(error, 'Failed to deprecate agent group');}}),@@ -619,64 +581,6 @@ export const agentGroupRouter = router({}}),- /**- * Publish agent group- * POST /market/agent-group/:identifier/publish- */- publishAgentGroup: agentGroupWriteProcedure- .input(z.object({ identifier: z.string() }))- .mutation(async ({ input, ctx }) => {- log('publishAgentGroup input: %O', input);-- try {- const publishUrl = `${MARKET_BASE_URL}/api/v1/agent-groups/${input.identifier}/publish`;-- const headers: Record<string, string> = {- 'Content-Type': 'application/json',- };-- const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;- const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;-- if (userInfo) {- const trustedClientToken = generateTrustedClientToken(userInfo);- if (trustedClientToken) {- headers['x-lobe-trust-token'] = trustedClientToken;- }- }-- if (!headers['x-lobe-trust-token'] && accessToken) {- headers['Authorization'] = `Bearer ${accessToken}`;- }-- const response = await fetch(publishUrl, {- headers,- method: 'POST',- });-- if (!response.ok) {- const errorText = await response.text();- log(- 'Publish agent group failed: %s %s - %s',- response.status,- response.statusText,- errorText,- );- throw new Error(`Failed to publish agent group: ${response.statusText}`);- }-- log('Publish agent group success');- return { success: true };- } catch (error) {- log('Error publishing agent group: %O', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: error instanceof Error ? error.message : 'Failed to publish agent group',- });- }- }),-/*** Unified publish or create agent group flow* 1. Check if identifier exists and if current user is owner@@ -776,64 +680,6 @@ export const agentGroupRouter = router({});}}),-- /**- * Unpublish agent group- * POST /market/agent-group/:identifier/unpublish- */- unpublishAgentGroup: agentGroupWriteProcedure- .input(z.object({ identifier: z.string() }))- .mutation(async ({ input, ctx }) => {- log('unpublishAgentGroup input: %O', input);-- try {- const unpublishUrl = `${MARKET_BASE_URL}/api/v1/agent-groups/${input.identifier}/unpublish`;-- const headers: Record<string, string> = {- 'Content-Type': 'application/json',- };-- const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;- const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;-- if (userInfo) {- const trustedClientToken = generateTrustedClientToken(userInfo);- if (trustedClientToken) {- headers['x-lobe-trust-token'] = trustedClientToken;- }- }-- if (!headers['x-lobe-trust-token'] && accessToken) {- headers['Authorization'] = `Bearer ${accessToken}`;- }-- const response = await fetch(unpublishUrl, {- headers,- method: 'POST',- });-- if (!response.ok) {- const errorText = await response.text();- log(- 'Unpublish agent group failed: %s %s - %s',- response.status,- response.statusText,- errorText,- );- throw new Error(`Failed to unpublish agent group: ${response.statusText}`);- }-- log('Unpublish agent group success');- return { success: true };- } catch (error) {- log('Error unpublishing agent group: %O', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: error instanceof Error ? error.message : 'Failed to unpublish agent group',- });- }- }),});export type AgentGroupRouter = typeof agentGroupRouter;diff --git a/apps/server/src/routers/lambda/market/index.test.ts b/apps/server/src/routers/lambda/market/index.test.tsnew file mode 100644index 00000000000..c7466f070e8--- /dev/null+++ b/apps/server/src/routers/lambda/market/index.test.ts@@ -0,0 +1,99 @@+// @vitest-environment node+import { MarketAPIError } from '@lobehub/market-sdk';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mockDiscover = vi.hoisted(() => ({+ getAssistantDetail: vi.fn(),+ getGroupAgentDetail: vi.fn(),+ getMcpDetail: vi.fn(),+ getMcpManifest: vi.fn(),+ getModelDetail: vi.fn(),+ getPluginDetail: vi.fn(),+ getProviderDetail: vi.fn(),+ getUserInfo: vi.fn(),+}));++vi.mock('@/libs/trpc/lambda/middleware', () => ({+ marketUserInfo: vi.fn(function (opts: any) {+ return opts.next({ ctx: opts.ctx });+ }),+ serverDatabase: vi.fn(function (opts: any) {+ return opts.next(opts);+ }),+}));+// Sibling routers have their own suites and need the full middleware surface.+vi.mock('./agent', async () => ({ agentRouter: (await import('@/libs/trpc/lambda')).router({}) }));+vi.mock('./agentGroup', async () => ({+ agentGroupRouter: (await import('@/libs/trpc/lambda')).router({}),+}));+vi.mock('./creds', async () => ({ credsRouter: (await import('@/libs/trpc/lambda')).router({}) }));+vi.mock('./oidc', async () => ({ oidcRouter: (await import('@/libs/trpc/lambda')).router({}) }));+vi.mock('./skill', async () => ({ skillRouter: (await import('@/libs/trpc/lambda')).router({}) }));+vi.mock('./social', async () => ({+ socialRouter: (await import('@/libs/trpc/lambda')).router({}),+}));+vi.mock('./socialProfile', async () => ({+ socialProfileRouter: (await import('@/libs/trpc/lambda')).router({}),+}));+vi.mock('./user', async () => ({ userRouter: (await import('@/libs/trpc/lambda')).router({}) }));+vi.mock('@/business/server/lambda-routers/marketDeployments', async () => {+ const { router } = await import('@/libs/trpc/lambda');+ return { marketDeploymentsRouter: router({}) };+});+vi.mock('@/server/services/discover', () => ({+ DiscoverService: vi.fn(function () {+ return mockDiscover;+ }),+}));+vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn(function () {+ return {};+ }),+}));++const createCaller = async () => {+ const { marketRouter } = await import('./index');+ return marketRouter.createCaller({ userId: 'user-1' } as any);+};++const detailCalls: Array<[string, (caller: any) => Promise<unknown>]> = [+ ['getAssistantDetail', (c) => c.getAssistantDetail({ identifier: 'x' })],+ ['getGroupAgentDetail', (c) => c.getGroupAgentDetail({ identifier: 'x' })],+ ['getMcpDetail', (c) => c.getMcpDetail({ identifier: 'x' })],+ ['getMcpManifest', (c) => c.getMcpManifest({ identifier: 'x' })],+ ['getModelDetail', (c) => c.getModelDetail({ identifier: 'x' })],+ ['getPluginDetail', (c) => c.getPluginDetail({ identifier: 'x' })],+ ['getProviderDetail', (c) => c.getProviderDetail({ identifier: 'x' })],+ ['getUserInfo', (c) => c.getUserInfo({ username: 'x' })],+];++describe('marketRouter detail procedures keep the upstream Market status', () => {+ beforeEach(() => vi.clearAllMocks());++ it.each(detailCalls)('%s maps a Market 404 to NOT_FOUND', async (name, call) => {+ mockDiscover[name as keyof typeof mockDiscover].mockRejectedValue(+ new MarketAPIError(404, 'Not Found'),+ );++ await expect(call(await createCaller())).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it.each(detailCalls)('%s maps a Market 429 to TOO_MANY_REQUESTS', async (name, call) => {+ mockDiscover[name as keyof typeof mockDiscover].mockRejectedValue(+ new MarketAPIError(429, 'Too Many'),+ );++ await expect(call(await createCaller())).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' });+ });++ it('keeps a non-Market failure as INTERNAL_SERVER_ERROR with the fallback message', async () => {+ mockDiscover.getGroupAgentDetail.mockRejectedValue(new Error('boom: secret detail'));++ await expect(+ (await createCaller()).getGroupAgentDetail({ identifier: 'x' }),+ ).rejects.toMatchObject({+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to fetch group agent detail',+ });+ });+});diff --git a/apps/server/src/routers/lambda/market/index.ts b/apps/server/src/routers/lambda/market/index.tsindex 73a8fe1d017..bc0ed9bb04f 100644--- a/apps/server/src/routers/lambda/market/index.ts+++ b/apps/server/src/routers/lambda/market/index.ts@@ -21,6 +21,7 @@ import {import { agentRouter } from './agent';import { agentGroupRouter } from './agentGroup';import { credsRouter } from './creds';+import { mapMarketError } from './marketError';import { oidcRouter } from './oidc';import { skillRouter } from './skill';import { socialRouter } from './social';@@ -130,10 +131,7 @@ export const marketRouter = router({return await ctx.discoverService.getAssistantDetail(input);} catch (error) {log('Error fetching assistants detail: %O', error);- throw new TRPCError({- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch assistants detail',- });+ throw mapMarketError(error, 'Failed to fetch assistants detail');}}),@@ -231,10 +229,7 @@ export const marketRouter = router({return await ctx.discoverService.getGroupAgentDetail(input);} catch (error) {log('Error fetching group agent detail: %O', error);- throw new TRPCError({- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch group agent detail',- });+ throw mapMarketError(error, 'Failed to fetch group agent detail');}}),@@ -341,10 +336,7 @@ export const marketRouter = router({return await ctx.discoverService.getMcpDetail(input);} catch (error) {console.error('Error fetching mcp detail: %O', error);- throw new TRPCError({- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch mcp detail',- });+ throw mapMarketError(error, 'Failed to fetch mcp detail');}}),@@ -393,10 +385,7 @@ export const marketRouter = router({return await ctx.discoverService.getMcpManifest(input);} catch (error) {log('Error fetching mcp manifest: %O', error);- throw new TRPCError({- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch mcp manifest',- });+ throw mapMarketError(error, 'Failed to fetch mcp manifest');}}),@@ -437,10 +426,7 @@ export const marketRouter = router({return await ctx.discoverService.getModelDetail(input);} catch (error) {log('Error fetching model details: %O', error);- throw new TRPCError({- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch model details',- });+ throw mapMarketError(error, 'Failed to fetch model details');}}),@@ -525,10 +511,7 @@ export const marketRouter = router({return await ctx.discoverService.getPluginDetail(input);} catch (error) {log('Error fetching plugin details: %O', error);- throw new TRPCError({- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch plugin details',- });+ throw mapMarketError(error, 'Failed to fetch plugin details');}}),@@ -590,10 +573,7 @@ export const marketRouter = router({return await ctx.discoverService.getProviderDetail(input);} catch (error) {log('Error fetching provider details: %O', error);- throw new TRPCError({- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch provider details',- });+ throw mapMarketError(error, 'Failed to fetch provider details');}}),@@ -653,10 +633,7 @@ export const marketRouter = router({return await ctx.discoverService.getUserInfo(input);} catch (error) {log('Error fetching user info: %O', error);- throw new TRPCError({- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch user info',- });+ throw mapMarketError(error, 'Failed to fetch user info');}}),diff --git a/apps/server/src/routers/lambda/market/marketError.ts b/apps/server/src/routers/lambda/market/marketError.tsnew file mode 100644index 00000000000..f1089cc17fa--- /dev/null+++ b/apps/server/src/routers/lambda/market/marketError.ts@@ -0,0 +1,49 @@+import { MarketAPIError } from '@lobehub/market-sdk';+import { TRPCError } from '@trpc/server';++/**+ * Note the deliberate absence of `401`.+ *+ * `UNAUTHORIZED` is not an inert status code here β it drives re-authentication+ * UI. `createResponseMeta` tags any `UNAUTHORIZED` whose message isn't the+ * `MARKET_AUTH_REQUIRED_MESSAGE` sentinel with `X-Auth-Required`, and the+ * desktop proxy opens the LobeHub re-login prompt on that header. Mapping an+ * upstream 401 through would therefore ask the user to re-sign into LobeHub+ * because *Market* rejected a credential.+ *+ * Signing into LobeHub cannot repair a credential Market rejected (a broken+ * server trusted-client token/config, or an expired Market token). Procedures+ * that need the user to sign into Market must say so explicitly with the+ * `MARKET_AUTH_REQUIRED_MESSAGE` sentinel / `requireMarketAuth`, not through+ * this generic mapper. So a 401 stays a 500.+ */+const MARKET_STATUS_TO_TRPC_CODE: Record<number, TRPCError['code']> = {+ 400: 'BAD_REQUEST',+ 403: 'FORBIDDEN',+ 404: 'NOT_FOUND',+ 429: 'TOO_MANY_REQUESTS',+};++/**+ * Preserve the upstream Market status instead of collapsing everything into a+ * blanket 500.+ *+ * This matters most for `429`: Market rate limits these endpoints, and a client+ * that only sees `INTERNAL_SERVER_ERROR` cannot tell a transient throttle from a+ * real outage β so it retries with exponential backoff, and those retries land+ * inside the same rate-limit window and keep the bucket empty. Surfacing+ * `TOO_MANY_REQUESTS` lets the SWR retry gate stand down (see `useClientDataSWR`)+ * and lets the UI say something true.+ */+export function mapMarketError(error: unknown, fallbackMessage: string): TRPCError {+ // Already mapped upstream (e.g. by a nested helper); re-wrapping would lose its code.+ if (error instanceof TRPCError) return error;+ if (error instanceof MarketAPIError) {+ return new TRPCError({+ cause: error,+ code: MARKET_STATUS_TO_TRPC_CODE[error.status] ?? 'INTERNAL_SERVER_ERROR',+ message: error.message || fallbackMessage,+ });+ }+ return new TRPCError({ cause: error, code: 'INTERNAL_SERVER_ERROR', message: fallbackMessage });+}diff --git a/apps/server/src/routers/lambda/market/skill.ts b/apps/server/src/routers/lambda/market/skill.tsindex 837ce3e1203..e4a39973982 100644--- a/apps/server/src/routers/lambda/market/skill.ts+++ b/apps/server/src/routers/lambda/market/skill.ts@@ -1,5 +1,3 @@-import { MarketAPIError } from '@lobehub/market-sdk';-import { TRPCError } from '@trpc/server';import debug from 'debug';import { z } from 'zod';@@ -8,52 +6,9 @@ import { marketUserInfo, serverDatabase } from '@/libs/trpc/lambda/middleware';import { MarketService } from '@/server/services/market';import { SkillSorts } from '@/types/discover';-const log = debug('lambda-router:market:skill');--/**- * Note the deliberate absence of `401`.- *- * `UNAUTHORIZED` is not an inert status code here β it drives re-authentication- * UI. `createResponseMeta` tags any `UNAUTHORIZED` whose message isn't the- * `MARKET_AUTH_REQUIRED_MESSAGE` sentinel with `X-Auth-Required`, and the- * desktop proxy opens the LobeHub re-login prompt on that header. Mapping an- * upstream 401 through would therefore ask the user to re-sign into LobeHub- * because *Market* rejected a credential.- *- * Routing it to the Market sentinel instead would be just as wrong for this- * router: these are `publicProcedure`s with no `requireMarketAuth`, authenticated- * by the server's trusted-client token. A 401 here means that server credential- * is broken β a misconfiguration the user cannot fix by signing in anywhere. So- * it stays a 500, which is what it is: our problem, not theirs.- */-const MARKET_STATUS_TO_TRPC_CODE: Record<number, TRPCError['code']> = {- 400: 'BAD_REQUEST',- 403: 'FORBIDDEN',- 404: 'NOT_FOUND',- 429: 'TOO_MANY_REQUESTS',-};+import { mapMarketError } from './marketError';-/**- * Preserve the upstream Market status instead of collapsing everything into a- * blanket 500.- *- * This matters most for `429`: Market rate limits these endpoints, and a client- * that only sees `INTERNAL_SERVER_ERROR` cannot tell a transient throttle from a- * real outage β so it retries with exponential backoff, and those retries land- * inside the same rate-limit window and keep the bucket empty. Surfacing- * `TOO_MANY_REQUESTS` lets the SWR retry gate stand down (see `useClientDataSWR`)- * and lets the UI say something true.- */-function mapMarketError(error: unknown, fallbackMessage: string): TRPCError {- if (error instanceof MarketAPIError) {- return new TRPCError({- cause: error,- code: MARKET_STATUS_TO_TRPC_CODE[error.status] ?? 'INTERNAL_SERVER_ERROR',- message: error.message || fallbackMessage,- });- }- return new TRPCError({ cause: error, code: 'INTERNAL_SERVER_ERROR', message: fallbackMessage });-}+const log = debug('lambda-router:market:skill');// Public procedure with optional user info for trusted client tokenconst marketProcedure = publicProcedurediff --git a/apps/server/src/routers/tools/market.test.ts b/apps/server/src/routers/tools/market.test.tsindex 98745955047..42c042ae3b5 100644--- a/apps/server/src/routers/tools/market.test.ts+++ b/apps/server/src/routers/tools/market.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { MarketAPIError } from '@lobehub/market-sdk';import { beforeEach, describe, expect, it, vi } from 'vitest';import { marketRouter } from './market';@@ -266,4 +267,39 @@ describe('tools marketRouter', () => {topicId: undefined,});});++ // Regression: the SDK carries the machine code in `error.code` and the message is human+ // text, so matching the message always fell through to INTERNAL_SERVER_ERROR.+ it.each(['NOT_CONNECTED', 'TOKEN_EXPIRED'])(+ 'should map a Market %s error to PRECONDITION_FAILED instead of UNAUTHORIZED',+ async (code) => {+ const caller = marketRouter.createCaller({ userId: 'user-1' } as any);+ mockMarketSDK.skills.callTool.mockRejectedValue(+ new MarketAPIError(401, 'Unauthorized', { error: { code, message: 'No connection' } }),+ );++ await expect(+ caller.connectCallTool({ provider: 'linear', toolName: 'createIssue' }),+ ).rejects.toMatchObject({+ cause: { data: { code } },+ code: 'PRECONDITION_FAILED',+ });+ },+ );++ it('should keep other connectCallTool failures as INTERNAL_SERVER_ERROR', async () => {+ const caller = marketRouter.createCaller({ userId: 'user-1' } as any);+ mockMarketSDK.skills.callTool.mockRejectedValueOnce(+ new MarketAPIError(500, 'Server Error', { error: { code: 'UPSTREAM_FAILED', message: 'x' } }),+ );+ await expect(+ caller.connectCallTool({ provider: 'linear', toolName: 'createIssue' }),+ ).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });++ // A message that merely mentions the code is not a connection error.+ mockMarketSDK.skills.callTool.mockRejectedValueOnce(new Error('NOT_CONNECTED'));+ await expect(+ caller.connectCallTool({ provider: 'linear', toolName: 'createIssue' }),+ ).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });+ });});diff --git a/apps/server/src/routers/tools/market.ts b/apps/server/src/routers/tools/market.tsindex 59f1322238c..92eb22db3e1 100644--- a/apps/server/src/routers/tools/market.ts+++ b/apps/server/src/routers/tools/market.ts@@ -1,4 +1,5 @@import { MARKET_AUTH_REQUIRED_MESSAGE } from '@lobechat/desktop-bridge';+import { MarketAPIError } from '@lobehub/market-sdk';import { TRPCError } from '@trpc/server';import debug from 'debug';import { z } from 'zod';@@ -25,6 +26,7 @@ import {} from '@/server/services/mcp/contentProcessor';import { createSandboxService, resolveSandboxSessionConfig } from '@/server/services/sandbox';import { preprocessLhCommand } from '@/server/services/toolExecution/preprocessLhCommand';+import { SkillConnectionErrorCode } from '@/types/skillConnectionError';import { scheduleToolCallReport } from './_helpers';import {@@ -508,17 +510,22 @@ export const marketRouter = router({const errorMessage = (error as Error).message;log('connectCallTool error: %s', errorMessage);- if (errorMessage.includes('NOT_CONNECTED')) {+ // The SDK carries the machine code in `error.code`; the message is human text.+ // Not UNAUTHORIZED: that code opens the LobeHub / Market re-login flows (see+ // createResponseMeta), and a provider connection is neither. The client tells+ // these apart by `errorData.code`.+ const connectionCode =+ error instanceof MarketAPIError+ ? Object.values(SkillConnectionErrorCode).find((code) => error.isErrorCode(code))+ : undefined;+ if (connectionCode) {throw new TRPCError({- code: 'UNAUTHORIZED',- message: 'Provider not connected. Please authorize first.',- });- }-- if (errorMessage.includes('TOKEN_EXPIRED')) {- throw new TRPCError({- code: 'UNAUTHORIZED',- message: 'Token expired. Please re-authorize.',+ cause: { data: { code: connectionCode } },+ code: 'PRECONDITION_FAILED',+ message:+ connectionCode === SkillConnectionErrorCode.NotConnected+ ? 'Provider not connected. Please authorize first.'+ : 'Token expired. Please re-authorize.',});}diff --git a/apps/server/src/services/discover/index.marketErrors.test.ts b/apps/server/src/services/discover/index.marketErrors.test.tsnew file mode 100644index 00000000000..1f2880e3154--- /dev/null+++ b/apps/server/src/services/discover/index.marketErrors.test.ts@@ -0,0 +1,161 @@+// @vitest-environment node+import { MarketAPIError } from '@lobehub/market-sdk';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DiscoverService } from './index';++const { market, getPluginList } = vi.hoisted(() => ({+ getPluginList: vi.fn(),+ market: {+ agentGroups: { getAgentGroupDetail: vi.fn() },+ agents: { getAgentDetail: vi.fn(), getAgentList: vi.fn() },+ plugins: {+ getPluginDetail: vi.fn(),+ getPluginList: vi.fn(),+ getPluginManifest: vi.fn(),+ },+ user: { getUserInfo: vi.fn() },+ },+}));++vi.mock('@/server/services/market', () => ({+ MarketService: class {+ market = market;+ },+}));+vi.mock('@/server/modules/AssistantStore', () => ({ AssistantStore: class {} }));+vi.mock('@/server/modules/PluginStore', () => ({+ PluginStore: class {+ getPluginList = getPluginList;+ },+}));+vi.mock('@/locales/resources', () => ({ normalizeLocale: (locale?: string) => locale || 'en' }));+vi.mock('@lobechat/builtin-tools', () => ({+ builtinTools: [+ { identifier: 'builtin-test', manifest: { meta: { title: 'Builtin test tool' } } },+ ],+}));++const missingErrors = [+ new MarketAPIError(404, 'Not Found'),+ new MarketAPIError(400, 'Bad Request', { error: { code: 'NOT_FOUND', message: 'Missing' } }),+];+const otherErrors = [+ ...[401, 403, 429, 500, 503].map((status) => new MarketAPIError(status, `Market ${status}`)),+ new Error('Network unavailable'),+];++describe('DiscoverService Market detail failures', () => {+ let service: DiscoverService;++ beforeEach(() => {+ vi.resetAllMocks();+ getPluginList.mockResolvedValue([]);+ market.agents.getAgentList.mockResolvedValue({ items: [] });+ market.plugins.getPluginList.mockResolvedValue({ items: [] });+ service = new DiscoverService();+ });++ describe.each([+ {+ call: (s: DiscoverService) => s.getAssistantDetail({ identifier: 'test-agent' }),+ name: 'assistant',+ sdk: market.agents.getAgentDetail,+ },+ {+ call: (s: DiscoverService) => s.getUserInfo({ username: 'test-user' }),+ name: 'user',+ sdk: market.user.getUserInfo,+ },+ {+ call: (s: DiscoverService) => s.getPluginDetail({ identifier: 'missing-plugin' }),+ name: 'plugin',+ sdk: market.plugins.getPluginDetail,+ },+ ])('$name lookup', ({ call, sdk }) => {+ it.each(missingErrors)('returns undefined for a Market not-found error: %s', async (error) => {+ sdk.mockRejectedValue(error);++ await expect(call(service)).resolves.toBeUndefined();+ });++ it.each(otherErrors)('propagates the original failure: %s', async (error) => {+ sdk.mockRejectedValue(error);++ await expect(call(service)).rejects.toBe(error);+ });+ });++ describe.each([+ {+ call: (s: DiscoverService) => s.getGroupAgentDetail({ identifier: 'test-group' }),+ name: 'group',+ sdk: market.agentGroups.getAgentGroupDetail,+ },+ {+ call: (s: DiscoverService) => s.getMcpDetail({ identifier: 'test-mcp' }),+ name: 'MCP',+ sdk: market.plugins.getPluginDetail,+ },+ {+ call: (s: DiscoverService) => s.getMcpManifest({ identifier: 'test-mcp' }),+ name: 'MCP manifest',+ sdk: market.plugins.getPluginManifest,+ },+ ])('$name lookup', ({ call, sdk }) => {+ it.each([missingErrors[0], ...otherErrors])(+ 'propagates the original failure: %s',+ async (error) => {+ sdk.mockRejectedValue(error);++ await expect(call(service)).rejects.toBe(error);+ },+ );+ });++ it('still returns an assistant detail after a successful SDK response', async () => {+ market.agents.getAgentDetail.mockResolvedValue({+ identifier: 'test-agent',+ name: 'Test agent',+ });++ await expect(service.getAssistantDetail({ identifier: 'test-agent' })).resolves.toMatchObject({+ identifier: 'test-agent',+ title: 'Test agent',+ });+ });++ it('still returns a user profile after a successful SDK response', async () => {+ market.user.getUserInfo.mockResolvedValue({ user: { id: 1, userName: 'test-user' } });++ await expect(service.getUserInfo({ username: 'test-user' })).resolves.toMatchObject({+ user: { id: 1, userName: 'test-user' },+ });+ });++ it('still returns legacy plugin detail with related items without querying Market', async () => {+ getPluginList.mockResolvedValue([+ { identifier: 'legacy-plugin', meta: { title: 'Legacy plugin' } },+ ]);++ await expect(service.getPluginDetail({ identifier: 'legacy-plugin' })).resolves.toMatchObject({+ identifier: 'legacy-plugin',+ related: [],+ source: 'legacy',+ title: 'Legacy plugin',+ });+ expect(market.plugins.getPluginDetail).not.toHaveBeenCalled();+ });++ it.each(missingErrors)(+ 'still falls back to builtin tools for Market not-found: %s',+ async (error) => {+ market.plugins.getPluginDetail.mockRejectedValue(error);++ await expect(service.getPluginDetail({ identifier: 'builtin-test' })).resolves.toMatchObject({+ identifier: 'builtin-test',+ source: 'builtin',+ });+ },+ );+});diff --git a/apps/server/src/services/discover/index.test.ts b/apps/server/src/services/discover/index.test.tsindex 7962a0cc569..26cb9be5013 100644--- a/apps/server/src/services/discover/index.test.ts+++ b/apps/server/src/services/discover/index.test.ts@@ -591,30 +591,6 @@ describe('DiscoverService', () => {expect(result.items[1].identifier).toBe('plugin-1');});});-- describe('getPluginDetail', () => {- it('should return plugin detail with related items', async () => {- const result = await service.getPluginDetail({- identifier: 'plugin-1',- });-- expect(result).toEqual(- expect.objectContaining({- identifier: 'plugin-1',- title: 'Test Plugin 1',- related: expect.any(Array),- }),- );- });-- it('should return undefined for non-existent plugin', async () => {- const result = await service.getPluginDetail({- identifier: 'non-existent',- });-- expect(result).toBeUndefined();- });- });});describe('MCP Market', () => {diff --git a/apps/server/src/services/discover/index.ts b/apps/server/src/services/discover/index.tsindex a05e4118702..846ec774520 100644--- a/apps/server/src/services/discover/index.ts+++ b/apps/server/src/services/discover/index.ts@@ -53,6 +53,7 @@ import {import {type CategoryItem,type CategoryListQuery,+ MarketAPIError,type MarketSDK,type UserInfoResponse,} from '@lobehub/market-sdk';@@ -77,6 +78,9 @@ import { MarketService } from '@/server/services/market';const log = debug('lobe-server:discover');+const isMarketNotFound = (error: unknown) =>+ error instanceof MarketAPIError && (error.status === 404 || error.isErrorCode('NOT_FOUND'));+const loadBuiltinModels = async () => {const { loadModels } = await import('@/business/client/model-bank/loadModels');return loadModels();@@ -563,17 +567,14 @@ export class DiscoverService {const normalizedLocale = normalizeLocale(locale);try {- // @ts-ignoreconst data = await this.market.agents.getAgentDetail(identifier, {locale: normalizedLocale,version,});-if (!data) {log('getAssistantDetail: assistant not found for identifier=%s', identifier);return;}-const normalizedAuthor = this.normalizeAuthorField(data.author);const assistant = {author:@@ -623,7 +624,6 @@ export class DiscoverService {version: item.version,})) || [],};-// Get related assistantsconst list = await this.getAssistantList({category: assistant.category,@@ -633,17 +633,15 @@ export class DiscoverService {pageSize: 7,source,});-const result = {...assistant,related: list.items.filter((item) => item.identifier !== assistant.identifier).slice(0, 6),};-log('getAssistantDetail: returning assistant with %d related items', result.related.length);return result;} catch (error) {log('getAssistantDetail: error fetching from market SDK: %O', error);- return;+ if (!isMarketNotFound(error)) throw error;}};@@ -1144,7 +1142,8 @@ export class DiscoverService {const plugin = merge(cloneDeep(DEFAULT_DISCOVER_PLUGIN_ITEM), convertedMcp);log('getPluginDetail: returning converted MCP plugin');return plugin as DiscoverPluginDetail;- } catch {+ } catch (error) {+ if (!isMarketNotFound(error)) throw error;log('getPluginDetail: MCP plugin not found for identifier=%s, trying builtin tools',identifier,@@ -2068,7 +2067,7 @@ export class DiscoverService {return result;} catch (error) {log('getUserInfo: error fetching user info: %O', error);- return undefined;+ if (!isMarketNotFound(error)) throw error;}};diff --git a/src/routes/(main)/community/(detail)/group_agent/index.tsx b/src/routes/(main)/community/(detail)/group_agent/index.tsxindex d408d4944b6..34c55e7b860 100644--- a/src/routes/(main)/community/(detail)/group_agent/index.tsx+++ b/src/routes/(main)/community/(detail)/group_agent/index.tsx@@ -9,6 +9,7 @@ import { RouteLoading } from '@/components/Skeleton/RouteSegment';import { useQuery } from '@/hooks/useQuery';import { useDiscoverStore } from '@/store/discover';import { groupAgentSelectors } from '@/store/discover/selectors';+import { isTrpcErrorCode } from '@/utils/trpcError';import NotFound from '../components/NotFound';import { TocProvider } from '../features/Toc/useToc';@@ -34,7 +35,9 @@ const GroupAgentDetailPage = memo<GroupAgentDetailPageProps>(({ mobile }) => {if (data === undefined) {if (isLoading) return <RouteLoading />;- if (error) return <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />;+ if (error && !isTrpcErrorCode(error, 'NOT_FOUND')) {+ return <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />;+ }return <NotFound />;}const status = (data as any)?.group?.status || (data as any)?.status;diff --git a/src/store/discover/slices/groupAgent/action.test.ts b/src/store/discover/slices/groupAgent/action.test.tsindex 44c47c93501..b6be7bbb382 100644--- a/src/store/discover/slices/groupAgent/action.test.ts+++ b/src/store/discover/slices/groupAgent/action.test.ts@@ -65,7 +65,11 @@ const syncCalls = async (([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,).map(([key, fetcher, config]) => ({- config: config as { onSuccess?: (data: unknown) => void; revalidateOnFocus?: boolean },+ config: config as {+ onError?: (error: unknown) => void;+ onSuccess?: (data: unknown) => void;+ revalidateOnFocus?: boolean;+ },fetcher: fetcher as () => Promise<any>,key: key as unknown[],}));@@ -206,6 +210,21 @@ describe('GroupAgentSlice (replica)', () => {expect(useStore.getState().groupAgentDetailMap[key]).toBeUndefined();});+ it('evicts a hydrated detail when revalidation answers NOT_FOUND, keeps it on transient errors', async () => {+ const { result } = renderHook(() =>+ useStore.getState().useFetchGroupAgentDetail({ identifier: 'group-1' }),+ );+ const key = result.current.queryKey!;+ useStore.setState({ groupAgentDetailMap: { [key]: { identifier: 'group-1' } as any } });++ const [call] = await syncCalls('groupAgentDetail');+ act(() => call.config.onError!({ data: { code: 'INTERNAL_SERVER_ERROR' } }));+ expect(groupAgentSelectors.groupAgentDetail(key)(useStore.getState())).toBeDefined();++ act(() => call.config.onError!({ data: { code: 'NOT_FOUND' } }));+ expect(groupAgentSelectors.groupAgentDetail(key)(useStore.getState())).toBeUndefined();+ });+it('keys the detail by identifier and version', () => {const { result } = renderHook(() => [useStore.getState().useFetchGroupAgentDetail({ identifier: 'writing-team' }),diff --git a/src/store/discover/slices/groupAgent/action.ts b/src/store/discover/slices/groupAgent/action.tsindex e9d6b881ba8..cc19d185dce 100644--- a/src/store/discover/slices/groupAgent/action.ts+++ b/src/store/discover/slices/groupAgent/action.ts@@ -11,6 +11,7 @@ import type {IdentifiersResponse,} from '@/types/discover';import { setNamespace } from '@/utils/storeDebug';+import { isTrpcErrorCode } from '@/utils/trpcError';import {type GroupAgentCategoriesParams,@@ -141,7 +142,17 @@ export class GroupAgentActionImpl {version: params.version,};const queryKey = groupAgentDetailQueryKey(normalized);- const sync = this.#detail.useSync(normalized, { enabled, revalidateOnFocus: false });+ const sync = this.#detail.useSync(normalized, {+ enabled,+ // NOT_FOUND is definitive: drop the hydrated entry (memory plus persisted+ // rows) so a deleted group stops painting a stale copy. Bind the removal+ // to the scope the failing request was captured under. Transient failures+ // keep the cached detail.+ onError: (error, { key, scope }) => {+ if (key && isTrpcErrorCode(error, 'NOT_FOUND')) this.#detail.remove(key, scope);+ },+ revalidateOnFocus: false,+ });return this.#toSyncResult(sync,queryKey,diff --git a/src/store/tool/slices/lobehubSkillStore/action.test.ts b/src/store/tool/slices/lobehubSkillStore/action.test.tsindex 9b347b96a40..3da9dbf3bc9 100644--- a/src/store/tool/slices/lobehubSkillStore/action.test.ts+++ b/src/store/tool/slices/lobehubSkillStore/action.test.ts@@ -269,65 +269,55 @@ describe('lobehubSkillStore actions', () => {expect(result.current.lobehubSkillExecutingToolIds.has('linear:createIssue')).toBe(false);});- it('should handle NOT_CONNECTED error', async () => {- const { result } = renderHook(() => useToolStore());-- act(() => {- useToolStore.setState({- lobehubSkillServers: [],- lobehubSkillLoadingIds: new Set(),- lobehubSkillExecutingToolIds: new Set(),+ // The server reports a missing / expired connection as PRECONDITION_FAILED with+ // the code in errorData (the message is human text).+ it.each(['NOT_CONNECTED', 'TOKEN_EXPIRED'])(+ 'should flag a PRECONDITION_FAILED %s error as needing authorization',+ async (code) => {+ const { result } = renderHook(() => useToolStore());++ vi.mocked(toolsClient.market.connectCallTool.mutate).mockRejectedValue(+ Object.assign(new Error('Provider not connected. Please authorize first.'), {+ data: { code: 'PRECONDITION_FAILED', errorData: { code } },+ }),+ );++ let callResult;+ await act(async () => {+ callResult = await result.current.callLobehubSkillTool({+ provider: 'linear',+ toolName: 'createIssue',+ });});- });-- vi.mocked(toolsClient.market.connectCallTool.mutate).mockRejectedValue(- new Error('NOT_CONNECTED'),- );- let callResult;- await act(async () => {- callResult = await result.current.callLobehubSkillTool({- provider: 'linear',- toolName: 'createIssue',+ expect(callResult).toEqual({+ error: 'Provider not connected. Please authorize first.',+ errorCode: 'NOT_CONNECTED',+ success: false,});- });+ expect(result.current.lobehubSkillExecutingToolIds.has('linear:createIssue')).toBe(false);+ },+ );- expect(callResult).toEqual({- error: 'NOT_CONNECTED',- errorCode: 'NOT_CONNECTED',- success: false,- });- expect(result.current.lobehubSkillExecutingToolIds.has('linear:createIssue')).toBe(false);- });-- it('should handle TOKEN_EXPIRED error', async () => {+ it('should not treat a generic UNAUTHORIZED or code-in-message error as NOT_CONNECTED', async () => {const { result } = renderHook(() => useToolStore());- act(() => {- useToolStore.setState({- lobehubSkillServers: [],- lobehubSkillLoadingIds: new Set(),- lobehubSkillExecutingToolIds: new Set(),- });- });-- vi.mocked(toolsClient.market.connectCallTool.mutate).mockRejectedValue(- new Error('TOKEN_EXPIRED'),- );-- let callResult;- await act(async () => {- callResult = await result.current.callLobehubSkillTool({- provider: 'linear',- toolName: 'createIssue',+ for (const error of [+ Object.assign(new Error('Unauthorized'), { data: { code: 'UNAUTHORIZED' } }),+ new Error('NOT_CONNECTED'),+ ]) {+ vi.mocked(toolsClient.market.connectCallTool.mutate).mockRejectedValueOnce(error);++ let callResult;+ await act(async () => {+ callResult = await result.current.callLobehubSkillTool({+ provider: 'linear',+ toolName: 'createIssue',+ });});- });- expect(callResult).toEqual({- error: 'TOKEN_EXPIRED',- errorCode: 'NOT_CONNECTED',- success: false,- });+ expect(callResult).toEqual({ error: error.message, success: false });+ }});it('should handle generic error', async () => {diff --git a/src/store/tool/slices/lobehubSkillStore/action.ts b/src/store/tool/slices/lobehubSkillStore/action.tsindex 66dd2baa5c9..7e16a2e46c1 100644--- a/src/store/tool/slices/lobehubSkillStore/action.ts+++ b/src/store/tool/slices/lobehubSkillStore/action.ts@@ -13,6 +13,7 @@ import { toolsClient } from '@/libs/trpc/client';import { type StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';+import { isSkillConnectionError } from '@/types/skillConnectionError';import { setNamespace } from '@/utils/storeDebug';import { type ToolStore } from '../../store';@@ -189,7 +190,9 @@ export class LobehubSkillStoreActionImpl {const errorMessage = error instanceof Error ? error.message : String(error);- if (errorMessage.includes('NOT_CONNECTED') || errorMessage.includes('TOKEN_EXPIRED')) {+ // The server flags a missing / expired connection as PRECONDITION_FAILED plus a+ // discriminator in errorData; its message is human text, never the code.+ if (isSkillConnectionError(error)) {return {error: errorMessage,errorCode: 'NOT_CONNECTED',diff --git a/src/types/skillConnectionError.test.ts b/src/types/skillConnectionError.test.tsnew file mode 100644index 00000000000..89038654891--- /dev/null+++ b/src/types/skillConnectionError.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';++import { isSkillConnectionError } from './skillConnectionError';++const trpcError = (code: string, errorCode?: string) => ({+ data: { code, errorData: errorCode ? { code: errorCode } : undefined },+});++describe('isSkillConnectionError', () => {+ it.each(['NOT_CONNECTED', 'TOKEN_EXPIRED'])('accepts PRECONDITION_FAILED + %s', (code) => {+ expect(isSkillConnectionError(trpcError('PRECONDITION_FAILED', code))).toBe(true);+ });++ it.each([+ ['plain UNAUTHORIZED', trpcError('UNAUTHORIZED')],+ ['UNAUTHORIZED carrying a connection code', trpcError('UNAUTHORIZED', 'NOT_CONNECTED')],+ ['PRECONDITION_FAILED without errorData', trpcError('PRECONDITION_FAILED')],+ ['PRECONDITION_FAILED with another code', trpcError('PRECONDITION_FAILED', 'OTHER')],+ ['error without data', new Error('NOT_CONNECTED')],+ ['null', null],+ ])('rejects %s', (_name, error) => {+ expect(isSkillConnectionError(error)).toBe(false);+ });+});diff --git a/src/types/skillConnectionError.ts b/src/types/skillConnectionError.tsnew file mode 100644index 00000000000..3021548ce36--- /dev/null+++ b/src/types/skillConnectionError.ts@@ -0,0 +1,25 @@+/**+ * Machine-readable discriminator for a LobeHub Skill provider whose connection+ * is missing or expired. Sent as the tRPC error's `cause.data.code` (surfaced+ * to clients as `error.data.errorData.code`) next to `PRECONDITION_FAILED`.+ *+ * Deliberately not `UNAUTHORIZED`: that code drives the LobeHub / Market+ * re-login flows, and a provider connection is neither.+ */+export const SkillConnectionErrorCode = {+ NotConnected: 'NOT_CONNECTED',+ TokenExpired: 'TOKEN_EXPIRED',+} as const;++export type SkillConnectionErrorCode =+ (typeof SkillConnectionErrorCode)[keyof typeof SkillConnectionErrorCode];++/** Whether a tRPC client error carries a provider-connection discriminator. */+export const isSkillConnectionError = (error: unknown): boolean => {+ const data = (error as { data?: { code?: unknown; errorData?: { code?: unknown } } } | null)+ ?.data;+ return (+ data?.code === 'PRECONDITION_FAILED' &&+ Object.values<unknown>(SkillConnectionErrorCode).includes(data.errorData?.code)+ );+};