mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
5
Commits
typechecking
...
chat
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e23c843ef9 | ||
|
|
0c4de2e2c0 | ||
|
|
477d055797 | ||
|
|
15c8040e35 | ||
|
|
68702abc41 |
No files matched your search
+12
-9
@@ -28,6 +28,7 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
import { OfflineIndicator } from '@/components/OfflineIndicator';
|
||||
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
import { GlobalChatProvider } from '@/components/GlobalChatProvider';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -177,15 +178,17 @@ export function App() {
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
<GlobalChatProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</GlobalChatProvider>
|
||||
</SessionManagerProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
|
||||
@@ -2,6 +2,8 @@ import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { SessionMonitor } from "./components/SessionMonitor";
|
||||
import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
import { FloatingChatButton } from "./components/FloatingChatButton";
|
||||
import { GlobalChatPane } from "./components/GlobalChatPane";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
@@ -56,6 +58,9 @@ export function AppRouter() {
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
{/* Global floating chat - available on all pages */}
|
||||
<FloatingChatButton />
|
||||
<GlobalChatPane />
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { MessageCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useGlobalChat } from '@/hooks/useGlobalChat';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function FloatingChatButton() {
|
||||
const { isOpen, setIsOpen, hasUnread } = useGlobalChat();
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Don't render if disabled in settings
|
||||
if (config.globalChatEnabled === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
size="lg"
|
||||
className={cn(
|
||||
'fixed bottom-6 right-6 z-40 h-14 w-14 rounded-full shadow-lg',
|
||||
'bg-primary hover:bg-primary/90 text-primary-foreground',
|
||||
'transition-all duration-200 hover:scale-105',
|
||||
'flex items-center justify-center p-0',
|
||||
isOpen && 'ring-2 ring-ring ring-offset-2'
|
||||
)}
|
||||
aria-label={isOpen ? 'Close chat' : 'Open chat'}
|
||||
>
|
||||
<MessageCircle className="h-6 w-6" />
|
||||
{/* Unread indicator - small dot when there are unread messages */}
|
||||
{!isOpen && hasUnread && (
|
||||
<span className="absolute top-0 right-0 h-3 w-3 rounded-full bg-destructive ring-2 ring-background" />
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Minimize2, Trash2, Copy, Check, ChevronDown, ArrowUp, Square, Loader2 } from 'lucide-react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
import { useGlobalChat } from '@/hooks/useGlobalChat';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { GlobalChatMessage } from '@/contexts/GlobalChatContext';
|
||||
|
||||
// Message component with copy functionality
|
||||
function ChatMessage({ message }: { message: GlobalChatMessage }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const { displayTheme } = useTheme();
|
||||
const isUser = message.role === 'user';
|
||||
|
||||
const handleCopy = useCallback(async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(message.content);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy:', error);
|
||||
}
|
||||
}, [message.content]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group relative flex',
|
||||
isUser ? 'justify-end' : 'justify-start'
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'relative max-w-[85%] rounded-2xl px-4 py-2.5',
|
||||
isUser
|
||||
? 'bg-primary text-primary-foreground rounded-br-md'
|
||||
: 'bg-muted rounded-bl-md'
|
||||
)}
|
||||
>
|
||||
{isUser ? (
|
||||
<p className="text-sm whitespace-pre-wrap break-words">{message.content}</p>
|
||||
) : (
|
||||
<div className="text-sm break-words">
|
||||
<Streamdown
|
||||
className="size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 prose prose-sm dark:prose-invert max-w-none"
|
||||
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
|
||||
>
|
||||
{message.content || '...'}
|
||||
</Streamdown>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Copy button - shows on hover */}
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className={cn(
|
||||
'absolute -bottom-1 opacity-0 group-hover:opacity-100 transition-opacity',
|
||||
'p-1 rounded bg-background/80 hover:bg-background shadow-sm border',
|
||||
isUser ? 'right-0 translate-y-full' : 'left-0 translate-y-full'
|
||||
)}
|
||||
aria-label="Copy message"
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3 text-muted-foreground" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function GlobalChatPane() {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
messages,
|
||||
isOpen,
|
||||
isLoading,
|
||||
sendMessage,
|
||||
stopGeneration,
|
||||
clearMessages,
|
||||
setIsOpen,
|
||||
providerModel,
|
||||
setProviderModel,
|
||||
} = useGlobalChat();
|
||||
const { config } = useAppContext();
|
||||
const { settings } = useAISettings();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const [input, setInput] = useState('');
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
// Initialize provider model from settings if not set
|
||||
useEffect(() => {
|
||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||
setProviderModel(settings.recentlyUsedModels[0]);
|
||||
}
|
||||
}, [providerModel, settings.recentlyUsedModels, setProviderModel]);
|
||||
|
||||
// Auto-scroll to bottom when new messages arrive
|
||||
useEffect(() => {
|
||||
if (scrollAreaRef.current) {
|
||||
const container = scrollAreaRef.current;
|
||||
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;
|
||||
|
||||
if (isNearBottom || messages.length <= 1) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
// Handle scroll to show/hide scroll-to-bottom button
|
||||
const handleScroll = useCallback(() => {
|
||||
if (scrollAreaRef.current) {
|
||||
const container = scrollAreaRef.current;
|
||||
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;
|
||||
setShowScrollToBottom(!isNearBottom && messages.length > 0);
|
||||
}
|
||||
}, [messages.length]);
|
||||
|
||||
const scrollToBottom = useCallback(() => {
|
||||
if (scrollAreaRef.current) {
|
||||
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
if (!input.trim() || isLoading || !providerModel) return;
|
||||
|
||||
const messageContent = input.trim();
|
||||
setInput('');
|
||||
|
||||
await sendMessage(messageContent, providerModel);
|
||||
|
||||
// Focus back on textarea
|
||||
textareaRef.current?.focus();
|
||||
}, [input, isLoading, providerModel, sendMessage]);
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !isMobile) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
}, [handleSend, isMobile]);
|
||||
|
||||
// Don't render if disabled or not open
|
||||
if (config.globalChatEnabled === false || !isOpen) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasProviders = settings.providers.length > 0;
|
||||
|
||||
// Mobile: Full screen drawer from bottom
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 bg-background flex flex-col animate-in slide-in-from-bottom duration-300">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
<h2 className="font-semibold text-lg">{t('globalChat')}</h2>
|
||||
<div className="flex items-center gap-1">
|
||||
{messages.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={clearMessages}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('clearChat')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => setIsOpen(false)}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Messages */}
|
||||
<div
|
||||
ref={scrollAreaRef}
|
||||
className="flex-1 overflow-y-auto p-4 space-y-4"
|
||||
onScroll={handleScroll}
|
||||
>
|
||||
{messages.length === 0 ? (
|
||||
<div className="flex-1 flex items-center justify-center text-center text-muted-foreground px-8 py-12">
|
||||
<div>
|
||||
<p className="text-lg font-medium mb-2">{t('globalChatWelcome')}</p>
|
||||
<p className="text-sm">{t('globalChatDescription')}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
messages.map((message) => (
|
||||
<ChatMessage key={message.id} message={message} />
|
||||
))
|
||||
)}
|
||||
|
||||
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
|
||||
<div className="flex justify-start">
|
||||
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Scroll to bottom button */}
|
||||
{showScrollToBottom && (
|
||||
<Button
|
||||
onClick={scrollToBottom}
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="absolute bottom-32 left-1/2 -translate-x-1/2 rounded-full shadow-lg"
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Input */}
|
||||
<div className="p-4 border-t bg-background space-y-3 pb-safe">
|
||||
<div className="flex gap-2">
|
||||
<ModelSelector
|
||||
value={providerModel}
|
||||
onChange={setProviderModel}
|
||||
className="flex-1"
|
||||
disabled={isLoading}
|
||||
placeholder={t('chooseModel')}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2 items-end">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
// Auto-resize
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
target.style.height = 'auto';
|
||||
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
|
||||
disabled={!hasProviders || isLoading}
|
||||
className="resize-none min-h-[44px] max-h-32"
|
||||
rows={1}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<Button onClick={stopGeneration} size="icon" variant="destructive" className="h-11 w-11 shrink-0">
|
||||
<Square className="h-4 w-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
size="icon"
|
||||
disabled={!input.trim() || !providerModel || !hasProviders}
|
||||
className="h-11 w-11 shrink-0"
|
||||
>
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Desktop: Floating panel
|
||||
return (
|
||||
<div className="fixed bottom-24 right-6 z-50 w-96 max-w-[calc(100vw-3rem)] bg-background border rounded-2xl shadow-2xl flex flex-col animate-in fade-in slide-in-from-bottom-4 duration-300">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b">
|
||||
<h2 className="font-semibold">{t('globalChat')}</h2>
|
||||
<div className="flex items-center gap-1">
|
||||
{messages.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={clearMessages}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('clearChat')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() => setIsOpen(false)}
|
||||
>
|
||||
<Minimize2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('minimizeChat')}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Messages */}
|
||||
<div
|
||||
ref={scrollAreaRef}
|
||||
className="flex-1 overflow-y-auto p-4 space-y-4 max-h-96 min-h-48"
|
||||
onScroll={handleScroll}
|
||||
>
|
||||
{messages.length === 0 ? (
|
||||
<div className="flex items-center justify-center text-center text-muted-foreground px-4 py-8">
|
||||
<div>
|
||||
<p className="font-medium mb-1">{t('globalChatWelcome')}</p>
|
||||
<p className="text-xs">{t('globalChatDescription')}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
messages.map((message) => (
|
||||
<ChatMessage key={message.id} message={message} />
|
||||
))
|
||||
)}
|
||||
|
||||
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
|
||||
<div className="flex justify-start">
|
||||
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Scroll to bottom button */}
|
||||
{showScrollToBottom && (
|
||||
<div className="absolute bottom-36 left-1/2 -translate-x-1/2">
|
||||
<Button
|
||||
onClick={scrollToBottom}
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-7 w-7 rounded-full shadow-lg p-0"
|
||||
>
|
||||
<ChevronDown className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Input */}
|
||||
<div className="p-3 border-t space-y-2">
|
||||
<ModelSelector
|
||||
value={providerModel}
|
||||
onChange={setProviderModel}
|
||||
className="w-full"
|
||||
disabled={isLoading}
|
||||
placeholder={t('chooseModel')}
|
||||
/>
|
||||
<div className="flex gap-2 items-end">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
// Auto-resize
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
target.style.height = 'auto';
|
||||
target.style.height = Math.min(target.scrollHeight, 96) + 'px';
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
|
||||
disabled={!hasProviders || isLoading}
|
||||
className="resize-none min-h-[40px] max-h-24 text-sm"
|
||||
rows={1}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<Button onClick={stopGeneration} size="icon" variant="destructive" className="h-10 w-10 shrink-0">
|
||||
<Square className="h-4 w-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
size="icon"
|
||||
disabled={!input.trim() || !providerModel || !hasProviders}
|
||||
className="h-10 w-10 shrink-0"
|
||||
>
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { useState, useCallback, useRef, type ReactNode } from 'react';
|
||||
import OpenAI from 'openai';
|
||||
import { GlobalChatContext, type GlobalChatMessage } from '@/contexts/GlobalChatContext';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
|
||||
// Maximum context size in characters (approximately 50k tokens worth)
|
||||
// This leaves room for the system prompt and response
|
||||
const MAX_CONTEXT_CHARS = 150000;
|
||||
|
||||
// Default system prompt for global chat
|
||||
const DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT = `You are a helpful AI assistant. You're here to have a friendly conversation and help answer questions on any topic.
|
||||
|
||||
Keep your responses concise but informative. Be friendly and conversational.`;
|
||||
|
||||
interface GlobalChatProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
|
||||
const [messages, setMessages] = useState<GlobalChatMessage[]>([]);
|
||||
const [isOpen, setIsOpenInternal] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [hasUnread, setHasUnread] = useState(false);
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const isOpenRef = useRef(false);
|
||||
|
||||
// Separate model storage for global chat (independent from project chat)
|
||||
const [globalChatModel, setGlobalChatModel] = useLocalStorage<string>('shakespeare-global-chat-model', '');
|
||||
|
||||
const { settings } = useAISettings();
|
||||
const { config } = useAppContext();
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// When opening the chat, mark messages as read
|
||||
const setIsOpen = useCallback((open: boolean) => {
|
||||
isOpenRef.current = open;
|
||||
setIsOpenInternal(open);
|
||||
if (open) {
|
||||
setHasUnread(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Trim messages from the top when context gets too long
|
||||
const trimMessages = useCallback((msgs: GlobalChatMessage[]): GlobalChatMessage[] => {
|
||||
let totalChars = msgs.reduce((sum, msg) => sum + msg.content.length, 0);
|
||||
|
||||
if (totalChars <= MAX_CONTEXT_CHARS) {
|
||||
return msgs;
|
||||
}
|
||||
|
||||
// Remove messages from the beginning until we're under the limit
|
||||
const trimmedMessages = [...msgs];
|
||||
while (trimmedMessages.length > 1 && totalChars > MAX_CONTEXT_CHARS) {
|
||||
const removed = trimmedMessages.shift();
|
||||
if (removed) {
|
||||
totalChars -= removed.content.length;
|
||||
}
|
||||
}
|
||||
|
||||
return trimmedMessages;
|
||||
}, []);
|
||||
|
||||
const sendMessage = useCallback(async (content: string, providerModelString: string) => {
|
||||
if (!content.trim() || isLoading) return;
|
||||
|
||||
// Parse provider and model
|
||||
const { model: modelId, provider } = parseProviderModel(providerModelString, settings.providers);
|
||||
|
||||
if (!provider) {
|
||||
console.error('Provider not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Create user message
|
||||
const userMessage: GlobalChatMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'user',
|
||||
content: content.trim(),
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
// Add user message and trim if necessary
|
||||
setMessages(prev => trimMessages([...prev, userMessage]));
|
||||
setIsLoading(true);
|
||||
|
||||
// Create abort controller for this request
|
||||
abortControllerRef.current = new AbortController();
|
||||
|
||||
try {
|
||||
// Create AI client
|
||||
const client = createAIClient(provider, config.corsProxy, user?.signer);
|
||||
|
||||
// Build messages for API
|
||||
const systemPrompt = config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT;
|
||||
|
||||
const apiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
...messages.map(msg => ({
|
||||
role: msg.role as 'user' | 'assistant',
|
||||
content: msg.content,
|
||||
})),
|
||||
{ role: 'user', content: content.trim() },
|
||||
];
|
||||
|
||||
// Create assistant message placeholder
|
||||
const assistantMessage: GlobalChatMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
setMessages(prev => [...prev, assistantMessage]);
|
||||
|
||||
// Stream the response
|
||||
const stream = await client.chat.completions.create({
|
||||
model: modelId,
|
||||
messages: apiMessages,
|
||||
stream: true,
|
||||
}, {
|
||||
signal: abortControllerRef.current.signal,
|
||||
});
|
||||
|
||||
let fullContent = '';
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const delta = chunk.choices[0]?.delta?.content || '';
|
||||
fullContent += delta;
|
||||
|
||||
// Update the assistant message with streamed content
|
||||
setMessages(prev => {
|
||||
const updated = [...prev];
|
||||
const lastMessage = updated[updated.length - 1];
|
||||
if (lastMessage && lastMessage.role === 'assistant') {
|
||||
lastMessage.content = fullContent;
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
// Final trim after response is complete
|
||||
setMessages(prev => trimMessages(prev));
|
||||
|
||||
// Mark as unread if chat is closed
|
||||
if (!isOpenRef.current) {
|
||||
setHasUnread(true);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
// User stopped generation, keep partial response
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('Global chat error:', error);
|
||||
|
||||
// Add error message
|
||||
const errorMessage: GlobalChatMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'assistant',
|
||||
content: `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
setMessages(prev => {
|
||||
// Remove empty assistant message if exists
|
||||
const filtered = prev.filter(m => m.role !== 'assistant' || m.content.trim());
|
||||
return [...filtered, errorMessage];
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
}, [config.corsProxy, config.globalChatSystemPrompt, isLoading, messages, settings.providers, trimMessages, user?.signer]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
abortControllerRef.current = null;
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<GlobalChatContext.Provider
|
||||
value={{
|
||||
messages,
|
||||
isOpen,
|
||||
isLoading,
|
||||
hasUnread,
|
||||
providerModel: globalChatModel,
|
||||
setProviderModel: setGlobalChatModel,
|
||||
sendMessage,
|
||||
stopGeneration,
|
||||
clearMessages,
|
||||
setIsOpen,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</GlobalChatContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -57,6 +57,10 @@ export interface AppConfig {
|
||||
sentryEnabled: boolean;
|
||||
/** System prompt EJS template */
|
||||
systemPrompt?: string;
|
||||
/** Whether the global floating chat is enabled */
|
||||
globalChatEnabled?: boolean;
|
||||
/** Custom system prompt for global chat */
|
||||
globalChatSystemPrompt?: string;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface GlobalChatMessage {
|
||||
id: string;
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface GlobalChatContextType {
|
||||
messages: GlobalChatMessage[];
|
||||
isOpen: boolean;
|
||||
isLoading: boolean;
|
||||
hasUnread: boolean;
|
||||
providerModel: string;
|
||||
setProviderModel: (model: string) => void;
|
||||
sendMessage: (content: string, providerModel: string) => Promise<void>;
|
||||
stopGeneration: () => void;
|
||||
clearMessages: () => void;
|
||||
setIsOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export const GlobalChatContext = createContext<GlobalChatContextType | undefined>(undefined);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useContext } from 'react';
|
||||
import { GlobalChatContext, type GlobalChatContextType } from '@/contexts/GlobalChatContext';
|
||||
|
||||
export function useGlobalChat(): GlobalChatContextType {
|
||||
const context = useContext(GlobalChatContext);
|
||||
if (!context) {
|
||||
throw new Error('useGlobalChat must be used within a GlobalChatProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
+13
-1
@@ -524,5 +524,17 @@
|
||||
"templateDeleted": "Template Deleted",
|
||||
"templateDeletedDescription": "Project template '{{name}}' has been deleted.",
|
||||
"noTemplatesConfigured": "No project templates configured yet. Add a template to get started.",
|
||||
"atLeastOneTemplateRequired": "At least one template is required"
|
||||
"atLeastOneTemplateRequired": "At least one template is required",
|
||||
"globalChat": "Chat",
|
||||
"globalChatWelcome": "Hi there! 👋",
|
||||
"globalChatDescription": "Ask me anything. I'm here to help with questions, ideas, and conversation.",
|
||||
"clearChat": "Clear chat",
|
||||
"popOutChat": "Pop out",
|
||||
"minimizeChat": "Minimize",
|
||||
"typeMessage": "Type a message...",
|
||||
"configureAIFirst": "Configure AI provider first",
|
||||
"globalChatEnabled": "Floating Chat Button",
|
||||
"globalChatEnabledDescription": "Show a floating chat button for quick AI conversations",
|
||||
"globalChatSystemPrompt": "Chat System Prompt",
|
||||
"globalChatSystemPromptDescription": "Custom system prompt for the floating chat assistant"
|
||||
}
|
||||
+13
-1
@@ -431,5 +431,17 @@
|
||||
"modified": "An Canza",
|
||||
"restoreToDefault": "Mayar da asali",
|
||||
"restoredToDefault": "An Mayar da Asali",
|
||||
"terminal": "Terminal"
|
||||
"terminal": "Terminal",
|
||||
"globalChat": "Tattaunawa",
|
||||
"globalChatWelcome": "Sannu! 👋",
|
||||
"globalChatDescription": "Tambayi komai. Ina nan don taimaka da tambayoyi, ra'ayoyi, da tattaunawa.",
|
||||
"clearChat": "Share tattaunawa",
|
||||
"popOutChat": "Fitar da waje",
|
||||
"minimizeChat": "Ragewa",
|
||||
"typeMessage": "Rubuta sako...",
|
||||
"configureAIFirst": "Da fari ka saita mai ba da AI",
|
||||
"globalChatEnabled": "Maballin Tattaunawa Mai Yawo",
|
||||
"globalChatEnabledDescription": "Nuna maballin tattaunawa mai yawo don saurin tattaunawa da AI",
|
||||
"globalChatSystemPrompt": "Jagorar Tsarin Tattaunawa",
|
||||
"globalChatSystemPromptDescription": "Jagorar tsarin da aka keɓe don mataimakin tattaunawa mai yawo"
|
||||
}
|
||||
+13
-1
@@ -428,5 +428,17 @@
|
||||
"modified": "Gbanwere",
|
||||
"restoreToDefault": "Weghachi na nke mbụ",
|
||||
"restoredToDefault": "Weghachiri na Nke Mbụ",
|
||||
"terminal": "Terminal"
|
||||
"terminal": "Terminal",
|
||||
"globalChat": "Nkata",
|
||||
"globalChatWelcome": "Ndewo! 👋",
|
||||
"globalChatDescription": "Jụọ ihe ọ bụla. Anọ m ebe a inyere gị aka na ajụjụ, echiche, na nkata.",
|
||||
"clearChat": "Kpochapụ nkata",
|
||||
"popOutChat": "Wepụta",
|
||||
"minimizeChat": "Belata",
|
||||
"typeMessage": "Dee ozi...",
|
||||
"configureAIFirst": "Bụrụ ụzọ hazie onye na-enye AI",
|
||||
"globalChatEnabled": "Bọtịnụ Nkata Na-epupụta",
|
||||
"globalChatEnabledDescription": "Gosi bọtịnụ nkata na-epupụta maka nkata AI ngwa ngwa",
|
||||
"globalChatSystemPrompt": "Usoro Nkata",
|
||||
"globalChatSystemPromptDescription": "Usoro nke gị maka onye enyemaka nkata na-epupụta"
|
||||
}
|
||||
+13
-1
@@ -440,5 +440,17 @@
|
||||
"modified": "Modificado",
|
||||
"restoreToDefault": "Restaurar para padrão",
|
||||
"restoredToDefault": "Restaurado para Padrão",
|
||||
"terminal": "Terminal"
|
||||
"terminal": "Terminal",
|
||||
"globalChat": "Chat",
|
||||
"globalChatWelcome": "Olá! 👋",
|
||||
"globalChatDescription": "Pergunte-me qualquer coisa. Estou aqui para ajudar com perguntas, ideias e conversas.",
|
||||
"clearChat": "Limpar chat",
|
||||
"popOutChat": "Destacar",
|
||||
"minimizeChat": "Minimizar",
|
||||
"typeMessage": "Digite uma mensagem...",
|
||||
"configureAIFirst": "Configure o provedor de IA primeiro",
|
||||
"globalChatEnabled": "Botão de Chat Flutuante",
|
||||
"globalChatEnabledDescription": "Mostrar um botão de chat flutuante para conversas rápidas com IA",
|
||||
"globalChatSystemPrompt": "Prompt do Sistema do Chat",
|
||||
"globalChatSystemPromptDescription": "Prompt do sistema personalizado para o assistente de chat flutuante"
|
||||
}
|
||||
+13
-1
@@ -428,5 +428,17 @@
|
||||
"modified": "Ti Yipada",
|
||||
"restoreToDefault": "Pada si atilẹwa",
|
||||
"restoredToDefault": "Ti Pada si Atilẹwa",
|
||||
"terminal": "Terminal"
|
||||
"terminal": "Terminal",
|
||||
"globalChat": "Ibanisọrọ",
|
||||
"globalChatWelcome": "Pẹlẹ o! 👋",
|
||||
"globalChatDescription": "Beere ohunkohun. Mo wa nibi lati ran ọ lọwọ pẹlu awọn ibeere, awọn ero, ati ibaraẹnisọrọ.",
|
||||
"clearChat": "Pa ibanisọrọ rẹ",
|
||||
"popOutChat": "Ya jade",
|
||||
"minimizeChat": "Din ku",
|
||||
"typeMessage": "Tẹ ifiranṣẹ...",
|
||||
"configureAIFirst": "Ṣeto olupese AI ni akọkọ",
|
||||
"globalChatEnabled": "Bọtini Ibanisọrọ Ti O N Lọ",
|
||||
"globalChatEnabledDescription": "Fi bọtini ibanisọrọ ti o n lọ han fun ibaraẹnisọrọ AI ni iyara",
|
||||
"globalChatSystemPrompt": "Itọsọna Eto Ibanisọrọ",
|
||||
"globalChatSystemPromptDescription": "Itọsọna eto aṣa fun oluranlọwọ ibanisọrọ ti o n lọ"
|
||||
}
|
||||
+13
-1
@@ -440,5 +440,17 @@
|
||||
"modified": "已修改",
|
||||
"restoreToDefault": "恢复默认值",
|
||||
"restoredToDefault": "已恢复默认值",
|
||||
"terminal": "终端"
|
||||
"terminal": "终端",
|
||||
"globalChat": "聊天",
|
||||
"globalChatWelcome": "你好! 👋",
|
||||
"globalChatDescription": "随便问我什么。我在这里帮助回答问题、提供想法和进行对话。",
|
||||
"clearChat": "清除聊天",
|
||||
"popOutChat": "弹出窗口",
|
||||
"minimizeChat": "最小化",
|
||||
"typeMessage": "输入消息...",
|
||||
"configureAIFirst": "请先配置AI提供商",
|
||||
"globalChatEnabled": "浮动聊天按钮",
|
||||
"globalChatEnabledDescription": "显示浮动聊天按钮以便快速AI对话",
|
||||
"globalChatSystemPrompt": "聊天系统提示",
|
||||
"globalChatSystemPromptDescription": "浮动聊天助手的自定义系统提示"
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { ThemePicker } from "@/components/ThemePicker";
|
||||
import { LanguagePicker } from "@/components/LanguagePicker";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { useIsMobile } from "@/hooks/useIsMobile";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
@@ -98,6 +99,32 @@ export function Preferences() {
|
||||
{t('shareErrorReportsDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Separator className="my-4" />
|
||||
|
||||
{/* Global Chat Settings */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="global-chat-enabled" className="text-sm font-medium">
|
||||
{t('globalChatEnabled')}
|
||||
</Label>
|
||||
</div>
|
||||
<Switch
|
||||
id="global-chat-enabled"
|
||||
checked={config.globalChatEnabled !== false}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
globalChatEnabled: checked,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('globalChatEnabledDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Cog, Globe, Image, Code, Monitor, Award, Bug, FolderTree, Terminal as TerminalIcon } from "lucide-react";
|
||||
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Cog, Globe, Image, Code, Monitor, Award, Bug, FolderTree, Terminal as TerminalIcon, MessageCircle } from "lucide-react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { useIsMobile } from "@/hooks/useIsMobile";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
@@ -13,6 +14,11 @@ import { useOffline } from "@/hooks/useOffline";
|
||||
import { useToast } from "@/hooks/useToast";
|
||||
import { Terminal } from "@/components/Terminal";
|
||||
|
||||
// Default system prompt for global chat
|
||||
const DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT = `You are a helpful AI assistant. You're here to have a friendly conversation and help answer questions on any topic.
|
||||
|
||||
Keep your responses concise but informative. Be friendly and conversational.`;
|
||||
|
||||
export function SystemSettings() {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
@@ -32,6 +38,9 @@ export function SystemSettings() {
|
||||
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
|
||||
const [fsPathTemplatesInput, setFsPathTemplatesInput] = useState(config.fsPathTemplates);
|
||||
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
|
||||
const [chatSystemPromptInput, setChatSystemPromptInput] = useState(
|
||||
config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT
|
||||
);
|
||||
|
||||
// Check which settings differ from defaults
|
||||
const isModified = useMemo(() => ({
|
||||
@@ -47,6 +56,7 @@ export function SystemSettings() {
|
||||
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
|
||||
fsPathTemplates: config.fsPathTemplates !== defaultConfig.fsPathTemplates,
|
||||
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
|
||||
globalChatSystemPrompt: (config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT) !== DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT,
|
||||
}), [config, defaultConfig]);
|
||||
|
||||
// Restore functions - clear the value from config to use the default
|
||||
@@ -156,6 +166,14 @@ export function SystemSettings() {
|
||||
});
|
||||
};
|
||||
|
||||
const restoreChatSystemPrompt = () => {
|
||||
setChatSystemPromptInput(DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT);
|
||||
updateConfig((current) => {
|
||||
const { globalChatSystemPrompt, ...rest } = current;
|
||||
return rest;
|
||||
});
|
||||
};
|
||||
|
||||
// Service Worker state
|
||||
const [swState, setSwState] = useState<string>('');
|
||||
const [isUpdatingSW, setIsUpdatingSW] = useState(false);
|
||||
@@ -952,6 +970,52 @@ export function SystemSettings() {
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Chat System Prompt Configuration */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="chat-system-prompt">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<MessageCircle className="h-4 w-4 text-muted-foreground" />
|
||||
<h4 className="text-sm font-medium">{t('globalChatSystemPrompt')}</h4>
|
||||
{isModified.globalChatSystemPrompt && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-2">
|
||||
<Textarea
|
||||
placeholder="Enter system prompt..."
|
||||
value={chatSystemPromptInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setChatSystemPromptInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
globalChatSystemPrompt: value,
|
||||
}));
|
||||
}}
|
||||
className="font-mono text-xs min-h-[150px]"
|
||||
/>
|
||||
{isModified.globalChatSystemPrompt && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={restoreChatSystemPrompt}
|
||||
className="w-full"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4 mr-2" />
|
||||
{t('restoreToDefault')}
|
||||
</Button>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('globalChatSystemPromptDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Terminal */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="terminal">
|
||||
|
||||
Reference in new issue
Block a user