First commit.

This commit is contained in:
emil
2026-04-26 14:52:50 +03:00
commit 1ff8c733cc
27 changed files with 7017 additions and 0 deletions
+86
View File
@@ -0,0 +1,86 @@
import { useEffect, useRef } from 'react';
import { useChatStore } from '@/stores/chatStore';
import Sidebar from '@/components/layout/Sidebar';
import ChatArea from '@/components/chat/ChatArea';
import SettingsModal from '@/components/chat/SettingsModal';
import { Menu, Settings } from 'lucide-react';
function App() {
const {
conversations,
currentConversationId,
isSidebarOpen,
isSettingsOpen,
createConversation,
toggleSidebar,
toggleSettings,
} = useChatStore();
const initialized = useRef(false);
useEffect(() => {
if (!initialized.current && conversations.length === 0) {
initialized.current = true;
createConversation();
}
}, [conversations.length, createConversation]);
return (
<div className="flex h-screen w-screen overflow-hidden bg-[var(--color-bg)]">
{/* Mobile sidebar overlay */}
{isSidebarOpen && (
<div
className="fixed inset-0 bg-black/50 z-30 lg:hidden"
onClick={toggleSidebar}
/>
)}
{/* Sidebar */}
<aside
className={`fixed lg:static inset-y-0 left-0 z-40 w-72 bg-[var(--color-surface)] border-r border-[var(--color-border)] transform transition-transform duration-300 ease-in-out ${
isSidebarOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0 lg:hidden'
}`}
>
<Sidebar />
</aside>
{/* Main Content */}
<main className="flex-1 flex flex-col min-w-0">
{/* Header */}
<header className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border)] bg-[var(--color-bg)]">
<div className="flex items-center gap-3">
<button
onClick={toggleSidebar}
className="p-2 rounded-lg hover:bg-[var(--color-surface-hover)] text-[var(--color-text-secondary)] hover:text-[var(--color-text)] transition-colors lg:hidden"
>
<Menu size={20} />
</button>
<h1 className="text-lg font-semibold text-[var(--color-text)] truncate">
AIUI Chat
</h1>
</div>
<button
onClick={toggleSettings}
className="p-2 rounded-lg hover:bg-[var(--color-surface-hover)] text-[var(--color-text-secondary)] hover:text-[var(--color-text)] transition-colors"
>
<Settings size={20} />
</button>
</header>
{/* Chat Area */}
{currentConversationId ? (
<ChatArea conversationId={currentConversationId} />
) : (
<div className="flex-1 flex items-center justify-center text-[var(--color-text-muted)]">
<p>Select or create a conversation to start chatting</p>
</div>
)}
</main>
{/* Settings Modal */}
{isSettingsOpen && <SettingsModal />}
</div>
);
}
export default App;
+132
View File
@@ -0,0 +1,132 @@
import { useRef, useCallback } from 'react';
import { useChatStore } from '@/stores/chatStore';
import { streamChatCompletion } from '@/services/api';
import type { Message } from '@/types';
import MessageList from './MessageList';
import ChatInput from './ChatInput';
interface ChatAreaProps {
conversationId: string;
}
export default function ChatArea({ conversationId }: ChatAreaProps) {
const {
getCurrentConversation,
addMessage,
updateMessage,
setLoading,
settings,
} = useChatStore();
const abortControllerRef = useRef<AbortController | null>(null);
const messagesRef = useRef<Message[]>([]);
const conversation = getCurrentConversation();
messagesRef.current = conversation?.messages || [];
const handleSendMessage = useCallback(
async (content: string) => {
if (!content.trim() || !settings.apiUrl || !settings.apiKey || !settings.model) {
return;
}
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
const userMessage: Message = {
id: Date.now().toString(36),
role: 'user',
content: content.trim(),
timestamp: Date.now(),
};
addMessage(conversationId, userMessage);
setLoading(true);
const assistantMessageId = Date.now().toString(36) + 'a';
const assistantMessage: Message = {
id: assistantMessageId,
role: 'assistant',
content: '',
timestamp: Date.now(),
isStreaming: true,
};
addMessage(conversationId, assistantMessage);
abortControllerRef.current = new AbortController();
let fullContent = '';
try {
const stream = streamChatCompletion(
[...messagesRef.current, userMessage],
settings.apiUrl,
settings.apiKey,
settings.model,
settings.temperature,
settings.maxTokens,
settings.systemPrompt,
abortControllerRef.current.signal
);
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
fullContent += content;
updateMessage(conversationId, assistantMessageId, {
content: fullContent,
});
}
}
updateMessage(conversationId, assistantMessageId, {
isStreaming: false,
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
if (errorMessage.includes('aborted')) {
updateMessage(conversationId, assistantMessageId, {
isStreaming: false,
});
} else {
updateMessage(conversationId, assistantMessageId, {
content: fullContent || `Error: ${errorMessage}`,
isStreaming: false,
error: errorMessage,
});
}
} finally {
setLoading(false);
abortControllerRef.current = null;
}
},
[conversationId, settings, addMessage, updateMessage, setLoading]
);
const handleStop = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
}, []);
if (!conversation) {
return (
<div className="flex-1 flex items-center justify-center text-[var(--color-text-muted)]">
Conversation not found
</div>
);
}
return (
<div className="flex-1 flex flex-col min-h-0">
<MessageList messages={conversation.messages} />
<ChatInput
onSend={handleSendMessage}
onStop={handleStop}
disabled={!settings.apiUrl || !settings.apiKey || !settings.model}
/>
</div>
);
}
@@ -0,0 +1,86 @@
import { useState, useRef, useCallback } from 'react';
import { Send, Square } from 'lucide-react';
import { useChatStore } from '@/stores/chatStore';
interface ChatInputProps {
onSend: (message: string) => void;
onStop: () => void;
disabled?: boolean;
}
export default function ChatInput({ onSend, onStop, disabled }: ChatInputProps) {
const [input, setInput] = useState('');
const textareaRef = useRef<HTMLTextAreaElement>(null);
const { isLoading } = useChatStore();
const handleSubmit = useCallback(() => {
if (!input.trim() || isLoading) return;
onSend(input);
setInput('');
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
}
}, [input, isLoading, onSend]);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit();
}
};
const handleInput = (e: React.FormEvent<HTMLTextAreaElement>) => {
const target = e.currentTarget;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 200) + 'px';
};
return (
<div className="border-t border-[var(--color-border)] bg-[var(--color-bg)] p-4">
<div className="max-w-4xl mx-auto">
{disabled && (
<div className="mb-2 text-xs text-center text-amber-400 bg-amber-400/10 rounded-lg py-2 px-3">
Please configure API settings (URL, Key, and Model) in the settings menu to start chatting
</div>
)}
<div className="flex items-end gap-2 bg-[var(--color-surface)] border border-[var(--color-border)] rounded-2xl p-2 focus-within:ring-2 focus-within:ring-primary-500/50 focus-within:border-primary-500 transition-all">
<textarea
ref={textareaRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onInput={handleInput}
placeholder={disabled ? 'Configure API settings first...' : 'Type a message...'}
disabled={disabled || isLoading}
rows={1}
className="flex-1 bg-transparent border-none outline-none resize-none px-3 py-2 text-[var(--color-text)] placeholder-[var(--color-text-muted)] max-h-[200px] min-h-[40px] disabled:opacity-50"
/>
{isLoading ? (
<button
onClick={onStop}
className="p-2.5 rounded-xl bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors shrink-0"
title="Stop generating"
>
<Square size={18} fill="currentColor" />
</button>
) : (
<button
onClick={handleSubmit}
disabled={!input.trim() || disabled}
className="p-2.5 rounded-xl bg-[var(--color-accent)] text-white hover:bg-[var(--color-accent-hover)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors shrink-0"
title="Send message"
>
<Send size={18} />
</button>
)}
</div>
<p className="text-center text-xs text-[var(--color-text-muted)] mt-2">
Press Enter to send, Shift+Enter for new line
</p>
</div>
</div>
);
}
@@ -0,0 +1,112 @@
import { useEffect, useRef } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { User, Bot, AlertCircle } from 'lucide-react';
import type { Message } from '@/types';
interface MessageListProps {
messages: Message[];
}
export default function MessageList({ messages }: MessageListProps) {
const bottomRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
const formatTime = (timestamp: number) => {
return new Date(timestamp).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
});
};
return (
<div
ref={containerRef}
className="flex-1 overflow-y-auto p-4 space-y-6 scroll-smooth"
>
{messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-[var(--color-text-muted)] space-y-4">
<Bot size={48} className="opacity-50" />
<div className="text-center space-y-2">
<h3 className="text-lg font-medium text-[var(--color-text)]">
Welcome to AIUI Chat
</h3>
<p className="text-sm max-w-md">
Start a conversation by typing a message below. Make sure to configure your API settings first.
</p>
</div>
</div>
) : (
messages.map((message) => (
<div
key={message.id}
className={`flex gap-4 ${
message.role === 'user' ? 'flex-row-reverse' : 'flex-row'
}`}
>
{/* Avatar */}
<div
className={`shrink-0 w-8 h-8 rounded-full flex items-center justify-center ${
message.role === 'user'
? 'bg-[var(--color-user-msg)]'
: 'bg-[var(--color-ai-msg)] border border-[var(--color-border)]'
}`}
>
{message.role === 'user' ? (
<User size={16} className="text-white" />
) : (
<Bot size={16} className="text-[var(--color-text-secondary)]" />
)}
</div>
{/* Message Content */}
<div
className={`flex-1 max-w-[85%] lg:max-w-[75%] space-y-1 ${
message.role === 'user' ? 'items-end' : 'items-start'
}`}
>
<div
className={`relative px-4 py-3 rounded-2xl ${
message.role === 'user'
? 'bg-[var(--color-user-msg)] text-white rounded-br-md'
: 'bg-[var(--color-ai-msg)] border border-[var(--color-border)] text-[var(--color-text)] rounded-bl-md'
}`}
>
{message.role === 'user' ? (
<p className="whitespace-pre-wrap text-sm">{message.content}</p>
) : (
<div className="markdown-body text-sm">
{message.content ? (
<ReactMarkdown remarkPlugins={[remarkGfm]}>
{message.content}
</ReactMarkdown>
) : message.isStreaming ? (
<span className="animate-pulse"></span>
) : null}
</div>
)}
{message.error && (
<div className="flex items-center gap-2 mt-2 text-red-400 text-xs">
<AlertCircle size={14} />
<span>{message.error}</span>
</div>
)}
</div>
<span className="text-xs text-[var(--color-text-muted)] px-1">
{formatTime(message.timestamp)}
{message.isStreaming && ' · typing...'}
</span>
</div>
</div>
))
)}
<div ref={bottomRef} />
</div>
);
}
@@ -0,0 +1,236 @@
import { useState, useEffect } from 'react';
import { X, RefreshCw, Eye, EyeOff } from 'lucide-react';
import { useChatStore } from '@/stores/chatStore';
import { fetchModels } from '@/services/api';
export default function SettingsModal() {
const { settings, updateSettings, toggleSettings, closeSettings } = useChatStore();
const [localSettings, setLocalSettings] = useState(settings);
const [models, setModels] = useState<string[]>([]);
const [isLoadingModels, setIsLoadingModels] = useState(false);
const [showApiKey, setShowApiKey] = useState(false);
const [error, setError] = useState('');
const handleSave = () => {
updateSettings(localSettings);
toggleSettings();
};
const handleLoadModels = async () => {
if (!localSettings.apiUrl || !localSettings.apiKey) {
setError('Please fill in API URL and API Key first');
return;
}
setError('');
setIsLoadingModels(true);
try {
const modelList = await fetchModels(localSettings.apiUrl, localSettings.apiKey);
setModels(modelList);
if (modelList.length > 0 && !localSettings.model) {
setLocalSettings((prev) => ({ ...prev, model: modelList[0] }));
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load models');
} finally {
setIsLoadingModels(false);
}
};
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') closeSettings();
};
document.addEventListener('keydown', handleEscape);
return () => document.removeEventListener('keydown', handleEscape);
}, [closeSettings]);
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<div
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
onClick={toggleSettings}
/>
<div className="relative bg-[var(--color-surface)] border border-[var(--color-border)] rounded-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto shadow-2xl">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-[var(--color-border)]">
<h2 className="text-xl font-semibold text-[var(--color-text)]">Settings</h2>
<button
onClick={toggleSettings}
className="p-2 rounded-lg hover:bg-[var(--color-surface-hover)] text-[var(--color-text-secondary)] hover:text-[var(--color-text)] transition-colors"
>
<X size={20} />
</button>
</div>
{/* Content */}
<div className="p-6 space-y-5">
{error && (
<div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-sm">
{error}
</div>
)}
{/* API URL */}
<div className="space-y-2">
<label className="text-sm font-medium text-[var(--color-text-secondary)]">
API Base URL
</label>
<input
type="text"
value={localSettings.apiUrl}
onChange={(e) => setLocalSettings((prev) => ({ ...prev, apiUrl: e.target.value }))}
placeholder="https://api.openai.com/v1"
className="input-field"
/>
<p className="text-xs text-[var(--color-text-muted)]">
e.g. https://api.openai.com/v1 or your local OpenAI-compatible endpoint
</p>
</div>
{/* API Key */}
<div className="space-y-2">
<label className="text-sm font-medium text-[var(--color-text-secondary)]">
API Key
</label>
<div className="relative">
<input
type={showApiKey ? 'text' : 'password'}
value={localSettings.apiKey}
onChange={(e) => setLocalSettings((prev) => ({ ...prev, apiKey: e.target.value }))}
placeholder="sk-..."
className="input-field pr-10"
/>
<button
onClick={() => setShowApiKey(!showApiKey)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] hover:text-[var(--color-text)] transition-colors"
>
{showApiKey ? <EyeOff size={18} /> : <Eye size={18} />}
</button>
</div>
</div>
{/* Model */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium text-[var(--color-text-secondary)]">
Model
</label>
<button
onClick={handleLoadModels}
disabled={isLoadingModels}
className="flex items-center gap-1.5 text-xs text-primary-400 hover:text-primary-300 transition-colors disabled:opacity-50"
>
<RefreshCw size={14} className={isLoadingModels ? 'animate-spin' : ''} />
{isLoadingModels ? 'Loading...' : 'Load models'}
</button>
</div>
{models.length > 0 ? (
<select
value={localSettings.model}
onChange={(e) => setLocalSettings((prev) => ({ ...prev, model: e.target.value }))}
className="input-field"
>
<option value="">Select a model</option>
{models.map((model) => (
<option key={model} value={model}>
{model}
</option>
))}
</select>
) : (
<input
type="text"
value={localSettings.model}
onChange={(e) => setLocalSettings((prev) => ({ ...prev, model: e.target.value }))}
placeholder="gpt-4, claude-3-opus, etc."
className="input-field"
/>
)}
</div>
{/* Temperature */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium text-[var(--color-text-secondary)]">
Temperature
</label>
<span className="text-xs text-[var(--color-text-muted)]">
{localSettings.temperature}
</span>
</div>
<input
type="range"
min="0"
max="2"
step="0.1"
value={localSettings.temperature}
onChange={(e) =>
setLocalSettings((prev) => ({ ...prev, temperature: parseFloat(e.target.value) }))
}
className="w-full accent-primary-500"
/>
<div className="flex justify-between text-xs text-[var(--color-text-muted)]">
<span>Precise (0)</span>
<span>Balanced (1)</span>
<span>Creative (2)</span>
</div>
</div>
{/* Max Tokens */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium text-[var(--color-text-secondary)]">
Max Tokens
</label>
<span className="text-xs text-[var(--color-text-muted)]">
{localSettings.maxTokens}
</span>
</div>
<input
type="range"
min="256"
max="8192"
step="256"
value={localSettings.maxTokens}
onChange={(e) =>
setLocalSettings((prev) => ({ ...prev, maxTokens: parseInt(e.target.value) }))
}
className="w-full accent-primary-500"
/>
</div>
{/* System Prompt */}
<div className="space-y-2">
<label className="text-sm font-medium text-[var(--color-text-secondary)]">
System Prompt
</label>
<textarea
value={localSettings.systemPrompt}
onChange={(e) =>
setLocalSettings((prev) => ({ ...prev, systemPrompt: e.target.value }))
}
placeholder="You are a helpful assistant."
rows={3}
className="input-field resize-none"
/>
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-end gap-3 p-6 border-t border-[var(--color-border)]">
<button
onClick={toggleSettings}
className="px-4 py-2 rounded-lg text-[var(--color-text-secondary)] hover:text-[var(--color-text)] hover:bg-[var(--color-surface-hover)] transition-colors"
>
Cancel
</button>
<button onClick={handleSave} className="btn-primary">
Save Settings
</button>
</div>
</div>
</div>
);
}
+107
View File
@@ -0,0 +1,107 @@
import { useChatStore } from '@/stores/chatStore';
import { Plus, Trash2, MessageSquare, ChevronLeft } from 'lucide-react';
export default function Sidebar() {
const {
conversations,
currentConversationId,
createConversation,
selectConversation,
deleteConversation,
toggleSidebar,
} = useChatStore();
const handleDelete = (e: React.MouseEvent, id: string) => {
e.stopPropagation();
if (confirm('Delete this conversation?')) {
deleteConversation(id);
}
};
const formatDate = (timestamp: number) => {
const date = new Date(timestamp);
const now = new Date();
const diff = now.getTime() - date.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days === 0) {
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
} else if (days === 1) {
return 'Yesterday';
} else if (days < 7) {
return date.toLocaleDateString([], { weekday: 'short' });
} else {
return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
}
};
return (
<div className="flex flex-col h-full">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-[var(--color-border)]">
<h2 className="text-sm font-semibold text-[var(--color-text-secondary)] uppercase tracking-wider">
Conversations
</h2>
<div className="flex items-center gap-1">
<button
onClick={() => createConversation()}
className="p-1.5 rounded-lg hover:bg-[var(--color-surface-hover)] text-[var(--color-text-secondary)] hover:text-[var(--color-text)] transition-colors"
title="New Chat"
>
<Plus size={18} />
</button>
<button
onClick={toggleSidebar}
className="p-1.5 rounded-lg hover:bg-[var(--color-surface-hover)] text-[var(--color-text-secondary)] hover:text-[var(--color-text)] transition-colors lg:hidden"
>
<ChevronLeft size={18} />
</button>
</div>
</div>
{/* Conversation List */}
<div className="flex-1 overflow-y-auto p-2 space-y-1">
{conversations.length === 0 ? (
<div className="text-center py-8 text-[var(--color-text-muted)] text-sm">
No conversations yet
</div>
) : (
conversations.map((conversation) => (
<div
key={conversation.id}
onClick={() => selectConversation(conversation.id)}
className={`sidebar-item group ${
conversation.id === currentConversationId ? 'active' : ''
}`}
>
<MessageSquare size={16} className="shrink-0" />
<div className="flex-1 min-w-0">
<p className="truncate font-medium">{conversation.title}</p>
<p className="text-xs text-[var(--color-text-muted)]">
{conversation.messages.length} messages · {formatDate(conversation.updatedAt)}
</p>
</div>
<button
onClick={(e) => handleDelete(e, conversation.id)}
className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-red-500/20 hover:text-red-400 text-[var(--color-text-muted)] transition-all"
>
<Trash2 size={14} />
</button>
</div>
))
)}
</div>
{/* Footer */}
<div className="p-4 border-t border-[var(--color-border)]">
<button
onClick={() => createConversation()}
className="w-full btn-primary flex items-center justify-center gap-2"
>
<Plus size={18} />
New Chat
</button>
</div>
</div>
);
}
+72
View File
@@ -0,0 +1,72 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--color-bg: #1f232e;
--color-surface: #2a2f3d;
--color-surface-hover: #343b4a;
--color-border: #3a4356;
--color-text: #eceef2;
--color-text-secondary: #b0bac9;
--color-text-muted: #8694ab;
--color-accent: #3b82f6;
--color-accent-hover: #2563eb;
--color-user-msg: #2563eb;
--color-ai-msg: #2a2f3d;
}
* {
scrollbar-width: thin;
scrollbar-color: #3a4356 transparent;
}
*::-webkit-scrollbar {
width: 6px;
}
*::-webkit-scrollbar-track {
background: transparent;
}
*::-webkit-scrollbar-thumb {
background-color: #3a4356;
border-radius: 3px;
}
body {
@apply bg-[var(--color-bg)] text-[var(--color-text)] antialiased;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
}
}
@layer components {
.markdown-body {
@apply prose prose-invert max-w-none;
@apply prose-p:my-2 prose-headings:my-3;
@apply prose-pre:bg-[#1a1d26] prose-pre:border prose-pre:border-[var(--color-border)];
@apply prose-code:text-primary-300;
@apply prose-blockquote:border-l-primary-500 prose-blockquote:bg-[#1a1d26] prose-blockquote:py-1 prose-blockquote:px-3 prose-blockquote:rounded-r;
@apply prose-a:text-primary-400 prose-a:no-underline hover:prose-a:text-primary-300;
@apply prose-ul:my-2 prose-ol:my-2;
@apply prose-li:my-0.5;
@apply prose-table:border prose-table:border-[var(--color-border)] prose-th:bg-[#1a1d26] prose-th:border prose-th:border-[var(--color-border)] prose-td:border prose-td:border-[var(--color-border)];
}
.btn-primary {
@apply px-4 py-2 bg-[var(--color-accent)] hover:bg-[var(--color-accent-hover)] text-white rounded-lg transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed;
}
.input-field {
@apply w-full px-4 py-2.5 bg-[var(--color-surface)] border border-[var(--color-border)] rounded-lg text-[var(--color-text)] placeholder-[var(--color-text-muted)] focus:outline-none focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 transition-all;
}
.sidebar-item {
@apply flex items-center gap-3 px-3 py-2.5 rounded-lg text-[var(--color-text-secondary)] hover:text-[var(--color-text)] hover:bg-[var(--color-surface-hover)] transition-all cursor-pointer text-sm;
}
.sidebar-item.active {
@apply bg-[var(--color-surface-hover)] text-[var(--color-text)];
}
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
+94
View File
@@ -0,0 +1,94 @@
import type { Message, OpenAIMessage, OpenAIStreamChunk } from '@/types';
export async function* streamChatCompletion(
messages: Message[],
apiUrl: string,
apiKey: string,
model: string,
temperature: number,
maxTokens: number,
systemPrompt: string,
abortSignal: AbortSignal
): AsyncGenerator<OpenAIStreamChunk, void, unknown> {
const formattedMessages: OpenAIMessage[] = [
{ role: 'system', content: systemPrompt },
...messages.map((m) => ({ role: m.role, content: m.content }) as OpenAIMessage),
];
const response = await fetch('/api/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
apiUrl,
apiKey,
model,
temperature,
max_tokens: maxTokens,
messages: formattedMessages,
stream: true,
}),
signal: abortSignal,
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error?.message || `HTTP error! status: ${response.status}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('No response body');
}
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed === 'data: [DONE]') continue;
if (trimmed.startsWith('data: ')) {
try {
const data: OpenAIStreamChunk = JSON.parse(trimmed.slice(6));
yield data;
} catch {
// Ignore parse errors for incomplete chunks
}
}
}
}
} finally {
reader.releaseLock();
}
}
export async function fetchModels(
apiUrl: string,
apiKey: string
): Promise<string[]> {
const response = await fetch('/api/v1/models', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ apiUrl, apiKey }),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error?.message || `HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.models || [];
}
+161
View File
@@ -0,0 +1,161 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { Conversation, Message, ChatSettings } from '@/types';
interface ChatState {
conversations: Conversation[];
currentConversationId: string | null;
isSidebarOpen: boolean;
isSettingsOpen: boolean;
isLoading: boolean;
settings: ChatSettings;
// Actions
createConversation: () => string;
selectConversation: (id: string) => void;
deleteConversation: (id: string) => void;
updateConversationTitle: (id: string, title: string) => void;
addMessage: (conversationId: string, message: Message) => void;
updateMessage: (conversationId: string, messageId: string, updates: Partial<Message>) => void;
toggleSidebar: () => void;
closeSettings: () => void;
toggleSettings: () => void;
setLoading: (loading: boolean) => void;
updateSettings: (settings: Partial<ChatSettings>) => void;
getCurrentConversation: () => Conversation | undefined;
}
const generateId = () => Date.now().toString(36) + Math.random().toString(36).substr(2);
const defaultSettings: ChatSettings = {
apiUrl: '',
apiKey: '',
model: '',
temperature: 0.7,
maxTokens: 4096,
systemPrompt: 'You are a helpful assistant.',
};
export const useChatStore = create<ChatState>()(
persist(
(set, get) => ({
conversations: [],
currentConversationId: null,
isSidebarOpen: true,
isSettingsOpen: false,
isLoading: false,
settings: defaultSettings,
createConversation: () => {
const id = generateId();
const newConversation: Conversation = {
id,
title: 'New Chat',
messages: [],
createdAt: Date.now(),
updatedAt: Date.now(),
};
set((state) => ({
conversations: [newConversation, ...state.conversations],
currentConversationId: id,
}));
return id;
},
selectConversation: (id) => {
set({ currentConversationId: id });
},
deleteConversation: (id) => {
set((state) => {
const newConversations = state.conversations.filter((c) => c.id !== id);
const newCurrentId =
state.currentConversationId === id
? newConversations[0]?.id || null
: state.currentConversationId;
return {
conversations: newConversations,
currentConversationId: newCurrentId,
};
});
},
updateConversationTitle: (id, title) => {
set((state) => ({
conversations: state.conversations.map((c) =>
c.id === id ? { ...c, title, updatedAt: Date.now() } : c
),
}));
},
addMessage: (conversationId, message) => {
set((state) => ({
conversations: state.conversations.map((c) =>
c.id === conversationId
? {
...c,
messages: [...c.messages, message],
updatedAt: Date.now(),
title:
c.title === 'New Chat' && message.role === 'user'
? message.content.slice(0, 50) + (message.content.length > 50 ? '...' : '')
: c.title,
}
: c
),
}));
},
updateMessage: (conversationId, messageId, updates) => {
set((state) => ({
conversations: state.conversations.map((c) =>
c.id === conversationId
? {
...c,
messages: c.messages.map((m) =>
m.id === messageId ? { ...m, ...updates } : m
),
}
: c
),
}));
},
toggleSidebar: () => {
set((state) => ({ isSidebarOpen: !state.isSidebarOpen }));
},
closeSettings: () => {
set({ isSettingsOpen: false });
},
toggleSettings: () => {
set((state) => ({ isSettingsOpen: !state.isSettingsOpen }));
},
setLoading: (loading) => {
set({ isLoading: loading });
},
updateSettings: (newSettings) => {
set((state) => ({
settings: { ...state.settings, ...newSettings },
}));
},
getCurrentConversation: () => {
const { conversations, currentConversationId } = get();
return conversations.find((c) => c.id === currentConversationId);
},
}),
{
name: 'aiui-chat-storage',
partialize: (state) => ({
conversations: state.conversations,
currentConversationId: state.currentConversationId,
settings: state.settings,
isSidebarOpen: state.isSidebarOpen,
}),
}
)
);
+46
View File
@@ -0,0 +1,46 @@
export interface Message {
id: string;
role: 'user' | 'assistant' | 'system';
content: string;
timestamp: number;
isStreaming?: boolean;
error?: string;
}
export interface Conversation {
id: string;
title: string;
messages: Message[];
createdAt: number;
updatedAt: number;
model?: string;
}
export interface ChatSettings {
apiUrl: string;
apiKey: string;
model: string;
temperature: number;
maxTokens: number;
systemPrompt: string;
}
export interface OpenAIMessage {
role: 'user' | 'assistant' | 'system';
content: string;
}
export interface OpenAIStreamChunk {
id: string;
object: string;
created: number;
model: string;
choices: Array<{
index: number;
delta: {
role?: string;
content?: string;
};
finish_reason: string | null;
}>;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />