bolt.new/packages/bolt/app/lib/persistence/useChatHistory.ts

126 lines
3.4 KiB
TypeScript
Raw Normal View History

2024-07-25 13:03:38 +00:00
import { useNavigate, useLoaderData } from '@remix-run/react';
import { useState, useEffect } from 'react';
import type { Message } from 'ai';
import { openDatabase, setMessages, getMessages, getNextId, getUrlId } from './db';
2024-07-25 13:03:38 +00:00
import { toast } from 'react-toastify';
import { workbenchStore } from '~/lib/stores/workbench';
2024-08-12 15:37:45 +00:00
import { sendAnalyticsEvent, AnalyticsAction } from '~/lib/analytics';
2024-07-25 13:03:38 +00:00
export interface ChatHistory {
id: string;
urlId?: string;
description?: string;
2024-07-25 13:03:38 +00:00
messages: Message[];
2024-07-31 21:21:40 +00:00
timestamp: string;
2024-07-25 13:03:38 +00:00
}
const persistenceEnabled = !import.meta.env.VITE_DISABLE_PERSISTENCE;
export const db = persistenceEnabled ? await openDatabase() : undefined;
2024-07-25 13:03:38 +00:00
export function useChatHistory() {
const navigate = useNavigate();
const { id: mixedId } = useLoaderData<{ id?: string }>();
2024-07-25 13:03:38 +00:00
const [chatId, setChatId] = useState(mixedId);
2024-07-25 13:03:38 +00:00
const [initialMessages, setInitialMessages] = useState<Message[]>([]);
const [ready, setReady] = useState<boolean>(false);
const [entryId, setEntryId] = useState<string | undefined>();
const [urlId, setUrlId] = useState<string | undefined>();
const [description, setDescription] = useState<string | undefined>();
2024-07-25 13:03:38 +00:00
useEffect(() => {
if (!db) {
setReady(true);
if (persistenceEnabled) {
toast.error(`Chat persistence is unavailable`);
}
return;
}
if (chatId) {
getMessages(db, chatId)
.then((storedMessages) => {
if (storedMessages && storedMessages.messages.length > 0) {
setInitialMessages(storedMessages.messages);
setUrlId(storedMessages.urlId);
setDescription(storedMessages.description);
setChatId(storedMessages.id);
2024-07-25 13:03:38 +00:00
} else {
navigate(`/`, { replace: true });
}
setReady(true);
})
.catch((error) => {
toast.error(error.message);
});
}
}, []);
return {
ready: !chatId || ready,
initialMessages,
storeMessageHistory: async (messages: Message[]) => {
if (!db || messages.length === 0) {
return;
}
const { firstArtifact } = workbenchStore;
if (!urlId && firstArtifact?.id) {
const urlId = await getUrlId(db, firstArtifact.id);
navigateChat(urlId);
setUrlId(urlId);
}
if (!description && firstArtifact?.title) {
setDescription(firstArtifact?.title);
}
2024-07-25 13:03:38 +00:00
if (initialMessages.length === 0) {
if (!entryId) {
const nextId = await getNextId(db);
2024-07-25 13:03:38 +00:00
await setMessages(db, nextId, messages, urlId, description);
2024-07-25 13:03:38 +00:00
setEntryId(nextId);
if (!urlId) {
navigateChat(nextId);
}
2024-07-25 13:03:38 +00:00
} else {
await setMessages(db, entryId, messages, urlId, description);
2024-07-25 13:03:38 +00:00
}
} else {
await setMessages(db, chatId as string, messages, urlId, description);
2024-07-25 13:03:38 +00:00
}
},
};
}
function navigateChat(nextId: string) {
/**
* FIXME: Using the intended navigate function causes a rerender for <Chat /> that breaks the app.
*
* `navigate(`/chat/${nextId}`, { replace: true });`
*/
const url = new URL(window.location.href);
url.pathname = `/chat/${nextId}`;
window.history.replaceState({}, '', url);
2024-08-12 15:37:45 +00:00
// since the `replaceState` call doesn't trigger a page reload, we need to manually log this event
sendAnalyticsEvent({
action: AnalyticsAction.Page,
payload: {
properties: {
url: url.href,
},
},
});
}