Skip to content

📈 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!

Better chat history & pinned chats support

Blue Mouseed7a7cbefdde
diff --git a/backend/apps/cloud/src/ai/ai-chat.service.ts b/backend/apps/cloud/src/ai/ai-chat.service.ts
index b03e079e6..0c87942c1 100644
--- a/backend/apps/cloud/src/ai/ai-chat.service.ts
+++ b/backend/apps/cloud/src/ai/ai-chat.service.ts
@@ -2,6 +2,15 @@ import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, FindManyOptions, FindOneOptions } from 'typeorm'
import { AiChat, ChatMessage } from './entity/ai-chat.entity'
+import { MAX_TAGS_PER_CHAT, MAX_TAG_LENGTH } from './dto/chat.dto'
+
+interface ListChatsOptions {
+ search?: string
+ tag?: string
+ pinned?: boolean
+ skip?: number
+ take?: number
+}
@Injectable()
export class AiChatService {
@@ -31,32 +40,122 @@ export class AiChatService {
.createQueryBuilder('chat')
.where('chat.projectId = :projectId', { projectId })
.andWhere('chat.userId = :userId', { userId })
- .orderBy('chat.updated', 'DESC')
+ .orderBy('chat.pinned', 'DESC')
+ .addOrderBy('chat.updated', 'DESC')
.take(limit)
return queryBuilder.getMany()
}
- async findAllByProject(
+ async listByProject(
projectId: string,
userId: string | null,
- skip: number = 0,
- take: number = 20,
+ options: ListChatsOptions = {},
): Promise<{ chats: AiChat[]; total: number }> {
if (!userId) {
return { chats: [], total: 0 }
}
- const queryBuilder = this.aiChatRepository
+ const { search, tag, pinned, skip = 0, take = 20 } = options
+
+ const baseQuery = () =>
+ this.aiChatRepository
+ .createQueryBuilder('chat')
+ .where('chat.projectId = :projectId', { projectId })
+ .andWhere('chat.userId = :userId', { userId })
+
+ const applyTagAndPinned = (qb: ReturnType<typeof baseQuery>) => {
+ if (typeof pinned === 'boolean') {
+ qb.andWhere('chat.pinned = :pinned', { pinned })
+ }
+ if (tag) {
+ // simple-array stores tags as a comma-separated string
+ qb.andWhere('(FIND_IN_SET(:tag, chat.tags) > 0 OR chat.tags = :tag)', {
+ tag,
+ })
+ }
+ return qb
+ }
+
+ const orderAndPaginate = (qb: ReturnType<typeof baseQuery>) =>
+ qb
+ .orderBy('chat.pinned', 'DESC')
+ .addOrderBy('chat.updated', 'DESC')
+ .skip(skip)
+ .take(take)
+
+ if (search && search.trim().length > 0) {
+ const term = `%${search.trim()}%`
+
+ const nameQb = applyTagAndPinned(baseQuery()).andWhere(
+ 'chat.name LIKE :term',
+ { term },
+ )
+
+ const [nameChats, nameTotal] =
+ await orderAndPaginate(nameQb).getManyAndCount()
+
+ if (nameTotal > 0) {
+ return { chats: nameChats, total: nameTotal }
+ }
+
+ // Fallback to content search across messages JSON
+ const contentQb = applyTagAndPinned(baseQuery()).andWhere(
+ 'CAST(chat.messages AS CHAR) LIKE :term',
+ { term },
+ )
+
+ const [contentChats, contentTotal] =
+ await orderAndPaginate(contentQb).getManyAndCount()
+ return { chats: contentChats, total: contentTotal }
+ }
+
+ const qb = orderAndPaginate(applyTagAndPinned(baseQuery()))
+ const [chats, total] = await qb.getManyAndCount()
+ return { chats, total }
+ }
+
+ /**
+ * @deprecated Use {@link listByProject} instead.
+ */
+ async findAllByProject(
+ projectId: string,
+ userId: string | null,
+ skip: number = 0,
+ take: number = 20,
+ ): Promise<{ chats: AiChat[]; total: number }> {
+ return this.listByProject(projectId, userId, { skip, take })
+ }
+
+ async listTagsByProject(
+ projectId: string,
+ userId: string | null,
+ ): Promise<string[]> {
+ if (!userId) return []
+
+ const rows = await this.aiChatRepository
.createQueryBuilder('chat')
+ .select('chat.tags', 'tags')
.where('chat.projectId = :projectId', { projectId })
.andWhere('chat.userId = :userId', { userId })
- .orderBy('chat.updated', 'DESC')
- .skip(skip)
- .take(take)
+ .andWhere('chat.tags IS NOT NULL')
+ .andWhere("chat.tags <> ''")
+ .getRawMany<{ tags: string | null }>()
- const [chats, total] = await queryBuilder.getManyAndCount()
- return { chats, total }
+ const set = new Set<string>()
+ for (const row of rows) {
+ if (!row.tags) continue
+ // simple-array is comma-separated
+ const parts = String(row.tags)
+ .split(',')
+ .map((t) => t.trim())
+ .filter(Boolean)
+ for (const p of parts) set.add(p)
+ }
+
+ return Array.from(set).sort((a, b) =>
+ a.localeCompare(b, undefined, { sensitivity: 'base' }),
+ )
}
async create(data: {
@@ -95,6 +194,52 @@ export class AiChatService {
return this.aiChatRepository.save(chat)
}
+ /**
+ * Sanitises a list of user-supplied tag labels:
+ * - trims, drops empty entries
+ * - enforces per-tag length cap
+ * - dedupes case-insensitively (keeping first occurrence)
+ * - caps total tags at MAX_TAGS_PER_CHAT
+ */
+ sanitiseTags(input: unknown): string[] {
+ if (!Array.isArray(input)) return []
+ const seen = new Set<string>()
+ const out: string[] = []
+ for (const raw of input) {
+ if (typeof raw !== 'string') continue
+ // simple-array uses comma as separator, so strip commas defensively
+ const trimmed = raw.replace(/,/g, '').trim().slice(0, MAX_TAG_LENGTH)
+ if (!trimmed) continue
+ const key = trimmed.toLowerCase()
+ if (seen.has(key)) continue
+ seen.add(key)
+ out.push(trimmed)
+ if (out.length >= MAX_TAGS_PER_CHAT) break
+ }
+ return out
+ }
+
+ async updateMeta(
+ id: string,
+ data: { pinned?: boolean; tags?: string[]; name?: string },
+ ): Promise<AiChat | null> {
+ const chat = await this.aiChatRepository.findOne({ where: { id } })
+ if (!chat) return null
+
+ if (typeof data.pinned === 'boolean') {
+ chat.pinned = data.pinned
+ }
+ if (data.tags !== undefined) {
+ chat.tags = this.sanitiseTags(data.tags)
+ }
+ if (data.name !== undefined) {
+ const trimmed = data.name.trim()
+ chat.name = trimmed.length > 0 ? trimmed : null
+ }
+
+ return this.aiChatRepository.save(chat)
+ }
+
async delete(id: string): Promise<boolean> {
const result = await this.aiChatRepository.delete(id)
return (result.affected ?? 0) > 0
diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.ts
index 2309d1fbb..b4e05a4b4 100644
--- a/backend/apps/cloud/src/ai/ai.controller.ts
+++ b/backend/apps/cloud/src/ai/ai.controller.ts
@@ -3,6 +3,7 @@ import {
Post,
Get,
Delete,
+ Patch,
Body,
Param,
Query,
@@ -12,6 +13,7 @@ import {
ForbiddenException,
HttpException,
HttpStatus,
+ ValidationPipe,
} from '@nestjs/common'
import { Response } from 'express'
import {
@@ -33,6 +35,7 @@ import {
ChatDto,
CreateChatDto,
UpdateChatDto,
+ UpdateChatMetaDto,
GetRecentChatsQueryDto,
GetAllChatsQueryDto,
FeedbackDto,
@@ -390,11 +393,15 @@ export class AiController {
@ApiBearerAuth()
@Get(':pid/chats')
@Auth(false, true) // Allow optional auth for public projects
- @ApiOperation({ summary: 'Get recent AI chats for a project' })
- @ApiResponse({ status: 200, description: 'List of recent chats' })
- async getRecentChats(
+ @ApiOperation({
+ summary:
+ 'List AI chats for a project (supports search, tag, pinned filters and pagination)',
+ })
+ @ApiResponse({ status: 200, description: 'List of chats' })
+ async getChats(
@Param('pid') pid: string,
- @Query() query: GetRecentChatsQueryDto,
+ @Query(new ValidationPipe({ transform: true, whitelist: true }))
+ query: GetRecentChatsQueryDto,
@CurrentUserId() uid: string | null,
@Headers() headers: Record<string, string>,
) {
@@ -412,31 +419,80 @@ export class AiController {
// Do not expose stored chat history to unauthenticated users (even on public projects).
if (!uid) {
- return []
+ return { chats: [], total: 0 }
}
- const chats = await this.aiChatService.findRecentByProject(
- pid,
- uid,
- query.limit ?? 5,
- )
+ const isLimitMode =
+ query.limit !== undefined &&
+ query.skip === undefined &&
+ query.take === undefined &&
+ !query.search &&
+ !query.tag &&
+ query.pinned === undefined
+
+ const take = isLimitMode ? (query.limit ?? 5) : (query.take ?? 20)
+
+ const result = await this.aiChatService.listByProject(pid, uid, {
+ search: query.search,
+ tag: query.tag,
+ pinned: query.pinned,
+ skip: query.skip ?? 0,
+ take,
+ })
- return chats.map((chat) => ({
- id: chat.id,
- name: chat.name,
- created: chat.created,
- updated: chat.updated,
- }))
+ return {
+ chats: result.chats.map((chat) => ({
+ id: chat.id,
+ name: chat.name,
+ pinned: chat.pinned,
+ tags: chat.tags ?? [],
+ created: chat.created,
+ updated: chat.updated,
+ })),
+ total: result.total,
+ }
+ }
+
+ @ApiBearerAuth()
+ @Get(':pid/chats/tags')
+ @Auth(false, true)
+ @ApiOperation({ summary: 'List distinct tags across the user’s chats' })
+ @ApiResponse({ status: 200, description: 'Sorted list of tag labels' })
+ async getChatTags(
+ @Param('pid') pid: string,
+ @CurrentUserId() uid: string | null,
+ @Headers() headers: Record<string, string>,
+ ) {
+ this.logger.log({ uid, pid }, 'GET /ai/:pid/chats/tags')
+
+ await this.applyRateLimit(uid, headers, 'read')
+
+ const project = await this.projectService.getFullProject(pid)
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+ this.projectService.allowedToView(project, uid)
+
+ if (!uid) {
+ return { tags: [] }
+ }
+
+ const tags = await this.aiChatService.listTagsByProject(pid, uid)
+ return { tags }
}
@ApiBearerAuth()
@Get(':pid/chats/all')
@Auth(false, true) // Allow optional auth for public projects
- @ApiOperation({ summary: 'Get all AI chats for a project (paginated)' })
+ @ApiOperation({
+ summary:
+ 'Get all AI chats for a project (paginated). Deprecated: use GET /:pid/chats with skip/take.',
+ })
@ApiResponse({ status: 200, description: 'Paginated list of chats' })
async getAllChats(
@Param('pid') pid: string,
- @Query() query: GetAllChatsQueryDto,
+ @Query(new ValidationPipe({ transform: true, whitelist: true }))
+ query: GetAllChatsQueryDto,
@CurrentUserId() uid: string | null,
@Headers() headers: Record<string, string>,
) {
@@ -452,22 +508,21 @@ export class AiController {
this.projectService.allowedToView(project, uid)
- // Do not expose stored chat history to unauthenticated users (even on public projects).
if (!uid) {
return { chats: [], total: 0 }
}
- const result = await this.aiChatService.findAllByProject(
- pid,
- uid,
- query.skip ?? 0,
- query.take ?? 20,
- )
+ const result = await this.aiChatService.listByProject(pid, uid, {
+ skip: query.skip ?? 0,
+ take: query.take ?? 20,
+ })
return {
chats: result.chats.map((chat) => ({
id: chat.id,
name: chat.name,
+ pinned: chat.pinned,
+ tags: chat.tags ?? [],
created: chat.created,
updated: chat.updated,
})),
@@ -512,6 +567,8 @@ export class AiController {
id: chat.id,
name: chat.name,
messages: chat.messages,
+ pinned: chat.pinned,
+ tags: chat.tags ?? [],
created: chat.created,
updated: chat.updated,
isOwner,
@@ -778,6 +835,55 @@ export class AiController {
}
}
+ @ApiBearerAuth()
+ @Patch(':pid/chats/:chatId')
+ @Auth(false, true) // Allow optional auth for public projects
+ @ApiOperation({
+ summary: 'Update chat metadata (pinned, tags, name) — owner only',
+ })
+ @ApiResponse({ status: 200, description: 'Chat metadata updated' })
+ async updateChatMeta(
+ @Param('pid') pid: string,
+ @Param('chatId') chatId: string,
+ @Body() body: UpdateChatMetaDto,
+ @CurrentUserId() uid: string | null,
+ @Headers() headers: Record<string, string>,
+ ) {
+ this.logger.log({ uid, pid, chatId }, 'PATCH /ai/:pid/chats/:chatId')
+
+ await this.applyRateLimit(uid, headers, 'write')
+
+ 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.verifyOwnerAccess(chatId, pid, uid)
+ if (!chat) {
+ throw new NotFoundException('Chat not found')
+ }
+
+ const updated = await this.aiChatService.updateMeta(chatId, {
+ pinned: body.pinned,
+ tags: body.tags,
+ name: body.name,
+ })
+
+ if (!updated) {
+ throw new NotFoundException('Chat not found')
+ }
+
+ return {
+ id: updated.id,
+ name: updated.name,
+ pinned: updated.pinned,
+ tags: updated.tags ?? [],
+ created: updated.created,
+ updated: updated.updated,
+ }
+ }
+
@ApiBearerAuth()
@Delete(':pid/chats/:chatId')
@Auth(false, true) // Allow optional auth for public projects
diff --git a/backend/apps/cloud/src/ai/dto/chat.dto.ts b/backend/apps/cloud/src/ai/dto/chat.dto.ts
index 827d6b23b..c7ef48239 100644
--- a/backend/apps/cloud/src/ai/dto/chat.dto.ts
+++ b/backend/apps/cloud/src/ai/dto/chat.dto.ts
@@ -7,10 +7,12 @@ import {
IsIn,
IsOptional,
IsInt,
+ IsBoolean,
Min,
Max,
ArrayMaxSize,
MaxLength,
+ MinLength,
} from 'class-validator'
import { Type, Transform } from 'class-transformer'
@@ -19,6 +21,8 @@ const MAX_MESSAGE_LENGTH = 5000
const MAX_CHAT_NAME_LENGTH = 200
const MAX_TOOL_CALLS_PER_MESSAGE = 50
const MAX_TOOL_NAME_LENGTH = 100
+export const MAX_TAGS_PER_CHAT = 5
+export const MAX_TAG_LENGTH = 30
class ChatMessageToolCallDto {
@ApiProperty({ description: 'Tool name that was invoked' })
@@ -158,18 +162,102 @@ export class UpdateChatDto {
name?: string
}
+const parseOptionalBool = ({ value }: { value: unknown }) => {
+ if (value === undefined || value === null || value === '') return undefined
+ if (typeof value === 'boolean') return value
+ const v = String(value).toLowerCase()
+ if (v === 'true' || v === '1') return true
+ if (v === 'false' || v === '0') return false
+ return undefined
+}
+
export class GetRecentChatsQueryDto {
@ApiProperty({
required: false,
- description: 'Maximum number of chats to return (1-50)',
+ description: 'Maximum number of chats to return (1-100)',
default: 5,
})
@IsOptional()
@Transform(({ value }) => parseInt(value, 10))
@IsInt()
@Min(1)
- @Max(50)
+ @Max(100)
limit?: number
+
+ @ApiProperty({
+ required: false,
+ description: 'Number of chats to skip (0 or greater)',
+ })
+ @IsOptional()
+ @Transform(({ value }) => parseInt(value, 10))
+ @IsInt()
+ @Min(0)
+ @Max(10000)
+ skip?: number
+
+ @ApiProperty({
+ required: false,
+ description: 'Number of chats to return (1-100)',
+ })
+ @IsOptional()
+ @Transform(({ value }) => parseInt(value, 10))
+ @IsInt()
+ @Min(1)
+ @Max(100)
+ take?: number
+
+ @ApiProperty({
+ required: false,
+ description: 'Search query (matches chat names; falls back to messages)',
+ })
+ @IsOptional()
+ @IsString()
+ @MinLength(2)
+ @MaxLength(100)
+ search?: string
+
+ @ApiProperty({
+ required: false,
+ description: 'Filter by tag (single tag string)',
+ })
+ @IsOptional()
+ @IsString()
+ @MaxLength(MAX_TAG_LENGTH)
+ tag?: string
+
+ @ApiProperty({
+ required: false,
+ description: 'When true, only pinned chats are returned',
+ })
+ @IsOptional()
+ @Transform(parseOptionalBool)
+ @IsBoolean()
+ pinned?: boolean
+}
+
+export class UpdateChatMetaDto {
+ @ApiProperty({ required: false, description: 'Whether the chat is pinned' })
+ @IsOptional()
+ @IsBoolean()
+ pinned?: boolean
+
+ @ApiProperty({
+ required: false,
+ type: [String],
+ description: `User-defined tag labels (max ${MAX_TAGS_PER_CHAT}, ${MAX_TAG_LENGTH} chars each)`,
+ })
+ @IsOptional()
+ @IsArray()
+ @ArrayMaxSize(MAX_TAGS_PER_CHAT)
+ @IsString({ each: true })
+ @MaxLength(MAX_TAG_LENGTH, { each: true })
+ tags?: string[]
+
+ @ApiProperty({ required: false, description: 'Custom name for the chat' })
+ @IsOptional()
+ @IsString()
+ @MaxLength(MAX_CHAT_NAME_LENGTH)
+ name?: string
}
export class FeedbackDto {
diff --git a/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts b/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
index d91ba8e08..6fbd2a267 100644
--- a/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
+++ b/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
@@ -38,6 +38,14 @@ export class AiChat {
@Column('json')
messages: ChatMessage[]
+ @ApiProperty()
+ @Column('boolean', { default: false })
+ pinned: boolean
+
+ @ApiProperty({ type: [String] })
+ @Column('simple-array', { nullable: true, default: null })
+ tags: string[]
+
@ApiProperty({ type: () => Project })
@ManyToOne(() => Project, { onDelete: 'CASCADE' })
@JoinColumn()
diff --git a/backend/migrations/mysql/2026_04_21_ai_chat_pin_tags.sql b/backend/migrations/mysql/2026_04_21_ai_chat_pin_tags.sql
new file mode 100644
index 000000000..a9a046b35
--- /dev/null
+++ b/backend/migrations/mysql/2026_04_21_ai_chat_pin_tags.sql
@@ -0,0 +1,5 @@
+ALTER TABLE `ai_chat`
+ ADD COLUMN `pinned` tinyint(1) NOT NULL DEFAULT 0,
+ ADD COLUMN `tags` text DEFAULT NULL;
+
+CREATE INDEX `idx_ai_chat_pinned_updated` ON `ai_chat` (`pinned`, `updated`);
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index de7495a8d..2ea92653c 100644
--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
@@ -16,7 +16,6 @@ import {
GitBranchIcon,
InfoIcon,
CheckIcon,
- ChatIcon,
TrashIcon,
XIcon,
LinkIcon,
@@ -32,6 +31,9 @@ import {
ListBulletsIcon,
MicrophoneIcon,
MicrophoneSlashIcon,
+ TagIcon,
+ PushPinIcon,
+ MagnifyingGlassIcon,
} from '@phosphor-icons/react'
import { marked } from 'marked'
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react'
@@ -44,7 +46,9 @@ import { useStickToBottom } from 'use-stick-to-bottom'
import { askAI } from '~/api'
import useSpeechRecognition from '~/hooks/useSpeechRecognition'
import { ProjectViewActionData } from '~/routes/projects.$id'
+import Button from '~/ui/Button'
import SwetrixLogo from '~/ui/icons/SwetrixLogo'
+import Input from '~/ui/Input'
import Modal from '~/ui/Modal'
import { Text } from '~/ui/Text'
import Textarea from '~/ui/Textarea'
@@ -64,10 +68,31 @@ interface MessagePart {
interface AIChatSummary {
id: string
name: string | null
+ pinned?: boolean
+ tags?: string[]
created: string
updated: string
}
+const MAX_TAGS_PER_CHAT = 5
+const MAX_TAG_LENGTH = 30
+
+const sanitiseTagsClient = (tags: string[]): string[] => {
+ const seen = new Set<string>()
+ const out: string[] = []
+ for (const raw of tags) {
+ if (typeof raw !== 'string') continue
+ const cleaned = raw.replace(/,/g, '').trim().slice(0, MAX_TAG_LENGTH)
+ if (!cleaned) continue
+ const key = cleaned.toLowerCase()
+ if (seen.has(key)) continue
+ seen.add(key)
+ out.push(cleaned)
+ if (out.length >= MAX_TAGS_PER_CHAT) break
+ }
+ return out
+}
+
interface MessageToolCall {
toolName: string
args: unknown
@@ -1153,12 +1178,583 @@ interface AIChat {
followUps?: string[]
toolCalls?: MessageToolCall[]
}[]
+ pinned?: boolean
+ tags?: string[]
isOwner?: boolean
branched?: boolean
created: string
updated: string
}
+interface ChatRowActions {
+ onOpen: (chatId: string) => void
+ onDelete: (chatId: string) => void
+ onTogglePin: (chat: AIChatSummary) => void
+ onSaveTags: (chatId: string, tags: string[]) => void
+ onRename: (chatId: string, name: string) => void
+ formatRelative: (dateStr: string) => string
+}
+
+const TagChip = ({
+ label,
+ active,
+ onClick,
+ onRemove,
+ className,
+}: {
+ label: string
+ active?: boolean
+ onClick?: () => void
+ onRemove?: () => void
+ className?: string
+}) => {
+ const baseClasses =
+ 'inline-flex max-w-[180px] items-center gap-1 rounded-md px-2 py-0.5 text-xs font-medium ring-1 ring-inset transition-colors'
+ const activeClasses =
+ 'bg-slate-900 text-gray-50 ring-slate-900 dark:bg-gray-50 dark:text-slate-900 dark:ring-gray-50'
+ const inactiveClasses =
+ 'bg-slate-50 text-slate-700 ring-slate-500/10 dark:bg-slate-400/10 dark:text-slate-300 dark:ring-slate-400/20'
+ const interactiveHover = onClick
+ ? 'hover:bg-slate-100 dark:hover:bg-slate-700/40'
+ : ''
+
+ const content = (
+ <>
+ <span className='truncate'>{label}</span>
+ {onRemove ? (
+ <button
+ type='button'
+ onClick={(e) => {
+ e.stopPropagation()
+ onRemove()
+ }}
+ aria-label='Remove tag'
+ className='rounded-full p-0.5 opacity-70 hover:opacity-100'
+ >
+ <XIcon className='h-3 w-3' />
+ </button>
+ ) : null}
+ </>
+ )
+
+ if (onClick) {
+ return (
+ <button
+ type='button'
+ onClick={onClick}
+ className={cn(
+ baseClasses,
+ active ? activeClasses : inactiveClasses,
+ interactiveHover,
+ className,
+ )}
+ >
+ {content}
+ </button>
+ )
+ }
+
+ return (
+ <span
+ className={cn(
+ baseClasses,
+ active ? activeClasses : inactiveClasses,
+ className,
+ )}
+ >
+ {content}
+ </span>
+ )
+}
+
+const TagEditor = ({
+ tags,
+ onSave,
+ onCancel,
+}: {
+ tags: string[]
+ onSave: (tags: string[]) => void
+ onCancel: () => void
+}) => {
+ const { t } = useTranslation('common')
+ const [draft, setDraft] = useState<string[]>(tags)
+ const [input, setInput] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const inputRef = useRef<HTMLInputElement>(null)
+
+ useEffect(() => {
+ inputRef.current?.focus()
+ }, [])
+
+ const addTag = (raw: string) => {
+ const cleaned = raw.replace(/,/g, '').trim()
+ if (!cleaned) {
+ setError(null)
+ return
+ }
+ if (cleaned.length > MAX_TAG_LENGTH) {
+ setError(t('project.askAi.tagInvalid', { max: MAX_TAG_LENGTH }))
+ return
+ }
+ if (draft.length >= MAX_TAGS_PER_CHAT) {
+ setError(t('project.askAi.tagsLimitReached', { max: MAX_TAGS_PER_CHAT }))
+ return
+ }
+ if (
+ draft.some((existing) => existing.toLowerCase() === cleaned.toLowerCase())
+ ) {
+ setError(t('project.askAi.tagAlreadyExists'))
+ return
+ }
+ setDraft((prev) => [...prev, cleaned])
+ setInput('')
+ setError(null)
+ }
+
+ const removeAt = (idx: number) => {
+ setDraft((prev) => prev.filter((_, i) => i !== idx))
+ setError(null)
+ }
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter' || e.key === ',') {
+ e.preventDefault()
+ addTag(input)
+ } else if (e.key === 'Backspace' && !input && draft.length > 0) {
+ e.preventDefault()
+ removeAt(draft.length - 1)
+ } else if (e.key === 'Escape') {
+ e.preventDefault()
+ onCancel()
+ }
+ }
+
+ const commit = () => {
+ const finalTags = input.trim() ? [...draft, input.trim()] : draft
+ onSave(sanitiseTagsClient(finalTags))
+ }
+
+ return (
+ <div
+ role='presentation'
+ className='flex flex-col gap-2 rounded-md border border-gray-200 bg-gray-50 p-2 dark:border-slate-700/80 dark:bg-slate-900/60'
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className='flex flex-wrap items-center gap-1.5'>
+ {_map(draft, (tag, idx) => (
+ <TagChip
+ key={`${tag}-${idx}`}
+ label={tag}
+ onRemove={() => removeAt(idx)}
+ />
+ ))}
+ <input
+ ref={inputRef}
+ type='text'
+ value={input}
+ onChange={(e) => {
+ setInput(e.target.value)
+ setError(null)
+ }}
+ onKeyDown={handleKeyDown}
+ placeholder={t('project.askAi.tagPlaceholder')}
+ maxLength={MAX_TAG_LENGTH}
+ className='min-w-[140px] flex-1 border-0 bg-transparent p-1 text-xs text-gray-900 placeholder-gray-400 focus:ring-0 focus:outline-none dark:text-white dark:placeholder-gray-500'
+ />
+ </div>
+ {error ? (
+ <Text size='xxs' colour='error'>
+ {error}
+ </Text>
+ ) : null}
+ <div className='flex items-center justify-end gap-2'>
+ <Button onClick={onCancel} secondary small className='py-1'>
+ {t('common.cancel')}
+ </Button>
+ <Button onClick={commit} primary small className='py-1'>
+ {t('project.askAi.saveTags')}
+ </Button>
+ </div>
+ </div>
+ )
+}
+
+const ChatRow = ({
+ chat,
+ actions,
+ variant = 'panel',
+}: {
+ chat: AIChatSummary
+ actions: ChatRowActions
+ variant?: 'panel' | 'compact'
+}) => {
+ const { t } = useTranslation('common')
+ const [isEditingTags, setIsEditingTags] = useState(false)
+ const [isEditingName, setIsEditingName] = useState(false)
+ const [nameDraft, setNameDraft] = useState(chat.name || '')
+ const nameInputRef = useRef<HTMLInputElement>(null)
+
+ useEffect(() => {
+ if (isEditingName) {
+ nameInputRef.current?.focus()
+ nameInputRef.current?.select()
+ }
+ }, [isEditingName])
+
+ const tags = chat.tags ?? []
+
+ if (variant === 'compact') {
+ return (
+ <button
+ type='button'
+ onClick={() => actions.onOpen(chat.id)}
+ className='group flex w-full items-center justify-between gap-3 py-1 text-left transition-colors'
+ >
+ <div className='flex min-w-0 items-center gap-2'>
+ {chat.pinned ? (
+ <PushPinIcon
+ className='h-3.5 w-3.5 shrink-0 text-amber-500 dark:text-amber-400'
+ weight='fill'
+ />
+ ) : null}
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ colour='primary'
+ truncate
+ className='group-hover:underline'
+ >
+ {chat.name || t('project.askAi.newChat')}
+ </Text>
+ </div>
+ <Text as='span' size='xs' colour='muted' className='shrink-0'>
+ {actions.formatRelative(chat.updated)}
+ </Text>
+ </button>
+ )
+ }
+
+ const submitRename = () => {
+ const trimmed = nameDraft.trim()
+ if (trimmed && trimmed !== chat.name) {
+ actions.onRename(chat.id, trimmed)
+ }
+ setIsEditingName(false)
+ }
+
+ const iconButtonCls =
+ 'flex h-7 w-7 items-center justify-center rounded-md text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-slate-800 dark:hover:text-gray-100'
+
+ return (
+ <div className='group rounded-md border border-gray-200 bg-white px-3 py-2 ring-1 ring-transparent transition-colors ring-inset hover:border-gray-300 hover:ring-gray-200/60 dark:border-slate-800/80 dark:bg-slate-900/40 hover:dark:border-slate-700 hover:dark:ring-slate-700/40'>
+ <div className='flex items-start gap-2'>
+ <button
+ type='button'
+ onClick={() => actions.onTogglePin(chat)}
+ className={cn(
+ 'mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition-colors',
+ chat.pinned
+ ? 'text-amber-500 hover:bg-amber-50 dark:text-amber-400 dark:hover:bg-amber-900/20'
+ : 'text-gray-400 opacity-0 group-hover:opacity-100 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-slate-800 dark:hover:text-gray-200',
+ )}
+ title={
+ chat.pinned ? t('project.askAi.unpin') : t('project.askAi.pin')
+ }
+ aria-label={
+ chat.pinned ? t('project.askAi.unpin') : t('project.askAi.pin')
+ }
+ >
+ <PushPinIcon
+ className='h-4 w-4'
+ weight={chat.pinned ? 'fill' : 'regular'}
+ />
+ </button>
+
+ <div className='flex min-w-0 flex-1 flex-col items-start gap-0.5'>
+ {isEditingName ? (
+ <input
+ ref={nameInputRef}
+ type='text'
+ value={nameDraft}
+ maxLength={200}
+ onChange={(e) => setNameDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault()
+ submitRename()
+ } else if (e.key === 'Escape') {
+ e.preventDefault()
+ setNameDraft(chat.name || '')
+ setIsEditingName(false)
+ }
+ }}
+ onBlur={submitRename}
+ className='w-full border-0 bg-transparent p-0 text-sm font-medium text-gray-900 focus:ring-0 focus:outline-none dark:text-gray-50'
+ placeholder={t('project.askAi.renameChatPlaceholder')}
+ />
+ ) : (
+ <Text
+ as='button'
+ size='sm'
+ weight='medium'
+ colour='primary'
+ truncate
+ type='button'
+ onClick={() => actions.onOpen(chat.id)}
+ className='block max-w-full text-left hover:underline'
+ >
+ {chat.name || t('project.askAi.newChat')}
+ </Text>
+ )}
+ <Text size='xxs' colour='muted'>
+ {actions.formatRelative(chat.updated)}
+ </Text>
+ </div>
+
+ <div className='flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100'>
+ <button
+ type='button'
+ onClick={(e) => {
+ e.stopPropagation()
+ setNameDraft(chat.name || '')
+ setIsEditingName(true)
+ }}
+ className={iconButtonCls}
+ aria-label={t('project.askAi.renameChat')}
+ title={t('project.askAi.renameChat')}
+ >
+ <PencilSimpleIcon className='h-3.5 w-3.5' />
+ </button>
+ <button
+ type='button'
+ onClick={(e) => {
+ e.stopPropagation()
+ setIsEditingTags(true)
+ }}
+ className={iconButtonCls}
+ aria-label={t('project.askAi.manageTags')}
+ title={t('project.askAi.manageTags')}
+ >
+ <TagIcon className='h-3.5 w-3.5' />
+ </button>
+ <button
+ type='button'
+ onClick={(e) => {
+ e.stopPropagation()
+ actions.onDelete(chat.id)
+ }}
+ className={cn(
+ iconButtonCls,
+ 'hover:text-red-600 dark:hover:text-red-400',
+ )}
+ aria-label={t('project.askAi.deleteChat')}
+ title={t('project.askAi.deleteChat')}
+ >
+ <TrashIcon className='h-3.5 w-3.5' />
+ </button>
+ </div>
+ </div>
+
+ {isEditingTags ? (
+ <div className='mt-2 ml-9'>
+ <TagEditor
+ tags={tags}
+ onSave={(next) => {
+ actions.onSaveTags(chat.id, next)
+ setIsEditingTags(false)
+ }}
+ onCancel={() => setIsEditingTags(false)}
+ />
+ </div>
+ ) : tags.length > 0 ? (
+ <div className='mt-1.5 ml-9 flex flex-wrap gap-1'>
+ {_map(tags, (tag) => (
+ <TagChip key={tag} label={tag} />
+ ))}
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
+const ChatHistoryPanel = ({
+ isOpen,
+ onClose,
+ search,
+ onSearchChange,
+ tagFilter,
+ onTagFilterChange,
+ availableTags,
+ chats,
+ total,
+ isLoading,
+ isFetchingMore,
+ actions,
+ onLoadMore,
+}: {
+ isOpen: boolean
+ onClose: () => void
+ search: string
+ onSearchChange: (value: string) => void
+ tagFilter: string | null
+ onTagFilterChange: (tag: string | null) => void
+ availableTags: string[]
+ chats: AIChatSummary[]
+ total: number
+ isLoading: boolean
+ isFetchingMore: boolean
+ actions: ChatRowActions
+ onLoadMore: () => void
+}) => {
+ const { t } = useTranslation('common')
+ const isSearching = search.trim().length >= 2 || tagFilter !== null
+ const showEmpty = !isLoading && chats.length === 0
+ const pinned = useMemo(() => chats.filter((c) => c.pinned), [chats])
+ const others = useMemo(() => chats.filter((c) => !c.pinned), [chats])
+
+ return (
+ <Modal
+ isOpened={isOpen}
+ onClose={onClose}
+ title={t('project.askAi.allChats')}
+ size='large'
+ message={
+ <div className='mt-3 flex flex-col gap-4'>
+ <div className='relative'>
+ <MagnifyingGlassIcon className='pointer-events-none absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400 dark:text-gray-500' />
+ <Input
+ type='search'
+ value={search}
+ onChange={(e) => onSearchChange(e.target.value)}
+ placeholder={t('project.askAi.searchChatsPlaceholder')}
+ classes={{ input: 'pl-9' }}
+ />
+ </div>
+ {search.trim().length === 1 ? (
+ <Text size='xs' colour='muted' className='-mt-2'>
+ {t('project.askAi.searchHint')}
+ </Text>
+ ) : null}
+
+ {availableTags.length > 0 ? (
+ <div className='flex flex-wrap items-center gap-1.5'>
+ <Text size='xs' weight='medium' colour='muted' className='mr-1'>
+ {t('project.askAi.filterByTag')}:
+ </Text>
+ <TagChip
+ label={t('project.askAi.allTags')}
+ active={tagFilter === null}
+ onClick={() => onTagFilterChange(null)}
+ />
+ {_map(availableTags, (tag) => (
+ <TagChip
+ key={tag}
+ label={tag}
+ active={tagFilter === tag}
+ onClick={() =>
+ onTagFilterChange(tagFilter === tag ? null : tag)
+ }
+ />
+ ))}
+ {tagFilter ? (
+ <button
+ type='button'
+ onClick={() => onTagFilterChange(null)}
+ className='ml-1 text-xs font-medium text-gray-500 transition-colors hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200'
+ >
+ {t('project.askAi.clearFilters')}
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+
+ <div className='-mx-1 max-h-[60vh] overflow-y-auto px-1'>
+ {showEmpty ? (
+ <Text
+ as='p'
+ size='sm'
+ colour='muted'
+ className='py-8 text-center'
+ >
+ {isSearching
+ ? t('project.askAi.noChatsMatch')
+ : t('project.askAi.noChats')}
+ </Text>
+ ) : (
+ <div className='flex flex-col gap-4'>
+ {pinned.length > 0 ? (
+ <div className='flex flex-col gap-2'>
+ <div className='flex items-center gap-1.5'>
+ <PushPinIcon
+ className='h-3 w-3 text-amber-500 dark:text-amber-400'
+ weight='fill'
+ />
+ <Text
+ size='xxs'
+ weight='semibold'
+ colour='muted'
+ tracking='wide'
+ className='uppercase'
+ >
+ {t('project.askAi.pinned')}
+ </Text>
+ </div>
+ <div className='flex flex-col gap-1.5'>
+ {_map(pinned, (chat) => (
+ <ChatRow key={chat.id} chat={chat} actions={actions} />
+ ))}
+ </div>
+ </div>
+ ) : null}
+
+ {others.length > 0 ? (
+ <div className='flex flex-col gap-2'>
+ {pinned.length > 0 ? (
+ <Text
+ size='xxs'
+ weight='semibold'
+ colour='muted'
+ tracking='wide'
+ className='uppercase'
+ >
+ {t('project.askAi.recentChats')}
+ </Text>
+ ) : null}
+ <div className='flex flex-col gap-1.5'>
+ {_map(others, (chat) => (
+ <ChatRow key={chat.id} chat={chat} actions={actions} />
+ ))}
+ </div>
+ </div>
+ ) : null}
+
+ {chats.length < total ? (
+ <Button
+ secondary
+ small
+ onClick={onLoadMore}
+ disabled={isFetchingMore}
+ loading={isFetchingMore}
+ className='justify-center self-center'
+ >
+ {t('project.askAi.loadMore')}
+ </Button>
+ ) : null}
+ </div>
+ )}
+ {isLoading && chats.length === 0 ? (
+ <div className='flex items-center justify-center py-8'>
+ <SpinnerGapIcon className='h-6 w-6 animate-spin text-gray-400' />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ }
+ />
+ )
+}
+
const AskAIView = ({ projectId }: AskAIViewProps) => {
const { t } = useTranslation('common')
const [searchParams, setSearchParams] = useSearchParams()
@@ -1187,8 +1783,12 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const [recentChats, setRecentChats] = useState<AIChatSummary[]>([])
const [allChats, setAllChats] = useState<AIChatSummary[]>([])
const [allChatsTotal, setAllChatsTotal] = useState(0)
- const [isViewAllModalOpen, setIsViewAllModalOpen] = useState(false)
+ const [isHistoryPanelOpen, setIsHistoryPanelOpen] = useState(false)
const [chatToDelete, setChatToDelete] = useState<string | null>(null)
+ const [historySearch, setHistorySearch] = useState('')
+ const [debouncedHistorySearch, setDebouncedHistorySearch] = useState('')
+ const [historyTagFilter, setHistoryTagFilter] = useState<string | null>(null)
+ const [availableTags, setAvailableTags] = useState<string[]>([])
const [feedbackMap, setFeedbackMap] = useState<
Record<string, 'good' | 'bad'>
>({})
@@ -1198,9 +1798,11 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const recentChatsFetcher = useFetcher<ProjectViewActionData>()
const allChatsFetcher = useFetcher<ProjectViewActionData>()
+ const tagsFetcher = useFetcher<ProjectViewActionData>()
const loadChatFetcher = useFetcher<ProjectViewActionData>()
const createChatFetcher = useFetcher<ProjectViewActionData>()
const updateChatFetcher = useFetcher<ProjectViewActionData>()
+ const updateMetaFetcher = useFetcher<ProjectViewActionData>()
const deleteChatFetcher = useFetcher<ProjectViewActionData>()
const titleFetcher = useFetcher<ProjectViewActionData>()
const feedbackFetcher = useFetcher<ProjectViewActionData>()
@@ -1235,30 +1837,57 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
if (recentChatsFetcher.state !== 'idle') return
const formData = new FormData()
- formData.append('intent', 'get-recent-ai-chats')
- formData.append('limit', '3')
+ formData.append('intent', 'list-ai-chats')
+ formData.append('take', '3')
recentChatsFetcher.submit(formData, { method: 'POST' })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [recentChatsFetcher.submit])
- // Handle recent chats fetcher response
useEffect(() => {
if (recentChatsFetcher.state === 'idle' && recentChatsFetcher.data) {
if (recentChatsFetcher.data.success && recentChatsFetcher.data.data) {
- setRecentChats(recentChatsFetcher.data.data as AIChatSummary[])
+ const payload = recentChatsFetcher.data.data as
+ | AIChatSummary[]
+ | { chats: AIChatSummary[]; total: number }
+ const list = Array.isArray(payload) ? payload : payload.chats
+ setRecentChats(list)
}
}
}, [recentChatsFetcher.state, recentChatsFetcher.data])
+ const loadAvailableTags = useCallback(() => {
+ if (tagsFetcher.state !== 'idle') return
+
+ const formData = new FormData()
+ formData.append('intent', 'list-ai-chat-tags')
+ tagsFetcher.submit(formData, { method: 'POST' })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [tagsFetcher.submit])
+
+ useEffect(() => {
+ if (tagsFetcher.state === 'idle' && tagsFetcher.data) {
+ if (tagsFetcher.data.success && tagsFetcher.data.data) {
+ const payload = tagsFetcher.data.data as { tags?: string[] }
+ setAvailableTags(payload.tags || [])
+ }
+ }
+ }, [tagsFetcher.state, tagsFetcher.data])
+
const loadAllChats = useCallback(
- (skip: number = 0) => {
+ (skip: number = 0, opts: { search?: string; tag?: string | null } = {}) => {
if (allChatsFetcher.state !== 'idle') return
const formData = new FormData()
- formData.append('intent', 'get-all-ai-chats')
+ formData.append('intent', 'list-ai-chats')
formData.append('skip', skip.toString())
formData.append('take', '20')
+ if (opts.search && opts.search.trim().length >= 2) {
+ formData.append('search', opts.search.trim())
+ }
+ if (opts.tag) {
+ formData.append('tag', opts.tag)
+ }
allChatsFetcher.submit(formData, { method: 'POST' })
},
@@ -1266,7 +1895,6 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
[allChatsFetcher.submit],
)
- // Handle all chats fetcher response
const [pendingAllChatsSkip, setPendingAllChatsSkip] = useState<number | null>(
null,
)
@@ -1278,7 +1906,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
chats: AIChatSummary[]
total: number
}
- if (pendingAllChatsSkip === 0) {
+ if (pendingAllChatsSkip === 0 || pendingAllChatsSkip === null) {
setAllChats(result.chats)
} else {
setAllChats((prev) => [...prev, ...result.chats])
@@ -1290,11 +1918,11 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
}, [allChatsFetcher.state, allChatsFetcher.data, pendingAllChatsSkip])
const loadAllChatsWithSkip = useCallback(
- (skip: number) => {
+ (skip: number, opts: { search?: string; tag?: string | null } = {}) => {
if (allChatsFetcher.state !== 'idle') return
setPendingAllChatsSkip(skip)
- loadAllChats(skip)
+ loadAllChats(skip, opts)
},
[allChatsFetcher.state, loadAllChats],
)
@@ -1546,7 +2174,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
}, [searchParams, setSearchParams])
const handleOpenChat = (chatId: string) => {
- setIsViewAllModalOpen(false)
+ setIsHistoryPanelOpen(false)
loadChatById(chatId)
const newParams = new URLSearchParams(searchParams)
newParams.set('chat', chatId)
@@ -1566,8 +2194,13 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
}
loadRecentChats()
- if (isViewAllModalOpen) {
- loadAllChatsWithSkip(0)
+ loadAvailableTags()
+ if (isHistoryPanelOpen) {
+ const term = debouncedHistorySearch.trim()
+ loadAllChatsWithSkip(0, {
+ search: term.length >= 2 ? term : undefined,
+ tag: historyTagFilter,
+ })
}
} else if (deleteChatFetcher.data.error) {
console.error('Failed to delete chat:', deleteChatFetcher.data.error)
@@ -1580,8 +2213,11 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
deleteChatFetcher.data,
deletingChatId,
currentChatId,
- isViewAllModalOpen,
+ isHistoryPanelOpen,
+ debouncedHistorySearch,
+ historyTagFilter,
loadRecentChats,
+ loadAvailableTags,
loadAllChatsWithSkip,
t,
handleNewChat,
@@ -1599,6 +2235,129 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
deleteChatFetcher.submit(formData, { method: 'POST' })
}
+ const updateChatMeta = useCallback(
+ (
+ chatId: string,
+ patch: { pinned?: boolean; tags?: string[]; name?: string },
+ ) => {
+ const formData = new FormData()
+ formData.append('intent', 'update-ai-chat-meta')
+ formData.append('chatId', chatId)
+ if (patch.pinned !== undefined) {
+ formData.append('pinned', String(patch.pinned))
+ }
+ if (patch.tags !== undefined) {
+ formData.append('tags', JSON.stringify(patch.tags))
+ }
+ if (patch.name !== undefined) {
+ formData.append('name', patch.name)
+ }
+ updateMetaFetcher.submit(formData, { method: 'POST' })
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [updateMetaFetcher.submit],
+ )
+
+ const applyMetaToList = (
+ list: AIChatSummary[],
+ chatId: string,
+ patch: { pinned?: boolean; tags?: string[]; name?: string },
+ ): AIChatSummary[] =>
+ list.map((c) =>
+ c.id === chatId
+ ? {
+ ...c,
+ ...(patch.pinned !== undefined ? { pinned: patch.pinned } : {}),
+ ...(patch.tags !== undefined ? { tags: patch.tags } : {}),
+ ...(patch.name !== undefined ? { name: patch.name } : {}),
+ }
+ : c,
+ )
+
+ const handleTogglePin = useCallback(
+ (chat: AIChatSummary) => {
+ const nextPinned = !chat.pinned
+ setRecentChats((prev) =>
+ applyMetaToList(prev, chat.id, { pinned: nextPinned }),
+ )
+ setAllChats((prev) =>
+ applyMetaToList(prev, chat.id, { pinned: nextPinned }),
+ )
+ updateChatMeta(chat.id, { pinned: nextPinned })
+ },
+ [updateChatMeta],
+ )
+
+ const handleSaveTags = useCallback(
+ (chatId: string, nextTags: string[]) => {
+ const sanitised = sanitiseTagsClient(nextTags)
+ setRecentChats((prev) =>
+ applyMetaToList(prev, chatId, { tags: sanitised }),
+ )
+ setAllChats((prev) => applyMetaToList(prev, chatId, { tags: sanitised }))
+ updateChatMeta(chatId, { tags: sanitised })
+ },
+ [updateChatMeta],
+ )
+
+ const handleRenameChat = useCallback(
+ (chatId: string, name: string) => {
+ const trimmed = name.trim()
+ if (!trimmed) return
+ setRecentChats((prev) => applyMetaToList(prev, chatId, { name: trimmed }))
+ setAllChats((prev) => applyMetaToList(prev, chatId, { name: trimmed }))
+ if (chatId === currentChatIdRef.current) setChatTitle(trimmed)
+ updateChatMeta(chatId, { name: trimmed })
+ },
+ [updateChatMeta],
+ )
+
+ useEffect(() => {
+ if (updateMetaFetcher.state === 'idle' && updateMetaFetcher.data) {
+ if (updateMetaFetcher.data.success) {
+ loadRecentChats()
+ loadAvailableTags()
+ } else if (updateMetaFetcher.data.error) {
+ toast.error(t('project.askAi.error'))
+ }
+ }
+ }, [
+ updateMetaFetcher.state,
+ updateMetaFetcher.data,
+ loadRecentChats,
+ loadAvailableTags,
+ t,
+ ])
+
+ // Debounce history search input (250ms)
+ useEffect(() => {
+ if (!isHistoryPanelOpen) return
+ const handle = window.setTimeout(() => {
+ setDebouncedHistorySearch(historySearch)
+ }, 250)
+ return () => window.clearTimeout(handle)
+ }, [historySearch, isHistoryPanelOpen])
+
+ useEffect(() => {
+ if (!isHistoryPanelOpen) return
+ const term = debouncedHistorySearch.trim()
+ if (term.length === 1) return // wait for >=2 chars
+ loadAllChatsWithSkip(0, {
+ search: term.length >= 2 ? term : undefined,
+ tag: historyTagFilter,
+ })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [debouncedHistorySearch, historyTagFilter, isHistoryPanelOpen])
+
+ const openHistoryPanel = useCallback(() => {
+ setIsHistoryPanelOpen(true)
+ setHistorySearch('')
+ setDebouncedHistorySearch('')
+ setHistoryTagFilter(null)
+ loadAvailableTags()
+ loadAllChatsWithSkip(0)
+ }, [loadAvailableTags, loadAllChatsWithSkip])
+
const runChatTurn = useCallback(
async (allMessages: Message[]) => {
setError(null)
@@ -1960,23 +2719,39 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const isEmpty = _isEmpty(messages) && !streamingMessage
const isChatActive = !isEmpty
- 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 t('project.askAi.timeFormat.justNow')
- if (diffMins < 60)
- return t('project.askAi.timeFormat.minutes', { count: diffMins })
- if (diffHours < 24)
- return t('project.askAi.timeFormat.hours', { count: diffHours })
- if (diffDays < 7)
- return t('project.askAi.timeFormat.days', { count: diffDays })
- return date.toLocaleDateString()
- }
+ const formatRelativeTime = useCallback(
+ (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 t('project.askAi.timeFormat.justNow')
+ if (diffMins < 60)
+ return t('project.askAi.timeFormat.minutes', { count: diffMins })
+ if (diffHours < 24)
+ return t('project.askAi.timeFormat.hours', { count: diffHours })
+ if (diffDays < 7)
+ return t('project.askAi.timeFormat.days', { count: diffDays })
+ return date.toLocaleDateString()
+ },
+ [t],
+ )
+
+ const chatRowActions = useMemo<ChatRowActions>(
+ () => ({
+ onOpen: handleOpenChat,
+ onDelete: (chatId) => setChatToDelete(chatId),
+ onTogglePin: handleTogglePin,
+ onSaveTags: handleSaveTags,
+ onRename: handleRenameChat,
+ formatRelative: formatRelativeTime,
+ }),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [handleTogglePin, handleSaveTags, handleRenameChat, formatRelativeTime],
+ )
return (
<div className='relative flex h-[calc(100vh-140px)] min-h-[600px] flex-col bg-gray-50 dark:bg-slate-950'>
@@ -2291,115 +3066,46 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
</Text>
<button
type='button'
- onClick={() => {
- setIsViewAllModalOpen(true)
- loadAllChatsWithSkip(0)
- }}
- className='text-sm font-medium text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
+ onClick={openHistoryPanel}
+ className='text-sm font-medium text-gray-500 transition-colors hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200'
>
{t('project.askAi.viewAll')}
</button>
</div>
- <div className='mt-4 space-y-3'>
- {_map(recentChats, (chat) => (
- <button
- key={chat.id}
- type='button'
- onClick={() => handleOpenChat(chat.id)}
- className='group flex w-full items-center justify-between text-left transition-colors'
- >
- <Text
- as='span'
- size='sm'
- weight='medium'
- truncate
- className='group-hover:underline'
- >
- {chat.name || t('project.askAi.newChat')}
- </Text>
- <Text
- as='span'
- size='sm'
- weight='medium'
- colour='muted'
- className='ml-4 shrink-0'
- >
- {formatRelativeTime(chat.updated)}
- </Text>
- </button>
+ <ul className='mt-3 divide-y divide-gray-200/70 dark:divide-slate-800/60'>
+ {_map(recentChats.slice(0, 3), (chat) => (
+ <li key={chat.id}>
+ <ChatRow
+ chat={chat}
+ variant='compact'
+ actions={chatRowActions}
+ />
+ </li>
))}
- </div>
+ </ul>
</div>
) : null}
- <Modal
- isOpened={isViewAllModalOpen}
- onClose={() => setIsViewAllModalOpen(false)}
- title={t('project.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('project.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-800/60 dark:bg-slate-900/25 hover:dark:bg-slate-700'
- >
- <button
- type='button'
- onClick={() => handleOpenChat(chat.id)}
- className='flex flex-1 items-center gap-3 overflow-hidden text-left'
- >
- <ChatIcon 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('project.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('project.askAi.deleteChat')}
- >
- <TrashIcon className='h-4 w-4' />
- </button>
- </div>
- ))}
- {allChats.length < allChatsTotal ? (
- <button
- type='button'
- onClick={() => loadAllChatsWithSkip(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-800/50 dark:bg-slate-900 dark:text-gray-200 hover:dark:bg-slate-700'
- >
- {isLoadingChats ? (
- <SpinnerGapIcon className='h-4 w-4 animate-spin' />
- ) : null}
- {t('project.askAi.loadMore')}
- </button>
- ) : null}
- </div>
- )}
- {isLoadingChats && _isEmpty(allChats) ? (
- <div className='flex items-center justify-center py-8'>
- <SpinnerGapIcon className='h-6 w-6 animate-spin text-gray-400' />
- </div>
- ) : null}
- </div>
- }
+ <ChatHistoryPanel
+ isOpen={isHistoryPanelOpen}
+ onClose={() => setIsHistoryPanelOpen(false)}
+ search={historySearch}
+ onSearchChange={setHistorySearch}
+ tagFilter={historyTagFilter}
+ onTagFilterChange={setHistoryTagFilter}
+ availableTags={availableTags}
+ chats={allChats}
+ total={allChatsTotal}
+ isLoading={isLoadingChats && allChats.length === 0}
+ isFetchingMore={isLoadingChats && allChats.length > 0}
+ actions={chatRowActions}
+ onLoadMore={() => {
+ const term = debouncedHistorySearch.trim()
+ loadAllChatsWithSkip(allChats.length, {
+ search: term.length >= 2 ? term : undefined,
+ tag: historyTagFilter,
+ })
+ }}
/>
<Modal
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index d5a145600..6673560dc 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -635,9 +635,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
'get-version-filters',
'get-recent-ai-chats',
'get-all-ai-chats',
+ 'list-ai-chats',
+ 'list-ai-chat-tags',
'get-ai-chat',
'create-ai-chat',
'update-ai-chat',
+ 'update-ai-chat-meta',
'delete-ai-chat',
'generate-ai-chat-title',
'submit-ai-chat-feedback',
@@ -1107,12 +1110,30 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
// AI Chat
- case 'get-recent-ai-chats': {
- const limit = Number(formData.get('limit') || '5')
+ case 'get-recent-ai-chats':
+ case 'get-all-ai-chats':
+ case 'list-ai-chats': {
+ const params = new URLSearchParams()
+ const limit = formData.get('limit')?.toString()
+ const skip = formData.get('skip')?.toString()
+ const take = formData.get('take')?.toString()
+ const search = formData.get('search')?.toString().trim()
+ const tag = formData.get('tag')?.toString()
+ const pinnedRaw = formData.get('pinned')?.toString()
+
+ if (limit) params.append('limit', limit)
+ if (skip) params.append('skip', skip)
+ if (take) params.append('take', take)
+ if (search && search.length >= 2) params.append('search', search)
+ if (tag) params.append('tag', tag)
+ if (pinnedRaw === 'true' || pinnedRaw === 'false') {
+ params.append('pinned', pinnedRaw)
+ }
+ const qs = params.toString()
const result = await serverFetch(
request,
- `ai/${projectId}/chats?limit=${limit}`,
+ `ai/${projectId}/chats${qs ? `?${qs}` : ''}`,
{
method: 'GET',
},
@@ -1131,17 +1152,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
}
- case 'get-all-ai-chats': {
- const skip = Number(formData.get('skip') || '0')
- const take = Number(formData.get('take') || '20')
-
- const result = await serverFetch(
- request,
- `ai/${projectId}/chats/all?skip=${skip}&take=${take}`,
- {
- method: 'GET',
- },
- )
+ case 'list-ai-chat-tags': {
+ const result = await serverFetch(request, `ai/${projectId}/chats/tags`, {
+ method: 'GET',
+ })
if (result.error) {
return data<ProjectViewActionData>(
@@ -1235,6 +1249,47 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
}
+ case 'update-ai-chat-meta': {
+ const chatId = formData.get('chatId')?.toString()
+ const pinnedRaw = formData.get('pinned')?.toString()
+ const tagsRaw = formData.get('tags')?.toString()
+ const name = formData.get('name')?.toString()
+
+ const body: Record<string, unknown> = {}
+ if (pinnedRaw === 'true' || pinnedRaw === 'false') {
+ body.pinned = pinnedRaw === 'true'
+ }
+ if (tagsRaw !== undefined) {
+ try {
+ body.tags = JSON.parse(tagsRaw)
+ } catch {
+ body.tags = []
+ }
+ }
+ if (name !== undefined) body.name = name
+
+ const result = await serverFetch(
+ request,
+ `ai/${projectId}/chats/${chatId}`,
+ {
+ method: 'PATCH',
+ body,
+ },
+ )
+
+ if (result.error) {
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
case 'delete-ai-chat': {
const chatId = formData.get('chatId')?.toString()
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 6572c6f37..9323e95ba 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -2111,13 +2111,36 @@
"error": "Sorry, something went wrong. Please try again.",
"disclaimer": "AI responses may not always be accurate. Verify important data.",
"recentChats": "Recent chats",
+ "pinnedChats": "Pinned chats",
"viewAll": "View all",
"allChats": "All chats",
"noChats": "No chat history yet",
+ "noChatsMatch": "No chats match your search",
"newChat": "New conversation",
"deleteChat": "Delete chat",
"deleteChatConfirm": "Are you sure you want to delete this chat?",
"chatDeleted": "Chat deleted",
+ "searchChatsPlaceholder": "Search chats by name or content…",
+ "searchHint": "Type at least 2 characters to search",
+ "filterByTag": "Filter by tag",
+ "clearFilters": "Clear filters",
+ "allTags": "All tags",
+ "pin": "Pin chat",
+ "unpin": "Unpin chat",
+ "pinned": "Pinned",
+ "tags": "Tags",
+ "addTag": "Add tag",
+ "tagPlaceholder": "e.g. research, billing, q4",
+ "tagsLimitReached": "Tags limit reached ({{max}} max)",
+ "tagAlreadyExists": "Tag already added",
+ "tagInvalid": "Tag must be 1-{{max}} characters",
+ "renameChat": "Rename chat",
+ "renameChatPlaceholder": "Chat name",
+ "saveTags": "Save tags",
+ "doneEditing": "Done",
+ "noTagsYet": "No tags yet",
+ "manageTags": "Manage tags",
+ "savingChanges": "Saving…",
"copyLink": "Copy link to chat",
"linkCopied": "Link copied to clipboard",
"copyMessage": "Copy message",