Skip to content

🀯 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.

πŸ› fix(edit-lock): allow same-user generic updates (#15969)

AmAzing-2c66867f659a
diff --git a/apps/server/src/services/editLock/__tests__/index.test.ts b/apps/server/src/services/editLock/__tests__/index.test.ts
index 142f2f74199..193bf377f13 100644
--- a/apps/server/src/services/editLock/__tests__/index.test.ts
+++ b/apps/server/src/services/editLock/__tests__/index.test.ts
@@ -171,6 +171,9 @@ describe('EditLockService', () => {
expect(
await new EditLockService('user-2', redis as any).getBlockingHolder('document', 'doc-1'),
).toBe('user-1');
+ expect(
+ await new EditLockService('user-1', redis as any).getBlockingHolder('document', 'doc-1'),
+ ).toBeNull();
expect(
await new EditLockService('user-1', redis as any).getBlockingHolder(
'document',
diff --git a/apps/server/src/services/editLock/index.ts b/apps/server/src/services/editLock/index.ts
index 7e35bcddb0b..2c07ac64834 100644
--- a/apps/server/src/services/editLock/index.ts
+++ b/apps/server/src/services/editLock/index.ts
@@ -203,9 +203,13 @@ export class EditLockService {
const holder = await this.getActiveLock(type, id);
if (!holder) return null;
// ownerId is broadcast on lock.changed; it can't authorize on its own.
- // Bind to userId first, then keep the stale-tab guard (same user, different
- // active ownerId still blocks so a ghost tab can't save over a newer one).
+ // Bind to userId first. When callers pass an ownerId, also keep the
+ // stale-tab guard (same user, different active ownerId blocks so a ghost tab
+ // can't save over a newer one). Callers without owner-scoped writes only
+ // need to reject other members; otherwise they would block their own generic
+ // metadata updates while holding the edit lock.
if (holder.userId !== this.userId) return holder.userId;
+ if (!ownerId) return null;
if (holder.ownerId && holder.ownerId !== ownerId) return holder.userId;
return null;
diff --git a/e2e/src/mocks/community/data.ts b/e2e/src/mocks/community/data.ts
index 0f895cc6071..771813fb019 100644
--- a/e2e/src/mocks/community/data.ts
+++ b/e2e/src/mocks/community/data.ts
@@ -1,212 +1,384 @@
/**
- * Mock data for Discover/Community module
+ * Mock data for Discover/Community module.
+ *
+ * Community E2E tests should not depend on the live marketplace service. These
+ * fixtures mirror the data shape returned by the app's tRPC market router.
*/
import type {
AssistantListResponse,
+ DiscoverAssistantItem,
+ DiscoverMcpItem,
+ DiscoverModelItem,
+ DiscoverProviderItem,
McpListResponse,
ModelListResponse,
ProviderListResponse,
} from './types';
+const CREATED_AT = '2026-01-01T00:00:00.000Z';
+const UPDATED_AT = '2026-01-10T00:00:00.000Z';
+
// ============================================
// Assistant Mock Data
// ============================================
-export const mockAssistantList: AssistantListResponse = {
- items: [
- {
- author: 'LobeHub',
- avatar: 'πŸ€–',
- backgroundColor: '#1890ff',
- category: 'general',
- createdAt: '2024-01-01T00:00:00.000Z',
- description: 'A versatile AI assistant for general tasks and conversations.',
- identifier: 'general-assistant',
- installCount: 1000,
- knowledgeCount: 5,
- pluginCount: 3,
- title: 'General Assistant',
- tokenUsage: 4096,
- userName: 'lobehub',
+export const mockAssistantItems: DiscoverAssistantItem[] = [
+ {
+ author: 'LobeHub',
+ avatar: 'πŸ€–',
+ backgroundColor: '#1890ff',
+ category: 'general',
+ config: {
+ openingMessage: 'Hello, I am your general assistant.',
+ openingQuestions: ['What can you do?'],
+ params: {},
+ plugins: [],
+ systemRole: 'You are a helpful general-purpose assistant for E2E tests.',
},
- {
- author: 'LobeHub',
- avatar: 'πŸ’»',
- backgroundColor: '#52c41a',
- category: 'programming',
- createdAt: '2024-01-02T00:00:00.000Z',
- description: 'Expert coding assistant for software development.',
- identifier: 'code-assistant',
- installCount: 800,
- knowledgeCount: 10,
- pluginCount: 5,
- title: 'Code Assistant',
- tokenUsage: 8192,
- userName: 'lobehub',
+ createdAt: CREATED_AT,
+ description: 'A versatile AI assistant for general tasks and conversations.',
+ identifier: 'general-assistant',
+ installCount: 1000,
+ knowledgeCount: 1,
+ pluginCount: 0,
+ summary: 'General-purpose assistant fixture.',
+ tags: ['general', 'fixture'],
+ title: 'General Assistant',
+ tokenUsage: 4096,
+ type: 'agent',
+ updatedAt: UPDATED_AT,
+ userName: 'lobehub',
+ },
+ {
+ author: 'LobeHub',
+ avatar: 'πŸ’»',
+ backgroundColor: '#52c41a',
+ category: 'programming',
+ config: {
+ openingMessage: 'Ready to help with development tasks.',
+ openingQuestions: ['Review this function'],
+ params: {},
+ plugins: [],
+ systemRole: 'You are an expert coding assistant for E2E tests.',
},
- {
- author: 'LobeHub',
- avatar: '✍️',
- backgroundColor: '#722ed1',
- category: 'copywriting',
- createdAt: '2024-01-03T00:00:00.000Z',
- description: 'Professional writing assistant for content creation.',
- identifier: 'writing-assistant',
- installCount: 600,
- knowledgeCount: 3,
- pluginCount: 2,
- title: 'Writing Assistant',
- tokenUsage: 4096,
- userName: 'lobehub',
+ createdAt: CREATED_AT,
+ description: 'Developer and coding assistant for software engineering workflows.',
+ identifier: 'code-assistant',
+ installCount: 800,
+ knowledgeCount: 2,
+ pluginCount: 1,
+ summary: 'Developer assistant fixture.',
+ tags: ['developer', 'programming'],
+ title: 'Code Assistant',
+ tokenUsage: 8192,
+ type: 'agent',
+ updatedAt: UPDATED_AT,
+ userName: 'lobehub',
+ },
+ {
+ author: 'LobeHub',
+ avatar: 'πŸŽ“',
+ backgroundColor: '#faad14',
+ category: 'academic',
+ config: {
+ openingMessage: 'Let us study together.',
+ openingQuestions: ['Explain this concept'],
+ params: {},
+ plugins: [],
+ systemRole: 'You are an academic tutor for E2E tests.',
},
- ],
- pagination: {
- page: 1,
- pageSize: 12,
- total: 3,
- totalPages: 1,
+ createdAt: CREATED_AT,
+ description: 'Academic research and study assistant for reliable category filtering.',
+ identifier: 'academic-tutor',
+ installCount: 640,
+ knowledgeCount: 3,
+ pluginCount: 0,
+ summary: 'Academic assistant fixture.',
+ tags: ['academic', 'education'],
+ title: 'Academic Tutor',
+ tokenUsage: 4096,
+ type: 'agent',
+ updatedAt: UPDATED_AT,
+ userName: 'lobehub',
},
+ {
+ author: 'LobeHub',
+ avatar: '✍️',
+ backgroundColor: '#722ed1',
+ category: 'copywriting',
+ config: {
+ openingMessage: 'Tell me what you want to write.',
+ openingQuestions: ['Draft a product intro'],
+ params: {},
+ plugins: [],
+ systemRole: 'You are a writing assistant for E2E tests.',
+ },
+ createdAt: CREATED_AT,
+ description: 'Professional writing assistant for content creation.',
+ identifier: 'writing-assistant',
+ installCount: 600,
+ knowledgeCount: 1,
+ pluginCount: 0,
+ summary: 'Writing assistant fixture.',
+ tags: ['copywriting'],
+ title: 'Writing Assistant',
+ tokenUsage: 4096,
+ type: 'agent',
+ updatedAt: UPDATED_AT,
+ userName: 'lobehub',
+ },
+];
+
+export const mockAssistantList: AssistantListResponse = {
+ currentPage: 1,
+ items: mockAssistantItems,
+ pageSize: 21,
+ totalCount: 42,
+ totalPages: 2,
};
export const mockAssistantCategories = [
- { id: 'general', name: 'General' },
- { id: 'programming', name: 'Programming' },
- { id: 'copywriting', name: 'Copywriting' },
- { id: 'education', name: 'Education' },
+ { category: 'general', count: 12 },
+ { category: 'programming', count: 10 },
+ { category: 'academic', count: 8 },
+ { category: 'copywriting', count: 6 },
];
// ============================================
// Model Mock Data
// ============================================
-export const mockModelList: ModelListResponse = {
- items: [
- {
- abilities: { functionCall: true, reasoning: true, vision: true },
- contextWindowTokens: 128_000,
- createdAt: '2024-01-01T00:00:00.000Z',
- description: 'Most capable model for complex tasks',
- displayName: 'GPT-4o',
- id: 'gpt-4o',
- providerId: 'openai',
- providerName: 'OpenAI',
- type: 'chat',
- },
- {
- abilities: { functionCall: true, reasoning: true, vision: false },
- contextWindowTokens: 200_000,
- createdAt: '2024-01-02T00:00:00.000Z',
- description: 'Advanced AI assistant by Anthropic',
- displayName: 'Claude 3.5 Sonnet',
- id: 'claude-3-5-sonnet-20241022',
- providerId: 'anthropic',
- providerName: 'Anthropic',
- type: 'chat',
- },
- {
- abilities: { functionCall: false, reasoning: false, vision: false },
- contextWindowTokens: 32_768,
- createdAt: '2024-01-03T00:00:00.000Z',
- description: 'Open source language model',
- displayName: 'Llama 3.1 70B',
- id: 'llama-3.1-70b',
- providerId: 'meta',
- providerName: 'Meta',
- type: 'chat',
- },
- ],
- pagination: {
- page: 1,
- pageSize: 12,
- total: 3,
- totalPages: 1,
+export const mockModelItems: DiscoverModelItem[] = [
+ {
+ abilities: { functionCall: true, reasoning: true, vision: true },
+ contextWindowTokens: 128_000,
+ description: 'Most capable fixture model for complex tasks.',
+ displayName: 'GPT-4o',
+ id: 'gpt-4o',
+ identifier: 'gpt-4o',
+ providerCount: 2,
+ providers: ['openai', 'lobehub'],
+ releasedAt: CREATED_AT,
+ type: 'chat',
+ },
+ {
+ abilities: { functionCall: true, reasoning: true, vision: false },
+ contextWindowTokens: 200_000,
+ description: 'Advanced AI assistant fixture by Anthropic.',
+ displayName: 'Claude 3.5 Sonnet',
+ id: 'claude-3-5-sonnet-20241022',
+ identifier: 'claude-3-5-sonnet-20241022',
+ providerCount: 1,
+ providers: ['anthropic'],
+ releasedAt: CREATED_AT,
+ type: 'chat',
+ },
+ {
+ abilities: { functionCall: false, reasoning: false, vision: false },
+ contextWindowTokens: 32_768,
+ description: 'Open source language model fixture.',
+ displayName: 'Llama 3.1 70B',
+ id: 'llama-3.1-70b',
+ identifier: 'llama-3.1-70b',
+ providerCount: 1,
+ providers: ['meta'],
+ releasedAt: CREATED_AT,
+ type: 'chat',
},
+];
+
+export const mockModelList: ModelListResponse = {
+ currentPage: 1,
+ items: mockModelItems,
+ pageSize: 21,
+ totalCount: mockModelItems.length,
+ totalPages: 1,
};
// ============================================
// Provider Mock Data
// ============================================
-export const mockProviderList: ProviderListResponse = {
- items: [
- {
- description: 'Leading AI research company',
- id: 'openai',
- logo: 'https://example.com/openai.png',
- modelCount: 10,
- name: 'OpenAI',
- },
- {
- description: 'AI safety focused research company',
- id: 'anthropic',
- logo: 'https://example.com/anthropic.png',
- modelCount: 5,
- name: 'Anthropic',
- },
- {
- description: 'Open source AI leader',
- id: 'meta',
- logo: 'https://example.com/meta.png',
- modelCount: 8,
- name: 'Meta',
- },
- ],
- pagination: {
- page: 1,
- pageSize: 12,
- total: 3,
- totalPages: 1,
+export const mockProviderItems: DiscoverProviderItem[] = [
+ {
+ description: 'Leading AI research company fixture.',
+ identifier: 'openai',
+ modelCount: 2,
+ models: ['gpt-4o', 'gpt-4o-mini'],
+ name: 'OpenAI',
+ url: 'https://openai.com',
},
+ {
+ description: 'AI safety focused research company fixture.',
+ identifier: 'anthropic',
+ modelCount: 1,
+ models: ['claude-3-5-sonnet-20241022'],
+ name: 'Anthropic',
+ url: 'https://anthropic.com',
+ },
+ {
+ description: 'Open source AI leader fixture.',
+ identifier: 'meta',
+ modelCount: 1,
+ models: ['llama-3.1-70b'],
+ name: 'Meta',
+ url: 'https://ai.meta.com',
+ },
+];
+
+export const mockProviderList: ProviderListResponse = {
+ currentPage: 1,
+ items: mockProviderItems,
+ pageSize: 21,
+ totalCount: mockProviderItems.length,
+ totalPages: 1,
};
// ============================================
// MCP Mock Data
// ============================================
+export const mockMcpItems: DiscoverMcpItem[] = [
+ {
+ author: 'LobeHub',
+ capabilities: { prompts: false, resources: false, tools: true },
+ category: 'business',
+ connectionType: 'stdio',
+ createdAt: CREATED_AT,
+ description: 'Business automation MCP tool fixture.',
+ github: { stars: 1200, url: 'https://github.com/lobehub/e2e-business-mcp' },
+ icon: 'πŸ“Š',
+ identifier: 'business-automation',
+ installCount: 500,
+ installationMethods: 'npm',
+ isClaimed: true,
+ isFeatured: true,
+ isOfficial: true,
+ isValidated: true,
+ manifestUrl: 'https://example.com/business-automation/manifest.json',
+ name: 'Business Automation',
+ toolsCount: 3,
+ updatedAt: UPDATED_AT,
+ },
+ {
+ author: 'LobeHub',
+ capabilities: { prompts: false, resources: true, tools: true },
+ category: 'developer',
+ connectionType: 'stdio',
+ createdAt: CREATED_AT,
+ description: 'Developer file-system MCP fixture.',
+ github: { stars: 900, url: 'https://github.com/lobehub/e2e-file-mcp' },
+ icon: 'πŸ“',
+ identifier: 'file-manager',
+ installCount: 300,
+ installationMethods: 'npm',
+ isClaimed: true,
+ isFeatured: false,
+ isOfficial: false,
+ isValidated: true,
+ manifestUrl: 'https://example.com/file-manager/manifest.json',
+ name: 'File Manager',
+ resourcesCount: 2,
+ toolsCount: 5,
+ updatedAt: UPDATED_AT,
+ },
+ {
+ author: 'LobeHub',
+ capabilities: { prompts: true, resources: false, tools: true },
+ category: 'productivity',
+ connectionType: 'http',
+ createdAt: CREATED_AT,
+ description: 'Productivity search MCP fixture.',
+ github: { stars: 600, url: 'https://github.com/lobehub/e2e-search-mcp' },
+ icon: 'πŸ”',
+ identifier: 'web-search',
+ installCount: 260,
+ installationMethods: 'docker',
+ isClaimed: false,
+ isFeatured: false,
+ isOfficial: false,
+ isValidated: true,
+ manifestUrl: 'https://example.com/web-search/manifest.json',
+ name: 'Web Search',
+ promptsCount: 1,
+ toolsCount: 2,
+ updatedAt: UPDATED_AT,
+ },
+];
+
export const mockMcpList: McpListResponse = {
- items: [
- {
- author: 'LobeHub',
- avatar: 'πŸ”',
- category: 'search',
- createdAt: '2024-01-01T00:00:00.000Z',
- description: 'Web search capabilities for AI assistants',
- identifier: 'web-search',
- installCount: 500,
- title: 'Web Search',
- },
+ categories: ['business', 'developer', 'productivity'],
+ currentPage: 1,
+ items: mockMcpItems,
+ pageSize: 21,
+ totalCount: mockMcpItems.length,
+ totalPages: 1,
+};
+
+export const mockMcpCategories = [
+ { category: 'business', count: 7 },
+ { category: 'developer', count: 5 },
+ { category: 'productivity', count: 3 },
+];
+
+// ============================================
+// Detail Mock Data
+// ============================================
+
+export const mockAssistantDetails = mockAssistantItems.map((item) => ({
+ ...item,
+ currentVersion: '1.0.0',
+ related: mockAssistantItems
+ .filter((related) => related.identifier !== item.identifier)
+ .slice(0, 3),
+ versions: [
{
- author: 'LobeHub',
- avatar: 'πŸ“',
- category: 'file',
- createdAt: '2024-01-02T00:00:00.000Z',
- description: 'File system operations and management',
- identifier: 'file-manager',
- installCount: 300,
- title: 'File Manager',
+ createdAt: item.createdAt,
+ isLatest: true,
+ isValidated: true,
+ status: 'published',
+ version: '1.0.0',
},
+ ],
+}));
+
+export const mockMcpDetails = mockMcpItems.map((item) => ({
+ ...item,
+ author: { name: item.author ?? 'LobeHub', url: 'https://lobehub.com' },
+ deploymentOptions: [
{
- author: 'LobeHub',
- avatar: 'πŸ—„οΈ',
- category: 'database',
- createdAt: '2024-01-03T00:00:00.000Z',
- description: 'Database query and management tools',
- identifier: 'db-tools',
- installCount: 200,
- title: 'Database Tools',
+ connection: { command: 'npx', type: item.connectionType ?? 'stdio' },
+ installationMethod: item.installationMethods ?? 'npm',
+ title: 'E2E recommended deployment',
},
],
- pagination: {
- page: 1,
- pageSize: 12,
- total: 3,
- totalPages: 1,
+ overview: {
+ readme: `# ${item.name}\n\n${item.description}`,
+ summary: item.description,
},
-};
+ related: mockMcpItems.filter((related) => related.identifier !== item.identifier).slice(0, 2),
+ tools: [{ description: 'Fixture tool for E2E tests', name: 'fixtureTool' }],
+ version: '1.0.0',
+ versions: [{ isLatest: true, version: '1.0.0' }],
+}));
-export const mockMcpCategories = [
- { id: 'search', name: 'Search' },
- { id: 'file', name: 'File' },
- { id: 'database', name: 'Database' },
- { id: 'utility', name: 'Utility' },
-];
+export const mockModelDetails = mockModelItems.map((item) => ({
+ ...item,
+ providers: mockProviderItems.map((provider) => ({
+ ...provider,
+ id: provider.identifier,
+ model: item,
+ })),
+ related: mockModelItems.filter((related) => related.identifier !== item.identifier).slice(0, 2),
+}));
+
+export const mockProviderDetails = mockProviderItems.map((item) => ({
+ ...item,
+ models: mockModelItems
+ .filter((model) => item.models.includes(model.identifier))
+ .map((model) => ({ ...model, maxOutput: 4096 })),
+ readme: `# ${item.name}\n\n${item.description}`,
+ related: mockProviderItems
+ .filter((related) => related.identifier !== item.identifier)
+ .slice(0, 2),
+}));
diff --git a/e2e/src/mocks/community/handlers.ts b/e2e/src/mocks/community/handlers.ts
index b78224d5f16..16fc69be91a 100644
--- a/e2e/src/mocks/community/handlers.ts
+++ b/e2e/src/mocks/community/handlers.ts
@@ -1,179 +1,346 @@
/**
- * Mock handlers for Discover/Community API endpoints
+ * Mock handlers for Discover/Community API endpoints.
*/
-import type { Route } from 'playwright';
+import type { Request, Route } from 'playwright';
+import superjson from 'superjson';
-import { type MockHandler, createTrpcResponse } from '../index';
+import type { MockHandler } from '../index';
import {
mockAssistantCategories,
+ mockAssistantDetails,
+ mockAssistantItems,
mockAssistantList,
mockMcpCategories,
+ mockMcpDetails,
+ mockMcpItems,
mockMcpList,
+ mockModelDetails,
+ mockModelItems,
mockModelList,
+ mockProviderDetails,
+ mockProviderItems,
mockProviderList,
} from './data';
-// ============================================
-// Helper to parse tRPC batch requests
-// ============================================
+interface IdentifierEntry {
+ identifier: string;
+ lastModified: string;
+}
+
+const SUCCESS_RESPONSE = { success: true };
+
+const createTrpcResult = <T>(data: T) => ({
+ result: {
+ data: superjson.serialize(data),
+ },
+});
+
+const createTrpcResponse = <T>(data: T): string => JSON.stringify(createTrpcResult(data));
+
+const createTrpcBatchResponse = <T>(data: T[]): string =>
+ JSON.stringify(data.map((item) => createTrpcResult(item)));
-function parseTrpcUrl(url: string): { input?: Record<string, unknown>; procedure: string } {
- const urlObj = new URL(url);
- const pathname = urlObj.pathname;
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const getStringInput = (input: unknown, key: string): string | undefined => {
+ if (!isRecord(input)) return undefined;
+ const value = input[key];
+ return typeof value === 'string' ? value : undefined;
+};
- // Extract procedure name from path like /trpc/lambda.market.getAssistantList
- const procedureMatch = pathname.match(/lambda\.market\.(\w+)/);
- const procedure = procedureMatch ? procedureMatch[1] : '';
+const getNumberInput = (input: unknown, key: string): number | undefined => {
+ if (!isRecord(input)) return undefined;
+ const value = input[key];
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
+ if (typeof value !== 'string') return undefined;
- // Parse input from query string
- let input: Record<string, unknown> | undefined;
- const inputParam = urlObj.searchParams.get('input');
- if (inputParam) {
+ const numberValue = Number(value);
+ return Number.isFinite(numberValue) ? numberValue : undefined;
+};
+
+const createIdentifiers = (
+ items: { identifier: string; updatedAt?: string }[],
+): IdentifierEntry[] =>
+ items.map((item) => ({ identifier: item.identifier, lastModified: item.updatedAt ?? '' }));
+
+const unwrapTrpcInput = (input: unknown): unknown => {
+ if (!isRecord(input)) return input;
+
+ if ('json' in input) return input.json;
+
+ return input;
+};
+
+const parseRequestInput = (request: Request, url: URL): unknown => {
+ const input = url.searchParams.get('input');
+
+ if (input) {
try {
- input = JSON.parse(inputParam);
+ return JSON.parse(input);
} catch {
- // Ignore parse errors
+ return undefined;
}
}
- return { input, procedure };
-}
+ try {
+ return request.postDataJSON();
+ } catch {
+ return undefined;
+ }
+};
-// ============================================
-// Mock Handlers
-// ============================================
+const getProcedureInputs = (request: Request, url: URL, count: number): unknown[] => {
+ const rawInput = parseRequestInput(request, url);
+ const isBatch = url.searchParams.get('batch') === '1' || count > 1;
-/**
- * Handler for assistant list endpoint
- */
-const assistantListHandler: MockHandler = {
- handler: async (route: Route) => {
- await route.fulfill({
- body: createTrpcResponse(mockAssistantList),
- contentType: 'application/json',
- status: 200,
- });
- },
- pattern: '**/trpc/lambda/market.getAssistantList**',
+ if (isBatch && isRecord(rawInput)) {
+ return Array.from({ length: count }, (_, index) => unwrapTrpcInput(rawInput[String(index)]));
+ }
+
+ return [unwrapTrpcInput(rawInput)];
};
-/**
- * Handler for assistant categories endpoint
- */
-const assistantCategoriesHandler: MockHandler = {
- handler: async (route: Route) => {
- await route.fulfill({
- body: createTrpcResponse(mockAssistantCategories),
- contentType: 'application/json',
- status: 200,
- });
- },
- pattern: '**/trpc/lambda/market.getAssistantCategories**',
+const getProcedures = (url: URL): string[] => {
+ const marker = '/trpc/lambda/';
+ const pathname = decodeURIComponent(url.pathname);
+ const markerIndex = pathname.indexOf(marker);
+
+ if (markerIndex === -1) return [];
+
+ const procedureSegment = pathname.slice(markerIndex + marker.length);
+ return procedureSegment.split(',').filter(Boolean);
};
-/**
- * Handler for model list endpoint
- */
-const modelListHandler: MockHandler = {
- handler: async (route: Route) => {
- await route.fulfill({
- body: createTrpcResponse(mockModelList),
- contentType: 'application/json',
- status: 200,
- });
- },
- pattern: '**/trpc/lambda/market.getModelList**',
+const isMarketProcedure = (procedure: string): boolean => procedure.startsWith('market.');
+
+const matchesText = (value: string | undefined, query: string) =>
+ value?.toLowerCase().includes(query.toLowerCase()) ?? false;
+
+const paginate = <T>(items: T[], input: unknown, fallbackTotal = items.length) => {
+ const page = getNumberInput(input, 'page') ?? 1;
+ const pageSize = getNumberInput(input, 'pageSize') ?? 21;
+
+ return {
+ currentPage: page,
+ items,
+ pageSize,
+ totalCount: Math.max(fallbackTotal, items.length),
+ totalPages: Math.max(1, Math.ceil(Math.max(fallbackTotal, items.length) / pageSize)),
+ };
};
-/**
- * Handler for provider list endpoint
- */
-const providerListHandler: MockHandler = {
- handler: async (route: Route) => {
- await route.fulfill({
- body: createTrpcResponse(mockProviderList),
- contentType: 'application/json',
- status: 200,
- });
- },
- pattern: '**/trpc/lambda/market.getProviderList**',
+const getAssistantList = (input: unknown) => {
+ const category = getStringInput(input, 'category');
+ const query = getStringInput(input, 'q');
+
+ let items = mockAssistantItems;
+
+ if (category && !['all', 'discover'].includes(category)) {
+ const filtered = items.filter((item) => item.category === category);
+ if (filtered.length > 0) items = filtered;
+ }
+
+ if (query) {
+ const filtered = items.filter(
+ (item) =>
+ matchesText(item.title, query) ||
+ matchesText(item.description, query) ||
+ matchesText(item.identifier, query) ||
+ matchesText(item.tags?.join(' '), query),
+ );
+ if (filtered.length > 0) items = filtered;
+ }
+
+ return { ...mockAssistantList, ...paginate(items, input, 42) };
};
-/**
- * Handler for MCP list endpoint
- */
-const mcpListHandler: MockHandler = {
- handler: async (route: Route) => {
- await route.fulfill({
- body: createTrpcResponse(mockMcpList),
- contentType: 'application/json',
- status: 200,
- });
- },
- pattern: '**/trpc/lambda/market.getMcpList**',
+const getMcpList = (input: unknown) => {
+ const category = getStringInput(input, 'category');
+ const query = getStringInput(input, 'q');
+
+ let items = mockMcpItems;
+
+ if (category && !['all', 'discover'].includes(category)) {
+ const filtered = items.filter((item) => item.category === category);
+ if (filtered.length > 0) items = filtered;
+ }
+
+ if (query) {
+ const filtered = items.filter(
+ (item) =>
+ matchesText(item.name, query) ||
+ matchesText(item.description, query) ||
+ matchesText(item.identifier, query),
+ );
+ if (filtered.length > 0) items = filtered;
+ }
+
+ return { ...mockMcpList, ...paginate(items, input), categories: mockMcpList.categories };
};
-/**
- * Handler for MCP categories endpoint
- */
-const mcpCategoriesHandler: MockHandler = {
- handler: async (route: Route) => {
- await route.fulfill({
- body: createTrpcResponse(mockMcpCategories),
- contentType: 'application/json',
- status: 200,
- });
- },
- pattern: '**/trpc/lambda/market.getMcpCategories**',
+const getModelList = (input: unknown) => {
+ const query = getStringInput(input, 'q');
+
+ let items = mockModelItems;
+ if (query) {
+ const filtered = items.filter(
+ (item) =>
+ matchesText(item.displayName, query) ||
+ matchesText(item.description, query) ||
+ matchesText(item.identifier, query),
+ );
+ if (filtered.length > 0) items = filtered;
+ }
+
+ return { ...mockModelList, ...paginate(items, input) };
};
-/**
- * Debug handler to log all trpc requests
- */
-const trpcDebugHandler: MockHandler = {
- handler: async (route: Route) => {
- const url = route.request().url();
- console.log(` πŸ” TRPC Request: ${url}`);
- await route.continue();
- },
- pattern: '**/trpc/**',
+const getProviderList = (input: unknown) => {
+ const query = getStringInput(input, 'q');
+
+ let items = mockProviderItems;
+ if (query) {
+ const filtered = items.filter(
+ (item) =>
+ matchesText(item.name, query) ||
+ matchesText(item.description, query) ||
+ matchesText(item.identifier, query),
+ );
+ if (filtered.length > 0) items = filtered;
+ }
+
+ return { ...mockProviderList, ...paginate(items, input) };
};
-/**
- * Fallback handler for any unhandled market endpoints
- * Returns empty data to prevent hanging requests
- */
-const marketFallbackHandler: MockHandler = {
+const findByIdentifier = <T extends { identifier: string }>(items: T[], input: unknown): T => {
+ const identifier = getStringInput(input, 'identifier');
+ return items.find((item) => item.identifier === identifier) ?? items[0];
+};
+
+const getMockResponse = (procedure: string, input: unknown): unknown => {
+ switch (procedure) {
+ case 'market.getAssistantCategories': {
+ return mockAssistantCategories;
+ }
+
+ case 'market.getAssistantDetail': {
+ return findByIdentifier(mockAssistantDetails, input);
+ }
+
+ case 'market.getAssistantIdentifiers': {
+ return createIdentifiers(mockAssistantItems);
+ }
+
+ case 'market.getAssistantList': {
+ return getAssistantList(input);
+ }
+
+ case 'market.getMcpCategories': {
+ return mockMcpCategories;
+ }
+
+ case 'market.getMcpDetail': {
+ return findByIdentifier(mockMcpDetails, input);
+ }
+
+ case 'market.getMcpList': {
+ return getMcpList(input);
+ }
+
+ case 'market.getModelCategories': {
+ return [];
+ }
+
+ case 'market.getModelDetail': {
+ return findByIdentifier(mockModelDetails, input);
+ }
+
+ case 'market.getModelIdentifiers': {
+ return createIdentifiers(mockModelItems);
+ }
+
+ case 'market.getModelList': {
+ return getModelList(input);
+ }
+
+ case 'market.getProviderDetail': {
+ return findByIdentifier(mockProviderDetails, input);
+ }
+
+ case 'market.getProviderIdentifiers': {
+ return createIdentifiers(mockProviderItems);
+ }
+
+ case 'market.getProviderList': {
+ return getProviderList(input);
+ }
+
+ case 'market.registerClientInMarketplace': {
+ return { clientId: 'e2e-market-client', clientSecret: 'e2e-market-secret' };
+ }
+
+ case 'market.registerM2MToken': {
+ return SUCCESS_RESPONSE;
+ }
+
+ case 'market.reportAgentEvent':
+ case 'market.reportAgentInstall':
+ case 'market.reportCall':
+ case 'market.reportGroupAgentEvent':
+ case 'market.reportGroupAgentInstall':
+ case 'market.reportMcpEvent':
+ case 'market.reportMcpInstallResult': {
+ return SUCCESS_RESPONSE;
+ }
+
+ case 'plugin.getPlugins': {
+ return [];
+ }
+
+ default: {
+ console.log(` ⚠️ Unhandled mocked lambda endpoint: ${procedure}`);
+ return SUCCESS_RESPONSE;
+ }
+ }
+};
+
+const marketHandler: MockHandler = {
handler: async (route: Route) => {
- const url = route.request().url();
- const { procedure } = parseTrpcUrl(url);
+ const request = route.request();
+ const url = new URL(request.url());
+ const procedures = getProcedures(url);
+
+ if (!procedures.some(isMarketProcedure)) {
+ await route.continue();
+ return;
+ }
+
+ const inputs = getProcedureInputs(request, url, procedures.length);
- console.log(` ⚠️ Unhandled market endpoint: ${procedure}`);
+ // Keep tRPC batch positions intact. Community pages can batch mocked
+ // market.* calls with normal app calls, such as plugin.getPlugins on the MCP
+ // detail page; returning only market responses would make the batch client
+ // read the wrong result for subsequent procedures.
+ const responses = procedures.map((procedure, index) =>
+ getMockResponse(procedure, inputs[index]),
+ );
+ const isBatch = url.searchParams.get('batch') === '1' || procedures.length > 1;
- // Return empty response to prevent timeout
await route.fulfill({
- body: createTrpcResponse({ items: [], pagination: { page: 1, pageSize: 12, total: 0 } }),
+ body: isBatch ? createTrpcBatchResponse(responses) : createTrpcResponse(responses[0]),
contentType: 'application/json',
+ headers: {
+ 'Set-Cookie': 'mp_token_status=active; Path=/; SameSite=Lax',
+ },
status: 200,
});
},
- pattern: '**/trpc/lambda/market.**',
+ pattern: '**/trpc/lambda/**',
};
// ============================================
// Export all handlers
// ============================================
-export const discoverHandlers: MockHandler[] = [
- // Debug handler first to log all requests
- trpcDebugHandler,
- // Specific handlers (order matters - more specific first)
- assistantListHandler,
- assistantCategoriesHandler,
- modelListHandler,
- providerListHandler,
- mcpListHandler,
- mcpCategoriesHandler,
- // Fallback handler (should be last)
- marketFallbackHandler,
-];
+export const discoverHandlers: MockHandler[] = [marketHandler];
diff --git a/e2e/src/mocks/community/types.ts b/e2e/src/mocks/community/types.ts
index 267a046cc1c..4d48a15351d 100644
--- a/e2e/src/mocks/community/types.ts
+++ b/e2e/src/mocks/community/types.ts
@@ -1,12 +1,15 @@
/**
- * Type definitions for Discover mock data
- * These mirror the actual types from the application
+ * Type definitions for Discover mock data.
+ *
+ * Keep these small and E2E-focused: they only include fields the Community UI
+ * reads while rendering list and detail pages.
*/
-export interface PaginationInfo {
- page: number;
+export interface ListResponse<T> {
+ currentPage: number;
+ items: T[];
pageSize: number;
- total: number;
+ totalCount: number;
totalPages: number;
}
@@ -19,21 +22,25 @@ export interface DiscoverAssistantItem {
avatar: string;
backgroundColor?: string;
category: string;
+ config?: Record<string, unknown>;
createdAt: string;
description: string;
+ examples?: Record<string, unknown>[];
identifier: string;
installCount?: number;
knowledgeCount?: number;
pluginCount?: number;
+ related?: DiscoverAssistantItem[];
+ summary?: string;
+ tags?: string[];
title: string;
tokenUsage?: number;
+ type?: 'agent' | 'agent-group';
+ updatedAt?: string;
userName?: string;
}
-export interface AssistantListResponse {
- items: DiscoverAssistantItem[];
- pagination: PaginationInfo;
-}
+export type AssistantListResponse = ListResponse<DiscoverAssistantItem>;
// ============================================
// Model Types
@@ -46,19 +53,17 @@ export interface DiscoverModelItem {
vision?: boolean;
};
contextWindowTokens: number;
- createdAt: string;
description: string;
displayName: string;
id: string;
- providerId: string;
- providerName: string;
+ identifier: string;
+ providerCount: number;
+ providers: string[];
+ releasedAt?: string;
type: string;
}
-export interface ModelListResponse {
- items: DiscoverModelItem[];
- pagination: PaginationInfo;
-}
+export type ModelListResponse = ListResponse<DiscoverModelItem>;
// ============================================
// Provider Types
@@ -66,33 +71,50 @@ export interface ModelListResponse {
export interface DiscoverProviderItem {
description: string;
- id: string;
- logo?: string;
+ identifier: string;
modelCount: number;
+ models: string[];
name: string;
+ url?: string;
}
-export interface ProviderListResponse {
- items: DiscoverProviderItem[];
- pagination: PaginationInfo;
-}
+export type ProviderListResponse = ListResponse<DiscoverProviderItem>;
// ============================================
// MCP Types
// ============================================
export interface DiscoverMcpItem {
- author: string;
- avatar: string;
+ author?: string;
+ capabilities: {
+ prompts: boolean;
+ resources: boolean;
+ tools: boolean;
+ };
category: string;
+ connectionType?: 'http' | 'stdio';
createdAt: string;
description: string;
+ github?: {
+ stars?: number;
+ url: string;
+ };
+ icon?: string;
identifier: string;
+ installationMethods?: string;
installCount?: number;
- title: string;
+ isClaimed?: boolean;
+ isFeatured?: boolean;
+ isOfficial?: boolean;
+ isValidated?: boolean;
+ manifestUrl: string;
+ name: string;
+ promptsCount?: number;
+ resourcesCount?: number;
+ toolsCount?: number;
+ updatedAt: string;
}
-export interface McpListResponse {
- items: DiscoverMcpItem[];
- pagination: PaginationInfo;
+export interface McpListResponse extends ListResponse<DiscoverMcpItem> {
+ categories: string[];
}
diff --git a/e2e/src/mocks/index.ts b/e2e/src/mocks/index.ts
index f384f920c51..26817d8b650 100644
--- a/e2e/src/mocks/index.ts
+++ b/e2e/src/mocks/index.ts
@@ -5,6 +5,7 @@
* It uses Playwright's route interception to mock tRPC and REST API calls.
*/
import type { Page, Route } from 'playwright';
+import superjson from 'superjson';
import { discoverMocks } from './community';
@@ -124,12 +125,23 @@ export class MockManager {
/**
* Create a JSON response for tRPC endpoints
*/
-export function createTrpcResponse<T>(data: T): string {
- return JSON.stringify({
+export function createTrpcResult<T>(data: T) {
+ return {
result: {
- data,
+ data: superjson.serialize(data),
},
- });
+ };
+}
+
+export function createTrpcResponse<T>(data: T): string {
+ return JSON.stringify(createTrpcResult(data));
+}
+
+/**
+ * Create a JSON response for batched tRPC endpoints
+ */
+export function createTrpcBatchResponse<T>(data: T[]): string {
+ return JSON.stringify(data.map((item) => createTrpcResult(item)));
}
/**
diff --git a/e2e/src/steps/hooks.ts b/e2e/src/steps/hooks.ts
index 4262c5df646..ad99f048ea8 100644
--- a/e2e/src/steps/hooks.ts
+++ b/e2e/src/steps/hooks.ts
@@ -1,6 +1,7 @@
import { After, AfterAll, Before, BeforeAll, setDefaultTimeout, Status } from '@cucumber/cucumber';
import { chromium, type Cookie } from 'playwright';
+import { mockManager } from '../mocks';
import { seedTestUser, TEST_USER } from '../support/seedTestUser';
import { startWebServer, stopWebServer } from '../support/webServer';
import type { CustomWorld } from '../support/world';
@@ -106,8 +107,16 @@ Before(async function (this: CustomWorld, { pickle }) {
);
console.log(`\nπŸ“ Running: ${pickle.name}${testId ? ` (${testId.name.replace('@', '')})` : ''}`);
- // Setup API mocks before any page navigation
- // await mockManager.setup(this.page);
+ // Setup Community API mocks before any page navigation. These PR E2E scenarios
+ // are the user-experience baseline for Community UI flows (list/search/filter/
+ // detail navigation), not a live marketplace availability check. The live
+ // marketplace rate-limits anonymous CI traffic, so Community scenarios use
+ // deterministic fixtures while the rest of the E2E suite keeps real app APIs.
+ // If we need to validate the real marketplace contract, cover that in a
+ // separate integration/nightly suite with dedicated credentials and SLA.
+ if (pickle.tags.some((tag) => tag.name === '@community')) {
+ await mockManager.setup(this.page);
+ }
// Set cached session cookies to skip login
if (sessionCookies.length > 0) {