Compare commits

...
Author SHA1 Message Date
MK Fain 5f76931941 Hide GlobalChatPane on settings pages
- Added useLocation hook to GlobalChatPane component
- Added check to hide GlobalChatPane when on settings pages (pathname starts with '/settings')
- Matches existing behavior of FloatingChatButton which already hides on settings pages
- Ensures consistent UX where both the chat button and pane are hidden in settings
2025-12-03 21:22:47 -06:00
MK Fain 6527f42e2f Fix infinite reload loop in GlobalChatProvider
Removed `isLoading` and `messages` from sendMessage's dependency array.
These were causing the callback to be recreated on every state change,
triggering infinite re-renders.

Instead, capture current messages inside the setMessages updater function
to avoid needing messages in the deps array.
2025-12-03 21:18:49 -06:00
MK Fain a42ea724fa Fix GlobalChatPane 3-second delay using loadingReleasedRef
The issue was that setIsLoading(false) was being called twice:
1. Inside the for-await loop when finish_reason is received
2. In the finally block after the loop completes (3 seconds later)

The finally block's setIsLoading(false) was overriding the early release,
causing React to wait until the entire async iterator finished draining
before updating the UI state.

Solution: Use a ref to track if loading was already released, and skip
the finally block's setIsLoading call if we already released it early.
2025-12-03 21:17:07 -06:00
MK Fain ad217937a3 Fix GlobalChatPane input delay after AI response completes
Release the loading state immediately when finish_reason is received,
but don't break from the for-await loop. Breaking triggers async iterator
cleanup which can cause a multi-second delay before the input becomes
available again. Instead, let the stream drain naturally while the UI
is already unlocked for user input.
2025-12-03 21:14:45 -06:00
MK Fain 6457fbda76 Auto-focus textarea when GlobalChatPane opens
When the global chat pane is opened, the textarea is now automatically
focused so users can immediately start typing without needing to click
on the input field first.
2025-12-03 21:08:00 -06:00
MK Fain b78a912af1 Fix GlobalChatPane input delay after AI finishes responding
Check for finish_reason in stream chunks to detect when the AI has
finished generating content, and release isLoading immediately rather
than waiting for the stream connection to fully close.
2025-12-03 20:56:46 -06:00
MK Fain b1bbf58867 Change GlobalChatPane minimize button back to X icon 2025-12-03 20:53:37 -06:00
MK Fain ecf6b72b21 Fix close button z-index on FloatingChatButton
Moved close button to render after main button so it appears on top
and is clickable in the overlapping area
2025-12-03 20:49:37 -06:00
MK Fain 1b287b90aa Add hover close button to FloatingChatButton and hide on settings pages
- Added "x" button that appears when hovering over the chat button
- Clicking "x" temporarily hides the button until page navigation or refresh
- Button no longer appears on /settings/* pages
- Reset hidden state when navigating to a different page
2025-12-03 20:47:13 -06:00
MK Fain e9a6177c5b Replace minimize icon with minus icon in GlobalChatPane
Changed from Minimize2 to Minus icon for the minimize button
2025-12-03 20:43:04 -06:00
MK Fain 361b6dae3c Keep textarea focused in GlobalChatPane after AI responds
- Focus textarea immediately after sending message (not after AI response)
- Add useEffect to refocus textarea when isLoading becomes false
- User can now type their next message right away without clicking
2025-12-03 20:40:05 -06:00
MK Fain 37071cde85 Fix GlobalChatPane (popup chat) auto-scroll behavior
- Scroll to bottom when chat opens using requestAnimationFrame
- Track userScrolledUp ref to detect when user manually scrolls up
- Auto-scroll follows streaming content by watching lastMessageContent
- Reset scroll tracking when clicking scroll-to-bottom button
- Reset scroll tracking when chat opens
- Only auto-scroll if user hasn't manually scrolled up to read history

Also reverted unintended changes to main ChatPane.tsx
2025-12-03 20:36:36 -06:00
MK Fain fc6ddbf8d6 Fix chat pane auto-scroll behavior
- Add userScrolledUp ref to track when user manually scrolls away from bottom
- Auto-scroll to bottom only when user hasn't manually scrolled up
- Reset scroll tracking when clicking scroll-to-bottom button
- Reset scroll tracking when switching between projects
- Ensures new messages always scroll into view unless user is reading history
2025-12-03 20:30:22 -06:00
MK Fain e23c843ef9 Fix GlobalChatProvider parseProviderModel usage
The parseProviderModel function returns { model, provider } but the code
was trying to destructure { providerId, modelId }. Fixed to correctly
use the actual return values and pass the required providers array
parameter to the function.
2025-12-03 20:10:18 -06:00
MK Fain 0c4de2e2c0 Fix global chat issues and move chat system prompt setting
1. Fixed user message not appearing in global chat
2. Made project chat and global chat remember separate models
   - Added separate localStorage storage for global chat model
   - Project chat continues to use recentlyUsedModels from AISettings
   - Global chat now stores its model independently
3. Moved Chat System Prompt setting from Preferences to System Settings
4. Removed chat pop-out functionality
   - Removed isPoppedOut state from GlobalChatContext
   - Removed handlePopOut function from GlobalChatPane
   - Removed pop-out button from desktop chat header
   - Removed isPoppedOut check from FloatingChatButton
2025-12-03 20:03:53 -06:00
MK Fain 477d055797 Improve unread message indicator for floating chat
- Add hasUnread state to track whether user has seen new messages
- Mark messages as read when chat is opened
- Mark as unread when assistant responds while chat is closed
- Change indicator from message count to simple dot for cleaner UX
2025-12-03 19:50:10 -06:00
MK Fain 15c8040e35 Fix: Move FloatingChatButton and GlobalChatPane inside Router
The ModelSelector component uses useNavigate which requires Router context.
Move the floating chat components from App.tsx into AppRouter.tsx where
they have access to the BrowserRouter/HashRouter context.
2025-12-03 19:47:29 -06:00
MK Fain 68702abc41 Add floating global chat feature
- Add GlobalChatContext, GlobalChatProvider for managing chat state
- Create FloatingChatButton component with unread message indicator
- Create GlobalChatPane with desktop (floating panel) and mobile (full screen) views
- Features include:
  - Streaming AI responses with markdown rendering
  - Auto context trimming when messages exceed ~50k tokens
  - Easy text copy from messages (hover to reveal copy button)
  - Pop-out to separate window
  - Minimize/dismiss functionality
  - Clear chat history
  - Mobile-optimized full-screen drawer
- Add settings in Preferences page:
  - Enable/disable floating chat button
  - Customize chat system prompt
- Add translations for all supported languages (en, pt, zh, ha, yo, ig)
- Integrate with existing AI provider configuration
2025-12-03 19:44:12 -06:00
17 changed files with 1012 additions and 23 deletions

No files matched your search

+12 -9
View File
@@ -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>
+5
View File
@@ -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>
);
}
+83
View File
@@ -0,0 +1,83 @@
import { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { MessageCircle, X } 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();
const location = useLocation();
const [isHovered, setIsHovered] = useState(false);
const [isHiddenTemporarily, setIsHiddenTemporarily] = useState(false);
// Reset hidden state when navigating to a different page
useEffect(() => {
setIsHiddenTemporarily(false);
}, [location.pathname]);
// Don't render if disabled in settings
if (config.globalChatEnabled === false) {
return null;
}
// Don't render on settings pages
if (location.pathname.startsWith('/settings')) {
return null;
}
// Don't render if temporarily hidden
if (isHiddenTemporarily) {
return null;
}
const handleClose = (e: React.MouseEvent) => {
e.stopPropagation();
setIsHiddenTemporarily(true);
};
return (
<div
className="fixed bottom-6 right-6 z-40"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{/* Main chat button */}
<Button
onClick={() => setIsOpen(!isOpen)}
size="lg"
className={cn(
'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>
{/* Close button - appears on hover, rendered last to be on top */}
<Button
onClick={handleClose}
size="icon"
variant="secondary"
className={cn(
'absolute -top-2 -right-2 h-6 w-6 rounded-full shadow-md border',
'transition-all duration-200',
isHovered ? 'opacity-100 scale-100' : 'opacity-0 scale-75 pointer-events-none'
)}
aria-label="Hide chat button"
>
<X className="h-3 w-3" />
</Button>
</div>
);
}
+449
View File
@@ -0,0 +1,449 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { X, 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 location = useLocation();
const [input, setInput] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Track if user has manually scrolled up
const userScrolledUp = useRef(false);
// Track the last message content to detect streaming updates
const lastMessageContent = messages[messages.length - 1]?.content || '';
// Initialize provider model from settings if not set
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
setProviderModel(settings.recentlyUsedModels[0]);
}
}, [providerModel, settings.recentlyUsedModels, setProviderModel]);
// Scroll to bottom and focus textarea when chat opens
useEffect(() => {
if (isOpen && scrollAreaRef.current) {
// Small delay to ensure content is rendered
requestAnimationFrame(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
// Focus the textarea so user can start typing immediately
textareaRef.current?.focus();
});
// Reset scroll tracking when opening
userScrolledUp.current = false;
}
}, [isOpen]);
// Auto-scroll to bottom when messages change or streaming content updates
useEffect(() => {
if (!scrollAreaRef.current || !isOpen) return;
// Only auto-scroll if user hasn't manually scrolled up
if (!userScrolledUp.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, [messages, lastMessageContent, isLoading, isOpen]);
// Handle scroll to detect user scrolling and show/hide scroll-to-bottom button
const handleScroll = useCallback(() => {
if (scrollAreaRef.current) {
const container = scrollAreaRef.current;
const threshold = 100;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Track if user scrolled away from bottom
userScrolledUp.current = !isNearBottom;
setShowScrollToBottom(!isNearBottom && messages.length > 0);
}
}, [messages.length]);
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
// Reset the flag so auto-scroll resumes
userScrolledUp.current = false;
}
}, []);
const handleSend = useCallback(async () => {
if (!input.trim() || isLoading || !providerModel) return;
const messageContent = input.trim();
setInput('');
// Focus immediately so user can keep typing
textareaRef.current?.focus();
await sendMessage(messageContent, providerModel);
}, [input, isLoading, providerModel, sendMessage]);
// Refocus textarea when AI finishes responding
useEffect(() => {
if (!isLoading && isOpen && messages.length > 0) {
textareaRef.current?.focus();
}
}, [isLoading, isOpen, messages.length]);
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;
}
// Don't render on settings pages
if (location.pathname.startsWith('/settings')) {
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)}
>
<X 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>
);
}
+228
View File
@@ -0,0 +1,228 @@
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);
const loadingReleasedRef = 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) => {
// 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 capture current messages for API call
let currentMessages: GlobalChatMessage[] = [];
setMessages(prev => {
currentMessages = prev;
return trimMessages([...prev, userMessage]);
});
setIsLoading(true);
// Create abort controller for this request
abortControllerRef.current = new AbortController();
// Reset the loading released flag for this new request
loadingReleasedRef.current = false;
try {
// Create AI client
const client = createAIClient(provider, config.corsProxy, user?.signer);
// Build messages for API using captured current messages
const systemPrompt = config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT;
const apiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
...currentMessages.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;
});
// Release loading as soon as finish_reason is received
// Don't break - let the stream drain naturally to avoid async iterator cleanup delays
const finishReason = chunk.choices[0]?.finish_reason;
if (finishReason && !loadingReleasedRef.current) {
loadingReleasedRef.current = true;
setIsLoading(false);
}
}
// 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 {
// Only set loading to false if we haven't already released it
if (!loadingReleasedRef.current) {
setIsLoading(false);
}
abortControllerRef.current = null;
}
}, [config.corsProxy, config.globalChatSystemPrompt, 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>
);
}
+28 -7
View File
@@ -377,6 +377,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
// Reset the flag so auto-scroll resumes
userScrolledUp.current = false;
}
}, []);
@@ -427,17 +429,34 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
};
}, [messages]); // Re-run when messages change to ensure proper setup
// Track whether user has manually scrolled up
const userScrolledUp = useRef(false);
// Detect when user manually scrolls
useEffect(() => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
// Check if user was already at or near the bottom (within 100px threshold)
const container = scrollAreaRef.current;
if (!container) return;
const handleUserScroll = () => {
const threshold = 100;
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Only auto-scroll if user was already near the bottom
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
}
// If user scrolled away from bottom, mark it
// If user scrolled back to bottom, reset the flag
userScrolledUp.current = !isNearBottom;
};
container.addEventListener('scroll', handleUserScroll);
return () => container.removeEventListener('scroll', handleUserScroll);
}, []);
// Auto-scroll when messages change or streaming content updates
useEffect(() => {
if (!scrollAreaRef.current) return;
// Only auto-scroll if user hasn't manually scrolled up
if (!userScrolledUp.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, [messages, streamingMessage, isLoading]);
@@ -448,6 +467,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const timer = setTimeout(() => {
scrollToBottom();
scrolledProjects.add(projectId);
// Reset the userScrolledUp flag when switching projects
userScrolledUp.current = false;
}, 100);
return () => clearTimeout(timer);
+4
View File
@@ -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 {
+23
View File
@@ -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);
+10
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -440,5 +440,17 @@
"modified": "已修改",
"restoreToDefault": "恢复默认值",
"restoredToDefault": "已恢复默认值",
"terminal": "终端"
"terminal": "终端",
"globalChat": "聊天",
"globalChatWelcome": "你好! 👋",
"globalChatDescription": "随便问我什么。我在这里帮助回答问题、提供想法和进行对话。",
"clearChat": "清除聊天",
"popOutChat": "弹出窗口",
"minimizeChat": "最小化",
"typeMessage": "输入消息...",
"configureAIFirst": "请先配置AI提供商",
"globalChatEnabled": "浮动聊天按钮",
"globalChatEnabledDescription": "显示浮动聊天按钮以便快速AI对话",
"globalChatSystemPrompt": "聊天系统提示",
"globalChatSystemPromptDescription": "浮动聊天助手的自定义系统提示"
}
+27
View File
@@ -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>
+65 -1
View File
@@ -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">