🤯 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
⚡️ perf(market): batch fork API for parallel marketplace install (#14537)
Innei4dade3196fa8
diff --git a/packages/types/src/discover/fork.ts b/packages/types/src/discover/fork.tsindex 8abcd1dbce9..c61b016b7d2 100644--- a/packages/types/src/discover/fork.ts+++ b/packages/types/src/discover/fork.ts@@ -18,6 +18,27 @@ export interface AgentForkRequest {visibility?: 'public' | 'private' | 'internal';}+/**+ * Fork batch input item — single fork request plus the source identifier+ * (the source identifier is part of the URL when calling upstream singly,+ * but is carried in the body for batch payloads).+ */+export interface AgentForkBatchInput extends AgentForkRequest {+ /** Source agent identifier to fork from */+ sourceIdentifier: string;+}++/**+ * Per-item result of a batch fork. Best-effort: one failure does not abort the rest.+ */+export type AgentForkBatchResult =+ | { data: AgentForkResponse; sourceIdentifier: string; success: true }+ | {+ error: { code: string; message: string };+ sourceIdentifier: string;+ success: false;+ };+/*** Fork response for Agent*/diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.test.tsnew file mode 100644index 00000000000..272d8971b26--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.test.ts@@ -0,0 +1,139 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { agentService } from '@/services/agent';+import { discoverService } from '@/services/discover';+import { marketApiService } from '@/services/marketApi';+import { useAgentStore } from '@/store/agent';+import { useHomeStore } from '@/store/home';++import { installMarketplaceAgents } from './installMarketplaceAgents';++describe('installMarketplaceAgents', () => {+ const createAgent = vi.fn();+ const refreshAgentList = vi.fn();++ beforeEach(() => {+ vi.restoreAllMocks();+ createAgent.mockReset();+ refreshAgentList.mockReset();+ refreshAgentList.mockResolvedValue(undefined);++ vi.spyOn(useAgentStore, 'getState').mockReturnValue({+ createAgent,+ } as unknown as ReturnType<typeof useAgentStore.getState>);+ vi.spyOn(useHomeStore, 'getState').mockReturnValue({+ refreshAgentList,+ } as unknown as ReturnType<typeof useHomeStore.getState>);+ vi.spyOn(discoverService, 'reportAgentEvent').mockResolvedValue(undefined);+ });++ it('sends a single batched fork call carrying every selected agent', async () => {+ const sourceIds = ['src-a', 'src-b', 'src-c'];++ vi.spyOn(agentService, 'getAgentByForkedFromIdentifier').mockResolvedValue(null);+ vi.spyOn(discoverService, 'getAssistantDetail').mockImplementation(+ async ({ identifier }) =>+ ({+ avatar: 'avatar',+ backgroundColor: '#fff',+ category: 'engineering',+ config: { params: {} } as any,+ description: `desc-${identifier}`,+ editorData: {},+ identifier,+ summary: `summary-${identifier}`,+ tags: [],+ title: `Title-${identifier}`,+ }) as any,+ );++ const forkSpy = vi.spyOn(marketApiService, 'forkAgent').mockImplementation(async (items) =>+ items.map((item) => ({+ data: {+ agent: {+ createdAt: '2026-01-01',+ forkedFromAgentId: 1,+ id: 1,+ identifier: item.identifier,+ name: item.name ?? '',+ ownerId: 1,+ updatedAt: '2026-01-01',+ },+ source: { agentId: 1, identifier: item.sourceIdentifier, versionNumber: 1 },+ version: { agentId: 1, createdAt: '2026-01-01', id: 1, versionNumber: 1 },+ },+ sourceIdentifier: item.sourceIdentifier,+ success: true as const,+ })),+ );++ createAgent.mockImplementation(async ({ config }: any) => ({+ agentId: `agent-${config.params.forkedFromIdentifier}`,+ }));++ const result = await installMarketplaceAgents(sourceIds);++ expect(forkSpy).toHaveBeenCalledTimes(1);+ const [items] = forkSpy.mock.calls[0];+ expect(items).toHaveLength(3);+ expect(items.map((i) => i.sourceIdentifier)).toEqual(sourceIds);++ expect(createAgent).toHaveBeenCalledTimes(3);+ expect(result.installedAgentIds).toHaveLength(3);+ expect(result.skippedAgentIds).toEqual([]);+ expect(refreshAgentList).toHaveBeenCalledTimes(1);+ });++ it('skips already-forked agents at the dedupe step', async () => {+ const sourceIds = ['src-a', 'src-b', 'src-c'];++ vi.spyOn(agentService, 'getAgentByForkedFromIdentifier').mockImplementation(async (id) =>+ id === 'src-a' ? null : `existing-${id}`,+ );+ vi.spyOn(discoverService, 'getAssistantDetail').mockImplementation(+ async ({ identifier }) =>+ ({+ avatar: 'a',+ backgroundColor: '#fff',+ category: 'engineering',+ config: { params: {} } as any,+ description: 'd',+ editorData: {},+ identifier,+ summary: 's',+ tags: [],+ title: 'T',+ }) as any,+ );+ const forkSpy = vi.spyOn(marketApiService, 'forkAgent').mockImplementation(async (items) =>+ items.map((item) => ({+ data: {+ agent: {+ createdAt: '',+ forkedFromAgentId: 1,+ id: 1,+ identifier: item.identifier,+ name: item.name ?? '',+ ownerId: 1,+ updatedAt: '',+ },+ source: { agentId: 1, identifier: item.sourceIdentifier, versionNumber: 1 },+ version: { agentId: 1, createdAt: '', id: 1, versionNumber: 1 },+ },+ sourceIdentifier: item.sourceIdentifier,+ success: true as const,+ })),+ );+ createAgent.mockImplementation(async ({ config }: any) => ({+ agentId: `agent-${config.params.forkedFromIdentifier}`,+ }));++ const result = await installMarketplaceAgents(sourceIds);++ expect(forkSpy).toHaveBeenCalledTimes(1);+ const [items] = forkSpy.mock.calls[0];+ expect(items.map((i) => i.sourceIdentifier)).toEqual(['src-a']);+ expect(result.skippedAgentIds).toEqual(['src-b', 'src-c']);+ expect(result.installedAgentIds).toEqual(['agent-src-a']);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.tsindex 24a30273fe2..e8bfec48161 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.ts@@ -30,71 +30,135 @@ export interface InstallMarketplaceAgentsResult {export const installMarketplaceAgents = async (sourceAgentIds: string[],): Promise<InstallMarketplaceAgentsResult> => {- const installedAgentIds: string[] = [];- const skippedAgentIds: string[] = [];- const summaries: InstallMarketplaceAgentSummary[] = [];+ if (sourceAgentIds.length === 0) {+ return { installedAgentIds: [], skippedAgentIds: [], summaries: [] };+ }+const createAgent = useAgentStore.getState().createAgent;const refreshAgentList = useHomeStore.getState().refreshAgentList;- for (const sourceAgentId of sourceAgentIds) {- const existingAgentId = await agentService.getAgentByForkedFromIdentifier(sourceAgentId);- if (existingAgentId) {- skippedAgentIds.push(sourceAgentId);- summaries.push({ skipped: true, templateId: sourceAgentId });- continue;+ // 1. Parallel dedupe — find which source ids are already forked+ const existing = await Promise.all(+ sourceAgentIds.map((id) => agentService.getAgentByForkedFromIdentifier(id)),+ );+ const skippedAgentIds: string[] = [];+ const pendingSourceIds: string[] = [];+ sourceAgentIds.forEach((id, i) => {+ if (existing[i]) skippedAgentIds.push(id);+ else pendingSourceIds.push(id);+ });++ // 2. Parallel fetch market detail for pending ids (best-effort per item)+ const detailResults = await Promise.allSettled(+ pendingSourceIds.map((id) =>+ discoverService.getAssistantDetail({ identifier: id, source: 'new' }),+ ),+ );++ // 3. Build batch fork input only for items with valid detail+ type Prepared = {+ detail: NonNullable<Awaited<ReturnType<typeof discoverService.getAssistantDetail>>>;+ newIdentifier: string;+ sourceId: string;+ };+ const prepared: Prepared[] = [];+ detailResults.forEach((result, i) => {+ const sourceId = pendingSourceIds[i];+ if (result.status !== 'fulfilled') {+ console.warn('Failed to fetch marketplace agent detail:', sourceId, result.reason);+ return;}-- const marketAgent = await discoverService.getAssistantDetail({- identifier: sourceAgentId,- source: 'new',+ const detail = result.value;+ if (!detail?.config) {+ console.warn('Marketplace agent config is missing:', sourceId);+ return;+ }+ prepared.push({+ detail: detail as Prepared['detail'],+ newIdentifier: generateMarketIdentifier(),+ sourceId,});-- if (!marketAgent?.config) {- throw new Error(`Marketplace agent config is missing: ${sourceAgentId}`);+ });++ // 4. Single batch fork call+ const forkOutcomes =+ prepared.length === 0+ ? []+ : await marketApiService.forkAgent(+ prepared.map((p) => ({+ identifier: p.newIdentifier,+ name: p.detail.title,+ sourceIdentifier: p.sourceId,+ status: 'published',+ visibility: 'public',+ })),+ );++ // 5. Parallel local createAgent for successful forks+ const installResults = await Promise.allSettled(+ forkOutcomes.map(async (outcome, i) => {+ const { detail, sourceId } = prepared[i];+ if (!outcome.success) {+ throw new Error(outcome.error.message);+ }+ const fork = outcome.data;+ const result = await createAgent({+ config: {+ ...detail.config,+ avatar: detail.avatar,+ backgroundColor: detail.backgroundColor,+ description: detail.description,+ editorData: detail.editorData,+ marketIdentifier: fork.agent.identifier,+ params: {+ ...detail.config.params,+ forkedFromIdentifier: sourceId,+ },+ tags: detail.tags,+ title: fork.agent.name,+ },+ });++ discoverService.reportAgentEvent({+ event: 'add',+ identifier: fork.agent.identifier,+ source: getSourcePath(),+ });++ return { agentId: result.agentId, sourceId };+ }),+ );++ // 6. Build summaries — preserve the original per-source ordering+ const installedBySource = new Map<string, string>();+ installResults.forEach((r, i) => {+ if (r.status === 'fulfilled') {+ installedBySource.set(r.value.sourceId, r.value.agentId);+ } else {+ console.warn('Failed to install marketplace agent:', prepared[i]?.sourceId, r.reason);}+ });++ const detailBySource = new Map<string, Prepared['detail']>();+ prepared.forEach((p) => detailBySource.set(p.sourceId, p.detail));- const summaryBase: InstallMarketplaceAgentSummary = {- avatar: marketAgent.avatar,- category: marketAgent.category,- description: marketAgent.description || marketAgent.summary,+ const summaries: InstallMarketplaceAgentSummary[] = sourceAgentIds.map((sourceId) => {+ if (skippedAgentIds.includes(sourceId)) {+ return { skipped: true, templateId: sourceId };+ }+ const detail = detailBySource.get(sourceId);+ return {+ avatar: detail?.avatar,+ category: detail?.category,+ description: detail?.description || detail?.summary,+ installedAgentId: installedBySource.get(sourceId),skipped: false,- templateId: sourceAgentId,- title: marketAgent.title,+ templateId: sourceId,+ title: detail?.title,};+ });- const forkResult = await marketApiService.forkAgent(sourceAgentId, {- identifier: generateMarketIdentifier(),- name: marketAgent.title,- status: 'published',- visibility: 'public',- });-- const result = await createAgent({- config: {- ...marketAgent.config,- avatar: marketAgent.avatar,- backgroundColor: marketAgent.backgroundColor,- description: marketAgent.description,- editorData: marketAgent.editorData,- marketIdentifier: forkResult.agent.identifier,- params: {- ...marketAgent.config.params,- forkedFromIdentifier: sourceAgentId,- },- tags: marketAgent.tags,- title: forkResult.agent.name,- },- });-- installedAgentIds.push(result.agentId);- summaries.push({ ...summaryBase, installedAgentId: result.agentId });-- discoverService.reportAgentEvent({- event: 'add',- identifier: forkResult.agent.identifier,- source: getSourcePath(),- });- }+ const installedAgentIds = Array.from(installedBySource.values());if (installedAgentIds.length > 0) {await refreshAgentList();diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsxindex 694514cc357..d7479c997a8 100644--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx@@ -79,13 +79,22 @@ const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {// Generate a unique identifier for the forked agentconst newIdentifier = generateMarketIdentifier();- // Step 2: Fork the agent via Market API- const forkResult = await marketApiService.forkAgent(identifier!, {- identifier: newIdentifier,- name: title,- status: 'published',- visibility: 'public',- });+ // Step 2: Fork the agent via Market API (single-item batch)+ const [forkOutcome] = await marketApiService.forkAgent([+ {+ identifier: newIdentifier,+ name: title,+ sourceIdentifier: identifier!,+ status: 'published',+ visibility: 'public',+ },+ ]);++ if (!forkOutcome.success) {+ throw new Error(forkOutcome.error?.message || 'Forking failed');+ }++ const forkResult = forkOutcome.data;// Step 3: Create agent config with forked dataif (!config) throw new Error('Agent config is missing');diff --git a/src/server/routers/lambda/market/agent.ts b/src/server/routers/lambda/market/agent.tsindex 44294b7c13e..3ba173fc86f 100644--- a/src/server/routers/lambda/market/agent.ts+++ b/src/server/routers/lambda/market/agent.ts@@ -8,6 +8,7 @@ import { marketSDK, marketUserInfo, serverDatabase } from '@/libs/trpc/lambda/miimport { type TrustedClientUserInfo } from '@/libs/trusted-client';import { generateTrustedClientToken } from '@/libs/trusted-client';import { normalizeLocale } from '@/locales/resources';+import type { AgentForkBatchResult, AgentForkResponse } from '@/types/discover';const MARKET_BASE_URL = process.env.MARKET_BASE_URL || 'https://market.lobehub.com';@@ -90,6 +91,103 @@ const fetchMarketUserInfo = async (}};+/**+ * Build market-API auth headers from a procedure context.+ * Mirrors the inline pattern used by other market.* procedures.+ */+const buildMarketAuthHeaders = (ctx: {+ marketOidcAccessToken?: string;+ marketUserInfo?: TrustedClientUserInfo;+}): Record<string, string> => {+ const headers: Record<string, string> = {+ 'Content-Type': 'application/json',+ };++ if (ctx.marketUserInfo) {+ const trustedClientToken = generateTrustedClientToken(ctx.marketUserInfo);+ if (trustedClientToken) {+ headers['x-lobe-trust-token'] = trustedClientToken;+ }+ }++ if (!headers['x-lobe-trust-token'] && ctx.marketOidcAccessToken) {+ headers['Authorization'] = `Bearer ${ctx.marketOidcAccessToken}`;+ }++ return headers;+};++interface ForkAgentItemInput {+ identifier: string;+ name?: string;+ sourceIdentifier: string;+ status?: 'published' | 'unpublished' | 'archived' | 'deprecated';+ versionNumber?: number;+ visibility?: 'public' | 'private' | 'internal';+}++const forkOneAgent = async (+ item: ForkAgentItemInput,+ headers: Record<string, string>,+): Promise<AgentForkBatchResult> => {+ try {+ const forkUrl = `${MARKET_BASE_URL}/api/v1/agents/${item.sourceIdentifier}/fork`;+ const response = await fetch(forkUrl, {+ body: JSON.stringify({+ identifier: item.identifier,+ name: item.name,+ status: item.status,+ versionNumber: item.versionNumber,+ visibility: item.visibility,+ }),+ headers,+ method: 'POST',+ });++ if (!response.ok) {+ const errorText = await response.text();+ log(+ 'Fork agent failed (source=%s): %s %s - %s',+ item.sourceIdentifier,+ response.status,+ response.statusText,+ errorText,+ );+ return {+ error: {+ code: `HTTP_${response.status}`,+ message: errorText || response.statusText || 'Failed to fork agent',+ },+ sourceIdentifier: item.sourceIdentifier,+ success: false,+ };+ }++ const data = (await response.json()) as AgentForkResponse;+ log('Fork agent success (source=%s)', item.sourceIdentifier);+ return { data, sourceIdentifier: item.sourceIdentifier, success: true };+ } catch (error) {+ log('Error forking agent (source=%s): %O', item.sourceIdentifier, error);+ return {+ error: {+ code: 'FORK_FAILED',+ message: error instanceof Error ? error.message : 'Failed to fork agent',+ },+ sourceIdentifier: item.sourceIdentifier,+ success: false,+ };+ }+};++const forkAgentItemSchema = z.object({+ identifier: z.string(),+ name: z.string().optional(),+ sourceIdentifier: z.string(),+ status: z.enum(['published', 'unpublished', 'archived', 'deprecated']).optional(),+ versionNumber: z.number().optional(),+ visibility: z.enum(['public', 'private', 'internal']).optional(),+});+// Authenticated procedure for agent management// Requires user to be logged in and has MarketSDK initialized// Also fetches user's market accessToken from database for OIDC authentication@@ -315,75 +413,20 @@ export const agentRouter = router({}),/**- * Fork an agent- * POST /market/agent/:identifier/fork+ * Fork one or more agents in a single batch.+ * POST /market/agent/fork (batch)+ *+ * Best-effort: single-item failures are returned in-line as+ * `{ success: false, error }` and do not abort the rest of the batch.*/forkAgent: agentProcedure- .input(- z.object({- identifier: z.string(),- name: z.string().optional(),- sourceIdentifier: z.string(),- status: z.enum(['published', 'unpublished', 'archived', 'deprecated']).optional(),- versionNumber: z.number().optional(),- visibility: z.enum(['public', 'private', 'internal']).optional(),- }),- )+ .input(z.object({ items: z.array(forkAgentItemSchema).min(1) })).mutation(async ({ input, ctx }) => {- log('forkAgent input: %O', input);+ log('forkAgent batch size: %d', input.items.length);- try {- // Call Market API directly to fork agent- const forkUrl = `${MARKET_BASE_URL}/api/v1/agents/${input.sourceIdentifier}/fork`;-- const headers: Record<string, string> = {- 'Content-Type': 'application/json',- };-- // Use trustedClientToken or accessToken for authentication- 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(forkUrl, {- body: JSON.stringify({- identifier: input.identifier,- name: input.name,- status: input.status,- versionNumber: input.versionNumber,- visibility: input.visibility,- }),- headers,- method: 'POST',- });-- if (!response.ok) {- const errorText = await response.text();- log('Fork agent failed: %s %s - %s', response.status, response.statusText, errorText);- throw new Error(`Failed to fork agent: ${response.statusText}`);- }+ const headers = buildMarketAuthHeaders(ctx);- const result = await response.json();- log('Fork agent success: %O', result);- return result;- } catch (error) {- log('Error forking agent: %O', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: error instanceof Error ? error.message : 'Failed to fork agent',- });- }+ return Promise.all(input.items.map((item) => forkOneAgent(item, headers)));}),/**diff --git a/src/services/marketApi.ts b/src/services/marketApi.tsindex 145be0c68ed..3141bbbbd7f 100644--- a/src/services/marketApi.ts+++ b/src/services/marketApi.ts@@ -7,8 +7,7 @@ import {import { lambdaClient } from '@/libs/trpc/client';import { discoverService } from '@/services/discover';import {- type AgentForkRequest,- type AgentForkResponse,+ type AgentForkBatchInput,type AgentForkSourceResponse,type AgentForksResponse,type AgentGroupForkRequest,@@ -119,17 +118,14 @@ export class MarketApiService {// ==================== Fork Agent API ====================/**- * Fork an agent- * @param sourceIdentifier - Source agent identifier- * @param forkData - Fork request parameters+ * Fork one or more agents in a single batch.+ *+ * Best-effort: each item is reported individually with `success` true or+ * false. A failed item does not abort the rest of the batch.*/- async forkAgent(- sourceIdentifier: string,- forkData: AgentForkRequest,- ): Promise<AgentForkResponse> {+ async forkAgent(items: AgentForkBatchInput[]) {return lambdaClient.market.agent.forkAgent.mutate({- sourceIdentifier,- ...forkData,+ items,});}