Add import, fix export

This commit is contained in:
eduardruzga 2024-11-23 00:23:45 +02:00
parent 9f49c25f96
commit fb34a4cb8f
9 changed files with 93 additions and 86 deletions

View File

@ -12,7 +12,6 @@ import { Messages } from './Messages.client';
import { SendButton } from './SendButton.client'; import { SendButton } from './SendButton.client';
import { APIKeyManager } from './APIKeyManager'; import { APIKeyManager } from './APIKeyManager';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import { exportChat, importChat } from '~/utils/chatExport';
import { toast } from 'react-toastify'; import { toast } from 'react-toastify';
import * as Tooltip from '@radix-ui/react-tooltip'; import * as Tooltip from '@radix-ui/react-tooltip';
@ -90,6 +89,8 @@ interface BaseChatProps {
sendMessage?: (event: React.UIEvent, messageInput?: string) => void; sendMessage?: (event: React.UIEvent, messageInput?: string) => void;
handleInputChange?: (event: React.ChangeEvent<HTMLTextAreaElement>) => void; handleInputChange?: (event: React.ChangeEvent<HTMLTextAreaElement>) => void;
enhancePrompt?: () => void; enhancePrompt?: () => void;
importChat?: (description: string, messages: Message[]) => Promise<void>;
exportChat?: () => void;
} }
export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>( export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
@ -113,7 +114,9 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
sendMessage, sendMessage,
handleInputChange, handleInputChange,
enhancePrompt, enhancePrompt,
handleStop handleStop,
importChat,
exportChat
}, },
ref ref
) => { ) => {
@ -292,7 +295,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
</> </>
)} )}
</IconButton> </IconButton>
<ClientOnly>{() => <ExportChatButton description={description} messages={messages}/>}</ClientOnly> <ClientOnly>{() => <ExportChatButton exportChat={exportChat}/>}</ClientOnly>
</div> </div>
{input.length > 3 ? ( {input.length > 3 ? (
<div className="text-xs text-bolt-elements-textTertiary"> <div className="text-xs text-bolt-elements-textTertiary">
@ -317,18 +320,31 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
accept=".json" accept=".json"
onChange={async (e) => { onChange={async (e) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (file) { if (file && importChat) {
try { try {
const { messages: importedMessages } = await importChat(file); const reader = new FileReader();
// Import each message reader.onload = async (e) => {
for (const msg of importedMessages) { try {
await sendMessage(new Event('import') as unknown as React.UIEvent, msg.content); const content = e.target?.result as string;
const data = JSON.parse(content);
if (!Array.isArray(data.messages)) {
toast.error('Invalid chat file format');
} }
await importChat(data.description, data.messages);
toast.success('Chat imported successfully'); toast.success('Chat imported successfully');
} catch (error) {
toast.error('Failed to parse chat file');
}
};
reader.onerror = () => toast.error('Failed to read chat file');
reader.readAsText(file);
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to import chat'); toast.error(error instanceof Error ? error.message : 'Failed to import chat');
} }
e.target.value = ''; // Reset file input e.target.value = ''; // Reset file input
} else {
toast.error('Something went wrong');
} }
}} }}
/> />

View File

@ -28,12 +28,12 @@ const logger = createScopedLogger('Chat');
export function Chat() { export function Chat() {
renderLogger.trace('Chat'); renderLogger.trace('Chat');
const { ready, initialMessages, storeMessageHistory } = useChatHistory(); const { ready, initialMessages, storeMessageHistory, importChat, exportChat } = useChatHistory();
const title = useStore(description); const title = useStore(description);
return ( return (
<> <>
{ready && <ChatImpl description={title} initialMessages={initialMessages} storeMessageHistory={storeMessageHistory} />} {ready && <ChatImpl description={title} initialMessages={initialMessages} exportChat={exportChat} storeMessageHistory={storeMessageHistory} importChat={importChat} />}
<ToastContainer <ToastContainer
closeButton={({ closeToast }) => { closeButton={({ closeToast }) => {
return ( return (
@ -68,9 +68,11 @@ export function Chat() {
interface ChatProps { interface ChatProps {
initialMessages: Message[]; initialMessages: Message[];
storeMessageHistory: (messages: Message[]) => Promise<void>; storeMessageHistory: (messages: Message[]) => Promise<void>;
importChat: (description: string, messages: Message[]) => Promise<void>;
exportChat: () => void;
} }
export const ChatImpl = memo(({ description, initialMessages, storeMessageHistory }: ChatProps) => { export const ChatImpl = memo(({ description, initialMessages, storeMessageHistory, importChat, exportChat }: ChatProps) => {
useShortcuts(); useShortcuts();
const textareaRef = useRef<HTMLTextAreaElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null);
@ -254,6 +256,8 @@ export const ChatImpl = memo(({ description, initialMessages, storeMessageHistor
handleInputChange={handleInputChange} handleInputChange={handleInputChange}
handleStop={abort} handleStop={abort}
description={description} description={description}
importChat={importChat}
exportChat={exportChat}
messages={messages.map((message, i) => { messages={messages.map((message, i) => {
if (message.role === 'user') { if (message.role === 'user') {
return message; return message;

View File

@ -1,14 +1,12 @@
import WithTooltip from '~/components/ui/Tooltip'; import WithTooltip from '~/components/ui/Tooltip';
import { IconButton } from '~/components/ui/IconButton'; import { IconButton } from '~/components/ui/IconButton';
import { exportChat } from '~/utils/chatExport';
import React from 'react'; import React from 'react';
import type { Message } from 'ai';
export const ExportChatButton = ({description, messages}: {description: string, messages: Message[]}) => { export const ExportChatButton = ({exportChat}: {exportChat: () => void}) => {
return (<WithTooltip tooltip="Export Chat"> return (<WithTooltip tooltip="Export Chat">
<IconButton <IconButton
title="Export Chat" title="Export Chat"
onClick={() => exportChat(messages || [], description)} onClick={exportChat}
> >
<div className="i-ph:download-simple text-xl"></div> <div className="i-ph:download-simple text-xl"></div>
</IconButton> </IconButton>

View File

@ -33,7 +33,6 @@ export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props:
toast.error('Chat persistence is not available'); toast.error('Chat persistence is not available');
return; return;
} }
const urlId = await forkChat(db, chatId.get()!, messageId); const urlId = await forkChat(db, chatId.get()!, messageId);
window.location.href = `/chat/${urlId}`; window.location.href = `/chat/${urlId}`;
} catch (error) { } catch (error) {

View File

@ -1,16 +1,16 @@
import * as Dialog from '@radix-ui/react-dialog'; import * as Dialog from '@radix-ui/react-dialog';
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { type ChatHistoryItem } from '~/lib/persistence'; import { type ChatHistoryItem } from '~/lib/persistence';
import { exportChat } from '~/utils/chatExport';
import WithTooltip from '~/components/ui/Tooltip'; import WithTooltip from '~/components/ui/Tooltip';
interface HistoryItemProps { interface HistoryItemProps {
item: ChatHistoryItem; item: ChatHistoryItem;
onDelete?: (event: React.UIEvent) => void; onDelete?: (event: React.UIEvent) => void;
onDuplicate?: (id: string) => void; onDuplicate?: (id: string) => void;
exportChat: (id?: string) => void;
} }
export function HistoryItem({ item, onDelete, onDuplicate }: HistoryItemProps) { export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: HistoryItemProps) {
const [hovering, setHovering] = useState(false); const [hovering, setHovering] = useState(false);
const hoverRef = useRef<HTMLDivElement>(null); const hoverRef = useRef<HTMLDivElement>(null);
@ -53,7 +53,8 @@ export function HistoryItem({ item, onDelete, onDuplicate }: HistoryItemProps) {
className="i-ph:download-simple scale-110 mr-2" className="i-ph:download-simple scale-110 mr-2"
onClick={(event) => { onClick={(event) => {
event.preventDefault(); event.preventDefault();
exportChat(item.messages, item.description); exportChat(item.id);
//exportChat(item.messages, item.description);
}} }}
title="Export chat" title="Export chat"
/> />

View File

@ -34,7 +34,7 @@ const menuVariants = {
type DialogContent = { type: 'delete'; item: ChatHistoryItem } | null; type DialogContent = { type: 'delete'; item: ChatHistoryItem } | null;
export function Menu() { export function Menu() {
const { duplicateCurrentChat } = useChatHistory(); const { duplicateCurrentChat, exportChat } = useChatHistory();
const menuRef = useRef<HTMLDivElement>(null); const menuRef = useRef<HTMLDivElement>(null);
const [list, setList] = useState<ChatHistoryItem[]>([]); const [list, setList] = useState<ChatHistoryItem[]>([]);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@ -102,7 +102,6 @@ export function Menu() {
const handleDeleteClick = (event: React.UIEvent, item: ChatHistoryItem) => { const handleDeleteClick = (event: React.UIEvent, item: ChatHistoryItem) => {
event.preventDefault(); event.preventDefault();
setDialogContent({ type: 'delete', item }); setDialogContent({ type: 'delete', item });
}; };
@ -144,6 +143,7 @@ export function Menu() {
<HistoryItem <HistoryItem
key={item.id} key={item.id}
item={item} item={item}
exportChat={exportChat}
onDelete={(event) => handleDeleteClick(event, item)} onDelete={(event) => handleDeleteClick(event, item)}
onDuplicate={() => handleDuplicate(item.id)} onDuplicate={() => handleDuplicate(item.id)}
/> />

View File

@ -170,37 +170,29 @@ export async function forkChat(db: IDBDatabase, chatId: string, messageId: strin
// Get messages up to and including the selected message // Get messages up to and including the selected message
const messages = chat.messages.slice(0, messageIndex + 1); const messages = chat.messages.slice(0, messageIndex + 1);
// Generate new IDs return createChatFromMessages(db, chat.description ? `${chat.description} (fork)` : 'Forked chat', messages);
const newId = await getNextId(db);
const urlId = await getUrlId(db, newId);
// Create the forked chat
await setMessages(
db,
newId,
messages,
urlId,
chat.description ? `${chat.description} (fork)` : 'Forked chat'
);
return urlId;
} }
export async function duplicateChat(db: IDBDatabase, id: string): Promise<string> { export async function duplicateChat(db: IDBDatabase, id: string): Promise<string> {
const chat = await getMessages(db, id); const chat = await getMessages(db, id);
if (!chat) { if (!chat) {
throw new Error('Chat not found'); throw new Error('Chat not found');
} }
return createChatFromMessages(db, `${chat.description || 'Chat'} (copy)`, chat.messages);
}
export async function createChatFromMessages(db: IDBDatabase, description: string, messages: Message[]) : Promise<string> {
const newId = await getNextId(db); const newId = await getNextId(db);
const newUrlId = await getUrlId(db, newId); // Get a new urlId for the duplicated chat const newUrlId = await getUrlId(db, newId); // Get a new urlId for the duplicated chat
await setMessages( await setMessages(
db, db,
newId, newId,
chat.messages, messages,
newUrlId, // Use the new urlId newUrlId, // Use the new urlId
`${chat.description || 'Chat'} (copy)` description
); );
return newUrlId; // Return the urlId instead of id for navigation return newUrlId; // Return the urlId instead of id for navigation

View File

@ -4,7 +4,15 @@ import { atom } from 'nanostores';
import type { Message } from 'ai'; import type { Message } from 'ai';
import { toast } from 'react-toastify'; import { toast } from 'react-toastify';
import { workbenchStore } from '~/lib/stores/workbench'; import { workbenchStore } from '~/lib/stores/workbench';
import { getMessages, getNextId, getUrlId, openDatabase, setMessages, duplicateChat } from './db'; import {
getMessages,
getNextId,
getUrlId,
openDatabase,
setMessages,
duplicateChat,
createChatFromMessages
} from './db';
export interface ChatHistoryItem { export interface ChatHistoryItem {
id: string; id: string;
@ -111,6 +119,41 @@ export function useChatHistory() {
} catch (error) { } catch (error) {
toast.error('Failed to duplicate chat'); toast.error('Failed to duplicate chat');
} }
},
importChat: async (description: string, messages:Message[]) => {
if (!db) {
return;
}
try {
const newId = await createChatFromMessages(db, description, messages);
window.location.href = `/chat/${newId}`;
toast.success('Chat imported successfully');
} catch (error) {
toast.error('Failed to import chat');
}
},
exportChat: async (id = urlId) => {
if (!db || !id) {
return;
}
const chat = await getMessages(db, id);
const chatData = {
messages: chat.messages,
description: chat.description,
exportDate: new Date().toISOString(),
};
const blob = new Blob([JSON.stringify(chatData, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `chat-${new Date().toISOString()}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} }
}; };
} }

View File

@ -1,46 +0,0 @@
import type { Message } from 'ai';
import { toast } from 'react-toastify';
export interface ChatExportData {
messages: Message[];
description?: string;
exportDate: string;
}
export const exportChat = (messages: Message[], description?: string) => {
const chatData: ChatExportData = {
messages,
description,
exportDate: new Date().toISOString(),
};
const blob = new Blob([JSON.stringify(chatData, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `chat-${new Date().toISOString()}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
export const importChat = async (file: File): Promise<ChatExportData> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const content = e.target?.result as string;
const data = JSON.parse(content);
if (!Array.isArray(data.messages)) {
throw new Error('Invalid chat file format');
}
resolve(data);
} catch (error) {
reject(new Error('Failed to parse chat file'));
}
};
reader.onerror = () => reject(new Error('Failed to read chat file'));
reader.readAsText(file);
});
};