📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
AI chat history
Blue Mouse1f67ba33a49a
diff --git a/backend/apps/cloud/src/ai/ai-chat.service.ts b/backend/apps/cloud/src/ai/ai-chat.service.tsnew file mode 100644index 000000000..c6aeaa05c--- /dev/null+++ b/backend/apps/cloud/src/ai/ai-chat.service.ts@@ -0,0 +1,134 @@+import { Injectable } from '@nestjs/common'+import { InjectRepository } from '@nestjs/typeorm'+import { Repository, FindManyOptions, FindOneOptions } from 'typeorm'+import { AiChat, ChatMessage } from './entity/ai-chat.entity'++@Injectable()+export class AiChatService {+ constructor(+ @InjectRepository(AiChat)+ private aiChatRepository: Repository<AiChat>,+ ) {}++ async findOne(options: FindOneOptions<AiChat>): Promise<AiChat | null> {+ return this.aiChatRepository.findOne(options)+ }++ async find(options: FindManyOptions<AiChat>): Promise<AiChat[]> {+ return this.aiChatRepository.find(options)+ }++ async findRecentByProject(+ projectId: string,+ userId: string | null,+ limit: number = 5,+ ): Promise<AiChat[]> {+ const queryBuilder = this.aiChatRepository+ .createQueryBuilder('chat')+ .where('chat.projectId = :projectId', { projectId })+ .orderBy('chat.updated', 'DESC')+ .take(limit)++ if (userId) {+ queryBuilder.andWhere('(chat.userId = :userId OR chat.userId IS NULL)', {+ userId,+ })+ }++ return queryBuilder.getMany()+ }++ async findAllByProject(+ projectId: string,+ userId: string | null,+ skip: number = 0,+ take: number = 20,+ ): Promise<{ chats: AiChat[]; total: number }> {+ const queryBuilder = this.aiChatRepository+ .createQueryBuilder('chat')+ .where('chat.projectId = :projectId', { projectId })+ .orderBy('chat.updated', 'DESC')+ .skip(skip)+ .take(take)++ if (userId) {+ queryBuilder.andWhere('(chat.userId = :userId OR chat.userId IS NULL)', {+ userId,+ })+ }++ const [chats, total] = await queryBuilder.getManyAndCount()+ return { chats, total }+ }++ async create(data: {+ projectId: string+ userId: string | null+ messages: ChatMessage[]+ name?: string+ }): Promise<AiChat> {+ const chat = this.aiChatRepository.create({+ project: { id: data.projectId },+ user: data.userId ? { id: data.userId } : null,+ messages: data.messages,+ name: data.name || this.generateChatName(data.messages),+ })+ return this.aiChatRepository.save(chat)+ }++ async update(+ id: string,+ data: { messages?: ChatMessage[]; name?: string },+ ): Promise<AiChat | null> {+ const chat = await this.aiChatRepository.findOne({ where: { id } })+ if (!chat) return null++ if (data.messages) {+ chat.messages = data.messages+ // Update name if not manually set and we have a new first user message+ if (!chat.name || chat.name === this.generateChatName(chat.messages)) {+ chat.name = this.generateChatName(data.messages)+ }+ }+ if (data.name !== undefined) {+ chat.name = data.name+ }++ return this.aiChatRepository.save(chat)+ }++ async delete(id: string): Promise<boolean> {+ const result = await this.aiChatRepository.delete(id)+ return (result.affected ?? 0) > 0+ }++ private generateChatName(messages: ChatMessage[]): string {+ // Use the first user message as the chat name+ const firstUserMessage = messages.find(m => m.role === 'user')+ if (firstUserMessage) {+ const content = firstUserMessage.content.trim()+ // Truncate to reasonable length+ return content.length > 100 ? content.slice(0, 97) + '...' : content+ }+ return 'New conversation'+ }++ async verifyAccess(+ chatId: string,+ projectId: string,+ userId: string | null,+ ): Promise<AiChat | null> {+ const queryBuilder = this.aiChatRepository+ .createQueryBuilder('chat')+ .where('chat.id = :chatId', { chatId })+ .andWhere('chat.projectId = :projectId', { projectId })++ if (userId) {+ queryBuilder.andWhere('(chat.userId = :userId OR chat.userId IS NULL)', {+ userId,+ })+ }++ return queryBuilder.getOne()+ }+}diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.tsindex 836c60f14..299cba99b 100644--- a/backend/apps/cloud/src/ai/ai.controller.ts+++ b/backend/apps/cloud/src/ai/ai.controller.ts@@ -1,8 +1,11 @@import {Controller,Post,+ Get,+ Delete,Body,Param,+ Query,Res,NotFoundException,ForbiddenException,@@ -15,6 +18,7 @@ import {ApiBearerAuth,ApiResponse,ApiOperation,+ ApiQuery,} from '@nestjs/swagger'import _isEmpty from 'lodash/isEmpty'@@ -23,13 +27,15 @@ import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'import { ProjectService } from '../project/project.service'import { AppLoggerService } from '../logger/logger.service'import { AiService } from './ai.service'-import { ChatDto } from './dto/chat.dto'+import { AiChatService } from './ai-chat.service'+import { ChatDto, CreateChatDto, UpdateChatDto } from './dto/chat.dto'@ApiTags('AI')@Controller(['ai', 'v1/ai'])export class AiController {constructor(private readonly aiService: AiService,+ private readonly aiChatService: AiChatService,private readonly projectService: ProjectService,private readonly logger: AppLoggerService,) {}@@ -215,4 +221,227 @@ export class AiController {res.end()}}++ @ApiBearerAuth()+ @Get(':pid/chats')+ @Auth()+ @ApiOperation({ summary: 'Get recent AI chats for a project' })+ @ApiQuery({ name: 'limit', required: false, type: Number })+ @ApiResponse({ status: 200, description: 'List of recent chats' })+ async getRecentChats(+ @Param('pid') pid: string,+ @Query('limit') limit: string,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ uid, pid }, 'GET /ai/:pid/chats')++ const project = await this.projectService.getFullProject(pid)++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToView(project, uid)++ const chats = await this.aiChatService.findRecentByProject(+ pid,+ uid,+ limit ? parseInt(limit, 10) : 5,+ )++ return chats.map(chat => ({+ id: chat.id,+ name: chat.name,+ created: chat.created,+ updated: chat.updated,+ }))+ }++ @ApiBearerAuth()+ @Get(':pid/chats/all')+ @Auth()+ @ApiOperation({ summary: 'Get all AI chats for a project (paginated)' })+ @ApiQuery({ name: 'skip', required: false, type: Number })+ @ApiQuery({ name: 'take', required: false, type: Number })+ @ApiResponse({ status: 200, description: 'Paginated list of chats' })+ async getAllChats(+ @Param('pid') pid: string,+ @Query('skip') skip: string,+ @Query('take') take: string,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ uid, pid }, 'GET /ai/:pid/chats/all')++ const project = await this.projectService.getFullProject(pid)++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToView(project, uid)++ const result = await this.aiChatService.findAllByProject(+ pid,+ uid,+ skip ? parseInt(skip, 10) : 0,+ take ? parseInt(take, 10) : 20,+ )++ return {+ chats: result.chats.map(chat => ({+ id: chat.id,+ name: chat.name,+ created: chat.created,+ updated: chat.updated,+ })),+ total: result.total,+ }+ }++ @ApiBearerAuth()+ @Get(':pid/chats/:chatId')+ @Auth()+ @ApiOperation({ summary: 'Get a specific AI chat' })+ @ApiResponse({ status: 200, description: 'Chat details with messages' })+ async getChat(+ @Param('pid') pid: string,+ @Param('chatId') chatId: string,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ uid, pid, chatId }, 'GET /ai/:pid/chats/:chatId')++ const project = await this.projectService.getFullProject(pid)++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToView(project, uid)++ const chat = await this.aiChatService.verifyAccess(chatId, pid, uid)++ if (!chat) {+ throw new NotFoundException('Chat not found')+ }++ return {+ id: chat.id,+ name: chat.name,+ messages: chat.messages,+ created: chat.created,+ updated: chat.updated,+ }+ }++ @ApiBearerAuth()+ @Post(':pid/chats')+ @Auth()+ @ApiOperation({ summary: 'Create a new AI chat' })+ @ApiResponse({ status: 201, description: 'Chat created' })+ async createChat(+ @Param('pid') pid: string,+ @Body() createChatDto: CreateChatDto,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ uid, pid }, 'POST /ai/:pid/chats')++ const project = await this.projectService.getFullProject(pid)++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToView(project, uid)++ const chat = await this.aiChatService.create({+ projectId: pid,+ userId: uid,+ messages: createChatDto.messages,+ name: createChatDto.name,+ })++ return {+ id: chat.id,+ name: chat.name,+ messages: chat.messages,+ created: chat.created,+ updated: chat.updated,+ }+ }++ @ApiBearerAuth()+ @Post(':pid/chats/:chatId')+ @Auth()+ @ApiOperation({ summary: 'Update an AI chat' })+ @ApiResponse({ status: 200, description: 'Chat updated' })+ async updateChat(+ @Param('pid') pid: string,+ @Param('chatId') chatId: string,+ @Body() updateChatDto: UpdateChatDto,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ uid, pid, chatId }, 'POST /ai/:pid/chats/:chatId')++ const project = await this.projectService.getFullProject(pid)++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToView(project, uid)++ const existingChat = await this.aiChatService.verifyAccess(chatId, pid, uid)++ if (!existingChat) {+ throw new NotFoundException('Chat not found')+ }++ const chat = await this.aiChatService.update(chatId, {+ messages: updateChatDto.messages,+ name: updateChatDto.name,+ })++ if (!chat) {+ throw new NotFoundException('Chat not found')+ }++ return {+ id: chat.id,+ name: chat.name,+ messages: chat.messages,+ created: chat.created,+ updated: chat.updated,+ }+ }++ @ApiBearerAuth()+ @Delete(':pid/chats/:chatId')+ @Auth()+ @ApiOperation({ summary: 'Delete an AI chat' })+ @ApiResponse({ status: 200, description: 'Chat deleted' })+ async deleteChat(+ @Param('pid') pid: string,+ @Param('chatId') chatId: string,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ uid, pid, chatId }, 'DELETE /ai/:pid/chats/:chatId')++ const project = await this.projectService.getFullProject(pid)++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToView(project, uid)++ const existingChat = await this.aiChatService.verifyAccess(chatId, pid, uid)++ if (!existingChat) {+ throw new NotFoundException('Chat not found')+ }++ await this.aiChatService.delete(chatId)++ return { success: true }+ }}diff --git a/backend/apps/cloud/src/ai/ai.module.ts b/backend/apps/cloud/src/ai/ai.module.tsindex cdda34cb7..a38a43f92 100644--- a/backend/apps/cloud/src/ai/ai.module.ts+++ b/backend/apps/cloud/src/ai/ai.module.ts@@ -1,15 +1,24 @@import { Module } from '@nestjs/common'+import { TypeOrmModule } from '@nestjs/typeorm'import { ProjectModule } from '../project/project.module'import { AppLoggerModule } from '../logger/logger.module'import { AnalyticsModule } from '../analytics/analytics.module'import { GoalModule } from '../goal/goal.module'import { AiService } from './ai.service'+import { AiChatService } from './ai-chat.service'import { AiController } from './ai.controller'+import { AiChat } from './entity/ai-chat.entity'@Module({- imports: [ProjectModule, AppLoggerModule, AnalyticsModule, GoalModule],- providers: [AiService],+ imports: [+ TypeOrmModule.forFeature([AiChat]),+ ProjectModule,+ AppLoggerModule,+ AnalyticsModule,+ GoalModule,+ ],+ providers: [AiService, AiChatService],controllers: [AiController],})export class AiModule {}diff --git a/backend/apps/cloud/src/ai/dto/chat.dto.ts b/backend/apps/cloud/src/ai/dto/chat.dto.tsindex 5f6f529b1..b2e29f3ec 100644--- a/backend/apps/cloud/src/ai/dto/chat.dto.ts+++ b/backend/apps/cloud/src/ai/dto/chat.dto.ts@@ -43,4 +43,52 @@ export class ChatDto {@IsOptional()@IsString()timezone?: string++ @ApiProperty({+ required: false,+ description: 'Chat ID to continue an existing conversation',+ })+ @IsOptional()+ @IsString()+ chatId?: string+}++export class CreateChatDto {+ @ApiProperty({+ type: [ChatMessageDto],+ description: 'Array of chat messages',+ })+ @IsArray()+ @ValidateNested({ each: true })+ @Type(() => ChatMessageDto)+ messages: ChatMessageDto[]++ @ApiProperty({+ required: false,+ description: 'Custom name for the chat',+ })+ @IsOptional()+ @IsString()+ name?: string+}++export class UpdateChatDto {+ @ApiProperty({+ type: [ChatMessageDto],+ required: false,+ description: 'Array of chat messages',+ })+ @IsOptional()+ @IsArray()+ @ValidateNested({ each: true })+ @Type(() => ChatMessageDto)+ messages?: ChatMessageDto[]++ @ApiProperty({+ required: false,+ description: 'Custom name for the chat',+ })+ @IsOptional()+ @IsString()+ name?: string}diff --git a/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts b/backend/apps/cloud/src/ai/entity/ai-chat.entity.tsnew file mode 100644index 000000000..c4d3651f3--- /dev/null+++ b/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts@@ -0,0 +1,50 @@+import {+ Column,+ CreateDateColumn,+ Entity,+ JoinColumn,+ ManyToOne,+ PrimaryGeneratedColumn,+ UpdateDateColumn,+} from 'typeorm'+import { ApiProperty } from '@nestjs/swagger'+import { Project } from '../../project/entity/project.entity'+import { User } from '../../user/entities/user.entity'++export interface ChatMessage {+ role: 'user' | 'assistant'+ content: string+}++@Entity('ai_chat')+export class AiChat {+ @ApiProperty()+ @PrimaryGeneratedColumn('uuid')+ id: string++ @ApiProperty()+ @Column('varchar', { length: 200, nullable: true })+ name: string | null++ @ApiProperty()+ @Column('json')+ messages: ChatMessage[]++ @ApiProperty({ type: () => Project })+ @ManyToOne(() => Project, { onDelete: 'CASCADE' })+ @JoinColumn()+ project: Project++ @ApiProperty({ type: () => User })+ @ManyToOne(() => User, { nullable: true, onDelete: 'CASCADE' })+ @JoinColumn()+ user: User | null++ @ApiProperty()+ @CreateDateColumn()+ created: Date++ @ApiProperty()+ @UpdateDateColumn()+ updated: Date+}diff --git a/backend/migrations/mysql/2025_12_07_ai_chat.sql b/backend/migrations/mysql/2025_12_07_ai_chat.sqlnew file mode 100644index 000000000..b076e8229--- /dev/null+++ b/backend/migrations/mysql/2025_12_07_ai_chat.sql@@ -0,0 +1,16 @@+-- AI Chat history table+CREATE TABLE IF NOT EXISTS `ai_chat` (+ `id` varchar(36) NOT NULL,+ `name` varchar(200) DEFAULT NULL,+ `messages` json NOT NULL,+ `created` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ `updated` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),+ `projectId` varchar(12) NOT NULL,+ `userId` varchar(36) DEFAULT NULL,+ PRIMARY KEY (`id`),+ KEY `idx_ai_chat_project` (`projectId`),+ KEY `idx_ai_chat_user` (`userId`),+ KEY `idx_ai_chat_updated` (`updated`),+ FOREIGN KEY (`projectId`) REFERENCES `project` (`id`) ON DELETE CASCADE,+ FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 9735455a8..d7f967d8f 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -1904,3 +1904,93 @@ export const askAI = async (callbacks.onError(error as Error)}}++// AI Chat History API+export interface AIChatSummary {+ id: string+ name: string | null+ created: string+ updated: string+}++export interface AIChat extends AIChatSummary {+ messages: AIChatMessage[]+}++export const getRecentAIChats = async (pid: string, limit: number = 5): Promise<AIChatSummary[]> => {+ return api+ .get(`ai/${pid}/chats`, {+ params: { limit },+ headers: { Authorization: getAccessToken() ? `Bearer ${getAccessToken()}` : '' },+ })+ .then((response): AIChatSummary[] => response.data)+ .catch((error) => {+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message+ })+}++export const getAllAIChats = async (+ pid: string,+ skip: number = 0,+ take: number = 20,+): Promise<{ chats: AIChatSummary[]; total: number }> => {+ return api+ .get(`ai/${pid}/chats/all`, {+ params: { skip, take },+ headers: { Authorization: getAccessToken() ? `Bearer ${getAccessToken()}` : '' },+ })+ .then((response): { chats: AIChatSummary[]; total: number } => response.data)+ .catch((error) => {+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message+ })+}++export const getAIChat = async (pid: string, chatId: string): Promise<AIChat> => {+ return api+ .get(`ai/${pid}/chats/${chatId}`, {+ headers: { Authorization: getAccessToken() ? `Bearer ${getAccessToken()}` : '' },+ })+ .then((response): AIChat => response.data)+ .catch((error) => {+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message+ })+}++export const createAIChat = async (pid: string, messages: AIChatMessage[], name?: string): Promise<AIChat> => {+ return api+ .post(+ `ai/${pid}/chats`,+ { messages, name },+ { headers: { Authorization: getAccessToken() ? `Bearer ${getAccessToken()}` : '' } },+ )+ .then((response): AIChat => response.data)+ .catch((error) => {+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message+ })+}++export const updateAIChat = async (+ pid: string,+ chatId: string,+ data: { messages?: AIChatMessage[]; name?: string },+): Promise<AIChat> => {+ return api+ .post(`ai/${pid}/chats/${chatId}`, data, {+ headers: { Authorization: getAccessToken() ? `Bearer ${getAccessToken()}` : '' },+ })+ .then((response): AIChat => response.data)+ .catch((error) => {+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message+ })+}++export const deleteAIChat = async (pid: string, chatId: string): Promise<{ success: boolean }> => {+ return api+ .delete(`ai/${pid}/chats/${chatId}`, {+ headers: { Authorization: getAccessToken() ? `Bearer ${getAccessToken()}` : '' },+ })+ .then((response): { success: boolean } => response.data)+ .catch((error) => {+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message+ })+}diff --git a/web/app/pages/Project/AskAI/AskAIView.tsx b/web/app/pages/Project/AskAI/AskAIView.tsxindex 33bd9c86d..e8636c912 100644--- a/web/app/pages/Project/AskAI/AskAIView.tsx+++ b/web/app/pages/Project/AskAI/AskAIView.tsx@@ -14,15 +14,30 @@ import {GitBranchIcon,InfoIcon,CheckIcon,+ MessageSquareIcon,+ PlusIcon,+ TrashIcon,} from 'lucide-react'import { marked } from 'marked'-import React, { useState, useRef, useEffect, useMemo } from 'react'+import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react'import { useTranslation } from 'react-i18next'+import { useSearchParams } from 'react-router'import sanitizeHtml from 'sanitize-html'+import { toast } from 'sonner'import { useStickToBottom } from 'use-stick-to-bottom'-import { askAI } from '~/api'+import {+ askAI,+ getRecentAIChats,+ getAllAIChats,+ getAIChat,+ createAIChat,+ updateAIChat,+ deleteAIChat,+ AIChatSummary,+} from '~/api'import SwetrixLogo from '~/ui/icons/SwetrixLogo'+import Modal from '~/ui/Modal'import Tooltip from '~/ui/Tooltip'import AIChart from './AIChart'@@ -394,6 +409,7 @@ const QUICK_ACTIONS = [const AskAIView = ({ projectId }: AskAIViewProps) => {const { t } = useTranslation('common')+ const [searchParams, setSearchParams] = useSearchParams()const [messages, setMessages] = useState<Message[]>([])const [input, setInput] = useState('')const [isLoading, setIsLoading] = useState(false)@@ -403,6 +419,16 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {const inputRef = useRef<HTMLTextAreaElement>(null)const abortControllerRef = useRef<AbortController | null>(null)+ // Chat history state+ const [currentChatId, setCurrentChatId] = useState<string | null>(null)+ const [recentChats, setRecentChats] = useState<AIChatSummary[]>([])+ const [allChats, setAllChats] = useState<AIChatSummary[]>([])+ const [allChatsTotal, setAllChatsTotal] = useState(0)+ const [isLoadingChats, setIsLoadingChats] = useState(false)+ const [isViewAllModalOpen, setIsViewAllModalOpen] = useState(false)+ const [chatToDelete, setChatToDelete] = useState<string | null>(null)+ const hasInitializedRef = useRef(false)+// Stick to bottom hook for chat auto-scrollconst { scrollRef, contentRef, isAtBottom, scrollToBottom } = useStickToBottom({resize: 'smooth',@@ -416,6 +442,147 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {const generateMessageId = () => `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`+ // Load recent chats+ const loadRecentChats = useCallback(async () => {+ try {+ const chats = await getRecentAIChats(projectId, 3)+ setRecentChats(chats)+ } catch (err) {+ console.error('Failed to load recent chats:', err)+ }+ }, [projectId])++ // Load all chats for modal+ const loadAllChats = useCallback(+ async (skip: number = 0) => {+ setIsLoadingChats(true)+ try {+ const result = await getAllAIChats(projectId, skip, 20)+ if (skip === 0) {+ setAllChats(result.chats)+ } else {+ setAllChats((prev) => [...prev, ...result.chats])+ }+ setAllChatsTotal(result.total)+ } catch (err) {+ console.error('Failed to load all chats:', err)+ } finally {+ setIsLoadingChats(false)+ }+ },+ [projectId],+ )++ // Load a specific chat+ const loadChat = useCallback(+ async (chatId: string) => {+ try {+ const chat = await getAIChat(projectId, chatId)+ setMessages(+ chat.messages.map((m) => ({+ id: generateMessageId(),+ role: m.role,+ content: m.content,+ })),+ )+ setCurrentChatId(chatId)+ } catch (err) {+ console.error('Failed to load chat:', err)+ // If chat not found, clear the param and start fresh+ const newParams = new URLSearchParams(searchParams)+ newParams.delete('chat')+ setSearchParams(newParams)+ }+ },+ [projectId, searchParams, setSearchParams],+ )++ // Save or update chat+ const saveChat = useCallback(+ async (messagesToSave: Message[]) => {+ const apiMessages = messagesToSave+ .filter((m) => m.content.trim().length > 0)+ .map((m) => ({+ role: m.role,+ content: m.content,+ }))++ if (apiMessages.length === 0) return++ try {+ if (currentChatId) {+ await updateAIChat(projectId, currentChatId, { messages: apiMessages })+ } else {+ const chat = await createAIChat(projectId, apiMessages)+ setCurrentChatId(chat.id)+ const newParams = new URLSearchParams(searchParams)+ newParams.set('chat', chat.id)+ setSearchParams(newParams, { replace: true })+ }+ // Refresh recent chats+ loadRecentChats()+ } catch (err) {+ console.error('Failed to save chat:', err)+ }+ },+ [projectId, currentChatId, searchParams, setSearchParams, loadRecentChats],+ )++ // Initialize: load chat from URL or load recent chats+ useEffect(() => {+ if (hasInitializedRef.current) return+ hasInitializedRef.current = true++ const chatId = searchParams.get('chat')+ if (chatId) {+ loadChat(chatId)+ }+ loadRecentChats()+ }, [searchParams, loadChat, loadRecentChats])++ // Start a new chat+ const handleNewChat = () => {+ setMessages([])+ setCurrentChatId(null)+ setStreamingMessage(null)+ setError(null)+ const newParams = new URLSearchParams(searchParams)+ newParams.delete('chat')+ setSearchParams(newParams)+ }++ // Open a chat from history+ const handleOpenChat = (chatId: string) => {+ setIsViewAllModalOpen(false)+ loadChat(chatId)+ const newParams = new URLSearchParams(searchParams)+ newParams.set('chat', chatId)+ setSearchParams(newParams)+ }++ // Delete a chat+ const handleDeleteChat = async (chatId: string) => {+ try {+ await deleteAIChat(projectId, chatId)+ toast.success(t('askAi.chatDeleted'))++ // If we're deleting the current chat, start fresh+ if (chatId === currentChatId) {+ handleNewChat()+ }++ // Refresh lists+ loadRecentChats()+ if (isViewAllModalOpen) {+ loadAllChats(0)+ }+ } catch (err) {+ console.error('Failed to delete chat:', err)+ } finally {+ setChatToDelete(null)+ }+ }+const handleSubmit = async (e?: React.FormEvent) => {e?.preventDefault()if (!input.trim() || isLoading) return@@ -492,16 +659,19 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {onComplete: () => {const finalContent = streamingContentRef.currentif (finalContent.trim() || streamingToolCallsRef.current.length > 0) {- setMessages((prev) => [- ...prev,- {- id: generateMessageId(),- role: 'assistant',- content: finalContent,- reasoning: streamingReasoningRef.current,- toolCalls: streamingToolCallsRef.current,- },- ])+ const assistantMessage: Message = {+ id: generateMessageId(),+ role: 'assistant',+ content: finalContent,+ reasoning: streamingReasoningRef.current,+ toolCalls: streamingToolCallsRef.current,+ }+ setMessages((prev) => {+ const updatedMessages = [...prev, assistantMessage]+ // Save chat after completion+ saveChat(updatedMessages)+ return updatedMessages+ })}setStreamingMessage(null)setIsLoading(false)@@ -532,16 +702,18 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {setIsWaitingForResponse(false)const finalContent = streamingContentRef.currentif (finalContent.trim()) {- setMessages((prev) => [- ...prev,- {- id: generateMessageId(),- role: 'assistant',- content: finalContent,- reasoning: streamingReasoningRef.current,- toolCalls: streamingToolCallsRef.current,- },- ])+ const assistantMessage: Message = {+ id: generateMessageId(),+ role: 'assistant',+ content: finalContent,+ reasoning: streamingReasoningRef.current,+ toolCalls: streamingToolCallsRef.current,+ }+ setMessages((prev) => {+ const updatedMessages = [...prev, assistantMessage]+ saveChat(updatedMessages)+ return updatedMessages+ })}setStreamingMessage(null)}@@ -572,6 +744,22 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {const isEmpty = _isEmpty(messages) && !streamingMessage+ // Format relative time+ const formatRelativeTime = (dateStr: string) => {+ const date = new Date(dateStr)+ const now = new Date()+ const diffMs = now.getTime() - date.getTime()+ const diffMins = Math.floor(diffMs / 60000)+ const diffHours = Math.floor(diffMs / 3600000)+ const diffDays = Math.floor(diffMs / 86400000)++ if (diffMins < 1) return 'Just now'+ if (diffMins < 60) return `${diffMins}m`+ if (diffHours < 24) return `${diffHours}h`+ if (diffDays < 7) return `${diffDays}d`+ return date.toLocaleDateString()+ }+return (<div className='flex h-[calc(100vh-200px)] min-h-[600px] flex-col bg-gray-50 dark:bg-slate-900'>{/* Error Banner */}@@ -668,6 +856,45 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {))}</div></div>++ {/* Recent Chats Section */}+ {!_isEmpty(recentChats) ? (+ <div className='mt-12 w-full max-w-2xl'>+ <div className='flex items-center justify-between'>+ <h3 className='text-sm font-medium text-gray-700 dark:text-gray-300'>{t('askAi.recentChats')}</h3>+ <button+ type='button'+ onClick={() => {+ setIsViewAllModalOpen(true)+ loadAllChats(0)+ }}+ className='text-sm font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300'+ >+ {t('askAi.viewAll')}+ </button>+ </div>+ <div className='mt-3 space-y-2'>+ {_map(recentChats, (chat) => (+ <button+ key={chat.id}+ type='button'+ onClick={() => handleOpenChat(chat.id)}+ className='flex w-full items-center justify-between rounded-lg border border-gray-200 bg-white px-4 py-3 text-left transition-colors hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:hover:bg-slate-700'+ >+ <div className='flex items-center gap-3 overflow-hidden'>+ <MessageSquareIcon className='h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500' />+ <span className='truncate text-sm text-gray-900 dark:text-white'>+ {chat.name || t('askAi.newChat')}+ </span>+ </div>+ <span className='ml-2 shrink-0 text-xs text-gray-500 dark:text-gray-400'>+ {formatRelativeTime(chat.updated)}+ </span>+ </button>+ ))}+ </div>+ </div>+ ) : null}</div>) : (<div className='mx-auto max-w-3xl space-y-6 px-4 py-6'>@@ -746,6 +973,97 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {</div></div>) : null}++ {/* New Chat Button (floating) */}+ {!isEmpty ? (+ <button+ type='button'+ onClick={handleNewChat}+ className='fixed right-6 bottom-32 z-20 flex h-10 w-10 items-center justify-center rounded-full bg-indigo-600 text-white shadow-lg transition-colors hover:bg-indigo-700 dark:bg-indigo-500 dark:hover:bg-indigo-600'+ aria-label={t('askAi.newChat')}+ >+ <PlusIcon className='h-5 w-5' />+ </button>+ ) : null}++ {/* View All Chats Modal */}+ <Modal+ isOpened={isViewAllModalOpen}+ onClose={() => setIsViewAllModalOpen(false)}+ title={t('askAi.allChats')}+ size='medium'+ message={+ <div className='mt-2 max-h-96 overflow-y-auto'>+ {_isEmpty(allChats) && !isLoadingChats ? (+ <p className='py-8 text-center text-gray-500 dark:text-gray-400'>{t('askAi.noChats')}</p>+ ) : (+ <div className='space-y-2'>+ {_map(allChats, (chat) => (+ <div+ key={chat.id}+ className='flex items-center justify-between rounded-lg border border-gray-200 bg-white px-4 py-3 transition-colors hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:hover:bg-slate-700'+ >+ <button+ type='button'+ onClick={() => handleOpenChat(chat.id)}+ className='flex flex-1 items-center gap-3 overflow-hidden text-left'+ >+ <MessageSquareIcon className='h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500' />+ <div className='overflow-hidden'>+ <span className='block truncate text-sm text-gray-900 dark:text-white'>+ {chat.name || t('askAi.newChat')}+ </span>+ <span className='text-xs text-gray-500 dark:text-gray-400'>+ {formatRelativeTime(chat.updated)}+ </span>+ </div>+ </button>+ <button+ type='button'+ onClick={(e) => {+ e.stopPropagation()+ setChatToDelete(chat.id)+ }}+ className='ml-2 rounded p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-red-500 dark:hover:bg-slate-600 dark:hover:text-red-400'+ aria-label={t('askAi.deleteChat')}+ >+ <TrashIcon className='h-4 w-4' />+ </button>+ </div>+ ))}+ {allChats.length < allChatsTotal ? (+ <button+ type='button'+ onClick={() => loadAllChats(allChats.length)}+ disabled={isLoadingChats}+ className='flex w-full items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50 disabled:opacity-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-300 dark:hover:bg-slate-700'+ >+ {isLoadingChats ? <Loader2Icon className='h-4 w-4 animate-spin' /> : null}+ Load more+ </button>+ ) : null}+ </div>+ )}+ {isLoadingChats && _isEmpty(allChats) ? (+ <div className='flex items-center justify-center py-8'>+ <Loader2Icon className='h-6 w-6 animate-spin text-gray-400' />+ </div>+ ) : null}+ </div>+ }+ />++ {/* Delete Chat Confirmation Modal */}+ <Modal+ isOpened={!!chatToDelete}+ onClose={() => setChatToDelete(null)}+ onSubmit={() => chatToDelete && handleDeleteChat(chatToDelete)}+ title={t('askAi.deleteChat')}+ message={t('askAi.deleteChatConfirm')}+ submitText={t('common.delete')}+ closeText={t('common.cancel')}+ submitType='danger'+ /></div>)}diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 6a5ce6039..7b0646100 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -1751,6 +1751,14 @@"suggestion2": "How is my traffic trending?","suggestion3": "Where are my visitors from?","error": "Sorry, something went wrong. Please try again.",- "disclaimer": "AI responses may not always be accurate. Verify important data."+ "disclaimer": "AI responses may not always be accurate. Verify important data.",+ "recentChats": "Recent chats",+ "viewAll": "View all",+ "allChats": "All chats",+ "noChats": "No chat history yet",+ "newChat": "New conversation",+ "deleteChat": "Delete chat",+ "deleteChatConfirm": "Are you sure you want to delete this chat?",+ "chatDeleted": "Chat deleted"}}