mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Simplify console message handling and reduce code complexity
- Remove unused useErrorDetection.ts hook (154 lines) - Remove separate console.ts type file, consolidate into ReadConsoleMessagesTool - Simplify console message state management in PreviewPane - Remove redundant console clearing logic in ProjectView - Streamline copy functionality in console UI - Clean up imports and formatting Preserves all functionality while reducing code complexity and maintenance burden.
This commit is contained in:
1 parent
6296fc4366
commit
7ab30af944
6 files changed
+19
-201
No files matched your search
@@ -34,11 +34,10 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
@@ -105,8 +104,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const { user } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
|
||||
|
||||
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `/projects/${projectId}`;
|
||||
const customTools = useMemo(() => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { addConsoleMessage, getConsoleMessages } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
@@ -24,7 +24,6 @@ import {
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ConsoleMessage } from '@/types/console';
|
||||
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
@@ -73,8 +72,6 @@ interface JSONRPCResponse {
|
||||
id: number;
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
||||
const { t } = useTranslation();
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
@@ -88,12 +85,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const [consoleMessages, setConsoleMessages] = useState<ConsoleMessage[]>([]);
|
||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -119,10 +114,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}
|
||||
}, [searchParams, setSearchParams]);
|
||||
|
||||
// Load console messages when project changes
|
||||
useEffect(() => {
|
||||
setConsoleMessages(getConsoleMessages());
|
||||
}, []);
|
||||
|
||||
|
||||
// Build automatically if "build" parameter was present
|
||||
useEffect(() => {
|
||||
@@ -226,9 +218,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
normalizedLevel = params.level as ConsoleMessage['level'];
|
||||
}
|
||||
|
||||
// Add to project-specific console messages
|
||||
// Add to console messages
|
||||
addConsoleMessage(normalizedLevel, params.message);
|
||||
setConsoleMessages(getConsoleMessages());
|
||||
|
||||
// Log to parent console for debugging with appropriate level
|
||||
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
|
||||
@@ -520,28 +511,19 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
|
||||
const ConsoleDropdown = () => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const copiedMessageRef = useRef<number | null>(null);
|
||||
const [_, setCopyUpdate] = useState(0);
|
||||
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
|
||||
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(msg.message);
|
||||
copiedMessageRef.current = msg.id;
|
||||
setCopyUpdate(prev => prev + 1);
|
||||
|
||||
// Reset the copied state after 2 seconds
|
||||
setTimeout(() => {
|
||||
copiedMessageRef.current = null;
|
||||
setCopyUpdate(prev => prev + 1);
|
||||
}, 2000);
|
||||
setCopiedMessageId(msg.id);
|
||||
setTimeout(() => setCopiedMessageId(null), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy message to clipboard:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const closePanel = () => {
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
const consoleMessages = getConsoleMessages();
|
||||
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
|
||||
const messageCount = consoleMessages.length;
|
||||
|
||||
@@ -602,7 +584,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}}
|
||||
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground bg-black/50 rounded"
|
||||
>
|
||||
{copiedMessageRef.current === msg.id ? (
|
||||
{copiedMessageId === msg.id ? (
|
||||
<Check className="h-2 w-2 text-green-400" />
|
||||
) : (
|
||||
<Copy className="h-2 w-2" />
|
||||
@@ -616,7 +598,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={closePanel}
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="absolute top-2 right-2 h-8 w-8 p-0 bg-gray-800/50 hover:bg-gray-700/70 rounded-md z-10 flex items-center justify-center border-0"
|
||||
>
|
||||
<X className="h-5 w-5 text-gray-400" />
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
import { useState, useCallback, useMemo } from 'react';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { getConsoleMessages } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
|
||||
export interface ConsoleErrorAlert {
|
||||
hasError: boolean;
|
||||
errorSummary: string | null;
|
||||
errorCount: number;
|
||||
dismiss: () => void;
|
||||
}
|
||||
|
||||
export const useConsoleErrorAlert = (
|
||||
aiMessages: AIMessage[],
|
||||
projectId?: string | null,
|
||||
isBuilding?: boolean,
|
||||
isLoading?: boolean
|
||||
): ConsoleErrorAlert => {
|
||||
const [dismissedErrorSummary, setDismissedErrorSummary] = useState<string>('');
|
||||
|
||||
const { hasError, errorSummary, errorCount } = useMemo(() => {
|
||||
// Don't show alerts while building or AI is working
|
||||
if (isBuilding || isLoading || !projectId) {
|
||||
return { hasError: false, errorSummary: null, errorCount: 0 };
|
||||
}
|
||||
|
||||
// Find the timestamp of the last AI assistant message
|
||||
// Since AIMessage doesn't have timestamps, we'll use a different approach:
|
||||
// Only show errors if there are any errors at all and no recent user activity
|
||||
const lastMessage = aiMessages[aiMessages.length - 1];
|
||||
const isLastMessageFromAssistant = lastMessage?.role === 'assistant';
|
||||
|
||||
// Only show console errors if the last message was from assistant (AI just responded)
|
||||
if (!isLastMessageFromAssistant) {
|
||||
return { hasError: false, errorSummary: null, errorCount: 0 };
|
||||
}
|
||||
|
||||
// Get recent errors (last 10 seconds worth to catch errors from recent AI actions)
|
||||
const recentTimeThreshold = Date.now() - (10 * 1000); // 10 seconds ago
|
||||
const messages = getConsoleMessages();
|
||||
const recentErrors = messages.filter(msg =>
|
||||
msg.level === 'error' &&
|
||||
msg.timestamp && msg.timestamp > recentTimeThreshold
|
||||
);
|
||||
|
||||
if (recentErrors.length === 0) {
|
||||
return { hasError: false, errorSummary: null, errorCount: 0 };
|
||||
}
|
||||
|
||||
// Just return the raw error messages, no formatting
|
||||
const summary = recentErrors.slice(-3).map(e => e.message).join('\n');
|
||||
|
||||
return {
|
||||
hasError: dismissedErrorSummary !== summary,
|
||||
errorSummary: summary,
|
||||
errorCount: recentErrors.length
|
||||
};
|
||||
}, [projectId, dismissedErrorSummary, aiMessages, isBuilding, isLoading]);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
if (errorSummary) {
|
||||
setDismissedErrorSummary(errorSummary);
|
||||
}
|
||||
}, [errorSummary]);
|
||||
|
||||
return {
|
||||
hasError,
|
||||
errorSummary,
|
||||
errorCount,
|
||||
dismiss
|
||||
};
|
||||
};
|
||||
|
||||
export interface AIModelErrorAlert {
|
||||
hasError: boolean;
|
||||
errorMessage: string | null;
|
||||
errorType: 'warn' | 'error' | null;
|
||||
action?: { label: string; onClick: () => void };
|
||||
dismiss: () => void;
|
||||
}
|
||||
|
||||
export const useAIModelErrorAlert = (
|
||||
messages: AIMessage[],
|
||||
onNewChat?: () => void,
|
||||
onChangeModel?: () => void
|
||||
): AIModelErrorAlert => {
|
||||
const [dismissedAlertKey, setDismissedAlertKey] = useState<string>('');
|
||||
|
||||
const { hasError, errorMessage, errorType, action } = useMemo(() => {
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
|
||||
// Only show AI model alerts if the last message is from the assistant
|
||||
// This ensures we don't show stale alerts when user continues the conversation
|
||||
if (!lastMessage || lastMessage.role !== 'assistant') {
|
||||
return { hasError: false, errorMessage: null, errorType: null, action: undefined };
|
||||
}
|
||||
|
||||
const content = typeof lastMessage.content === 'string' ? lastMessage.content : '';
|
||||
|
||||
// Define error patterns with actions
|
||||
const errorPatterns = [
|
||||
{
|
||||
test: (content: string) => /AI service error: 422/.test(content) || /Provider returned error/.test(content),
|
||||
type: 'error' as const,
|
||||
message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.',
|
||||
action: onChangeModel ? { label: 'Change model', onClick: onChangeModel } : undefined
|
||||
},
|
||||
{
|
||||
test: (content: string) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content),
|
||||
type: 'warn' as const,
|
||||
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
|
||||
action: onNewChat ? { label: 'New chat', onClick: onNewChat } : undefined
|
||||
},
|
||||
{
|
||||
test: (content: string) => /rate limit/i.test(content) || /too many requests/i.test(content),
|
||||
type: 'warn' as const,
|
||||
message: 'You\'re sending requests too quickly. Please wait a moment before trying again.'
|
||||
}
|
||||
];
|
||||
|
||||
for (const pattern of errorPatterns) {
|
||||
if (pattern.test(content)) {
|
||||
const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
|
||||
const alertKey = `${pattern.message}_${messageContent.slice(0, 50)}_${Date.now()}`;
|
||||
|
||||
return {
|
||||
hasError: dismissedAlertKey !== alertKey,
|
||||
errorMessage: pattern.message,
|
||||
errorType: pattern.type,
|
||||
action: pattern.action,
|
||||
alertKey
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { hasError: false, errorMessage: null, errorType: null, action: undefined };
|
||||
}, [messages, dismissedAlertKey, onNewChat, onChangeModel]);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
if (errorMessage && lastMessage) {
|
||||
const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
|
||||
const alertKey = `${errorMessage}_${messageContent.slice(0, 50)}_${Date.now()}`;
|
||||
setDismissedAlertKey(alertKey);
|
||||
}
|
||||
}, [errorMessage, messages]);
|
||||
|
||||
return {
|
||||
hasError,
|
||||
errorMessage,
|
||||
errorType,
|
||||
action,
|
||||
dismiss
|
||||
};
|
||||
};
|
||||
@@ -1,5 +1,11 @@
|
||||
import { Tool } from './Tool';
|
||||
import type { ConsoleMessage } from '@/types/console';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
id: number;
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
export interface ReadConsoleMessagesParams {
|
||||
filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all';
|
||||
|
||||
@@ -79,14 +79,7 @@ export function ProjectView() {
|
||||
}
|
||||
}, [isPreviewable, mobileView, activeTab]);
|
||||
|
||||
// Clear console messages when projectId changes or component unmounts
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (projectId) {
|
||||
clearConsoleMessages();
|
||||
}
|
||||
};
|
||||
}, [projectId]);
|
||||
|
||||
|
||||
const handleNewChat = () => {
|
||||
// Reset to chat view on mobile when starting new chat
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
export interface ConsoleMessage {
|
||||
id: number;
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
timestamp?: number;
|
||||
}
|
||||
Reference in new issue
Block a user