From d44c2d3f5aeab25a9405896f48a36082cee5d8ac Mon Sep 17 00:00:00 2001 From: firecoperana Date: Sun, 20 Jul 2025 05:33:55 -0500 Subject: Webui: New Features for Conversations, Settings, and Chat Messages (#618) * Webui: add Rename/Upload conversation in header and sidebar webui: don't change modified date when renaming conversation * webui: add a preset feature to the settings #14649 * webui: Add editing assistant messages #13522 Webui: keep the following message while editing assistance response. webui: change icon to edit message * webui: DB import and export #14347 * webui: Wrap long numbers instead of infinite horizontal scroll (#14062) fix sidebar being covered by main content #14082 --------- Co-authored-by: firecoperana --- .../server/webui/src/components/ChatMessage.tsx | 17 +- .../server/webui/src/components/ChatScreen.tsx | 57 ++- examples/server/webui/src/components/Header.tsx | 86 ++++- .../server/webui/src/components/ModalProvider.tsx | 151 ++++++++ .../server/webui/src/components/SettingDialog.tsx | 268 ++++++++++++++- examples/server/webui/src/components/Sidebar.tsx | 382 +++++++++++++++++++-- 6 files changed, 901 insertions(+), 60 deletions(-) create mode 100644 examples/server/webui/src/components/ModalProvider.tsx (limited to 'examples/server/webui/src/components') diff --git a/examples/server/webui/src/components/ChatMessage.tsx b/examples/server/webui/src/components/ChatMessage.tsx index 40ea7471..a60fd241 100644 --- a/examples/server/webui/src/components/ChatMessage.tsx +++ b/examples/server/webui/src/components/ChatMessage.tsx @@ -20,6 +20,7 @@ export default function ChatMessage({ onEditMessage, onChangeSibling, isPending, + onContinueMessage, }: { msg: Message | PendingMessage; siblingLeafNodeIds: Message['id'][]; @@ -27,6 +28,7 @@ export default function ChatMessage({ id?: string; onRegenerateMessage(msg: Message): void; onEditMessage(msg: Message, content: string): void; + onContinueMessage(msg: Message, content: string): void; onChangeSibling(sibling: Message['id']): void; isPending?: boolean; }) { @@ -112,7 +114,11 @@ export default function ChatMessage({ onClick={() => { if (msg.content !== null) { setEditingContent(null); - onEditMessage(msg as Message, editingContent); + if (msg.role === 'user') { + onEditMessage(msg as Message, editingContent); + } else { + onContinueMessage(msg as Message, editingContent); + } } }} > @@ -283,6 +289,15 @@ export default function ChatMessage({ 🔄 Regenerate )} + {!isPending && ( + + )} )} { + if (!viewingChat || !continueMessageAndGenerate) return; + setCurrNodeId(msg.id); + scrollToBottom(false); + await continueMessageAndGenerate( + viewingChat.conv.id, + msg.id, + content, + onChunk + ); + setCurrNodeId(-1); + scrollToBottom(false); + }; + const hasCanvas = !!canvasData; useEffect(() => { @@ -204,7 +219,7 @@ export default function ChatScreen() { // due to some timing issues of StorageUtils.appendMsg(), we need to make sure the pendingMsg is not duplicated upon rendering (i.e. appears once in the saved conversation and once in the pendingMsg) const pendingMsgDisplay: MessageDisplay[] = - pendingMsg && messages.at(-1)?.msg.id !== pendingMsg.id + pendingMsg && !messages.some((m) => m.msg.id === pendingMsg.id) // Only show if pendingMsg is not an existing message being continued ? [ { msg: pendingMsg, @@ -236,17 +251,35 @@ export default function ChatScreen() { {/* placeholder to shift the message to the bottom */} {viewingChat ? '' : 'Send a message to start'} - {[...messages, ...pendingMsgDisplay].map((msg) => ( - - ))} + {[...messages, ...pendingMsgDisplay].map((msgDisplay) => { + const actualMsgObject = msgDisplay.msg; + // Check if the current message from the list is the one actively being generated/continued + const isThisMessageTheActivePendingOne = + pendingMsg?.id === actualMsgObject.id; + + return ( + + ); + })} {/* chat input */} diff --git a/examples/server/webui/src/components/Header.tsx b/examples/server/webui/src/components/Header.tsx index 84fea191..601fb960 100644 --- a/examples/server/webui/src/components/Header.tsx +++ b/examples/server/webui/src/components/Header.tsx @@ -5,6 +5,14 @@ import { classNames } from '../utils/misc'; import daisyuiThemes from 'daisyui/theme/object'; import { THEMES } from '../Config'; import { useNavigate } from 'react-router'; +import toast from 'react-hot-toast'; +import { useModals } from './ModalProvider'; +import { + ArrowUpTrayIcon, + ArrowDownTrayIcon, + PencilIcon, + TrashIcon, +} from '@heroicons/react/24/outline'; export default function Header() { const navigate = useNavigate(); @@ -24,9 +32,11 @@ export default function Header() { ); }, [selectedTheme]); + const {showPrompt } = useModals(); const { isGenerating, viewingChat } = useAppContext(); const isCurrConvGenerating = isGenerating(viewingChat?.conv.id ?? ''); + // remove conversation const removeConversation = () => { if (isCurrConvGenerating || !viewingChat) return; const convId = viewingChat?.conv.id; @@ -35,6 +45,37 @@ export default function Header() { navigate('/'); } }; + + // rename conversation + async function renameConversation() { + if (isGenerating(viewingChat?.conv.id ?? '')) { + toast.error( + 'Cannot rename conversation while generating' + ); + return; + } + const newName = await showPrompt( + 'Enter new name for the conversation', + viewingChat?.conv.name + ); + if (newName && newName.trim().length > 0) { + StorageUtils.updateConversationName(viewingChat?.conv.id ?? '', newName); + } + //const importedConv = await StorageUtils.updateConversationName(); + //if (importedConv) { + //console.log('Successfully imported:', importedConv.name); + // Refresh UI or navigate to conversation + //} + }; + + // at the top of your file, alongside ConversationExport: + async function importConversation() { + const importedConv = await StorageUtils.importConversationFromFile(); + if (importedConv) { + console.log('Successfully imported:', importedConv.name); + // Refresh UI or navigate to conversation + } + }; const downloadConversation = () => { if (isCurrConvGenerating || !viewingChat) return; @@ -99,12 +140,45 @@ export default function Header() { tabIndex={0} className="dropdown-content menu bg-base-100 rounded-box z-[1] w-52 p-2 shadow" > -
  • - Download -
  • -
  • - Delete -
  • + {/* Always show Upload when viewingChat is false */} + {!viewingChat && ( +
  • + + + Upload + +
  • + )} + + {/* Show all three when viewingChat is true */} + {viewingChat && ( + <> +
  • + + + Upload + +
  • +
  • + + + Rename + +
  • +
  • + + + Download + +
  • +
  • + + + Delete + +
  • + + )} )} diff --git a/examples/server/webui/src/components/ModalProvider.tsx b/examples/server/webui/src/components/ModalProvider.tsx new file mode 100644 index 00000000..f2ebf8e0 --- /dev/null +++ b/examples/server/webui/src/components/ModalProvider.tsx @@ -0,0 +1,151 @@ +import React, { createContext, useState, useContext } from 'react'; + +type ModalContextType = { + showConfirm: (message: string) => Promise; + showPrompt: ( + message: string, + defaultValue?: string + ) => Promise; + showAlert: (message: string) => Promise; +}; +const ModalContext = createContext(null!); + +interface ModalState { + isOpen: boolean; + message: string; + defaultValue?: string; + resolve: ((value: T) => void) | null; +} + +export function ModalProvider({ children }: { children: React.ReactNode }) { + const [confirmState, setConfirmState] = useState>({ + isOpen: false, + message: '', + resolve: null, + }); + const [promptState, setPromptState] = useState< + ModalState + >({ isOpen: false, message: '', resolve: null }); + const [alertState, setAlertState] = useState>({ + isOpen: false, + message: '', + resolve: null, + }); + const inputRef = React.useRef(null); + + const showConfirm = (message: string): Promise => { + return new Promise((resolve) => { + setConfirmState({ isOpen: true, message, resolve }); + }); + }; + + const showPrompt = ( + message: string, + defaultValue?: string + ): Promise => { + return new Promise((resolve) => { + setPromptState({ isOpen: true, message, defaultValue, resolve }); + }); + }; + + const showAlert = (message: string): Promise => { + return new Promise((resolve) => { + setAlertState({ isOpen: true, message, resolve }); + }); + }; + + const handleConfirm = (result: boolean) => { + confirmState.resolve?.(result); + setConfirmState({ isOpen: false, message: '', resolve: null }); + }; + + const handlePrompt = (result?: string) => { + promptState.resolve?.(result); + setPromptState({ isOpen: false, message: '', resolve: null }); + }; + + const handleAlertClose = () => { + alertState.resolve?.(); + setAlertState({ isOpen: false, message: '', resolve: null }); + }; + + return ( + + {children} + + {/* Confirm Modal */} + {confirmState.isOpen && ( + +
    +

    {confirmState.message}

    +
    + + +
    +
    +
    + )} + + {/* Prompt Modal */} + {promptState.isOpen && ( + +
    +

    {promptState.message}

    + { + if (e.key === 'Enter') { + handlePrompt((e.target as HTMLInputElement).value); + } + }} + /> +
    + + +
    +
    +
    + )} + + {/* Alert Modal */} + {alertState.isOpen && ( + +
    +

    {alertState.message}

    +
    + +
    +
    +
    + )} +
    + ); +} + +export function useModals() { + const context = useContext(ModalContext); + if (!context) throw new Error('useModals must be used within ModalProvider'); + return context; +} diff --git a/examples/server/webui/src/components/SettingDialog.tsx b/examples/server/webui/src/components/SettingDialog.tsx index cd091a55..004b51ab 100644 --- a/examples/server/webui/src/components/SettingDialog.tsx +++ b/examples/server/webui/src/components/SettingDialog.tsx @@ -3,16 +3,21 @@ import { useAppContext } from '../utils/app.context'; import { CONFIG_DEFAULT, CONFIG_INFO } from '../Config'; import { isDev } from '../Config'; import StorageUtils from '../utils/storage'; +import { useModals } from './ModalProvider'; import { classNames, isBoolean, isNumeric, isString } from '../utils/misc'; import { BeakerIcon, + BookmarkIcon, ChatBubbleOvalLeftEllipsisIcon, Cog6ToothIcon, FunnelIcon, HandRaisedIcon, SquaresPlusIcon, + TrashIcon, } from '@heroicons/react/24/outline'; import { OpenInNewTab } from '../utils/common'; +import { SettingsPreset } from '../utils/types'; +import toast from 'react-hot-toast' type SettKey = keyof typeof CONFIG_DEFAULT; @@ -74,7 +79,155 @@ interface SettingSection { const ICON_CLASSNAME = 'w-4 h-4 mr-1 inline'; -const SETTING_SECTIONS: SettingSection[] = [ +// Presets Component +function PresetsManager({ + currentConfig, + onLoadPreset, +}: { + currentConfig: typeof CONFIG_DEFAULT; + onLoadPreset: (config: typeof CONFIG_DEFAULT) => void; +}) { + const [presets, setPresets] = useState(() => + StorageUtils.getPresets() + ); + const [presetName, setPresetName] = useState(''); + const [selectedPresetId, setSelectedPresetId] = useState(null); + const { showConfirm, showAlert } = useModals(); + + const handleSavePreset = async () => { + if (!presetName.trim()) { + await showAlert('Please enter a preset name'); + return; + } + + // Check if preset name already exists + const existingPreset = presets.find((p) => p.name === presetName.trim()); + if (existingPreset) { + if ( + await showConfirm( + `Preset "${presetName}" already exists. Do you want to overwrite it?` + ) + ) { + StorageUtils.updatePreset(existingPreset.id, currentConfig); + setPresets(StorageUtils.getPresets()); + setPresetName(''); + await showAlert('Preset updated successfully'); + } + } else { + const newPreset = StorageUtils.savePreset( + presetName.trim(), + currentConfig + ); + setPresets([...presets, newPreset]); + setPresetName(''); + await showAlert('Preset saved successfully'); + } + }; + + const handleLoadPreset = async (preset: SettingsPreset) => { + if ( + await showConfirm( + `Load preset "${preset.name}"? Current settings will be replaced.` + ) + ) { + onLoadPreset(preset.config as typeof CONFIG_DEFAULT); + setSelectedPresetId(preset.id); + } + }; + + const handleDeletePreset = async (preset: SettingsPreset) => { + if (await showConfirm(`Delete preset "${preset.name}"?`)) { + StorageUtils.deletePreset(preset.id); + setPresets(presets.filter((p) => p.id !== preset.id)); + if (selectedPresetId === preset.id) { + setSelectedPresetId(null); + } + } + }; + + return ( +
    + {/* Save current settings as preset */} +
    + +
    + setPresetName(e.target.value)} + onKeyPress={(e) => { + if (e.key === 'Enter') { + handleSavePreset(); + } + }} + /> + +
    +
    + + {/* List of saved presets */} +
    + + {presets.length === 0 ? ( +
    + No presets saved yet +
    + ) : ( +
    + {presets.map((preset) => ( +
    +
    +
    +

    {preset.name}

    +

    + Created: {new Date(preset.createdAt).toLocaleString()} +

    +
    +
    + + +
    +
    +
    + ))} +
    + )} +
    +
    + ); +} + +const SETTING_SECTIONS = ( + localConfig: typeof CONFIG_DEFAULT, + setLocalConfig: (config: typeof CONFIG_DEFAULT) => void +): SettingSection[] => [ { title: ( <> @@ -187,6 +340,85 @@ const SETTING_SECTIONS: SettingSection[] = [ ); }, }, + { + type: SettingInputType.CUSTOM, + key: 'custom', // dummy key, won't be used + component: () => { + const exportDB = async () => { + const blob = await StorageUtils.exportDB(); + const a = document.createElement('a'); + document.body.appendChild(a); + a.href = URL.createObjectURL(blob); + document.body.appendChild(a); + a.download = `llamawebui_dump.json`; + a.click(); + document.body.removeChild(a); + }; + return ( + + ); + }, + }, + { + type: SettingInputType.CUSTOM, + key: 'custom', // dummy key, won't be used + component: () => { + const importDB = async (e: React.ChangeEvent) => { + console.log(e); + if (!e.target.files) { + toast.error('Target.files cant be null'); + throw new Error('e.target.files cant be null'); + } + if (e.target.files.length != 1) + { + toast.error( + 'Number of selected files for DB import must be 1 but was ' + + e.target.files.length + + '.'); + throw new Error( + 'Number of selected files for DB import must be 1 but was ' + + e.target.files.length + + '.' + ); + } + const file = e.target.files[0]; + try { + if (!file) throw new Error('No DB found to import.'); + console.log('Importing DB ' + file.name); + await StorageUtils.importDB(file); + toast.success('Import complete') + window.location.reload(); + } catch (error) { + console.error('' + error); + toast.error('' + error); + } + }; + return ( +
    + + +
    + ); + }, + }, + { type: SettingInputType.CHECKBOX, label: 'Show tokens per second', @@ -257,6 +489,26 @@ const SETTING_SECTIONS: SettingSection[] = [ }, ], }, + { + title: ( + <> + + Presets + + ), + fields: [ + { + type: SettingInputType.CUSTOM, + key: 'custom', // dummy key for presets + component: () => ( + + ), + }, + ], + }, ]; export default function SettingDialog({ @@ -274,6 +526,12 @@ export default function SettingDialog({ JSON.parse(JSON.stringify(config)) ); + // Generate sections with access to local state + const SETTING_SECTIONS_GENERATED = SETTING_SECTIONS( + localConfig, + setLocalConfig + ); + const resetConfig = () => { if (window.confirm('Are you sure you want to reset all settings?')) { setLocalConfig(CONFIG_DEFAULT); @@ -332,7 +590,7 @@ export default function SettingDialog({
    {/* Left panel, showing sections - Desktop version */}
    - {SETTING_SECTIONS.map((section, idx) => ( + {SETTING_SECTIONS_GENERATED.map((section, idx) => (
    - {SETTING_SECTIONS[sectionIdx].title} + {SETTING_SECTIONS_GENERATED[sectionIdx].title}
      - {SETTING_SECTIONS.map((section, idx) => ( + {SETTING_SECTIONS_GENERATED.map((section, idx) => (
      - {SETTING_SECTIONS[sectionIdx].fields.map((field, idx) => { + {SETTING_SECTIONS_GENERATED[sectionIdx].fields.map((field, idx) => { const key = `${sectionIdx}-${idx}`; if (field.type === SettingInputType.SHORT_INPUT) { return ( diff --git a/examples/server/webui/src/components/Sidebar.tsx b/examples/server/webui/src/components/Sidebar.tsx index 34727c62..4b0adbae 100644 --- a/examples/server/webui/src/components/Sidebar.tsx +++ b/examples/server/webui/src/components/Sidebar.tsx @@ -1,13 +1,36 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useMemo, useState } from 'react'; import { classNames } from '../utils/misc'; import { Conversation } from '../utils/types'; import StorageUtils from '../utils/storage'; import { useNavigate, useParams } from 'react-router'; +import { + ArrowUpTrayIcon, + ArrowDownTrayIcon, + EllipsisVerticalIcon, + PencilIcon, + PencilSquareIcon, + TrashIcon, + XMarkIcon, +} from '@heroicons/react/24/outline'; +import { BtnWithTooltips } from '../utils/common'; +import { useAppContext } from '../utils/app.context'; +import toast from 'react-hot-toast'; +import { useModals } from './ModalProvider'; + // at the top of your file, alongside ConversationExport: + async function importConversation() { + const importedConv = await StorageUtils.importConversationFromFile(); + if (importedConv) { + console.log('Successfully imported:', importedConv.name); + // Refresh UI or navigate to conversation + } + }; export default function Sidebar() { const params = useParams(); const navigate = useNavigate(); + const { isGenerating, viewingChat } = useAppContext(); + const [conversations, setConversations] = useState([]); const [currConv, setCurrConv] = useState(null); @@ -25,68 +48,176 @@ export default function Sidebar() { StorageUtils.offConversationChanged(handleConversationChange); }; }, []); + const { showConfirm, showPrompt } = useModals(); + + const groupedConv = useMemo( + () => groupConversationsByDate(conversations), + [conversations] + ); + + return ( <> -
      +
      + + + Skip to main content + +
      -

      Conversations

      +

      + Conversations +

      {/* close sidebar button */} -
      - {/* list of conversations */} -
      navigate('/')} + aria-label="New conversation" > - + New conversation -
      - {conversations.map((conv) => ( -
      navigate(`/chat/${conv.id}`)} - dir="auto" - > - {conv.name} + + New conversation + + + {/* list of conversations */} + {groupedConv.map((group, i) => ( +
      + {/* group name (by date) */} + {group.title ? ( + // we use btn class here to make sure that the padding/margin are aligned with the other items + + {group.title} + + ) : ( +
      + )} + + {group.conversations.map((conv) => ( + { + navigate(`/chat/${conv.id}`); + }} + onDelete={async () => { + if (isGenerating(conv.id)) { + toast.error( + 'Cannot delete conversation while generating' + ); + return; + } + if ( + await showConfirm( + 'Are you sure to delete this conversation?' + ) + ) { + toast.success('Conversation deleted'); + StorageUtils.remove(conv.id); + navigate('/'); + } + }} + + onDownload={() => { + if (isGenerating(conv.id)) { + toast.error( + 'Cannot download conversation while generating' + ); + return; + } + // Get the current system message from config + const systemMessage = StorageUtils.getConfig().systemMessage; + + // Clone the viewingChat object to avoid modifying the original + const exportData = { + conv: { ...viewingChat?.conv }, + messages: viewingChat?.messages.map(msg => ({ ...msg })) + }; + + // Find the root message and update its content + const rootMessage = exportData.messages?.find(m => m.type === 'root'); + if (rootMessage) { + rootMessage.content = systemMessage; + } + + + const conversationJson = JSON.stringify(exportData, null, 2); + // const conversationJson = JSON.stringify(conv, null, 2); + const blob = new Blob([conversationJson], { + type: 'application/json', + }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `conversation_${conv.id}.json`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }} + onRename={async () => { + if (isGenerating(conv.id)) { + toast.error( + 'Cannot rename conversation while generating' + ); + return; + } + const newName = await showPrompt( + 'Enter new name for the conversation', + conv.name + ); + if (newName && newName.trim().length > 0) { + StorageUtils.updateConversationName(conv.id, newName); + } + }} + /> + ))}
      ))} -
      +
      Conversations are saved to browser's IndexedDB
      @@ -94,3 +225,182 @@ export default function Sidebar() { ); } + +function ConversationItem({ + conv, + isCurrConv, + onSelect, + onDelete, + onDownload, + onRename, +}: { + conv: Conversation; + isCurrConv: boolean; + onSelect: () => void; + onDelete: () => void; + onDownload: () => void; + onRename: () => void; +}) { + return ( +
      + +
      + + {/* dropdown menu */} + +
      +
      + ); +} + +// WARN: vibe code below + +export interface GroupedConversations { + title?: string; + conversations: Conversation[]; +} + +// TODO @ngxson : add test for this function +// Group conversations by date +// - "Previous 7 Days" +// - "Previous 30 Days" +// - "Month Year" (e.g., "April 2023") +export function groupConversationsByDate( + conversations: Conversation[] +): GroupedConversations[] { + const now = new Date(); + const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // Start of today + + const sevenDaysAgo = new Date(today); + sevenDaysAgo.setDate(today.getDate() - 7); + + const thirtyDaysAgo = new Date(today); + thirtyDaysAgo.setDate(today.getDate() - 30); + + const groups: { [key: string]: Conversation[] } = { + Today: [], + 'Previous 7 Days': [], + 'Previous 30 Days': [], + }; + const monthlyGroups: { [key: string]: Conversation[] } = {}; // Key format: "Month Year" e.g., "April 2023" + + // Sort conversations by lastModified date in descending order (newest first) + // This helps when adding to groups, but the final output order of groups is fixed. + const sortedConversations = [...conversations].sort( + (a, b) => b.lastModified - a.lastModified + ); + + for (const conv of sortedConversations) { + const convDate = new Date(conv.lastModified); + + if (convDate >= today) { + groups['Today'].push(conv); + } else if (convDate >= sevenDaysAgo) { + groups['Previous 7 Days'].push(conv); + } else if (convDate >= thirtyDaysAgo) { + groups['Previous 30 Days'].push(conv); + } else { + const monthName = convDate.toLocaleString('default', { month: 'long' }); + const year = convDate.getFullYear(); + const monthYearKey = `${monthName} ${year}`; + if (!monthlyGroups[monthYearKey]) { + monthlyGroups[monthYearKey] = []; + } + monthlyGroups[monthYearKey].push(conv); + } + } + + const result: GroupedConversations[] = []; + + if (groups['Today'].length > 0) { + result.push({ + title: undefined, // no title for Today + conversations: groups['Today'], + }); + } + + if (groups['Previous 7 Days'].length > 0) { + result.push({ + title: 'Previous 7 Days', + conversations: groups['Previous 7 Days'], + }); + } + + if (groups['Previous 30 Days'].length > 0) { + result.push({ + title: 'Previous 30 Days', + conversations: groups['Previous 30 Days'], + }); + } + + // Sort monthly groups by date (most recent month first) + const sortedMonthKeys = Object.keys(monthlyGroups).sort((a, b) => { + const dateA = new Date(a); // "Month Year" can be parsed by Date constructor + const dateB = new Date(b); + return dateB.getTime() - dateA.getTime(); + }); + + for (const monthKey of sortedMonthKeys) { + if (monthlyGroups[monthKey].length > 0) { + result.push({ title: monthKey, conversations: monthlyGroups[monthKey] }); + } + } + + return result; +} -- cgit v1.2.3