diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx index 2642e08d6..b83c563eb 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx @@ -15,6 +15,7 @@ import { $createParagraphNode, $getRoot, createEditor } from "lexical" import { AnimatePresence } from "motion/react" import { nanoid } from "nanoid" import type { FC, RefObject } from "react" +import * as React from "react" import { Suspense, use, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react" import { useEventCallback, useEventListener } from "usehooks-ts" @@ -26,6 +27,7 @@ import { AIChatMessage, AIChatWaitingIndicator, } from "~/modules/ai-chat/components/message/AIChatMessage" +import { ErrorMessage } from "~/modules/ai-chat/components/message/ErrorMessage" import { UserChatMessage } from "~/modules/ai-chat/components/message/UserChatMessage" import { useAutoScroll } from "~/modules/ai-chat/hooks/useAutoScroll" import { useAutoTimelineSummaryShortcut } from "~/modules/ai-chat/hooks/useAutoTimelineSummaryShortcut" @@ -45,12 +47,13 @@ import { LexicalAIEditorNodes, ShortcutNode } from "../../editor" import { useAttachScrollBeyond } from "../../hooks/useAttachScrollBeyond" import { AIPanelRefsContext, useAIChatStore } from "../../store/AIChatContext" import type { AIChatContextBlock, BizUIMessage, SendingUIMessage } from "../../store/types" +import { isRateLimitError } from "../../utils/error" import { generateAndUpdateChatTitle } from "../../utils/titleGeneration" import { GlobalFileDropZone } from "../file/GlobalFileDropZone" import { AIErrorFallback } from "./AIErrorFallback" import { ChatInput } from "./ChatInput" import { ChatShortcutsRow } from "./ChatShortcutsRow" -import { CollapsibleError } from "./CollapsibleError" +import { RateLimitNotice } from "./RateLimitNotice" import { WelcomeScreen } from "./WelcomeScreen" const SCROLL_BOTTOM_THRESHOLD = 100 @@ -60,6 +63,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const status = useChatStatus() const chatActions = useChatActions() const error = useChatError() + useAutoTimelineSummaryShortcut() const isFocusWithIn = useFocusable() @@ -312,6 +316,13 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const shouldShowScrollToBottom = hasMessages && !isAtBottom && !isLoadingHistory const { handleScroll } = useAttachScrollBeyond() + + // Check if error is a rate limit error + const hasRateLimitError = useMemo(() => isRateLimitError(error), [error]) + + // Additional height for rate limit notice (~40px) + const rateLimitExtraHeight = hasRateLimitError ? 40 : 0 + return (
@@ -326,14 +337,14 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { scrollbarClassName="mt-12" scrollbarProps={{ style: { - marginBottom: Math.max(160, bottomPanelHeight) + (error ? 64 : 0), + marginBottom: Math.max(160, bottomPanelHeight) + rateLimitExtraHeight, }, }} ref={setScrollAreaRef} rootClassName="flex-1" viewportProps={{ style: { - paddingBottom: Math.max(128, bottomPanelHeight) + (error ? 64 : 0), + paddingBottom: Math.max(128, bottomPanelHeight) + rateLimitExtraHeight, }, }} viewportClassName={"pt-12"} @@ -393,7 +404,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { "bottom-1/2 translate-y-[calc(100%+1rem)] duration-200", )} > - {error && } + {hasRateLimitError && error && } { const tempEditor = createEditor({ @@ -458,6 +469,7 @@ export const ChatInterface = (props: ChatInterfaceProps) => ( export const Messages: FC<{ contentRef?: RefObject }> = ({ contentRef }) => { const messages = useMessages() + const error = useChatError() const fallbackRef = useRef(null) const messageContainerWidth = useElementWidth(contentRef ?? fallbackRef) @@ -484,6 +496,8 @@ export const Messages: FC<{ contentRef?: RefObject }> = ({ conte ) })} + {/* Render error as the last message in the list */} + {!!messageContainerWidth && error && }
) } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/CollapsibleError.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/CollapsibleError.tsx deleted file mode 100644 index 267f9200d..000000000 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/CollapsibleError.tsx +++ /dev/null @@ -1,218 +0,0 @@ -import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js" -import { cn } from "@follow/utils" -import { ExceptionCodeMap } from "@follow-app/client-sdk" -import * as React from "react" - -import { useI18n } from "~/hooks/common/useI18n" - -interface CollapsibleErrorProps { - error: Error | string - title?: string - className?: string - collapsedHeight?: string - icon?: string - expandedMaxHeight?: string -} - -interface ErrorData { - code?: number - remainedTokens?: number - windowResetTime?: string - [key: string]: any -} - -export const CollapsibleError: React.FC = ({ - error, - title, - className, - collapsedHeight = "48px", - icon = "i-mgc-alert-cute-fi", - expandedMaxHeight = "240px", -}) => { - const [isExpanded, setIsExpanded] = React.useState(false) - const t = useI18n() - - const { displayMessage, errorCode, errorData, isBusinessError } = React.useMemo(() => { - const rawMessage = typeof error === "string" ? error : error.message - - try { - const parsed = JSON.parse(rawMessage) - - const errorData: ErrorData = parsed || {} - const { code } = errorData - - if (code && ExceptionCodeMap[code]) { - // This is a business exception code - const errorKey = `errors:${code}` as any - const translatedMessage = t(errorKey) - // If translation exists and is different from the key, use it; otherwise fallback to raw message - const userFriendlyMessage = translatedMessage !== errorKey ? translatedMessage : rawMessage - return { - displayMessage: userFriendlyMessage, - errorCode: code, - errorData, - isBusinessError: true, - } - } - - // If no code in data, return the original message - return { - displayMessage: rawMessage, - errorCode: null, - errorData: null, - isBusinessError: false, - } - } catch { - // If parsing fails, return the original message - return { - displayMessage: rawMessage, - errorCode: null, - errorData: null, - isBusinessError: false, - } - } - }, [error, t]) - - const formatResetTime = (windowResetTime: string) => { - const resetDate = new Date(windowResetTime) - - // Format date part as YYYY/MM/DD - const dateFormatter = new Intl.DateTimeFormat("en-CA", { - year: "numeric", - month: "2-digit", - day: "2-digit", - }) - const datePart = dateFormatter.format(resetDate).replaceAll("-", "/") - - // Format time part as HH:mm - const timeFormatter = new Intl.DateTimeFormat("en-GB", { - hour: "2-digit", - minute: "2-digit", - hour12: false, - }) - const timePart = timeFormatter.format(resetDate) - - // Get timezone offset - const timezoneFormatter = new Intl.DateTimeFormat("en", { - timeZoneName: "short", - }) - const timezone = - timezoneFormatter.formatToParts(resetDate).find((part) => part.type === "timeZoneName") - ?.value || "" - - return `${datePart} ${timePart} (${timezone})` - } - - const getContextualInfo = () => { - if (!isBusinessError || !errorData) return null - - switch (errorCode) { - case ExceptionCodeMap.AIRateLimitExceeded: { - // AI Rate Limit Exceeded - return ( -
- {errorData.remainedTokens !== undefined && ( -
- Remaining tokens: - {errorData.remainedTokens} -
- )} - {errorData.windowResetTime && ( -
- Rate limit resets at: - {formatResetTime(errorData.windowResetTime)} -
- )} -
- ) - } - default: { - return null - } - } - } - - const getErrorTitle = () => { - if (title) return title - - if (isBusinessError) { - switch (errorCode) { - case ExceptionCodeMap.AIRateLimitExceeded: { - return "AI Rate Limit Exceeded" - } - default: { - return "Error occurred" - } - } - } - - return "Error occurred" - } - - const contextualInfo = getContextualInfo() - - return ( -
setIsExpanded(true)} - onMouseLeave={() => setIsExpanded(false)} - > -
- {/* Collapsed Content */} -
-
- -
-
-
{getErrorTitle()}
-
- - hover to expand - -
- - {/* Expanded Content */} -
- -
-
- {displayMessage as string} -
- {contextualInfo && ( -
- {contextualInfo} -
- )} -
-
-
-
-
- ) -} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/RateLimitNotice.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/RateLimitNotice.tsx new file mode 100644 index 000000000..09056ddec --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/RateLimitNotice.tsx @@ -0,0 +1,91 @@ +import { cn } from "@follow/utils" +import { m } from "motion/react" +import * as React from "react" + +import { parseAIError } from "../../utils/error" + +interface RateLimitNoticeProps { + error: Error | string + className?: string +} + +/** + * RateLimitNotice component + * Displays rate limit information above the input in a subtle, non-alarming way + */ +export const RateLimitNotice: React.FC = ({ error, className }) => { + const parsedError = React.useMemo(() => parseAIError(error), [error]) + const { isRateLimitError, errorData } = parsedError + + // Only render for rate limit errors + if (!isRateLimitError || !errorData) { + return null + } + + const formatResetTime = (windowResetTime: string) => { + const resetDate = new Date(windowResetTime) + const now = new Date() + const diffMs = resetDate.getTime() - now.getTime() + const diffMinutes = Math.ceil(diffMs / (1000 * 60)) + + // Show relative time if less than 60 minutes + if (diffMinutes < 60 && diffMinutes > 0) { + return `${diffMinutes} minute${diffMinutes > 1 ? "s" : ""}` + } + + // Otherwise show absolute time + const timeFormatter = new Intl.DateTimeFormat("en-GB", { + hour: "2-digit", + minute: "2-digit", + hour12: false, + }) + return timeFormatter.format(resetDate) + } + + const remainingTokens = errorData.remainedTokens + const resetTime = errorData.windowResetTime ? formatResetTime(errorData.windowResetTime) : null + + // Build compact message text + const buildMessage = () => { + const parts: string[] = [] + + // Tokens info + if (remainingTokens !== undefined) { + if (remainingTokens === 0) { + parts.push("AI tokens depleted") + } else { + parts.push(`${remainingTokens.toLocaleString()} tokens left`) + } + } else { + parts.push("AI usage limit reached") + } + + // Reset time + if (resetTime) { + if (resetTime.includes("minute")) { + parts.push(`resets in ${resetTime}`) + } else { + parts.push(`resets at ${resetTime}`) + } + } + + return parts.join(" ยท ") + } + + return ( + +
+ + + {buildMessage()} + +
+
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ErrorMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ErrorMessage.tsx new file mode 100644 index 000000000..3d38b0b65 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ErrorMessage.tsx @@ -0,0 +1,88 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { cn } from "@follow/utils" +import { ExceptionCodeMap } from "@follow-app/client-sdk" +import { m } from "motion/react" +import * as React from "react" + +import { getErrorMessage, parseAIError } from "~/modules/ai-chat/utils/error" + +interface ErrorMessageProps { + error: Error | string + className?: string +} + +/** + * ErrorMessage component for displaying errors in the message list + * Uses a subtle, message-like appearance with low-key colors + * Note: Rate limit errors are handled separately by RateLimitNotice component + */ +export const ErrorMessage: React.FC = ({ error, className }) => { + const parsedError = React.useMemo(() => parseAIError(error), [error]) + + if (parsedError.isRateLimitError) { + return null + } + + const displayMessage = getErrorMessage(parsedError) + const { errorCode, errorData } = parsedError + + const getContextualInfo = () => { + if (!parsedError.isBusinessError || !errorData) return null + + switch (errorCode) { + default: { + return null + } + } + } + + const getErrorTitle = () => { + if (parsedError.isBusinessError) { + switch (errorCode) { + case ExceptionCodeMap.AIRateLimitExceeded: { + return "AI Rate Limit Exceeded" + } + default: { + return "Error occurred" + } + } + } + return "Error occurred" + } + + const contextualInfo = getContextualInfo() + + return ( + +
+ {/* Main error message bubble - similar to AI message style */} +
+
+ {/* Header with subtle icon */} +
+ + {getErrorTitle()} +
+ + {/* Error message - always visible but subtle */} +
+ {displayMessage} +
+ + {/* Contextual info if exists */} + {contextualInfo && ( +
+ {contextualInfo} +
+ )} +
+
+
+
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/error.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/error.ts new file mode 100644 index 000000000..0710d8091 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/error.ts @@ -0,0 +1,89 @@ +import { ExceptionCodeMap } from "@follow-app/client-sdk" + +import { getI18n } from "~/i18n" + +export interface ParsedErrorData { + code?: number + remainedTokens?: number + windowResetTime?: string + [key: string]: any +} + +export interface ParsedError { + rawMessage: string + errorCode: number | null + errorData: ParsedErrorData | null + isBusinessError: boolean + isRateLimitError: boolean +} + +/** + * Parse error object or string to extract structured error information + * @param error - Error object or error message string + * @returns Parsed error information + */ +export function parseAIError(error: Error | string | undefined): ParsedError { + if (!error) { + return { + rawMessage: "", + errorCode: null, + errorData: null, + isBusinessError: false, + isRateLimitError: false, + } + } + + const rawMessage = typeof error === "string" ? error : error.message + + try { + const parsed = JSON.parse(rawMessage) + const errorData: ParsedErrorData = parsed || {} + const { code } = errorData + + const isRateLimitError = code === ExceptionCodeMap.AIRateLimitExceeded + const isBusinessError = !!(code && ExceptionCodeMap[code]) + + return { + rawMessage, + errorCode: code || null, + errorData: isBusinessError ? errorData : null, + isBusinessError, + isRateLimitError, + } + } catch { + // Not a JSON error, return as plain text error + return { + rawMessage, + errorCode: null, + errorData: null, + isBusinessError: false, + isRateLimitError: false, + } + } +} + +/** + * Check if an error is a rate limit error + * @param error - Error object or error message string + * @returns True if the error is a rate limit error + */ +export function isRateLimitError(error: Error | string | undefined): boolean { + return parseAIError(error).isRateLimitError +} + +/** + * Get translated error message with fallback + * @param error - Parsed error information + * @returns User-friendly error message + */ +export function getErrorMessage(error: ParsedError): string { + if (!error.isBusinessError || !error.errorCode) { + return error.rawMessage + } + + const errorKey = `errors:${error.errorCode}` as any + const translatedMessage = getI18n().t(errorKey) + + // If translation exists and is different from the key, use it; otherwise fallback to raw message + return translatedMessage !== errorKey ? translatedMessage : error.rawMessage +} diff --git a/apps/desktop/layer/renderer/src/modules/new-user-guide/ai-chat-pane.tsx b/apps/desktop/layer/renderer/src/modules/new-user-guide/ai-chat-pane.tsx index 0654d51e7..91af3215b 100644 --- a/apps/desktop/layer/renderer/src/modules/new-user-guide/ai-chat-pane.tsx +++ b/apps/desktop/layer/renderer/src/modules/new-user-guide/ai-chat-pane.tsx @@ -35,10 +35,11 @@ import { } from "~/modules/ai-chat/store/hooks" import type { AIChatContextBlock, BizUIMessage } from "~/modules/ai-chat/store/types" -import { CollapsibleError } from "../ai-chat/components/layouts/CollapsibleError" +import { RateLimitNotice } from "../ai-chat/components/layouts/RateLimitNotice" import { AIChatWaitingIndicator } from "../ai-chat/components/message/AIChatMessage" import { AIShortcutButton } from "../ai-chat/components/ui/AIShortcutButton" import { LexicalAIEditorNodes } from "../ai-chat/editor" +import { isRateLimitError } from "../ai-chat/utils/error" import { stepAtom } from "./store" const SUGGESTION_KEYS = [ @@ -56,7 +57,7 @@ const SUGGESTION_KEYS = [ "new_user_guide.ai_chat.suggestions.robotics_coach", "new_user_guide.ai_chat.suggestions.saas_marketing_manager", "new_user_guide.ai_chat.suggestions.ai_regulation_learner", -] as const +] as I18nKeys[] const SUGGESTION_SAMPLE_SIZE = 5 @@ -446,6 +447,12 @@ function AIChatInterface({ inputRef }: AIChatInterfaceProps) { const shouldShowScrollToBottom = hasMessages && !isAtBottom + // Check if error is a rate limit error + const hasRateLimitError = useMemo(() => isRateLimitError(error), [error]) + + // Additional height for rate limit notice (~40px) + const rateLimitExtraHeight = hasRateLimitError ? 40 : 0 + const messages = useMessages() const setStep = useSetAtom(stepAtom) @@ -461,14 +468,14 @@ function AIChatInterface({ inputRef }: AIChatInterfaceProps) { scrollbarClassName="mt-12" scrollbarProps={{ style: { - marginBottom: Math.max(160, bottomPanelHeight) + (error ? 64 : 0), + marginBottom: Math.max(160, bottomPanelHeight) + rateLimitExtraHeight, }, }} ref={setScrollAreaRef} rootClassName="flex-1" viewportProps={{ style: { - paddingBottom: Math.max(128, bottomPanelHeight) + (error ? 64 : 0), + paddingBottom: Math.max(128, bottomPanelHeight) + rateLimitExtraHeight, }, }} viewportClassName={"pt-12"} @@ -514,7 +521,7 @@ function AIChatInterface({ inputRef }: AIChatInterfaceProps) { )}
- {error && } + {hasRateLimitError && error && }