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
4 changed files with 154 additions and 30 deletions

No files matched your search

+49 -2
View File
@@ -1,4 +1,6 @@
import { MessageCircle } from 'lucide-react'; import { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { MessageCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { useGlobalChat } from '@/hooks/useGlobalChat'; import { useGlobalChat } from '@/hooks/useGlobalChat';
import { useAppContext } from '@/hooks/useAppContext'; import { useAppContext } from '@/hooks/useAppContext';
@@ -7,18 +9,47 @@ import { cn } from '@/lib/utils';
export function FloatingChatButton() { export function FloatingChatButton() {
const { isOpen, setIsOpen, hasUnread } = useGlobalChat(); const { isOpen, setIsOpen, hasUnread } = useGlobalChat();
const { config } = useAppContext(); 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 // Don't render if disabled in settings
if (config.globalChatEnabled === false) { if (config.globalChatEnabled === false) {
return null; 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 ( return (
<div
className="fixed bottom-6 right-6 z-40"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{/* Main chat button */}
<Button <Button
onClick={() => setIsOpen(!isOpen)} onClick={() => setIsOpen(!isOpen)}
size="lg" size="lg"
className={cn( className={cn(
'fixed bottom-6 right-6 z-40 h-14 w-14 rounded-full shadow-lg', 'h-14 w-14 rounded-full shadow-lg',
'bg-primary hover:bg-primary/90 text-primary-foreground', 'bg-primary hover:bg-primary/90 text-primary-foreground',
'transition-all duration-200 hover:scale-105', 'transition-all duration-200 hover:scale-105',
'flex items-center justify-center p-0', 'flex items-center justify-center p-0',
@@ -32,5 +63,21 @@ export function FloatingChatButton() {
<span className="absolute top-0 right-0 h-3 w-3 rounded-full bg-destructive ring-2 ring-background" /> <span className="absolute top-0 right-0 h-3 w-3 rounded-full bg-destructive ring-2 ring-background" />
)} )}
</Button> </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>
); );
} }
+53 -14
View File
@@ -1,6 +1,7 @@
import { useState, useRef, useEffect, useCallback } from 'react'; import { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { X, Minimize2, Trash2, Copy, Check, ChevronDown, ArrowUp, Square, Loader2 } from 'lucide-react'; import { useLocation } from 'react-router-dom';
import { X, Trash2, Copy, Check, ChevronDown, ArrowUp, Square, Loader2 } from 'lucide-react';
import { Streamdown } from 'streamdown'; import { Streamdown } from 'streamdown';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea'; import { Textarea } from '@/components/ui/textarea';
@@ -95,12 +96,18 @@ export function GlobalChatPane() {
const { config } = useAppContext(); const { config } = useAppContext();
const { settings } = useAISettings(); const { settings } = useAISettings();
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const location = useLocation();
const [input, setInput] = useState(''); const [input, setInput] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null); const scrollAreaRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(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 // Initialize provider model from settings if not set
useEffect(() => { useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) { if (!providerModel && settings.recentlyUsedModels?.length) {
@@ -108,23 +115,41 @@ export function GlobalChatPane() {
} }
}, [providerModel, settings.recentlyUsedModels, setProviderModel]); }, [providerModel, settings.recentlyUsedModels, setProviderModel]);
// Auto-scroll to bottom when new messages arrive // Scroll to bottom and focus textarea when chat opens
useEffect(() => { useEffect(() => {
if (isOpen && scrollAreaRef.current) {
// Small delay to ensure content is rendered
requestAnimationFrame(() => {
if (scrollAreaRef.current) { if (scrollAreaRef.current) {
const container = scrollAreaRef.current; scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;
if (isNearBottom || messages.length <= 1) {
container.scrollTop = container.scrollHeight;
} }
// Focus the textarea so user can start typing immediately
textareaRef.current?.focus();
});
// Reset scroll tracking when opening
userScrolledUp.current = false;
} }
}, [messages]); }, [isOpen]);
// Handle scroll to show/hide scroll-to-bottom button // 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(() => { const handleScroll = useCallback(() => {
if (scrollAreaRef.current) { if (scrollAreaRef.current) {
const container = scrollAreaRef.current; const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100; 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); setShowScrollToBottom(!isNearBottom && messages.length > 0);
} }
}, [messages.length]); }, [messages.length]);
@@ -132,6 +157,8 @@ export function GlobalChatPane() {
const scrollToBottom = useCallback(() => { const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) { if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight; scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
// Reset the flag so auto-scroll resumes
userScrolledUp.current = false;
} }
}, []); }, []);
@@ -141,12 +168,19 @@ export function GlobalChatPane() {
const messageContent = input.trim(); const messageContent = input.trim();
setInput(''); setInput('');
await sendMessage(messageContent, providerModel); // Focus immediately so user can keep typing
// Focus back on textarea
textareaRef.current?.focus(); textareaRef.current?.focus();
await sendMessage(messageContent, providerModel);
}, [input, isLoading, providerModel, sendMessage]); }, [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>) => { const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !isMobile) { if (e.key === 'Enter' && !e.shiftKey && !isMobile) {
e.preventDefault(); e.preventDefault();
@@ -159,6 +193,11 @@ export function GlobalChatPane() {
return null; return null;
} }
// Don't render on settings pages
if (location.pathname.startsWith('/settings')) {
return null;
}
const hasProviders = settings.providers.length > 0; const hasProviders = settings.providers.length > 0;
// Mobile: Full screen drawer from bottom // Mobile: Full screen drawer from bottom
@@ -313,7 +352,7 @@ export function GlobalChatPane() {
className="h-7 w-7" className="h-7 w-7"
onClick={() => setIsOpen(false)} onClick={() => setIsOpen(false)}
> >
<Minimize2 className="h-3.5 w-3.5" /> <X className="h-3.5 w-3.5" />
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent>{t('minimizeChat')}</TooltipContent> <TooltipContent>{t('minimizeChat')}</TooltipContent>
+24 -7
View File
@@ -28,6 +28,7 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
const [hasUnread, setHasUnread] = useState(false); const [hasUnread, setHasUnread] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null); const abortControllerRef = useRef<AbortController | null>(null);
const isOpenRef = useRef(false); const isOpenRef = useRef(false);
const loadingReleasedRef = useRef(false);
// Separate model storage for global chat (independent from project chat) // Separate model storage for global chat (independent from project chat)
const [globalChatModel, setGlobalChatModel] = useLocalStorage<string>('shakespeare-global-chat-model', ''); const [globalChatModel, setGlobalChatModel] = useLocalStorage<string>('shakespeare-global-chat-model', '');
@@ -66,8 +67,6 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
}, []); }, []);
const sendMessage = useCallback(async (content: string, providerModelString: string) => { const sendMessage = useCallback(async (content: string, providerModelString: string) => {
if (!content.trim() || isLoading) return;
// Parse provider and model // Parse provider and model
const { model: modelId, provider } = parseProviderModel(providerModelString, settings.providers); const { model: modelId, provider } = parseProviderModel(providerModelString, settings.providers);
@@ -84,23 +83,30 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
timestamp: Date.now(), timestamp: Date.now(),
}; };
// Add user message and trim if necessary // Add user message and capture current messages for API call
setMessages(prev => trimMessages([...prev, userMessage])); let currentMessages: GlobalChatMessage[] = [];
setMessages(prev => {
currentMessages = prev;
return trimMessages([...prev, userMessage]);
});
setIsLoading(true); setIsLoading(true);
// Create abort controller for this request // Create abort controller for this request
abortControllerRef.current = new AbortController(); abortControllerRef.current = new AbortController();
// Reset the loading released flag for this new request
loadingReleasedRef.current = false;
try { try {
// Create AI client // Create AI client
const client = createAIClient(provider, config.corsProxy, user?.signer); const client = createAIClient(provider, config.corsProxy, user?.signer);
// Build messages for API // Build messages for API using captured current messages
const systemPrompt = config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT; const systemPrompt = config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT;
const apiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ const apiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt }, { role: 'system', content: systemPrompt },
...messages.map(msg => ({ ...currentMessages.map(msg => ({
role: msg.role as 'user' | 'assistant', role: msg.role as 'user' | 'assistant',
content: msg.content, content: msg.content,
})), })),
@@ -141,6 +147,14 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
} }
return updated; 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 // Final trim after response is complete
@@ -173,10 +187,13 @@ export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
return [...filtered, errorMessage]; return [...filtered, errorMessage];
}); });
} finally { } finally {
// Only set loading to false if we haven't already released it
if (!loadingReleasedRef.current) {
setIsLoading(false); setIsLoading(false);
}
abortControllerRef.current = null; abortControllerRef.current = null;
} }
}, [config.corsProxy, config.globalChatSystemPrompt, isLoading, messages, settings.providers, trimMessages, user?.signer]); }, [config.corsProxy, config.globalChatSystemPrompt, settings.providers, trimMessages, user?.signer]);
const stopGeneration = useCallback(() => { const stopGeneration = useCallback(() => {
if (abortControllerRef.current) { if (abortControllerRef.current) {
+28 -7
View File
@@ -377,6 +377,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const scrollToBottom = useCallback(() => { const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) { if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight; 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 }, [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(() => { useEffect(() => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
// Check if user was already at or near the bottom (within 100px threshold)
const threshold = 100;
const container = scrollAreaRef.current; const container = scrollAreaRef.current;
if (!container) return;
const handleUserScroll = () => {
const threshold = 100;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold; const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Only auto-scroll if user was already near the bottom // If user scrolled away from bottom, mark it
if (isNearBottom) { // If user scrolled back to bottom, reset the flag
container.scrollTop = container.scrollHeight; 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]); }, [messages, streamingMessage, isLoading]);
@@ -448,6 +467,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const timer = setTimeout(() => { const timer = setTimeout(() => {
scrollToBottom(); scrollToBottom();
scrolledProjects.add(projectId); scrolledProjects.add(projectId);
// Reset the userScrolledUp flag when switching projects
userScrolledUp.current = false;
}, 100); }, 100);
return () => clearTimeout(timer); return () => clearTimeout(timer);