mirror of
https://github.com/coleam00/bolt.new-any-llm
synced 2024-12-27 06:12:07 +00:00
feat: initial persistence (#3)
This commit is contained in:
parent
2b1bf0fdaf
commit
5db834e2f7
13
.editorconfig
Normal file
13
.editorconfig
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
indent_style = space
|
||||||
|
end_of_line = lf
|
||||||
|
charset = utf-8
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
|
max_line_length = 120
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
trim_trailing_whitespace = false
|
@ -1,3 +1,4 @@
|
|||||||
|
import type { Message } from 'ai';
|
||||||
import { useChat } from 'ai/react';
|
import { useChat } from 'ai/react';
|
||||||
import { useAnimate } from 'framer-motion';
|
import { useAnimate } from 'framer-motion';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
@ -8,6 +9,7 @@ import { workbenchStore } from '~/lib/stores/workbench';
|
|||||||
import { cubicEasingFn } from '~/utils/easings';
|
import { cubicEasingFn } from '~/utils/easings';
|
||||||
import { createScopedLogger } from '~/utils/logger';
|
import { createScopedLogger } from '~/utils/logger';
|
||||||
import { BaseChat } from './BaseChat';
|
import { BaseChat } from './BaseChat';
|
||||||
|
import { useChatHistory } from '~/lib/persistence';
|
||||||
|
|
||||||
const toastAnimation = cssTransition({
|
const toastAnimation = cssTransition({
|
||||||
enter: 'animated fadeInRight',
|
enter: 'animated fadeInRight',
|
||||||
@ -17,9 +19,25 @@ const toastAnimation = cssTransition({
|
|||||||
const logger = createScopedLogger('Chat');
|
const logger = createScopedLogger('Chat');
|
||||||
|
|
||||||
export function Chat() {
|
export function Chat() {
|
||||||
|
const { ready, initialMessages, storeMessageHistory } = useChatHistory();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{ready && <ChatImpl initialMessages={initialMessages} storeMessageHistory={storeMessageHistory} />}
|
||||||
|
<ToastContainer position="bottom-right" stacked pauseOnFocusLoss transition={toastAnimation} />;
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ChatProps {
|
||||||
|
initialMessages: Message[];
|
||||||
|
storeMessageHistory: (messages: Message[]) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ChatImpl({ initialMessages, storeMessageHistory }: ChatProps) {
|
||||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
const [chatStarted, setChatStarted] = useState(false);
|
const [chatStarted, setChatStarted] = useState(initialMessages.length > 0);
|
||||||
|
|
||||||
const [animationScope, animate] = useAnimate();
|
const [animationScope, animate] = useAnimate();
|
||||||
|
|
||||||
@ -32,6 +50,7 @@ export function Chat() {
|
|||||||
onFinish: () => {
|
onFinish: () => {
|
||||||
logger.debug('Finished streaming');
|
logger.debug('Finished streaming');
|
||||||
},
|
},
|
||||||
|
initialMessages,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
|
const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
|
||||||
@ -41,6 +60,7 @@ export function Chat() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
parseMessages(messages, isLoading);
|
parseMessages(messages, isLoading);
|
||||||
|
storeMessageHistory(messages).catch((error) => toast.error(error.message));
|
||||||
}, [messages, isLoading, parseMessages]);
|
}, [messages, isLoading, parseMessages]);
|
||||||
|
|
||||||
const scrollTextArea = () => {
|
const scrollTextArea = () => {
|
||||||
@ -97,38 +117,35 @@ export function Chat() {
|
|||||||
const [messageRef, scrollRef] = useSnapScroll();
|
const [messageRef, scrollRef] = useSnapScroll();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<BaseChat
|
||||||
<BaseChat
|
ref={animationScope}
|
||||||
ref={animationScope}
|
textareaRef={textareaRef}
|
||||||
textareaRef={textareaRef}
|
input={input}
|
||||||
input={input}
|
chatStarted={chatStarted}
|
||||||
chatStarted={chatStarted}
|
isStreaming={isLoading}
|
||||||
isStreaming={isLoading}
|
enhancingPrompt={enhancingPrompt}
|
||||||
enhancingPrompt={enhancingPrompt}
|
promptEnhanced={promptEnhanced}
|
||||||
promptEnhanced={promptEnhanced}
|
sendMessage={sendMessage}
|
||||||
sendMessage={sendMessage}
|
messageRef={messageRef}
|
||||||
messageRef={messageRef}
|
scrollRef={scrollRef}
|
||||||
scrollRef={scrollRef}
|
handleInputChange={handleInputChange}
|
||||||
handleInputChange={handleInputChange}
|
handleStop={abort}
|
||||||
handleStop={abort}
|
messages={messages.map((message, i) => {
|
||||||
messages={messages.map((message, i) => {
|
if (message.role === 'user') {
|
||||||
if (message.role === 'user') {
|
return message;
|
||||||
return message;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...message,
|
...message,
|
||||||
content: parsedMessages[i] || '',
|
content: parsedMessages[i] || '',
|
||||||
};
|
};
|
||||||
})}
|
})}
|
||||||
enhancePrompt={() => {
|
enhancePrompt={() => {
|
||||||
enhancePrompt(input, (input) => {
|
enhancePrompt(input, (input) => {
|
||||||
setInput(input);
|
setInput(input);
|
||||||
scrollTextArea();
|
scrollTextArea();
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<ToastContainer position="bottom-right" stacked={true} pauseOnFocusLoss={true} transition={toastAnimation} />
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,19 @@
|
|||||||
import { env } from 'node:process';
|
import { env } from 'node:process';
|
||||||
|
import { isAuthenticated } from './sessions';
|
||||||
|
import { json, redirect, type LoaderFunctionArgs } from '@remix-run/cloudflare';
|
||||||
|
|
||||||
export function verifyPassword(password: string, cloudflareEnv: Env) {
|
export function verifyPassword(password: string, cloudflareEnv: Env) {
|
||||||
const loginPassword = env.LOGIN_PASSWORD || cloudflareEnv.LOGIN_PASSWORD;
|
const loginPassword = env.LOGIN_PASSWORD || cloudflareEnv.LOGIN_PASSWORD;
|
||||||
|
|
||||||
return password === loginPassword;
|
return password === loginPassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function handleAuthRequest({ request, context }: LoaderFunctionArgs, body: object = {}) {
|
||||||
|
const authenticated = await isAuthenticated(request, context.cloudflare.env);
|
||||||
|
|
||||||
|
if (import.meta.env.DEV || authenticated) {
|
||||||
|
return json(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect('/login');
|
||||||
|
}
|
||||||
|
@ -9,15 +9,13 @@ export function useSnapScroll() {
|
|||||||
const messageRef = useCallback((node: HTMLDivElement | null) => {
|
const messageRef = useCallback((node: HTMLDivElement | null) => {
|
||||||
if (node) {
|
if (node) {
|
||||||
const observer = new ResizeObserver(() => {
|
const observer = new ResizeObserver(() => {
|
||||||
if (autoScrollRef.current) {
|
if (autoScrollRef.current && scrollNodeRef.current) {
|
||||||
if (scrollNodeRef.current) {
|
const { scrollHeight, clientHeight } = scrollNodeRef.current;
|
||||||
const { scrollHeight, clientHeight } = scrollNodeRef.current;
|
const scrollTarget = scrollHeight - clientHeight;
|
||||||
const scrollTarget = scrollHeight - clientHeight;
|
|
||||||
|
|
||||||
scrollNodeRef.current.scrollTo({
|
scrollNodeRef.current.scrollTo({
|
||||||
top: scrollTarget,
|
top: scrollTarget,
|
||||||
});
|
});
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
67
packages/bolt/app/lib/persistence/db.ts
Normal file
67
packages/bolt/app/lib/persistence/db.ts
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
import type { ChatHistory } from './useChatHistory';
|
||||||
|
import type { Message } from 'ai';
|
||||||
|
import { createScopedLogger } from '~/utils/logger';
|
||||||
|
|
||||||
|
const logger = createScopedLogger('ChatHistory');
|
||||||
|
|
||||||
|
// this is used at the top level and never rejects
|
||||||
|
export async function openDatabase(): Promise<IDBDatabase | undefined> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const request = indexedDB.open('boltHistory', 1);
|
||||||
|
|
||||||
|
request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
|
||||||
|
const db = (event.target as IDBOpenDBRequest).result;
|
||||||
|
|
||||||
|
if (!db.objectStoreNames.contains('chats')) {
|
||||||
|
const store = db.createObjectStore('chats', { keyPath: 'id' });
|
||||||
|
store.createIndex('id', 'id', { unique: true });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
request.onsuccess = (event: Event) => {
|
||||||
|
resolve((event.target as IDBOpenDBRequest).result);
|
||||||
|
};
|
||||||
|
|
||||||
|
request.onerror = (event: Event) => {
|
||||||
|
resolve(undefined);
|
||||||
|
logger.error((event.target as IDBOpenDBRequest).error);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setMessages(db: IDBDatabase, id: string, messages: Message[]): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = db.transaction('chats', 'readwrite');
|
||||||
|
const store = transaction.objectStore('chats');
|
||||||
|
|
||||||
|
const request = store.put({
|
||||||
|
id,
|
||||||
|
messages,
|
||||||
|
});
|
||||||
|
|
||||||
|
request.onsuccess = () => resolve();
|
||||||
|
request.onerror = () => reject(request.error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMessages(db: IDBDatabase, id: string): Promise<ChatHistory> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = db.transaction('chats', 'readonly');
|
||||||
|
const store = transaction.objectStore('chats');
|
||||||
|
const request = store.get(id);
|
||||||
|
|
||||||
|
request.onsuccess = () => resolve(request.result as ChatHistory);
|
||||||
|
request.onerror = () => reject(request.error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getNextID(db: IDBDatabase): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = db.transaction('chats', 'readonly');
|
||||||
|
const store = transaction.objectStore('chats');
|
||||||
|
const request = store.count();
|
||||||
|
|
||||||
|
request.onsuccess = () => resolve(String(request.result));
|
||||||
|
request.onerror = () => reject(request.error);
|
||||||
|
});
|
||||||
|
}
|
2
packages/bolt/app/lib/persistence/index.ts
Normal file
2
packages/bolt/app/lib/persistence/index.ts
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
export * from './db';
|
||||||
|
export * from './useChatHistory';
|
86
packages/bolt/app/lib/persistence/useChatHistory.ts
Normal file
86
packages/bolt/app/lib/persistence/useChatHistory.ts
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
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 { toast } from 'react-toastify';
|
||||||
|
|
||||||
|
export interface ChatHistory {
|
||||||
|
id: string;
|
||||||
|
displayName?: string;
|
||||||
|
messages: Message[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const persistenceEnabled = !import.meta.env.VITE_DISABLE_PERSISTENCE;
|
||||||
|
|
||||||
|
const db = persistenceEnabled ? await openDatabase() : undefined;
|
||||||
|
|
||||||
|
export function useChatHistory() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { id: chatId } = useLoaderData<{ id?: string }>();
|
||||||
|
|
||||||
|
const [initialMessages, setInitialMessages] = useState<Message[]>([]);
|
||||||
|
const [ready, setReady] = useState<boolean>(false);
|
||||||
|
const [entryId, setEntryId] = useState<string | undefined>();
|
||||||
|
|
||||||
|
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);
|
||||||
|
} 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (initialMessages.length === 0) {
|
||||||
|
if (!entryId) {
|
||||||
|
const nextId = await getNextID(db);
|
||||||
|
|
||||||
|
await setMessages(db, nextId, messages);
|
||||||
|
|
||||||
|
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);
|
||||||
|
} else {
|
||||||
|
await setMessages(db, entryId, messages);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await setMessages(db, chatId as string, messages);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
@ -1,22 +1,16 @@
|
|||||||
import { json, redirect, type LoaderFunctionArgs, type MetaFunction } from '@remix-run/cloudflare';
|
import { type LoaderFunctionArgs, type MetaFunction } from '@remix-run/cloudflare';
|
||||||
import { ClientOnly } from 'remix-utils/client-only';
|
import { ClientOnly } from 'remix-utils/client-only';
|
||||||
import { BaseChat } from '~/components/chat/BaseChat';
|
import { BaseChat } from '~/components/chat/BaseChat';
|
||||||
import { Chat } from '~/components/chat/Chat.client';
|
import { Chat } from '~/components/chat/Chat.client';
|
||||||
import { Header } from '~/components/Header';
|
import { Header } from '~/components/Header';
|
||||||
import { isAuthenticated } from '~/lib/.server/sessions';
|
import { handleAuthRequest } from '~/lib/.server/login';
|
||||||
|
|
||||||
export const meta: MetaFunction = () => {
|
export const meta: MetaFunction = () => {
|
||||||
return [{ title: 'Bolt' }, { name: 'description', content: 'Talk with Bolt, an AI assistant from StackBlitz' }];
|
return [{ title: 'Bolt' }, { name: 'description', content: 'Talk with Bolt, an AI assistant from StackBlitz' }];
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function loader({ request, context }: LoaderFunctionArgs) {
|
export async function loader(args: LoaderFunctionArgs) {
|
||||||
const authenticated = await isAuthenticated(request, context.cloudflare.env);
|
return handleAuthRequest(args);
|
||||||
|
|
||||||
if (import.meta.env.DEV || authenticated) {
|
|
||||||
return json({});
|
|
||||||
}
|
|
||||||
|
|
||||||
return redirect('/login');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Index() {
|
export default function Index() {
|
||||||
|
9
packages/bolt/app/routes/chat.$id.tsx
Normal file
9
packages/bolt/app/routes/chat.$id.tsx
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import type { LoaderFunctionArgs } from '@remix-run/cloudflare';
|
||||||
|
import { default as IndexRoute } from './_index';
|
||||||
|
import { handleAuthRequest } from '~/lib/.server/login';
|
||||||
|
|
||||||
|
export async function loader(args: LoaderFunctionArgs) {
|
||||||
|
return handleAuthRequest(args, { id: args.params.id });
|
||||||
|
}
|
||||||
|
|
||||||
|
export default IndexRoute;
|
Loading…
Reference in New Issue
Block a user