feat(ai-chat): refactor error handling and introduce rate limit notice
- Replaced the CollapsibleError component with a new RateLimitNotice component to handle rate limit errors more effectively. - Added ErrorMessage component for displaying general error messages in the chat interface. - Updated ChatInterface and AIChatInterface to accommodate the new error handling structure, ensuring proper display of rate limit and other errors. - Enhanced error parsing utility functions to streamline error information extraction. Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
+18
-4
@@ -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 (
|
||||
<GlobalFileDropZone className="flex size-full flex-col @container">
|
||||
<div className="flex min-h-0 flex-1 flex-col" ref={scrollContainerParentRef}>
|
||||
@@ -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 && <CollapsibleError error={error} />}
|
||||
{hasRateLimitError && error && <RateLimitNotice error={error} />}
|
||||
<ChatShortcutsRow
|
||||
onSelect={(shortcutData) => {
|
||||
const tempEditor = createEditor({
|
||||
@@ -458,6 +469,7 @@ export const ChatInterface = (props: ChatInterfaceProps) => (
|
||||
|
||||
export const Messages: FC<{ contentRef?: RefObject<HTMLDivElement> }> = ({ contentRef }) => {
|
||||
const messages = useMessages()
|
||||
const error = useChatError()
|
||||
const fallbackRef = useRef<HTMLDivElement>(null)
|
||||
const messageContainerWidth = useElementWidth(contentRef ?? fallbackRef)
|
||||
|
||||
@@ -484,6 +496,8 @@ export const Messages: FC<{ contentRef?: RefObject<HTMLDivElement> }> = ({ conte
|
||||
</Suspense>
|
||||
)
|
||||
})}
|
||||
{/* Render error as the last message in the list */}
|
||||
{!!messageContainerWidth && error && <ErrorMessage error={error} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
-218
@@ -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<CollapsibleErrorProps> = ({
|
||||
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 (
|
||||
<div className="space-y-2">
|
||||
{errorData.remainedTokens !== undefined && (
|
||||
<div className="flex justify-between text-xs">
|
||||
<span className="text-text-secondary">Remaining tokens:</span>
|
||||
<span className="font-medium">{errorData.remainedTokens}</span>
|
||||
</div>
|
||||
)}
|
||||
{errorData.windowResetTime && (
|
||||
<div className="flex justify-between text-xs">
|
||||
<span className="text-text-secondary">Rate limit resets at:</span>
|
||||
<span className="font-medium">{formatResetTime(errorData.windowResetTime)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
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 (
|
||||
<div
|
||||
className={cn(
|
||||
"group mb-3 duration-300 animate-in fade-in-0 slide-in-from-bottom-2",
|
||||
className,
|
||||
)}
|
||||
onMouseEnter={() => setIsExpanded(true)}
|
||||
onMouseLeave={() => setIsExpanded(false)}
|
||||
>
|
||||
<div
|
||||
className={
|
||||
"relative overflow-hidden rounded-xl border-red/20 shadow-red/5 backdrop-blur-background transition-all duration-200 bg-mix-red-20 dark:shadow-red/10"
|
||||
}
|
||||
>
|
||||
{/* Collapsed Content */}
|
||||
<div
|
||||
className="relative z-10 flex items-center gap-3 p-3"
|
||||
style={{ minHeight: collapsedHeight }}
|
||||
>
|
||||
<div className="flex size-6 flex-shrink-0 items-center justify-center rounded-full bg-red/20 transition-colors duration-200">
|
||||
<i className={cn(icon, "size-3 text-red")} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium text-red">{getErrorTitle()}</div>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"text-xs text-text-tertiary",
|
||||
"transition-[opacity,transform] duration-150 ease-in-out",
|
||||
"[@starting-style]:scale-100 [@starting-style]:opacity-100",
|
||||
isExpanded ? "scale-95 opacity-0" : "scale-100 opacity-100",
|
||||
)}
|
||||
>
|
||||
hover to expand
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Expanded Content */}
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden [interpolate-size:allow-keywords] [transition-behavior:allow-discrete]",
|
||||
"transition-[height,opacity,display] duration-200 ease-in-out",
|
||||
"[@starting-style]:h-0 [@starting-style]:opacity-0",
|
||||
isExpanded ? "block h-[calc-size(auto)] opacity-100" : "hidden h-0 opacity-0",
|
||||
)}
|
||||
aria-hidden={!isExpanded}
|
||||
data-state={isExpanded ? "open" : "closed"}
|
||||
>
|
||||
<ScrollArea focusable={false} viewportProps={{ style: { maxHeight: expandedMaxHeight } }}>
|
||||
<div className="border-t border-red/20 bg-red/5 px-3 pb-3">
|
||||
<div className="mt-2 cursor-text select-text break-all rounded-md bg-red/10 p-3 text-xs leading-relaxed text-red/80">
|
||||
{displayMessage as string}
|
||||
</div>
|
||||
{contextualInfo && (
|
||||
<div className="mt-3 rounded-md border border-red/10 bg-red/5 p-3">
|
||||
{contextualInfo}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+91
@@ -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<RateLimitNoticeProps> = ({ 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 (
|
||||
<m.div
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className={cn("mb-3", className)}
|
||||
>
|
||||
<div className="flex items-center gap-2 rounded-lg border border-border bg-fill/50 px-3 py-2 backdrop-blur-sm">
|
||||
<i className="i-mgc-information-cute-re size-4 flex-shrink-0 text-text-tertiary" />
|
||||
<span className="min-w-0 flex-1 truncate text-xs text-text-secondary">
|
||||
{buildMessage()}
|
||||
</span>
|
||||
</div>
|
||||
</m.div>
|
||||
)
|
||||
}
|
||||
@@ -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<ErrorMessageProps> = ({ 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 (
|
||||
<m.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={Spring.presets.smooth}
|
||||
className={cn("group mb-4 flex justify-start", className)}
|
||||
>
|
||||
<div className="relative flex max-w-full flex-col text-text">
|
||||
{/* Main error message bubble - similar to AI message style */}
|
||||
<div className="rounded-2xl border border-border bg-fill/50 px-4 py-3">
|
||||
<div className="flex flex-col gap-2">
|
||||
{/* Header with subtle icon */}
|
||||
<div className="flex items-center gap-2">
|
||||
<i className="i-mgc-information-cute-re size-4 text-text-tertiary" />
|
||||
<span className="text-xs font-medium text-text-secondary">{getErrorTitle()}</span>
|
||||
</div>
|
||||
|
||||
{/* Error message - always visible but subtle */}
|
||||
<div className="cursor-text select-text text-sm leading-relaxed text-text-secondary">
|
||||
{displayMessage}
|
||||
</div>
|
||||
|
||||
{/* Contextual info if exists */}
|
||||
{contextualInfo && (
|
||||
<div className="mt-1 space-y-1.5 rounded-lg border border-border/50 bg-fill-secondary/30 p-2.5">
|
||||
{contextualInfo}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</m.div>
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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) {
|
||||
)}
|
||||
|
||||
<div ref={bottomPanelRef} className={"px-6"}>
|
||||
{error && <CollapsibleError error={error} />}
|
||||
{hasRateLimitError && error && <RateLimitNotice error={error} />}
|
||||
<ChatInput
|
||||
ref={inputRef}
|
||||
onSend={handleSendMessage}
|
||||
|
||||
Reference in New Issue
Block a user