feat(playground): improve Playground chat experience and Markdown rendering (#5217)

* refactor(playground): streamline chat request state

- extract conversation actions from the page component to keep message flow logic reusable.
- unify streaming and non-streaming generation state, including abort support for non-stream requests.
- simplify message rendering and payload construction while localizing Playground prompts.

* fix(playground): validate persisted chat state

- wrap saved Playground state with a storage version while still reading legacy values.

- validate config, parameter toggles, and messages before restoring them from localStorage.

- cap stored chat history to the latest messages to avoid oversized or stale state.

* refactor(playground): centralize message content access

- route chat rendering, copy actions, and error display through shared message helpers.

- reuse the current-version update helper for non-streaming assistant responses.

- keep message version details behind utility functions to reduce future model churn.

* refactor(playground): split storage schemas

- move Playground storage validation schemas into a dedicated module.

- keep storage read and write logic focused on migration, trimming, and persistence.

- preserve the existing storage envelope and validation behavior.

* refactor(playground): extract options loading hook

- move model and group queries into a dedicated hook so the page component stays focused on layout wiring.
- preserve existing fallback selection and error toast behavior while reusing the hook through the playground barrel export.

* refactor(playground): extract prompt suggestions

- move static prompt suggestion rendering into a focused component so the input stays centered on compose controls.
- preserve translated suggestion submission behavior while isolating icon metadata from the input form.

* refactor(playground): extract input tools

- move attachment and search controls into a dedicated component so the prompt input stays focused on compose state.
- keep existing development toast behavior and disabled handling while centralizing tool metadata.

* refactor(playground): extract input controls

- move model, group, send, and stop controls into a focused component so the input only manages compose state.
- preserve existing disabled states and generation button behavior while isolating control rendering.

* refactor(playground): extract message content display

- move sources, reasoning, loading, error, and response rendering into a dedicated message content component.
- keep the chat list focused on message iteration, edit state, and action wiring without changing display behavior.

* refactor(playground): extract message editor

- move inline message editing controls into a dedicated editor component so the chat list stays focused on rendering flow.
- preserve save, save-and-submit, cancel, and disabled-state behavior for edited messages.

* refactor(playground): extract stream error parsing

- move SSE error payload parsing into a reusable stream utility so the request hook stays focused on lifecycle handling.
- preserve existing error message, error code, and fallback behavior for raw or empty stream errors.

* refactor(playground): extract request error parsing

- move non-stream request error extraction into a shared utility so the chat handler stays focused on request flow.
- preserve the existing response message, error code, and fallback priority for failed chat completions.

* refactor(playground): extract streaming chunk updates

- move reasoning and content chunk application into a message utility so the chat handler only wires stream events.
- preserve error-state skipping, reasoning accumulation, and content streaming behavior for assistant messages.

* refactor(playground): extract message reasoning parser

- move think tag parsing into a dedicated playground message utility.
- export the parser through the shared playground lib barrel for consistent imports.

* refactor(playground): extract message streaming utilities

- move stream chunk application and message finalization into a dedicated utility.
- keep stored message sanitization with the streaming lifecycle helpers.

* refactor(playground): extract message update utilities

- move assistant message update helpers into a focused playground utility.
- keep error-state message updates separate from core message construction helpers.

* refactor(playground): extract completion choice handling

- move non-streaming choice application into the message streaming utilities.
- keep the chat handler focused on request orchestration and message updates.

* refactor(playground): centralize assistant completion state

- add a helper for finalizing assistant messages with complete status.
- reuse the helper in stream completion and stop-generation paths.

* refactor(playground): extract stream message parsing

- move SSE delta parsing into a shared stream utility.
- keep the stream request hook focused on lifecycle handling and update dispatch.

* refactor(playground): extract stream ready state checks

- move SSE ready-state status handling into stream utilities.
- keep weak source status typing outside the stream request hook.

* refactor(playground): extract conversation message helpers

- move send, regenerate, and edit message list construction into focused utilities.
- keep the conversation hook focused on edit state and update dispatch.

* refactor(playground): extract state initialization helpers

- move playground initial state loading into focused utility helpers.
- centralize message state updater resolution outside the React state hook.

* refactor(playground): extract option fallback helpers

- move model and group fallback selection into focused playground utilities.
- keep the options hook focused on query results, toasts, and config updates.

* refactor(playground): extract message action helpers

- move message action state derivation into focused utilities.

- keep the action component focused on guarded handlers and rendering.

* refactor(playground): extract input control state

- move submit, stop, and selector state derivation into a pure helper.

- keep input controls focused on rendering model selectors and action buttons.

* refactor(playground): extract message content state

- move source, reasoning, loader, and body visibility checks into a pure helper.

- use a discriminated state shape so rendered reasoning content stays type-safe.

* refactor(playground): extract message editor state

- move save eligibility and submit visibility checks into a pure helper.

- keep the editor component focused on textarea and button rendering.

* refactor(playground): extract message error state

- move error kind, fallback content, and admin visibility checks into a pure helper.

- centralize the model pricing settings path used by the error action.

* refactor(playground): extract chat render state

- move editing content lookup and per-message render flags into conversation helpers.

- keep the chat component focused on mapping messages to editor and content views.

* refactor(playground): extract suggestion display state

- move suggestion class selection into a pure helper.

- keep the suggestions component focused on translation and rendering.

* refactor(playground): extract assistant message state checks

- move final and pending assistant status checks into streaming utilities.

- keep the chat handler focused on request lifecycle updates.

* refactor(playground): extract input tool state

- move attachment action metadata and development notices into input tool utilities.

- keep the input tools component focused on menu and button rendering.

* refactor(playground): extract stream protocol checks

- move SSE done-message and closed-ready-state checks into stream utilities.

- keep the stream request hook focused on event handling flow.

* refactor(playground): extract message removal helper

- move delete-message filtering into conversation message utilities.

- keep the conversation hook focused on action orchestration.

* refactor(playground): extract option error messages

- move option load error message selection into playground option utilities
- keep the options hook focused on query effects and fallback updates

* refactor(playground): extract input submit text helper

- move prompt submit text validation into input control utilities
- let the input component submit only when a concrete text value is available

* refactor(playground): centralize error message checks

- add a shared helper for identifying error messages
- remove direct status string checks from message content rendering

* refactor(playground): extract message content display checks

- move loader and content visibility decisions into local helper functions
- keep message content state assembly focused on composing render state

* refactor(playground): replace raw message role checks

- use shared message role constants in conversation edit handling
- avoid raw assistant role literals when validating API messages

* refactor(playground): extract non-stream response handling

- move chat completion response choice handling into message streaming utilities
- keep the chat handler focused on request lifecycle and error routing

* refactor(playground): centralize stream cleanup

- reuse one stream cleanup path for completion, errors, startup failures, and manual stops
- preserve the current-source guard when closing SSE streams

* refactor(playground): extract pending assistant check

- centralize pending assistant message detection in streaming utilities
- reuse the helper when sanitizing stored playground messages

* perf(playground): improve mobile input controls

- split mobile input controls into selector and action rows
- keep the desktop input footer compact while reducing mobile control crowding

* perf(playground): add starter empty state

- show starter prompts in the empty playground chat area
- wire empty-state prompt selection into the existing send flow
- add localized copy for the new empty state

* perf(playground): improve mobile message actions

- collapse mobile message actions into a touch-friendly dropdown menu
- keep the desktop hover action strip unchanged for pointer workflows
- share one action list between desktop buttons and the mobile menu

* perf(playground): add error recovery actions

- show retry, edit, and delete actions inside error message alerts
- route edit recovery to the previous user prompt when available
- keep recovery controls touch-friendly on mobile layouts

* perf(playground): refine message editing experience

- present message edits in a focused bordered editor panel
- add unsaved-change state, reset, and cancel confirmation flows
- improve mobile touch targets and keyboard shortcuts for editing

* perf(playground): improve markdown code blocks

- render fenced markdown code with syntax highlighting, line numbers, and fallback plain text
- add copy, download, and collapse controls for playground AI responses
- tighten code block layout and theme token styles for responsive markdown rendering

* fix(playground): constrain markdown code block height

- collapse long playground code blocks after a short preview instead of waiting for very large snippets
- cap expanded code blocks so long responses scroll inside the code block
- keep generic code block usage unconstrained unless a caller opts in

* feat(playground): add chat history clearing

- add a toolbar action that is enabled only when saved playground messages exist.
- confirm destructive clears before removing browser-stored conversation state.
- add localized strings for the action, dialog, and completion toast.

* perf(playground): improve chat markdown rendering

- refine assistant and user message surfaces so chat content matches the app UI.
- normalize markdown typography, tables, images, lists, blockquotes, and details rendering.
- add indentation cues for collapsible reasoning and source sections.

* style: format code block component

* style: format playground frontend files

* feat(playground): render markdown with stream parser

- replace Streamdown with stream-markdown-parser for project-owned markdown rendering and styling.
- split response rendering into focused block, inline, table, alert, details, and footnote modules.
- pass message final state into response parsing so streaming content can be parsed incrementally.

* fix(playground): localize reasoning and chat feedback

- translate reasoning status, message actions, playground errors, and response renderer fallbacks across supported locales.
- keep reasoning duration numeric and tighten the collapsible layout to prevent trigger jitter.
- register dynamic keys so i18n sync keeps runtime labels covered.

* refactor(playground): group files by functional area

- move chat, input, and message components into focused subdirectories to make the UI structure easier to scan.
- split playground helpers into input, message, streaming, storage, options, state, and suggestions modules.
- update barrel exports and imports so existing feature entry points continue to work.

* fix(playground): prevent history replay from freezing page

- defer saved conversation loading so route entry no longer blocks on localStorage parsing and markdown rendering.
- limit initial history rendering and skip expensive markdown parsing for oversized responses.
- normalize corrupted streaming snapshots and cumulative chunks to keep saved playground history bounded.
- add message timing metadata and layout alignment groundwork without introducing live timers.

* feat(playground): allow regenerating from user messages

- show regenerate actions on user messages with saved content.
- truncate following conversation state before starting a fresh assistant response.

* feat(playground): add raw response source view

- add a per-message source toggle for assistant responses.
- render raw response content with the existing code block viewer.
- localize the new source and preview action labels.

* feat(playground): render code with unified editor

- replace Shiki HTML rendering with a read-only CodeMirror view for code blocks and raw responses.
- reuse the same CodeMirror frame for message editing so source and edit modes stay visually aligned.
- add lightweight CodeMirror dependencies while keeping language support scoped to Markdown.

* perf(playground): streamline chat input controls

- combine model and group selection into one compact picker for faster context switching.
- switch playground action buttons to icon-first controls with tooltips to reduce toolbar width.
- refresh input footer styling and submit states so active and destructive actions are clearer.
- bump dompurify lockfile entry to keep the frontend dependency current.

* fix(playground): filter models by selected group

- query user models by the selected playground group instead of reusing the cross-group model union.
- clear unavailable model selections and block sending when the active group has no models.
- align model selector and error action controls with the existing playground interaction style.

* perf(playground): remove input suggestion chips

- remove the prompt suggestion row below the playground input to reduce visual noise.
- delete the now-unused suggestion component and display helper.

* perf(playground): stabilize reasoning trigger layout

- use fixed icon slots around the reasoning label so the left content stays still when toggling.
- limit the open state animation to the chevron rotation for a smoother collapse interaction.

* perf(playground): smooth reasoning expansion

- use the collapsible panel height animation for vertical reasoning reveals.
- sync inner content opacity and position with the panel state.
This commit is contained in:
QuentinHsu
2026-06-27 17:23:25 +08:00
committed by GitHub
parent df44a75d53
commit 966af88ec3
80 changed files with 6695 additions and 1801 deletions
+8 -3
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { api } from '@/lib/api'
import { API_ENDPOINTS } from './constants'
import type {
ChatCompletionRequest,
@@ -29,9 +30,11 @@ import type {
* Send chat completion request (non-streaming)
*/
export async function sendChatCompletion(
payload: ChatCompletionRequest
payload: ChatCompletionRequest,
signal?: AbortSignal
): Promise<ChatCompletionResponse> {
const res = await api.post(API_ENDPOINTS.CHAT_COMPLETIONS, payload, {
signal,
skipErrorHandler: true,
} as Record<string, unknown>)
return res.data
@@ -40,8 +43,10 @@ export async function sendChatCompletion(
/**
* Get user available models
*/
export async function getUserModels(): Promise<ModelOption[]> {
const res = await api.get(API_ENDPOINTS.USER_MODELS)
export async function getUserModels(group: string): Promise<ModelOption[]> {
const res = await api.get(API_ENDPOINTS.USER_MODELS, {
params: { group },
})
const { data } = res
if (!data.success || !Array.isArray(data.data)) {
@@ -0,0 +1,223 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
Conversation,
ConversationContent,
ConversationScrollButton,
} from '@/components/ai-elements/conversation'
import { Loader } from '@/components/ai-elements/loader'
import { Message } from '@/components/ai-elements/message'
import {
getChatMessageRenderState,
getEditingMessageContent,
getMessageAlignment,
getPreviousUserMessage,
isErrorMessage,
} from '../../lib'
import type {
Message as MessageType,
PlaygroundMessageLayoutMode,
} from '../../types'
import { MessageActions } from '../message/message-actions'
import { MessageErrorActions } from '../message/message-error-actions'
import { PlaygroundMessageContent } from '../message/playground-message-content'
import { PlaygroundMessageEditor } from '../message/playground-message-editor'
import { PlaygroundEmptyState } from './playground-empty-state'
const MAX_RENDERED_HISTORY_MESSAGES = 24
interface PlaygroundChatProps {
messages: MessageType[]
onCopyMessage?: (message: MessageType) => void
onRegenerateMessage?: (message: MessageType) => void
onEditMessage?: (message: MessageType) => void
onDeleteMessage?: (message: MessageType) => void
onSelectPrompt?: (prompt: string) => void
isGenerating?: boolean
isLoadingMessages?: boolean
editingKey?: string | null
onSaveEdit?: (newContent: string) => void
onCancelEdit?: (open: boolean) => void
onSaveEditAndSubmit?: (newContent: string) => void
messageLayoutMode?: PlaygroundMessageLayoutMode
}
export function PlaygroundChat({
messages,
onCopyMessage,
onRegenerateMessage,
onEditMessage,
onDeleteMessage,
onSelectPrompt,
isGenerating = false,
isLoadingMessages = false,
editingKey,
onSaveEdit,
onCancelEdit,
onSaveEditAndSubmit,
messageLayoutMode = 'alternating',
}: PlaygroundChatProps) {
const { t } = useTranslation()
const [editText, setEditText] = useState('')
const [originalText, setOriginalText] = useState('')
const [sourceMessageKeys, setSourceMessageKeys] = useState<
ReadonlySet<string>
>(() => new Set())
const visibleMessageOffset = Math.max(
0,
messages.length - MAX_RENDERED_HISTORY_MESSAGES
)
const visibleMessages = messages.slice(visibleMessageOffset)
function handleToggleMessageSource(message: MessageType): void {
setSourceMessageKeys((currentKeys) => {
const nextKeys = new Set(currentKeys)
if (nextKeys.has(message.key)) {
nextKeys.delete(message.key)
} else {
nextKeys.add(message.key)
}
return nextKeys
})
}
useEffect(() => {
if (!editingKey) return
const content = getEditingMessageContent(messages, editingKey)
// eslint-disable-next-line react-hooks/set-state-in-effect
setEditText(content)
setOriginalText(content)
}, [editingKey, messages])
let chatContent = visibleMessages.map((message, visibleMessageIndex) => {
const messageIndex = visibleMessageOffset + visibleMessageIndex
const { alwaysShowActions, content, isEditing } = getChatMessageRenderState(
messages,
message,
messageIndex,
editingKey
)
const isError = isErrorMessage(message)
const previousUserMessage = isError
? getPreviousUserMessage(messages, messageIndex)
: null
const alignment = getMessageAlignment(message, messageLayoutMode)
const isSourceVisible = sourceMessageKeys.has(message.key)
return (
<Message
className='group flex-row-reverse py-2.5'
from={message.from}
key={message.key}
>
<div className='w-full min-w-0 flex-1 basis-full'>
{isEditing ? (
<PlaygroundMessageEditor
editText={editText}
message={message}
onCancelEdit={onCancelEdit}
onEditTextChange={setEditText}
onSaveEdit={onSaveEdit}
onSaveEditAndSubmit={onSaveEditAndSubmit}
originalText={originalText}
/>
) : (
<PlaygroundMessageContent
alignment={alignment}
actions={
<MessageActions
message={message}
onCopy={onCopyMessage}
onRegenerate={onRegenerateMessage}
onToggleSource={handleToggleMessageSource}
onEdit={onEditMessage}
onDelete={onDeleteMessage}
isSourceVisible={isSourceVisible}
isGenerating={isGenerating}
alwaysVisible={alwaysShowActions}
className='mt-1.5'
/>
}
isSourceVisible={isSourceVisible}
message={message}
errorActions={
isError ? (
<MessageErrorActions
disabled={isGenerating}
onRetry={
onRegenerateMessage
? () => onRegenerateMessage(message)
: undefined
}
onEditPrompt={
onEditMessage && previousUserMessage
? () => onEditMessage(previousUserMessage)
: undefined
}
onDelete={
onDeleteMessage
? () => onDeleteMessage(message)
: undefined
}
/>
) : undefined
}
versionContent={content}
/>
)}
</div>
</Message>
)
})
if (visibleMessages.length === 0 && onSelectPrompt) {
chatContent = [
<PlaygroundEmptyState key='empty' onSelectPrompt={onSelectPrompt} />,
]
}
if (isLoadingMessages) {
chatContent = [
<div
className='text-muted-foreground flex min-h-[min(520px,calc(100svh-18rem))] items-center justify-center gap-2 text-sm'
key='loading'
>
<Loader />
<span>{t('Loading conversation...')}</span>
</div>,
]
}
return (
<Conversation>
{/* Remove outer padding; apply padding to inner centered container to align with input */}
<ConversationContent className='p-0'>
<div className='mx-auto w-full max-w-4xl px-4 py-4'>{chatContent}</div>
</ConversationContent>
<ConversationScrollButton />
</Conversation>
)
}
@@ -0,0 +1,84 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
BarChartIcon,
CodeSquareIcon,
GraduationCapIcon,
MessageSquarePlusIcon,
NotepadTextIcon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
type PlaygroundEmptyStateProps = {
onSelectPrompt: (prompt: string) => void
}
const starterPrompts = [
{ icon: BarChartIcon, text: 'Analyze data' },
{ icon: NotepadTextIcon, text: 'Summarize text' },
{ icon: CodeSquareIcon, text: 'Code' },
{ icon: GraduationCapIcon, text: 'Get advice' },
]
export function PlaygroundEmptyState({
onSelectPrompt,
}: PlaygroundEmptyStateProps) {
const { t } = useTranslation()
return (
<div className='flex min-h-[min(520px,calc(100svh-18rem))] items-center justify-center px-1 py-8 md:py-12'>
<div className='grid w-full max-w-2xl gap-5 text-center'>
<div className='bg-muted/50 text-muted-foreground mx-auto flex size-11 items-center justify-center rounded-xl border'>
<MessageSquarePlusIcon className='size-5' aria-hidden='true' />
</div>
<div className='grid gap-2'>
<h2 className='text-xl font-semibold tracking-tight text-balance md:text-2xl'>
{t('Start a playground chat')}
</h2>
<p className='text-muted-foreground mx-auto max-w-lg text-sm leading-6 text-balance'>
{t(
'Test a model with a starter prompt, or write your own request below.'
)}
</p>
</div>
<div className='grid gap-2 sm:grid-cols-2'>
{starterPrompts.map(({ icon: Icon, text }) => {
const prompt = t(text)
return (
<Button
className='h-auto min-h-11 justify-start gap-2 px-3 py-2.5 text-left whitespace-normal'
key={text}
onClick={() => onSelectPrompt(prompt)}
variant='outline'
>
<Icon className='text-muted-foreground size-4' />
<span>{prompt}</span>
</Button>
)
})}
</div>
</div>
</div>
)
}
@@ -0,0 +1,125 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { SendIcon, SquareIcon } from 'lucide-react'
import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { PromptInputButton } from '@/components/ai-elements/prompt-input'
import { ModelGroupSelector } from '@/components/model-group-selector'
import { getInputControlState } from '../../lib'
import type { GroupOption, ModelOption } from '../../types'
type PlaygroundInputControlsProps = {
disabled?: boolean
groups: GroupOption[]
groupValue: string
isGenerating?: boolean
isModelLoading?: boolean
models: ModelOption[]
modelValue: string
onGroupChange: (value: string) => void
onModelChange: (value: string) => void
onStop?: () => void
text: string
tools: ReactNode
}
export function PlaygroundInputControls({
disabled,
groups,
groupValue,
isGenerating,
isModelLoading = false,
models,
modelValue,
onGroupChange,
onModelChange,
onStop,
text,
tools,
}: PlaygroundInputControlsProps) {
const { t } = useTranslation()
const { canSubmit, isSelectorDisabled, shouldShowStop } =
getInputControlState({
disabled,
groups,
hasStopHandler: Boolean(onStop),
isGenerating,
isModelLoading,
models,
text,
})
const renderSelector = () => (
<ModelGroupSelector
selectedModel={modelValue}
models={models}
onModelChange={onModelChange}
selectedGroup={groupValue}
groups={groups}
onGroupChange={onGroupChange}
disabled={isSelectorDisabled}
/>
)
const renderSubmitButton = () =>
shouldShowStop ? (
<PromptInputButton
className='border-destructive/25 bg-destructive/10 text-destructive hover:bg-destructive/15 font-medium'
onClick={onStop}
variant='secondary'
>
<SquareIcon className='fill-current' size={16} />
<span className='hidden sm:inline'>{t('Stop')}</span>
<span className='sr-only sm:hidden'>{t('Stop')}</span>
</PromptInputButton>
) : (
<PromptInputButton
className='bg-primary text-primary-foreground hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground h-8 px-3 font-medium shadow-sm'
disabled={!canSubmit}
type='submit'
variant='default'
>
<SendIcon size={16} />
<span className='hidden sm:inline'>{t('Send')}</span>
<span className='sr-only sm:hidden'>{t('Send')}</span>
</PromptInputButton>
)
return (
<div className='flex w-full flex-col gap-2.5 md:flex-row md:items-center md:justify-between'>
<div className='flex min-w-0 items-center justify-end md:hidden'>
{renderSelector()}
</div>
<div className='flex items-center justify-between gap-2 md:justify-start'>
{tools}
<div className='flex items-center gap-1.5 md:hidden'>
{renderSubmitButton()}
</div>
</div>
<div className='hidden min-w-0 items-center gap-2 md:flex'>
{renderSelector()}
{renderSubmitButton()}
</div>
</div>
)
}
@@ -0,0 +1,169 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { GlobeIcon, PaperclipIcon, Trash2Icon } from 'lucide-react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import {
PromptInputButton,
PromptInputTools,
} from '@/components/ai-elements/prompt-input'
import { ConfirmDialog } from '@/components/confirm-dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip'
import {
ATTACHMENT_ACTIONS,
getAttachmentActionNotice,
getSearchActionNotice,
} from '../../lib'
type PlaygroundInputToolsProps = {
disabled?: boolean
hasMessages?: boolean
onClearMessages?: () => void
}
export function PlaygroundInputTools({
disabled,
hasMessages = false,
onClearMessages,
}: PlaygroundInputToolsProps) {
const { t } = useTranslation()
const [clearConfirmOpen, setClearConfirmOpen] = useState(false)
const handleFileAction = (action: string) => {
const notice = getAttachmentActionNotice(action)
toast.info(t(notice.title), {
description: notice.description,
})
}
const handleSearchAction = () => {
const notice = getSearchActionNotice()
toast.info(t(notice.title))
}
const handleClearMessages = () => {
onClearMessages?.()
setClearConfirmOpen(false)
toast.success(t('Conversation cleared'))
}
return (
<>
<PromptInputTools className='bg-background/70 border-border/60 rounded-lg border p-1 shadow-xs'>
<Tooltip>
<DropdownMenu>
<TooltipTrigger
render={
<DropdownMenuTrigger
render={
<PromptInputButton
aria-label={t('Attach')}
className='text-muted-foreground hover:text-foreground hover:bg-muted/70 font-medium'
disabled={disabled}
variant='ghost'
/>
}
>
<PaperclipIcon size={16} />
</DropdownMenuTrigger>
}
/>
<TooltipContent>
<p>{t('Attach')}</p>
</TooltipContent>
<DropdownMenuContent align='start'>
{ATTACHMENT_ACTIONS.map(({ action, icon: Icon, label }) => (
<DropdownMenuItem
key={action}
onClick={() => handleFileAction(action)}
>
<Icon className='mr-2' size={16} />
{t(label)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<PromptInputButton
aria-label={t('Search')}
className='text-muted-foreground hover:text-foreground hover:bg-muted/70 font-medium'
disabled={disabled}
onClick={handleSearchAction}
variant='ghost'
>
<GlobeIcon size={16} />
</PromptInputButton>
}
/>
<TooltipContent>
<p>{t('Search')}</p>
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<PromptInputButton
aria-label={t('Clear chat history')}
className='text-muted-foreground hover:text-destructive hover:bg-destructive/10 font-medium'
disabled={disabled || !hasMessages || !onClearMessages}
onClick={() => setClearConfirmOpen(true)}
variant='ghost'
>
<Trash2Icon size={16} />
</PromptInputButton>
}
/>
<TooltipContent>
<p>{t('Clear chat history')}</p>
</TooltipContent>
</Tooltip>
</PromptInputTools>
<ConfirmDialog
destructive
desc={t(
'All playground messages saved in this browser will be removed. This cannot be undone.'
)}
confirmText={t('Clear')}
handleConfirm={handleClearMessages}
open={clearConfirmOpen}
onOpenChange={setClearConfirmOpen}
title={t('Clear chat history?')}
/>
</>
)
}
@@ -0,0 +1,120 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
PromptInput,
PromptInputFooter,
PromptInputTextarea,
type PromptInputMessage,
} from '@/components/ai-elements/prompt-input'
import { getSubmittableInputText } from '../../lib'
import type { ModelOption, GroupOption } from '../../types'
import { PlaygroundInputControls } from './playground-input-controls'
import { PlaygroundInputTools } from './playground-input-tools'
interface PlaygroundInputProps {
onSubmit: (text: string) => void
onStop?: () => void
disabled?: boolean
isGenerating?: boolean
models: ModelOption[]
modelValue: string
onModelChange: (value: string) => void
isModelLoading?: boolean
groups: GroupOption[]
groupValue: string
onGroupChange: (value: string) => void
hasMessages?: boolean
onClearMessages?: () => void
}
export function PlaygroundInput({
onSubmit,
onStop,
disabled,
isGenerating,
models,
modelValue,
onModelChange,
isModelLoading = false,
groups,
groupValue,
onGroupChange,
hasMessages = false,
onClearMessages,
}: PlaygroundInputProps) {
const { t } = useTranslation()
const [text, setText] = useState('')
const handleSubmit = (message: PromptInputMessage) => {
const submittableText = getSubmittableInputText(message, disabled)
if (!submittableText) return
onSubmit(submittableText)
setText('')
}
return (
<div className='grid shrink-0 gap-4 px-1 md:pb-4'>
<PromptInput
className='relative'
groupClassName='bg-background/95 dark:bg-background/80 border-border/70 shadow-[0_18px_60px_-32px_rgba(0,0,0,0.65)] ring-1 ring-foreground/5 rounded-xl overflow-hidden transition-all duration-200 focus-within:border-primary/45 focus-within:ring-primary/15 focus-within:shadow-[0_22px_70px_-34px_rgba(0,0,0,0.75)]'
onSubmit={handleSubmit}
>
<PromptInputTextarea
autoComplete='off'
autoCorrect='off'
autoCapitalize='off'
spellCheck={false}
className='min-h-20 px-5 pt-4 pb-3 leading-7 md:min-h-24 md:text-base'
disabled={disabled}
onChange={(event) => setText(event.target.value)}
placeholder={t('Ask anything')}
value={text}
/>
<PromptInputFooter className='border-border/60 bg-muted/20 dark:bg-muted/10 border-t px-3 py-2.5 backdrop-blur'>
<PlaygroundInputControls
disabled={disabled}
groups={groups}
groupValue={groupValue}
isGenerating={isGenerating}
isModelLoading={isModelLoading}
models={models}
modelValue={modelValue}
onGroupChange={onGroupChange}
onModelChange={onModelChange}
onStop={onStop}
text={text}
tools={
<PlaygroundInputTools
disabled={disabled}
hasMessages={hasMessages}
onClearMessages={onClearMessages}
/>
}
/>
</PromptInputFooter>
</PromptInput>
</div>
)
}
@@ -1,128 +0,0 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Copy, Check, RefreshCw, Edit, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'
import { TooltipProvider } from '@/components/ui/tooltip'
import { MESSAGE_ACTION_LABELS } from '../constants'
import { useMessageActionGuard } from '../hooks/use-message-action-guard'
import type { Message } from '../types'
import { MessageActionButton } from './message-action-button'
interface MessageActionsProps {
message: Message
onCopy?: (message: Message) => void
onRegenerate?: (message: Message) => void
onEdit?: (message: Message) => void
onDelete?: (message: Message) => void
isGenerating?: boolean
alwaysVisible?: boolean
className?: string
}
export function MessageActions({
message,
onCopy,
onRegenerate,
onEdit,
onDelete,
isGenerating = false,
alwaysVisible = false,
className = '',
}: MessageActionsProps) {
const { copiedText, copyToClipboard } = useCopyToClipboard()
const { guardAction } = useMessageActionGuard(isGenerating)
const isAssistant = message.from === 'assistant'
const hasContent = message.versions.some((v) => v.content)
const isLoading =
message.status === 'loading' || message.status === 'streaming'
const content = message.versions[0]?.content || ''
const isCopied = copiedText === content
const handleCopy = () => {
if (!content) {
toast.warning(MESSAGE_ACTION_LABELS.NO_CONTENT)
return
}
copyToClipboard(content)
onCopy?.(message)
}
const handleRegenerate = guardAction(() => onRegenerate?.(message))
const handleEdit = guardAction(() => onEdit?.(message))
const handleDelete = guardAction(() => onDelete?.(message))
const visibilityClass = alwaysVisible
? 'opacity-100'
: 'opacity-0 group-hover:opacity-100 max-md:opacity-100'
return (
<TooltipProvider delay={300}>
<div
className={`flex items-center gap-0.5 transition-opacity ${visibilityClass} ${className}`}
>
{/* Copy */}
{hasContent && (
<MessageActionButton
icon={isCopied ? Check : Copy}
label={
isCopied
? MESSAGE_ACTION_LABELS.COPIED
: MESSAGE_ACTION_LABELS.COPY
}
onClick={handleCopy}
className={isCopied ? 'text-green-600' : ''}
/>
)}
{/* Regenerate - only for assistant messages */}
{isAssistant && !isLoading && onRegenerate && (
<MessageActionButton
icon={RefreshCw}
label={MESSAGE_ACTION_LABELS.REGENERATE}
onClick={handleRegenerate}
disabled={isGenerating}
/>
)}
{/* Edit */}
{hasContent && onEdit && (
<MessageActionButton
icon={Edit}
label={MESSAGE_ACTION_LABELS.EDIT}
onClick={handleEdit}
disabled={isGenerating}
/>
)}
{/* Delete */}
{onDelete && (
<MessageActionButton
icon={Trash2}
label={MESSAGE_ACTION_LABELS.DELETE}
onClick={handleDelete}
disabled={isGenerating}
variant='destructive'
/>
)}
</div>
</TooltipProvider>
)
}
@@ -23,7 +23,7 @@ import {
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { MESSAGE_ACTION_BUTTON_STYLES } from '../constants'
import { MESSAGE_ACTION_BUTTON_STYLES } from '../../constants'
interface MessageActionButtonProps {
icon: LucideIcon
@@ -0,0 +1,221 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
Check,
Copy,
Edit,
FileCode2,
MoreHorizontal,
RefreshCw,
Trash2,
type LucideIcon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuShortcut,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { TooltipProvider } from '@/components/ui/tooltip'
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'
import { MESSAGE_ACTION_LABELS } from '../../constants'
import { useMessageActionGuard } from '../../hooks/use-message-action-guard'
import {
getMessageActionState,
getMessageActionsVisibilityClass,
} from '../../lib'
import type { Message } from '../../types'
import { MessageActionButton } from './message-action-button'
interface MessageActionsProps {
message: Message
onCopy?: (message: Message) => void
onRegenerate?: (message: Message) => void
onToggleSource?: (message: Message) => void
onEdit?: (message: Message) => void
onDelete?: (message: Message) => void
isSourceVisible?: boolean
isGenerating?: boolean
alwaysVisible?: boolean
className?: string
}
type MessageActionItem = {
className?: string
disabled?: boolean
icon: LucideIcon
label: string
onClick: () => void
variant?: 'default' | 'destructive'
}
export function MessageActions({
message,
onCopy,
onRegenerate,
onToggleSource,
onEdit,
onDelete,
isSourceVisible = false,
isGenerating = false,
alwaysVisible = false,
className = '',
}: MessageActionsProps) {
const { t } = useTranslation()
const { copiedText, copyToClipboard } = useCopyToClipboard()
const { guardAction } = useMessageActionGuard(isGenerating)
const { content, hasContent, isAssistant, isLoading, isUser } =
getMessageActionState(message)
const isCopied = copiedText === content
const handleCopy = () => {
if (!content) {
toast.warning(t(MESSAGE_ACTION_LABELS.NO_CONTENT))
return
}
copyToClipboard(content)
onCopy?.(message)
}
const handleRegenerate = guardAction(() => onRegenerate?.(message))
const handleToggleSource = () => onToggleSource?.(message)
const handleEdit = guardAction(() => onEdit?.(message))
const handleDelete = guardAction(() => onDelete?.(message))
const visibilityClass = getMessageActionsVisibilityClass(alwaysVisible)
const actions: MessageActionItem[] = []
if (hasContent) {
actions.push({
className: isCopied ? 'text-green-600' : '',
icon: isCopied ? Check : Copy,
label: isCopied
? MESSAGE_ACTION_LABELS.COPIED
: MESSAGE_ACTION_LABELS.COPY,
onClick: handleCopy,
})
}
if (isAssistant && hasContent && !isLoading && onToggleSource) {
actions.push({
icon: FileCode2,
label: isSourceVisible
? MESSAGE_ACTION_LABELS.SHOW_PREVIEW
: MESSAGE_ACTION_LABELS.SHOW_SOURCE,
onClick: handleToggleSource,
})
}
if ((isAssistant || isUser) && hasContent && !isLoading && onRegenerate) {
actions.push({
disabled: isGenerating,
icon: RefreshCw,
label: MESSAGE_ACTION_LABELS.REGENERATE,
onClick: handleRegenerate,
})
}
if (hasContent && onEdit) {
actions.push({
disabled: isGenerating,
icon: Edit,
label: MESSAGE_ACTION_LABELS.EDIT,
onClick: handleEdit,
})
}
if (onDelete) {
actions.push({
disabled: isGenerating,
icon: Trash2,
label: MESSAGE_ACTION_LABELS.DELETE,
onClick: handleDelete,
variant: 'destructive',
})
}
if (actions.length === 0) return null
return (
<>
<TooltipProvider delay={300}>
<div
className={`hidden items-center gap-0.5 transition-opacity md:flex ${visibilityClass} ${className}`}
>
{actions.map((action) => (
<MessageActionButton
className={action.className}
disabled={action.disabled}
icon={action.icon}
key={action.label}
label={t(action.label)}
onClick={action.onClick}
variant={action.variant}
/>
))}
</div>
</TooltipProvider>
<div className={`md:hidden ${className}`}>
<DropdownMenu modal={false}>
<DropdownMenuTrigger
render={
<Button
aria-label={t('Open menu')}
className='data-popup-open:bg-muted text-muted-foreground hover:text-foreground size-11'
size='icon'
variant='ghost'
/>
}
>
<MoreHorizontal className='size-4' />
<span className='sr-only'>{t('Open menu')}</span>
</DropdownMenuTrigger>
<DropdownMenuContent align='end' className='w-44'>
{actions.map((action) => {
const Icon = action.icon
return (
<DropdownMenuItem
className='min-h-11'
disabled={action.disabled}
key={action.label}
onClick={action.onClick}
variant={action.variant}
>
{t(action.label)}
<DropdownMenuShortcut>
<Icon className='size-4' />
</DropdownMenuShortcut>
</DropdownMenuItem>
)
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
</>
)
}
@@ -0,0 +1,74 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Edit, RefreshCw, Trash2 } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { MessageActionButton } from './message-action-button'
type MessageErrorActionsProps = {
disabled?: boolean
onDelete?: () => void
onEditPrompt?: () => void
onRetry?: () => void
}
export function MessageErrorActions({
disabled = false,
onDelete,
onEditPrompt,
onRetry,
}: MessageErrorActionsProps) {
const { t } = useTranslation()
if (!onRetry && !onEditPrompt && !onDelete) {
return null
}
return (
<div className='flex flex-wrap items-center gap-0.5 pt-2'>
{onRetry && (
<MessageActionButton
disabled={disabled}
icon={RefreshCw}
label={t('Retry')}
onClick={onRetry}
/>
)}
{onEditPrompt && (
<MessageActionButton
disabled={disabled}
icon={Edit}
label={t('Edit')}
onClick={onEditPrompt}
/>
)}
{onDelete && (
<MessageActionButton
disabled={disabled}
icon={Trash2}
label={t('Delete')}
onClick={onDelete}
variant='destructive'
/>
)}
</div>
)
}
@@ -1,3 +1,4 @@
import { AlertCircle, AlertTriangle, Settings } from 'lucide-react'
/*
Copyright (C) 2023-2026 QuantumNous
@@ -16,54 +17,67 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { AlertCircle, AlertTriangle, Settings } from 'lucide-react'
import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { useAuthStore } from '@/stores/auth-store'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { MESSAGE_STATUS } from '../constants'
import type { Message } from '../types'
import { useAuthStore } from '@/stores/auth-store'
import {
FALLBACK_ERROR_CONTENT,
getMessageErrorState,
isAdminRole,
MODEL_PRICING_SETTINGS_PATH,
} from '../../lib'
import type { Message } from '../../types'
interface MessageErrorProps {
message: Message
className?: string
actions?: ReactNode
}
/**
* Display error messages using Alert component
* Following ai-elements pattern for error handling
*/
export function MessageError({ message, className = '' }: MessageErrorProps) {
export function MessageError({
message,
className = '',
actions,
}: MessageErrorProps) {
const { t } = useTranslation()
const user = useAuthStore((s) => s.auth.user)
const isAdmin = user?.role != null && user.role >= 10
const errorState = getMessageErrorState(message, isAdminRole(user?.role))
if (message.status !== MESSAGE_STATUS.ERROR) {
if (!errorState) {
return null
}
const errorContent =
message.versions[0]?.content || 'An unknown error occurred'
if (errorState.kind === 'model-price') {
const content =
errorState.content === FALLBACK_ERROR_CONTENT
? t(FALLBACK_ERROR_CONTENT)
: errorState.content
if (message.errorCode === 'model_price_error') {
return (
<Alert variant='default' className={className}>
<AlertTriangle className='text-orange-500' />
<AlertTitle>{t('Model Price Not Configured')}</AlertTitle>
<AlertDescription className='space-y-2'>
<p>{errorContent}</p>
{isAdmin && (
<p>{content}</p>
{errorState.showSettingsLink && (
<Button
variant='outline'
size='sm'
onClick={() =>
window.open('/system-settings/billing/model-pricing', '_blank')
}
onClick={() => window.open(MODEL_PRICING_SETTINGS_PATH, '_blank')}
>
<Settings className='mr-1 h-3.5 w-3.5' />
{t('Go to Settings')}
</Button>
)}
{actions}
</AlertDescription>
</Alert>
)
@@ -73,7 +87,14 @@ export function MessageError({ message, className = '' }: MessageErrorProps) {
<Alert variant='destructive' className={className}>
<AlertCircle />
<AlertTitle>{t('Error')}</AlertTitle>
<AlertDescription>{errorContent}</AlertDescription>
<AlertDescription className='space-y-2'>
<p>
{errorState.content === FALLBACK_ERROR_CONTENT
? t(FALLBACK_ERROR_CONTENT)
: errorState.content}
</p>
{actions}
</AlertDescription>
</Alert>
)
}
@@ -0,0 +1,84 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { TFunction } from 'i18next'
import { useTranslation } from 'react-i18next'
import { cn } from '@/lib/utils'
import type { MessageAlignment } from '../../lib'
import type { Message } from '../../types'
type MessageMetadataProps = {
alignment: MessageAlignment
message: Message
}
function formatMessageTime(timestamp?: number): string | undefined {
if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) {
return undefined
}
return new Intl.DateTimeFormat(undefined, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
}).format(new Date(timestamp))
}
function formatDuration(
durationMs: number | undefined,
t: TFunction
): string | undefined {
if (typeof durationMs !== 'number' || !Number.isFinite(durationMs)) {
return undefined
}
if (durationMs < 1000) {
return t('{{value}}ms', { value: Math.max(1, Math.round(durationMs)) })
}
return t('{{value}}s', { value: (durationMs / 1000).toFixed(2) })
}
export function MessageMetadata(props: MessageMetadataProps) {
const { t } = useTranslation()
const messageTime = formatMessageTime(props.message.createdAt)
const duration = formatDuration(props.message.durationMs, t)
if (!messageTime && !duration) {
return null
}
return (
<div
className={cn(
'text-muted-foreground mt-1 flex min-h-4 items-center gap-1.5 text-[11px] leading-none',
props.alignment === 'right' && 'justify-end'
)}
>
{messageTime && <time>{messageTime}</time>}
{duration && (
<>
{messageTime && <span aria-hidden='true'>·</span>}
<span>{t('Response time: {{duration}}', { duration })}</span>
</>
)}
</div>
)
}
@@ -0,0 +1,167 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import {
CodeBlock,
CodeBlockCopyButton,
} from '@/components/ai-elements/code-block'
import { Loader } from '@/components/ai-elements/loader'
import { MessageContent } from '@/components/ai-elements/message'
import {
Reasoning,
ReasoningContent,
ReasoningTrigger,
} from '@/components/ai-elements/reasoning'
import { Response } from '@/components/ai-elements/response'
import { Shimmer } from '@/components/ai-elements/shimmer'
import {
Source,
Sources,
SourcesContent,
SourcesTrigger,
} from '@/components/ai-elements/sources'
import { cn } from '@/lib/utils'
import { MESSAGE_STATUS } from '../../constants'
import {
getMessageAlignmentClass,
getMessageContentState,
isErrorMessage,
type MessageAlignment,
} from '../../lib'
import { getMessageContentStyles } from '../../lib/message/message-styles'
import type { Message } from '../../types'
import { MessageError } from './message-error'
import { MessageMetadata } from './message-metadata'
type PlaygroundMessageContentProps = {
actions: ReactNode
alignment: MessageAlignment
errorActions?: ReactNode
isSourceVisible?: boolean
message: Message
versionContent: string
}
export function PlaygroundMessageContent({
actions,
alignment,
errorActions,
isSourceVisible = false,
message,
versionContent,
}: PlaygroundMessageContentProps) {
const { t } = useTranslation()
const {
displayContent,
hasReasoning,
hasSources,
reasoningContent,
showLoader,
showMessageContent,
sources,
} = getMessageContentState(message, versionContent)
const isError = isErrorMessage(message)
const isMessageFinal =
message.status !== MESSAGE_STATUS.LOADING &&
message.status !== MESSAGE_STATUS.STREAMING
return (
<div
className={cn(
'flex w-full min-w-0 flex-col',
getMessageAlignmentClass(alignment)
)}
>
{hasSources && (
<Sources>
<SourcesTrigger count={sources.length} />
<SourcesContent>
{sources.map((source) => (
<Source
href={source.href}
key={`${source.href}-${source.title}`}
title={source.title}
/>
))}
</SourcesContent>
</Sources>
)}
{hasReasoning && (
<Reasoning
defaultOpen
duration={message.reasoning?.duration}
isStreaming={message.isReasoningStreaming}
>
<ReasoningTrigger />
<ReasoningContent>{reasoningContent}</ReasoningContent>
</Reasoning>
)}
{showLoader && (
<div className='flex items-center gap-2 py-2'>
<Loader />
<Shimmer className='text-sm' duration={1}>
{t('Responding...')}
</Shimmer>
</div>
)}
{isError && (
<>
<MessageError message={message} className='mb-2' />
<MessageMetadata alignment={alignment} message={message} />
{errorActions}
</>
)}
{!isError && showMessageContent && (
<>
{isSourceVisible ? (
<CodeBlock
code={versionContent}
className='my-0 group-[.is-assistant]:w-full group-[.is-assistant]:max-w-[78ch]'
collapsedLines={24}
defaultCollapsed={false}
language='markdown'
maxExpandedLines={48}
showLineNumbers
showToolbar
title={t('Raw response')}
>
<CodeBlockCopyButton />
</CodeBlock>
) : (
<MessageContent
variant='flat'
className={cn(getMessageContentStyles())}
>
<Response final={isMessageFinal}>{displayContent}</Response>
</MessageContent>
)}
<MessageMetadata alignment={alignment} message={message} />
{actions}
</>
)}
</div>
)
}
@@ -0,0 +1,155 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Check, RotateCcw, Send, X } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { CodeBlockEditor } from '@/components/ai-elements/code-block'
import { Button } from '@/components/ui/button'
import { getMessageEditorState } from '../../lib'
import type { Message } from '../../types'
type PlaygroundMessageEditorProps = {
editText: string
message: Message
onCancelEdit?: (open: boolean) => void
onEditTextChange: (text: string) => void
onSaveEdit?: (newContent: string) => void
onSaveEditAndSubmit?: (newContent: string) => void
originalText: string
}
export function PlaygroundMessageEditor({
editText,
message,
onCancelEdit,
onEditTextChange,
onSaveEdit,
onSaveEditAndSubmit,
originalText,
}: PlaygroundMessageEditorProps) {
const { t } = useTranslation()
const { canSave, hasChanged, showSaveAndSubmit } = getMessageEditorState(
message,
editText,
originalText
)
const handleCancel = () => {
if (
hasChanged &&
!window.confirm(
t('You have unsaved changes. Are you sure you want to leave?')
)
) {
return
}
onCancelEdit?.(false)
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault()
handleCancel()
return
}
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
event.preventDefault()
if (!canSave) return
if (showSaveAndSubmit) {
onSaveEditAndSubmit?.(editText)
} else {
onSaveEdit?.(editText)
}
}
}
const editorActions = (
<>
{showSaveAndSubmit && (
<Button
aria-label={t('Save & Submit')}
disabled={!canSave}
onClick={() => onSaveEditAndSubmit?.(editText)}
size='icon-sm'
type='button'
>
<Send className='size-4' />
</Button>
)}
<Button
aria-label={t('Save')}
disabled={!canSave}
onClick={() => onSaveEdit?.(editText)}
size='icon-sm'
type='button'
variant={showSaveAndSubmit ? 'ghost' : 'default'}
>
<Check className='size-4' />
</Button>
{hasChanged && (
<Button
aria-label={t('Reset')}
onClick={() => onEditTextChange(originalText)}
size='icon-sm'
type='button'
variant='ghost'
>
<RotateCcw className='size-4' />
</Button>
)}
<Button
aria-label={t('Cancel')}
onClick={handleCancel}
size='icon-sm'
type='button'
variant='ghost'
>
<X className='size-4' />
</Button>
</>
)
return (
<CodeBlockEditor
actions={editorActions}
ariaLabel={t('Edit')}
className='my-0 group-[.is-assistant]:w-full group-[.is-assistant]:max-w-[78ch] group-[.is-user]:max-w-[85%] sm:group-[.is-user]:max-w-[62ch] md:group-[.is-user]:max-w-[68ch] lg:group-[.is-user]:max-w-[72ch]'
language='markdown'
onChange={onEditTextChange}
onKeyDown={handleKeyDown}
rows={8}
title={
<span className='inline-flex items-center gap-2'>
<span>{t('Edit')}</span>
<span className='text-muted-foreground/80 normal-case'>
{hasChanged ? t('Unsaved changes') : t('No changes')}
</span>
</span>
}
value={editText}
/>
)
}
@@ -1,291 +0,0 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffect, useMemo, useState } from 'react'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import {
Branch,
BranchMessages,
BranchNext,
BranchPage,
BranchPrevious,
BranchSelector,
} from '@/components/ai-elements/branch'
import {
Conversation,
ConversationContent,
ConversationScrollButton,
} from '@/components/ai-elements/conversation'
import { Loader } from '@/components/ai-elements/loader'
import { Message, MessageContent } from '@/components/ai-elements/message'
import {
Reasoning,
ReasoningContent,
ReasoningTrigger,
} from '@/components/ai-elements/reasoning'
import { Response } from '@/components/ai-elements/response'
import { Shimmer } from '@/components/ai-elements/shimmer'
import {
Source,
Sources,
SourcesContent,
SourcesTrigger,
} from '@/components/ai-elements/sources'
import { MESSAGE_ROLES } from '../constants'
import { getMessageContentStyles } from '../lib/message-styles'
import { parseThinkTags } from '../lib/message-utils'
import type { Message as MessageType } from '../types'
import { MessageActions } from './message-actions'
import { MessageError } from './message-error'
interface PlaygroundChatProps {
messages: MessageType[]
onCopyMessage?: (message: MessageType) => void
onRegenerateMessage?: (message: MessageType) => void
onEditMessage?: (message: MessageType) => void
onDeleteMessage?: (message: MessageType) => void
isGenerating?: boolean
editingKey?: string | null
onSaveEdit?: (newContent: string) => void
onCancelEdit?: (open: boolean) => void
onSaveEditAndSubmit?: (newContent: string) => void
}
export function PlaygroundChat({
messages,
onCopyMessage,
onRegenerateMessage,
onEditMessage,
onDeleteMessage,
isGenerating = false,
editingKey,
onSaveEdit,
onCancelEdit,
onSaveEditAndSubmit,
}: PlaygroundChatProps) {
const [editText, setEditText] = useState('')
const [originalText, setOriginalText] = useState('')
useEffect(() => {
if (!editingKey) return
const message = messages.find((m) => m.key === editingKey)
const content = message?.versions?.[0]?.content || ''
// eslint-disable-next-line react-hooks/set-state-in-effect
setEditText(content)
setOriginalText(content)
}, [editingKey, messages])
const isEditing = (key: string) => editingKey === key
const isEmpty = useMemo(() => !editText.trim(), [editText])
const isChanged = useMemo(
() => editText !== originalText,
[editText, originalText]
)
return (
<Conversation>
{/* Remove outer padding; apply padding to inner centered container to align with input */}
<ConversationContent className='p-0'>
<div className='mx-auto w-full max-w-4xl px-4 py-4'>
{messages.map((message, messageIndex) => {
const { versions = [] } = message
const isLastAssistantMessage =
messageIndex === messages.length - 1 &&
message.from === MESSAGE_ROLES.ASSISTANT
return (
<Branch defaultBranch={0} key={message.key}>
<BranchMessages>
{versions.map((version, versionIndex) => (
<Message
className='group flex-row-reverse'
from={message.from}
key={`${message.key}-${version.id}-${versionIndex}`}
>
<div className='w-full min-w-0 flex-1 basis-full py-1'>
{isEditing(message.key) ? (
<div className='space-y-2'>
<Textarea
value={editText}
onChange={(e) => setEditText(e.target.value)}
className='font-mono text-sm'
rows={8}
/>
<div className='flex gap-2'>
{/* Save & Submit only makes sense for user messages */}
{message.from === MESSAGE_ROLES.USER && (
<Button
size='sm'
onClick={() =>
onSaveEditAndSubmit?.(editText)
}
disabled={isEmpty || !isChanged}
>
Save & Submit
</Button>
)}
<Button
size='sm'
onClick={() => onSaveEdit?.(editText)}
disabled={isEmpty || !isChanged}
>
Save
</Button>
<Button
size='sm'
variant='outline'
onClick={() => onCancelEdit?.(false)}
>
Cancel
</Button>
</div>
</div>
) : (
<>
{(() => {
const isAssistant =
message.from === MESSAGE_ROLES.ASSISTANT
const hasSources = !!message.sources?.length
const showReasoning =
isAssistant && !!message.reasoning?.content
const showLoader =
isAssistant &&
!message.isReasoningStreaming &&
(message.status === 'loading' ||
(message.status === 'streaming' &&
!version.content))
const showMessageContent =
(message.from === MESSAGE_ROLES.USER ||
!message.isReasoningStreaming) &&
!!version.content
// Extract visible content (remove <think> tags for assistant messages)
const displayContent = isAssistant
? parseThinkTags(version.content).visibleContent
: version.content
const actions = (
<MessageActions
message={message}
onCopy={onCopyMessage}
onRegenerate={onRegenerateMessage}
onEdit={onEditMessage}
onDelete={onDeleteMessage}
isGenerating={isGenerating}
alwaysVisible={isLastAssistantMessage}
className='mt-1'
/>
)
return (
<>
{/* Sources */}
{hasSources && (
<Sources>
<SourcesTrigger
count={message.sources!.length}
/>
<SourcesContent>
{message.sources!.map(
(source, sourceIndex) => (
<Source
href={source.href}
key={`${message.key}-source-${sourceIndex}`}
title={source.title}
/>
)
)}
</SourcesContent>
</Sources>
)}
{/* Reasoning */}
{showReasoning && (
<Reasoning
defaultOpen={true}
isStreaming={message.isReasoningStreaming}
>
<ReasoningTrigger />
<ReasoningContent>
{message.reasoning!.content}
</ReasoningContent>
</Reasoning>
)}
{/* Loader */}
{showLoader && (
<div className='flex items-center gap-2 py-2'>
<Loader />
<Shimmer className='text-sm' duration={1}>
Responding...
</Shimmer>
</div>
)}
{/* Error or Content */}
{message.status === 'error' ? (
<>
<MessageError
message={message}
className='mb-2'
/>
{actions}
</>
) : (
showMessageContent && (
<>
<MessageContent
variant='flat'
className={cn(
getMessageContentStyles()
)}
>
<Response>{displayContent}</Response>
</MessageContent>
{actions}
</>
)
)}
</>
)
})()}
</>
)}
</div>
</Message>
))}
</BranchMessages>
{/* Branch selector for multiple versions */}
{versions.length > 1 && (
<BranchSelector className='px-0' from={message.from}>
<BranchPrevious />
<BranchPage />
<BranchNext />
</BranchSelector>
)}
</Branch>
)
})}
</div>
</ConversationContent>
<ConversationScrollButton />
</Conversation>
)
}
@@ -1,239 +0,0 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState } from 'react'
import {
PaperclipIcon,
FileIcon,
ImageIcon,
ScreenShareIcon,
CameraIcon,
GlobeIcon,
SendIcon,
SquareIcon,
BarChartIcon,
BoxIcon,
NotepadTextIcon,
CodeSquareIcon,
GraduationCapIcon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
PromptInput,
PromptInputButton,
PromptInputFooter,
PromptInputTextarea,
PromptInputTools,
type PromptInputMessage,
} from '@/components/ai-elements/prompt-input'
import { Suggestion, Suggestions } from '@/components/ai-elements/suggestion'
import { ModelGroupSelector } from '@/components/model-group-selector'
import type { ModelOption, GroupOption } from '../types'
interface PlaygroundInputProps {
onSubmit: (text: string) => void
onStop?: () => void
disabled?: boolean
isGenerating?: boolean
models: ModelOption[]
modelValue: string
onModelChange: (value: string) => void
isModelLoading?: boolean
groups: GroupOption[]
groupValue: string
onGroupChange: (value: string) => void
}
const suggestions = [
{ icon: BarChartIcon, text: 'Analyze data', color: '#76d0eb' },
{ icon: BoxIcon, text: 'Surprise me', color: '#76d0eb' },
{ icon: NotepadTextIcon, text: 'Summarize text', color: '#ea8444' },
{ icon: CodeSquareIcon, text: 'Code', color: '#6c71ff' },
{ icon: GraduationCapIcon, text: 'Get advice', color: '#76d0eb' },
{ icon: null, text: 'More' },
]
export function PlaygroundInput({
onSubmit,
onStop,
disabled,
isGenerating,
models,
modelValue,
onModelChange,
isModelLoading = false,
groups,
groupValue,
onGroupChange,
}: PlaygroundInputProps) {
const { t } = useTranslation()
const [text, setText] = useState('')
const isModelSelectDisabled =
disabled || isModelLoading || models.length === 0
const isGroupSelectDisabled = disabled || groups.length === 0
const handleSubmit = (message: PromptInputMessage) => {
if (!message.text?.trim() || disabled) return
onSubmit(message.text)
setText('')
}
const handleFileAction = (action: string) => {
toast.info(t('Feature in development'), {
description: action,
})
}
const handleSuggestionClick = (suggestion: string) => {
onSubmit(suggestion)
}
return (
<div className='grid shrink-0 gap-4 px-1 md:pb-4'>
<PromptInput groupClassName='rounded-xl' onSubmit={handleSubmit}>
<PromptInputTextarea
autoComplete='off'
autoCorrect='off'
autoCapitalize='off'
spellCheck={false}
className='px-5 md:text-base'
disabled={disabled}
onChange={(event) => setText(event.target.value)}
placeholder={t('Ask anything')}
value={text}
/>
<PromptInputFooter className='p-2.5'>
<PromptInputTools>
<DropdownMenu>
<DropdownMenuTrigger
render={
<PromptInputButton
className='border font-medium'
disabled={disabled}
variant='outline'
/>
}
>
<PaperclipIcon size={16} />
<span className='hidden sm:inline'>{t('Attach')}</span>
<span className='sr-only sm:hidden'>{t('Attach')}</span>
</DropdownMenuTrigger>
<DropdownMenuContent align='start'>
<DropdownMenuItem
onClick={() => handleFileAction('upload-file')}
>
<FileIcon className='mr-2' size={16} />
{t('Upload file')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleFileAction('upload-photo')}
>
<ImageIcon className='mr-2' size={16} />
{t('Upload photo')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleFileAction('take-screenshot')}
>
<ScreenShareIcon className='mr-2' size={16} />
{t('Take screenshot')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleFileAction('take-photo')}
>
<CameraIcon className='mr-2' size={16} />
{t('Take photo')}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<PromptInputButton
className='border font-medium'
disabled={disabled}
onClick={() => toast.info(t('Search feature in development'))}
variant='outline'
>
<GlobeIcon size={16} />
<span className='hidden sm:inline'>{t('Search')}</span>
<span className='sr-only sm:hidden'>{t('Search')}</span>
</PromptInputButton>
</PromptInputTools>
<div className='flex items-center gap-1.5 md:gap-2'>
<ModelGroupSelector
selectedModel={modelValue}
models={models}
onModelChange={onModelChange}
selectedGroup={groupValue}
groups={groups}
onGroupChange={onGroupChange}
disabled={isModelSelectDisabled || isGroupSelectDisabled}
/>
{isGenerating && onStop ? (
<PromptInputButton
className='text-foreground font-medium'
onClick={onStop}
variant='secondary'
>
<SquareIcon className='fill-current' size={16} />
<span className='hidden sm:inline'>{t('Stop')}</span>
<span className='sr-only sm:hidden'>{t('Stop')}</span>
</PromptInputButton>
) : (
<PromptInputButton
className='text-foreground font-medium'
disabled={disabled || !text.trim()}
type='submit'
variant='secondary'
>
<SendIcon size={16} />
<span className='hidden sm:inline'>{t('Send')}</span>
<span className='sr-only sm:hidden'>{t('Send')}</span>
</PromptInputButton>
)}
</div>
</PromptInputFooter>
</PromptInput>
<Suggestions>
{suggestions.map(({ icon: Icon, text, color }) => (
<Suggestion
className={`text-xs font-normal sm:text-sm ${
text === 'More' ? 'hidden sm:flex' : ''
}`}
key={text}
onClick={() => handleSuggestionClick(text)}
suggestion={text}
>
{Icon && <Icon size={16} style={{ color }} />}
{text}
</Suggestion>
))}
</Suggestions>
</div>
)
}
+2
View File
@@ -94,6 +94,8 @@ export const MESSAGE_ACTION_LABELS = {
COPY: 'Copy',
COPIED: 'Copied!',
REGENERATE: 'Regenerate',
SHOW_PREVIEW: 'Show preview',
SHOW_SOURCE: 'Show source',
EDIT: 'Edit',
DELETE: 'Delete',
NO_CONTENT: 'No content to copy',
+2
View File
@@ -20,3 +20,5 @@ export * from './use-playground-state'
export * from './use-stream-request'
export * from './use-chat-handler'
export * from './use-message-action-guard'
export * from './use-playground-conversation'
export * from './use-playground-options'
+177 -69
View File
@@ -16,16 +16,23 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { sendChatCompletion } from '../api'
import { MESSAGE_STATUS, ERROR_MESSAGES } from '../constants'
import { ERROR_MESSAGES } from '../constants'
import {
applyStreamingChunk,
buildChatCompletionPayload,
updateAssistantMessageWithError,
updateLastAssistantMessage,
processStreamingContent,
finalizeMessage,
parseRequestErrorDetails,
applyChatCompletionResponse,
completeAssistantMessage,
hasChatCompletionChoice,
isAssistantMessageFinal,
isAssistantMessagePending,
} from '../lib'
import type { Message, PlaygroundConfig, ParameterEnabled } from '../types'
import { useStreamRequest } from './use-stream-request'
@@ -36,6 +43,25 @@ interface UseChatHandlerOptions {
onMessageUpdate: (updater: (prev: Message[]) => Message[]) => void
}
const KNOWN_ERROR_MESSAGES = new Set<string>(Object.values(ERROR_MESSAGES))
const STREAM_UPDATE_FLUSH_MS = 50
type PendingStreamChunks = {
content: string
reasoning: string
}
function mergePendingStreamChunk(
currentChunk: string,
nextChunk: string
): string {
if (!currentChunk || !nextChunk.startsWith(currentChunk)) {
return currentChunk + nextChunk
}
return nextChunk
}
/**
* Hook for handling chat message sending and receiving
*/
@@ -44,65 +70,141 @@ export function useChatHandler({
parameterEnabled,
onMessageUpdate,
}: UseChatHandlerOptions) {
const { t } = useTranslation()
const { sendStreamRequest, stopStream, isStreaming } = useStreamRequest()
const [isRequesting, setIsRequesting] = useState(false)
const abortControllerRef = useRef<AbortController | null>(null)
const requestIdRef = useRef(0)
const pendingStreamChunksRef = useRef<PendingStreamChunks>({
content: '',
reasoning: '',
})
const streamFlushTimerRef = useRef<number | null>(null)
const flushStreamUpdates = useCallback(() => {
if (streamFlushTimerRef.current !== null) {
window.clearTimeout(streamFlushTimerRef.current)
streamFlushTimerRef.current = null
}
const pendingChunks = pendingStreamChunksRef.current
if (!pendingChunks.reasoning && !pendingChunks.content) {
return
}
pendingStreamChunksRef.current = { content: '', reasoning: '' }
onMessageUpdate((prev) =>
updateLastAssistantMessage(prev, (message) => {
let updatedMessage = message
if (pendingChunks.reasoning) {
updatedMessage = applyStreamingChunk(
updatedMessage,
'reasoning',
pendingChunks.reasoning
)
}
if (pendingChunks.content) {
updatedMessage = applyStreamingChunk(
updatedMessage,
'content',
pendingChunks.content
)
}
return updatedMessage
})
)
}, [onMessageUpdate])
const scheduleStreamFlush = useCallback(() => {
if (streamFlushTimerRef.current !== null) {
return
}
streamFlushTimerRef.current = window.setTimeout(
flushStreamUpdates,
STREAM_UPDATE_FLUSH_MS
)
}, [flushStreamUpdates])
useEffect(
() => () => {
if (streamFlushTimerRef.current !== null) {
window.clearTimeout(streamFlushTimerRef.current)
}
},
[]
)
const getDisplayError = useCallback(
(error: string) => {
if (KNOWN_ERROR_MESSAGES.has(error)) {
return t(error)
}
const connectionClosedSuffix = `: ${ERROR_MESSAGES.CONNECTION_CLOSED}`
if (error.endsWith(connectionClosedSuffix)) {
return `${error.slice(0, -ERROR_MESSAGES.CONNECTION_CLOSED.length)}${t(
ERROR_MESSAGES.CONNECTION_CLOSED
)}`
}
return error
},
[t]
)
// Handle stream update
const handleStreamUpdate = useCallback(
(type: 'reasoning' | 'content', chunk: string) => {
onMessageUpdate((prev) =>
updateLastAssistantMessage(prev, (message) => {
if (message.status === MESSAGE_STATUS.ERROR) return message
if (type === 'reasoning') {
// Direct API reasoning_content
return {
...message,
reasoning: {
content: (message.reasoning?.content || '') + chunk,
duration: 0,
},
isReasoningStreaming: true,
status: MESSAGE_STATUS.STREAMING,
}
}
// Content streaming: handle <think> tags
return {
...processStreamingContent(message, chunk),
status: MESSAGE_STATUS.STREAMING,
}
})
pendingStreamChunksRef.current[type] = mergePendingStreamChunk(
pendingStreamChunksRef.current[type],
chunk
)
scheduleStreamFlush()
},
[onMessageUpdate]
[scheduleStreamFlush]
)
// Handle stream complete
const handleStreamComplete = useCallback(() => {
flushStreamUpdates()
setIsRequesting(false)
onMessageUpdate((prev) =>
updateLastAssistantMessage(prev, (message) =>
message.status === MESSAGE_STATUS.COMPLETE ||
message.status === MESSAGE_STATUS.ERROR
isAssistantMessageFinal(message)
? message
: { ...finalizeMessage(message), status: MESSAGE_STATUS.COMPLETE }
: completeAssistantMessage(message)
)
)
}, [onMessageUpdate])
}, [flushStreamUpdates, onMessageUpdate])
// Handle stream error
const handleStreamError = useCallback(
(error: string, errorCode?: string) => {
toast.error(error)
flushStreamUpdates()
setIsRequesting(false)
const displayError = getDisplayError(error)
toast.error(displayError)
const errorTitle = t(ERROR_MESSAGES.API_REQUEST_ERROR)
onMessageUpdate((prev) =>
updateAssistantMessageWithError(prev, error, errorCode)
updateAssistantMessageWithError(
prev,
displayError,
errorCode,
errorTitle
)
)
},
[onMessageUpdate]
[flushStreamUpdates, getDisplayError, onMessageUpdate, t]
)
// Send streaming chat request
const sendStreamingChat = useCallback(
(messages: Message[]) => {
setIsRequesting(true)
const payload = buildChatCompletionPayload(
messages,
config,
@@ -133,42 +235,45 @@ export function useChatHandler({
config,
parameterEnabled
)
const requestId = requestIdRef.current + 1
const abortController = new AbortController()
requestIdRef.current = requestId
abortControllerRef.current = abortController
try {
const response = await sendChatCompletion(payload)
const choice = response.choices?.[0]
if (!choice) return
setIsRequesting(true)
const response = await sendChatCompletion(
payload,
abortController.signal
)
if (abortController.signal.aborted) return
if (!hasChatCompletionChoice(response)) {
handleStreamError(ERROR_MESSAGES.API_REQUEST_ERROR)
return
}
onMessageUpdate((prev) =>
updateLastAssistantMessage(prev, (message) => ({
...finalizeMessage(
{
...message,
versions: [
{
...message.versions[0],
content: choice.message?.content || '',
},
],
},
choice.message?.reasoning_content
),
status: MESSAGE_STATUS.COMPLETE,
}))
updateLastAssistantMessage(prev, (message) => {
const updatedMessage = applyChatCompletionResponse(
message,
response
)
return updatedMessage ?? message
})
)
} catch (error: unknown) {
const err = error as {
response?: {
data?: { message?: string; error?: { code?: string } }
}
message?: string
if (abortController.signal.aborted) return
const { errorCode, errorMessage } = parseRequestErrorDetails(error)
handleStreamError(errorMessage, errorCode)
} finally {
if (requestIdRef.current === requestId) {
abortControllerRef.current = null
setIsRequesting(false)
}
handleStreamError(
err?.response?.data?.message ||
err?.message ||
ERROR_MESSAGES.API_REQUEST_ERROR,
err?.response?.data?.error?.code || undefined
)
}
},
[config, parameterEnabled, onMessageUpdate, handleStreamError]
@@ -189,19 +294,22 @@ export function useChatHandler({
// Stop generation
const stopGeneration = useCallback(() => {
stopStream()
flushStreamUpdates()
abortControllerRef.current?.abort()
abortControllerRef.current = null
setIsRequesting(false)
onMessageUpdate((prev) =>
updateLastAssistantMessage(prev, (message) =>
message.status === MESSAGE_STATUS.LOADING ||
message.status === MESSAGE_STATUS.STREAMING
? { ...finalizeMessage(message), status: MESSAGE_STATUS.COMPLETE }
isAssistantMessagePending(message)
? completeAssistantMessage(message)
: message
)
)
}, [stopStream, onMessageUpdate])
}, [stopStream, flushStreamUpdates, onMessageUpdate])
return {
sendChat,
stopGeneration,
isGenerating: isStreaming,
isGenerating: isStreaming || isRequesting,
}
}
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { MESSAGE_ACTION_LABELS } from '../constants'
@@ -25,17 +26,18 @@ import { MESSAGE_ACTION_LABELS } from '../constants'
* Provides a wrapper that checks if generation is active before executing
*/
export function useMessageActionGuard(isGenerating: boolean) {
const { t } = useTranslation()
const guardAction = useCallback(
(action: () => void) => {
return () => {
if (isGenerating) {
toast.warning(MESSAGE_ACTION_LABELS.WAIT_GENERATION)
toast.warning(t(MESSAGE_ACTION_LABELS.WAIT_GENERATION))
return
}
action()
}
},
[isGenerating]
[isGenerating, t]
)
return { guardAction }
@@ -0,0 +1,116 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useState } from 'react'
import {
appendUserMessagePair,
applyMessageEdit,
createRegeneratedMessages,
removeMessageByKey,
} from '../lib'
import type { Message } from '../types'
type UsePlaygroundConversationOptions = {
messages: Message[]
updateMessages: (
updater: Message[] | ((prev: Message[]) => Message[])
) => void
sendChat: (messages: Message[]) => void
}
export function usePlaygroundConversation({
messages,
updateMessages,
sendChat,
}: UsePlaygroundConversationOptions) {
const [editingMessageKey, setEditingMessageKey] = useState<string | null>(
null
)
const handleSendMessage = useCallback(
(text: string) => {
const nextMessages = appendUserMessagePair(messages, text)
updateMessages(nextMessages)
sendChat(nextMessages)
},
[messages, updateMessages, sendChat]
)
const handleRegenerateMessage = useCallback(
(message: Message) => {
const nextMessages = createRegeneratedMessages(messages, message.key)
if (!nextMessages) return
updateMessages(nextMessages)
sendChat(nextMessages)
},
[messages, updateMessages, sendChat]
)
const handleEditMessage = useCallback((message: Message) => {
setEditingMessageKey(message.key)
}, [])
const handleEditOpenChange = useCallback((open: boolean) => {
if (!open) {
setEditingMessageKey(null)
}
}, [])
const applyEdit = useCallback(
(newContent: string, shouldSubmit: boolean) => {
if (!editingMessageKey) return
const editResult = applyMessageEdit(
messages,
editingMessageKey,
newContent,
shouldSubmit
)
if (!editResult) return
setEditingMessageKey(null)
updateMessages(editResult.messages)
if (editResult.shouldSend) {
sendChat(editResult.messages)
}
},
[editingMessageKey, messages, updateMessages, sendChat]
)
const handleDeleteMessage = useCallback(
(message: Message) => {
updateMessages((previousMessages) =>
removeMessageByKey(previousMessages, message.key)
)
},
[updateMessages]
)
return {
editingMessageKey,
handleSendMessage,
handleRegenerateMessage,
handleEditMessage,
handleEditOpenChange,
applyEdit,
handleDeleteMessage,
}
}
@@ -0,0 +1,125 @@
import { useQuery } from '@tanstack/react-query'
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { getUserGroups, getUserModels } from '../api'
import {
getGroupFallback,
getModelFallback,
getOptionLoadErrorMessage,
shouldClearModelForGroup,
} from '../lib'
import type { GroupOption, ModelOption, PlaygroundConfig } from '../types'
type UsePlaygroundOptionsParams = {
currentGroup: string
currentModel: string
setGroups: (groups: GroupOption[]) => void
setModels: (models: ModelOption[]) => void
updateConfig: <K extends keyof PlaygroundConfig>(
key: K,
value: PlaygroundConfig[K]
) => void
}
export function usePlaygroundOptions({
currentGroup,
currentModel,
setGroups,
setModels,
updateConfig,
}: UsePlaygroundOptionsParams) {
const { t } = useTranslation()
const {
data: modelsData,
error: modelsError,
isError: isModelsError,
isLoading: isLoadingModels,
} = useQuery({
queryKey: ['playground-models', currentGroup],
queryFn: () => getUserModels(currentGroup),
enabled: currentGroup !== '',
})
const {
data: groupsData,
error: groupsError,
isError: isGroupsError,
} = useQuery({
queryKey: ['playground-groups'],
queryFn: getUserGroups,
})
useEffect(() => {
if (!isModelsError) return
toast.error(
getOptionLoadErrorMessage(
modelsError,
t('Failed to load playground models')
)
)
}, [isModelsError, modelsError, t])
useEffect(() => {
if (!isGroupsError) return
toast.error(
getOptionLoadErrorMessage(
groupsError,
t('Failed to load playground groups')
)
)
}, [isGroupsError, groupsError, t])
useEffect(() => {
if (!modelsData) return
setModels(modelsData)
const fallback = getModelFallback(modelsData, currentModel)
if (fallback) {
updateConfig('model', fallback)
return
}
if (shouldClearModelForGroup(modelsData, currentModel)) {
updateConfig('model', '')
}
}, [modelsData, currentModel, setModels, updateConfig])
useEffect(() => {
if (!groupsData) return
setGroups(groupsData)
const fallback = getGroupFallback(groupsData, currentGroup)
if (fallback) {
updateConfig('group', fallback)
}
}, [groupsData, currentGroup, setGroups, updateConfig])
return {
isLoadingModels,
}
}
@@ -16,15 +16,18 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { DEFAULT_CONFIG, DEFAULT_PARAMETER_ENABLED } from '../constants'
import {
loadConfig,
saveConfig,
loadParameterEnabled,
saveParameterEnabled,
loadMessages,
saveMessages,
applyMessageStateUpdate,
getInitialParameterEnabled,
getInitialPlaygroundConfig,
loadMessages,
type MessageStateUpdater,
} from '../lib'
import type {
Message,
@@ -34,30 +37,77 @@ import type {
GroupOption,
} from '../types'
const MESSAGE_SAVE_DEBOUNCE_MS = 500
/**
* Main state management hook for playground
*/
export function usePlaygroundState() {
// Load initial state from localStorage
const [config, setConfig] = useState<PlaygroundConfig>(() => {
const savedConfig = loadConfig()
return { ...DEFAULT_CONFIG, ...savedConfig }
})
const [parameterEnabled, setParameterEnabled] = useState<ParameterEnabled>(
() => {
const saved = loadParameterEnabled()
return { ...DEFAULT_PARAMETER_ENABLED, ...saved }
}
const [config, setConfig] = useState<PlaygroundConfig>(
getInitialPlaygroundConfig
)
const [messages, setMessages] = useState<Message[]>(() => {
return loadMessages() || []
})
const [parameterEnabled, setParameterEnabled] = useState<ParameterEnabled>(
getInitialParameterEnabled
)
const [messages, setMessages] = useState<Message[]>([])
const [isLoadingMessages, setIsLoadingMessages] = useState(true)
const messagesSaveTimerRef = useRef<number | null>(null)
const latestMessagesRef = useRef<Message[]>(messages)
const hasLoadedMessagesRef = useRef(false)
const [models, setModels] = useState<ModelOption[]>([])
const [groups, setGroups] = useState<GroupOption[]>([])
const persistMessages = useCallback((messagesToSave: Message[]) => {
latestMessagesRef.current = messagesToSave
if (!hasLoadedMessagesRef.current) {
return
}
if (messagesSaveTimerRef.current !== null) {
window.clearTimeout(messagesSaveTimerRef.current)
}
messagesSaveTimerRef.current = window.setTimeout(() => {
messagesSaveTimerRef.current = null
saveMessages(latestMessagesRef.current)
}, MESSAGE_SAVE_DEBOUNCE_MS)
}, [])
useEffect(() => {
let cancelled = false
window.setTimeout(() => {
const loadedMessages = loadMessages() ?? []
if (cancelled) {
return
}
latestMessagesRef.current = loadedMessages
hasLoadedMessagesRef.current = true
setMessages(loadedMessages)
setIsLoadingMessages(false)
}, 0)
return () => {
cancelled = true
}
}, [])
useEffect(
() => () => {
if (messagesSaveTimerRef.current !== null) {
window.clearTimeout(messagesSaveTimerRef.current)
saveMessages(latestMessagesRef.current)
}
},
[]
)
// Update config with automatic save
const updateConfig = useCallback(
<K extends keyof PlaygroundConfig>(key: K, value: PlaygroundConfig[K]) => {
@@ -84,15 +134,14 @@ export function usePlaygroundState() {
// Update messages with automatic save
const updateMessages = useCallback(
(updater: Message[] | ((prev: Message[]) => Message[])) => {
(updater: MessageStateUpdater) => {
setMessages((prev) => {
const newMessages =
typeof updater === 'function' ? updater(prev) : updater
saveMessages(newMessages)
const newMessages = applyMessageStateUpdate(prev, updater)
persistMessages(newMessages)
return newMessages
})
},
[]
[persistMessages]
)
// Clear all messages
@@ -113,6 +162,7 @@ export function usePlaygroundState() {
config,
parameterEnabled,
messages,
isLoadingMessages,
models,
groups,
@@ -16,11 +16,20 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useRef } from 'react'
import { useCallback, useRef, useState } from 'react'
import { SSE } from 'sse.js'
import { getCommonHeaders } from '@/lib/api'
import { API_ENDPOINTS, ERROR_MESSAGES } from '../constants'
import type { ChatCompletionRequest, ChatCompletionChunk } from '../types'
import {
getStreamReadyStateError,
isStreamClosedReadyState,
isStreamDoneMessage,
parseStreamErrorDetails,
parseStreamMessageUpdates,
} from '../lib'
import type { ChatCompletionRequest } from '../types'
/**
* Hook for handling streaming chat completion requests
@@ -28,6 +37,17 @@ import type { ChatCompletionRequest, ChatCompletionChunk } from '../types'
export function useStreamRequest() {
const sseSourceRef = useRef<SSE | null>(null)
const isStreamCompleteRef = useRef(false)
const [isStreaming, setIsStreaming] = useState(false)
const closeActiveStream = useCallback((source?: SSE) => {
const streamSource = source ?? sseSourceRef.current
streamSource?.close()
if (!source || sseSourceRef.current === source) {
sseSourceRef.current = null
setIsStreaming(false)
}
}, [])
const sendStreamRequest = useCallback(
(
@@ -36,6 +56,8 @@ export function useStreamRequest() {
onComplete: () => void,
onError: (error: string, errorCode?: string) => void
) => {
sseSourceRef.current?.close()
const source = new SSE(API_ENDPOINTS.CHAT_COMPLETIONS, {
headers: getCommonHeaders(),
method: 'POST',
@@ -44,38 +66,28 @@ export function useStreamRequest() {
sseSourceRef.current = source
isStreamCompleteRef.current = false
const closeSource = () => {
source.close()
sseSourceRef.current = null
}
setIsStreaming(true)
const handleError = (errorMessage: string, errorCode?: string) => {
if (!isStreamCompleteRef.current) {
onError(errorMessage, errorCode)
closeSource()
closeActiveStream(source)
}
}
source.addEventListener('message', (e: MessageEvent) => {
if (e.data === '[DONE]') {
if (isStreamDoneMessage(e.data)) {
isStreamCompleteRef.current = true
closeSource()
closeActiveStream(source)
onComplete()
return
}
try {
const chunk: ChatCompletionChunk = JSON.parse(e.data)
const delta = chunk.choices?.[0]?.delta
const updates = parseStreamMessageUpdates(e.data)
if (delta) {
if (delta.reasoning_content) {
onUpdate('reasoning', delta.reasoning_content)
}
if (delta.content) {
onUpdate('content', delta.content)
}
for (const update of updates) {
onUpdate(update.type, update.chunk)
}
} catch (error) {
// eslint-disable-next-line no-console
@@ -86,24 +98,10 @@ export function useStreamRequest() {
source.addEventListener('error', (e: Event & { data?: string }) => {
// Only handle errors if stream didn't complete normally
if (source.readyState !== 2) {
if (!isStreamClosedReadyState(source.readyState)) {
// eslint-disable-next-line no-console
console.error('SSE Error:', e)
let errorMessage = e.data || ERROR_MESSAGES.API_REQUEST_ERROR
let errorCode: string | undefined
if (e.data) {
try {
const parsed = JSON.parse(e.data) as {
error?: { message?: string; code?: string }
}
if (parsed?.error) {
errorMessage = parsed.error.message || errorMessage
errorCode = parsed.error.code || undefined
}
} catch {
// not JSON, use raw string
}
}
const { errorCode, errorMessage } = parseStreamErrorDetails(e.data)
handleError(errorMessage, errorCode)
}
})
@@ -111,14 +109,10 @@ export function useStreamRequest() {
source.addEventListener(
'readystatechange',
(e: Event & { readyState?: number }) => {
const status = (source as unknown as { status?: number }).status
if (
e.readyState !== undefined &&
e.readyState >= 2 &&
status !== undefined &&
status !== 200
) {
handleError(`HTTP ${status}: ${ERROR_MESSAGES.CONNECTION_CLOSED}`)
const errorMessage = getStreamReadyStateError(e.readyState, source)
if (errorMessage) {
handleError(errorMessage)
}
}
)
@@ -129,26 +123,19 @@ export function useStreamRequest() {
// eslint-disable-next-line no-console
console.error('Failed to start SSE stream:', error)
onError(ERROR_MESSAGES.STREAM_START_ERROR)
sseSourceRef.current = null
closeActiveStream(source)
}
},
[]
[closeActiveStream]
)
const stopStream = useCallback(() => {
if (sseSourceRef.current) {
sseSourceRef.current.close()
sseSourceRef.current = null
}
}, [])
// eslint-disable-next-line react-hooks/refs
const isStreaming = sseSourceRef.current !== null
closeActiveStream()
}, [closeActiveStream])
return {
sendStreamRequest,
stopStream,
// eslint-disable-next-line react-hooks/refs
isStreaming,
}
}
+39 -151
View File
@@ -16,29 +16,28 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useEffect, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { getUserModels, getUserGroups } from './api'
import { PlaygroundChat } from './components/playground-chat'
import { PlaygroundInput } from './components/playground-input'
import { usePlaygroundState, useChatHandler } from './hooks'
import { createUserMessage, createLoadingAssistantMessage } from './lib'
import type { Message as MessageType } from './types'
import { PlaygroundChat } from './components/chat/playground-chat'
import { PlaygroundInput } from './components/input/playground-input'
import {
useChatHandler,
usePlaygroundConversation,
usePlaygroundOptions,
usePlaygroundState,
} from './hooks'
export function Playground() {
const { t } = useTranslation()
const {
config,
parameterEnabled,
messages,
isLoadingMessages,
models,
groups,
updateMessages,
setModels,
setGroups,
updateConfig,
clearMessages,
} = usePlaygroundState()
const { sendChat, stopGeneration, isGenerating } = useChatHandler({
@@ -47,157 +46,44 @@ export function Playground() {
onMessageUpdate: updateMessages,
})
// Edit dialog state
const [editingMessageKey, setEditingMessageKey] = useState<string | null>(
null
)
// Load models
const { data: modelsData, isLoading: isLoadingModels } = useQuery({
queryKey: ['playground-models'],
queryFn: async () => {
try {
return await getUserModels()
} catch (error) {
toast.error(
error instanceof Error
? error.message
: t('Failed to load playground models')
)
return []
}
},
const {
editingMessageKey,
handleSendMessage,
handleRegenerateMessage,
handleEditMessage,
handleEditOpenChange,
applyEdit,
handleDeleteMessage,
} = usePlaygroundConversation({
messages,
updateMessages,
sendChat,
})
// Load groups
const { data: groupsData } = useQuery({
queryKey: ['playground-groups'],
queryFn: async () => {
try {
return await getUserGroups()
} catch (error) {
toast.error(
error instanceof Error
? error.message
: t('Failed to load playground groups')
)
return []
}
},
const handleClearMessages = () => {
handleEditOpenChange(false)
clearMessages()
}
const { isLoadingModels } = usePlaygroundOptions({
currentGroup: config.group,
currentModel: config.model,
setGroups,
setModels,
updateConfig,
})
// Update models when data changes
useEffect(() => {
if (!modelsData) return
setModels(modelsData)
// Set default model if current model is not available
const isCurrentModelValid = modelsData.some((m) => m.value === config.model)
if (modelsData.length > 0 && !isCurrentModelValid) {
updateConfig('model', modelsData[0].value)
}
}, [modelsData, config.model, setModels, updateConfig])
// Update groups when data changes
useEffect(() => {
if (!groupsData) return
setGroups(groupsData)
const hasCurrentGroup = groupsData.some((g) => g.value === config.group)
if (!hasCurrentGroup && groupsData.length > 0) {
const fallback =
groupsData.find((g) => g.value === 'default')?.value ??
groupsData[0].value
updateConfig('group', fallback)
}
}, [groupsData, setGroups, config.group, updateConfig])
const handleSendMessage = (text: string) => {
const userMessage = createUserMessage(text)
const assistantMessage = createLoadingAssistantMessage()
const newMessages = [...messages, userMessage, assistantMessage]
updateMessages(newMessages)
// Send chat request
sendChat(newMessages)
}
const handleCopyMessage = (message: MessageType) => {
// Copy is handled in MessageActions component
// eslint-disable-next-line no-console
console.log('Message copied:', message.key)
}
const handleRegenerateMessage = (message: MessageType) => {
// Find the message index and regenerate from there
const messageIndex = messages.findIndex((m) => m.key === message.key)
if (messageIndex === -1) return
// Remove messages after this one and regenerate
const messagesUpToHere = messages.slice(0, messageIndex)
const loadingMessage = createLoadingAssistantMessage()
const newMessages = [...messagesUpToHere, loadingMessage]
updateMessages(newMessages)
sendChat(newMessages)
}
const handleEditMessage = useCallback((message: MessageType) => {
setEditingMessageKey(message.key)
}, [])
const handleEditOpenChange = useCallback((open: boolean) => {
if (!open) setEditingMessageKey(null)
}, [])
// Apply edit and optionally re-submit from the edited user message
const applyEdit = useCallback(
(newContent: string, submit: boolean) => {
if (!editingMessageKey) return
const index = messages.findIndex((m) => m.key === editingMessageKey)
if (index === -1) return
const updated = messages.map((m) =>
m.key === editingMessageKey
? { ...m, versions: [{ ...m.versions[0], content: newContent }] }
: m
)
setEditingMessageKey(null)
if (!submit || updated[index].from !== 'user') {
updateMessages(updated)
return
}
const toSubmit = [
...updated.slice(0, index + 1),
createLoadingAssistantMessage(),
]
updateMessages(toSubmit)
sendChat(toSubmit)
},
[editingMessageKey, messages, updateMessages, sendChat]
)
const handleDeleteMessage = (message: MessageType) => {
const newMessages = messages.filter((m) => m.key !== message.key)
updateMessages(newMessages)
}
return (
<div className='relative flex size-full flex-col overflow-hidden'>
<div className='relative flex size-full min-h-0 flex-col overflow-hidden'>
{/* Full-width scroll container: scrolling works even over side whitespace */}
<div className='flex flex-1 flex-col overflow-hidden'>
<div className='flex min-h-0 flex-1 flex-col overflow-hidden'>
<PlaygroundChat
messages={messages}
onCopyMessage={handleCopyMessage}
isLoadingMessages={isLoadingMessages}
onRegenerateMessage={handleRegenerateMessage}
onEditMessage={handleEditMessage}
onDeleteMessage={handleDeleteMessage}
onSelectPrompt={handleSendMessage}
isGenerating={isGenerating}
editingKey={editingMessageKey}
onCancelEdit={handleEditOpenChange}
@@ -217,9 +103,11 @@ export function Playground() {
modelValue={config.model}
models={models}
onGroupChange={(value) => updateConfig('group', value)}
onClearMessages={handleClearMessages}
onModelChange={(value) => updateConfig('model', value)}
onStop={stopGeneration}
onSubmit={handleSendMessage}
hasMessages={messages.length > 0}
/>
</div>
</div>
+20 -4
View File
@@ -16,7 +16,23 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export * from './message-utils'
export * from './payload-builder'
export * from './storage'
export * from './message-styles'
export * from './input/input-control-utils'
export * from './input/input-tool-utils'
export * from './message/conversation-message-utils'
export * from './message/message-action-utils'
export * from './message/message-content-utils'
export * from './message/message-editor-utils'
export * from './message/message-error-utils'
export * from './message/message-layout-utils'
export * from './message/message-reasoning-utils'
export * from './message/message-streaming-utils'
export * from './message/message-styles'
export * from './message/message-timing-utils'
export * from './message/message-update-utils'
export * from './message/message-utils'
export * from './options/playground-option-utils'
export * from './state/playground-state-utils'
export * from './storage/storage'
export * from './streaming/payload-builder'
export * from './streaming/request-error-utils'
export * from './streaming/stream-utils'
@@ -0,0 +1,68 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { GroupOption, ModelOption } from '../../types'
type InputControlStateOptions = {
disabled?: boolean
groups: GroupOption[]
hasStopHandler: boolean
isGenerating?: boolean
isModelLoading?: boolean
models: ModelOption[]
text: string
}
type InputControlState = {
canSubmit: boolean
isSelectorDisabled: boolean
shouldShowStop: boolean
}
type SubmittableInputMessage = {
text?: string | null
}
export function getSubmittableInputText(
message: SubmittableInputMessage,
disabled?: boolean
): string | null {
if (disabled || !message.text?.trim()) {
return null
}
return message.text
}
export function getInputControlState({
disabled,
groups,
hasStopHandler,
isGenerating,
isModelLoading,
models,
text,
}: InputControlStateOptions): InputControlState {
const hasModels = models.length > 0
return {
canSubmit: !disabled && hasModels && text.trim().length > 0,
isSelectorDisabled: disabled || isModelLoading || groups.length === 0,
shouldShowStop: Boolean(isGenerating && hasStopHandler),
}
}
@@ -0,0 +1,60 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
CameraIcon,
FileIcon,
ImageIcon,
ScreenShareIcon,
type LucideIcon,
} from 'lucide-react'
type AttachmentAction = {
action: string
icon: LucideIcon
label: string
}
type InputToolNotice = {
description?: string
title: string
}
export const ATTACHMENT_ACTIONS = [
{ action: 'upload-file', icon: FileIcon, label: 'Upload file' },
{ action: 'upload-photo', icon: ImageIcon, label: 'Upload photo' },
{
action: 'take-screenshot',
icon: ScreenShareIcon,
label: 'Take screenshot',
},
{ action: 'take-photo', icon: CameraIcon, label: 'Take photo' },
] satisfies AttachmentAction[]
export function getAttachmentActionNotice(action: string): InputToolNotice {
return {
description: action,
title: 'Feature in development',
}
}
export function getSearchActionNotice(): InputToolNotice {
return {
title: 'Search feature in development',
}
}
-355
View File
@@ -1,355 +0,0 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { nanoid } from 'nanoid'
import { MESSAGE_ROLES, MESSAGE_STATUS, ERROR_MESSAGES } from '../constants'
import type {
Message,
MessageVersion,
ChatCompletionMessage,
ContentPart,
} from '../types'
/**
* Create a new message version
*/
export function createMessageVersion(content: string): MessageVersion {
return {
id: nanoid(),
content,
}
}
/**
* Get current version from message (always returns the first version)
*/
export function getCurrentVersion(message: Message): MessageVersion {
return message.versions[0] || { id: 'default', content: '' }
}
/**
* Update current version content in message
*/
export function updateCurrentVersionContent(
message: Message,
content: string
): Message {
const currentVersion = getCurrentVersion(message)
return {
...message,
versions: [{ ...currentVersion, content }],
}
}
/**
* Create a user message
*/
export function createUserMessage(content: string): Message {
return {
key: nanoid(),
from: MESSAGE_ROLES.USER,
versions: [createMessageVersion(content)],
}
}
/**
* Create a loading assistant message
*/
export function createLoadingAssistantMessage(): Message {
return {
key: nanoid(),
from: MESSAGE_ROLES.ASSISTANT,
versions: [createMessageVersion('')],
reasoning: undefined,
isReasoningComplete: false,
isContentComplete: false,
isReasoningStreaming: false,
status: MESSAGE_STATUS.LOADING,
}
}
/**
* Build message content with optional images
*/
export function buildMessageContent(
text: string,
imageUrls: string[] = []
): string | ContentPart[] {
const validImages = imageUrls.filter((url) => url.trim() !== '')
if (validImages.length === 0) {
return text
}
const parts: ContentPart[] = [
{
type: 'text',
text: text || '',
},
...validImages.map((url) => ({
type: 'image_url' as const,
image_url: { url: url.trim() },
})),
]
return parts
}
/**
* Extract text content from message content
*/
export function getTextContent(content: string | ContentPart[]): string {
if (typeof content === 'string') {
return content
}
if (Array.isArray(content)) {
const textPart = content.find((part) => part.type === 'text')
return textPart?.text || ''
}
return ''
}
/**
* Format message for API request
*/
export function formatMessageForAPI(message: Message): ChatCompletionMessage {
const currentVersion = getCurrentVersion(message)
return {
role: message.from,
content: currentVersion.content,
}
}
/**
* Check if message is valid for API request
* Excludes loading/streaming assistant messages and empty content
*/
export function isValidMessage(message: Message): boolean {
if (!message || !message.from || !message.versions.length) return false
const content = message.versions[0]?.content
if (content === undefined) return false
// Exclude empty assistant messages (loading/streaming placeholders)
if (message.from === 'assistant' && !content.trim()) return false
return true
}
/**
* Parse content to separate thinking from visible text
* Handles both complete and incomplete <think> tags
*/
export function parseThinkTags(content: string): {
visibleContent: string
reasoning: string
hasUnclosedTag: boolean
} {
if (!content.includes('<think>')) {
return { visibleContent: content, reasoning: '', hasUnclosedTag: false }
}
const visibleParts: string[] = []
const reasoningParts: string[] = []
let currentPos = 0
let hasUnclosed = false
while (true) {
// Find next <think> tag
const openPos = content.indexOf('<think>', currentPos)
if (openPos === -1) {
// No more think tags, add remaining content
if (currentPos < content.length) {
visibleParts.push(content.substring(currentPos))
}
break
}
// Add visible content before this tag
if (openPos > currentPos) {
visibleParts.push(content.substring(currentPos, openPos))
}
// Look for matching </think> tag
const closePos = content.indexOf('</think>', openPos + 7)
if (closePos === -1) {
// Unclosed tag: rest is reasoning buffer
reasoningParts.push(content.substring(openPos + 7))
hasUnclosed = true
break
}
// Extract reasoning content between tags
reasoningParts.push(content.substring(openPos + 7, closePos))
currentPos = closePos + 8
}
return {
visibleContent: visibleParts.join('').trim(),
reasoning: reasoningParts.join('\n\n').trim(),
hasUnclosedTag: hasUnclosed,
}
}
/**
* Update the last assistant message with an error
* @param messages - Current messages array
* @param errorMessage - Error message to display
* @returns Updated messages array
*/
export function updateAssistantMessageWithError(
messages: Message[],
errorMessage: string,
errorCode?: string
): Message[] {
return updateLastAssistantMessage(messages, (message) => {
const updatedMessage = updateCurrentVersionContent(
message,
`${ERROR_MESSAGES.API_REQUEST_ERROR}: ${errorMessage}`
)
return {
...updatedMessage,
status: MESSAGE_STATUS.ERROR,
isReasoningStreaming: false,
errorCode: errorCode || null,
}
})
}
/**
* Helper function to update the last assistant message
* @param messages - Current messages array
* @param updater - Function to update the message
* @returns Updated messages array or original if no assistant message found
*/
export function updateLastAssistantMessage(
messages: Message[],
updater: (message: Message) => Message
): Message[] {
if (messages.length === 0) return messages
const last = messages[messages.length - 1]
if (!last || last.from !== MESSAGE_ROLES.ASSISTANT) return messages
const updated = [...messages]
updated[updated.length - 1] = updater(last)
return updated
}
/**
* Process content chunk during streaming
* Separates <think> reasoning from visible content in real-time
* Note: versions[0].content keeps the full raw content (with tags) during streaming
*/
export function processStreamingContent(
message: Message,
contentChunk?: string
): Message {
const currentVersion = getCurrentVersion(message)
const fullContent = contentChunk
? currentVersion.content + contentChunk
: currentVersion.content
const { reasoning, hasUnclosedTag } = parseThinkTags(fullContent)
// Preserve existing reasoning if no think tags found (e.g., from API reasoning_content)
const finalReasoning = reasoning
? { content: reasoning, duration: 0 }
: message.reasoning
return {
...updateCurrentVersionContent(message, fullContent),
reasoning: finalReasoning,
isReasoningStreaming: hasUnclosedTag,
}
}
/**
* Finalize message after streaming completes
* Cleans content and consolidates reasoning from all sources
*/
export function finalizeMessage(
message: Message,
apiReasoningContent?: string
): Message {
const currentVersion = getCurrentVersion(message)
const { visibleContent, reasoning } = parseThinkTags(currentVersion.content)
// Priority:
// 1. API reasoning_content passed as parameter (non-streaming response)
// 2. Existing message.reasoning (from streaming reasoning_content)
// 3. Extracted think tags from content
const finalReasoning =
apiReasoningContent || message.reasoning?.content || reasoning || ''
return {
...updateCurrentVersionContent(message, visibleContent),
reasoning: finalReasoning
? { content: finalReasoning, duration: message.reasoning?.duration || 0 }
: undefined,
isReasoningStreaming: false,
}
}
/**
* Sanitize messages loaded from storage
* Converts stuck loading/streaming messages to stable state
*/
export function sanitizeMessagesOnLoad(messages: Message[]): Message[] {
let targetIndex = -1
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i]
if (
m?.from === MESSAGE_ROLES.ASSISTANT &&
(m?.status === MESSAGE_STATUS.LOADING ||
m?.status === MESSAGE_STATUS.STREAMING)
) {
targetIndex = i
break
}
}
if (targetIndex === -1) return messages
const finalized = finalizeMessage(messages[targetIndex])
const hasContent = finalized.versions?.[0]?.content?.trim()
const hasReasoning = finalized.reasoning?.content?.trim()
const sanitized: Message =
hasContent || hasReasoning
? {
...finalized,
status: MESSAGE_STATUS.COMPLETE,
isReasoningStreaming: false,
}
: {
...updateCurrentVersionContent(
finalized,
`${ERROR_MESSAGES.API_REQUEST_ERROR}: ${ERROR_MESSAGES.INTERRUPTED}`
),
status: MESSAGE_STATUS.ERROR,
isReasoningStreaming: false,
}
const result = [...messages]
result[targetIndex] = sanitized
return result
}
@@ -0,0 +1,159 @@
import { MESSAGE_ROLES } from '../../constants'
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { Message } from '../../types'
import {
createLoadingAssistantMessage,
createUserMessage,
getMessageContent,
updateCurrentVersionContent,
} from './message-utils'
type ApplyMessageEditResult = {
messages: Message[]
shouldSend: boolean
}
type ChatMessageRenderState = {
alwaysShowActions: boolean
content: string
isEditing: boolean
}
export function appendUserMessagePair(
messages: Message[],
content: string
): Message[] {
const submittedAt = Date.now()
return [
...messages,
createUserMessage(content, submittedAt),
createLoadingAssistantMessage(submittedAt),
]
}
export function createRegeneratedMessages(
messages: Message[],
messageKey: string
): Message[] | null {
const messageIndex = messages.findIndex(
(message) => message.key === messageKey
)
if (messageIndex === -1) {
return null
}
if (messages[messageIndex].from === MESSAGE_ROLES.USER) {
return [
...messages.slice(0, messageIndex + 1),
createLoadingAssistantMessage(),
]
}
return [...messages.slice(0, messageIndex), createLoadingAssistantMessage()]
}
export function removeMessageByKey(
messages: Message[],
messageKey: string
): Message[] {
return messages.filter((message) => message.key !== messageKey)
}
export function getPreviousUserMessage(
messages: Message[],
beforeIndex: number
): Message | null {
for (let index = beforeIndex - 1; index >= 0; index--) {
if (messages[index].from === MESSAGE_ROLES.USER) {
return messages[index]
}
}
return null
}
export function applyMessageEdit(
messages: Message[],
messageKey: string,
content: string,
shouldSubmit: boolean
): ApplyMessageEditResult | null {
const submittedAt = Date.now()
const messageIndex = messages.findIndex(
(message) => message.key === messageKey
)
if (messageIndex === -1) {
return null
}
const updatedMessages = messages.map((message) =>
message.key === messageKey
? {
...updateCurrentVersionContent(message, content),
createdAt: shouldSubmit ? submittedAt : message.createdAt,
}
: message
)
if (
!shouldSubmit ||
updatedMessages[messageIndex].from !== MESSAGE_ROLES.USER
) {
return { messages: updatedMessages, shouldSend: false }
}
return {
messages: [
...updatedMessages.slice(0, messageIndex + 1),
createLoadingAssistantMessage(submittedAt),
],
shouldSend: true,
}
}
export function getEditingMessageContent(
messages: Message[],
editingKey?: string | null
): string {
if (!editingKey) {
return ''
}
const message = messages.find((item) => item.key === editingKey)
return message ? getMessageContent(message) : ''
}
export function getChatMessageRenderState(
messages: Message[],
message: Message,
messageIndex: number,
editingKey?: string | null
): ChatMessageRenderState {
return {
alwaysShowActions:
messageIndex === messages.length - 1 &&
message.from === MESSAGE_ROLES.ASSISTANT,
content: getMessageContent(message),
isEditing: editingKey === message.key,
}
}
@@ -0,0 +1,49 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { MESSAGE_ROLES, MESSAGE_STATUS } from '../../constants'
import type { Message } from '../../types'
import { getMessageContent, hasMessageContent } from './message-utils'
type MessageActionState = {
content: string
hasContent: boolean
isAssistant: boolean
isLoading: boolean
isUser: boolean
}
export function getMessageActionState(message: Message): MessageActionState {
return {
content: getMessageContent(message),
hasContent: hasMessageContent(message),
isAssistant: message.from === MESSAGE_ROLES.ASSISTANT,
isUser: message.from === MESSAGE_ROLES.USER,
isLoading:
message.status === MESSAGE_STATUS.LOADING ||
message.status === MESSAGE_STATUS.STREAMING,
}
}
export function getMessageActionsVisibilityClass(
alwaysVisible: boolean
): string {
return alwaysVisible
? 'opacity-100'
: 'opacity-0 group-hover:opacity-100 max-md:opacity-100'
}
@@ -0,0 +1,115 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { MESSAGE_ROLES, MESSAGE_STATUS } from '../../constants'
import type { Message } from '../../types'
import { parseThinkTags } from './message-reasoning-utils'
type MessageContentStateBase = {
displayContent: string
hasSources: boolean
isAssistant: boolean
showLoader: boolean
showMessageContent: boolean
sources: NonNullable<Message['sources']>
}
type MessageContentState = MessageContentStateBase &
(
| {
hasReasoning: true
reasoningContent: string
}
| {
hasReasoning: false
reasoningContent: undefined
}
)
function shouldShowMessageLoader(
message: Message,
isAssistant: boolean,
versionContent: string
): boolean {
return (
isAssistant &&
!message.isReasoningStreaming &&
(message.status === MESSAGE_STATUS.LOADING ||
(message.status === MESSAGE_STATUS.STREAMING && !versionContent))
)
}
function shouldShowMessageContent(
message: Message,
versionContent: string
): boolean {
return (
(message.from === MESSAGE_ROLES.USER || !message.isReasoningStreaming) &&
versionContent.length > 0
)
}
function getDisplayContent(message: Message, versionContent: string): string {
if (message.from !== MESSAGE_ROLES.ASSISTANT) {
return versionContent
}
if (!versionContent.includes('<think>')) {
return versionContent
}
return parseThinkTags(versionContent).visibleContent
}
export function getMessageContentState(
message: Message,
versionContent: string
): MessageContentState {
const isAssistant = message.from === MESSAGE_ROLES.ASSISTANT
const sources = message.sources ?? []
const reasoningContent = isAssistant ? message.reasoning?.content : undefined
const showLoader = shouldShowMessageLoader(
message,
isAssistant,
versionContent
)
const showMessageContent = shouldShowMessageContent(message, versionContent)
const baseState: MessageContentStateBase = {
displayContent: getDisplayContent(message, versionContent),
hasSources: sources.length > 0,
isAssistant,
showLoader,
showMessageContent,
sources,
}
if (reasoningContent) {
return {
...baseState,
hasReasoning: true,
reasoningContent,
}
}
return {
...baseState,
hasReasoning: false,
reasoningContent: undefined,
}
}
@@ -0,0 +1,41 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { MESSAGE_ROLES } from '../../constants'
import type { Message } from '../../types'
type MessageEditorState = {
canSave: boolean
hasChanged: boolean
showSaveAndSubmit: boolean
}
export function getMessageEditorState(
message: Message,
editText: string,
originalText: string
): MessageEditorState {
const hasText = editText.trim().length > 0
const hasChanged = editText !== originalText
return {
canSave: hasText && hasChanged,
hasChanged,
showSaveAndSubmit: message.from === MESSAGE_ROLES.USER,
}
}
@@ -0,0 +1,59 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { MESSAGE_STATUS } from '../../constants'
import type { Message } from '../../types'
import { getMessageContent } from './message-utils'
export const MODEL_PRICING_SETTINGS_PATH =
'/system-settings/billing/model-pricing'
const MODEL_PRICE_ERROR_CODE = 'model_price_error'
export const FALLBACK_ERROR_CONTENT = 'An unknown error occurred'
type MessageErrorState = {
content: string
kind: 'generic' | 'model-price'
showSettingsLink: boolean
}
export function isAdminRole(role?: number | null): boolean {
return role != null && role >= 10
}
export function isErrorMessage(message: Message): boolean {
return message.status === MESSAGE_STATUS.ERROR
}
export function getMessageErrorState(
message: Message,
isAdmin: boolean
): MessageErrorState | null {
if (!isErrorMessage(message)) {
return null
}
const content = getMessageContent(message) || FALLBACK_ERROR_CONTENT
const isModelPriceError = message.errorCode === MODEL_PRICE_ERROR_CODE
return {
content,
kind: isModelPriceError ? 'model-price' : 'generic',
showSettingsLink: isModelPriceError && isAdmin,
}
}
@@ -0,0 +1,39 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { MESSAGE_ROLES } from '../../constants'
import type { Message, PlaygroundMessageLayoutMode } from '../../types'
export type MessageAlignment = 'left' | 'right'
export function getMessageAlignment(
message: Message,
layoutMode: PlaygroundMessageLayoutMode
): MessageAlignment {
if (layoutMode === 'left') {
return 'left'
}
return message.from === MESSAGE_ROLES.USER ? 'right' : 'left'
}
export function getMessageAlignmentClass(alignment: MessageAlignment): string {
return alignment === 'right'
? 'items-end text-right'
: 'items-start text-left'
}
@@ -0,0 +1,71 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
interface ParsedThinkTags {
visibleContent: string
reasoning: string
hasUnclosedTag: boolean
}
/**
* Parse content to separate thinking from visible text.
* Handles both complete and incomplete <think> tags.
*/
export function parseThinkTags(content: string): ParsedThinkTags {
if (!content.includes('<think>')) {
return { visibleContent: content, reasoning: '', hasUnclosedTag: false }
}
const visibleParts: string[] = []
const reasoningParts: string[] = []
let currentPos = 0
let hasUnclosedTag = false
while (true) {
const openPos = content.indexOf('<think>', currentPos)
if (openPos === -1) {
if (currentPos < content.length) {
visibleParts.push(content.slice(currentPos))
}
break
}
if (openPos > currentPos) {
visibleParts.push(content.slice(currentPos, openPos))
}
const closePos = content.indexOf('</think>', openPos + 7)
if (closePos === -1) {
reasoningParts.push(content.slice(openPos + 7))
hasUnclosedTag = true
break
}
reasoningParts.push(content.slice(openPos + 7, closePos))
currentPos = closePos + 8
}
return {
visibleContent: visibleParts.join('').trim(),
reasoning: reasoningParts.join('\n\n').trim(),
hasUnclosedTag,
}
}
@@ -0,0 +1,256 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { t } from 'i18next'
import { ERROR_MESSAGES, MESSAGE_ROLES, MESSAGE_STATUS } from '../../constants'
import type { ChatCompletionResponse, Message } from '../../types'
import { parseThinkTags } from './message-reasoning-utils'
import {
completeAssistantTiming,
completeReasoningTiming,
startReasoningTiming,
} from './message-timing-utils'
import {
getCurrentVersion,
hasMessageContent,
updateCurrentVersionContent,
} from './message-utils'
/**
* Process content chunk during streaming.
* Separates <think> reasoning from visible content in real-time.
* Note: versions[0].content keeps the full raw content with tags during streaming.
*/
export function processStreamingContent(
message: Message,
contentChunk?: string
): Message {
const currentVersion = getCurrentVersion(message)
const fullContent = contentChunk
? currentVersion.content + contentChunk
: currentVersion.content
if (!message.reasoning && !fullContent.includes('<think>')) {
return {
...updateCurrentVersionContent(message, fullContent),
isReasoningStreaming: false,
}
}
const { reasoning, hasUnclosedTag } = parseThinkTags(fullContent)
const finalReasoning = reasoning
? {
...startReasoningTiming(message),
content: reasoning,
}
: message.reasoning
return {
...updateCurrentVersionContent(message, fullContent),
reasoning: finalReasoning,
isReasoningStreaming: hasUnclosedTag,
}
}
export type StreamChunkType = 'reasoning' | 'content'
function getAppendableChunk(currentContent: string, chunk: string): string {
if (!currentContent || !chunk.startsWith(currentContent)) {
return chunk
}
return chunk.slice(currentContent.length)
}
export function applyStreamingChunk(
message: Message,
type: StreamChunkType,
chunk: string
): Message {
if (message.status === MESSAGE_STATUS.ERROR) {
return message
}
if (type === 'reasoning') {
const reasoning = startReasoningTiming(message)
const appendableChunk = getAppendableChunk(reasoning.content, chunk)
return {
...message,
reasoning: {
...reasoning,
content: reasoning.content + appendableChunk,
},
isReasoningStreaming: true,
status: MESSAGE_STATUS.STREAMING,
}
}
const currentVersion = getCurrentVersion(message)
const appendableChunk = getAppendableChunk(currentVersion.content, chunk)
const contentMessage = processStreamingContent(message, appendableChunk)
return {
...(contentMessage.isReasoningStreaming
? contentMessage
: completeReasoningTiming(contentMessage)),
status: MESSAGE_STATUS.STREAMING,
}
}
/**
* Finalize message after streaming completes.
* Cleans content and consolidates reasoning from all sources.
*/
export function finalizeMessage(
message: Message,
apiReasoningContent?: string
): Message {
const currentVersion = getCurrentVersion(message)
const parsedThinkTags = currentVersion.content.includes('<think>')
? parseThinkTags(currentVersion.content)
: undefined
const visibleContent =
parsedThinkTags?.visibleContent ?? currentVersion.content
const finalReasoning =
apiReasoningContent ||
message.reasoning?.content ||
parsedThinkTags?.reasoning ||
''
const finalized = {
...updateCurrentVersionContent(message, visibleContent),
reasoning: finalReasoning
? {
...startReasoningTiming(message),
content: finalReasoning,
}
: undefined,
isReasoningStreaming: false,
}
return completeReasoningTiming(finalized)
}
export function completeAssistantMessage(message: Message): Message {
return completeAssistantTiming({
...finalizeMessage(message),
status: MESSAGE_STATUS.COMPLETE,
})
}
export function isAssistantMessageFinal(message: Message): boolean {
return (
message.status === MESSAGE_STATUS.COMPLETE ||
message.status === MESSAGE_STATUS.ERROR
)
}
export function isAssistantMessagePending(message: Message): boolean {
return (
message.status === MESSAGE_STATUS.LOADING ||
message.status === MESSAGE_STATUS.STREAMING
)
}
export function isPendingAssistantMessage(message?: Message): boolean {
return Boolean(
message?.from === MESSAGE_ROLES.ASSISTANT &&
isAssistantMessagePending(message)
)
}
type ChatCompletionChoice = ChatCompletionResponse['choices'][number]
export function hasChatCompletionChoice(
response: ChatCompletionResponse
): boolean {
return Boolean(response.choices?.[0])
}
export function applyChatCompletionChoice(
message: Message,
choice: ChatCompletionChoice
): Message {
return completeAssistantTiming({
...finalizeMessage(
updateCurrentVersionContent(message, choice.message?.content || ''),
choice.message?.reasoning_content
),
status: MESSAGE_STATUS.COMPLETE,
})
}
export function applyChatCompletionResponse(
message: Message,
response: ChatCompletionResponse
): Message | null {
const choice = response.choices?.[0]
if (!choice) {
return null
}
return applyChatCompletionChoice(message, choice)
}
/**
* Sanitize messages loaded from storage.
* Converts stuck loading/streaming messages to stable state.
*/
export function sanitizeMessagesOnLoad(messages: Message[]): Message[] {
let targetIndex = -1
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i]
if (isPendingAssistantMessage(message)) {
targetIndex = i
break
}
}
if (targetIndex === -1) return messages
const finalized = finalizeMessage(messages[targetIndex])
const hasContent = hasMessageContent(finalized)
const hasReasoning = finalized.reasoning?.content?.trim()
const sanitized: Message =
hasContent || hasReasoning
? completeAssistantTiming({
...finalized,
status: MESSAGE_STATUS.COMPLETE,
isReasoningStreaming: false,
})
: completeAssistantTiming({
...updateCurrentVersionContent(
finalized,
`${t(ERROR_MESSAGES.API_REQUEST_ERROR)}: ${t(
ERROR_MESSAGES.INTERRUPTED
)}`
),
status: MESSAGE_STATUS.ERROR,
isReasoningStreaming: false,
})
const result = [...messages]
result[targetIndex] = sanitized
return result
}
@@ -22,25 +22,39 @@ For commercial licensing, please contact support@quantumnous.com
*/
export function getMessageContentStyles() {
return [
// Assistant content fills the row; user bubble auto-width
// Assistant content reads like a document column; user bubble stays compact.
'group-[.is-assistant]:w-full',
'group-[.is-assistant]:max-w-none',
'group-[.is-assistant]:max-w-[78ch]',
'group-[.is-user]:w-fit',
// User bubble: rounded and themed background
// User bubble: compact surface that stays calm in both light and dark themes.
'group-[.is-user]:rounded-2xl',
'group-[.is-user]:rounded-br-md',
'group-[.is-user]:border',
'group-[.is-user]:border-border/70',
'group-[.is-user]:bg-muted/70',
'group-[.is-user]:px-4',
'group-[.is-user]:py-2.5',
'group-[.is-user]:text-foreground',
'group-[.is-user]:bg-secondary',
'dark:group-[.is-user]:bg-muted',
'group-[.is-user]:rounded-3xl',
// Assistant bubble: flat serif style (one-sided style)
'group-[.is-assistant]:text-foreground',
'group-[.is-user]:shadow-sm',
'group-[.is-user]:shadow-black/5',
// Assistant response: flat reading surface using the active UI font axis.
'group-[.is-assistant]:bg-transparent',
'group-[.is-assistant]:p-0',
'group-[.is-assistant]:font-serif',
'group-[.is-assistant]:rounded-none',
'group-[.is-assistant]:overflow-visible',
'group-[.is-assistant]:[font-family:var(--font-body)]',
'group-[.is-assistant]:text-foreground/90',
// Preferred readable widths and wrapping
'leading-relaxed',
'text-[0.95rem]',
'leading-6',
'break-words',
'whitespace-pre-wrap',
'sm:text-[0.975rem]',
'sm:leading-7',
// Cap user bubble width so it does not look like a banner
'group-[.is-user]:max-w-[85%]',
'sm:group-[.is-user]:max-w-[62ch]',
@@ -0,0 +1,75 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { MESSAGE_ROLES } from '../../constants'
import type { Message } from '../../types'
export function completeAssistantTiming(
message: Message,
completedAt: number = Date.now()
): Message {
if (message.from !== MESSAGE_ROLES.ASSISTANT) {
return message
}
const startedAt = message.startedAt ?? message.createdAt ?? completedAt
return {
...message,
startedAt,
completedAt,
durationMs: Math.max(0, completedAt - startedAt),
}
}
export function startReasoningTiming(
message: Message,
startedAt: number = Date.now()
): NonNullable<Message['reasoning']> {
return {
content: message.reasoning?.content ?? '',
duration: message.reasoning?.duration ?? 0,
startedAt: message.reasoning?.startedAt ?? startedAt,
completedAt: message.reasoning?.completedAt,
durationMs: message.reasoning?.durationMs,
}
}
export function completeReasoningTiming(
message: Message,
completedAt: number = Date.now()
): Message {
if (!message.reasoning || message.reasoning.durationMs !== undefined) {
return message
}
const startedAt =
message.reasoning.startedAt ?? message.startedAt ?? completedAt
const durationMs = Math.max(0, completedAt - startedAt)
return {
...message,
reasoning: {
...message.reasoning,
startedAt,
completedAt,
durationMs,
duration: Math.ceil(durationMs / 1000),
},
}
}
@@ -0,0 +1,63 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { ERROR_MESSAGES, MESSAGE_ROLES, MESSAGE_STATUS } from '../../constants'
import type { Message } from '../../types'
import { completeAssistantTiming } from './message-timing-utils'
import { updateCurrentVersionContent } from './message-utils'
/**
* Update the last assistant message with an error.
*/
export function updateAssistantMessageWithError(
messages: Message[],
errorMessage: string,
errorCode?: string,
title: string = ERROR_MESSAGES.API_REQUEST_ERROR
): Message[] {
return updateLastAssistantMessage(messages, (message) => {
const updatedMessage = updateCurrentVersionContent(
message,
`${title}: ${errorMessage}`
)
return completeAssistantTiming({
...updatedMessage,
status: MESSAGE_STATUS.ERROR,
isReasoningStreaming: false,
errorCode: errorCode || null,
})
})
}
/**
* Update the most recent assistant message, preserving the array when absent.
*/
export function updateLastAssistantMessage(
messages: Message[],
updater: (message: Message) => Message
): Message[] {
if (messages.length === 0) return messages
const last = messages.at(-1)
if (!last || last.from !== MESSAGE_ROLES.ASSISTANT) return messages
const updated = [...messages]
updated[updated.length - 1] = updater(last)
return updated
}
@@ -0,0 +1,176 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { nanoid } from 'nanoid'
import { MESSAGE_ROLES, MESSAGE_STATUS } from '../../constants'
import type {
Message,
MessageVersion,
ChatCompletionMessage,
ContentPart,
} from '../../types'
/**
* Create a new message version
*/
export function createMessageVersion(content: string): MessageVersion {
return {
id: nanoid(),
content,
}
}
/**
* Get current version from message (always returns the first version)
*/
export function getCurrentVersion(message: Message): MessageVersion {
return message.versions[0] || { id: 'default', content: '' }
}
/**
* Get displayable content from the current message version.
*/
export function getMessageContent(message: Message): string {
return getCurrentVersion(message).content
}
/**
* Check whether a message has non-empty content in its current version.
*/
export function hasMessageContent(message: Message): boolean {
return getMessageContent(message).trim() !== ''
}
/**
* Update current version content in message
*/
export function updateCurrentVersionContent(
message: Message,
content: string
): Message {
const currentVersion = getCurrentVersion(message)
return {
...message,
versions: [{ ...currentVersion, content }],
}
}
/**
* Create a user message
*/
export function createUserMessage(
content: string,
createdAt: number = Date.now()
): Message {
return {
key: nanoid(),
from: MESSAGE_ROLES.USER,
versions: [createMessageVersion(content)],
createdAt,
}
}
/**
* Create a loading assistant message
*/
export function createLoadingAssistantMessage(
startedAt: number = Date.now()
): Message {
return {
key: nanoid(),
from: MESSAGE_ROLES.ASSISTANT,
versions: [createMessageVersion('')],
createdAt: startedAt,
startedAt,
reasoning: undefined,
isReasoningComplete: false,
isContentComplete: false,
isReasoningStreaming: false,
status: MESSAGE_STATUS.LOADING,
}
}
/**
* Build message content with optional images
*/
export function buildMessageContent(
text: string,
imageUrls: string[] = []
): string | ContentPart[] {
const validImages = imageUrls.filter((url) => url.trim() !== '')
if (validImages.length === 0) {
return text
}
const parts: ContentPart[] = [
{
type: 'text',
text: text || '',
},
...validImages.map((url) => ({
type: 'image_url' as const,
image_url: { url: url.trim() },
})),
]
return parts
}
/**
* Extract text content from message content
*/
export function getTextContent(content: string | ContentPart[]): string {
if (typeof content === 'string') {
return content
}
if (Array.isArray(content)) {
const textPart = content.find((part) => part.type === 'text')
return textPart?.text || ''
}
return ''
}
/**
* Format message for API request
*/
export function formatMessageForAPI(message: Message): ChatCompletionMessage {
const currentVersion = getCurrentVersion(message)
return {
role: message.from,
content: currentVersion.content,
}
}
/**
* Check if message is valid for API request
* Excludes loading/streaming assistant messages and empty content
*/
export function isValidMessage(message: Message): boolean {
if (!message || !message.from || !message.versions.length) return false
// Exclude empty assistant messages (loading/streaming placeholders)
if (message.from === MESSAGE_ROLES.ASSISTANT && !hasMessageContent(message)) {
return false
}
return true
}
@@ -0,0 +1,65 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { GroupOption, ModelOption } from '../../types'
export function getModelFallback(
models: ModelOption[],
currentModel: string
): string | null {
const hasCurrentModel = models.some((model) => model.value === currentModel)
if (hasCurrentModel || models.length === 0) {
return null
}
return models[0].value
}
export function shouldClearModelForGroup(
models: ModelOption[],
currentModel: string
): boolean {
if (currentModel === '') {
return false
}
return !models.some((model) => model.value === currentModel)
}
export function getGroupFallback(
groups: GroupOption[],
currentGroup: string
): string | null {
const hasCurrentGroup = groups.some((group) => group.value === currentGroup)
if (hasCurrentGroup || groups.length === 0) {
return null
}
return (
groups.find((group) => group.value === 'default')?.value ?? groups[0].value
)
}
export function getOptionLoadErrorMessage(
error: unknown,
fallbackMessage: string
): string {
return error instanceof Error ? error.message : fallbackMessage
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { DEFAULT_CONFIG, DEFAULT_PARAMETER_ENABLED } from '../../constants'
import type { Message, ParameterEnabled, PlaygroundConfig } from '../../types'
import { loadConfig, loadMessages, loadParameterEnabled } from '../storage/storage'
export type MessageStateUpdater =
| Message[]
| ((previousMessages: Message[]) => Message[])
export function getInitialPlaygroundConfig(): PlaygroundConfig {
return { ...DEFAULT_CONFIG, ...loadConfig() }
}
export function getInitialParameterEnabled(): ParameterEnabled {
return { ...DEFAULT_PARAMETER_ENABLED, ...loadParameterEnabled() }
}
export function getInitialMessages(): Message[] {
return loadMessages() || []
}
export function applyMessageStateUpdate(
previousMessages: Message[],
updater: MessageStateUpdater
): Message[] {
return typeof updater === 'function' ? updater(previousMessages) : updater
}
-133
View File
@@ -1,133 +0,0 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { STORAGE_KEYS } from '../constants'
import type { PlaygroundConfig, ParameterEnabled, Message } from '../types'
import { sanitizeMessagesOnLoad } from './message-utils'
/**
* Load playground config from localStorage
*/
export function loadConfig(): Partial<PlaygroundConfig> {
try {
const saved = localStorage.getItem(STORAGE_KEYS.CONFIG)
if (saved) {
return JSON.parse(saved)
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load config:', error)
}
return {}
}
/**
* Save playground config to localStorage
*/
export function saveConfig(config: Partial<PlaygroundConfig>): void {
try {
localStorage.setItem(STORAGE_KEYS.CONFIG, JSON.stringify(config))
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to save config:', error)
}
}
/**
* Load parameter enabled state from localStorage
*/
export function loadParameterEnabled(): Partial<ParameterEnabled> {
try {
const saved = localStorage.getItem(STORAGE_KEYS.PARAMETER_ENABLED)
if (saved) {
return JSON.parse(saved)
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load parameter enabled:', error)
}
return {}
}
/**
* Save parameter enabled state to localStorage
*/
export function saveParameterEnabled(
parameterEnabled: Partial<ParameterEnabled>
): void {
try {
localStorage.setItem(
STORAGE_KEYS.PARAMETER_ENABLED,
JSON.stringify(parameterEnabled)
)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to save parameter enabled:', error)
}
}
/**
* Load messages from localStorage
*/
export function loadMessages(): Message[] | null {
try {
const saved = localStorage.getItem(STORAGE_KEYS.MESSAGES)
if (saved) {
const parsed: unknown = JSON.parse(saved)
if (!Array.isArray(parsed)) {
return null
}
const sanitized = sanitizeMessagesOnLoad(parsed as Message[])
// Persist sanitized result to avoid re-sanitizing on subsequent loads
if (sanitized !== parsed) {
saveMessages(sanitized)
}
return sanitized
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load messages:', error)
}
return null
}
/**
* Save messages to localStorage
*/
export function saveMessages(messages: Message[]): void {
try {
localStorage.setItem(STORAGE_KEYS.MESSAGES, JSON.stringify(messages))
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to save messages:', error)
}
}
/**
* Clear all playground data
*/
export function clearPlaygroundData(): void {
try {
localStorage.removeItem(STORAGE_KEYS.CONFIG)
localStorage.removeItem(STORAGE_KEYS.PARAMETER_ENABLED)
localStorage.removeItem(STORAGE_KEYS.MESSAGES)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to clear playground data:', error)
}
}
@@ -0,0 +1,91 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { z } from 'zod'
export const STORAGE_VERSION = 1
export const MAX_STORED_MESSAGES = 100
export const MAX_STORED_MESSAGES_BYTES = 1024 * 1024
export const MAX_LOADED_MESSAGES_CHARS = 120_000
export const MAX_LOADED_MESSAGE_CHARS = 40_000
export const playgroundConfigSchema = z.object({
model: z.string().optional(),
group: z.string().optional(),
temperature: z.number().optional(),
top_p: z.number().optional(),
max_tokens: z.number().optional(),
frequency_penalty: z.number().optional(),
presence_penalty: z.number().optional(),
seed: z.number().nullable().optional(),
stream: z.boolean().optional(),
})
export const parameterEnabledSchema = z.object({
temperature: z.boolean().optional(),
top_p: z.boolean().optional(),
max_tokens: z.boolean().optional(),
frequency_penalty: z.boolean().optional(),
presence_penalty: z.boolean().optional(),
seed: z.boolean().optional(),
})
const messageRoleSchema = z.enum(['user', 'assistant', 'system'])
const messageStatusSchema = z.enum([
'loading',
'streaming',
'complete',
'error',
])
const messageVersionSchema = z.object({
id: z.string(),
content: z.string(),
})
const sourceSchema = z.object({
href: z.string(),
title: z.string(),
})
const reasoningSchema = z.object({
content: z.string(),
duration: z.number(),
startedAt: z.number().optional(),
completedAt: z.number().optional(),
durationMs: z.number().optional(),
})
const messageSchema = z.object({
key: z.string(),
from: messageRoleSchema,
versions: z.array(messageVersionSchema).min(1),
createdAt: z.number().optional(),
startedAt: z.number().optional(),
completedAt: z.number().optional(),
durationMs: z.number().optional(),
sources: z.array(sourceSchema).optional(),
reasoning: reasoningSchema.optional(),
isReasoningStreaming: z.boolean().optional(),
isReasoningComplete: z.boolean().optional(),
isContentComplete: z.boolean().optional(),
status: messageStatusSchema.optional(),
errorCode: z.string().nullable().optional(),
})
export const messagesSchema = z.array(messageSchema)
@@ -0,0 +1,398 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { MESSAGE_STATUS, STORAGE_KEYS } from '../../constants'
import type { PlaygroundConfig, ParameterEnabled, Message } from '../../types'
import {
finalizeMessage,
isAssistantMessagePending,
sanitizeMessagesOnLoad,
} from '../message/message-streaming-utils'
import { completeAssistantTiming } from '../message/message-timing-utils'
import { hasMessageContent } from '../message/message-utils'
import {
MAX_LOADED_MESSAGE_CHARS,
MAX_LOADED_MESSAGES_CHARS,
MAX_STORED_MESSAGES,
MAX_STORED_MESSAGES_BYTES,
STORAGE_VERSION,
messagesSchema,
parameterEnabledSchema,
playgroundConfigSchema,
} from './storage-schema'
type StoredEnvelope<T> = {
version: number
data: T
}
const TRUNCATED_CONTENT_SUFFIX = '\n\n[...]'
const MIN_PREFIX_COLLAPSE_LENGTH = 2000
const MIN_REPEATED_SECTION_COUNT = 3
const SECTION_HEADING_LINE_PATTERN = /^#{2,6}\s+\d+\.\s+.+$/gm
function readStoredValue(key: string): unknown | null {
const saved = localStorage.getItem(key)
if (!saved) return null
return JSON.parse(saved) as unknown
}
function readStoredMessagesValue(): unknown | null {
const saved = localStorage.getItem(STORAGE_KEYS.MESSAGES)
if (!saved) return null
if (saved.length > MAX_STORED_MESSAGES_BYTES) {
localStorage.removeItem(STORAGE_KEYS.MESSAGES)
return null
}
return JSON.parse(saved) as unknown
}
function unwrapStoredValue(value: unknown): unknown {
if (!value || typeof value !== 'object') {
return value
}
if ('version' in value && 'data' in value) {
return (value as StoredEnvelope<unknown>).data
}
return value
}
function writeStoredValue<T>(key: string, data: T): void {
const payload: StoredEnvelope<T> = {
version: STORAGE_VERSION,
data,
}
localStorage.setItem(key, JSON.stringify(payload))
}
function trimMessages(messages: Message[]): Message[] {
if (messages.length <= MAX_STORED_MESSAGES) {
return messages
}
return messages.slice(-MAX_STORED_MESSAGES)
}
function getMessageSize(message: Message): number {
const versionsSize = message.versions.reduce(
(total, version) => total + version.content.length,
0
)
const reasoningSize = message.reasoning?.content.length ?? 0
return versionsSize + reasoningSize
}
function truncateText(text: string, maxLength: number): string {
if (text.length <= maxLength) {
return text
}
if (maxLength <= TRUNCATED_CONTENT_SUFFIX.length) {
return text.slice(0, maxLength)
}
return `${text.slice(0, maxLength - TRUNCATED_CONTENT_SUFFIX.length)}${TRUNCATED_CONTENT_SUFFIX}`
}
type SectionOccurrence = {
heading: string
index: number
}
function getSectionOccurrences(text: string): SectionOccurrence[] {
const occurrences: SectionOccurrence[] = []
const matches = text.matchAll(SECTION_HEADING_LINE_PATTERN)
for (const match of matches) {
const index = match.index
if (index === undefined) {
continue
}
occurrences.push({
heading: match[0],
index,
})
}
return occurrences
}
function getHeadingCounts(
occurrences: SectionOccurrence[]
): Map<string, number> {
const counts = new Map<string, number>()
for (const occurrence of occurrences) {
counts.set(occurrence.heading, (counts.get(occurrence.heading) ?? 0) + 1)
}
return counts
}
function findLastRepeatedSectionRunStart(text: string): number {
const occurrences = getSectionOccurrences(text)
const headingCounts = getHeadingCounts(occurrences)
const lastRepeatedIndexes: number[] = []
const seenHeadings = new Set<string>()
for (let index = occurrences.length - 1; index >= 0; index--) {
const occurrence = occurrences[index]
const count = headingCounts.get(occurrence.heading) ?? 0
if (
count < MIN_REPEATED_SECTION_COUNT ||
seenHeadings.has(occurrence.heading)
) {
continue
}
seenHeadings.add(occurrence.heading)
lastRepeatedIndexes.push(occurrence.index)
}
if (lastRepeatedIndexes.length === 0) {
return -1
}
return Math.min(...lastRepeatedIndexes)
}
function collapseRepeatedSectionSnapshots(text: string): string {
if (text.length < MIN_PREFIX_COLLAPSE_LENGTH) {
return text
}
const lastRepeatedRunStart = findLastRepeatedSectionRunStart(text)
if (lastRepeatedRunStart === -1) {
return text
}
return text.slice(lastRepeatedRunStart)
}
function normalizeStoredMessageForLoad(message: Message): Message {
let changed = false
const versions = message.versions.map((version) => {
const collapsedContent = collapseRepeatedSectionSnapshots(version.content)
const content = truncateText(collapsedContent, MAX_LOADED_MESSAGE_CHARS)
if (content === version.content && collapsedContent === version.content) {
return version
}
changed = true
return {
...version,
content,
}
})
const reasoning = message.reasoning
? {
...message.reasoning,
content: truncateText(
message.reasoning.content,
MAX_LOADED_MESSAGE_CHARS
),
}
: undefined
if (reasoning?.content !== message.reasoning?.content) {
changed = true
}
const normalized = changed ? { ...message, versions, reasoning } : message
if (!isAssistantMessagePending(normalized)) {
return normalized
}
const hasContent = hasMessageContent(normalized)
const hasReasoning = normalized.reasoning?.content.trim()
if (!hasContent && !hasReasoning) {
return normalized
}
const completedAt =
normalized.completedAt ??
normalized.reasoning?.completedAt ??
normalized.startedAt ??
normalized.createdAt ??
Date.now()
return completeAssistantTiming(
{
...finalizeMessage(normalized),
status: MESSAGE_STATUS.COMPLETE,
isReasoningStreaming: false,
},
completedAt
)
}
function trimMessagesByContentSize(messages: Message[]): Message[] {
let totalSize = 0
const result: Message[] = []
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index]
const messageSize = getMessageSize(message)
if (
result.length > 0 &&
totalSize + messageSize > MAX_LOADED_MESSAGES_CHARS
) {
break
}
totalSize += messageSize
result.push(message)
}
return result.reverse()
}
/**
* Load playground config from localStorage
*/
export function loadConfig(): Partial<PlaygroundConfig> {
try {
const saved = readStoredValue(STORAGE_KEYS.CONFIG)
if (!saved) return {}
return playgroundConfigSchema.parse(unwrapStoredValue(saved))
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load config:', error)
}
return {}
}
/**
* Save playground config to localStorage
*/
export function saveConfig(config: Partial<PlaygroundConfig>): void {
try {
const parsed = playgroundConfigSchema.parse(config)
writeStoredValue(STORAGE_KEYS.CONFIG, parsed)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to save config:', error)
}
}
/**
* Load parameter enabled state from localStorage
*/
export function loadParameterEnabled(): Partial<ParameterEnabled> {
try {
const saved = readStoredValue(STORAGE_KEYS.PARAMETER_ENABLED)
if (!saved) return {}
return parameterEnabledSchema.parse(unwrapStoredValue(saved))
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load parameter enabled:', error)
}
return {}
}
/**
* Save parameter enabled state to localStorage
*/
export function saveParameterEnabled(
parameterEnabled: Partial<ParameterEnabled>
): void {
try {
const parsed = parameterEnabledSchema.parse(parameterEnabled)
writeStoredValue(STORAGE_KEYS.PARAMETER_ENABLED, parsed)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to save parameter enabled:', error)
}
}
/**
* Load messages from localStorage
*/
export function loadMessages(): Message[] | null {
try {
const saved = readStoredMessagesValue()
if (!saved) return null
const parsed = messagesSchema.parse(unwrapStoredValue(saved)) as Message[]
const normalized = parsed.map(normalizeStoredMessageForLoad)
const normalizedChanged = normalized.some(
(message, index) => message !== parsed[index]
)
const trimmed = trimMessages(normalized)
const sizeTrimmed = trimMessagesByContentSize(trimmed)
const sanitized = sanitizeMessagesOnLoad(sizeTrimmed)
if (
normalizedChanged ||
trimmed !== normalized ||
sizeTrimmed !== trimmed ||
sanitized !== sizeTrimmed
) {
saveMessages(sanitized)
}
return sanitized
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load messages:', error)
}
return null
}
/**
* Save messages to localStorage
*/
export function saveMessages(messages: Message[]): void {
try {
const trimmed = trimMessages(messages)
const parsed = messagesSchema.parse(trimmed) as Message[]
writeStoredValue(STORAGE_KEYS.MESSAGES, parsed)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to save messages:', error)
}
}
/**
* Clear all playground data
*/
export function clearPlaygroundData(): void {
try {
localStorage.removeItem(STORAGE_KEYS.CONFIG)
localStorage.removeItem(STORAGE_KEYS.PARAMETER_ENABLED)
localStorage.removeItem(STORAGE_KEYS.MESSAGES)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to clear playground data:', error)
}
}
@@ -21,8 +21,8 @@ import type {
Message,
PlaygroundConfig,
ParameterEnabled,
} from '../types'
import { formatMessageForAPI, isValidMessage } from './message-utils'
} from '../../types'
import { formatMessageForAPI, isValidMessage } from '../message/message-utils'
/**
* Build API request payload from messages and config
@@ -44,24 +44,29 @@ export function buildChatCompletionPayload(
stream: config.stream,
}
// Add enabled parameters
const parameterKeys: Array<keyof ParameterEnabled> = [
'temperature',
'top_p',
'max_tokens',
'frequency_penalty',
'presence_penalty',
'seed',
]
if (parameterEnabled.temperature) {
payload.temperature = config.temperature
}
parameterKeys.forEach((key) => {
if (parameterEnabled[key]) {
const value = config[key as keyof PlaygroundConfig]
if (value !== undefined && value !== null) {
;(payload as unknown as Record<string, unknown>)[key] = value
}
}
})
if (parameterEnabled.top_p) {
payload.top_p = config.top_p
}
if (parameterEnabled.max_tokens) {
payload.max_tokens = config.max_tokens
}
if (parameterEnabled.frequency_penalty) {
payload.frequency_penalty = config.frequency_penalty
}
if (parameterEnabled.presence_penalty) {
payload.presence_penalty = config.presence_penalty
}
if (parameterEnabled.seed && config.seed !== null) {
payload.seed = config.seed
}
return payload
}
@@ -0,0 +1,48 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { ERROR_MESSAGES } from '../../constants'
type RequestErrorLike = {
message?: string
response?: {
data?: {
error?: {
code?: string
}
message?: string
}
}
}
export type RequestErrorDetails = {
errorCode?: string
errorMessage: string
}
export function parseRequestErrorDetails(error: unknown): RequestErrorDetails {
const requestError = error as RequestErrorLike
return {
errorCode: requestError?.response?.data?.error?.code || undefined,
errorMessage:
requestError?.response?.data?.message ||
requestError?.message ||
ERROR_MESSAGES.API_REQUEST_ERROR,
}
}
@@ -0,0 +1,112 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { ERROR_MESSAGES } from '../../constants'
import type { ChatCompletionChunk } from '../../types'
const STREAM_DONE_MESSAGE = '[DONE]'
const STREAM_CLOSED_READY_STATE = 2
export type StreamUpdateType = 'reasoning' | 'content'
export type StreamMessageUpdate = {
type: StreamUpdateType
chunk: string
}
type StreamErrorPayload = {
error?: {
code?: string
message?: string
}
}
export type StreamErrorDetails = {
errorCode?: string
errorMessage: string
}
export function parseStreamErrorDetails(data?: string): StreamErrorDetails {
const fallbackMessage = data || ERROR_MESSAGES.API_REQUEST_ERROR
if (!data) {
return { errorMessage: fallbackMessage }
}
try {
const parsed = JSON.parse(data) as StreamErrorPayload
if (!parsed?.error) {
return { errorMessage: fallbackMessage }
}
return {
errorCode: parsed.error.code || undefined,
errorMessage: parsed.error.message || fallbackMessage,
}
} catch {
return { errorMessage: fallbackMessage }
}
}
export function parseStreamMessageUpdates(data: string): StreamMessageUpdate[] {
const chunk = JSON.parse(data) as ChatCompletionChunk
const delta = chunk.choices?.[0]?.delta
if (!delta) {
return []
}
const updates: StreamMessageUpdate[] = []
if (delta.reasoning_content) {
updates.push({ type: 'reasoning', chunk: delta.reasoning_content })
}
if (delta.content) {
updates.push({ type: 'content', chunk: delta.content })
}
return updates
}
export function isStreamDoneMessage(data: string): boolean {
return data === STREAM_DONE_MESSAGE
}
export function isStreamClosedReadyState(readyState?: number): boolean {
return readyState === STREAM_CLOSED_READY_STATE
}
export function getStreamReadyStateError(
eventReadyState: number | undefined,
source: unknown
): string | null {
const status = (source as { status?: number }).status
if (
eventReadyState !== undefined &&
eventReadyState >= STREAM_CLOSED_READY_STATE &&
status !== undefined &&
status !== 200
) {
return `HTTP ${status}: ${ERROR_MESSAGES.CONNECTION_CLOSED}`
}
return null
}
+9
View File
@@ -21,6 +21,8 @@ export type MessageRole = 'user' | 'assistant' | 'system'
export type MessageStatus = 'loading' | 'streaming' | 'complete' | 'error'
export type PlaygroundMessageLayoutMode = 'alternating' | 'left'
export interface MessageVersion {
id: string
content: string
@@ -30,10 +32,17 @@ export interface Message {
key: string
from: MessageRole
versions: MessageVersion[]
createdAt?: number
startedAt?: number
completedAt?: number
durationMs?: number
sources?: { href: string; title: string }[]
reasoning?: {
content: string
duration: number
startedAt?: number
completedAt?: number
durationMs?: number
}
isReasoningStreaming?: boolean
isReasoningComplete?: boolean