feat: use artifact id in urls, store metadata in history (#15)

This commit is contained in:
Kirjava
2024-07-29 14:02:15 +01:00
committed by GitHub
parent 4eb54949cf
commit a9036a1030
4 changed files with 134 additions and 35 deletions

View File

@@ -1,5 +1,5 @@
import type { ChatHistory } from './useChatHistory';
import type { Message } from 'ai';
import type { ChatHistory } from './useChatHistory';
import { createScopedLogger } from '~/utils/logger';
const logger = createScopedLogger('ChatHistory');
@@ -15,6 +15,7 @@ export async function openDatabase(): Promise<IDBDatabase | undefined> {
if (!db.objectStoreNames.contains('chats')) {
const store = db.createObjectStore('chats', { keyPath: 'id' });
store.createIndex('id', 'id', { unique: true });
store.createIndex('urlId', 'urlId', { unique: true });
}
};
@@ -29,7 +30,13 @@ export async function openDatabase(): Promise<IDBDatabase | undefined> {
});
}
export async function setMessages(db: IDBDatabase, id: string, messages: Message[]): Promise<void> {
export async function setMessages(
db: IDBDatabase,
id: string,
messages: Message[],
urlId?: string,
description?: string,
): Promise<void> {
return new Promise((resolve, reject) => {
const transaction = db.transaction('chats', 'readwrite');
const store = transaction.objectStore('chats');
@@ -37,6 +44,8 @@ export async function setMessages(db: IDBDatabase, id: string, messages: Message
const request = store.put({
id,
messages,
urlId,
description,
});
request.onsuccess = () => resolve();
@@ -45,6 +54,22 @@ export async function setMessages(db: IDBDatabase, id: string, messages: Message
}
export async function getMessages(db: IDBDatabase, id: string): Promise<ChatHistory> {
return (await getMessagesById(db, id)) || (await getMessagesByUrlId(db, id));
}
export async function getMessagesByUrlId(db: IDBDatabase, id: string): Promise<ChatHistory> {
return new Promise((resolve, reject) => {
const transaction = db.transaction('chats', 'readonly');
const store = transaction.objectStore('chats');
const index = store.index('urlId');
const request = index.get(id);
request.onsuccess = () => resolve(request.result as ChatHistory);
request.onerror = () => reject(request.error);
});
}
export async function getMessagesById(db: IDBDatabase, id: string): Promise<ChatHistory> {
return new Promise((resolve, reject) => {
const transaction = db.transaction('chats', 'readonly');
const store = transaction.objectStore('chats');
@@ -55,7 +80,7 @@ export async function getMessages(db: IDBDatabase, id: string): Promise<ChatHist
});
}
export async function getNextID(db: IDBDatabase): Promise<string> {
export async function getNextId(db: IDBDatabase): Promise<string> {
return new Promise((resolve, reject) => {
const transaction = db.transaction('chats', 'readonly');
const store = transaction.objectStore('chats');
@@ -65,3 +90,44 @@ export async function getNextID(db: IDBDatabase): Promise<string> {
request.onerror = () => reject(request.error);
});
}
export async function getUrlId(db: IDBDatabase, id: string): Promise<string> {
const idList = await getUrlIds(db);
if (!idList.includes(id)) {
return id;
} else {
let i = 2;
while (idList.includes(`${id}-${i}`)) {
i++;
}
return `${id}-${i}`;
}
}
async function getUrlIds(db: IDBDatabase): Promise<string[]> {
return new Promise((resolve, reject) => {
const transaction = db.transaction('chats', 'readonly');
const store = transaction.objectStore('chats');
const idList: string[] = [];
const request = store.openCursor();
request.onsuccess = (event: Event) => {
const cursor = (event.target as IDBRequest<IDBCursorWithValue>).result;
if (cursor) {
idList.push(cursor.value.urlId);
cursor.continue();
} else {
resolve(idList);
}
};
request.onerror = () => {
reject(request.error);
};
});
}

View File

@@ -1,12 +1,14 @@
import { useNavigate, useLoaderData } from '@remix-run/react';
import { useState, useEffect } from 'react';
import type { Message } from 'ai';
import { openDatabase, setMessages, getMessages, getNextID } from './db';
import { openDatabase, setMessages, getMessages, getNextId, getUrlId } from './db';
import { toast } from 'react-toastify';
import { workbenchStore } from '~/lib/stores/workbench';
export interface ChatHistory {
id: string;
displayName?: string;
urlId?: string;
description?: string;
messages: Message[];
}
@@ -21,6 +23,8 @@ export function useChatHistory() {
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>();
useEffect(() => {
if (!db) {
@@ -58,29 +62,48 @@ export function useChatHistory() {
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);
}
if (initialMessages.length === 0) {
if (!entryId) {
const nextId = await getNextID(db);
const nextId = await getNextId(db);
await setMessages(db, nextId, messages);
await setMessages(db, nextId, messages, urlId, description);
setEntryId(nextId);
/**
* 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);
if (!urlId) {
navigateChat(nextId);
}
} else {
await setMessages(db, entryId, messages);
await setMessages(db, entryId, messages, urlId, description);
}
} else {
await setMessages(db, chatId as string, messages);
await setMessages(db, chatId as string, messages, urlId, description);
}
},
};
}
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);
}