Compare commits

...
5 changed files with 389 additions and 121 deletions

No files matched your search

+3
View File
@@ -11,6 +11,9 @@ vi.mock('@/hooks/useLocalStorage');
vi.mock('@/hooks/useProjectSessionStatus', () => ({
useProjectSessionStatus: () => ({ hasRunningSessions: false })
}));
vi.mock('@/hooks/useDraftMessages', () => ({
useDraftMessages: () => ({ hasDraft: () => false })
}));
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
+13 -3
View File
@@ -1,13 +1,14 @@
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Pencil } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useDraftMessages } from '@/hooks/useDraftMessages';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
@@ -19,9 +20,10 @@ interface ProjectItemProps {
isSelected: boolean;
onSelect: (project: Project) => void;
isFavorite?: boolean;
hasDraft?: boolean;
}
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite, hasDraft }) => {
const navigate = useNavigate();
const { hasRunningSessions } = useProjectSessionStatus(project.id);
@@ -51,10 +53,16 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
)}
</div>
<div className="flex justify-between gap-2 flex-1 min-w-0">
<div className="min-w-0 flex-1 flex items-center">
<div className="min-w-0 flex-1 flex items-center gap-2">
<h3 className="font-medium text-sm truncate">
{project.name}
</h3>
{/* Draft indicator - only shown when project has draft */}
{hasDraft && (
<div className="flex-shrink-0 pointer-events-none">
<Pencil className="h-3 w-3 text-sidebar-foreground opacity-60" />
</div>
)}
</div>
{/* Star indicator - only shown when favorited */}
@@ -93,6 +101,7 @@ export function ProjectSidebar({
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const { hasDraft } = useDraftMessages(); // Use without projectId for global access
const isMobile = useIsMobile();
const navigate = useNavigate();
@@ -221,6 +230,7 @@ export function ProjectSidebar({
isSelected={selectedProject?.id === project.id}
onSelect={onSelectProject}
isFavorite={favorites.includes(project.id)}
hasDraft={hasDraft(project.id)}
/>
))}
</div>
+226 -118
View File
@@ -8,13 +8,15 @@ import { CircularProgress } from '@/components/ui/circular-progress';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { FileAttachment } from '@/components/ui/file-attachment';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
import { Square, Loader2, ChevronDown, ArrowUp, Plus } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useKeepAlive } from '@/hooks/useKeepAlive';
import { useAIChat } from '@/hooks/useAIChat';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useMessageQueue } from '@/hooks/useMessageQueue';
import { useDraftMessages } from '@/hooks/useDraftMessages';
import { ModelSelector } from '@/components/ModelSelector';
import { AIMessageItem } from '@/components/AIMessageItem';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
@@ -85,6 +87,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
// Message queue for handling messages while AI is working
const { queuedMessages, addToQueue, clearQueue, hasQueuedMessages, queueLength } = useMessageQueue(projectId);
// Draft messages for preserving input across project switches
const { getDraft, saveDraft, clearDraft } = useDraftMessages(projectId);
// Determine which error to show - console error takes priority over AI errors
const displayError = consoleError || aiError;
@@ -131,6 +138,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
setAIError(null);
}, [projectId, providerModel]);
// Load draft when switching projects
useEffect(() => {
const draft = getDraft();
setInput(draft);
}, [projectId, getDraft]);
// Initialize AI chat with tools
const cwd = `/projects/${projectId}`;
const customTools = useMemo(() => {
@@ -258,6 +271,64 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Use external loading state if provided, otherwise use internal state
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
// Process queued messages when AI becomes available for this project
const processQueuedMessages = useCallback(async () => {
if (isLoading || !isConfigured || !providerModel.trim() || queuedMessages.length === 0) return;
const messagesToProcess = [...queuedMessages];
// Clear the queue first to prevent re-processing
clearQueue();
const modelToUse = providerModel.trim();
addRecentlyUsedModel(modelToUse);
// Combine all queued messages into a single batch
const allContentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
for (const queuedMessage of messagesToProcess) {
// Add text content if present
if (queuedMessage.content.trim()) {
allContentParts.push({
type: 'text',
text: queuedMessage.content.trim()
});
}
// Process attached files for this message
if (queuedMessage.attachedFiles.length > 0) {
const filePromises = queuedMessage.attachedFiles.map(async (file) => {
try {
const savedPath = await saveFileToTmp(fs, file);
return `Added file: ${savedPath}`;
} catch (error) {
console.error('Failed to save file:', error);
return `Failed to save file: ${file.name}`;
}
});
const fileResults = await Promise.all(filePromises);
fileResults.forEach(fileResult => {
allContentParts.push({
type: 'text',
text: fileResult
});
});
}
}
// Send all queued messages as a single batch
if (allContentParts.length > 0) {
const messageContent = allContentParts.length === 1 ? allContentParts[0].text : allContentParts;
await sendMessage(messageContent, modelToUse);
}
}, [addRecentlyUsedModel, clearQueue, fs, isConfigured, isLoading, providerModel, queuedMessages, sendMessage]);
useEffect(() => {
if (!isLoading && hasQueuedMessages) {
processQueuedMessages();
}
}, [isLoading, hasQueuedMessages, processQueuedMessages]);
// Calculate context usage percentage
const currentModel = useMemo(() => {
if (!providerModel.trim()) return null;
@@ -412,8 +483,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
e.stopPropagation();
setIsDragOver(false);
if (isLoading || !providerModel.trim()) return;
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
@@ -422,7 +491,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
};
const send = useCallback(async (input: string, attachedFiles: File[]) => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
if ((!input.trim() && attachedFiles.length === 0)) return;
// If AI is loading, add to queue instead of sending immediately
if (isLoading) {
addToQueue(input, attachedFiles);
setInput('');
setAttachedFiles([]);
clearDraft(); // Clear draft when message is queued
return;
}
// If AI is not configured, show onboarding dialog
if (!isConfigured) {
@@ -473,6 +551,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
setInput('');
setAttachedFiles([]);
clearDraft(); // Clear draft when message is sent
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
@@ -480,7 +559,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
}, [addRecentlyUsedModel, addToQueue, clearDraft, fs, isConfigured, isLoading, providerModel, sendMessage]);
const handleSend = useCallback(async () => {
await send(input, attachedFiles);
@@ -673,131 +752,160 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="border-t p-4">
{/* Chat Input Container */}
<div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={`${hasQueuedMessages ? 'focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 rounded-2xl' : ''} transition-all`}
>
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={handleTextareaFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{/* Queued Messages Indicator */}
{hasQueuedMessages && (
<div className="w-full px-3 py-1 text-xs text-muted-foreground bg-muted/50 border border-input rounded-t-2xl text-left mb-0">
{queueLength} message{queueLength > 1 ? 's' : ''} queued • will send when AI finishes
</div>
)}
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* File Attachment */}
<FileAttachment
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isLoading}
multiple={true}
<div
className={`flex flex-col border border-input bg-background shadow-sm transition-all ${hasQueuedMessages
? 'rounded-b-2xl border-t-0'
: 'rounded-2xl focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2'
} ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<Textarea
value={input}
onChange={(e) => {
const newValue = e.target.value;
setInput(newValue);
saveDraft(newValue);
}}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={handleTextareaFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isConfigured && !providerModel.trim()}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{/* Context Usage Wheel */}
{contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="cursor-help">
<CircularProgress
value={contextUsagePercentage}
size={20}
strokeWidth={2}
/>
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('contextUsage', {
tokens: lastInputTokens.toLocaleString(),
total: currentModel.contextLength.toLocaleString(),
percentage: contextUsagePercentage.toFixed(1)
})}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Cost Display */}
{totalCost >= 0.01 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
${totalCost.toFixed(2)}
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('totalCostSession')}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Model Selector */}
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={setIsModelSelectorOpen}
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* File Attachment */}
<FileAttachment
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={false}
multiple={true}
/>
</div>
{/* Send/Stop Button */}
<div>
{isLoading ? (
<Button
onClick={stopGeneration}
size="sm"
variant="ghost"
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
>
<Square />
</Button>
) : (
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
<ArrowUp />
</Button>
{/* Context Usage Wheel */}
{contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="cursor-help">
<CircularProgress
value={contextUsagePercentage}
size={20}
strokeWidth={2}
/>
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('contextUsage', {
tokens: lastInputTokens.toLocaleString(),
total: currentModel.contextLength.toLocaleString(),
percentage: contextUsagePercentage.toFixed(1)
})}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Cost Display */}
{totalCost >= 0.01 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
${totalCost.toFixed(2)}
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('totalCostSession')}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Model Selector */}
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={setIsModelSelectorOpen}
/>
</div>
{/* Send/Stop Button */}
<div>
{isLoading ? (
<Button
onClick={stopGeneration}
size="sm"
variant="ghost"
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
>
<Square />
</Button>
) : (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
{hasQueuedMessages ? <Plus /> : <ArrowUp />}
</Button>
</TooltipTrigger>
{hasQueuedMessages && (
<TooltipContent>
<p>{queueLength} message{queueLength > 1 ? 's' : ''} will send when AI finishes</p>
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
)}
</div>
</div>
</div>
</div>
</div>
{/* Onboarding Dialog */}
<OnboardingDialog
open={showOnboarding}
+93
View File
@@ -0,0 +1,93 @@
import { useCallback, useState, useEffect } from 'react';
// Global drafts storage shared across all hook instances
const globalDrafts = new Map<string, string>();
// Global listeners for draft changes
const listeners = new Set<() => void>();
// Notify all listeners when drafts change
const notifyListeners = () => {
listeners.forEach(listener => listener());
};
/**
* Hook to manage draft messages per project.
* Drafts are stored in global memory and persist when switching between projects.
* Drafts are cleared when messages are sent or queued.
*
* Can be used in two ways:
* 1. With projectId - for managing drafts for a specific project
* 2. Without projectId - for accessing global draft functionality (checking any project's drafts)
*/
export function useDraftMessages(projectId?: string) {
// Use state to trigger re-renders when drafts change
const [, forceUpdate] = useState(0);
// Register listener for draft changes
useEffect(() => {
const listener = () => forceUpdate(prev => prev + 1);
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}, []);
// Get draft for a specific project (or current project if projectId provided)
const getDraft = useCallback((targetProjectId?: string): string => {
const id = targetProjectId || projectId;
if (!id) return '';
return globalDrafts.get(id) || '';
}, [projectId]);
// Save draft for a specific project (or current project if projectId provided)
const saveDraft = useCallback((content: string, targetProjectId?: string) => {
const id = targetProjectId || projectId;
if (!id) return;
if (content.trim()) {
globalDrafts.set(id, content);
} else {
// Clear draft if content is empty
globalDrafts.delete(id);
}
notifyListeners();
}, [projectId]);
// Clear draft for a specific project (or current project if projectId provided)
const clearDraft = useCallback((targetProjectId?: string) => {
const id = targetProjectId || projectId;
if (!id) return;
globalDrafts.delete(id);
notifyListeners();
}, [projectId]);
// Check if a specific project has a draft (or current project if projectId provided)
const hasDraft = useCallback((targetProjectId?: string): boolean => {
const id = targetProjectId || projectId;
if (!id) return false;
const draft = globalDrafts.get(id);
return Boolean(draft && draft.trim());
}, [projectId]);
// Get all projects that have drafts (global functionality)
const getProjectsWithDrafts = useCallback((): string[] => {
const projectsWithDrafts: string[] = [];
globalDrafts.forEach((draft, id) => {
if (draft && draft.trim()) {
projectsWithDrafts.push(id);
}
});
return projectsWithDrafts;
}, []);
return {
getDraft,
saveDraft,
clearDraft,
hasDraft,
getProjectsWithDrafts
};
}
+54
View File
@@ -0,0 +1,54 @@
import { useState, useCallback, useRef, useEffect } from 'react';
/**
* Simple hook to manage a message queue per project.
* Messages are only stored in memory and cleared when AI processes them.
*/
export function useMessageQueue(projectId: string) {
// Use ref to store queues for all projects to persist across re-renders
const queuesRef = useRef<Map<string, Array<{ content: string; attachedFiles: File[] }>>>(new Map());
// Local state for current project's queue to trigger re-renders
const [currentQueue, setCurrentQueue] = useState<Array<{ content: string; attachedFiles: File[] }>>([]);
// Sync current queue with the ref when projectId changes
useEffect(() => {
const queue = queuesRef.current.get(projectId) || [];
setCurrentQueue(queue);
}, [projectId]);
const addToQueue = useCallback((content: string, attachedFiles: File[] = []) => {
if (!content.trim() && attachedFiles.length === 0) return;
const currentProjectQueue = queuesRef.current.get(projectId) || [];
const updatedQueue = [...currentProjectQueue, { content: content.trim(), attachedFiles }];
queuesRef.current.set(projectId, updatedQueue);
setCurrentQueue(updatedQueue);
}, [projectId]);
const clearQueue = useCallback(() => {
queuesRef.current.set(projectId, []);
setCurrentQueue([]);
}, [projectId]);
const removeFromQueue = useCallback((index: number) => {
const currentProjectQueue = queuesRef.current.get(projectId) || [];
const updatedQueue = currentProjectQueue.filter((_, i) => i !== index);
queuesRef.current.set(projectId, updatedQueue);
setCurrentQueue(updatedQueue);
}, [projectId]);
const hasQueuedMessages = currentQueue.length > 0;
const queueLength = currentQueue.length;
return {
queuedMessages: currentQueue,
addToQueue,
clearQueue,
removeFromQueue,
hasQueuedMessages,
queueLength
};
}