🤯 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
feat: add market registerUser method and invite code i18n (#11614)
YuTengjingb062f8556f40
diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex b9ee0b0c04d..5612a030b23 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -12,6 +12,11 @@"import.importConfigFile.title": "Import Failed","import.incompatible.description": "This file was exported from a higher version. Please try upgrading to the latest version and then re-importing.","import.incompatible.title": "Current application does not support importing this file",+ "inviteCode.currentEmail": "Current account: {{email}}",+ "inviteCode.desc": "An invite code is required to access LobeHub. Please enter a valid invite code to continue.",+ "inviteCode.friends": "Friends",+ "inviteCode.getCodeHint": "Get an invite code from:",+ "inviteCode.title": "Invite Code Required","loginRequired.desc": "You will be redirected to the login page shortly","loginRequired.title": "Please log in to use this feature","notFound.backHome": "Back to Home",@@ -144,5 +149,9 @@"upload.networkError": "Please check your network connection and ensure that the file storage service's cross-origin configuration is correct.","upload.title": "File upload failed. Please check your network connection or try again later","upload.unknownError": "Error reason: {{reason}}",- "upload.uploadFailed": "File upload failed."+ "upload.uploadFailed": "File upload failed.",+ "waitlist.currentEmail": "Current account: {{email}}",+ "waitlist.desc": "Your account is not on the whitelist. Please contact the administrator to request access.",+ "waitlist.switchAccount": "Switch Account",+ "waitlist.title": "Access Restricted"}diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.jsonindex ac3e19262ec..2183b194360 100644--- a/locales/en-US/subscription.json+++ b/locales/en-US/subscription.json@@ -288,7 +288,7 @@"referral.rules.backfill.description": "Forgot to enter invite code? You can backfill within 3 days of registration","referral.rules.backfill.expiredTip": "Backfill period has expired. Cannot backfill after 3 days of registration","referral.rules.backfill.link": "Backfill Invite Code",- "referral.rules.backfill.placeholder": "Enter invite code",+ "referral.rules.backfill.placeholder": "Enter invite code or link","referral.rules.backfill.submit": "Confirm Binding","referral.rules.backfill.success": "Invite code bound successfully","referral.rules.backfill.title": "Backfill Invite Code",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex e36138eb752..d312087fcfd 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -12,6 +12,11 @@"import.importConfigFile.title": "导入遇到了问题","import.incompatible.description": "该文件由更高版本导出。请升级到最新版后再导入","import.incompatible.title": "版本不兼容",+ "inviteCode.currentEmail": "当前账号:{{email}}",+ "inviteCode.desc": "需要邀请码才能访问 LobeHub。请输入有效的邀请码以继续。",+ "inviteCode.friends": "好友",+ "inviteCode.getCodeHint": "获取邀请码:",+ "inviteCode.title": "需要邀请码","loginRequired.desc": "将为你跳转到登录页。登录后即可继续","loginRequired.title": "需要登录后继续","notFound.backHome": "返回首页",@@ -144,5 +149,9 @@"upload.networkError": "网络异常或跨域配置不正确。请检查文件存储服务的 CORS 设置后重试","upload.title": "上传未能完成","upload.unknownError": "原因:{{reason}}",- "upload.uploadFailed": "上传未能完成"+ "upload.uploadFailed": "上传未能完成",+ "waitlist.currentEmail": "当前账号:{{email}}",+ "waitlist.desc": "你的账号不在白名单中。请联系管理员申请访问权限。",+ "waitlist.switchAccount": "切换账号",+ "waitlist.title": "访问受限"}diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.jsonindex 83f7222cf5f..cc82eb91ad6 100644--- a/locales/zh-CN/subscription.json+++ b/locales/zh-CN/subscription.json@@ -288,7 +288,7 @@"referral.rules.backfill.description": "忘记填写邀请码?注册三天内可以补填","referral.rules.backfill.expiredTip": "补填期限已过,注册超过三天后无法补填","referral.rules.backfill.link": "补填邀请码",- "referral.rules.backfill.placeholder": "请输入邀请码",+ "referral.rules.backfill.placeholder": "请输入邀请码或链接","referral.rules.backfill.submit": "确认绑定","referral.rules.backfill.success": "邀请码绑定成功","referral.rules.backfill.title": "补填邀请码",diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex 520a75f26a3..518117f4121 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -133,14 +133,6 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>routers: Routers;}-const formatErrorMessage = (error: unknown): string => {- if (error instanceof Error) {- return error.name ? `${error.name}: ${error.message}` : error.message;- }-- return String(error);-};-export const createRouterRuntime = ({id,routers,@@ -310,30 +302,28 @@ export const createRouterRuntime = ({} catch (error) {lastError = error;- const message = formatErrorMessage(error);if (attempt < totalOptions) {log(- 'attempt failed, fallback to next: model=%s attempt=%d/%d apiType=%s channelId=%s remark=%s error=%s',- model,+ 'attempt %d/%d failed (model=%s apiType=%s channelId=%s remark=%s), trying next',attempt,totalOptions,+ model,resolvedApiType,channelId ?? '',remark ?? '',- message,);} else {log(- 'attempt failed, no more fallbacks: model=%s attempt=%d/%d apiType=%s channelId=%s remark=%s error=%s',- model,+ 'attempt %d/%d failed (model=%s apiType=%s channelId=%s remark=%s), no more fallbacks',attempt,totalOptions,+ model,resolvedApiType,channelId ?? '',remark ?? '',- message,);}+ console.error(error);}}diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex c10dbbb7fb3..d13e68c8aaf 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -84,6 +84,7 @@ export interface UserInitializationState {hasConversation?: boolean;interests?: string[];isFreePlan?: boolean;+ isInviteCodeRequired?: boolean;isInWaitList?: boolean;/** @deprecated Use onboarding field instead */isOnboard?: boolean;diff --git a/src/business/server/user.ts b/src/business/server/user.tsindex 3930fd5636a..081339c47a8 100644--- a/src/business/server/user.ts+++ b/src/business/server/user.ts@@ -13,6 +13,10 @@ export async function getIsInWaitList(userId: string): Promise<boolean> {return false;}+export async function getIsInviteCodeRequired(userId: string): Promise<boolean> {+ return false;+}+export async function initNewUserForBusiness(userId: string,createdAt: Date | null | undefined,diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsxindex 6a64f9786df..ee755de553c 100644--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx@@ -17,6 +17,7 @@ import { shallow } from 'zustand/shallow';import RepoIcon from '@/components/LibIcon';import { clearTreeFolderCache } from '@/features/ResourceManager/components/LibraryHierarchy';import { PAGE_FILE_TYPE } from '@/features/ResourceManager/constants';+import { useAppOrigin } from '@/hooks/useAppOrigin';import { documentService } from '@/services/document';import { useFileStore } from '@/store/file';import { useKnowledgeBaseStore } from '@/store/library';@@ -53,6 +54,7 @@ export const useFileItemDropdown = ({}: UseFileItemDropdownParams): UseFileItemDropdownReturn => {const { t } = useTranslation(['components', 'common', 'knowledgeBase']);const { message, modal } = App.useApp();+ const appOrigin = useAppOrigin();const { deleteResource, refreshFileList } = useFileStore((s) => ({@@ -184,11 +186,10 @@ export const useFileItemDropdown = ({// For pages, use the route path instead of the storage URLlet urlToCopy = url;if (isPage) {- const baseUrl = window.location.origin;if (libraryId) {- urlToCopy = `${baseUrl}/resource/library/${libraryId}?file=${id}`;+ urlToCopy = `${appOrigin}/resource/library/${libraryId}?file=${id}`;} else {- urlToCopy = `${baseUrl}/resource?file=${id}`;+ urlToCopy = `${appOrigin}/resource?file=${id}`;}}diff --git a/src/features/SharePopover/index.tsx b/src/features/SharePopover/index.tsxindex e1fa4f863d2..aa722e0dace 100644--- a/src/features/SharePopover/index.tsx+++ b/src/features/SharePopover/index.tsx@@ -2,11 +2,12 @@import { Button, Flexbox, Popover, copyToClipboard, usePopoverContext } from '@lobehub/ui';import { App, Divider, Select, Skeleton, Typography } from 'antd';-import { CopyIcon, ExternalLinkIcon, LinkIcon, LockIcon } from 'lucide-react';+import { ExternalLinkIcon, LinkIcon, LockIcon } from 'lucide-react';import { type ReactNode, memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import useSWR from 'swr';+import { useAppOrigin } from '@/hooks/useAppOrigin';import { useIsMobile } from '@/hooks/useIsMobile';import { topicService } from '@/services/topic';import { useChatStore } from '@/store/chat';@@ -26,6 +27,7 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ onOpenModal }) =>const [updating, setUpdating] = useState(false);const { close } = usePopoverContext();const containerRef = useRef<HTMLDivElement>(null);+ const appOrigin = useAppOrigin();const activeTopicId = useChatStore((s) => s.activeTopicId);@@ -46,7 +48,7 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ onOpenModal }) =>}}, [isLoading, shareInfo, activeTopicId, mutate]);- const shareUrl = shareInfo?.id ? `${window.location.origin}/share/t/${shareInfo.id}` : '';+ const shareUrl = shareInfo?.id ? `${appOrigin}/share/t/${shareInfo.id}` : '';const currentVisibility = (shareInfo?.visibility as Visibility) || 'private';const updateVisibility = useCallback(@@ -178,7 +180,7 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ onOpenModal }) =>>{t('shareModal.popover.moreOptions')}</Button>- <Button icon={CopyIcon} onClick={handleCopyLink} size="small" type="primary">+ <Button icon={LinkIcon} onClick={handleCopyLink} size="small" type="primary">{t('shareModal.copyLink')}</Button></Flexbox>diff --git a/src/hooks/useAppOrigin.ts b/src/hooks/useAppOrigin.tsnew file mode 100644index 00000000000..30090fe7fb5--- /dev/null+++ b/src/hooks/useAppOrigin.ts@@ -0,0 +1,16 @@+'use client';++import { isDesktop } from '@lobechat/const';++import { useElectronStore } from '@/store/electron';+import { electronSyncSelectors } from '@/store/electron/selectors';++/**+ * Returns the correct app origin URL for sharing/linking.+ * - Web: uses window.location.origin+ * - Desktop: uses remoteServerUrl from electron store+ */+export const useAppOrigin = () => {+ const remoteServerUrl = useElectronStore(electronSyncSelectors.remoteServerUrl);+ return isDesktop ? remoteServerUrl : window.location.origin;+};diff --git a/src/layout/GlobalProvider/useUserStateRedirect.ts b/src/layout/GlobalProvider/useUserStateRedirect.tsindex 8c9f8f7bf7d..e104016ee37 100644--- a/src/layout/GlobalProvider/useUserStateRedirect.ts+++ b/src/layout/GlobalProvider/useUserStateRedirect.ts@@ -20,43 +20,51 @@ export const useDesktopUserStateRedirect = () => {const dataSyncConfig = useElectronStore((s) => s.dataSyncConfig);const logout = useUserStore((s) => s.logout);- const handleDesktopWaitlist = useCallback(async () => {- const waitlistBaseUrl = dataSyncConfig.remoteServerUrl || OFFICIAL_URL;- let waitlistUrl = waitlistBaseUrl;- try {- waitlistUrl = new URL('/waitlist', waitlistBaseUrl).toString();- } catch {- // Ignore: keep fallback URL for external open attempt.- }+ const openExternalAndLogout = useCallback(+ async (path: string) => {+ const baseUrl = dataSyncConfig.remoteServerUrl || OFFICIAL_URL;+ let targetUrl = baseUrl;+ try {+ targetUrl = new URL(path, baseUrl).toString();+ } catch {+ // Ignore: keep fallback URL for external open attempt.+ }- try {- const { electronSystemService } = await import('@/services/electron/system');- await electronSystemService.openExternalLink(waitlistUrl);- } catch {- // Ignore: fallback to logout flow even if IPC is unavailable.- }+ try {+ const { electronSystemService } = await import('@/services/electron/system');+ await electronSystemService.openExternalLink(targetUrl);+ } catch {+ // Ignore: fallback to logout flow even if IPC is unavailable.+ }- try {- const { remoteServerService } = await import('@/services/electron/remoteServer');- await remoteServerService.clearRemoteServerConfig();- } catch {- // Ignore: fallback to logout flow even if IPC is unavailable.- }+ try {+ const { remoteServerService } = await import('@/services/electron/remoteServer');+ await remoteServerService.clearRemoteServerConfig();+ } catch {+ // Ignore: fallback to logout flow even if IPC is unavailable.+ }- await logout();- }, [dataSyncConfig.remoteServerUrl, logout]);+ await logout();+ },+ [dataSyncConfig.remoteServerUrl, logout],+ );return useCallback((state: UserInitializationState) => {if (state.isInWaitList === true) {- void handleDesktopWaitlist();+ void openExternalAndLogout('/waitlist');+ return;+ }++ if (state.isInviteCodeRequired === true) {+ void openExternalAndLogout('/invite-code');return;}if (!getDesktopOnboardingCompleted()) return;// Desktop onboarding is handled by desktop-only flow.},- [handleDesktopWaitlist],+ [openExternalAndLogout],);};@@ -68,6 +76,11 @@ export const useWebUserStateRedirect = () =>return;}+ if (state.isInviteCodeRequired === true) {+ redirectIfNotOn(pathname, '/invite-code');+ return;+ }+if (!onboardingSelectors.needsOnboarding(state)) return;redirectIfNotOn(pathname, '/onboarding');diff --git a/src/locales/default/error.ts b/src/locales/default/error.tsindex b3bfcaa85b0..2df9f42bff8 100644--- a/src/locales/default/error.ts+++ b/src/locales/default/error.ts@@ -16,6 +16,12 @@ export default {'import.incompatible.description':'This file was exported from a higher version. Please try upgrading to the latest version and then re-importing.','import.incompatible.title': 'Current application does not support importing this file',+ 'inviteCode.currentEmail': 'Current account: {{email}}',+ 'inviteCode.desc':+ 'An invite code is required to access LobeHub. Please enter a valid invite code to continue.',+ 'inviteCode.friends': 'Friends',+ 'inviteCode.getCodeHint': 'Get an invite code from:',+ 'inviteCode.title': 'Invite Code Required','loginRequired.desc': 'You will be redirected to the login page shortly','loginRequired.title': 'Please log in to use this feature','notFound.backHome': 'Back to Home',@@ -238,5 +244,10 @@ export default {'upload.title': 'File upload failed. Please check your network connection or try again later','upload.unknownError': 'Error reason: {{reason}}','upload.uploadFailed': 'File upload failed.',+ 'waitlist.currentEmail': 'Current account: {{email}}',+ 'waitlist.desc':+ 'Your account is not on the whitelist. Please contact the administrator to request access.',+ 'waitlist.switchAccount': 'Switch Account',+ 'waitlist.title': 'Access Restricted',...businessErrorsLocales,};diff --git a/src/locales/default/subscription.ts b/src/locales/default/subscription.tsindex dfab7882310..ce5514a83f9 100644--- a/src/locales/default/subscription.ts+++ b/src/locales/default/subscription.ts@@ -328,7 +328,7 @@ export default {'referral.rules.backfill.expiredTip':'Backfill period has expired. Cannot backfill after 3 days of registration','referral.rules.backfill.link': 'Backfill Invite Code',- 'referral.rules.backfill.placeholder': 'Enter invite code',+ 'referral.rules.backfill.placeholder': 'Enter invite code or link','referral.rules.backfill.submit': 'Confirm Binding','referral.rules.backfill.success': 'Invite code bound successfully','referral.rules.backfill.title': 'Backfill Invite Code',diff --git a/src/server/routers/lambda/user.ts b/src/server/routers/lambda/user.tsindex 7c228be9cdc..17d1f39042e 100644--- a/src/server/routers/lambda/user.ts+++ b/src/server/routers/lambda/user.ts@@ -16,7 +16,12 @@ import { after } from 'next/server';import { v4 as uuidv4 } from 'uuid';import { z } from 'zod';-import { getIsInWaitList, getReferralStatus, getSubscriptionPlan } from '@/business/server/user';+import {+ getIsInviteCodeRequired,+ getIsInWaitList,+ getReferralStatus,+ getSubscriptionPlan,+} from '@/business/server/user';import { MessageModel } from '@/database/models/message';import { SessionModel } from '@/database/models/session';import { UserModel, UserNotFoundError } from '@/database/models/user';@@ -129,15 +134,23 @@ export const userRouter = router({};// Run user state fetch and count queries in parallel- const [state, messageCount, hasExtraSession, referralStatus, subscriptionPlan, isInWaitList] =- await Promise.all([- getOrCreateUserState(),- ctx.messageModel.countUpTo(5),- ctx.sessionModel.hasMoreThanN(1),- getReferralStatus(ctx.userId),- getSubscriptionPlan(ctx.userId),- getIsInWaitList(ctx.userId),- ]);+ const [+ state,+ messageCount,+ hasExtraSession,+ referralStatus,+ subscriptionPlan,+ isInWaitList,+ isInviteCodeRequired,+ ] = await Promise.all([+ getOrCreateUserState(),+ ctx.messageModel.countUpTo(5),+ ctx.sessionModel.hasMoreThanN(1),+ getReferralStatus(ctx.userId),+ getSubscriptionPlan(ctx.userId),+ getIsInWaitList(ctx.userId),+ getIsInviteCodeRequired(ctx.userId),+ ]);const hasMoreThan4Messages = messageCount > 4;const hasAnyMessages = messageCount > 0;@@ -168,6 +181,7 @@ export const userRouter = router({referralStatus,subscriptionPlan,isInWaitList,+ isInviteCodeRequired,isFreePlan: !subscriptionPlan || subscriptionPlan === Plans.Free,} satisfies UserInitializationState;/* eslint-enable sort-keys-fix/sort-keys-fix */diff --git a/src/server/services/market/index.ts b/src/server/services/market/index.tsindex 64d40ecb1b0..09ac76a5214 100644--- a/src/server/services/market/index.ts+++ b/src/server/services/market/index.ts@@ -368,6 +368,13 @@ export class MarketService {return this.market.user.getUserInfo(username, options);}+ /**+ * Register user on market and optionally follow another user+ */+ async registerUser(params: { followUserId?: string; registerUserId: string }): Promise<void> {+ await this.market.user.register(params);+ }+// ============================== Skills Methods ==============================/**