Skip to content

An AI-powered search engine with a generative UI

feat(chat): cache opened chats on the client instead of the server (#1093)

Yoshiki Miuracc234c08ed98
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index c41e165f..5019592b 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -1,4 +1,3 @@
-import { revalidateTag } from 'next/cache'
import { cookies } from 'next/headers'
import { after } from 'next/server'
@@ -515,12 +514,6 @@ export async function POST(req: Request) {
}
})()
- // Invalidate the cache for this specific chat after creating the response
- // This ensures the next load will get fresh data
- if (chatId && !isGuest) {
- revalidateTag(`chat-${chatId}`, 'max')
- }
-
const totalTime = performance.now() - startTime
perfLog(`Total API route time: ${totalTime.toFixed(2)}ms`)
perfLog(`=== Summary ===`)
diff --git a/app/api/chats/[id]/__tests__/route.test.ts b/app/api/chats/[id]/__tests__/route.test.ts
new file mode 100644
index 00000000..37fdc03c
--- /dev/null
+++ b/app/api/chats/[id]/__tests__/route.test.ts
@@ -0,0 +1,85 @@
+import { NextRequest } from 'next/server'
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { loadChat } from '@/lib/actions/chat'
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+
+import { GET } from '../route'
+
+vi.mock('@/lib/actions/chat', () => ({ loadChat: vi.fn() }))
+vi.mock('@/lib/auth/get-current-user', () => ({ getCurrentUserId: vi.fn() }))
+
+const request = () =>
+ GET(new NextRequest('http://localhost/api/chats/chat'), {
+ params: Promise.resolve({ id: 'chat' })
+ })
+
+describe('GET /api/chats/[id]', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(getCurrentUserId).mockResolvedValue('owner')
+ })
+ it('returns the owner history without caching', async () => {
+ const chat = {
+ id: 'chat',
+ title: 'Title',
+ visibility: 'private',
+ userId: 'owner',
+ messages: [],
+ createdAt: new Date()
+ }
+ vi.mocked(loadChat).mockResolvedValue(
+ chat as Awaited<ReturnType<typeof loadChat>>
+ )
+ const result = await request()
+ expect(result.status).toBe(200)
+ expect(result.headers.get('Cache-Control')).toBe('private, no-store')
+ expect(await result.json()).toEqual({
+ id: 'chat',
+ title: 'Title',
+ visibility: 'private',
+ userId: 'owner',
+ messages: []
+ })
+ expect(loadChat).toHaveBeenCalledWith('chat', 'owner')
+ })
+ it('returns 404 when the loader hides missing or inaccessible chats', async () => {
+ vi.mocked(loadChat).mockResolvedValue(null)
+ const result = await request()
+ expect(result.status).toBe(404)
+ expect(await result.json()).toEqual({ error: 'Chat not found' })
+ })
+ it('serves public history without a session', async () => {
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined)
+ const chat = {
+ id: 'chat',
+ title: 'Public',
+ visibility: 'public' as const,
+ userId: 'owner',
+ messages: [
+ {
+ id: 'message',
+ role: 'user' as const,
+ parts: [{ type: 'text' as const, text: 'Shared history' }]
+ }
+ ],
+ createdAt: new Date()
+ }
+ vi.mocked(loadChat).mockResolvedValue(chat)
+ const result = await request()
+ expect(result.status).toBe(200)
+ expect(result.headers.get('Cache-Control')).toBe('private, no-store')
+ expect((await result.json()).messages).toEqual(chat.messages)
+ expect(loadChat).toHaveBeenCalledWith('chat', undefined)
+ })
+
+ it('returns 404 for private history without a session', async () => {
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined)
+ vi.mocked(loadChat).mockResolvedValue(null)
+ const result = await request()
+ expect(result.status).toBe(404)
+ expect(await result.json()).toEqual({ error: 'Chat not found' })
+ expect(loadChat).toHaveBeenCalledWith('chat', undefined)
+ })
+})
diff --git a/app/api/chats/[id]/route.ts b/app/api/chats/[id]/route.ts
new file mode 100644
index 00000000..d2d43df6
--- /dev/null
+++ b/app/api/chats/[id]/route.ts
@@ -0,0 +1,38 @@
+import { NextRequest, NextResponse } from 'next/server'
+
+import { loadChat } from '@/lib/actions/chat'
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+
+export async function GET(
+ _request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ const headers = { 'Cache-Control': 'private, no-store' }
+ const userId = await getCurrentUserId()
+ try {
+ const { id } = await params
+ const chat = await loadChat(id, userId ?? undefined)
+ if (!chat) {
+ return NextResponse.json(
+ { error: 'Chat not found' },
+ { status: 404, headers }
+ )
+ }
+ return NextResponse.json(
+ {
+ id: chat.id,
+ title: chat.title,
+ visibility: chat.visibility,
+ userId: chat.userId,
+ messages: chat.messages
+ },
+ { headers }
+ )
+ } catch (error) {
+ console.error('API route error fetching chat:', error)
+ return NextResponse.json(
+ { error: 'Failed to load chat' },
+ { status: 500, headers }
+ )
+ }
+}
diff --git a/app/search/[id]/__tests__/page.test.tsx b/app/search/[id]/__tests__/page.test.tsx
new file mode 100644
index 00000000..a86735ee
--- /dev/null
+++ b/app/search/[id]/__tests__/page.test.tsx
@@ -0,0 +1,103 @@
+import { notFound, redirect } from 'next/navigation'
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { getChatMeta, loadChat } from '@/lib/actions/chat'
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import type { Chat as ChatRow } from '@/lib/db/schema'
+
+import { Chat } from '@/components/chat'
+
+import Page, { generateMetadata } from '../page'
+
+vi.mock('@/lib/actions/chat', () => ({
+ getChatMeta: vi.fn(),
+ loadChat: vi.fn()
+}))
+vi.mock('@/lib/auth/get-current-user', () => ({ getCurrentUserId: vi.fn() }))
+vi.mock('@/lib/auth/provider', () => ({ isAnonymousMode: () => false }))
+vi.mock('@/lib/model-selector/get-model-selector-data', () => ({
+ getModelSelectorData: vi.fn(async () => undefined)
+}))
+vi.mock('@/components/chat', () => ({ Chat: () => null }))
+vi.mock('next/navigation', () => ({
+ redirect: vi.fn(() => {
+ throw new Error('redirect')
+ }),
+ notFound: vi.fn(() => {
+ throw new Error('notFound')
+ })
+}))
+
+const props = () => ({ params: Promise.resolve({ id: 'chat' }) })
+const row: ChatRow = {
+ id: 'chat',
+ title: 'Title',
+ visibility: 'private',
+ userId: 'owner',
+ createdAt: new Date()
+}
+
+describe('saved chat page', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(getCurrentUserId).mockResolvedValue('owner')
+ vi.mocked(getChatMeta).mockResolvedValue(row)
+ })
+
+ it.each(['owner', undefined])(
+ 'renders metadata only for %s',
+ async userId => {
+ vi.mocked(getCurrentUserId).mockResolvedValue(userId)
+ vi.mocked(getChatMeta).mockResolvedValue({ ...row, visibility: 'public' })
+ const tree = await Page(props())
+ expect(tree.type).toBe(Chat)
+ expect(tree.props).toMatchObject({ id: 'chat', isGuest: !userId })
+ expect(tree.props).not.toHaveProperty('savedMessages')
+ expect(getChatMeta).toHaveBeenCalledWith('chat', userId)
+ expect(loadChat).not.toHaveBeenCalled()
+ }
+ )
+
+ it('renders an owner private chat without messages', async () => {
+ const tree = await Page(props())
+ expect(tree.props).not.toHaveProperty('savedMessages')
+ expect(redirect).not.toHaveBeenCalled()
+ expect(notFound).not.toHaveBeenCalled()
+ expect(loadChat).not.toHaveBeenCalled()
+ })
+
+ it('redirects logged-out visitors when the row is hidden or missing', async () => {
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined)
+ vi.mocked(getChatMeta).mockResolvedValue(null)
+ await expect(Page(props())).rejects.toThrow('redirect')
+ expect(redirect).toHaveBeenCalledWith('/auth/login?next=%2Fsearch%2Fchat')
+ expect(notFound).not.toHaveBeenCalled()
+ })
+
+ it('preserves the private-chat login guard', async () => {
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined)
+ await expect(Page(props())).rejects.toThrow('redirect')
+ expect(redirect).toHaveBeenCalledWith('/auth/login?next=%2Fsearch%2Fchat')
+ })
+
+ it('returns not found for signed-in visitors when the row is hidden or missing', async () => {
+ vi.mocked(getChatMeta).mockResolvedValue(null)
+ await expect(Page(props())).rejects.toThrow('notFound')
+ expect(redirect).not.toHaveBeenCalled()
+ })
+
+ it('uses the row title for metadata without loading messages', async () => {
+ vi.mocked(getChatMeta).mockResolvedValue({ ...row, title: 'x'.repeat(60) })
+ expect(await generateMetadata(props())).toEqual({ title: 'x'.repeat(50) })
+ expect(loadChat).not.toHaveBeenCalled()
+ })
+
+ it.each([null, { ...row, title: '' }])(
+ 'uses the metadata fallback for %s',
+ async chat => {
+ vi.mocked(getChatMeta).mockResolvedValue(chat)
+ expect(await generateMetadata(props())).toEqual({ title: 'Search' })
+ }
+ )
+})
diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsx
index d57b87d5..c0019727 100644
--- a/app/search/[id]/page.tsx
+++ b/app/search/[id]/page.tsx
@@ -1,8 +1,7 @@
+import { cache } from 'react'
import { notFound, redirect } from 'next/navigation'
-import { UIMessage } from 'ai'
-
-import { loadChat } from '@/lib/actions/chat'
+import { getChatMeta } from '@/lib/actions/chat'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { isAnonymousMode } from '@/lib/auth/provider'
import { getModelSelectorData } from '@/lib/model-selector/get-model-selector-data'
@@ -11,13 +10,16 @@ import { Chat } from '@/components/chat'
export const maxDuration = 60
+// Dedupe the read shared by generateMetadata and the page within one request
+const getChat = cache(getChatMeta)
+
export async function generateMetadata(props: {
params: Promise<{ id: string }>
}) {
const { id } = await props.params
const userId = await getCurrentUserId()
- const chat = await loadChat(id, userId)
+ const chat = await getChat(id, userId)
if (!chat) {
return { title: 'Search' }
@@ -34,7 +36,7 @@ export default async function SearchPage(props: {
const { id } = await props.params
const userId = await getCurrentUserId()
- const chat = await loadChat(id, userId)
+ const chat = await getChat(id, userId)
if (!chat) {
// A logged-out visitor cannot tell a private chat from a missing one:
@@ -52,7 +54,6 @@ export default async function SearchPage(props: {
redirect(`/auth/login?next=${encodeURIComponent(`/search/${id}`)}`)
}
- const messages: UIMessage[] = chat.messages
const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
const libraryAvailable = !isAnonymousMode()
const modelSelectorData = await getModelSelectorData()
@@ -60,7 +61,6 @@ export default async function SearchPage(props: {
return (
<Chat
id={id}
- savedMessages={messages}
isGuest={!userId}
isCloudDeployment={isCloudDeployment}
libraryAvailable={libraryAvailable}
diff --git a/components/__tests__/account-settings-dialog.test.tsx b/components/__tests__/account-settings-dialog.test.tsx
index 4c400bdf..72b3f8f6 100644
--- a/components/__tests__/account-settings-dialog.test.tsx
+++ b/components/__tests__/account-settings-dialog.test.tsx
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { deleteAccount } from '@/lib/actions/account'
import { signOut } from '@/lib/actions/auth'
import type { AppUser } from '@/lib/auth/types'
+import { chatStore } from '@/lib/chat-store'
import { AppUserProvider } from '@/lib/contexts/app-user-context'
import { AccountSettingsDialog } from '@/components/account-settings-dialog'
@@ -79,6 +80,8 @@ describe('AccountSettingsDialog', () => {
vi.mocked(signOut).mockResolvedValue({ success: true })
renderDialog()
+ chatStore.getOrCreate('cached', { messages: [] })
+
fireEvent.click(screen.getByRole('button', { name: 'Delete account' }))
fireEvent.click(
screen.getAllByRole('button', { name: 'Delete account' }).at(-1)!
@@ -87,6 +90,7 @@ describe('AccountSettingsDialog', () => {
await waitFor(() => {
expect(deleteAccount).toHaveBeenCalledTimes(1)
expect(signOut).toHaveBeenCalledTimes(1)
+ expect(chatStore.get('cached')).toBeUndefined()
expect(mockPush).toHaveBeenCalledWith('/')
expect(mockRefresh).toHaveBeenCalled()
})
diff --git a/components/__tests__/chat-cache-invalidation.test.tsx b/components/__tests__/chat-cache-invalidation.test.tsx
new file mode 100644
index 00000000..c4145832
--- /dev/null
+++ b/components/__tests__/chat-cache-invalidation.test.tsx
@@ -0,0 +1,89 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { clearChats, deleteChat } from '@/lib/actions/chat'
+import { chatStore } from '@/lib/chat-store'
+import type { Chat } from '@/lib/db/schema'
+
+import { ChatMenuItem } from '../sidebar/chat-menu-item'
+import { ClearHistoryAction } from '../sidebar/clear-history-action'
+
+vi.mock('@/lib/actions/chat', () => ({
+ deleteChat: vi.fn(),
+ clearChats: vi.fn()
+}))
+vi.mock('next/navigation', () => ({
+ usePathname: () => '/',
+ useRouter: () => ({ push: vi.fn() })
+}))
+vi.mock('@/components/ui/alert-dialog', () => {
+ const Container = ({ children }: any) => <div>{children}</div>
+ const Button = ({ children, onClick }: any) => (
+ <button onClick={onClick}>{children}</button>
+ )
+ return {
+ AlertDialog: Container,
+ AlertDialogContent: Container,
+ AlertDialogDescription: Container,
+ AlertDialogFooter: Container,
+ AlertDialogHeader: Container,
+ AlertDialogTitle: Container,
+ AlertDialogTrigger: Container,
+ AlertDialogCancel: Button,
+ AlertDialogAction: Button
+ }
+})
+vi.mock('@/components/ui/dropdown-menu', () => {
+ const Container = ({ children }: any) => <div>{children}</div>
+ return {
+ DropdownMenu: Container,
+ DropdownMenuContent: Container,
+ DropdownMenuItem: Container,
+ DropdownMenuTrigger: Container
+ }
+})
+vi.mock('@/components/ui/sidebar', () => {
+ const Container = ({ children }: any) => <div>{children}</div>
+ return {
+ SidebarMenuAction: Container,
+ SidebarMenuButton: Container,
+ SidebarMenuItem: Container,
+ SidebarGroupAction: Container
+ }
+})
+
+describe('chat cache invalidation actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ chatStore.clear()
+ chatStore.getOrCreate('cached', { messages: [] })
+ })
+
+ it('removes a sidebar-deleted chat after success', async () => {
+ vi.mocked(deleteChat).mockResolvedValue({ success: true })
+ render(
+ <ChatMenuItem
+ chat={{ id: 'cached', title: 'Chat', createdAt: new Date() } as Chat}
+ />
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }))
+ await waitFor(() => expect(chatStore.get('cached')).toBeUndefined())
+ expect(deleteChat).toHaveBeenCalledWith('cached')
+ })
+
+ it('clears the cache after clearing history', async () => {
+ vi.mocked(clearChats).mockResolvedValue({ success: true })
+ render(<ClearHistoryAction empty={false} />)
+ fireEvent.click(screen.getByRole('button', { name: 'Clear' }))
+ await waitFor(() => expect(chatStore.get('cached')).toBeUndefined())
+ expect(clearChats).toHaveBeenCalledOnce()
+ })
+
+ it('retains history if the deletion fails', async () => {
+ vi.mocked(clearChats).mockResolvedValue({ success: false, error: 'Failed' })
+ render(<ClearHistoryAction empty={false} />)
+ fireEvent.click(screen.getByRole('button', { name: 'Clear' }))
+ await waitFor(() => expect(clearChats).toHaveBeenCalledOnce())
+ expect(chatStore.get('cached')).toBeDefined()
+ })
+})
diff --git a/components/__tests__/chat-cache.test.tsx b/components/__tests__/chat-cache.test.tsx
new file mode 100644
index 00000000..4aff84dd
--- /dev/null
+++ b/components/__tests__/chat-cache.test.tsx
@@ -0,0 +1,686 @@
+import {
+ createContext,
+ type MutableRefObject,
+ StrictMode,
+ useContext
+} from 'react'
+import { hydrateRoot } from 'react-dom/client'
+import { renderToString } from 'react-dom/server'
+
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within
+} from '@testing-library/react'
+import { toast } from 'sonner'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { summarizeGenui } from '@/lib/analytics/genui-summary'
+import { captureClient } from '@/lib/analytics/posthog-client'
+import { chatStore } from '@/lib/chat-store'
+import { useChatContext } from '@/lib/contexts/chat-context'
+import type { UIMessage } from '@/lib/types/ai'
+
+import { Chat } from '../chat'
+
+const RefreshContext = createContext<(() => Promise<void>) | null>(null)
+const streamingRefs: MutableRefObject<boolean>[] = []
+
+vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))
+vi.mock('@/lib/analytics/genui-summary', () => ({ summarizeGenui: vi.fn() }))
+vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
+vi.mock('@/lib/contexts/app-user-context', () => ({
+ useAppUser: () => ({ id: 'owner' })
+}))
+vi.mock('@/lib/analytics/posthog-client', () => ({
+ getDistinctId: () => 'visitor',
+ captureClient: vi.fn()
+}))
+vi.mock('@/hooks/use-file-dropzone', () => ({ useFileDropzone: () => ({}) }))
+vi.mock('../draft/draft-store', () => ({
+ registerDraftSource: vi.fn(),
+ unregisterDraftSource: vi.fn()
+}))
+vi.mock('../chat-messages', () => ({
+ ChatMessages: ({ sections, reload, onUpdateMessage }: any) => (
+ <div>
+ {JSON.stringify(sections)}
+ <button onClick={() => reload('seed')}>Reload</button>
+ <button onClick={() => onUpdateMessage('seed', 'edited')}>Edit</button>
+ </div>
+ )
+}))
+vi.mock('../chat-panel', () => ({
+ ChatPanel: ({
+ disabled,
+ isHistoryPending,
+ messages,
+ append,
+ onNewChat,
+ stop,
+ input,
+ handleInputChange,
+ handleSubmit
+ }: any) => {
+ const { isStreamingRef } = useChatContext()
+ if (!streamingRefs.includes(isStreamingRef))
+ streamingRefs.push(isStreamingRef)
+ return (
+ <div>
+ {!isHistoryPending && messages.length === 0 && (
+ <h1>What would you like to know?</h1>
+ )}
+ <button disabled={disabled} onClick={() => append({ text: 'hello' })}>
+ Send
+ </button>
+ <button onClick={onNewChat}>New</button>
+ <button onClick={stop}>Stop</button>
+ <form onSubmit={handleSubmit}>
+ <textarea
+ aria-label="Message"
+ value={input}
+ onChange={handleInputChange}
+ />
+ <button type="submit">Submit</button>
+ </form>
+ </div>
+ )
+ }
+}))
+vi.mock('../drag-overlay', () => ({ DragOverlay: () => null }))
+vi.mock('../error-modal', () => ({
+ ErrorModal: ({ open, error }: any) =>
+ open ? <div role="dialog">{error.type}</div> : null
+}))
+vi.mock('../usage-budget-provider', () => ({
+ UsageBudgetWarning: () => null,
+ useUsageBudget: () => {
+ const refreshUsage = useContext(RefreshContext)
+ return { enabled: !!refreshUsage, refreshUsage }
+ }
+}))
+
+const messages = (text: string): UIMessage[] => [
+ { id: text, role: 'user', parts: [{ type: 'text', text }] }
+]
+const reply = (text: string) =>
+ new Response(JSON.stringify({ messages: messages(text) }))
+
+describe('Chat client cache', () => {
+ beforeEach(() => {
+ chatStore.clear()
+ streamingRefs.length = 0
+ vi.clearAllMocks()
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply('server')))
+ })
+ afterEach(() => {
+ chatStore.clear()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ const finishResponse = () =>
+ new Response(
+ 'data: {"type":"start","messageId":"answer"}\n\ndata: {"type":"finish","finishReason":"stop"}\n\ndata: [DONE]\n\n',
+ {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'x-vercel-ai-ui-message-stream': 'v1'
+ }
+ }
+ )
+
+ const mountSharedChat = (
+ refreshUsage = vi.fn().mockResolvedValue(undefined)
+ ) => {
+ const view = render(
+ <RefreshContext.Provider value={refreshUsage}>
+ <Chat id="shared" savedMessages={messages('seed')} />
+ </RefreshContext.Provider>
+ )
+ return { ...view, refreshUsage }
+ }
+
+ it.each(['Send', 'Reload', 'Edit'])(
+ 'keeps finish callbacks with the first component after %s',
+ async action => {
+ let resolve!: (response: Response) => void
+ vi.mocked(fetch).mockReturnValueOnce(
+ new Promise(r => {
+ resolve = r
+ })
+ )
+ vi.mocked(summarizeGenui).mockReturnValueOnce({
+ blockCount: 1,
+ contentBlockCount: 1,
+ imageCount: 0,
+ hasImage: false,
+ hasRelated: false,
+ componentTypes: ['Text']
+ })
+ const first = mountSharedChat()
+ const second = mountSharedChat()
+ await act(async () => {
+ fireEvent.click(within(first.container).getByText(action))
+ })
+ expect(streamingRefs[0].current).toBe(true)
+ expect(chatStore.get('shared')!.chat.status).toBe('submitted')
+ await act(async () => {
+ resolve(finishResponse())
+ })
+ await waitFor(() => expect(first.refreshUsage).toHaveBeenCalledOnce())
+ expect(second.refreshUsage).not.toHaveBeenCalled()
+ expect(captureClient).toHaveBeenCalledOnce()
+ expect(streamingRefs.map(ref => ref.current)).toEqual([false, false])
+ }
+ )
+
+ it('does not steal callbacks when another component mounts during a turn', async () => {
+ let resolve!: (response: Response) => void
+ vi.mocked(fetch).mockReturnValueOnce(
+ new Promise(r => {
+ resolve = r
+ })
+ )
+ const first = mountSharedChat()
+ await act(async () => {
+ fireEvent.click(within(first.container).getByText('Send'))
+ })
+ const owner = chatStore.get('shared')!.handlers.current
+ const second = mountSharedChat()
+ expect(chatStore.get('shared')!.handlers.current).toBe(owner)
+ second.unmount()
+ expect(chatStore.get('shared')!.handlers.current).toBe(owner)
+ await act(async () => {
+ resolve(finishResponse())
+ })
+ await waitFor(() => expect(first.refreshUsage).toHaveBeenCalledOnce())
+ expect(second.refreshUsage).not.toHaveBeenCalled()
+ first.unmount()
+ expect(chatStore.get('shared')!.handlers.current).toEqual({})
+ })
+
+ it.each(['finish', 'error'] as const)(
+ 'hands off the %s callback after the sender unmounts while streaming',
+ async outcome => {
+ let controller!: ReadableStreamDefaultController<Uint8Array>
+ const encoder = new TextEncoder()
+ const stream = new ReadableStream<Uint8Array>({
+ start(value) {
+ controller = value
+ controller.enqueue(
+ encoder.encode(
+ 'data: {"type":"start","messageId":"answer"}\n\ndata: {"type":"text-start","id":"text"}\n\ndata: {"type":"text-delta","id":"text","delta":"hello"}\n\n'
+ )
+ )
+ }
+ })
+ vi.mocked(fetch).mockResolvedValueOnce(
+ new Response(stream, {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'x-vercel-ai-ui-message-stream': 'v1'
+ }
+ })
+ )
+ const first = mountSharedChat()
+ fireEvent.click(within(first.container).getByText('Send'))
+ const entry = chatStore.get('shared')!
+ await waitFor(() => expect(entry.chat.status).toBe('streaming'))
+ first.unmount()
+ expect(entry.handlers.current).toEqual({})
+
+ const second = mountSharedChat()
+ const callback = vi.spyOn(
+ entry.handlers.current,
+ outcome === 'finish' ? 'onFinish' : 'onError'
+ )
+ await act(async () => {
+ const chunk =
+ outcome === 'finish'
+ ? { type: 'finish', finishReason: 'stop' }
+ : {
+ type: 'error',
+ errorText: JSON.stringify({
+ error: 'Request failed',
+ type: 'auth',
+ code: 'auth_required'
+ })
+ }
+ controller.enqueue(
+ encoder.encode(`data: ${JSON.stringify(chunk)}\n\ndata: [DONE]\n\n`)
+ )
+ controller.close()
+ })
+
+ await waitFor(() => expect(callback).toHaveBeenCalledOnce())
+ expect(second.refreshUsage).toHaveBeenCalledOnce()
+ expect(first.refreshUsage).not.toHaveBeenCalled()
+ if (outcome === 'error') {
+ expect(within(second.container).getByRole('dialog')).toHaveTextContent(
+ 'auth'
+ )
+ }
+ }
+ )
+
+ it.each([
+ ['rate-limit', 'rate_limit', 429],
+ ['auth', 'auth_required', 401],
+ ['forbidden', 'forbidden', 403]
+ ] as const)(
+ 'shows a %s modal only in the sending component',
+ async (type, code, status) => {
+ let resolve!: (response: Response) => void
+ vi.mocked(fetch).mockReturnValueOnce(
+ new Promise(r => {
+ resolve = r
+ })
+ )
+ const first = mountSharedChat()
+ const second = mountSharedChat()
+ await act(async () => {
+ fireEvent.click(within(first.container).getByText('Send'))
+ })
+ expect(streamingRefs[0].current).toBe(true)
+ await act(async () => {
+ resolve(
+ new Response(
+ JSON.stringify({ error: 'Request failed', type, code }),
+ { status }
+ )
+ )
+ })
+ expect(
+ await within(first.container).findByRole('dialog')
+ ).toHaveTextContent(type)
+ expect(
+ within(second.container).queryByRole('dialog')
+ ).not.toBeInTheDocument()
+ expect(first.refreshUsage).toHaveBeenCalledOnce()
+ expect(second.refreshUsage).not.toHaveBeenCalled()
+ expect(streamingRefs.map(ref => ref.current)).toEqual([false, false])
+ }
+ )
+
+ it('shows a general error toast once for the sending component', async () => {
+ vi.mocked(fetch).mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ error: 'Request failed',
+ type: 'general',
+ code: 'unknown'
+ }),
+ { status: 500 }
+ )
+ )
+ const first = mountSharedChat()
+ const second = mountSharedChat()
+ await act(async () => {
+ fireEvent.click(within(first.container).getByText('Send'))
+ })
+ await waitFor(() => expect(toast.error).toHaveBeenCalledOnce())
+ expect(first.refreshUsage).toHaveBeenCalledOnce()
+ expect(second.refreshUsage).not.toHaveBeenCalled()
+ expect(captureClient).not.toHaveBeenCalled()
+ expect(streamingRefs.map(ref => ref.current)).toEqual([false, false])
+ })
+
+ it.each(['ready', 'error'])(
+ 'clears stale streaming refs in every component on %s',
+ async status => {
+ mountSharedChat()
+ mountSharedChat()
+ const chat = chatStore.get('shared')!.chat as unknown as {
+ state: { status: string }
+ }
+ await act(async () => {
+ chat.state.status = 'streaming'
+ })
+ streamingRefs.forEach(ref => {
+ ref.current = true
+ })
+ await act(async () => {
+ chat.state.status = status
+ })
+ await waitFor(() =>
+ expect(streamingRefs.map(ref => ref.current)).toEqual([false, false])
+ )
+ }
+ )
+
+ it.each([false, true])(
+ 'renders a skeleton before effects for guest=%s',
+ isGuest => {
+ const html = renderToString(<Chat id="initial" isGuest={isGuest} />)
+ expect(html).toContain('Loading chat')
+ expect(fetch).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([false, true])(
+ 'hydrates unloaded history for guest=%s without a mismatch',
+ async isGuest => {
+ const host = document.createElement('div')
+ const element = <Chat id="hydrate" isGuest={isGuest} />
+ host.innerHTML = renderToString(element)
+ const serverHtml = host.innerHTML
+ document.body.appendChild(host)
+ const onRecoverableError = vi.fn()
+ let resolve!: (response: Response) => void
+ vi.mocked(fetch).mockReturnValueOnce(
+ new Promise(r => {
+ resolve = r
+ })
+ )
+ let root!: ReturnType<typeof hydrateRoot>
+ try {
+ await act(async () => {
+ root = hydrateRoot(host, element, { onRecoverableError })
+ })
+ expect(host.innerHTML).toBe(serverHtml)
+ expect(onRecoverableError).not.toHaveBeenCalled()
+ expect(fetch).toHaveBeenCalledOnce()
+ await act(async () => {
+ resolve(reply('hydrated history'))
+ })
+ expect(host).toHaveTextContent('hydrated history')
+ } finally {
+ act(() => root.unmount())
+ host.remove()
+ }
+ }
+ )
+
+ it('hides the home state while history loads and after a load error', async () => {
+ let reject!: (error: Error) => void
+ vi.mocked(fetch).mockReturnValueOnce(
+ new Promise((_, r) => {
+ reject = r
+ })
+ )
+ render(<Chat id="existing" />)
+ expect(
+ screen.getByRole('status', { name: 'Loading chat' })
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByRole('heading', { name: 'What would you like to know?' })
+ ).not.toBeInTheDocument()
+ expect(screen.getByTestId('full-chat')).not.toHaveClass('justify-center')
+ await act(async () => {
+ reject(new Error('Failed to load chat'))
+ })
+ expect(screen.getByRole('alert')).toHaveTextContent('Failed to load chat')
+ expect(
+ screen.queryByRole('heading', { name: 'What would you like to know?' })
+ ).not.toBeInTheDocument()
+ fireEvent.click(screen.getByText('New'))
+ expect(
+ screen.getByRole('heading', { name: 'What would you like to know?' })
+ ).toBeInTheDocument()
+ })
+
+ it.each([{}, { id: 'query', query: 'hello' }])(
+ 'keeps the home state for a new chat %s',
+ props => {
+ render(<Chat {...props} />)
+ expect(
+ screen.getByRole('heading', { name: 'What would you like to know?' })
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByRole('status', { name: 'Loading chat' })
+ ).not.toBeInTheDocument()
+ expect(fetch).not.toHaveBeenCalled()
+ }
+ )
+
+ it('fetches an owner history once and reuses it on reopening', async () => {
+ const first = render(<Chat id="a" />)
+ expect(await screen.findByText(/server/)).toBeInTheDocument()
+ first.unmount()
+ render(<Chat id="a" />)
+ expect(screen.getByText(/server/)).toBeInTheDocument()
+ expect(fetch).toHaveBeenCalledOnce()
+ })
+
+ it('loads guest history under Strict Mode', async () => {
+ render(
+ <StrictMode>
+ <Chat id="public" isGuest />
+ </StrictMode>
+ )
+ expect(await screen.findByText(/server/)).toBeInTheDocument()
+ expect(screen.getByText('Send')).toBeEnabled()
+ expect(fetch).toHaveBeenCalledOnce()
+ })
+
+ it('loads public guest history and fetches again on a new mount', async () => {
+ let resolve!: (response: Response) => void
+ vi.mocked(fetch).mockReturnValueOnce(
+ new Promise(r => {
+ resolve = r
+ })
+ )
+ const first = render(<Chat id="public" isGuest />)
+ expect(
+ screen.getByRole('status', { name: 'Loading chat' })
+ ).toBeInTheDocument()
+ expect(screen.getByText('Send')).toBeDisabled()
+ expect(fetch).toHaveBeenCalledWith('/api/chats/public', {
+ cache: 'no-store'
+ })
+ await act(async () => {
+ resolve(reply('public history'))
+ })
+ expect(screen.getByText(/public history/)).toBeInTheDocument()
+ expect(screen.getByText('Send')).toBeEnabled()
+ expect(chatStore.get('public')).toBeUndefined()
+ first.unmount()
+ render(<Chat id="public" isGuest />)
+ expect(await screen.findByText(/server/)).toBeInTheDocument()
+ expect(fetch).toHaveBeenCalledTimes(2)
+ })
+
+ it('sends the full fetched history for a guest follow-up', async () => {
+ render(<Chat id="public" isGuest />)
+ expect(await screen.findByText(/server/)).toBeInTheDocument()
+ vi.mocked(fetch).mockResolvedValueOnce(
+ new Response(
+ 'data: {"type":"start","messageId":"answer"}\n\ndata: {"type":"finish","finishReason":"stop"}\n\ndata: [DONE]\n\n',
+ {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'x-vercel-ai-ui-message-stream': 'v1'
+ }
+ }
+ )
+ )
+ fireEvent.click(screen.getByText('Send'))
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2))
+ const body = JSON.parse(vi.mocked(fetch).mock.calls[1][1]!.body as string)
+ expect(body.messages).toHaveLength(2)
+ expect(body.messages[0]).toEqual(messages('server')[0])
+ expect(body.isNewChat).toBe(false)
+ await waitFor(() => expect(screen.getByText('Send')).toBeEnabled())
+ })
+
+ it('does not fetch history for a new query chat', () => {
+ render(<Chat id="query-chat" query="hello" />)
+ expect(screen.getByText('Send')).toBeEnabled()
+ expect(fetch).not.toHaveBeenCalled()
+ })
+
+ it('reopens the same live Chat without fetching within the verified window', () => {
+ const first = render(<Chat id="a" savedMessages={messages('seed')} />)
+ act(() => {
+ chatStore.get('a')!.chat.messages = messages('latest')
+ })
+ const instance = chatStore.get('a')!.chat
+ first.unmount()
+ render(<Chat id="a" savedMessages={messages('old page')} />)
+ expect(chatStore.get('a')!.chat).toBe(instance)
+ expect(screen.getByText(/latest/)).toBeInTheDocument()
+ expect(fetch).not.toHaveBeenCalled()
+ })
+
+ it('shows cached messages while revalidating an older entry', async () => {
+ const first = render(<Chat id="a" savedMessages={messages('cached')} />)
+ first.unmount()
+ chatStore.get('a')!.verifiedAt -= 30_000
+ let resolve!: (response: Response) => void
+ vi.mocked(fetch).mockReturnValue(
+ new Promise(r => {
+ resolve = r
+ })
+ )
+ render(<Chat id="a" savedMessages={messages('old page')} />)
+ expect(screen.getByText(/cached/)).toBeInTheDocument()
+ expect(fetch).toHaveBeenCalledOnce()
+ await act(async () => {
+ resolve(reply('fresh'))
+ })
+ expect(screen.getByText(/fresh/)).toBeInTheDocument()
+ })
+
+ it('blocks sending while unverified history loads', async () => {
+ let resolve!: (response: Response) => void
+ vi.mocked(fetch).mockReturnValue(
+ new Promise(r => {
+ resolve = r
+ })
+ )
+ render(<Chat id="a" />)
+ expect(screen.getByText('Send')).toBeDisabled()
+ await act(async () => {
+ resolve(reply('loaded'))
+ })
+ expect(screen.getByText('Send')).toBeEnabled()
+ })
+
+ it.each(['seeded', 'local'] as const)(
+ 'keeps %s messages sendable after a background refresh fails',
+ async source => {
+ const logError = vi.spyOn(console, 'error').mockImplementation(() => {})
+ chatStore.setUser('owner')
+ const entry = chatStore.getOrCreate('a', {
+ messages: source === 'seeded' ? messages('cached') : undefined
+ })
+ if (source === 'local') entry.chat.messages = messages('cached')
+ if (entry.verifiedAt !== 0) entry.verifiedAt -= 30_000
+ vi.mocked(fetch).mockRejectedValueOnce(new Error('Network unavailable'))
+
+ render(<Chat id="a" savedMessages={messages('old page')} />)
+
+ await waitFor(() => expect(logError).toHaveBeenCalledOnce())
+ expect(screen.getByText(/cached/)).toBeInTheDocument()
+ expect(screen.getByText('Send')).toBeEnabled()
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ }
+ )
+
+ it('shows a blocking error and retry when no history could be loaded', async () => {
+ vi.mocked(fetch).mockRejectedValueOnce(new Error('Failed to load chat'))
+ render(<Chat id="a" />)
+ expect(
+ screen.getByRole('status', { name: 'Loading chat' })
+ ).toBeInTheDocument()
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'Failed to load chat'
+ )
+ expect(screen.getByText('Send')).toBeDisabled()
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ await waitFor(() => expect(screen.getByText('Send')).toBeEnabled())
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ })
+
+ it('creates an empty client entry on New and invalidates on stop', async () => {
+ render(<Chat id="a" savedMessages={messages('seed')} />)
+ fireEvent.click(screen.getByText('New'))
+ await waitFor(() =>
+ expect(screen.queryByText(/seed/)).not.toBeInTheDocument()
+ )
+ expect(fetch).not.toHaveBeenCalled()
+ expect(chatStore.get('a')!.chat.messages).toEqual(messages('seed'))
+ fireEvent.click(screen.getByText('Stop'))
+ })
+
+ it('discards a background response while the cached Chat streams', async () => {
+ const first = render(<Chat id="a" savedMessages={messages('cached')} />)
+ first.unmount()
+ chatStore.get('a')!.verifiedAt -= 30_000
+ let resolve!: (response: Response) => void
+ vi.mocked(fetch).mockReturnValue(
+ new Promise(r => {
+ resolve = r
+ })
+ )
+ render(<Chat id="a" savedMessages={messages('old page')} />)
+ await act(async () => {
+ const chat = chatStore.get('a')!.chat as unknown as {
+ state: { status: string }
+ }
+ chat.state.status = 'streaming'
+ resolve(reply('obsolete'))
+ })
+ expect(chatStore.get('a')!.chat.messages).toEqual(messages('cached'))
+ })
+
+ it('retains the homepage entry after pushing the first-message URL', async () => {
+ window.history.replaceState({}, '', '/')
+ vi.mocked(fetch).mockImplementation(() =>
+ Promise.resolve(
+ new Response(
+ 'data: {"type":"start","messageId":"answer"}\n\ndata: {"type":"finish","finishReason":"stop"}\n\ndata: [DONE]\n\n',
+ {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'x-vercel-ai-ui-message-stream': 'v1'
+ }
+ }
+ )
+ )
+ )
+ const view = render(<Chat />)
+ fireEvent.change(screen.getByLabelText('Message'), {
+ target: { value: 'hello' }
+ })
+ fireEvent.click(screen.getByText('Submit'))
+ const id = window.location.pathname.split('/').pop()!
+ expect(window.location.pathname).toBe(`/search/${id}`)
+ const entry = chatStore.get(id)!
+ expect(entry).toBeDefined()
+ await waitFor(() => expect(entry.hasServerHistory).toBe(true))
+ view.rerender(<Chat id={id} savedMessages={[]} />)
+ expect(chatStore.get(id)).toBe(entry)
+ expect(entry.chat.messages[0].parts).toEqual([
+ { type: 'text', text: 'hello' }
+ ])
+ expect(fetch).toHaveBeenCalledOnce()
+ fireEvent.click(screen.getByText('Stop'))
+ expect(entry.verifiedAt).toBe(0)
+ window.history.replaceState({}, '', '/')
+ })
+
+ it('does not retain guest messages when changing conversations', () => {
+ const view = render(
+ <Chat id="a" savedMessages={messages('first')} isGuest />
+ )
+ view.rerender(<Chat id="b" savedMessages={messages('second')} isGuest />)
+ view.rerender(<Chat id="a" savedMessages={messages('reloaded')} isGuest />)
+ expect(screen.getByText(/reloaded/)).toBeInTheDocument()
+ expect(screen.queryByText(/first/)).not.toBeInTheDocument()
+ expect(fetch).not.toHaveBeenCalled()
+ })
+
+ it('keeps guest state outside the shared store and skips history fetching', () => {
+ render(
+ <Chat id="guest" savedMessages={messages('guest history')} isGuest />
+ )
+ expect(screen.getByText(/guest history/)).toBeInTheDocument()
+ expect(chatStore.get('guest')).toBeUndefined()
+ expect(fetch).not.toHaveBeenCalled()
+ })
+})
diff --git a/components/__tests__/chat-panel.test.tsx b/components/__tests__/chat-panel.test.tsx
index 780151ac..3d18300f 100644
--- a/components/__tests__/chat-panel.test.tsx
+++ b/components/__tests__/chat-panel.test.tsx
@@ -1,9 +1,10 @@
import React from 'react'
-import { fireEvent, render, waitFor } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { toast } from 'sonner'
import { beforeEach, describe, expect, test, vi } from 'vitest'
+import { SHORTCUT_EVENTS } from '@/lib/keyboard-shortcuts'
import type { UploadedFile } from '@/lib/types'
import { deleteCookie, getCookie, setCookie } from '@/lib/utils/cookies'
@@ -18,7 +19,7 @@ vi.mock('../artifact/artifact-context', () => ({
}))
vi.mock('../action-buttons', () => ({
- ActionButtons: () => null
+ ActionButtons: () => <div data-testid="suggestions" />
}))
vi.mock('../library/library-context', () => ({
@@ -69,6 +70,40 @@ describe('ChatPanel', () => {
deleteCookie('searchMode')
})
+ test('hides the home panel while history is unresolved and shows it for a new chat', () => {
+ const props = {
+ chatId: 'chat',
+ input: '',
+ handleInputChange: vi.fn(),
+ handleSubmit: vi.fn(),
+ status: 'ready' as const,
+ messages: [],
+ setMessages: vi.fn(),
+ stop: vi.fn(),
+ append: vi.fn(),
+ showScrollToBottomButton: false,
+ scrollContainerRef: React.createRef<HTMLDivElement>(),
+ uploadedFiles: [],
+ setUploadedFiles: vi.fn(),
+ quotedContexts: [],
+ setQuotedContexts: vi.fn(),
+ noteContexts: [],
+ setNoteContexts: vi.fn()
+ }
+ const view = render(<ChatPanel {...props} isHistoryPending />)
+ expect(
+ screen.queryByRole('heading', { name: 'What would you like to know?' })
+ ).not.toBeInTheDocument()
+ expect(screen.queryByTestId('suggestions')).not.toBeInTheDocument()
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
+ view.rerender(<ChatPanel {...props} />)
+ expect(
+ screen.getByRole('heading', { name: 'What would you like to know?' })
+ ).toBeInTheDocument()
+ expect(screen.getByTestId('suggestions')).toBeInTheDocument()
+ expect(screen.getByRole('textbox')).toBeInTheDocument()
+ })
+
test('preserves and submits the initial query after resetting a stale adaptive cookie', async () => {
const append = vi.fn()
const onAdaptiveModeAuthRequired = vi.fn()
@@ -112,6 +147,36 @@ describe('ChatPanel', () => {
expect(onAdaptiveModeAuthRequired).not.toHaveBeenCalled()
})
+ test('starts a new chat without clearing the cached conversation', () => {
+ const setMessages = vi.fn()
+ const onNewChat = vi.fn()
+ render(
+ <ChatPanel
+ chatId="chat"
+ input=""
+ handleInputChange={vi.fn()}
+ handleSubmit={vi.fn()}
+ status="ready"
+ messages={[]}
+ setMessages={setMessages}
+ stop={vi.fn()}
+ append={vi.fn()}
+ showScrollToBottomButton={false}
+ scrollContainerRef={React.createRef<HTMLDivElement>()}
+ uploadedFiles={[]}
+ setUploadedFiles={vi.fn()}
+ quotedContexts={[]}
+ setQuotedContexts={vi.fn()}
+ noteContexts={[]}
+ setNoteContexts={vi.fn()}
+ onNewChat={onNewChat}
+ />
+ )
+ fireEvent(window, new Event(SHORTCUT_EVENTS.newChat))
+ expect(onNewChat).toHaveBeenCalledOnce()
+ expect(setMessages).not.toHaveBeenCalled()
+ })
+
describe('attachment limit', () => {
const existing = (count: number): UploadedFile[] =>
Array.from({ length: count }, (_, i) => ({
diff --git a/components/__tests__/invitations-manager.test.tsx b/components/__tests__/invitations-manager.test.tsx
index 3d56c2ff..d2ed050a 100644
--- a/components/__tests__/invitations-manager.test.tsx
+++ b/components/__tests__/invitations-manager.test.tsx
@@ -9,6 +9,9 @@ import {
import { InvitationsManager } from '@/components/admin/invitations-manager'
+const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }))
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh }) }))
+
vi.mock('@/lib/actions/admin', () => ({
createInvitationAction: vi.fn(),
revokeInvitationAction: vi.fn()
@@ -99,6 +102,7 @@ describe('InvitationsManager', () => {
})
expect(screen.getByText('[email protected]')).toBeInTheDocument()
+ expect(refresh).toHaveBeenCalledOnce()
expect(
screen.getByDisplayValue(
'http://localhost:3000/auth/sign-up?token=tok3'
@@ -134,6 +138,7 @@ describe('InvitationsManager', () => {
await waitFor(() => {
expect(revokeInvitationAction).toHaveBeenCalledWith('inv-1')
+ expect(refresh).toHaveBeenCalledOnce()
expect(screen.getAllByText('Revoked')).toHaveLength(2)
})
})
diff --git a/components/__tests__/member-role-manager.test.tsx b/components/__tests__/member-role-manager.test.tsx
index 7e2ddae8..e860af21 100644
--- a/components/__tests__/member-role-manager.test.tsx
+++ b/components/__tests__/member-role-manager.test.tsx
@@ -5,6 +5,9 @@ import { promoteMemberAction } from '@/lib/actions/admin'
import { MemberRoleManager } from '@/components/admin/member-role-manager'
+const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }))
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh }) }))
+
vi.mock('@/lib/actions/admin', () => ({
promoteMemberAction: vi.fn()
}))
@@ -29,6 +32,7 @@ describe('MemberRoleManager', () => {
await waitFor(() => {
expect(promoteMemberAction).toHaveBeenCalledWith({ userId: 'user-1' })
expect(screen.getByText('Promoted')).toBeInTheDocument()
+ expect(refresh).toHaveBeenCalledOnce()
})
expect(
screen.queryByRole('button', { name: 'Promote to admin' })
diff --git a/components/__tests__/user-menu.test.tsx b/components/__tests__/user-menu.test.tsx
index 0349efd7..7a1d53ef 100644
--- a/components/__tests__/user-menu.test.tsx
+++ b/components/__tests__/user-menu.test.tsx
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { signOut } from '@/lib/actions/auth'
import type { AppUser } from '@/lib/auth/types'
+import { chatStore } from '@/lib/chat-store'
import { AppUserProvider } from '@/lib/contexts/app-user-context'
import UserMenu from '@/components/user-menu'
@@ -102,10 +103,13 @@ describe('UserMenu', () => {
</AppUserProvider>
)
+ chatStore.getOrCreate('cached', { messages: [] })
+
fireEvent.click(screen.getByRole('menuitem', { name: /Logout/ }))
await waitFor(() => {
expect(signOut).toHaveBeenCalledTimes(1)
+ expect(chatStore.get('cached')).toBeUndefined()
expect(mockPush).toHaveBeenCalledWith('/')
expect(mockRefresh).toHaveBeenCalled()
})
diff --git a/components/account-settings-dialog.tsx b/components/account-settings-dialog.tsx
index 2b2f9f5e..78b1e771 100644
--- a/components/account-settings-dialog.tsx
+++ b/components/account-settings-dialog.tsx
@@ -14,6 +14,7 @@ import { toast } from 'sonner'
import { deleteAccount } from '@/lib/actions/account'
import { signOut } from '@/lib/actions/auth'
import type { AppUser } from '@/lib/auth/types'
+import { chatStore } from '@/lib/chat-store'
import { useAuthCapabilities } from '@/lib/contexts/app-user-context'
import {
@@ -71,6 +72,7 @@ export function AccountSettingsDialog({
const result = await deleteAccount()
if (result.success) {
+ chatStore.setUser(null)
try {
await signOut()
} catch (error) {
diff --git a/components/admin/invitations-manager.tsx b/components/admin/invitations-manager.tsx
index ed550397..7058e268 100644
--- a/components/admin/invitations-manager.tsx
+++ b/components/admin/invitations-manager.tsx
@@ -1,6 +1,7 @@
'use client'
import { useState } from 'react'
+import { useRouter } from 'next/navigation'
import {
createInvitationAction,
@@ -17,6 +18,7 @@ export function InvitationsManager({
}: {
invitations: InvitationView[]
}) {
+ const router = useRouter()
const [invitations, setInvitations] = useState(initialInvitations)
// Expiration is computed server-side when the list is rendered, and
// each row shows its exact expiry time. The server rejects expired
@@ -42,6 +44,7 @@ export function InvitationsManager({
setInvitations(current => [result.invitation!, ...current])
setNewLink(result.link ?? null)
setEmail('')
+ router.refresh()
} else {
setError(result.error ?? 'Failed to create invitation')
}
@@ -65,6 +68,7 @@ export function InvitationsManager({
return
}
if (result.success) {
+ router.refresh()
setInvitations(current =>
current.map(invitation =>
invitation.id === id ? { ...invitation, revoked: true } : invitation
diff --git a/components/admin/member-role-manager.tsx b/components/admin/member-role-manager.tsx
index d5fdfe2d..27d3652c 100644
--- a/components/admin/member-role-manager.tsx
+++ b/components/admin/member-role-manager.tsx
@@ -1,6 +1,7 @@
'use client'
import { useState } from 'react'
+import { useRouter } from 'next/navigation'
import { promoteMemberAction } from '@/lib/actions/admin'
import type { MemberSummary } from '@/lib/auth/better-auth/members'
@@ -8,6 +9,7 @@ import type { MemberSummary } from '@/lib/auth/better-auth/members'
import { Button } from '@/components/ui/button'
export function MemberRoleManager({ members }: { members: MemberSummary[] }) {
+ const router = useRouter()
const [promotedIds, setPromotedIds] = useState<Set<string>>(new Set())
const [error, setError] = useState<string | null>(null)
const [busyId, setBusyId] = useState<string | null>(null)
@@ -19,6 +21,7 @@ export function MemberRoleManager({ members }: { members: MemberSummary[] }) {
const result = await promoteMemberAction({ userId })
if (result.success) {
setPromotedIds(prev => new Set(prev).add(userId))
+ router.refresh()
} else {
setError(result.error ?? 'Failed to promote member')
}
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index 08ab3156..98854bb5 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -82,6 +82,8 @@ function getSearchModeSnapshot(): SearchMode {
}
interface ChatPanelProps {
+ disabled?: boolean
+ isHistoryPending?: boolean
chatId: string
input: string
handleInputChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
@@ -115,6 +117,8 @@ interface ChatPanelProps {
}
export function ChatPanel({
+ disabled = false,
+ isHistoryPending = false,
chatId,
input,
handleInputChange,
@@ -207,7 +211,7 @@ export function ChatPanel({
}, [uploadedFiles])
const handleNewChat = useCallback(() => {
- setMessages([])
+ if (!onNewChat) setMessages([])
closeArtifact()
// Reset focus state when clearing chat
setIsInputFocused(false)
@@ -448,6 +452,8 @@ export function ChatPanel({
}
}
+ if (isHistoryPending) return null
+
return (
<div
className={cn(
@@ -784,7 +790,7 @@ export function ChatPanel({
placeholder={messages.length > 0 ? 'Reply...' : 'Ask anything...'}
spellCheck={false}
value={input}
- disabled={isLoading || isToolInvocationInProgress()}
+ disabled={disabled || isLoading || isToolInvocationInProgress()}
className="resize-none w-full min-h-12 bg-transparent border-0 p-3 md:p-4 text-sm placeholder:text-muted-foreground focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50"
onChange={handleInputChange}
onPaste={e => {
@@ -946,7 +952,9 @@ export function ChatPanel({
'size-8 md:size-10 rounded-full'
)}
disabled={
- (!hasPendingInput && !isLoading) || !hasAvailableModels
+ disabled ||
+ (!hasPendingInput && !isLoading) ||
+ !hasAvailableModels
}
onClick={isLoading ? stop : undefined}
title={
diff --git a/components/chat.tsx b/components/chat.tsx
index 10a5266b..8fb08ffa 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -1,14 +1,23 @@
'use client'
-import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore
+} from 'react'
import { useRouter } from 'next/navigation'
import { useChat } from '@ai-sdk/react'
-import { DefaultChatTransport } from 'ai'
import { toast } from 'sonner'
import { summarizeGenui } from '@/lib/analytics/genui-summary'
-import { captureClient, getDistinctId } from '@/lib/analytics/posthog-client'
+import { captureClient } from '@/lib/analytics/posthog-client'
+import { type ChatHandlers, ChatStore, chatStore } from '@/lib/chat-store'
+import { useAppUser } from '@/lib/contexts/app-user-context'
import { ChatProvider } from '@/lib/contexts/chat-context'
import { generateId } from '@/lib/db/schema'
import {
@@ -37,8 +46,11 @@ import { getTextFromParts } from '@/lib/utils/message-utils'
import { useFileDropzone } from '@/hooks/use-file-dropzone'
import { registerDraftSource, unregisterDraftSource } from './draft/draft-store'
+import { Button } from './ui/button'
+import { Card, CardDescription, CardFooter, CardHeader } from './ui/card'
import { ChatMessages } from './chat-messages'
import { ChatPanel } from './chat-panel'
+import { DefaultSkeleton } from './default-skeleton'
import { DragOverlay } from './drag-overlay'
import { ErrorModal } from './error-modal'
import { UsageBudgetWarning, useUsageBudget } from './usage-budget-provider'
@@ -52,7 +64,7 @@ interface ChatSection {
export function Chat({
id: providedId,
- savedMessages = [],
+ savedMessages,
query,
isGuest = false,
isCloudDeployment = false,
@@ -81,6 +93,12 @@ export function Chat({
// - Otherwise, generate a new ID (e.g., / homepage for new chats)
const [chatId, setChatId] = useState(() => providedId || generateId())
+ const [previousId, setPreviousId] = useState(providedId)
+ if (previousId !== providedId) {
+ setPreviousId(providedId)
+ if (providedId) setChatId(providedId)
+ }
+
// Callback to reset chat state when user clicks "New" button
const handleNewChat = () => {
const newId = generateId()
@@ -139,112 +157,140 @@ export function Chat({
[isGuest, isCloudDeployment]
)
+ const user = useAppUser()
+ const { store, entry } = useMemo(() => {
+ const store =
+ isGuest || typeof window === 'undefined' ? new ChatStore() : chatStore
+ store.setUser(user?.id ?? null)
+ const entry = store.getOrCreate(chatId, {
+ messages: chatId === providedId ? savedMessages : undefined,
+ isNew: chatId !== providedId || !!query,
+ isGuest
+ })
+ return { store, entry }
+ }, [chatId, providedId, user?.id, savedMessages, isGuest, query])
+ useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot)
+ const handlersRef = useRef<ChatHandlers>({})
+ useEffect(() => {
+ handlersRef.current = {
+ onFinish: ({ message, isError }) => {
+ isStreamingRef.current = false
+ if (isError) return
+ if (usageBudgetEnabled) void refreshUsage()
+
+ const summary = summarizeGenui(getTextFromParts(message.parts))
+ if (summary) {
+ captureClient('genui_component_shown', { chatId, ...summary })
+ }
+ },
+ onError: error => {
+ isStreamingRef.current = false
+ const publicError = toPublicErrorPayload(error)
+
+ if (
+ usageBudgetEnabled &&
+ publicError.code === 'usage_limit' &&
+ publicError.reason !== 'hourly'
+ ) {
+ const resetAt = publicError.resetAt
+ ? new Date(publicError.resetAt).toISOString()
+ : undefined
+ void refreshUsage().then(usage => {
+ showUsageLimit(usage?.resetAt ?? resetAt)
+ })
+ } else if (publicError.type === 'rate-limit') {
+ if (usageBudgetEnabled) void refreshUsage()
+ setErrorModal({
+ open: true,
+ type: 'rate-limit',
+ message: publicError.error,
+ details: getPublicRateLimitDetails(publicError)
+ })
+ } else if (publicError.type === 'auth') {
+ if (usageBudgetEnabled) void refreshUsage()
+ setErrorModal({
+ open: true,
+ type: 'auth',
+ message: publicError.error
+ })
+ } else if (publicError.type === 'forbidden') {
+ if (usageBudgetEnabled) void refreshUsage()
+ setErrorModal({
+ open: true,
+ type: 'forbidden',
+ message: publicError.error
+ })
+ } else {
+ if (usageBudgetEnabled) void refreshUsage()
+ toast.error(publicError.error)
+ }
+ }
+ }
+ })
+ const handlers = useMemo<ChatHandlers>(
+ () => ({
+ onFinish: event => handlersRef.current.onFinish?.(event),
+ onError: error => handlersRef.current.onError?.(error)
+ }),
+ []
+ )
+ useEffect(() => {
+ if (
+ (entry.chat.status === 'submitted' ||
+ entry.chat.status === 'streaming') &&
+ !entry.handlers.current.onFinish &&
+ !entry.handlers.current.onError
+ ) {
+ store.attachHandlers(entry, handlers)
+ }
+ return () => {
+ if (entry.handlers.current === handlers) entry.handlers.current = {}
+ if (isGuest) void entry.chat.stop()
+ }
+ }, [store, entry, handlers, isGuest])
+ useEffect(() => {
+ void store.revalidate(chatId)
+ }, [store, entry, chatId])
const {
messages,
status,
setMessages,
- stop,
sendMessage,
regenerate,
addToolResult,
error
- } = useChat({
- id: chatId, // use the client-generated or provided chatId
- transport: new DefaultChatTransport({
- api: '/api/chat',
- prepareSendMessagesRequest: ({ messages, trigger, messageId, body }) => {
- // Simplify by passing AI SDK's default trigger values directly
- const lastMessage = messages[messages.length - 1]
- const messageToRegenerate =
- trigger === 'regenerate-message'
- ? messages.find(m => m.id === messageId)
- : undefined
-
- return {
- body: {
- ...body,
- trigger, // Use AI SDK's default trigger value directly
- chatId: chatId,
- messageId,
- clientSource: 'web',
- analyticsId: getDistinctId(),
- ...(isGuest ? { messages } : {}),
- message:
- trigger === 'regenerate-message' &&
- messageToRegenerate?.role === 'user'
- ? messageToRegenerate
- : trigger === 'submit-message'
- ? lastMessage
- : undefined,
- isNewChat:
- trigger === 'submit-message' &&
- messages.length === 1 &&
- savedMessages.length === 0
- }
- }
- }
- }),
- messages: savedMessages,
- onFinish: ({ message }) => {
- isStreamingRef.current = false
- if (usageBudgetEnabled) void refreshUsage()
- window.dispatchEvent(new CustomEvent('chat-history-updated'))
-
- const summary = summarizeGenui(getTextFromParts(message.parts))
- if (summary) {
- captureClient('genui_component_shown', { chatId, ...summary })
- }
- },
- onError: error => {
+ } = useChat({ chat: entry.chat, throttle: 100 })
+ useEffect(() => {
+ if (status === 'ready' || status === 'error') {
isStreamingRef.current = false
- const publicError = toPublicErrorPayload(error)
-
- if (
- usageBudgetEnabled &&
- publicError.code === 'usage_limit' &&
- publicError.reason !== 'hourly'
- ) {
- const resetAt = publicError.resetAt
- ? new Date(publicError.resetAt).toISOString()
- : undefined
- void refreshUsage().then(usage => {
- showUsageLimit(usage?.resetAt ?? resetAt)
- })
- } else if (publicError.type === 'rate-limit') {
- if (usageBudgetEnabled) void refreshUsage()
- setErrorModal({
- open: true,
- type: 'rate-limit',
- message: publicError.error,
- details: getPublicRateLimitDetails(publicError)
- })
- } else if (publicError.type === 'auth') {
- if (usageBudgetEnabled) void refreshUsage()
- setErrorModal({
- open: true,
- type: 'auth',
- message: publicError.error
- })
- } else if (publicError.type === 'forbidden') {
- if (usageBudgetEnabled) void refreshUsage()
- setErrorModal({
- open: true,
- type: 'forbidden',
- message: publicError.error
- })
- } else {
- if (usageBudgetEnabled) void refreshUsage()
- toast.error(publicError.error)
- }
- },
- throttle: 100,
- generateId
- })
+ }
+ }, [status])
+ const stop = useCallback(() => {
+ store.invalidate(chatId)
+ return entry.chat.stop()
+ }, [store, chatId, entry])
+ const isHistoryPending =
+ entry.verifiedAt === 0 && !entry.hasServerHistory && messages.length === 0
+ const sendingBlocked =
+ (entry.verifiedAt === 0 && (!!entry.fetching || !!entry.error)) ||
+ (entry.verifiedAt === 0 &&
+ !entry.hasServerHistory &&
+ messages.length === 0 &&
+ chatId === providedId)
+ const canSend = useCallback(
+ () =>
+ !(entry.verifiedAt === 0 && (entry.fetching || entry.error)) &&
+ !sendingBlocked &&
+ entry.chat.status !== 'submitted' &&
+ entry.chat.status !== 'streaming',
+ [entry, sendingBlocked]
+ )
// Keep all request entry points reflected in isStreamingRef so downstream
// action handlers can reliably reject overlapping sends.
const safeSendMessage = useCallback<typeof sendMessage>(
(message, options) => {
+ if (!canSend()) return Promise.resolve()
if (isCurrentAdaptiveModeAuthBlocked()) {
showAdaptiveModeAuthModal()
return Promise.resolve()
@@ -253,6 +299,7 @@ export function Chat({
isStreamingRef.current = true
try {
const tracksUsage = isCloudDeployment && !isGuest
+ store.attachHandlers(entry, handlers)
const request = sendMessage(
message,
tracksUsage
@@ -281,12 +328,16 @@ export function Chat({
}
},
[
+ canSend,
consumeUsage,
+ entry,
+ handlers,
isCloudDeployment,
isCurrentAdaptiveModeAuthBlocked,
isGuest,
sendMessage,
showAdaptiveModeAuthModal,
+ store,
usageBudgetEnabled,
usageCosts
]
@@ -294,6 +345,7 @@ export function Chat({
const safeRegenerate = useCallback(
async (options?: Parameters<typeof regenerate>[0]) => {
+ if (!canSend()) return Promise.resolve()
if (isCurrentAdaptiveModeAuthBlocked()) {
showAdaptiveModeAuthModal()
return
@@ -302,6 +354,7 @@ export function Chat({
isStreamingRef.current = true
try {
const tracksUsage = isCloudDeployment && !isGuest
+ store.attachHandlers(entry, handlers)
const request = regenerate(
tracksUsage
? {
@@ -329,12 +382,16 @@ export function Chat({
}
},
[
+ canSend,
consumeUsage,
+ entry,
+ handlers,
isCloudDeployment,
isCurrentAdaptiveModeAuthBlocked,
isGuest,
regenerate,
showAdaptiveModeAuthModal,
+ store,
usageBudgetEnabled,
usageCosts
]
@@ -534,6 +591,7 @@ export function Chat({
editedMessageId: string,
newContentText: string
) => {
+ if (!canSend()) return
if (!chatId) {
toast.error('Chat ID is missing.')
console.error('handleUpdateAndReloadMessage: chatId is undefined.')
@@ -594,6 +652,7 @@ export function Chat({
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
+ if (!canSend()) return
const uploaded = uploadedFiles.filter(f => f.status === 'uploaded')
@@ -653,7 +712,9 @@ export function Chat({
<div
className={cn(
'relative flex h-full min-w-0 flex-1 flex-col',
- messages.length === 0 ? 'items-center justify-center' : ''
+ messages.length === 0 && !isHistoryPending
+ ? 'items-center justify-center'
+ : ''
)}
data-testid="full-chat"
onDragOver={dragHandlers.handleDragOver}
@@ -709,9 +770,38 @@ export function Chat({
error={error}
onQuoteContext={handleQuoteContext}
/>
+ {isHistoryPending && !entry.error && (
+ <div
+ role="status"
+ aria-label="Loading chat"
+ className="mx-auto w-full max-w-3xl px-4 pt-12"
+ >
+ <DefaultSkeleton />
+ </div>
+ )}
+ {entry.error && (
+ <div className="mx-auto w-full max-w-3xl px-4 pt-12">
+ <Card role="alert">
+ <CardHeader>
+ <CardDescription>{entry.error.message}</CardDescription>
+ </CardHeader>
+ <CardFooter>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void store.revalidate(chatId)}
+ >
+ Retry
+ </Button>
+ </CardFooter>
+ </Card>
+ </div>
+ )}
<UsageBudgetWarning />
<ChatPanel
chatId={chatId}
+ disabled={sendingBlocked}
+ isHistoryPending={isHistoryPending}
input={input}
handleInputChange={handleInputChange}
handleSubmit={onSubmit}
diff --git a/components/model-selector-client.tsx b/components/model-selector-client.tsx
index 29bff39e..7677f889 100644
--- a/components/model-selector-client.tsx
+++ b/components/model-selector-client.tsx
@@ -2,6 +2,7 @@
import { useMemo, useState } from 'react'
import Image from 'next/image'
+import { useRouter } from 'next/navigation'
import {
IconCheck as Check,
@@ -63,6 +64,7 @@ interface ModelSelectorClientProps {
}
export function ModelSelectorClient({ data }: ModelSelectorClientProps) {
+ const router = useRouter()
const [open, setOpen] = useState(false)
const [selectedModelKey, setSelectedModelKey] = useState<string>(
data.selectedModelKey
@@ -164,6 +166,7 @@ export function ModelSelectorClient({ data }: ModelSelectorClientProps) {
})
)
setOpen(false)
+ router.refresh()
}}
className="cursor-pointer"
>
diff --git a/components/sidebar/chat-menu-item.tsx b/components/sidebar/chat-menu-item.tsx
index 854d5bca..77e55962 100644
--- a/components/sidebar/chat-menu-item.tsx
+++ b/components/sidebar/chat-menu-item.tsx
@@ -11,6 +11,7 @@ import {
import { toast } from 'sonner'
import { deleteChat } from '@/lib/actions/chat'
+import { chatStore } from '@/lib/chat-store'
import { Chat as DBChat } from '@/lib/db/schema'
import {
@@ -98,6 +99,7 @@ export function ChatMenuItem({ chat }: ChatMenuItemProps) {
const result = await deleteChat(chat.id)
if (result?.success) {
+ chatStore.remove(chat.id)
toast.success('Chat deleted')
if (isActive) {
router.push('/')
diff --git a/components/sidebar/clear-history-action.tsx b/components/sidebar/clear-history-action.tsx
index e4ea2a88..25894926 100644
--- a/components/sidebar/clear-history-action.tsx
+++ b/components/sidebar/clear-history-action.tsx
@@ -10,6 +10,7 @@ import {
import { toast } from 'sonner'
import { clearChats } from '@/lib/actions/chat'
+import { chatStore } from '@/lib/chat-store'
import {
AlertDialog,
@@ -45,6 +46,7 @@ export function ClearHistoryAction({ empty }: ClearHistoryActionProps) {
startTransition(async () => {
const res = await clearChats()
if (res?.success) {
+ chatStore.clear()
toast.success('History cleared')
router.push('/')
} else if (res?.error) {
diff --git a/components/user-menu.tsx b/components/user-menu.tsx
index 9053aec9..85c20d53 100644
--- a/components/user-menu.tsx
+++ b/components/user-menu.tsx
@@ -14,6 +14,7 @@ import {
import { signOut } from '@/lib/actions/auth'
import type { AppUser } from '@/lib/auth/types'
+import { chatStore } from '@/lib/chat-store'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import {
@@ -64,6 +65,7 @@ export default function UserMenu({ user }: UserMenuProps) {
const handleLogout = async () => {
await signOut()
+ chatStore.setUser(null)
router.push('/')
router.refresh()
}
diff --git a/lib/actions/__tests__/account.test.ts b/lib/actions/__tests__/account.test.ts
index 641f9860..a602855d 100644
--- a/lib/actions/__tests__/account.test.ts
+++ b/lib/actions/__tests__/account.test.ts
@@ -1,5 +1,3 @@
-import { revalidateTag } from 'next/cache'
-
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { trackAccountDeleted } from '@/lib/analytics'
@@ -109,7 +107,6 @@ describe('Account Actions', () => {
expect(dbActions.anonymizeUserFeedback).toHaveBeenCalledWith(user.id)
expect(deleteUserObjects).toHaveBeenCalledWith(user.id)
expect(deleteUser).toHaveBeenCalledWith(user.id)
- expect(revalidateTag).toHaveBeenCalledWith('chat', 'max')
expect(trackAccountDeleted).toHaveBeenCalledTimes(1)
// supabase has no in-database guard, so no transaction is opened:
// an outer transaction would hold a pooled connection while the
diff --git a/lib/actions/__tests__/chat.test.ts b/lib/actions/__tests__/chat.test.ts
index 84c0566a..b0e24e25 100644
--- a/lib/actions/__tests__/chat.test.ts
+++ b/lib/actions/__tests__/chat.test.ts
@@ -1,5 +1,3 @@
-import { revalidateTag } from 'next/cache'
-
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { generateChatTitle } from '@/lib/agents/title-generator'
@@ -21,6 +19,7 @@ import {
deleteChat,
deleteMessagesAfter,
deleteMessagesFromIndex,
+ getChatMeta,
getChats,
getChatsPage,
loadChat,
@@ -52,6 +51,31 @@ describe('Chat Actions', () => {
vi.clearAllMocks()
})
+ describe('getChatMeta', () => {
+ it.each(['owner', undefined])(
+ 'reads only the chat row for %s',
+ async userId => {
+ const chat: Chat = {
+ id: 'chat',
+ title: 'Title',
+ userId: 'owner',
+ visibility: 'public',
+ createdAt: new Date()
+ }
+ vi.mocked(dbActions.getChat).mockResolvedValue(chat)
+ expect(await getChatMeta('chat', userId)).toEqual(chat)
+ expect(dbActions.getChat).toHaveBeenCalledWith('chat', userId)
+ expect(dbActions.loadChatWithMessages).not.toHaveBeenCalled()
+ expect(signFilePartUrlsInMessages).not.toHaveBeenCalled()
+ }
+ )
+
+ it('preserves null from the visibility check', async () => {
+ vi.mocked(dbActions.getChat).mockResolvedValue(null)
+ expect(await getChatMeta('private')).toBeNull()
+ })
+ })
+
describe('getChats', () => {
it('should return chats for authenticated user', async () => {
const userId = 'user-123'
@@ -192,7 +216,6 @@ describe('Chat Actions', () => {
}
vi.mocked(dbActions.createChat).mockResolvedValue(mockChat)
- vi.mocked(revalidateTag).mockReturnValue(undefined)
const result = await createChat(chatId, title, userId)
@@ -203,7 +226,6 @@ describe('Chat Actions', () => {
userId,
visibility: 'private'
})
- expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`, 'max')
})
it('should generate ID and use default title when not provided', async () => {
@@ -333,7 +355,6 @@ describe('Chat Actions', () => {
parts: [{ type: 'text', text: 'Hello' }]
}
})
- expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`, 'max')
})
})
@@ -368,7 +389,6 @@ describe('Chat Actions', () => {
},
userId
)
- expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`, 'max')
})
it('should generate message ID if not provided', async () => {
@@ -415,7 +435,6 @@ describe('Chat Actions', () => {
expect(result).toEqual({ success: true })
expect(dbActions.deleteChat).toHaveBeenCalledWith(chatId, userId)
- expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`, 'max')
})
it('should return error for unauthenticated user', async () => {
@@ -461,7 +480,6 @@ describe('Chat Actions', () => {
expect(dbActions.deleteChat).toHaveBeenCalledTimes(2)
expect(dbActions.deleteChat).toHaveBeenCalledWith('chat-1', userId)
expect(dbActions.deleteChat).toHaveBeenCalledWith('chat-2', userId)
- expect(revalidateTag).toHaveBeenCalledWith('chat', 'max')
})
})
@@ -489,7 +507,6 @@ describe('Chat Actions', () => {
chatId,
messageId
)
- expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`, 'max')
})
it('should return error for unauthorized access', async () => {
@@ -555,7 +572,6 @@ describe('Chat Actions', () => {
userId,
'public'
)
- expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`, 'max')
})
it('should return null for unauthenticated user', async () => {
@@ -664,7 +680,6 @@ describe('Chat Actions', () => {
messageId,
userId
)
- expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`, 'max')
})
})
@@ -698,7 +713,6 @@ describe('Chat Actions', () => {
chatId,
generatedTitle
)
- expect(revalidateTag).toHaveBeenCalledWith(`chat-${chatId}`, 'max')
})
it('should not generate title for existing chat', async () => {
diff --git a/lib/actions/account.ts b/lib/actions/account.ts
index c66b537a..9239c71e 100644
--- a/lib/actions/account.ts
+++ b/lib/actions/account.ts
@@ -1,7 +1,5 @@
'use server'
-import { revalidateTag } from 'next/cache'
-
import { trackAccountDeleted } from '@/lib/analytics'
import { getCurrentUser } from '@/lib/auth/get-current-user'
import { getAuthProvider } from '@/lib/auth/provider'
@@ -189,7 +187,6 @@ export async function deleteAccount(): Promise<{
// provider deferred because of concurrent sign-ups.
await provider.postDeletion?.(wasAdmin)
- revalidateTag('chat', 'max')
await trackAccountDeleted(user.id)
return { success: true }
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
index 82f1e18c..fe36b002 100644
--- a/lib/actions/chat.ts
+++ b/lib/actions/chat.ts
@@ -1,7 +1,5 @@
'use server'
-import { revalidateTag, unstable_cache } from 'next/cache'
-
import { generateChatTitle } from '@/lib/agents/title-generator'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { getAuthProvider, isShareEnabled } from '@/lib/auth/provider'
@@ -18,26 +16,6 @@ import { getTextFromParts } from '@/lib/utils/message-utils'
// Constants
const DEFAULT_CHAT_TITLE = 'Untitled'
-// Create cached version of loadChatWithMessages with dynamic tags per chat
-const getCachedChatWithMessages = (
- chatId: string,
- requestingUserId?: string
-) => {
- // Create a unique cache instance for each chat
- const cachedFunction = unstable_cache(
- async () => {
- return dbActions.loadChatWithMessages(chatId, requestingUserId)
- },
- ['chat-with-messages', chatId, requestingUserId || 'anonymous'], // cache key
- {
- tags: [`chat-${chatId}`, 'chat'], // both specific and general tags
- revalidate: 60 // revalidate after 60 seconds
- }
- )
-
- return cachedFunction()
-}
-
async function signChatFilePartUrls(
chat: (Chat & { messages: UIMessage[] }) | null
): Promise<(Chat & { messages: UIMessage[] }) | null> {
@@ -73,28 +51,19 @@ export async function getChatsPage(limit = 20, offset = 0) {
return dbActions.getChatsPage(userId, limit, offset)
}
-/**
- * Load a chat with messages
- * If requestingUserId is provided, it will be used for authorization
- * Otherwise, no authorization check is performed (assumes already authorized)
- */
-export async function loadChat(
+export async function getChatMeta(
chatId: string,
requestingUserId?: string
-): Promise<(Chat & { messages: UIMessage[] }) | null> {
- // Use cached version for individual chat loading
- const chat = await getCachedChatWithMessages(chatId, requestingUserId)
-
- return signChatFilePartUrls(chat)
+): Promise<Chat | null> {
+ return dbActions.getChat(chatId, requestingUserId)
}
/**
- * Load a chat bypassing the request cache.
- * The assistant answer is persisted after the streaming response has been
- * returned, so its revalidateTag never reaches the cache and a cached read
- * can miss the previous turn's answer.
+ * Load a chat with messages
+ * If requestingUserId is provided, it will be used for authorization
+ * Otherwise, no authorization check is performed (assumes already authorized)
*/
-export async function loadChatUncached(
+export async function loadChat(
chatId: string,
requestingUserId?: string
): Promise<(Chat & { messages: UIMessage[] }) | null> {
@@ -123,9 +92,6 @@ export async function createChat(
visibility: 'private'
})
- // Revalidate cache
- revalidateTag(`chat-${chatId}`, 'max')
-
return chat
}
@@ -163,9 +129,6 @@ export async function createChatAndSaveMessage(
chatId
})
- // Revalidate cache
- revalidateTag(`chat-${chatId}`, 'max')
-
return { chat, message: dbMessage }
}
@@ -193,9 +156,6 @@ export async function createChatWithFirstMessage(
}
})
- // Revalidate cache
- revalidateTag(`chat-${chatId}`, 'max')
-
return result
}
@@ -228,9 +188,6 @@ export async function upsertMessage(
userId
)
- // Revalidate cache
- revalidateTag(`chat-${chatId}`, 'max')
-
return dbMessage
}
@@ -245,10 +202,6 @@ export async function deleteChat(chatId: string) {
const result = await dbActions.deleteChat(chatId, userId)
- if (result.success) {
- revalidateTag(`chat-${chatId}`, 'max')
- }
-
return result
}
@@ -267,8 +220,6 @@ export async function clearChats() {
await dbActions.deleteChat(chat.id, userId)
}
- // Clear all chat caches since we deleted all chats
- revalidateTag('chat', 'max')
return { success: true }
}
@@ -289,8 +240,6 @@ export async function deleteMessagesAfter(chatId: string, messageId: string) {
const result = await dbActions.deleteMessagesAfter(chatId, messageId)
- revalidateTag(`chat-${chatId}`, 'max')
-
return { success: true, count: result.count }
}
@@ -324,10 +273,6 @@ export async function shareChat(chatId: string) {
'public'
)
- if (updatedChat) {
- revalidateTag(`chat-${chatId}`, 'max')
- }
-
return updatedChat
}
@@ -356,8 +301,6 @@ export async function deleteMessagesFromIndex(
userId
)
- revalidateTag(`chat-${chatId}`, 'max')
-
return { success: true, count: result.count }
}
@@ -381,6 +324,5 @@ export async function saveChatTitle(
modelId
})
await dbActions.updateChatTitle(chatId, title)
- revalidateTag(`chat-${chatId}`, 'max')
}
}
diff --git a/lib/chat-store/index.test.ts b/lib/chat-store/index.test.ts
new file mode 100644
index 00000000..b399688e
--- /dev/null
+++ b/lib/chat-store/index.test.ts
@@ -0,0 +1,458 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { UIMessage } from '@/lib/types/ai'
+
+import { ChatStore } from './index'
+
+vi.mock('@/lib/analytics/posthog-client', () => ({
+ getDistinctId: () => 'visitor'
+}))
+
+const messages = (text: string): UIMessage[] => [
+ { id: text, role: 'user', parts: [{ type: 'text', text }] }
+]
+const response = (text: string) =>
+ new Response(JSON.stringify({ messages: messages(text) }))
+const deferred = () => {
+ let resolve!: (value: Response) => void
+ const promise = new Promise<Response>(r => {
+ resolve = r
+ })
+ return { promise, resolve }
+}
+
+// Exercise SDK status transitions without issuing a generation request.
+function setStatus(
+ entry: ReturnType<ChatStore['getOrCreate']>,
+ status: 'submitted' | 'streaming' | 'ready'
+) {
+ ;(entry.chat as unknown as { state: { status: string } }).state.status =
+ status
+}
+
+describe('ChatStore', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-01-01'))
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockImplementation(() => Promise.resolve(response('server')))
+ )
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('seeds once and reuses the live Chat within the verified window', async () => {
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a', { messages: messages('seed') })
+ entry.chat.messages = messages('local')
+ expect(store.getOrCreate('a', { messages: messages('stale page') })).toBe(
+ entry
+ )
+ await store.revalidate('a')
+ expect(fetch).not.toHaveBeenCalled()
+ expect(entry.chat.messages).toEqual(messages('local'))
+ vi.advanceTimersByTime(30_000)
+ const request = store.revalidate('a')
+ expect(entry.chat.messages).toEqual(messages('local'))
+ await request
+ expect(entry.chat.messages).toEqual(messages('server'))
+ })
+
+ it('fetches missing history and deduplicates concurrent fetches', async () => {
+ const pending = deferred()
+ vi.mocked(fetch).mockReturnValue(pending.promise)
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a')
+ const first = store.revalidate('a')
+ expect(entry.verifiedAt).toBe(0)
+ expect(entry.fetching).toBe(first)
+ expect(store.revalidate('a')).toBe(first)
+ expect(fetch).toHaveBeenCalledTimes(1)
+ pending.resolve(response('loaded'))
+ await first
+ expect(entry.hasServerHistory).toBe(true)
+ expect(entry.fetching).toBeUndefined()
+ })
+
+ it('refreshes signed URLs despite a recent verification', async () => {
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a', { messages: messages('old url') })
+ vi.advanceTimersByTime(30 * 60_000)
+ store.markVerified('a')
+ await store.revalidate('a')
+ expect(fetch).toHaveBeenCalledOnce()
+ expect(entry.chat.messages).toEqual(messages('server'))
+ expect(entry.loadedAt).toBe(Date.now())
+ })
+
+ it.each(['submitted', 'streaming'] as const)(
+ 'discards background results while %s',
+ async status => {
+ const pending = deferred()
+ vi.mocked(fetch).mockReturnValue(pending.promise)
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a', { messages: messages('cached') })
+ store.invalidate('a')
+ const request = store.revalidate('a')
+ setStatus(entry, status)
+ pending.resolve(response('stale'))
+ await request
+ expect(entry.chat.messages).toEqual(messages('cached'))
+ expect(entry.verifiedAt).toBe(0)
+ }
+ )
+
+ it('discards results after a local turn finishes or is invalidated', async () => {
+ const pending = deferred()
+ vi.mocked(fetch).mockReturnValue(pending.promise)
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a')
+ const request = store.revalidate('a')
+ entry.chat.messages = messages('finished')
+ store.markVerified('a')
+ pending.resolve(response('stale'))
+ await request
+ expect(entry.chat.messages).toEqual(messages('finished'))
+ })
+
+ it('evicts least recently used entries', () => {
+ const store = new ChatStore(2)
+ store.getOrCreate('a')
+ store.getOrCreate('b')
+ store.getOrCreate('a')
+ store.getOrCreate('c')
+ expect(store.get('a')).toBeDefined()
+ expect(store.get('b')).toBeUndefined()
+ })
+
+ it('enforces the total size cap, including message edits', () => {
+ const size = JSON.stringify(messages('a')).length
+ const store = new ChatStore(20, size * 2)
+ store.getOrCreate('a', { messages: messages('a') })
+ const b = store.getOrCreate('b', { messages: messages('b') })
+ b.chat.messages = messages('longer')
+ expect(store.get('a')).toBeUndefined()
+ expect(store.get('b')).toBe(b)
+ })
+
+ it.each([
+ [1, Infinity, 'submitted'],
+ [1, Infinity, 'streaming'],
+ [20, 2, 'submitted'],
+ [20, 2, 'streaming']
+ ] as const)(
+ 'keeps a newly opened entry with limits %s/%s while another is %s',
+ async (maxEntries, maxSize, status) => {
+ const store = new ChatStore(maxEntries, maxSize)
+ const a = store.getOrCreate('a')
+ setStatus(a, status)
+ const b = store.getOrCreate('b')
+ expect(store.get('a')).toBe(a)
+ expect(store.get('b')).toBe(b)
+ await store.revalidate('b')
+ expect(b.chat.messages).toEqual(messages('server'))
+ expect(b.verifiedAt).toBe(Date.now())
+ expect(store.get('b')).toBe(b)
+
+ setStatus(a, 'ready')
+ expect(store.get('a')).toBe(a)
+ expect(store.get('b')).toBeUndefined()
+ }
+ )
+
+ it('keeps an entry whose history load is pending when another settles', async () => {
+ const store = new ChatStore(1)
+ const a = store.getOrCreate('a')
+ setStatus(a, 'streaming')
+ const pending = deferred()
+ vi.mocked(fetch).mockReturnValueOnce(pending.promise)
+ const b = store.getOrCreate('b')
+ const load = store.revalidate('b')
+
+ setStatus(a, 'ready')
+ expect(store.get('b')).toBe(b)
+
+ pending.resolve(response('server'))
+ await load
+ expect(b.chat.messages).toEqual(messages('server'))
+ expect(b.verifiedAt).toBe(Date.now())
+ })
+
+ it('keeps a touched entry even when it alone exceeds the size cap', () => {
+ const store = new ChatStore(20, 2)
+ const entry = store.getOrCreate('a')
+ entry.chat.messages = messages('large')
+ expect(store.get('a')).toBe(entry)
+ expect(store.getOrCreate('a')).toBe(entry)
+ })
+
+ it.each([undefined, [] as UIMessage[]])(
+ 'skips revalidation for an untouched local chat initialized with %s',
+ async initialMessages => {
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a', {
+ isNew: true,
+ messages: initialMessages
+ })
+ vi.advanceTimersByTime(30_000)
+ expect(store.getOrCreate('a')).toBe(entry)
+ await store.revalidate('a')
+ store.invalidate('a')
+ await store.revalidate('a')
+ expect(fetch).not.toHaveBeenCalled()
+ expect(entry.chat.messages).toEqual([])
+ expect(entry.error).toBeUndefined()
+ }
+ )
+
+ it('refreshes an aborted first local turn and adopts server messages', async () => {
+ const events = [
+ { type: 'start', messageId: 'answer' },
+ { type: 'text-start', id: 'text' },
+ { type: 'text-delta', id: 'text', delta: 'partial answer' }
+ ]
+ vi.mocked(fetch).mockResolvedValueOnce(
+ new Response(
+ new ReadableStream({
+ pull(controller) {
+ const event = events.shift()
+ if (event) {
+ controller.enqueue(
+ new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`)
+ )
+ } else {
+ controller.error(new DOMException('Aborted', 'AbortError'))
+ }
+ }
+ }),
+ {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'x-vercel-ai-ui-message-stream': 'v1'
+ }
+ }
+ )
+ )
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a', { isNew: true })
+ const onFinish = vi.fn()
+ store.attachHandlers(entry, { onFinish })
+
+ await entry.chat.sendMessage({ text: 'first' })
+
+ expect(onFinish).toHaveBeenCalledWith(
+ expect.objectContaining({ isAbort: true })
+ )
+ expect(entry.chat.messages).toHaveLength(2)
+ expect(entry.chat.messages[1].parts).toContainEqual(
+ expect.objectContaining({ type: 'text', text: 'partial answer' })
+ )
+ expect(entry.hasServerHistory).toBe(false)
+ expect(entry.verifiedAt).toBe(0)
+ vi.advanceTimersByTime(30_000)
+
+ await store.revalidate('a')
+
+ expect(fetch).toHaveBeenCalledTimes(2)
+ expect(entry.chat.messages).toEqual(messages('server'))
+ expect(entry.hasServerHistory).toBe(true)
+ expect(entry.verifiedAt).toBe(Date.now())
+ })
+
+ it('keeps an unsaved first local message sendable after a 404', async () => {
+ vi.mocked(fetch)
+ .mockResolvedValueOnce(new Response(null, { status: 429 }))
+ .mockResolvedValueOnce(new Response(null, { status: 404 }))
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a', { isNew: true })
+ await entry.chat.sendMessage({ text: 'first' })
+ const localMessages = entry.chat.messages
+ vi.advanceTimersByTime(30_000)
+
+ await store.revalidate('a')
+
+ expect(fetch).toHaveBeenCalledTimes(2)
+ expect(entry.chat.messages).toBe(localMessages)
+ expect(entry.chat.messages).toHaveLength(1)
+ expect(entry.error).toBeUndefined()
+ expect(entry.hasServerHistory).toBe(false)
+ expect(entry.fetching).toBeUndefined()
+ expect(entry.verifiedAt).toBe(0)
+ })
+
+ it('clears on user changes and prevents old fetches from restoring data', async () => {
+ const pending = deferred()
+ vi.mocked(fetch).mockReturnValue(pending.promise)
+ const store = new ChatStore()
+ store.setUser('first')
+ store.getOrCreate('a')
+ const request = store.revalidate('a')
+ store.setUser('first')
+ expect(store.get('a')).toBeDefined()
+ store.setUser('second')
+ expect(store.get('a')).toBeUndefined()
+ pending.resolve(response('old account'))
+ await request
+ expect(store.get('a')).toBeUndefined()
+ store.getOrCreate('b')
+ store.setUser(null)
+ expect(store.get('b')).toBeUndefined()
+ })
+
+ it.each(['seeded', 'local', 'empty server history'] as const)(
+ 'keeps %s usable after background revalidation fails and retries on reopen',
+ async source => {
+ const logError = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const failure = new Error('Network unavailable')
+ vi.mocked(fetch).mockRejectedValueOnce(failure)
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a', {
+ messages:
+ source === 'seeded'
+ ? messages('cached')
+ : source === 'empty server history'
+ ? []
+ : undefined
+ })
+ if (source === 'local') entry.chat.messages = messages('local')
+ const originalMessages = entry.chat.messages
+ const verifiedAt = entry.verifiedAt
+ vi.advanceTimersByTime(30_000)
+
+ await store.revalidate('a')
+
+ expect(entry.verifiedAt).toBe(verifiedAt)
+ expect(entry.error).toBeUndefined()
+ expect(entry.fetching).toBeUndefined()
+ expect(entry.chat.messages).toBe(originalMessages)
+ expect(logError).toHaveBeenCalledWith(
+ 'Failed to revalidate chat:',
+ failure
+ )
+
+ store.getOrCreate('a')
+ await store.revalidate('a')
+ expect(fetch).toHaveBeenCalledTimes(2)
+ expect(entry.chat.messages).toEqual(messages('server'))
+ }
+ )
+
+ it('blocks an empty entry after a load failure and allows retry', async () => {
+ vi.mocked(fetch).mockResolvedValueOnce(new Response('{}', { status: 404 }))
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a')
+ await store.revalidate('a')
+ expect(entry.chat.messages).toEqual([])
+ expect(entry.fetching).toBeUndefined()
+ expect(entry.error?.message).toBe('Chat not found')
+ expect(entry.verifiedAt).toBe(0)
+ await store.revalidate('a')
+ expect(entry.error).toBeUndefined()
+ expect(entry.verifiedAt).toBe(Date.now())
+ })
+
+ it.each(['seeded', 'local', 'empty server history', 'saved local'] as const)(
+ 'clears %s and blocks the entry after a 404',
+ async source => {
+ const logError = vi.spyOn(console, 'error').mockImplementation(() => {})
+ vi.mocked(fetch).mockResolvedValueOnce(
+ new Response(null, { status: 404 })
+ )
+ const store = new ChatStore()
+ const entry = store.getOrCreate('a', {
+ isNew: source === 'saved local',
+ messages:
+ source === 'seeded'
+ ? messages('cached')
+ : source === 'empty server history'
+ ? []
+ : undefined
+ })
+ if (source === 'local') entry.chat.messages = messages('local')
+ if (source === 'saved local') {
+ entry.chat.messages = messages('saved')
+ store.markVerified('a')
+ }
+ vi.advanceTimersByTime(30_000)
+
+ await store.revalidate('a')
+
+ expect(entry.chat.messages).toEqual([])
+ expect(entry.error?.message).toBe('Chat not found')
+ expect(entry.verifiedAt).toBe(0)
+ expect(entry.fetching).toBeUndefined()
+ expect(logError).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([false, true])(
+ 'sends the expected history for guest=%s and verifies on finish',
+ async isGuest => {
+ vi.useRealTimers()
+ const events = [
+ { type: 'start', messageId: 'answer' },
+ { type: 'text-start', id: 'text' },
+ { type: 'text-delta', id: 'text', delta: 'answer' },
+ { type: 'text-end', id: 'text' },
+ { type: 'finish', finishReason: 'stop' }
+ ]
+ const streamResponse = () =>
+ new Response(
+ events.map(event => `data: ${JSON.stringify(event)}\n\n`).join('') +
+ 'data: [DONE]\n\n',
+ {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'x-vercel-ai-ui-message-stream': 'v1'
+ }
+ }
+ )
+ vi.mocked(fetch).mockImplementation(() =>
+ Promise.resolve(streamResponse())
+ )
+ const store = new ChatStore()
+ const entry = store.getOrCreate('new', { isNew: true, isGuest })
+ const oldHandler = vi.fn()
+ const currentHandler = vi.fn()
+ const detachOld = store.attachHandlers(entry, { onFinish: oldHandler })
+ store.attachHandlers(entry, { onFinish: currentHandler })
+ detachOld()
+ await entry.chat.sendMessage({ text: 'first' })
+ const firstBody = JSON.parse(
+ vi.mocked(fetch).mock.calls[0][1]!.body as string
+ )
+ expect(firstBody.isNewChat).toBe(true)
+ expect(firstBody.messages).toEqual(
+ isGuest ? expect.any(Array) : undefined
+ )
+ expect(entry.hasServerHistory).toBe(true)
+ expect(entry.verifiedAt).toBeGreaterThan(0)
+ expect(currentHandler).toHaveBeenCalledOnce()
+ expect(oldHandler).not.toHaveBeenCalled()
+ await entry.chat.sendMessage({ text: 'second' })
+ const secondBody = JSON.parse(
+ vi.mocked(fetch).mock.calls[1][1]!.body as string
+ )
+ expect(secondBody.isNewChat).toBe(false)
+ if (isGuest) expect(secondBody.messages).toHaveLength(3)
+ }
+ )
+
+ it('removes and clears entries and notifies subscribers', () => {
+ const store = new ChatStore()
+ const listener = vi.fn()
+ const unsubscribe = store.subscribe(listener)
+ store.getOrCreate('a')
+ store.remove('a')
+ expect(store.get('a')).toBeUndefined()
+ store.getOrCreate('b')
+ store.clear()
+ expect(store.get('b')).toBeUndefined()
+ expect(listener).toHaveBeenCalled()
+ unsubscribe()
+ })
+})
diff --git a/lib/chat-store/index.ts b/lib/chat-store/index.ts
new file mode 100644
index 00000000..52cb650a
--- /dev/null
+++ b/lib/chat-store/index.ts
@@ -0,0 +1,277 @@
+'use client'
+
+import { Chat } from '@ai-sdk/react'
+import { ChatInit, DefaultChatTransport } from 'ai'
+
+import { getDistinctId } from '@/lib/analytics/posthog-client'
+import { generateId } from '@/lib/db/schema'
+import type { UIMessage } from '@/lib/types/ai'
+
+export type ChatHandlers = Pick<ChatInit<UIMessage>, 'onFinish' | 'onError'>
+export type ChatEntry = {
+ chat: Chat<UIMessage>
+ handlers: { current: ChatHandlers }
+ verifiedAt: number
+ loadedAt: number
+ hasServerHistory: boolean
+ createdLocally: boolean
+ fetching?: Promise<void>
+ error?: Error
+ revision: number
+ size: number
+ dispose: () => void
+}
+
+const busy = (entry: ChatEntry) =>
+ entry.chat.status === 'submitted' || entry.chat.status === 'streaming'
+
+export class ChatStore {
+ private entries = new Map<string, ChatEntry>()
+ private userId: string | null = null
+ private listeners = new Set<() => void>()
+ private version = 0
+
+ constructor(
+ private maxEntries = 20,
+ private maxSize = 20 * 1024 * 1024
+ ) {}
+
+ subscribe = (listener: () => void) => {
+ this.listeners.add(listener)
+ return () => {
+ this.listeners.delete(listener)
+ }
+ }
+ getSnapshot = () => this.version
+ private emit() {
+ this.version++
+ this.listeners.forEach(listener => listener())
+ }
+
+ setUser(userId: string | null) {
+ if (this.userId !== userId) {
+ this.userId = userId
+ this.clear()
+ }
+ }
+
+ attachHandlers(entry: ChatEntry, handlers: ChatHandlers) {
+ entry.handlers.current = handlers
+ return () => {
+ if (entry.handlers.current === handlers) entry.handlers.current = {}
+ }
+ }
+
+ get(id: string) {
+ return this.entries.get(id)
+ }
+
+ getOrCreate(
+ id: string,
+ options: { messages?: UIMessage[]; isNew?: boolean; isGuest?: boolean } = {}
+ ) {
+ const existing = this.entries.get(id)
+ if (existing) {
+ this.entries.delete(id)
+ this.entries.set(id, existing)
+ this.prune(existing)
+ return existing
+ }
+ const now = Date.now()
+ const handlers: ChatEntry['handlers'] = { current: {} }
+ const entry: ChatEntry = {
+ chat: new Chat<UIMessage>({
+ id,
+ messages: options.messages,
+ generateId,
+ transport: new DefaultChatTransport({
+ api: '/api/chat',
+ prepareSendMessagesRequest: ({
+ messages,
+ trigger,
+ messageId,
+ body
+ }) => {
+ const lastMessage = messages[messages.length - 1]
+ const original =
+ trigger === 'regenerate-message'
+ ? messages.find(m => m.id === messageId)
+ : undefined
+ return {
+ body: {
+ ...body,
+ trigger,
+ chatId: id,
+ messageId,
+ clientSource: 'web',
+ analyticsId: getDistinctId(),
+ ...(options.isGuest ? { messages } : {}),
+ message:
+ trigger === 'regenerate-message' && original?.role === 'user'
+ ? original
+ : trigger === 'submit-message'
+ ? lastMessage
+ : undefined,
+ isNewChat:
+ trigger === 'submit-message' &&
+ messages.length === 1 &&
+ !entry.hasServerHistory
+ }
+ }
+ }
+ }),
+ onFinish: event => {
+ if (this.entries.get(id) === entry) {
+ if (event.isAbort || event.isError) this.invalidate(id)
+ else this.markVerified(id)
+ }
+ if (typeof window !== 'undefined') {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ }
+ return handlers.current.onFinish?.(event)
+ },
+ onError: error => {
+ if (this.entries.get(id) === entry) this.invalidate(id)
+ handlers.current.onError?.(error)
+ }
+ }),
+ handlers,
+ verifiedAt: options.messages !== undefined || options.isNew ? now : 0,
+ loadedAt: now,
+ hasServerHistory: options.messages !== undefined && !options.isNew,
+ createdLocally: !!options.isNew,
+ revision: 0,
+ size: 0,
+ dispose: () => {}
+ }
+ const updateSize = () => {
+ if (!busy(entry)) {
+ entry.size = JSON.stringify(entry.chat.messages).length
+ this.prune(entry)
+ }
+ }
+ const unsubscribes = [
+ entry.chat['~registerMessagesCallback'](updateSize),
+ entry.chat['~registerStatusCallback'](() => {
+ entry.revision++
+ updateSize()
+ })
+ ]
+ entry.dispose = () => unsubscribes.forEach(unsubscribe => unsubscribe())
+ entry.size = JSON.stringify(entry.chat.messages).length
+ this.entries.set(id, entry)
+ this.prune(entry)
+ return entry
+ }
+
+ private prune(protectedEntry: ChatEntry) {
+ let size = [...this.entries.values()].reduce((sum, e) => sum + e.size, 0)
+ for (const [id, entry] of this.entries) {
+ if (this.entries.size <= this.maxEntries && size <= this.maxSize) break
+ if (entry === protectedEntry || busy(entry) || entry.fetching) continue
+ size -= entry.size
+ entry.dispose()
+ this.entries.delete(id)
+ }
+ }
+
+ markVerified(id: string) {
+ const entry = this.entries.get(id)
+ if (!entry) return
+ entry.verifiedAt = Date.now()
+ entry.hasServerHistory = true
+ entry.revision++
+ this.emit()
+ }
+ invalidate(id: string) {
+ const entry = this.entries.get(id)
+ if (!entry) return
+ entry.verifiedAt = 0
+ entry.revision++
+ this.emit()
+ }
+ remove(id: string) {
+ const entry = this.entries.get(id)
+ if (entry) entry.handlers.current = {}
+ entry?.dispose()
+ this.entries.delete(id)
+ void entry?.chat.stop()
+ this.emit()
+ }
+ clear() {
+ const entries = [...this.entries.values()]
+ this.entries.clear()
+ entries.forEach(entry => {
+ entry.handlers.current = {}
+ entry.dispose()
+ void entry.chat.stop()
+ })
+ this.emit()
+ }
+
+ revalidate(id: string): Promise<void> {
+ const entry = this.entries.get(id)
+ if (!entry) return Promise.resolve()
+ if (
+ entry.createdLocally &&
+ !entry.hasServerHistory &&
+ entry.chat.messages.length === 0
+ )
+ return Promise.resolve()
+ if (entry.fetching) return entry.fetching
+ const now = Date.now()
+ if (
+ entry.verifiedAt !== 0 &&
+ now - entry.verifiedAt < 30_000 &&
+ now - entry.loadedAt < 30 * 60_000
+ )
+ return Promise.resolve()
+ const revision = entry.revision
+ entry.error = undefined
+ entry.fetching = (async () => {
+ let notFound = false
+ try {
+ const response = await fetch(`/api/chats/${encodeURIComponent(id)}`, {
+ cache: 'no-store'
+ })
+ if (!response.ok) {
+ notFound = response.status === 404
+ throw new Error(notFound ? 'Chat not found' : 'Failed to load chat')
+ }
+ const data = (await response.json()) as { messages: UIMessage[] }
+ // A local turn or account change makes this response obsolete.
+ if (
+ this.entries.get(id) !== entry ||
+ busy(entry) ||
+ entry.revision !== revision
+ )
+ return
+ entry.chat.messages = data.messages
+ entry.loadedAt = Date.now()
+ this.markVerified(id)
+ } catch (error) {
+ if (this.entries.get(id) === entry && entry.revision === revision) {
+ if (notFound) {
+ if (entry.createdLocally && !entry.hasServerHistory) return
+ entry.chat.messages = []
+ entry.verifiedAt = 0
+ entry.error = new Error('Chat not found')
+ } else if (entry.hasServerHistory || entry.chat.messages.length > 0) {
+ console.error('Failed to revalidate chat:', error)
+ } else {
+ entry.verifiedAt = 0
+ entry.error =
+ error instanceof Error ? error : new Error('Failed to load chat')
+ }
+ }
+ } finally {
+ entry.fetching = undefined
+ this.emit()
+ }
+ })()
+ this.emit()
+ return entry.fetching
+ }
+}
+
+export const chatStore = new ChatStore()
diff --git a/lib/contexts/app-user-context.tsx b/lib/contexts/app-user-context.tsx
index 82c7eed3..30bec427 100644
--- a/lib/contexts/app-user-context.tsx
+++ b/lib/contexts/app-user-context.tsx
@@ -1,8 +1,9 @@
'use client'
-import { createContext, useContext } from 'react'
+import { createContext, useContext, useEffect } from 'react'
import type { AppUser, AuthCapabilities } from '@/lib/auth/types'
+import { chatStore } from '@/lib/chat-store'
interface AppUserContextValue {
user: AppUser | null
@@ -36,6 +37,9 @@ export function AppUserProvider({
capabilities: AuthCapabilities
children: React.ReactNode
}) {
+ useEffect(() => {
+ chatStore.setUser(user?.id ?? null)
+ }, [user?.id])
return (
<AppUserContext.Provider value={{ user, capabilities }}>
{children}
diff --git a/lib/streaming/__tests__/create-chat-stream-response.test.ts b/lib/streaming/__tests__/create-chat-stream-response.test.ts
index 4aed00c9..5f5df94e 100644
--- a/lib/streaming/__tests__/create-chat-stream-response.test.ts
+++ b/lib/streaming/__tests__/create-chat-stream-response.test.ts
@@ -35,8 +35,7 @@ vi.mock('@/instrumentation', () => ({
}))
vi.mock('@/lib/actions/chat', () => ({
- loadChat: vi.fn(),
- loadChatUncached: vi.fn()
+ loadChat: vi.fn()
}))
vi.mock('@/lib/agents/researcher', () => ({
@@ -73,7 +72,7 @@ vi.mock('@/lib/utils/usage-logging', () => ({
logUsage: vi.fn()
}))
-import { loadChat, loadChatUncached } from '@/lib/actions/chat'
+import { loadChat } from '@/lib/actions/chat'
import { researcher } from '@/lib/agents/researcher'
import { DeterministicPreparationError } from '@/lib/errors/deterministic-preparation-error'
import { serializeToolFailure, ToolFailureError } from '@/lib/errors/tool-error'
@@ -222,14 +221,13 @@ describe('createChatStreamResponse', () => {
)
})
- it('loads an existing chat without the cache', async () => {
+ it('loads an existing chat', async () => {
mocks.stream.mockResolvedValue(createFakeResult())
await createChatStreamResponse({ ...createConfig(), isNewChat: false })
await mocks.finishPromise
- expect(loadChatUncached).toHaveBeenCalledWith('chat-id', 'user-id')
- expect(loadChat).not.toHaveBeenCalled()
+ expect(loadChat).toHaveBeenCalledWith('chat-id', 'user-id')
})
it('does not mark the span as failed for an aborted stream error', async () => {
@@ -294,7 +292,7 @@ describe('createChatStreamResponse', () => {
})
it('maps deterministic initial chat load failures to public errors', async () => {
- vi.mocked(loadChatUncached).mockRejectedValueOnce(
+ vi.mocked(loadChat).mockRejectedValueOnce(
new DeterministicPreparationError(
'Unknown part type: private-user-content'
)
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 47686088..660aca04 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -16,7 +16,7 @@ import {
import { nextCitationLabelNumber } from '@/lib/utils/citation'
import { isTracingEnabled } from '@/lib/utils/telemetry'
-import { loadChatUncached } from '../actions/chat'
+import { loadChat } from '../actions/chat'
import { generateChatTitle } from '../agents/title-generator'
import {
getMaxAllowedTokens,
@@ -97,9 +97,7 @@ export async function createChatStreamResponse(
if (!isNewChat) {
try {
const loadChatStart = performance.now()
- // Read uncached: the prompt must not be built from a snapshot that
- // predates the previous turn's answer
- initialChat = await loadChatUncached(chatId, userId)
+ initialChat = await loadChat(chatId, userId)
perfTime('loadChat completed', loadChatStart)
} catch (error) {
logAPICallErrorDiagnostics(error)
diff --git a/lib/streaming/helpers/prepare-messages.ts b/lib/streaming/helpers/prepare-messages.ts
index 6218efe2..6268da83 100644
--- a/lib/streaming/helpers/prepare-messages.ts
+++ b/lib/streaming/helpers/prepare-messages.ts
@@ -67,9 +67,7 @@ export async function prepareMessages(
const targetMessageId = targetMessage.id
if (targetMessage.role === 'assistant') {
await deleteMessagesFromIndex(chatId, targetMessageId, userId)
- // Use in-memory messages instead of re-fetching from cache
- // loadChat uses unstable_cache which may return stale data
- // even after revalidateTag within the same request
+ // Use in-memory messages instead of re-fetching
return currentChat.messages.slice(0, messageIndex)
} else {
// User message edit
@@ -91,7 +89,7 @@ export async function prepareMessages(
if (messagesToDelete.length > 0) {
await deleteMessagesFromIndex(chatId, messagesToDelete[0].id, userId)
}
- // Use in-memory messages instead of re-fetching from cache
+ // Use in-memory messages instead of re-fetching
const messagesBeforeTarget = currentChat.messages.slice(0, messageIndex)
const editedMessage =
message && message.id === messageId ? message : targetMessage
diff --git a/next.config.mjs b/next.config.mjs
index 623af753..b26a4636 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -1,6 +1,9 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
skipTrailingSlashRedirect: true,
+ experimental: {
+ staleTimes: { dynamic: 300 }
+ },
async headers() {
return [
{
diff --git a/vitest.setup.ts b/vitest.setup.ts
index c7a8227b..d4d06fee 100644
--- a/vitest.setup.ts
+++ b/vitest.setup.ts
@@ -1,14 +1,5 @@
-import { vi } from 'vitest'
-
import '@testing-library/jest-dom'
// Provide dummy values for environment variables required during tests
process.env.DATABASE_URL =
process.env.DATABASE_URL ?? 'postgres://user:pass@localhost:5432/testdb'
-
-// Mock Next.js functions
-vi.mock('next/cache', () => ({
- revalidateTag: vi.fn(),
- revalidatePath: vi.fn(),
- unstable_cache: vi.fn(fn => fn)
-}))