From e3309a379ae9e2bfb7eaefbdae5bf0867efaccd8 Mon Sep 17 00:00:00 2001 From: monster Date: Tue, 30 Jun 2026 18:15:57 +0800 Subject: [PATCH] feat: update pricing plans and site region prompt --- frontend/src/App.tsx | 2 + .../console/nav/subscription-plan-dialog.tsx | 194 ++++++------------ .../src/components/site-region-prompt.tsx | 128 ++++++++++++ .../welcome/terminal-native-page.tsx | 15 +- frontend/src/i18n/resources/cn.ts | 65 +++--- frontend/src/i18n/resources/en.ts | 65 +++--- frontend/src/main.tsx | 9 +- frontend/src/site-redirect.ts | 66 +++++- frontend/test/site-redirect.test.ts | 48 ++++- 9 files changed, 362 insertions(+), 230 deletions(-) create mode 100644 frontend/src/components/site-region-prompt.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 84ea0d04..b495e2f1 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -33,6 +33,7 @@ import PrivacyPolicyPage from "./pages/privacy-policy" import UserAgreementPage from "./pages/user-agreement" import { TooltipProvider } from "@/components/ui/tooltip" import { IS_OFFLINE_EDITION } from "@/utils/edition" +import { SiteRegionPrompt } from "@/components/site-region-prompt" function TaskDetailRoute() { const { taskId } = useParams() @@ -97,6 +98,7 @@ function App() { } /> + diff --git a/frontend/src/components/console/nav/subscription-plan-dialog.tsx b/frontend/src/components/console/nav/subscription-plan-dialog.tsx index 656b0470..3846dabb 100644 --- a/frontend/src/components/console/nav/subscription-plan-dialog.tsx +++ b/frontend/src/components/console/nav/subscription-plan-dialog.tsx @@ -1,5 +1,5 @@ import { useEffect, useState } from "react" -import { IconBuildingSkyscraper, IconCheck, IconCrown, IconHelpCircle, IconX } from "@tabler/icons-react" +import { IconCheck, IconCrown, IconHelpCircle, IconX } from "@tabler/icons-react" import { toast } from "sonner" import { ConstsSubscriptionPeriodUnit, ConstsSubscriptionPlan } from "@/api/Api" @@ -29,7 +29,6 @@ import dayjs from "dayjs" import { useTranslation } from "react-i18next" type PersonalAccountPlanId = "basic" | "pro" | "ultra" -type AccountPlanId = PersonalAccountPlanId | "team" type SubscriptionBillingPeriod = "monthly" | "yearly" type AccountPlanFeature = { @@ -38,23 +37,13 @@ type AccountPlanFeature = { } type AccountPlanCard = { - id: AccountPlanId + id: PersonalAccountPlanId name: string desc: string monthlyAmount: number yearlyAmount: number } -const teamPlanFeatureKeys = [ - "sharedPool", - "memberManagement", - "usageStats", - "privateDeployment", - "customSolution", - "salesFollowUp", -] as const -const TEAM_CONSULT_URL = "https://baizhi.cloud/consult" - const monthlyPeriodCounts = Array.from({ length: 12 }, (_, index) => index + 1) const yearlyPeriodCounts = Array.from({ length: 5 }, (_, index) => index + 1) @@ -112,13 +101,6 @@ export default function SubscriptionPlanDialog({ open, onOpenChange }: Subscript monthlyAmount: 499, yearlyAmount: 4999, }, - { - id: "team", - name: t("subscriptionPlan.plans.team.name"), - desc: t("subscriptionPlan.plans.team.desc"), - monthlyAmount: 0, - yearlyAmount: 0, - }, ] const accountPlanComparisonRows: { label: string; tooltip?: string; values: Record }[] = [ { @@ -138,30 +120,19 @@ export default function SubscriptionPlanDialog({ open, onOpenChange }: Subscript }, }, { - label: t("subscriptionPlan.features.basicModels.label"), - tooltip: t("subscriptionPlan.features.basicModels.tooltip"), + label: t("subscriptionPlan.features.dailyQuota.label"), values: { - basic: { label: t("subscriptionPlan.featureValues.dailyTokens30m") }, - pro: { label: t("subscriptionPlan.featureValues.dailyTokens30m") }, - ultra: { label: t("subscriptionPlan.featureValues.dailyTokens60m") }, + basic: { label: t("subscriptionPlan.featureValues.dailyQuotaBasic") }, + pro: { label: t("subscriptionPlan.featureValues.dailyQuotaPro") }, + ultra: { label: t("subscriptionPlan.featureValues.dailyQuotaUltra") }, }, }, { - label: t("subscriptionPlan.features.proModels.label"), - tooltip: t("subscriptionPlan.features.proModels.tooltip"), + label: t("subscriptionPlan.features.modelScope.label"), values: { - basic: { label: t("subscriptionPlan.featureValues.noQuota"), status: "unsupported" }, - pro: { label: t("subscriptionPlan.featureValues.dailyTokens30m") }, - ultra: { label: t("subscriptionPlan.featureValues.dailyTokens60m") }, - }, - }, - { - label: t("subscriptionPlan.features.ultraModels.label"), - tooltip: t("subscriptionPlan.features.ultraModels.tooltip"), - values: { - basic: { label: t("subscriptionPlan.featureValues.noQuota"), status: "unsupported" }, - pro: { label: t("subscriptionPlan.featureValues.noQuota"), status: "unsupported" }, - ultra: { label: t("subscriptionPlan.featureValues.dailyTokens60m") }, + basic: { label: t("subscriptionPlan.featureValues.modelScopeBasic") }, + pro: { label: t("subscriptionPlan.featureValues.modelScopePro") }, + ultra: { label: t("subscriptionPlan.featureValues.modelScopeUltra") }, }, }, { @@ -192,7 +163,7 @@ export default function SubscriptionPlanDialog({ open, onOpenChange }: Subscript }, }, ] - const [selectedAccountPlanId, setSelectedAccountPlanId] = useState("basic") + const [selectedAccountPlanId, setSelectedAccountPlanId] = useState("basic") const [selectedBillingPeriod, setSelectedBillingPeriod] = useState("monthly") const [selectedPeriodCount, setSelectedPeriodCount] = useState(1) const [confirmSubscriptionPlan, setConfirmSubscriptionPlan] = useState<"pro" | "ultra" | null>(null) @@ -211,16 +182,12 @@ export default function SubscriptionPlanDialog({ open, onOpenChange }: Subscript : false const confirmingPlanCard = accountPlanCards.find((plan) => plan.id === confirmSubscriptionPlan) const selectedAccountPlan = accountPlanCards.find((plan) => plan.id === selectedAccountPlanId) || accountPlanCards[0] - const isSelectedTeamPlan = selectedAccountPlan.id === "team" - const SelectedPlanIcon = isSelectedTeamPlan ? IconBuildingSkyscraper : IconCrown - const selectedAccountPlanFeatures = isSelectedTeamPlan - ? [] - : accountPlanComparisonRows.map((row) => ({ - label: row.label, - tooltip: row.tooltip, - feature: row.values[selectedAccountPlan.id as PersonalAccountPlanId], - })) - const selectedSubscriptionPlan = selectedAccountPlan.id === "pro" || selectedAccountPlan.id === "ultra" ? selectedAccountPlan.id : null + const selectedAccountPlanFeatures = accountPlanComparisonRows.map((row) => ({ + label: row.label, + tooltip: row.tooltip, + feature: row.values[selectedAccountPlan.id], + })) + const selectedSubscriptionPlan = selectedAccountPlan.id === "basic" ? null : selectedAccountPlan.id const isSelectedCurrentPlan = selectedAccountPlan.id === "basic" ? !hasAdvancedPlan : selectedAccountPlan.id === "pro" ? isProPlan : selectedAccountPlan.id === "ultra" ? isFlagshipPlan : false const isSelectedPlanLoading = selectedAccountPlan.id === "pro" ? isProLoading : selectedAccountPlan.id === "ultra" ? isFlagshipLoading : false const canSubscribeSelectedPlan = selectedSubscriptionPlan === "pro" ? !isFlagshipPlan : selectedSubscriptionPlan === "ultra" @@ -309,7 +276,7 @@ export default function SubscriptionPlanDialog({ open, onOpenChange }: Subscript return ( <> - + {t("subscriptionPlan.dialog.title")} @@ -342,11 +309,10 @@ export default function SubscriptionPlanDialog({ open, onOpenChange }: Subscript ) : null}
-
+
{accountPlanCards.map((plan) => { const isCurrentPlan = plan.id === "basic" ? !hasAdvancedPlan : plan.id === "pro" ? isProPlan : plan.id === "ultra" ? isFlagshipPlan : false const isSelected = selectedAccountPlan.id === plan.id - const PlanIcon = plan.id === "team" ? IconBuildingSkyscraper : IconCrown return ( - - ) : ( - <>
)}
- - )}
diff --git a/frontend/src/components/site-region-prompt.tsx b/frontend/src/components/site-region-prompt.tsx new file mode 100644 index 00000000..1c472ff3 --- /dev/null +++ b/frontend/src/components/site-region-prompt.tsx @@ -0,0 +1,128 @@ +import { useEffect, useMemo, useState } from "react" +import { useTranslation } from "react-i18next" + +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog" +import { getSiteRedirectPrompt, type SiteRedirectPrompt, type SiteRegion } from "@/site-redirect" + +const SITE_REGION_PROMPT_STORAGE_PREFIX = "site_region_prompt_dismissed:" +const LANGUAGE_DISPLAY_LIMIT = 2 + +function getStorageKey(prompt: SiteRedirectPrompt) { + const languages = prompt.detectedLanguages.slice(0, LANGUAGE_DISPLAY_LIMIT).join(",") || "unknown" + return `${SITE_REGION_PROMPT_STORAGE_PREFIX}${prompt.currentHost}->${prompt.targetHost}:${languages}` +} + +function hasDismissedPrompt(prompt: SiteRedirectPrompt) { + if (typeof window === "undefined") { + return false + } + + try { + return window.localStorage.getItem(getStorageKey(prompt)) === "1" + } catch { + return false + } +} + +function dismissPrompt(prompt: SiteRedirectPrompt) { + if (typeof window === "undefined") { + return + } + + try { + window.localStorage.setItem(getStorageKey(prompt), "1") + } catch { + // Ignore storage failures. The user can still choose for the current page. + } +} + +function getRegionLanguage(region: SiteRegion) { + return region === "cn" ? "cn" : "en" +} + +export function SiteRegionPrompt() { + const { t } = useTranslation() + const prompt = useMemo(() => getSiteRedirectPrompt(), []) + const [open, setOpen] = useState(false) + + useEffect(() => { + if (!prompt || hasDismissedPrompt(prompt)) { + return + } + + setOpen(true) + }, [prompt]) + + if (!prompt) { + return null + } + + const targetLanguage = getRegionLanguage(prompt.targetRegion) + const currentLanguage = getRegionLanguage(prompt.currentRegion) + const currentRegionLabel = t(`siteRegionPrompt.versions.${prompt.currentRegion}`, { lng: targetLanguage }) + const targetRegionLabel = t(`siteRegionPrompt.versions.${prompt.targetRegion}`, { lng: targetLanguage }) + const stayRegionLabel = t(`siteRegionPrompt.versions.${prompt.currentRegion}`, { lng: currentLanguage }) + const switchRegionLabel = t(`siteRegionPrompt.versions.${prompt.targetRegion}`, { lng: targetLanguage }) + + const handleStay = () => { + dismissPrompt(prompt) + setOpen(false) + } + + const handleSwitch = () => { + dismissPrompt(prompt) + window.location.replace(prompt.targetUrl) + } + + return ( + { + if (!nextOpen) { + handleStay() + return + } + + setOpen(true) + }}> + + + + {t("siteRegionPrompt.title", { + lng: targetLanguage, + targetRegion: targetRegionLabel, + })} + + + {t("siteRegionPrompt.description", { + lng: targetLanguage, + currentRegion: currentRegionLabel, + targetRegion: targetRegionLabel, + })} + + + + + {t("siteRegionPrompt.actions.stay", { + lng: currentLanguage, + region: stayRegionLabel, + })} + + + {t("siteRegionPrompt.actions.switch", { + lng: targetLanguage, + region: switchRegionLabel, + })} + + + + + ) +} diff --git a/frontend/src/components/welcome/terminal-native-page.tsx b/frontend/src/components/welcome/terminal-native-page.tsx index 3cb5d1ac..bd6d9c81 100644 --- a/frontend/src/components/welcome/terminal-native-page.tsx +++ b/frontend/src/components/welcome/terminal-native-page.tsx @@ -165,9 +165,8 @@ const pricingTiers: PricingTier[] = [ features: [ { key: "concurrency1" }, { key: "cloud1c4g" }, - { key: "basic30m" }, - { key: "proNone", status: "unsupported" }, - { key: "ultraNone", status: "unsupported" }, + { key: "dailyQuotaBasic" }, + { key: "modelScopeBasic" }, { key: "noCredits", status: "unsupported", tooltipKey: "credit" }, { key: "thirdPartyModels", status: "partial", tooltipKey: "thirdPartyModels" }, { key: "enhancedCapabilities", status: "partial", tooltipKey: "enhancedCapabilities" }, @@ -183,9 +182,8 @@ const pricingTiers: PricingTier[] = [ features: [ { key: "concurrency3" }, { key: "cloud2c8g" }, - { key: "basic30m" }, - { key: "pro30m" }, - { key: "ultraNone", status: "unsupported" }, + { key: "dailyQuotaPro" }, + { key: "modelScopePro" }, { key: "credits10k", tooltipKey: "credit" }, { key: "thirdPartyModels", tooltipKey: "thirdPartyModels" }, { key: "enhancedCapabilities", tooltipKey: "enhancedCapabilities" }, @@ -200,9 +198,8 @@ const pricingTiers: PricingTier[] = [ features: [ { key: "concurrency3" }, { key: "cloud2c8g" }, - { key: "basic60m" }, - { key: "pro60m" }, - { key: "ultra60m" }, + { key: "dailyQuotaUltra" }, + { key: "modelScopeUltra" }, { key: "credits100k", tooltipKey: "credit" }, { key: "thirdPartyModels", tooltipKey: "thirdPartyModels" }, { key: "enhancedCapabilities", tooltipKey: "enhancedCapabilities" }, diff --git a/frontend/src/i18n/resources/cn.ts b/frontend/src/i18n/resources/cn.ts index 4e99f0b6..f4639a4e 100644 --- a/frontend/src/i18n/resources/cn.ts +++ b/frontend/src/i18n/resources/cn.ts @@ -36,6 +36,18 @@ const cn = { connectionError: "终端连接发生错误", }, }, + siteRegionPrompt: { + title: "切换到{{targetRegion}}?", + description: "当前访问的是{{currentRegion}},是否需要切换到{{targetRegion}}", + versions: { + cn: "中文版", + global: "国际版", + }, + actions: { + stay: "留在{{region}}", + switch: "切换到{{region}}", + }, + }, requestUtils: { errors: { methodMissing: "API 方法 \"{{method}}\" 不存在", @@ -1468,10 +1480,6 @@ const cn = { name: "旗舰会员", desc: "面向专业开发者和重度用户。", }, - team: { - name: "团队版", - desc: "面向企业级开发团队。", - }, }, features: { taskConcurrency: { @@ -1480,17 +1488,11 @@ const cn = { cloudDevEnvironment: { label: "云开发环境", }, - basicModels: { - label: "基础模型", - tooltip: "当前为 qwen3.6-plus", + dailyQuota: { + label: "每日额度", }, - proModels: { - label: "专业模型", - tooltip: "上下文更大,能力更强,对标国内一线厂商的当前主力模型,如 qwen3.6-plus, minimax-m2.7, kimi-k2.6, glm-5.1 等", - }, - ultraModels: { - label: "旗舰模型", - tooltip: "超长的上下文和超强的能力,对标国际一线厂商的主力模型,如 gpt-5.5, claude-opus-4.6 等", + modelScope: { + label: "模型范围", }, monthlyCredits: { label: "每月赠送积分", @@ -1508,28 +1510,18 @@ const cn = { featureValues: { oneTask: "1 个任务", threeTasks: "3 个任务", - dailyTokens30m: "每天 3000 万 Token", - dailyTokens60m: "每天 6000 万 Token", - noQuota: "无额度", + dailyQuotaBasic: "每天 30M Token", + dailyQuotaPro: "每天 100M Token", + dailyQuotaUltra: "每天 300M Token", + modelScopeBasic: "基础模型", + modelScopePro: "基础模型、专业模型", + modelScopeUltra: "基础模型、专业模型、旗舰模型", noCredits: "不赠送积分", credits10k: "1 万积分", credits100k: "10 万积分", partialSupport: "部分支持", supported: "支持", }, - team: { - intro: "面向企业级开发团队,团队版支持团队内共享额度和私有化部署。", - contactDescription: "提交联系方式后,我们会根据团队规模和部署需求联系你。", - contactSales: "联系销售", - features: { - sharedPool: "统一额度池,团队成员共享使用", - memberManagement: "成员管理,支持按团队统一开通", - usageStats: "用量统计,便于查看团队消耗", - privateDeployment: "私有化部署,适配企业内网和合规要求", - customSolution: "专属方案,按团队规模和模型需求配置", - salesFollowUp: "咨询留资,销售专人跟进", - }, - }, billing: { monthly: "月付", yearly: "年付", @@ -2302,13 +2294,12 @@ const cn = { concurrency3: "3 个任务并发", cloud1c4g: "云开发环境 1C / 4G", cloud2c8g: "云开发环境 2C / 8G", - basic30m: "基础模型:每天 3000 万 Token", - basic60m: "基础模型:每天 6000 万 Token", - proNone: "专业模型:无额度", - pro30m: "专业模型:每天 3000 万 Token", - pro60m: "专业模型:每天 6000 万 Token", - ultraNone: "旗舰模型:无额度", - ultra60m: "旗舰模型:每天 6000 万 Token", + dailyQuotaBasic: "每日额度:每天 30M Token", + dailyQuotaPro: "每日额度:每天 100M Token", + dailyQuotaUltra: "每日额度:每天 300M Token", + modelScopeBasic: "模型范围:基础模型", + modelScopePro: "模型范围:基础模型、专业模型", + modelScopeUltra: "模型范围:基础模型、专业模型、旗舰模型", noCredits: "不赠送积分", credits10k: "每月赠送 1 万积分", credits100k: "每月赠送 10 万积分", diff --git a/frontend/src/i18n/resources/en.ts b/frontend/src/i18n/resources/en.ts index b13205f7..09ecbc51 100644 --- a/frontend/src/i18n/resources/en.ts +++ b/frontend/src/i18n/resources/en.ts @@ -36,6 +36,18 @@ const en = { connectionError: "Terminal connection error", }, }, + siteRegionPrompt: { + title: "Switch to {{targetRegion}}?", + description: "You are currently visiting the {{currentRegion}}. Switch to the {{targetRegion}}?", + versions: { + cn: "Chinese", + global: "International", + }, + actions: { + stay: "Stay on {{region}}", + switch: "Switch to {{region}}", + }, + }, requestUtils: { errors: { methodMissing: "API method \"{{method}}\" does not exist", @@ -1468,10 +1480,6 @@ const en = { name: "Ultra", desc: "For professional developers and heavy users.", }, - team: { - name: "Team", - desc: "For enterprise development teams.", - }, }, features: { taskConcurrency: { @@ -1480,17 +1488,11 @@ const en = { cloudDevEnvironment: { label: "Cloud development environment", }, - basicModels: { - label: "Basic models", - tooltip: "Currently qwen3.6-plus", + dailyQuota: { + label: "Daily quota", }, - proModels: { - label: "Pro models", - tooltip: "Larger context and stronger capability, aligned with current leading domestic models such as qwen3.6-plus, minimax-m2.7, kimi-k2.6, and glm-5.1.", - }, - ultraModels: { - label: "Ultra models", - tooltip: "Extra-long context and top-tier capability, aligned with leading international models such as gpt-5.5 and claude-opus-4.6.", + modelScope: { + label: "Model scope", }, monthlyCredits: { label: "Monthly credits", @@ -1508,28 +1510,18 @@ const en = { featureValues: { oneTask: "1 task", threeTasks: "3 tasks", - dailyTokens30m: "30M tokens/day", - dailyTokens60m: "60M tokens/day", - noQuota: "No quota", + dailyQuotaBasic: "30M tokens/day", + dailyQuotaPro: "100M tokens/day", + dailyQuotaUltra: "300M tokens/day", + modelScopeBasic: "Basic models", + modelScopePro: "Basic and Pro models", + modelScopeUltra: "Basic, Pro, and Ultra models", noCredits: "No credits", credits10k: "10,000 credits", credits100k: "100,000 credits", partialSupport: "Partial support", supported: "Supported", }, - team: { - intro: "Team is for enterprise development teams, with shared quotas and private deployment support.", - contactDescription: "Submit your contact information and we will reach out based on your team size and deployment needs.", - contactSales: "Contact sales", - features: { - sharedPool: "Unified quota pool shared by team members", - memberManagement: "Member management with team-wide enablement", - usageStats: "Usage statistics for team consumption", - privateDeployment: "Private deployment for internal networks and compliance requirements", - customSolution: "Dedicated plan configured by team size and model needs", - salesFollowUp: "Sales follow-up after consultation submission", - }, - }, billing: { monthly: "Monthly", yearly: "Yearly", @@ -2302,13 +2294,12 @@ const en = { concurrency3: "3 concurrent tasks", cloud1c4g: "Cloud environment 1C / 4G", cloud2c8g: "Cloud environment 2C / 8G", - basic30m: "Basic models: 30M tokens per day", - basic60m: "Basic models: 60M tokens per day", - proNone: "Pro models: no quota", - pro30m: "Pro models: 30M tokens per day", - pro60m: "Pro models: 60M tokens per day", - ultraNone: "Ultra models: no quota", - ultra60m: "Ultra models: 60M tokens per day", + dailyQuotaBasic: "Daily quota: 30M tokens/day", + dailyQuotaPro: "Daily quota: 100M tokens/day", + dailyQuotaUltra: "Daily quota: 300M tokens/day", + modelScopeBasic: "Model scope: Basic models", + modelScopePro: "Model scope: Basic and Pro models", + modelScopeUltra: "Model scope: Basic, Pro, and Ultra models", noCredits: "No included credits", credits10k: "10K credits included monthly", credits100k: "100K credits included monthly", diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index bac3f3aa..d8c9d19f 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -6,7 +6,6 @@ import './index.css' import App from './App.tsx' import { initI18n } from './i18n' import { AppRuntimeProvider } from './components/app-runtime-provider' -import { getSiteRedirectUrl } from './site-redirect' import dayjs from 'dayjs'; @@ -27,10 +26,4 @@ function renderApp() { ) } -const siteRedirectUrl = getSiteRedirectUrl() - -if (siteRedirectUrl) { - window.location.replace(siteRedirectUrl) -} else { - void initI18n().then(renderApp) -} +void initI18n().then(renderApp) diff --git a/frontend/src/site-redirect.ts b/frontend/src/site-redirect.ts index 7f4cf270..a1acb682 100644 --- a/frontend/src/site-redirect.ts +++ b/frontend/src/site-redirect.ts @@ -1,36 +1,92 @@ +export type SiteRegion = "cn" | "global" + const CN_SITE_HOST = "monkeycode-ai.com" const GLOBAL_SITE_HOST = "monkeycode-ai.net" +const LOCAL_SITE_HOSTS = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]"]) const LANGUAGE_CHAIN_LIMIT = 2 type SiteLocation = Pick +export type SiteRedirectPrompt = { + currentHost: string + currentRegion: SiteRegion + targetHost: string + targetRegion: SiteRegion + targetUrl: string + detectedLanguages: string[] +} + export function getSiteRedirectUrl( location: SiteLocation | null = getCurrentLocation(), languages: readonly string[] = getBrowserLanguages(), ): string | null { + return getSiteRedirectPrompt(location, languages)?.targetUrl || null +} + +export function getSiteRedirectPrompt( + location: SiteLocation | null = getCurrentLocation(), + languages: readonly string[] = getBrowserLanguages(), +): SiteRedirectPrompt | null { if (!location) { return null } const { hostname, pathname, search, hash } = location - if (hostname !== CN_SITE_HOST && hostname !== GLOBAL_SITE_HOST) { + if (!isSupportedSiteHost(hostname)) { return null } - const targetHost = languagesContainChinese(languages) ? CN_SITE_HOST : GLOBAL_SITE_HOST - if (hostname === targetHost) { + const detectedRegion: SiteRegion = languagesContainChinese(languages) ? "cn" : "global" + const isLocalHost = isLocalSiteHost(hostname) + const currentRegion = isLocalHost ? detectedRegion : getSiteRegion(hostname) + const targetRegion = isLocalHost ? getOppositeSiteRegion(currentRegion) : detectedRegion + const targetHost = getSiteHost(targetRegion) + if (!isLocalHost && hostname === targetHost) { return null } - return `https://${targetHost}${pathname}${search}${hash}` + return { + currentHost: hostname, + currentRegion, + targetHost, + targetRegion, + targetUrl: `https://${targetHost}${pathname}${search}${hash}`, + detectedLanguages: normalizeBrowserLanguages(languages), + } } export function languagesContainChinese(languages: readonly string[]): boolean { - return languages + return normalizeBrowserLanguages(languages) .slice(0, LANGUAGE_CHAIN_LIMIT) .some((language) => /^zh($|[-_])/i.test(language.trim())) } +function normalizeBrowserLanguages(languages: readonly string[]): string[] { + return languages + .map((language) => language.trim()) + .filter(Boolean) +} + +function getSiteRegion(hostname: string): SiteRegion { + return hostname === CN_SITE_HOST ? "cn" : "global" +} + +function getSiteHost(region: SiteRegion): string { + return region === "cn" ? CN_SITE_HOST : GLOBAL_SITE_HOST +} + +function isSupportedSiteHost(hostname: string): boolean { + return hostname === CN_SITE_HOST || hostname === GLOBAL_SITE_HOST || isLocalSiteHost(hostname) +} + +function isLocalSiteHost(hostname: string): boolean { + return LOCAL_SITE_HOSTS.has(hostname) +} + +function getOppositeSiteRegion(region: SiteRegion): SiteRegion { + return region === "cn" ? "global" : "cn" +} + function getCurrentLocation(): SiteLocation | null { if (typeof window === "undefined") { return null diff --git a/frontend/test/site-redirect.test.ts b/frontend/test/site-redirect.test.ts index fb233a3b..534a8d6c 100644 --- a/frontend/test/site-redirect.test.ts +++ b/frontend/test/site-redirect.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict" import test from "node:test" -import { getSiteRedirectUrl, languagesContainChinese } from "../src/site-redirect.ts" +import { getSiteRedirectPrompt, getSiteRedirectUrl, languagesContainChinese } from "../src/site-redirect.ts" function location(hostname: string) { return { @@ -19,6 +19,20 @@ test("国际站语言链前两项包含中文时跳转到中文站并保留路 ) }) +test("国际站语言链前两项包含中文时返回区域切换提示信息", () => { + assert.deepEqual( + getSiteRedirectPrompt(location("monkeycode-ai.net"), [" en-US ", "zh-CN", "ja-JP"]), + { + currentHost: "monkeycode-ai.net", + currentRegion: "global", + targetHost: "monkeycode-ai.com", + targetRegion: "cn", + targetUrl: "https://monkeycode-ai.com/login?next=%2Fconsole%2Ftasks#section", + detectedLanguages: ["en-US", "zh-CN", "ja-JP"], + }, + ) +}) + test("中文站语言链前两项不包含中文时跳转到国际站并保留路径", () => { assert.equal( getSiteRedirectUrl(location("monkeycode-ai.com"), ["en-US", "ja-JP"]), @@ -31,8 +45,36 @@ test("已经在匹配站点时不跳转", () => { assert.equal(getSiteRedirectUrl(location("monkeycode-ai.net"), ["en-US"]), null) }) -test("非正式域名不跳转", () => { - assert.equal(getSiteRedirectUrl(location("localhost"), ["zh-CN"]), null) +test("localhost 中文浏览器环境按中文版返回区域切换提示信息", () => { + assert.deepEqual( + getSiteRedirectPrompt(location("localhost"), ["zh-CN"]), + { + currentHost: "localhost", + currentRegion: "cn", + targetHost: "monkeycode-ai.net", + targetRegion: "global", + targetUrl: "https://monkeycode-ai.net/login?next=%2Fconsole%2Ftasks#section", + detectedLanguages: ["zh-CN"], + }, + ) +}) + +test("localhost 非中文浏览器环境按国际版返回区域切换提示信息", () => { + assert.deepEqual( + getSiteRedirectPrompt(location("localhost"), ["en-US"]), + { + currentHost: "localhost", + currentRegion: "global", + targetHost: "monkeycode-ai.com", + targetRegion: "cn", + targetUrl: "https://monkeycode-ai.com/login?next=%2Fconsole%2Ftasks#section", + detectedLanguages: ["en-US"], + }, + ) +}) + +test("无关域名不跳转", () => { + assert.equal(getSiteRedirectUrl(location("example.com"), ["zh-CN"]), null) }) test("语言链只检查前两项", () => {