🤯 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: sync some changes from cloud (#10882)
YuTengjingc927d5ec86d5
diff --git a/packages/database/src/schemas/_helpers.ts b/packages/database/src/schemas/_helpers.tsindex 4eb9acfabe9..bed89b84134 100644--- a/packages/database/src/schemas/_helpers.ts+++ b/packages/database/src/schemas/_helpers.ts@@ -1,4 +1,4 @@-import { timestamp, varchar } from 'drizzle-orm/pg-core';+import { numeric, timestamp, varchar } from 'drizzle-orm/pg-core';export const timestamptz = (name: string) => timestamp(name, { withTimezone: true });@@ -16,6 +16,14 @@ export const accessedAt = () =>.defaultNow().$onUpdate(() => new Date());+/**+ * Amount field - Unified configuration with precision 20, scale 6, returns number type+ *+ * Caller should handle default and nullable values+ */+export const amountNumeric = (name: string) =>+ numeric(name, { mode: 'number', precision: 20, scale: 6 });+// columns.helpers.tsexport const timestamps = {accessedAt: accessedAt(),diff --git a/packages/database/src/utils/idGenerator.ts b/packages/database/src/utils/idGenerator.tsindex 7dbe485c90c..af4e18c76f1 100644--- a/packages/database/src/utils/idGenerator.ts+++ b/packages/database/src/utils/idGenerator.ts@@ -7,6 +7,7 @@ export const createNanoId = (size = 8) =>const prefixes = {agents: 'agt',+ budget: 'bgt',chatGroups: 'cg',documents: 'docs',files: 'file',diff --git a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.tsindex ee08d0d2234..1f01ffff322 100644--- a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts+++ b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts@@ -1,9 +1,11 @@import { LobeAnthropicAI } from '../../providers/anthropic';import { LobeAzureAI } from '../../providers/azureai';+import { LobeBedrockAI } from '../../providers/bedrock';import { LobeCloudflareAI } from '../../providers/cloudflare';import { LobeDeepSeekAI } from '../../providers/deepseek';import { LobeFalAI } from '../../providers/fal';import { LobeGoogleAI } from '../../providers/google';+import { LobeMinimaxAI } from '../../providers/minimax';import { LobeOpenAI } from '../../providers/openai';import { LobeQwenAI } from '../../providers/qwen';import { LobeXAI } from '../../providers/xai';@@ -11,10 +13,12 @@ import { LobeXAI } from '../../providers/xai';export const baseRuntimeMap = {anthropic: LobeAnthropicAI,azure: LobeAzureAI,+ bedrock: LobeBedrockAI,cloudflare: LobeCloudflareAI,deepseek: LobeDeepSeekAI,fal: LobeFalAI,google: LobeGoogleAI,+ minimax: LobeMinimaxAI,openai: LobeOpenAI,qwen: LobeQwenAI,xai: LobeXAI,diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex fdb61a0ee20..d9b65d318ce 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -141,7 +141,7 @@ export const createRouterRuntime = ({baseURL: options.baseURL?.trim(),};- // 保存配置但不创建 runtimes+ // Save configuration without creating runtimesthis._routers = routers;this._params = params;this._id = id;@@ -263,13 +263,11 @@ export const createRouterRuntime = ({async embeddings(payload: EmbeddingsPayload, options?: EmbeddingsOptions) {const runtime = await this.getRuntimeByModel(payload.model);-return runtime.embeddings!(payload, options);}async textToSpeech(payload: TextToSpeechPayload, options?: EmbeddingsOptions) {const runtime = await this.getRuntimeByModel(payload.model);-return runtime.textToSpeech!(payload, options);}};diff --git a/packages/model-runtime/src/providers/anthropic/resolveCacheTTL.ts b/packages/model-runtime/src/providers/anthropic/resolveCacheTTL.tsindex 345e255436e..ba01bdec880 100644--- a/packages/model-runtime/src/providers/anthropic/resolveCacheTTL.ts+++ b/packages/model-runtime/src/providers/anthropic/resolveCacheTTL.ts@@ -5,11 +5,11 @@ import { ChatStreamPayload } from '../../types';type CacheTTL = Anthropic.Messages.CacheControlEphemeral['ttl'];const DEFAULT_CACHE_TTL = '5m' as const;-/**- * Resolves cache TTL from Anthropic payload or request settings.- * Returns the first valid TTL found in system messages or content blocks.+ * Resolves cache TTL from Anthropic payload or request settings+ * Returns the first valid TTL found in system messages or content blocks*/+export const resolveCacheTTL = (requestPayload: ChatStreamPayload,anthropicPayload: {@@ -30,6 +30,7 @@ export const resolveCacheTTL = (if (!Array.isArray(message.content)) continue;for (const block of message.content) {+ // Message content blocks might have cache_control propertyconst ttl = ('cache_control' in block && block.cache_control?.ttl) as CacheTTL | undefined;if (ttl) return ttl;}diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.tsindex 81a83c85022..ea5e626d85a 100644--- a/packages/model-runtime/src/providers/bedrock/index.ts+++ b/packages/model-runtime/src/providers/bedrock/index.ts@@ -148,7 +148,7 @@ export class LobeBedrockAI implements LobeRuntimeAI {type: err.name,},errorType: AgentRuntimeErrorType.ProviderBizError,- provider: ModelProvider.Bedrock,+ provider: this.id,region: this.region,});}@@ -273,7 +273,7 @@ export class LobeBedrockAI implements LobeRuntimeAI {type: err.name,},errorType: AgentRuntimeErrorType.ProviderBizError,- provider: ModelProvider.Bedrock,+ provider: this.id,region: this.region,});}@@ -320,7 +320,7 @@ export class LobeBedrockAI implements LobeRuntimeAI {type: err.name,},errorType: AgentRuntimeErrorType.ProviderBizError,- provider: ModelProvider.Bedrock,+ provider: this.id,region: this.region,});}diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.tsindex cf944512ebc..3b213d3ad75 100644--- a/packages/types/src/asyncTask.ts+++ b/packages/types/src/asyncTask.ts@@ -13,6 +13,19 @@ export enum AsyncTaskStatus {export enum AsyncTaskErrorType {EmbeddingError = 'EmbeddingError',++ /* ↓ cloud slot | free plan limit error type ↓ */+ /**+ * Free plan users are not allowed to use this feature+ */+ FreePlanLimit = 'FreePlanLimit',+ /**+ * Subscription plan limit reached (paid users run out of credits)+ */+ SubscriptionPlanLimit = 'SubscriptionPlanLimit',+ /* ↑ cloud slot ↑ */++ // eslint-disable-next-line typescript-sort-keys/string-enumInvalidProviderAPIKey = 'InvalidProviderAPIKey',/*** Model not found on serverdiff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex dd90e0f36e9..567df3bd50c 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -72,6 +72,8 @@ export interface UserPreference {useCmdEnterToSend?: boolean;}+export type ReferralStatusString = 'registered' | 'suspected' | 'rewarded' | 'revoked';+export interface UserInitializationState {avatar?: string;canEnablePWAGuide?: boolean;@@ -81,11 +83,16 @@ export interface UserInitializationState {fullName?: string;hasConversation?: boolean;interests?: string[];+ isFreePlan?: boolean;/** @deprecated Use onboarding field instead */isOnboard?: boolean;lastName?: string;onboarding?: UserOnboarding;preference: UserPreference;+ /**+ * Referral lifecycle status for the current user (invitee side).+ */+ referralStatus?: ReferralStatusString;settings: PartialDeep<UserSettings>;subscriptionPlan?: Plans;userId?: string;diff --git a/packages/utils/src/time.test.ts b/packages/utils/src/time.test.tsindex ae9efbe0bb7..2c363e4d491 100644--- a/packages/utils/src/time.test.ts+++ b/packages/utils/src/time.test.ts@@ -5,6 +5,7 @@ import {daysAgo,getYYYYmmddHHMMss,hoursAgo,+ isNewReleaseDate,lastMonth,monthsAgo,thisMonth,@@ -256,4 +257,38 @@ describe('time utilities', () => {expect(result).toBe('20240615_143045');});});++ describe('isNewReleaseDate', () => {+ it('should return true if date is within 14 days', () => {+ const date = '2024-06-15'; // 0 days before 2024-06-15+ expect(isNewReleaseDate(date)).toBe(true);+ });++ it('should return true if date is exactly 13 days ago', () => {+ const date = '2024-06-02'; // 13 days before 2024-06-15+ expect(isNewReleaseDate(date)).toBe(true);+ });++ it('should return false if date is 15 days ago', () => {+ const date = '2024-05-31'; // 15 days before 2024-06-15+ expect(isNewReleaseDate(date)).toBe(false);+ });++ it('should return true if date is in future', () => {+ const date = '2024-06-16'; // 1 day after 2024-06-15+ expect(isNewReleaseDate(date)).toBe(true);+ });++ it('should work with real model release date (gemini-3-pro-preview)', () => {+ // Released at 2025-11-18, system time is 2024-06-15, so it's in future+ const date = '2025-11-18';+ expect(isNewReleaseDate(date)).toBe(true);+ });++ it('should work with custom days', () => {+ const date = '2024-06-09'; // 6 days ago from 2024-06-15+ expect(isNewReleaseDate(date, 7)).toBe(true);+ expect(isNewReleaseDate(date, 5)).toBe(false);+ });+ });});diff --git a/src/app/(backend)/trpc/lambda/[trpc]/route.ts b/src/app/(backend)/trpc/lambda/[trpc]/route.tsindex 550c158c3de..231825a7f3b 100644--- a/src/app/(backend)/trpc/lambda/[trpc]/route.ts+++ b/src/app/(backend)/trpc/lambda/[trpc]/route.ts@@ -1,7 +1,6 @@import { fetchRequestHandler } from '@trpc/server/adapters/fetch';import type { NextRequest } from 'next/server';-import { pino } from '@/libs/logger';import { createLambdaContext } from '@/libs/trpc/lambda/context';import { prepareRequestForTRPC } from '@/libs/trpc/utils/request-adapter';import { lambdaRouter } from '@/server/routers/lambda';@@ -20,7 +19,11 @@ const handler = (req: NextRequest) => {endpoint: '/trpc/lambda',onError: ({ error, path, type }) => {- pino.info(`Error in tRPC handler (lambda) on path: ${path}, type: ${type}`);+ // Filter out the error of UNAUTHORIZED, because this is normal behavior+ // And it has been displayed at the front end to let the user login+ if (error.code === 'UNAUTHORIZED') return;++ console.info(`Error in tRPC handler (lambda) on path: ${path}, type: ${type}`);console.error(error);},diff --git a/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsxindex 6997b4bf203..04895579bfd 100644--- a/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx+++ b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx@@ -122,11 +122,13 @@ const ProviderConfig = memo<ProviderConfigProps>(logo,className,checkErrorRender,+ canDeactivate = true,name,showAceGcm = true,extra,source = AiProviderSourceEnum.Builtin,apiKeyUrl,+ title,}) => {const {proxyUrl,@@ -363,7 +365,7 @@ const ProviderConfig = memo<ProviderConfigProps>({extra}{isCustom && <UpdateProviderInfo />}- <EnableSwitch id={id} />+ {canDeactivate && <EnableSwitch id={id} />}</Flexbox>),title: (@@ -388,7 +390,7 @@ const ProviderConfig = memo<ProviderConfigProps>(</Flexbox>) : (<>- <ProviderCombine provider={id} size={24} />+ {title ?? <ProviderCombine provider={id} size={24} />}<Tooltip title={t('providerModels.config.helpDoc')}><Linkhref={urlJoin(BASE_PROVIDER_DOC_URL, id)}diff --git a/src/components/404/index.tsx b/src/components/404/index.tsxindex a4aa590a50f..8edb1aeaf2f 100644--- a/src/components/404/index.tsx+++ b/src/components/404/index.tsx@@ -28,11 +28,10 @@ const NotFound = memo(() => {<h2 style={{ fontWeight: 'bold', marginTop: '1em', textAlign: 'center' }}>{t('notFound.title')}</h2>- <p style={{ lineHeight: '1.8', marginBottom: '2em' }}>- {t('notFound.desc')}- <br />- <div style={{ textAlign: 'center' }}>{t('notFound.check')}</div>- </p>+ <div style={{ lineHeight: '1.8', marginBottom: '2em', textAlign: 'center' }}>+ <div>{t('notFound.desc')}</div>+ <div style={{ marginTop: '0.5em' }}>{t('notFound.check')}</div>+ </div><Link href="/"><Button type={'primary'}>{t('notFound.backHome')}</Button></Link>diff --git a/src/features/PluginStore/McpList/Detail/Settings/index.tsx b/src/features/PluginStore/McpList/Detail/Settings/index.tsxindex 750d8be42aa..2fc9cd52e44 100644--- a/src/features/PluginStore/McpList/Detail/Settings/index.tsx+++ b/src/features/PluginStore/McpList/Detail/Settings/index.tsx@@ -1,5 +1,5 @@import { Flexbox, Icon, Input, Text } from '@lobehub/ui';-import { Form as AForm, App, Button, Space, Typography } from 'antd';+import { Form as AForm, App, Button, Space } from 'antd';import { createStyles } from 'antd-style';import { EditIcon, LinkIcon, SaveIcon, Settings2Icon, TerminalIcon } from 'lucide-react';import { memo, useState } from 'react';@@ -371,7 +371,7 @@ const Settings = memo<{ identifier: string }>(({ identifier }) => {{t('settings.configuration.title')}</div><div className={styles.emptyState}>- <Typography.Text type="secondary">{t('settings.httpTypeNotice')}</Typography.Text>+ <Text type="secondary">{t('settings.httpTypeNotice')}</Text></div></div>)}diff --git a/src/hooks/useTTS.ts b/src/hooks/useTTS.tsindex 64624b1a4e2..c79db7b160f 100644--- a/src/hooks/useTTS.ts+++ b/src/hooks/useTTS.ts@@ -38,7 +38,7 @@ export const useTTS = (content: string, config?: TTSConfig) => {options = {api: {headers: createHeaderWithOpenAI(),- serviceUrl: API_ENDPOINTS.tts,+ serviceUrl: API_ENDPOINTS.tts('openai'),},options: {model: ttsSettings.openAI.ttsModel,diff --git a/src/libs/trpc/lambda/context.ts b/src/libs/trpc/lambda/context.tsindex 7fafa5405db..3d7827b380f 100644--- a/src/libs/trpc/lambda/context.ts+++ b/src/libs/trpc/lambda/context.ts@@ -18,6 +18,19 @@ import { validateOIDCJWT } from '@/libs/oidc-provider/jwt';// Create context logger namespaceconst log = debug('lobe-trpc:lambda:context');+const extractClientIp = (request: NextRequest): string | undefined => {+ const forwardedFor = request.headers.get('x-forwarded-for');+ if (forwardedFor) {+ const ip = forwardedFor.split(',')[0]?.trim();+ if (ip) return ip;+ }++ const realIp = request.headers.get('x-real-ip')?.trim();+ if (realIp) return realIp;++ return undefined;+};+export interface OIDCAuth {// Other OIDC information that might be needed (optional, as payload contains all info)[key: string]: any;@@ -30,6 +43,7 @@ export interface OIDCAuth {export interface AuthContext {authorizationHeader?: string | null;clerkAuth?: IClerkAuth;+ clientIp?: string | null;jwtPayload?: ClientSecretPayload | null;marketAccessToken?: string;nextAuth?: User;@@ -47,6 +61,7 @@ export interface AuthContext {export const createContextInner = async (params?: {authorizationHeader?: string | null;clerkAuth?: IClerkAuth;+ clientIp?: string | null;marketAccessToken?: string;nextAuth?: User;oidcAuth?: OIDCAuth | null;@@ -59,6 +74,7 @@ export const createContextInner = async (params?: {return {authorizationHeader: params?.authorizationHeader,clerkAuth: params?.clerkAuth,+ clientIp: params?.clientIp,marketAccessToken: params?.marketAccessToken,nextAuth: params?.nextAuth,oidcAuth: params?.oidcAuth,@@ -92,6 +108,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaCconst authorization = request.headers.get(LOBE_CHAT_AUTH_HEADER);const userAgent = request.headers.get('user-agent') || undefined;+ const clientIp = extractClientIp(request);// get marketAccessToken from cookiesconst cookieHeader = request.headers.get('cookie');@@ -101,6 +118,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaClog('marketAccessToken from cookie:', marketAccessToken ? '[HIDDEN]' : 'undefined');const commonContext = {authorizationHeader: authorization,+ clientIp,marketAccessToken,userAgent,};diff --git a/src/server/modules/ModelRuntime/index.ts b/src/server/modules/ModelRuntime/index.tsindex 9dde39779d6..c5893647f85 100644--- a/src/server/modules/ModelRuntime/index.ts+++ b/src/server/modules/ModelRuntime/index.ts@@ -23,6 +23,10 @@ const getParamsFromPayload = (provider: string, payload: ClientSecretPayload) =>const llmConfig = getLLMConfig() as Record<string, any>;switch (provider) {+ case ModelProvider.LobeHub: {+ return { apikey: payload.apiKey, baseURL: payload.baseURL, ...payload };+ }+case ModelProvider.VertexAI: {return {};}@@ -171,7 +175,10 @@ const buildVertexOptions = (const project = projectFromParams || projectFromCredentials || projectFromEnv;const location =- (params.location as string | undefined) || payload.vertexAIRegion || process.env.VERTEXAI_LOCATION || undefined;+ (params.location as string | undefined) ||+ payload.vertexAIRegion ||+ process.env.VERTEXAI_LOCATION ||+ undefined;const googleAuthOptions = params.googleAuthOptions || (credentials ? { credentials } : undefined);diff --git a/src/services/_url.ts b/src/services/_url.tsindex 1a5bb5cc8d6..f746b1fa3e0 100644--- a/src/services/_url.ts+++ b/src/services/_url.ts@@ -28,7 +28,7 @@ export const API_ENDPOINTS = {stt: withElectronProtocolIfElectron('/webapi/stt/openai'),// TTS- tts: withElectronProtocolIfElectron('/webapi/tts/openai'),+ tts: (provider: string) => withElectronProtocolIfElectron(`/webapi/tts/${provider}`),edge: withElectronProtocolIfElectron('/webapi/tts/edge'),microsoft: withElectronProtocolIfElectron('/webapi/tts/microsoft'),};diff --git a/src/store/user/slices/auth/selectors.ts b/src/store/user/slices/auth/selectors.tsindex 6ba77c466e4..23131f15443 100644--- a/src/store/user/slices/auth/selectors.ts+++ b/src/store/user/slices/auth/selectors.ts@@ -49,6 +49,7 @@ export const userProfileSelectors = {export const authSelectors = {authProviders: (s: UserStore): SSOProvider[] => s.authProviders || [],hasPasswordAccount: (s: UserStore) => s.hasPasswordAccount ?? false,+ isFreePlan: (s: UserStore) => s.isFreePlan,isLoaded: (s: UserStore) => s.isLoaded,isLoadedAuthProviders: (s: UserStore) => s.isLoadedAuthProviders ?? false,isLogin: (s: UserStore) => s.isSignedIn,diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.tsindex b02b180e495..0750bb1477b 100644--- a/src/store/user/slices/common/action.ts+++ b/src/store/user/slices/common/action.ts@@ -131,6 +131,7 @@ export const createCommonSlice: StateCreator<set({defaultSettings,+ isFreePlan: data.isFreePlan,isOnboard: data.isOnboard,isShowPWAGuide: data.canEnablePWAGuide,isUserCanEnableTrace: data.canEnableTrace,@@ -138,6 +139,7 @@ export const createCommonSlice: StateCreator<isUserStateInit: true,onboarding: data.onboarding,preference,+ referralStatus: data.referralStatus,settings: data.settings || {},subscriptionPlan: data.subscriptionPlan,user,diff --git a/src/store/user/slices/common/initialState.ts b/src/store/user/slices/common/initialState.tsindex 0bc62b9ecd8..339f34fa2c8 100644--- a/src/store/user/slices/common/initialState.ts+++ b/src/store/user/slices/common/initialState.ts@@ -1,19 +1,25 @@+import { ReferralStatusString } from '@lobechat/types';+import { Plans } from '@/types/subscription';export interface CommonState {+ isFreePlan?: boolean;/** @deprecated Use onboarding field instead */isOnboard: boolean;isShowPWAGuide: boolean;isUserCanEnableTrace: boolean;isUserHasConversation: boolean;isUserStateInit: boolean;+ referralStatus?: ReferralStatusString;subscriptionPlan?: Plans;}export const initialCommonState: CommonState = {+ isFreePlan: true,isOnboard: false,isShowPWAGuide: false,isUserCanEnableTrace: false,isUserHasConversation: false,isUserStateInit: false,+ referralStatus: undefined,};diff --git a/src/utils/errorResponse.ts b/src/utils/errorResponse.tsindex 26b6a53ef39..a8825b95cd4 100644--- a/src/utils/errorResponse.ts+++ b/src/utils/errorResponse.ts@@ -6,6 +6,11 @@ const getStatus = (errorType: ILobeAgentRuntimeErrorType | ErrorType) => {if (errorType.toString().includes('Invalid')) return 401;switch (errorType) {+ case ChatErrorType.SubscriptionPlanLimit:+ case ChatErrorType.FreePlanLimit: {+ return 403;+ }+// TODO: Need to refactor to Invalid OpenAI API Keycase AgentRuntimeErrorType.InvalidProviderAPIKey:case AgentRuntimeErrorType.NoOpenAIAPIKey: {