🤯 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
🔨 chore: enhance EdgeConfig with per-user feature flags support (#9541)
René Wang794748373b1f
diff --git a/src/config/featureFlags/index.ts b/src/config/featureFlags/index.tsindex 6c8fca90253..349a7f4d8ea 100644--- a/src/config/featureFlags/index.ts+++ b/src/config/featureFlags/index.ts@@ -22,10 +22,10 @@ export const getServerFeatureFlagsValue = () => {return merge(DEFAULT_FEATURE_FLAGS, flags);};-export const serverFeatureFlags = () => {+export const serverFeatureFlags = (userId?: string) => {const serverConfig = getServerFeatureFlagsValue();- return mapFeatureFlagsEnvToState(serverConfig);+ return mapFeatureFlagsEnvToState(serverConfig, userId);};export * from './schema';diff --git a/src/config/featureFlags/schema.test.ts b/src/config/featureFlags/schema.test.tsindex ffe537b7944..4843c85dad0 100644--- a/src/config/featureFlags/schema.test.ts+++ b/src/config/featureFlags/schema.test.ts@@ -1,11 +1,10 @@import { describe, expect, it } from 'vitest';-import { FeatureFlagsSchema, mapFeatureFlagsEnvToState } from './schema';+import { FeatureFlagsSchema, evaluateFeatureFlag, mapFeatureFlagsEnvToState } from './schema';describe('FeatureFlagsSchema', () => {- it('should validate correct feature flags', () => {+ it('should validate correct feature flags with boolean values', () => {const result = FeatureFlagsSchema.safeParse({- webrtc_sync: true,language_model_settings: false,openai_api_key: true,openai_proxy_url: false,@@ -18,20 +17,89 @@ describe('FeatureFlagsSchema', () => {expect(result.success).toBe(true);});- it('should reject invalid feature flags', () => {+ it('should validate correct feature flags with user ID arrays', () => {const result = FeatureFlagsSchema.safeParse({- edit_agent: 'yes', // Invalid type, should be boolean+ edit_agent: ['user-123', 'user-456'],+ create_session: ['user-789'],+ dalle: true,+ ai_image: false,+ });++ expect(result.success).toBe(true);+ });++ it('should validate mixed boolean and array values', () => {+ const result = FeatureFlagsSchema.safeParse({+ edit_agent: ['user-123'],+ create_session: true,+ dalle: false,+ knowledge_base: ['user-456', 'user-789'],+ });++ expect(result.success).toBe(true);+ });++ it('should reject invalid feature flags with wrong types', () => {+ const result = FeatureFlagsSchema.safeParse({+ edit_agent: 'yes', // Invalid type, should be boolean or array+ });++ expect(result.success).toBe(false);+ });++ it('should reject invalid feature flags with non-string array elements', () => {+ const result = FeatureFlagsSchema.safeParse({+ edit_agent: [123, 456], // Invalid, array should contain strings});expect(result.success).toBe(false);});});+describe('evaluateFeatureFlag', () => {+ it('should return true for boolean true value', () => {+ expect(evaluateFeatureFlag(true)).toBe(true);+ expect(evaluateFeatureFlag(true, 'user-123')).toBe(true);+ });++ it('should return false for boolean false value', () => {+ expect(evaluateFeatureFlag(false)).toBe(false);+ expect(evaluateFeatureFlag(false, 'user-123')).toBe(false);+ });++ it('should return undefined for undefined value', () => {+ expect(evaluateFeatureFlag(undefined)).toBe(undefined);+ expect(evaluateFeatureFlag(undefined, 'user-123')).toBe(undefined);+ });++ it('should return true if user ID is in the allowlist', () => {+ const allowlist = ['user-123', 'user-456'];+ expect(evaluateFeatureFlag(allowlist, 'user-123')).toBe(true);+ expect(evaluateFeatureFlag(allowlist, 'user-456')).toBe(true);+ });++ it('should return false if user ID is not in the allowlist', () => {+ const allowlist = ['user-123', 'user-456'];+ expect(evaluateFeatureFlag(allowlist, 'user-789')).toBe(false);+ });++ it('should return false if no user ID provided with array value', () => {+ const allowlist = ['user-123', 'user-456'];+ expect(evaluateFeatureFlag(allowlist)).toBe(false);+ expect(evaluateFeatureFlag(allowlist, undefined)).toBe(false);+ });++ it('should handle empty array', () => {+ expect(evaluateFeatureFlag([], 'user-123')).toBe(false);+ expect(evaluateFeatureFlag([])).toBe(false);+ });+});+describe('mapFeatureFlagsEnvToState', () => {- it('should correctly map feature flags to state', () => {+ it('should correctly map boolean feature flags to state', () => {const config = {- webrtc_sync: true,language_model_settings: false,+ provider_settings: true,openai_api_key: true,openai_proxy_url: false,create_session: true,@@ -40,22 +108,110 @@ describe('mapFeatureFlagsEnvToState', () => {ai_image: true,check_updates: true,welcome_suggest: true,+ plugins: true,+ knowledge_base: false,+ rag_eval: true,+ clerk_sign_up: false,+ market: true,+ speech_to_text: true,+ changelog: false,+ pin_list: true,+ api_key_manage: false,+ cloud_promotion: true,+ commercial_hide_github: false,+ commercial_hide_docs: true,};- const expectedState = {+ const mappedState = mapFeatureFlagsEnvToState(config);++ expect(mappedState).toMatchObject({isAgentEditable: false,showCreateSession: true,showLLM: false,+ showProvider: true,showOpenAIApiKey: true,showOpenAIProxyUrl: false,showDalle: true,showAiImage: true,enableCheckUpdates: true,showWelcomeSuggest: true,+ enablePlugins: true,+ enableKnowledgeBase: false,+ enableRAGEval: true,+ enableClerkSignUp: false,+ showMarket: true,+ enableSTT: true,+ showChangelog: false,+ showPinList: true,+ showApiKeyManage: false,+ showCloudPromotion: true,+ hideGitHub: false,+ hideDocs: true,+ });+ });++ it('should correctly evaluate user-specific flags with allowlist', () => {+ const userId = 'user-123';+ const config = {+ edit_agent: ['user-123', 'user-456'],+ create_session: ['user-789'],+ dalle: true,+ knowledge_base: ['user-123'],+ };++ const mappedState = mapFeatureFlagsEnvToState(config, userId);++ expect(mappedState.isAgentEditable).toBe(true); // user-123 is in allowlist+ expect(mappedState.showCreateSession).toBe(false); // user-123 is not in allowlist+ expect(mappedState.showDalle).toBe(true); // boolean true+ expect(mappedState.enableKnowledgeBase).toBe(true); // user-123 is in allowlist+ });++ it('should return false for array flags when user ID is not in allowlist', () => {+ const userId = 'user-999';+ const config = {+ edit_agent: ['user-123', 'user-456'],+ create_session: ['user-789'],+ dalle: true,+ };++ const mappedState = mapFeatureFlagsEnvToState(config, userId);++ expect(mappedState.isAgentEditable).toBe(false);+ expect(mappedState.showCreateSession).toBe(false);+ expect(mappedState.showDalle).toBe(true);+ });++ it('should return false for array flags when no user ID provided', () => {+ const config = {+ edit_agent: ['user-123', 'user-456'],+ create_session: true,};const mappedState = mapFeatureFlagsEnvToState(config);- expect(mappedState).toEqual(expectedState);+ expect(mappedState.isAgentEditable).toBe(false);+ expect(mappedState.showCreateSession).toBe(true);+ });++ it('should handle mixed boolean and array values correctly', () => {+ const userId = 'user-123';+ const config = {+ edit_agent: ['user-123'],+ create_session: true,+ dalle: false,+ ai_image: ['user-456'],+ knowledge_base: ['user-123', 'user-789'],+ rag_eval: true,+ };++ const mappedState = mapFeatureFlagsEnvToState(config, userId);++ expect(mappedState.isAgentEditable).toBe(true);+ expect(mappedState.showCreateSession).toBe(true);+ expect(mappedState.showDalle).toBe(false);+ expect(mappedState.showAiImage).toBe(false);+ expect(mappedState.enableKnowledgeBase).toBe(true);+ expect(mappedState.enableRAGEval).toBe(true);});});diff --git a/src/config/featureFlags/schema.ts b/src/config/featureFlags/schema.tsindex 24efb32e75a..38d9e5bd055 100644--- a/src/config/featureFlags/schema.ts+++ b/src/config/featureFlags/schema.ts@@ -1,51 +1,71 @@/* eslint-disable sort-keys-fix/sort-keys-fix */import { z } from 'zod';+// Define a union type for feature flag values: either boolean or array of user IDs+const FeatureFlagValue = z.union([z.boolean(), z.array(z.string())]);+export const FeatureFlagsSchema = z.object({- check_updates: z.boolean().optional(),- pin_list: z.boolean().optional(),+ check_updates: FeatureFlagValue.optional(),+ pin_list: FeatureFlagValue.optional(),// settings- language_model_settings: z.boolean().optional(),- provider_settings: z.boolean().optional(),+ language_model_settings: FeatureFlagValue.optional(),+ provider_settings: FeatureFlagValue.optional(),- openai_api_key: z.boolean().optional(),- openai_proxy_url: z.boolean().optional(),+ openai_api_key: FeatureFlagValue.optional(),+ openai_proxy_url: FeatureFlagValue.optional(),// profile- api_key_manage: z.boolean().optional(),+ api_key_manage: FeatureFlagValue.optional(),- create_session: z.boolean().optional(),- edit_agent: z.boolean().optional(),+ create_session: FeatureFlagValue.optional(),+ edit_agent: FeatureFlagValue.optional(),- plugins: z.boolean().optional(),- dalle: z.boolean().optional(),- ai_image: z.boolean().optional(),- speech_to_text: z.boolean().optional(),- token_counter: z.boolean().optional(),+ plugins: FeatureFlagValue.optional(),+ dalle: FeatureFlagValue.optional(),+ ai_image: FeatureFlagValue.optional(),+ speech_to_text: FeatureFlagValue.optional(),+ token_counter: FeatureFlagValue.optional(),- welcome_suggest: z.boolean().optional(),- changelog: z.boolean().optional(),+ welcome_suggest: FeatureFlagValue.optional(),+ changelog: FeatureFlagValue.optional(),- clerk_sign_up: z.boolean().optional(),+ clerk_sign_up: FeatureFlagValue.optional(),- market: z.boolean().optional(),- knowledge_base: z.boolean().optional(),+ market: FeatureFlagValue.optional(),+ knowledge_base: FeatureFlagValue.optional(),- rag_eval: z.boolean().optional(),+ rag_eval: FeatureFlagValue.optional(),// internal flag- cloud_promotion: z.boolean().optional(),+ cloud_promotion: FeatureFlagValue.optional(),// the flags below can only be used with commercial license// if you want to use it in the commercial usage// please contact us for more information: [email protected]- commercial_hide_github: z.boolean().optional(),- commercial_hide_docs: z.boolean().optional(),+ commercial_hide_github: FeatureFlagValue.optional(),+ commercial_hide_docs: FeatureFlagValue.optional(),});export type IFeatureFlags = z.infer<typeof FeatureFlagsSchema>;+/**+ * Evaluate a feature flag value against a user ID+ * @param flagValue - The feature flag value (boolean or array of user IDs)+ * @param userId - The current user ID+ * @returns boolean indicating if the feature is enabled for the user+ */+export const evaluateFeatureFlag = (+ flagValue: boolean | string[] | undefined,+ userId?: string,+): boolean | undefined => {+ if (typeof flagValue === 'boolean') return flagValue;++ if (Array.isArray(flagValue)) {+ return userId ? flagValue.includes(userId) : false;+ }+};+export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {pin_list: false,@@ -86,39 +106,41 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {commercial_hide_docs: false,};-export const mapFeatureFlagsEnvToState = (config: IFeatureFlags) => {+export const mapFeatureFlagsEnvToState = (config: IFeatureFlags, userId?: string) => {return {- isAgentEditable: config.edit_agent,+ isAgentEditable: evaluateFeatureFlag(config.edit_agent, userId),- showCreateSession: config.create_session,- showLLM: config.language_model_settings,- showProvider: config.provider_settings,- showPinList: config.pin_list,+ showCreateSession: evaluateFeatureFlag(config.create_session, userId),+ showLLM: evaluateFeatureFlag(config.language_model_settings, userId),+ showProvider: evaluateFeatureFlag(config.provider_settings, userId),+ showPinList: evaluateFeatureFlag(config.pin_list, userId),- showOpenAIApiKey: config.openai_api_key,- showOpenAIProxyUrl: config.openai_proxy_url,+ showOpenAIApiKey: evaluateFeatureFlag(config.openai_api_key, userId),+ showOpenAIProxyUrl: evaluateFeatureFlag(config.openai_proxy_url, userId),- showApiKeyManage: config.api_key_manage,+ showApiKeyManage: evaluateFeatureFlag(config.api_key_manage, userId),- enablePlugins: config.plugins,- showDalle: config.dalle,- showAiImage: config.ai_image,- showChangelog: config.changelog,+ enablePlugins: evaluateFeatureFlag(config.plugins, userId),+ showDalle: evaluateFeatureFlag(config.dalle, userId),+ showAiImage: evaluateFeatureFlag(config.ai_image, userId),+ showChangelog: evaluateFeatureFlag(config.changelog, userId),- enableCheckUpdates: config.check_updates,- showWelcomeSuggest: config.welcome_suggest,+ enableCheckUpdates: evaluateFeatureFlag(config.check_updates, userId),+ showWelcomeSuggest: evaluateFeatureFlag(config.welcome_suggest, userId),- enableClerkSignUp: config.clerk_sign_up,+ enableClerkSignUp: evaluateFeatureFlag(config.clerk_sign_up, userId),- enableKnowledgeBase: config.knowledge_base,- enableRAGEval: config.rag_eval,+ enableKnowledgeBase: evaluateFeatureFlag(config.knowledge_base, userId),+ enableRAGEval: evaluateFeatureFlag(config.rag_eval, userId),- showCloudPromotion: config.cloud_promotion,+ showCloudPromotion: evaluateFeatureFlag(config.cloud_promotion, userId),- showMarket: config.market,- enableSTT: config.speech_to_text,+ showMarket: evaluateFeatureFlag(config.market, userId),+ enableSTT: evaluateFeatureFlag(config.speech_to_text, userId),- hideGitHub: config.commercial_hide_github,- hideDocs: config.commercial_hide_docs,+ hideGitHub: evaluateFeatureFlag(config.commercial_hide_github, userId),+ hideDocs: evaluateFeatureFlag(config.commercial_hide_docs, userId),};};++export type IFeatureFlagsState = ReturnType<typeof mapFeatureFlagsEnvToState>;diff --git a/src/server/featureFlags/index.ts b/src/server/featureFlags/index.tsnew file mode 100644index 00000000000..70818983fc9--- /dev/null+++ b/src/server/featureFlags/index.ts@@ -0,0 +1,56 @@+import createDebug from 'debug';++import {+ DEFAULT_FEATURE_FLAGS,+ getServerFeatureFlagsValue,+ mapFeatureFlagsEnvToState,+} from '@/config/featureFlags';+import { merge } from '@/utils/merge';++import { EdgeConfig } from '../modules/EdgeConfig';++const debug = createDebug('lobe:featureFlags');++/**+ * Get feature flags from EdgeConfig with fallback to environment variables+ * @param userId - Optional user ID for user-specific feature flag evaluation+ */+export const getServerFeatureFlagsFromEdgeConfig = async (userId?: string) => {+ // Try to get feature flags from EdgeConfig first+ if (EdgeConfig.isEnabled()) {+ try {+ const edgeConfig = new EdgeConfig();+ const edgeFeatureFlags = await edgeConfig.getFeatureFlags();++ if (edgeFeatureFlags && Object.keys(edgeFeatureFlags).length > 0) {+ // Merge EdgeConfig flags with defaults+ const mergedFlags = merge(DEFAULT_FEATURE_FLAGS, edgeFeatureFlags);+ debug('Using EdgeConfig flags for user: %s', userId || 'anonymous');+ return mergedFlags;+ } else {+ debug('EdgeConfig returned empty/null/undefined, falling back to environment variables');+ }+ } catch (error) {+ console.error(+ '[FeatureFlags] Failed to fetch feature flags from EdgeConfig, falling back to environment variables:',+ error,+ );+ }+ } else {+ debug('EdgeConfig not enabled, using environment variables');+ }++ // Fallback to environment variable-based feature flags+ const envFlags = getServerFeatureFlagsValue();+ debug('Using environment variable flags for user: %s', userId || 'anonymous');+ return envFlags;+};++/**+ * Get server feature flags from EdgeConfig and map them to state with user ID+ * @param userId - Optional user ID for user-specific feature flag evaluation+ */+export const getServerFeatureFlagsStateFromEdgeConfig = async (userId?: string) => {+ const flags = await getServerFeatureFlagsFromEdgeConfig(userId);+ return mapFeatureFlagsEnvToState(flags, userId);+};diff --git a/src/server/modules/EdgeConfig/index.ts b/src/server/modules/EdgeConfig/index.tsindex 225b6410508..6bb0329fa81 100644--- a/src/server/modules/EdgeConfig/index.ts+++ b/src/server/modules/EdgeConfig/index.ts@@ -1,8 +1,24 @@import { EdgeConfigClient, createClient } from '@vercel/edge-config';+import createDebug from 'debug';import { appEnv } from '@/envs/app';-import type { EdgeConfigData } from './types';+const debug = createDebug('lobe-server:edge-config');++const EdgeConfigKeys = {+ /**+ * Assistant whitelist+ */+ AssistantBlacklist: 'assistant_blacklist',+ /**+ * Assistant whitelist+ */+ AssistantWhitelist: 'assistant_whitelist',+ /**+ * Feature flags configuration+ */+ FeatureFlags: 'feature_flags',+};export class EdgeConfig {get client(): EdgeConfigClient {@@ -16,12 +32,35 @@ export class EdgeConfig {* Check if Edge Config is enabled*/static isEnabled() {- return !!appEnv.VERCEL_EDGE_CONFIG;+ const isEnabled = !!appEnv.VERCEL_EDGE_CONFIG;+ debug('VERCEL_EDGE_CONFIG env var: %s', appEnv.VERCEL_EDGE_CONFIG ? 'SET' : 'NOT SET');+ debug('EdgeConfig enabled: %s', isEnabled);+ return isEnabled;}getAgentRestrictions = async () => {const { assistant_blacklist: blacklist, assistant_whitelist: whitelist } =- await this.client.getAll<EdgeConfigData>(['assistant_whitelist', 'assistant_blacklist']);- return { blacklist, whitelist };+ await this.client.getAll([+ EdgeConfigKeys.AssistantWhitelist,+ EdgeConfigKeys.AssistantBlacklist,+ ]);++ return { blacklist, whitelist } as {+ blacklist: string[] | undefined;+ whitelist: string[] | undefined;+ };+ };++ getFlagByKey = async (key: string) => {+ const value = await this.client.get(key);+ return value;+ };++ getFeatureFlags = async () => {+ const featureFlags = await this.client.get(EdgeConfigKeys.FeatureFlags);+ debug('Feature flags retrieved: %O', featureFlags);+ return featureFlags as Record<string, boolean | string[]> | undefined;};}++export { EdgeConfigKeys };