🤯 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: translate non-English comments to English in src/hooks (#11720)
LobeHub Botae3b6fdd0fd2
diff --git a/src/hooks/useAgentEnableSearch.ts b/src/hooks/useAgentEnableSearch.tsindex 40a4be72930..b502aad58f7 100644--- a/src/hooks/useAgentEnableSearch.ts+++ b/src/hooks/useAgentEnableSearch.ts@@ -11,9 +11,9 @@ export const useAgentEnableSearch = () => {const searchImpl = useAiInfraStore(aiModelSelectors.modelBuiltinSearchImpl(model, provider));- // 只要是内置的搜索实现,一定可以联网搜索+ // Built-in search implementations always support web searchif (searchImpl === 'internal') return true;- // 如果是关闭状态,一定不能联网搜索+ // If disabled, web search is not allowedreturn agentSearchMode !== 'off';};diff --git a/src/hooks/useAgentOwnershipCheck.ts b/src/hooks/useAgentOwnershipCheck.tsindex 72603c4f579..e30cd5fc532 100644--- a/src/hooks/useAgentOwnershipCheck.ts+++ b/src/hooks/useAgentOwnershipCheck.ts@@ -6,31 +6,31 @@ import { marketApiService } from '@/services/marketApi';import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';interface AgentOwnershipResult {- // null = loading, true = 是用户的, false = 不是用户的+ // null = loading, true = user owns it, false = user doesn't own iterror?: string;isOwnAgent: boolean | null;}-// 简单的缓存机制避免重复 API 调用+// Simple cache mechanism to avoid duplicate API callsconst agentOwnershipCache = new Map<string, { result: boolean; timestamp: number }>();-const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存+const CACHE_DURATION = 5 * 60 * 1000; // 5-minute cacheconst buildCacheKey = (marketIdentifier: string, accountId?: string | number | null) =>`${marketIdentifier}::${accountId ?? 'unknown'}`;/**- * 获取当前用户 ID+ * Get current user ID*/function getCurrentAccountId(marketAuth: MarketAuthContextType): string | number | null {try {- // 首先尝试从 marketAuth 中获取用户信息+ // First try to get user info from marketAuthconst userInfo = marketAuth.getCurrentUserInfo?.();if (userInfo?.accountId !== null) {console.log('[useAgentOwnershipCheck] User ID from userInfo:', userInfo?.accountId);return userInfo?.accountId ?? null;}- // 如果没有,尝试从 sessionStorage 中获取+ // If not available, try to get from sessionStorageconst userInfoData = sessionStorage.getItem('market_user_info');if (userInfoData) {const parsedUserInfo = JSON.parse(userInfoData);@@ -53,7 +53,7 @@ interface CheckOwnershipParams {accessToken?: string;accountId?: string | number | null;/**- * 是否启用了 trustedClient 模式,启用时不需要 accessToken+ * Whether trustedClient mode is enabled; when enabled, accessToken is not required*/enableMarketTrustedClient?: boolean;marketIdentifier?: string;@@ -61,7 +61,7 @@ interface CheckOwnershipParams {}/**- * 校验当前账号是否为指定 agent 的 owner+ * Verify if the current account is the owner of the specified agent*/export const checkOwnership = async ({accountId,@@ -70,7 +70,7 @@ export const checkOwnership = async ({marketIdentifier,skipCache = false,}: CheckOwnershipParams): Promise<boolean> => {- // 在 trustedClient 模式下,不需要 accessToken;否则需要+ // In trustedClient mode, accessToken is not required; otherwise it is requiredif (!marketIdentifier || !accountId || (!enableMarketTrustedClient && !accessToken)) {console.warn('[checkOwnership] Missing required parameters', {accessToken: Boolean(accessToken),@@ -88,7 +88,7 @@ export const checkOwnership = async ({return cached.result;}- // 只有在非 trustedClient 模式下才设置 accessToken+ // Only set accessToken when not in trustedClient modeif (!enableMarketTrustedClient && accessToken) {marketApiService.setAccessToken(accessToken);}@@ -106,14 +106,14 @@ export const checkOwnership = async ({};/**- * 检查当前用户是否拥有指定的 agent+ * Check if the current user owns the specified agent*/export const useAgentOwnershipCheck = (marketIdentifier?: string): AgentOwnershipResult => {const [result, setResult] = useState<AgentOwnershipResult>({ isOwnAgent: null });const marketAuth = useMarketAuth();const { isAuthenticated } = marketAuth;- // 检查是否启用了 Market Trusted Client 认证+ // Check if Market Trusted Client authentication is enabledconst enableMarketTrustedClient = useServerConfigStore(serverConfigSelectors.enableMarketTrustedClient,);@@ -128,7 +128,7 @@ export const useAgentOwnershipCheck = (marketIdentifier?: string): AgentOwnershitry {console.log('[useAgentOwnershipCheck] Checking ownership for:', marketIdentifier);- // 获取当前用户 ID+ // Get current user IDconst currentAccountId = getCurrentAccountId(marketAuth);console.log('[useAgentOwnershipCheck] Current user ID:', currentAccountId);@@ -138,7 +138,7 @@ export const useAgentOwnershipCheck = (marketIdentifier?: string): AgentOwnershireturn;}- // trustedClient 模式下不需要获取 accessToken+ // No need to get accessToken in trustedClient modeconst accessToken = enableMarketTrustedClient? undefined: (marketAuth.getAccessToken() ?? undefined);diff --git a/src/hooks/useFetchTopics.ts b/src/hooks/useFetchTopics.tsindex 29a1dad4a02..9ebf34b1751 100644--- a/src/hooks/useFetchTopics.ts+++ b/src/hooks/useFetchTopics.ts@@ -29,7 +29,7 @@ export const useFetchTopics = (options?: { excludeTriggers?: string[] }) => {});return {- // isRevalidating: 有缓存数据,后台正在更新+ // isRevalidating: has cached data, updating in backgroundisRevalidating: isValidating && !!data,};};diff --git a/src/hooks/useGeminiChineseWarning.tsx b/src/hooks/useGeminiChineseWarning.tsxindex e42c7516394..494f06356c2 100644--- a/src/hooks/useGeminiChineseWarning.tsx+++ b/src/hooks/useGeminiChineseWarning.tsx@@ -48,7 +48,7 @@ export const useGeminiChineseWarning = () => {return new Promise<boolean>((resolve) => {let doNotShowAgain = false;- // 根据场景选择不同的按钮文案+ // Select different button text based on scenarioconst continueText =scenario === 'image'? t('geminiImageChineseWarning.continueGenerate')diff --git a/src/hooks/useInitGroupConfig.ts b/src/hooks/useInitGroupConfig.tsindex 26ab3a8ede2..988f08cbc34 100644--- a/src/hooks/useInitGroupConfig.ts+++ b/src/hooks/useInitGroupConfig.ts@@ -19,7 +19,7 @@ export const useInitGroupConfig = () => {data,error: rest.error || (!shouldFetch ? undefined : rest.error),isLoading: (rest.isLoading && isLogin) || !shouldFetch,- // isRevalidating: 有缓存数据,后台正在更新+ // isRevalidating: has cached data, updating in backgroundisRevalidating: isValidating && !!data,};};diff --git a/src/hooks/useInitRecentPage.ts b/src/hooks/useInitRecentPage.tsindex b8a31f6ce8d..3f05ab628b4 100644--- a/src/hooks/useInitRecentPage.ts+++ b/src/hooks/useInitRecentPage.ts@@ -24,7 +24,7 @@ export const useInitRecentPage = () => {...rest,data,isLoading: rest.isLoading && isLogin,- // isRevalidating: 有缓存数据,后台正在更新+ // isRevalidating: has cached data, updating in backgroundisRevalidating: isValidating && !!data,};};diff --git a/src/hooks/useInitRecentResource.ts b/src/hooks/useInitRecentResource.tsindex cf7de5297d0..d974a98b2d5 100644--- a/src/hooks/useInitRecentResource.ts+++ b/src/hooks/useInitRecentResource.ts@@ -24,7 +24,7 @@ export const useInitRecentResource = () => {...rest,data,isLoading: rest.isLoading && isLogin,- // isRevalidating: 有缓存数据,后台正在更新+ // isRevalidating: has cached data, updating in backgroundisRevalidating: isValidating && !!data,};};diff --git a/src/hooks/useInitRecentTopic.ts b/src/hooks/useInitRecentTopic.tsindex be4e7529b8a..e549591f220 100644--- a/src/hooks/useInitRecentTopic.ts+++ b/src/hooks/useInitRecentTopic.ts@@ -24,7 +24,7 @@ export const useInitRecentTopic = () => {...rest,data,isLoading: rest.isLoading && isLogin,- // isRevalidating: 有缓存数据,后台正在更新+ // isRevalidating: has cached data, updating in backgroundisRevalidating: isValidating && !!data,};};diff --git a/src/hooks/useQueryParam.ts b/src/hooks/useQueryParam.tsindex 4fb9264ab68..da43ced027b 100644--- a/src/hooks/useQueryParam.ts+++ b/src/hooks/useQueryParam.ts@@ -3,7 +3,7 @@ import { useSearchParams } from 'react-router-dom';type HistoryMode = 'push' | 'replace';-// options 接口,用于 useQueryParam hook+// Options interface for useQueryParam hookinterface QueryParamOptions<T> {clearOnDefault?: boolean;defaultValue?: T;@@ -11,13 +11,13 @@ interface QueryParamOptions<T> {throttleMs?: number;}-// 解析器接口+// Parser interfaceinterface Parser<T> {parse: (value: string | null) => T;serialize: (value: T) => string | null;}-// 带默认值的解析器接口+// Parser interface with default valueinterface ParserWithDefault<T> extends Parser<T> {// nuqs has an optional default value on parsersdefaultValue?: T;@@ -25,8 +25,8 @@ interface ParserWithDefault<T> extends Parser<T> {}/**- * 核心钩子,用于管理单个查询参数- * 为 react-router-dom 替换 nuqs 的 useQueryState 功能+ * Core hook for managing a single query parameter+ * Replaces nuqs's useQueryState functionality for react-router-dom*/export function useQueryParam<T>(key: string,@@ -35,7 +35,7 @@ export function useQueryParam<T>(): [T, (value: T | ((prev: T) => T)) => void] {const [searchParams, setSearchParams] = useSearchParams();- // 从 options 或 parser 本身提取 defaultValue+ // Extract defaultValue from options or parser itselfconst {clearOnDefault = false,defaultValue = (parser as ParserWithDefault<T>)?.defaultValue,@@ -47,14 +47,14 @@ export function useQueryParam<T>(const throttleTimer = useRef<NodeJS.Timeout | null>(null);const lastExecuteTime = useRef<number>(0);- // 使用 ref 存储最新的值,让 setValue 保持稳定+ // Use ref to store latest values, keeping setValue stableconst searchParamsRef = useRef(searchParams);const parserRef = useRef(parser);const defaultValueRef = useRef(defaultValue);const clearOnDefaultRef = useRef(clearOnDefault);const historyRef = useRef(history);- // 每次渲染时更新 ref+ // Update refs on every renderuseEffect(() => {searchParamsRef.current = searchParams;parserRef.current = parser;@@ -63,34 +63,34 @@ export function useQueryParam<T>(historyRef.current = history;});- // 从 URL 解析当前值+ // Parse current value from URLconst currentValue = parser.parse(searchParams.get(key));const value = currentValue ?? (defaultValue as T);- // setValue 现在是稳定的,不会因为 searchParams 变化而重新创建+ // setValue is now stable and won't be recreated when searchParams changesconst setValue = useCallback((newValue: T | ((prev: T) => T)) => {- // 从 ref 读取最新值,避免闭包陈旧值问题+ // Read latest values from refs to avoid stale closure issuesconst currentSearchParams = searchParamsRef.current;const currentParser = parserRef.current;const currentDefaultValue = defaultValueRef.current;const currentClearOnDefault = clearOnDefaultRef.current;const currentHistory = historyRef.current;- // 通过函数形式获取最新值+ // Get latest value through function formconst currentVal =currentParser.parse(currentSearchParams.get(key)) ?? (currentDefaultValue as T);const actualValue =typeof newValue === 'function' ? (newValue as (prev: T) => T)(currentVal) : newValue;const updateParams = () => {- // 使用函数式更新,确保基于最新的 searchParams+ // Use functional update to ensure it's based on latest searchParamssetSearchParams((prevParams) => {const newSearchParams = new URLSearchParams(prevParams);const serialized = currentParser.serialize(actualValue);- // 处理 clearOnDefault 选项+ // Handle clearOnDefault optionif (currentClearOnDefault &¤tDefaultValue !== undefined &&@@ -109,22 +109,22 @@ export function useQueryParam<T>();};- // 处理节流+ // Handle throttlingif (throttleMs > 0) {const now = Date.now();const timeSinceLastExecute = now - lastExecuteTime.current;if (timeSinceLastExecute >= throttleMs) {- // 距离上次执行已超过节流时间,立即执行+ // Throttle time exceeded since last execution, execute immediatelylastExecuteTime.current = now;updateParams();- // 清理可能存在的定时器+ // Clear any existing timerif (throttleTimer.current) {clearTimeout(throttleTimer.current);throttleTimer.current = null;}} else {- // 还在节流期内,设置定时器在剩余时间后执行最后一次+ // Still within throttle period, set timer to execute one last time after remaining timeif (throttleTimer.current) {clearTimeout(throttleTimer.current);}@@ -139,10 +139,10 @@ export function useQueryParam<T>(updateParams();}},- [key, setSearchParams, throttleMs], // 只依赖不会频繁变化的值+ [key, setSearchParams, throttleMs], // Only depend on values that don't change frequently);- // 组件卸载时清理节流计时器+ // Clean up throttle timer on component unmountuseEffect(() => {return () => {if (throttleTimer.current) {@@ -154,10 +154,10 @@ export function useQueryParam<T>(return [value, setValue];}-// ===== 解析器 (Parsers) =====+// ===== Parsers =====/**- * 字符串解析器 - 默认行为+ * String parser - default behavior*/export const parseAsString: Parser<string | null> & {withDefault: (defaultValue: string) => ParserWithDefault<string>;@@ -172,7 +172,7 @@ export const parseAsString: Parser<string | null> & {};/**- * 布尔值解析器+ * Boolean parser*/export const parseAsBoolean: Parser<boolean | null> & {withDefault: (defaultValue: boolean) => ParserWithDefault<boolean>;@@ -196,7 +196,7 @@ export const parseAsBoolean: Parser<boolean | null> & {};/**- * 整数解析器+ * Integer parser*/export const parseAsInteger: Parser<number | null> & {withDefault: (defaultValue: number) => ParserWithDefault<number>;@@ -222,7 +222,7 @@ export const parseAsInteger: Parser<number | null> & {};/**- * 字符串枚举解析器+ * String enum parser*/export function parseAsStringEnum<T extends string>(validValues: readonly T[]) {const parser: Parser<T | null> = {@@ -245,75 +245,75 @@ export function parseAsStringEnum<T extends string>(validValues: readonly T[]) {return Object.assign(parser, { withDefault });}-// ===== 简化的 API (Simplified API) =====+// ===== Simplified API =====-// --- 重载签名 ---+// --- Overload Signatures ----// 字符串 (无解析器或仅有 options)+// String (no parser or only options)export function useQueryState(key: string,options?: QueryParamOptions<string | null>,): [string | null, (value: string | null | ((prev: string | null) => string | null)) => void];-// 带默认值的字符串解析器+// String parser with default value// eslint-disable-next-line no-redeclareexport function useQueryState(key: string,parserWithDefault: ParserWithDefault<string>,): [string, (value: string | ((prev: string) => string)) => void];-// 布尔值解析器+// Boolean parser// eslint-disable-next-line no-redeclareexport function useQueryState(key: string,parser: typeof parseAsBoolean,): [boolean | null, (value: boolean | null | ((prev: boolean | null) => boolean | null)) => void];-// 带默认值的布尔值解析器+// Boolean parser with default value// eslint-disable-next-line no-redeclareexport function useQueryState(key: string,parserWithDefault: ParserWithDefault<boolean>,): [boolean, (value: boolean | ((prev: boolean) => boolean)) => void];-// 整数解析器+// Integer parser// eslint-disable-next-line no-redeclareexport function useQueryState(key: string,parser: typeof parseAsInteger,): [number | null, (value: number | null | ((prev: number | null) => number | null)) => void];-// 带默认值的整数解析器+// Integer parser with default value// eslint-disable-next-line no-redeclareexport function useQueryState(key: string,parserWithDefault: ParserWithDefault<number>,): [number, (value: number | ((prev: number) => number)) => void];-// 带默认值的字符串枚举解析器+// String enum parser with default value// eslint-disable-next-line no-redeclareexport function useQueryState<T extends string>(key: string,parserWithDefault: ParserWithDefault<T>,): [T, (value: T | ((prev: T) => T)) => void];-// --- 单一实现 ---+// --- Single Implementation ---// eslint-disable-next-line no-redeclareexport function useQueryState(key: string, parserOrOptions?: any): any {- // 修复了逻辑分派问题+ // Fixed logic dispatch issuelet parser: Parser<any>;let options: QueryParamOptions<any> = {};if (!parserOrOptions) {- // 场景 1: useQueryState('key')+ // Scenario 1: useQueryState('key')parser = parseAsString;} else if (typeof parserOrOptions.parse === 'function') {- // 场景 2: useQueryState('key', parseAsInteger) 或 useQueryState('key', parseAsInteger.withDefault(10))+ // Scenario 2: useQueryState('key', parseAsInteger) or useQueryState('key', parseAsInteger.withDefault(10))parser = parserOrOptions;- // 从解析器自身提取 options (例如 defaultValue)+ // Extract options from parser itself (e.g. defaultValue)options = parserOrOptions;} else {- // 场景 3: useQueryState('key', { defaultValue: 'foo', throttleMs: 500 })+ // Scenario 3: useQueryState('key', { defaultValue: 'foo', throttleMs: 500 })parser = parseAsString;options = parserOrOptions;}diff --git a/src/hooks/useTokenCount.ts b/src/hooks/useTokenCount.tsindex 774ff652078..d8fac7342b1 100644--- a/src/hooks/useTokenCount.ts+++ b/src/hooks/useTokenCount.ts@@ -22,7 +22,7 @@ export const useTokenCount = (input: string = '') => {debouncedEncode(input || '');});- // 清理函数+ // Cleanup functionreturn () => {debouncedEncode.cancel();};