From 561e5614c5e06b63e44959863a99784b09d75b9c Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 17:21:59 +0700 Subject: [PATCH 01/40] chat intervention component and flow --- src/components/Shakespeare/ChatPane.tsx | 142 +++++++++++++++++++++--- 1 file changed, 129 insertions(+), 13 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index e6dc2218..40e32994 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -40,6 +40,111 @@ import { makeSystemPrompt } from '@/lib/system'; import { assistantContentEmpty } from '@/lib/ai-messages'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { AlertTriangle, AlertCircle } from 'lucide-react'; + +const ALERT_TYPE = { + WARN: 'warn', + ERROR: 'error' +} as const; + +type AlertType = typeof ALERT_TYPE[keyof typeof ALERT_TYPE]; + +interface ChatAlert { + type: AlertType; + message: string; +} + +function ChatIntervention({ alert, onDismiss }: { alert: ChatAlert; onDismiss: () => void }) { + const isError = alert.type === ALERT_TYPE.ERROR; + + return ( + + {isError ? : } + + {alert.message} + + + + ); +} + +interface ErrorPattern { + test: (content: string) => boolean; + type: AlertType; + message: string; +} + +const ERROR_PATTERNS: ErrorPattern[] = [ + { + test: (content) => /AI service error: 422/.test(content) || /Provider returned error/.test(content), + type: ALERT_TYPE.ERROR, + message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.' + }, + { + test: (content) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content), + type: ALERT_TYPE.WARN, + message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.' + }, + { + test: (content) => /rate limit/i.test(content) || /too many requests/i.test(content), + type: ALERT_TYPE.WARN, + message: 'You\'re sending requests too quickly. Please wait a moment before trying again.' + } +]; + +function useChatAlert(messages: AIMessage[], scrollToBottom: () => void): { alert: ChatAlert | null; dismiss: () => void } { + const [dismissedAlert, setDismissedAlert] = useState(null); + const [prevAlert, setPrevAlert] = useState(null); + + const alert = useMemo(() => { + const lastMessage = messages[messages.length - 1]; + if (!lastMessage || lastMessage.role !== 'assistant') return null; + + const content = typeof lastMessage.content === 'string' ? lastMessage.content : ''; + + for (const pattern of ERROR_PATTERNS) { + if (pattern.test(content)) { + const alert = { + type: pattern.type, + message: pattern.message + }; + + // Only show if not dismissed + return dismissedAlert !== alert.message ? alert : null; + } + } + + return null; + }, [messages, dismissedAlert]); + + // Handle alert changes - scroll when alert appears/disappears + useEffect(() => { + const alertChanged = prevAlert !== alert; + if (alertChanged && alert) { + // Small delay to ensure alert is rendered + setTimeout(() => { + scrollToBottom(); + }, 50); + } + setPrevAlert(alert); + }, [alert, prevAlert, scrollToBottom]); + + const dismiss = useCallback(() => { + if (alert) { + setDismissedAlert(alert.message); + } + }, [alert]); + + return { alert, dismiss }; +} interface ChatPaneProps { projectId: string; @@ -211,6 +316,16 @@ export const ChatPane = forwardRef(({ } }, [internalIsLoading, onLoadingChange]); + // Function to scroll to bottom + const scrollToBottom = () => { + if (scrollAreaRef.current) { + scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight; + } + }; + + // Check for chat alerts based on messages + const { alert: chatAlert, dismiss: dismissAlert } = useChatAlert(messages, scrollToBottom); + // Check for autostart parameter and trigger AI generation useEffect(() => { const autostart = searchParams.get('autostart'); @@ -239,14 +354,6 @@ export const ChatPane = forwardRef(({ } }, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]); - - // Function to scroll to bottom - const scrollToBottom = () => { - if (scrollAreaRef.current) { - scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight; - } - }; - // Simple scroll event listener useEffect(() => { const container = scrollAreaRef.current; @@ -281,7 +388,6 @@ export const ChatPane = forwardRef(({ if (isNearBottom) { container.scrollTop = container.scrollHeight; } - } }, [messages, streamingMessage, isLoading]); @@ -400,7 +506,7 @@ export const ChatPane = forwardRef(({ await sendMessage(messageContent, modelToUse); } catch (error) { console.error('AI chat error:', error); - // Error handling is done in the useAIChat hook + // Error handling is done in the useAIChat hook and SessionManager } }; @@ -564,6 +670,17 @@ export const ChatPane = forwardRef(({ )} + + {/* Chat Alert */} + {chatAlert && ( +
+ +
+ )} + @@ -584,9 +701,8 @@ export const ChatPane = forwardRef(({
{/* Chat Input Container */}
Date: Mon, 22 Sep 2025 17:23:46 +0700 Subject: [PATCH 02/40] alert spacing --- src/components/Shakespeare/ChatPane.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 40e32994..bfad8b6e 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -673,12 +673,10 @@ export const ChatPane = forwardRef(({ {/* Chat Alert */} {chatAlert && ( -
- -
+ )}
From fb192b8657c6217dbe7ebdda18f008525c8a27ac Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 18:00:04 +0700 Subject: [PATCH 03/40] make model selector controlled --- src/components/ModelSelector.tsx | 44 +++++++++++++++++++------------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index 420be9d9..8b896c06 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -17,6 +17,8 @@ interface ModelSelectorProps { className?: string; disabled?: boolean; placeholder?: string; + open?: boolean; + onOpenChange?: (open: boolean) => void; } export function ModelSelector({ @@ -25,9 +27,15 @@ export function ModelSelector({ className, disabled = false, placeholder, + open: controlledOpen, + onOpenChange: setControlledOpen, }: ModelSelectorProps) { const { t } = useTranslation(); - const [open, setOpen] = useState(false); + const [uncontrolledOpen, setUncontrolledOpen] = useState(false); + + // Use controlled state if provided, otherwise use local state + const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen; + const setOpen = setControlledOpen || setUncontrolledOpen; const [isCustomInput, setIsCustomInput] = useState(false); const [customValue, setCustomValue] = useState(''); const { settings, addRecentlyUsedModel, isConfigured } = useAISettings(); @@ -140,23 +148,23 @@ export function ModelSelector({ return ( - - - + + + {isConfigured && } From f4190d22fb48758ecd581d902d14d6bb85674373 Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 18:15:31 +0700 Subject: [PATCH 04/40] expose a ref to the model selector --- src/components/ModelSelector.tsx | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index 8b896c06..aa4b7790 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -1,4 +1,4 @@ -import { useState, useMemo } from 'react'; +import { useState, useMemo, forwardRef, useImperativeHandle } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react'; @@ -21,7 +21,7 @@ interface ModelSelectorProps { onOpenChange?: (open: boolean) => void; } -export function ModelSelector({ +export const ModelSelector = forwardRef<{ open: () => void }, ModelSelectorProps>(({ value, onChange, className, @@ -29,13 +29,18 @@ export function ModelSelector({ placeholder, open: controlledOpen, onOpenChange: setControlledOpen, -}: ModelSelectorProps) { +}, ref) => { const { t } = useTranslation(); const [uncontrolledOpen, setUncontrolledOpen] = useState(false); // Use controlled state if provided, otherwise use local state const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen; const setOpen = setControlledOpen || setUncontrolledOpen; + + // Expose open method via ref + useImperativeHandle(ref, () => ({ + open: () => setOpen(true) + }), [setOpen]); const [isCustomInput, setIsCustomInput] = useState(false); const [customValue, setCustomValue] = useState(''); const { settings, addRecentlyUsedModel, isConfigured } = useAISettings(); @@ -287,4 +292,4 @@ export function ModelSelector({ ); -} \ No newline at end of file +}); \ No newline at end of file From 8e8976b9bcbdcdb81c56b5524ffc5fbccd73ec2f Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 18:30:02 +0700 Subject: [PATCH 05/40] chat intervention actions --- src/components/ModelSelector.tsx | 12 +-- src/components/Shakespeare/ChatPane.tsx | 121 +++++++++++++++++------- 2 files changed, 93 insertions(+), 40 deletions(-) diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index aa4b7790..590bca08 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -1,4 +1,4 @@ -import { useState, useMemo, forwardRef, useImperativeHandle } from 'react'; +import { useState, useMemo } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react'; @@ -21,7 +21,7 @@ interface ModelSelectorProps { onOpenChange?: (open: boolean) => void; } -export const ModelSelector = forwardRef<{ open: () => void }, ModelSelectorProps>(({ +export function ModelSelector({ value, onChange, className, @@ -29,7 +29,7 @@ export const ModelSelector = forwardRef<{ open: () => void }, ModelSelectorProps placeholder, open: controlledOpen, onOpenChange: setControlledOpen, -}, ref) => { +}: ModelSelectorProps) { const { t } = useTranslation(); const [uncontrolledOpen, setUncontrolledOpen] = useState(false); @@ -37,10 +37,6 @@ export const ModelSelector = forwardRef<{ open: () => void }, ModelSelectorProps const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen; const setOpen = setControlledOpen || setUncontrolledOpen; - // Expose open method via ref - useImperativeHandle(ref, () => ({ - open: () => setOpen(true) - }), [setOpen]); const [isCustomInput, setIsCustomInput] = useState(false); const [customValue, setCustomValue] = useState(''); const { settings, addRecentlyUsedModel, isConfigured } = useAISettings(); @@ -292,4 +288,4 @@ export const ModelSelector = forwardRef<{ open: () => void }, ModelSelectorProps ); -}); \ No newline at end of file +} \ No newline at end of file diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index bfad8b6e..51ce0225 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -53,6 +53,10 @@ type AlertType = typeof ALERT_TYPE[keyof typeof ALERT_TYPE]; interface ChatAlert { type: AlertType; message: string; + action?: { + label: string; + onClick: () => void; + }; } function ChatIntervention({ alert, onDismiss }: { alert: ChatAlert; onDismiss: () => void }) { @@ -61,16 +65,34 @@ function ChatIntervention({ alert, onDismiss }: { alert: ChatAlert; onDismiss: ( return ( {isError ? : } - - {alert.message} - + +
+ {alert.message} + +
+ {alert.action && ( +
+ +
+ )}
); @@ -80,41 +102,62 @@ interface ErrorPattern { test: (content: string) => boolean; type: AlertType; message: string; + action?: { + label: string; + onClick: () => void; + }; } -const ERROR_PATTERNS: ErrorPattern[] = [ - { - test: (content) => /AI service error: 422/.test(content) || /Provider returned error/.test(content), - type: ALERT_TYPE.ERROR, - message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.' - }, - { - test: (content) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content), - type: ALERT_TYPE.WARN, - message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.' - }, - { - test: (content) => /rate limit/i.test(content) || /too many requests/i.test(content), - type: ALERT_TYPE.WARN, - message: 'You\'re sending requests too quickly. Please wait a moment before trying again.' - } -]; -function useChatAlert(messages: AIMessage[], scrollToBottom: () => void): { alert: ChatAlert | null; dismiss: () => void } { +function useChatAlert( + messages: AIMessage[], + scrollToBottom: () => void, + onNewChat?: () => void, + openModelSelector?: () => void +): { alert: ChatAlert | null; dismiss: () => void } { const [dismissedAlert, setDismissedAlert] = useState(null); const [prevAlert, setPrevAlert] = useState(null); + const alert = useMemo(() => { const lastMessage = messages[messages.length - 1]; if (!lastMessage || lastMessage.role !== 'assistant') return null; const content = typeof lastMessage.content === 'string' ? lastMessage.content : ''; - for (const pattern of ERROR_PATTERNS) { + // Define error patterns inside the useMemo + const errorPatterns: ErrorPattern[] = [ + { + test: (content) => /AI service error: 422/.test(content) || /Provider returned error/.test(content), + type: ALERT_TYPE.ERROR, + message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.', + action: openModelSelector ? { + label: 'Change model', + onClick: openModelSelector + } : undefined + }, + { + test: (content) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content), + type: ALERT_TYPE.WARN, + 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) => /rate limit/i.test(content) || /too many requests/i.test(content), + type: ALERT_TYPE.WARN, + message: 'You\'re sending requests too quickly. Please wait a moment before trying again.' + } + ]; + + for (const pattern of errorPatterns) { if (pattern.test(content)) { const alert = { type: pattern.type, - message: pattern.message + message: pattern.message, + action: pattern.action }; // Only show if not dismissed @@ -123,7 +166,7 @@ function useChatAlert(messages: AIMessage[], scrollToBottom: () => void): { aler } return null; - }, [messages, dismissedAlert]); + }, [messages, dismissedAlert, onNewChat, openModelSelector]); // Handle alert changes - scroll when alert appears/disappears useEffect(() => { @@ -190,6 +233,8 @@ export const ChatPane = forwardRef(({ // Initialize with first recently used model if available, otherwise empty return settings.recentlyUsedModels?.[0] || ''; }); + // State to control model selector dropdown + const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false); useEffect(() => { if (!providerModel && settings.recentlyUsedModels?.length) { @@ -323,8 +368,18 @@ export const ChatPane = forwardRef(({ } }; + // Function to open model selector dropdown + const openModelSelector = useCallback(() => { + setIsModelSelectorOpen(true); + }, []); + // Check for chat alerts based on messages - const { alert: chatAlert, dismiss: dismissAlert } = useChatAlert(messages, scrollToBottom); + const { alert: chatAlert, dismiss: dismissAlert } = useChatAlert( + messages, + scrollToBottom, + _onNewChat, + openModelSelector + ); // Check for autostart parameter and trigger AI generation useEffect(() => { @@ -787,6 +842,8 @@ export const ChatPane = forwardRef(({ className="w-full" disabled={isLoading} placeholder={t('chooseModel')} + open={isModelSelectorOpen} + onOpenChange={setIsModelSelectorOpen} />
From 999c250216aafa2f4eadd6a5bbcce0fecd97a4c2 Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 19:29:00 +0700 Subject: [PATCH 06/40] #keepnostrweird quilly to thee rescue --- src/assets/quilly.svg | 114 ++++++++++++++++++++++++ src/components/Shakespeare/ChatPane.tsx | 69 +++++++------- src/components/ui/QuillySVG.tsx | 63 +++++++++++++ 3 files changed, 215 insertions(+), 31 deletions(-) create mode 100644 src/assets/quilly.svg create mode 100644 src/components/ui/QuillySVG.tsx diff --git a/src/assets/quilly.svg b/src/assets/quilly.svg new file mode 100644 index 00000000..e26247fc --- /dev/null +++ b/src/assets/quilly.svg @@ -0,0 +1,114 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 51ce0225..e973642e 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -41,7 +41,7 @@ import { assistantContentEmpty } from '@/lib/ai-messages'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; import { Alert, AlertDescription } from '@/components/ui/alert'; -import { AlertTriangle, AlertCircle } from 'lucide-react'; +import { QuillySVG } from '@/components/ui/QuillySVG'; const ALERT_TYPE = { WARN: 'warn', @@ -63,37 +63,44 @@ function ChatIntervention({ alert, onDismiss }: { alert: ChatAlert; onDismiss: ( const isError = alert.type === ALERT_TYPE.ERROR; return ( - - {isError ? : } - -
- {alert.message} - + +
+ +
+ +
+

+ Pardon the Interruption +

+

{alert.message}

+
+ {alert.action && ( +
+ +
+ )} +
- {alert.action && ( -
- -
- )} - + +
); } diff --git a/src/components/ui/QuillySVG.tsx b/src/components/ui/QuillySVG.tsx new file mode 100644 index 00000000..f7e7ceb3 --- /dev/null +++ b/src/components/ui/QuillySVG.tsx @@ -0,0 +1,63 @@ +import React from 'react'; + +interface QuillySVGProps extends React.SVGProps { + className?: string; + fillColor?: string; +} + +export function QuillySVG({ className = "w-4 h-4", fillColor = "currentColor", ...props }: QuillySVGProps) { + return ( + + {/* Main quill head/top part */} + + + {/* Main quill feather/plume part */} + + + {/* Body/torso part */} + + + {/* Additional body details */} + + + {/* Eyes */} + + + + {/* Extended body details */} + + + {/* Main body section */} + + + {/* Additional body details */} + + + {/* Body shading */} + + + {/* More body shading */} + + + {/* Lower body/legs area */} + + + {/* Extended body section */} + + + {/* Additional details */} + + + {/* Final details */} + + + {/* Bottom section */} + + + ); +} \ No newline at end of file From c97117db5d55c40eb23d837b2d622f0ce01d3ea4 Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 19:34:49 +0700 Subject: [PATCH 07/40] quilly beautification --- src/components/Shakespeare/ChatPane.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index e973642e..71a55104 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -63,16 +63,16 @@ function ChatIntervention({ alert, onDismiss }: { alert: ChatAlert; onDismiss: ( const isError = alert.type === ALERT_TYPE.ERROR; return ( - +
- +
- +
-

+

Pardon the Interruption

-

{alert.message}

+

{alert.message}

{alert.action && (
@@ -90,7 +90,7 @@ function ChatIntervention({ alert, onDismiss }: { alert: ChatAlert; onDismiss: (
)} - +
- +
); } From c38113c9b89c6fe4f13c65e59122d9af008e44dc Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 20:19:08 +0700 Subject: [PATCH 08/40] wip catch errors from the app and offer to help fix --- src/components/Shakespeare/ChatPane.tsx | 177 +++++++------------ src/components/Shakespeare/PreviewPane.tsx | 189 ++++++++++----------- src/hooks/useConsoleMessages.ts | 79 +++++++++ src/hooks/useErrorDetection.ts | 113 ++++++++++++ 4 files changed, 345 insertions(+), 213 deletions(-) create mode 100644 src/hooks/useConsoleMessages.ts create mode 100644 src/hooks/useErrorDetection.ts diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 71a55104..ba574047 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -40,12 +40,14 @@ import { makeSystemPrompt } from '@/lib/system'; import { assistantContentEmpty } from '@/lib/ai-messages'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; +import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { QuillySVG } from '@/components/ui/QuillySVG'; const ALERT_TYPE = { WARN: 'warn', - ERROR: 'error' + ERROR: 'error', + CONSOLE_ERROR: 'console_error' } as const; type AlertType = typeof ALERT_TYPE[keyof typeof ALERT_TYPE]; @@ -59,9 +61,17 @@ interface ChatAlert { }; } -function ChatIntervention({ alert, onDismiss }: { alert: ChatAlert; onDismiss: () => void }) { - const isError = alert.type === ALERT_TYPE.ERROR; - +function ChatIntervention({ + type, + message, + onDismiss, + action +}: { + type: string; + message: string; + onDismiss: () => void; + action?: { label: string; onClick: () => void }; +}) { return (
@@ -70,23 +80,19 @@ function ChatIntervention({ alert, onDismiss }: { alert: ChatAlert; onDismiss: (

- Pardon the Interruption + Pardon the interruption

-

{alert.message}

+

{message}

- {alert.action && ( + {action && (
)} @@ -105,96 +111,7 @@ function ChatIntervention({ alert, onDismiss }: { alert: ChatAlert; onDismiss: ( ); } -interface ErrorPattern { - test: (content: string) => boolean; - type: AlertType; - message: string; - action?: { - label: string; - onClick: () => void; - }; -} - - -function useChatAlert( - messages: AIMessage[], - scrollToBottom: () => void, - onNewChat?: () => void, - openModelSelector?: () => void -): { alert: ChatAlert | null; dismiss: () => void } { - const [dismissedAlert, setDismissedAlert] = useState(null); - const [prevAlert, setPrevAlert] = useState(null); - - - const alert = useMemo(() => { - const lastMessage = messages[messages.length - 1]; - if (!lastMessage || lastMessage.role !== 'assistant') return null; - - const content = typeof lastMessage.content === 'string' ? lastMessage.content : ''; - - // Define error patterns inside the useMemo - const errorPatterns: ErrorPattern[] = [ - { - test: (content) => /AI service error: 422/.test(content) || /Provider returned error/.test(content), - type: ALERT_TYPE.ERROR, - message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.', - action: openModelSelector ? { - label: 'Change model', - onClick: openModelSelector - } : undefined - }, - { - test: (content) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content), - type: ALERT_TYPE.WARN, - 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) => /rate limit/i.test(content) || /too many requests/i.test(content), - type: ALERT_TYPE.WARN, - message: 'You\'re sending requests too quickly. Please wait a moment before trying again.' - } - ]; - - for (const pattern of errorPatterns) { - if (pattern.test(content)) { - const alert = { - type: pattern.type, - message: pattern.message, - action: pattern.action - }; - - // Only show if not dismissed - return dismissedAlert !== alert.message ? alert : null; - } - } - - return null; - }, [messages, dismissedAlert, onNewChat, openModelSelector]); - - // Handle alert changes - scroll when alert appears/disappears - useEffect(() => { - const alertChanged = prevAlert !== alert; - if (alertChanged && alert) { - // Small delay to ensure alert is rendered - setTimeout(() => { - scrollToBottom(); - }, 50); - } - setPrevAlert(alert); - }, [alert, prevAlert, scrollToBottom]); - - const dismiss = useCallback(() => { - if (alert) { - setDismissedAlert(alert.message); - } - }, [alert]); - - return { alert, dismiss }; -} +// Clean interfaces now handled by proper hooks interface ChatPaneProps { projectId: string; @@ -380,13 +297,30 @@ export const ChatPane = forwardRef(({ setIsModelSelectorOpen(true); }, []); - // Check for chat alerts based on messages - const { alert: chatAlert, dismiss: dismissAlert } = useChatAlert( - messages, - scrollToBottom, - _onNewChat, - openModelSelector - ); + // Function to suggest error fix + // Clean alert hooks with proper interfaces + const aiModelAlert = useAIModelErrorAlert(messages); + const consoleAlert = useConsoleErrorAlert(); + + const suggestErrorFix = useCallback((errorMessage: string, errorCount: number) => { + const errorText = errorCount === 1 ? 'this error' : 'these errors'; + setInput(`The user gets ${errorText} in the app now: ${errorMessage}\n\nCan you identify the problem and create a concise fix.`); + }, []); + + const getAIModelAction = useCallback((errorType: 'warn' | 'error' | null) => { + if (errorType === 'error') { + return { + label: 'Change model', + onClick: openModelSelector + }; + } else if (errorType === 'warn') { + return { + label: 'New chat', + onClick: _onNewChat + }; + } + return undefined; + }, [openModelSelector, _onNewChat]); // Check for autostart parameter and trigger AI generation useEffect(() => { @@ -733,11 +667,26 @@ export const ChatPane = forwardRef(({
)} - {/* Chat Alert */} - {chatAlert && ( + {/* AI Model Alert */} + {aiModelAlert.hasError && ( + )} + + {/* Console Error Alert */} + {consoleAlert.hasError && ( + suggestErrorFix(consoleAlert.errorSummary || '', consoleAlert.errorCount) + }} /> )} diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 7d7ed0d7..a5424484 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -3,6 +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 { useConsoleMessages, addConsoleMessage, clearConsoleMessages, type ConsoleMessage } from '@/hooks/useConsoleMessages'; import { Tabs, TabsContent } from '@/components/ui/tabs'; import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'; import { Button } from '@/components/ui/button'; @@ -57,11 +58,6 @@ interface JSONRPCResponse { id: number; } -interface ConsoleMessage { - id: number; - level: 'log' | 'warn' | 'error' | 'info' | 'debug'; - message: string; -} export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const { t } = useTranslation(); @@ -74,11 +70,11 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const [currentPath, setCurrentPath] = useState('/'); const [navigationHistory, setNavigationHistory] = useState(['/']); const [historyIndex, setHistoryIndex] = useState(0); - const [consoleMessages, setConsoleMessages] = useState([]); const [copiedMessageId, setCopiedMessageId] = useState(null); const iframeRef = useRef(null); const { fs } = useFS(); const projectsManager = useProjectsManager(); + const { messages: consoleMessages } = useConsoleMessages(); const loadFileContent = useCallback(async (filePath: string) => { setIsLoading(true); @@ -219,13 +215,8 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { normalizedLevel = params.level as ConsoleMessage['level']; } - const newConsoleMessage: ConsoleMessage = { - id: Date.now(), - level: normalizedLevel, - message: params.message, - }; - - setConsoleMessages(prev => [...prev, newConsoleMessage]); + // Add to global console messages + addConsoleMessage(normalizedLevel, params.message); // Log to parent console for debugging with appropriate level console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`); @@ -399,100 +390,100 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { }; const ConsoleDropdown = () => { - const getLevelColor = (level: ConsoleMessage['level']) => { - switch (level) { - case 'error': return 'text-red-500'; - case 'warn': return 'text-yellow-500'; - case 'info': return 'text-blue-500'; - case 'debug': return 'text-gray-500'; - default: return 'text-gray-400'; - } - }; + const getLevelColor = (level: ConsoleMessage['level']) => { + switch (level) { + case 'error': return 'text-red-500'; + case 'warn': return 'text-yellow-500'; + case 'info': return 'text-blue-500'; + case 'debug': return 'text-gray-500'; + default: return 'text-gray-400'; + } + }; - const getLevelIcon = (level: ConsoleMessage['level']) => { - switch (level) { - case 'error': return '!'; - case 'warn': return '⚠'; - case 'info': return 'ℹ'; - case 'debug': return '🔍'; - default: return '•'; - } - }; + const getLevelIcon = (level: ConsoleMessage['level']) => { + switch (level) { + case 'error': return '!'; + case 'warn': return '⚠'; + case 'info': return 'ℹ'; + case 'debug': return '🔍'; + default: return '•'; + } + }; - const clearConsole = () => { - setConsoleMessages([]); - }; + const clearConsole = () => { + clearConsoleMessages(); + }; - const copyMessageToClipboard = async (msg: ConsoleMessage) => { - try { - // Create a formatted string with all message details - const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`; + const copyMessageToClipboard = async (msg: ConsoleMessage) => { + try { + // Create a formatted string with all message details + const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`; - await navigator.clipboard.writeText(formattedMessage); - setCopiedMessageId(msg.id); + await navigator.clipboard.writeText(formattedMessage); + setCopiedMessageId(msg.id); - // Reset the copied state after 2 seconds - setTimeout(() => { - setCopiedMessageId(null); - }, 2000); - } catch (error) { - console.error('Failed to copy message to clipboard:', error); - } - }; + // Reset the copied state after 2 seconds + setTimeout(() => { + setCopiedMessageId(null); + }, 2000); + } catch (error) { + console.error('Failed to copy message to clipboard:', error); + } + }; - return ( - - - - - -
- Console Output ({consoleMessages.length}) - -
- -
- {consoleMessages.length === 0 ? ( -
- No console messages -
- ) : ( - consoleMessages.map((msg) => ( -
-
-
{getLevelIcon(msg.level)} {msg.message}
- -
-
- )) + return ( + + + + + +
+ Console Output ({consoleMessages.length}) +
- -
-
- ); -}; + +
+ {consoleMessages.length === 0 ? ( +
+ No console messages +
+ ) : ( + consoleMessages.map((msg) => ( +
+
+
{getLevelIcon(msg.level)} {msg.message}
+ +
+
+ )) + )} +
+
+ + + ); + }; return (
diff --git a/src/hooks/useConsoleMessages.ts b/src/hooks/useConsoleMessages.ts new file mode 100644 index 00000000..b5340e19 --- /dev/null +++ b/src/hooks/useConsoleMessages.ts @@ -0,0 +1,79 @@ +import { useState, useCallback, useEffect } from 'react'; + +export interface ConsoleMessage { + id: number; + level: 'log' | 'warn' | 'error' | 'info' | 'debug'; + message: string; + timestamp: number; +} + +// Global state for console messages +let globalConsoleMessages: ConsoleMessage[] = []; +let listeners: Set<(messages: ConsoleMessage[]) => void> = new Set(); + +const notifyListeners = () => { + listeners.forEach(listener => listener([...globalConsoleMessages])); +}; + +export const useConsoleMessages = () => { + const [messages, setMessages] = useState(globalConsoleMessages); + + const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => { + const newMessage: ConsoleMessage = { + id: Date.now() + Math.random(), // Ensure uniqueness + level, + message, + timestamp: Date.now(), + }; + + globalConsoleMessages = [...globalConsoleMessages, newMessage]; + notifyListeners(); + }, []); + + const clearMessages = useCallback(() => { + globalConsoleMessages = []; + notifyListeners(); + }, []); + + const getErrorsSince = useCallback((timestamp: number) => { + return globalConsoleMessages.filter( + msg => msg.level === 'error' && msg.timestamp > timestamp + ); + }, []); + + // Subscribe to global state changes + useEffect(() => { + const listener = (newMessages: ConsoleMessage[]) => { + setMessages(newMessages); + }; + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, []); + + return { + messages, + addMessage, + clearMessages, + getErrorsSince, + }; +}; + +// Export functions for external use (like PreviewPane) +export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { + const newMessage: ConsoleMessage = { + id: Date.now() + Math.random(), + level, + message, + timestamp: Date.now(), + }; + + globalConsoleMessages = [...globalConsoleMessages, newMessage]; + notifyListeners(); +}; + +export const clearConsoleMessages = () => { + globalConsoleMessages = []; + notifyListeners(); +}; diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts new file mode 100644 index 00000000..ef76533b --- /dev/null +++ b/src/hooks/useErrorDetection.ts @@ -0,0 +1,113 @@ +import { useState, useCallback, useMemo } from 'react'; +import { useConsoleMessages } from './useConsoleMessages'; + +export interface ConsoleErrorAlert { + hasError: boolean; + errorSummary: string | null; + errorCount: number; + dismiss: () => void; +} + +export const useConsoleErrorAlert = (): ConsoleErrorAlert => { + const { messages } = useConsoleMessages(); + const [dismissedErrorSummary, setDismissedErrorSummary] = useState(''); + + const { hasError, errorSummary, errorCount } = useMemo(() => { + const errors = messages.filter(msg => msg.level === 'error'); + + if (errors.length === 0) { + return { hasError: false, errorSummary: null, errorCount: 0 }; + } + + // Just return the raw error messages, no formatting + const summary = errors.slice(-3).map(e => e.message).join('\n'); + + return { + hasError: dismissedErrorSummary !== summary, + errorSummary: summary, + errorCount: errors.length + }; + }, [messages, dismissedErrorSummary]); + + 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; + dismiss: () => void; +} + +export const useAIModelErrorAlert = (messages: any[]): AIModelErrorAlert => { + const [dismissedAlertKey, setDismissedAlertKey] = useState(''); + + const { hasError, errorMessage, errorType } = useMemo(() => { + const lastMessage = messages[messages.length - 1]; + if (!lastMessage || lastMessage.role !== 'assistant') { + return { hasError: false, errorMessage: null, errorType: null }; + } + + const content = typeof lastMessage.content === 'string' ? lastMessage.content : ''; + + // Define error patterns + 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.' + }, + { + 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.' + }, + { + 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 alertKey = `${pattern.message}_${lastMessage.id || Date.now()}`; + + return { + hasError: dismissedAlertKey !== alertKey, + errorMessage: pattern.message, + errorType: pattern.type, + alertKey + }; + } + } + + return { hasError: false, errorMessage: null, errorType: null }; + }, [messages, dismissedAlertKey]); + + const dismiss = useCallback(() => { + const lastMessage = messages[messages.length - 1]; + if (errorMessage && lastMessage) { + const alertKey = `${errorMessage}_${lastMessage.id || Date.now()}`; + setDismissedAlertKey(alertKey); + } + }, [errorMessage, messages]); + + return { + hasError, + errorMessage, + errorType, + dismiss + }; +}; From ff95c13f8418be53060404cd6d514eceff823e41 Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 20:33:39 +0700 Subject: [PATCH 09/40] fix scroll to bottom on alert --- src/components/Shakespeare/ChatPane.tsx | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index ba574047..0a0a6aef 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -302,6 +302,15 @@ export const ChatPane = forwardRef(({ const aiModelAlert = useAIModelErrorAlert(messages); const consoleAlert = useConsoleErrorAlert(); + // Scroll to bottom when alerts appear + useEffect(() => { + if (aiModelAlert.hasError || consoleAlert.hasError) { + setTimeout(() => { + scrollToBottom(); + }, 50); + } + }, [aiModelAlert.hasError, consoleAlert.hasError, scrollToBottom]); + const suggestErrorFix = useCallback((errorMessage: string, errorCount: number) => { const errorText = errorCount === 1 ? 'this error' : 'these errors'; setInput(`The user gets ${errorText} in the app now: ${errorMessage}\n\nCan you identify the problem and create a concise fix.`); From 0e80915d581ec4fe3e089b6c0e81587058f30f32 Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 20:54:43 +0700 Subject: [PATCH 10/40] define actions in errorPatterns --- src/components/Shakespeare/ChatPane.tsx | 18 ++---------------- src/hooks/useErrorDetection.ts | 25 +++++++++++++++++-------- 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 0a0a6aef..032120ca 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -299,7 +299,7 @@ export const ChatPane = forwardRef(({ // Function to suggest error fix // Clean alert hooks with proper interfaces - const aiModelAlert = useAIModelErrorAlert(messages); + const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector); const consoleAlert = useConsoleErrorAlert(); // Scroll to bottom when alerts appear @@ -316,20 +316,6 @@ export const ChatPane = forwardRef(({ setInput(`The user gets ${errorText} in the app now: ${errorMessage}\n\nCan you identify the problem and create a concise fix.`); }, []); - const getAIModelAction = useCallback((errorType: 'warn' | 'error' | null) => { - if (errorType === 'error') { - return { - label: 'Change model', - onClick: openModelSelector - }; - } else if (errorType === 'warn') { - return { - label: 'New chat', - onClick: _onNewChat - }; - } - return undefined; - }, [openModelSelector, _onNewChat]); // Check for autostart parameter and trigger AI generation useEffect(() => { @@ -682,7 +668,7 @@ export const ChatPane = forwardRef(({ type={aiModelAlert.errorType || 'error'} message={aiModelAlert.errorMessage || ''} onDismiss={aiModelAlert.dismiss} - action={getAIModelAction(aiModelAlert.errorType)} + action={aiModelAlert.action} /> )} diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts index ef76533b..c64c4417 100644 --- a/src/hooks/useErrorDetection.ts +++ b/src/hooks/useErrorDetection.ts @@ -47,31 +47,38 @@ export interface AIModelErrorAlert { hasError: boolean; errorMessage: string | null; errorType: 'warn' | 'error' | null; + action?: { label: string; onClick: () => void }; dismiss: () => void; } -export const useAIModelErrorAlert = (messages: any[]): AIModelErrorAlert => { +export const useAIModelErrorAlert = ( + messages: any[], + onNewChat?: () => void, + onChangeModel?: () => void +): AIModelErrorAlert => { const [dismissedAlertKey, setDismissedAlertKey] = useState(''); - const { hasError, errorMessage, errorType } = useMemo(() => { + const { hasError, errorMessage, errorType, action } = useMemo(() => { const lastMessage = messages[messages.length - 1]; if (!lastMessage || lastMessage.role !== 'assistant') { - return { hasError: false, errorMessage: null, errorType: null }; + return { hasError: false, errorMessage: null, errorType: null, action: undefined }; } const content = typeof lastMessage.content === 'string' ? lastMessage.content : ''; - // Define error patterns + // 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.' + 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.' + 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), @@ -88,13 +95,14 @@ export const useAIModelErrorAlert = (messages: any[]): AIModelErrorAlert => { hasError: dismissedAlertKey !== alertKey, errorMessage: pattern.message, errorType: pattern.type, + action: pattern.action, alertKey }; } } - return { hasError: false, errorMessage: null, errorType: null }; - }, [messages, dismissedAlertKey]); + return { hasError: false, errorMessage: null, errorType: null, action: undefined }; + }, [messages, dismissedAlertKey, onNewChat, onChangeModel]); const dismiss = useCallback(() => { const lastMessage = messages[messages.length - 1]; @@ -108,6 +116,7 @@ export const useAIModelErrorAlert = (messages: any[]): AIModelErrorAlert => { hasError, errorMessage, errorType, + action, dismiss }; }; From 37e15ac78616f51cc6e464f0b6176889595b540e Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 22:28:01 +0700 Subject: [PATCH 11/40] lint / text fixes --- src/components/Shakespeare/ChatPane.tsx | 27 +++---------------------- src/hooks/useConsoleMessages.ts | 2 +- src/hooks/useErrorDetection.ts | 3 ++- 3 files changed, 6 insertions(+), 26 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index f9af956c..9a1b372b 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -41,33 +41,14 @@ import { assistantContentEmpty } from '@/lib/ai-messages'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection'; -import { Alert, AlertDescription } from '@/components/ui/alert'; import { QuillySVG } from '@/components/ui/QuillySVG'; -const ALERT_TYPE = { - WARN: 'warn', - ERROR: 'error', - CONSOLE_ERROR: 'console_error' -} as const; - -type AlertType = typeof ALERT_TYPE[keyof typeof ALERT_TYPE]; - -interface ChatAlert { - type: AlertType; - message: string; - action?: { - label: string; - onClick: () => void; - }; -} function ChatIntervention({ - type, message, onDismiss, action }: { - type: string; message: string; onDismiss: () => void; action?: { label: string; onClick: () => void }; @@ -281,11 +262,11 @@ export const ChatPane = forwardRef(({ }, [internalIsLoading, onLoadingChange]); // Function to scroll to bottom - const scrollToBottom = () => { + const scrollToBottom = useCallback(() => { if (scrollAreaRef.current) { scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight; } - }; + }, []); // Function to open model selector dropdown const openModelSelector = useCallback(() => { @@ -388,7 +369,7 @@ export const ChatPane = forwardRef(({ return () => clearTimeout(timer); } - }, [projectId, scrolledProjects]); + }, [projectId, scrolledProjects, scrollToBottom]); const handleFileSelect = (file: File) => { setAttachedFiles(prev => [...prev, file]); @@ -660,7 +641,6 @@ export const ChatPane = forwardRef(({ {/* AI Model Alert */} {aiModelAlert.hasError && ( (({ {/* Console Error Alert */} {consoleAlert.hasError && ( void> = new Set(); +const listeners: Set<(messages: ConsoleMessage[]) => void> = new Set(); const notifyListeners = () => { listeners.forEach(listener => listener([...globalConsoleMessages])); diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts index c64c4417..209d12d6 100644 --- a/src/hooks/useErrorDetection.ts +++ b/src/hooks/useErrorDetection.ts @@ -1,4 +1,5 @@ import { useState, useCallback, useMemo } from 'react'; +import OpenAI from 'openai'; import { useConsoleMessages } from './useConsoleMessages'; export interface ConsoleErrorAlert { @@ -52,7 +53,7 @@ export interface AIModelErrorAlert { } export const useAIModelErrorAlert = ( - messages: any[], + messages: OpenAI.Chat.Completions.ChatCompletionMessage[], onNewChat?: () => void, onChangeModel?: () => void ): AIModelErrorAlert => { From 3a8e040212a84586ccf477f1ffcd158f2d0509f5 Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 22:48:26 +0700 Subject: [PATCH 12/40] lint --- src/hooks/useErrorDetection.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts index 209d12d6..832472e8 100644 --- a/src/hooks/useErrorDetection.ts +++ b/src/hooks/useErrorDetection.ts @@ -1,5 +1,5 @@ import { useState, useCallback, useMemo } from 'react'; -import OpenAI from 'openai'; +import type { AIMessage } from '@/lib/SessionManager'; import { useConsoleMessages } from './useConsoleMessages'; export interface ConsoleErrorAlert { @@ -53,7 +53,7 @@ export interface AIModelErrorAlert { } export const useAIModelErrorAlert = ( - messages: OpenAI.Chat.Completions.ChatCompletionMessage[], + messages: AIMessage[], onNewChat?: () => void, onChangeModel?: () => void ): AIModelErrorAlert => { @@ -90,7 +90,8 @@ export const useAIModelErrorAlert = ( for (const pattern of errorPatterns) { if (pattern.test(content)) { - const alertKey = `${pattern.message}_${lastMessage.id || Date.now()}`; + 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, @@ -108,7 +109,8 @@ export const useAIModelErrorAlert = ( const dismiss = useCallback(() => { const lastMessage = messages[messages.length - 1]; if (errorMessage && lastMessage) { - const alertKey = `${errorMessage}_${lastMessage.id || Date.now()}`; + 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]); From e88a11ce210b74287d36aa15bad2982df0d1c94b Mon Sep 17 00:00:00 2001 From: sam Date: Mon, 22 Sep 2025 22:55:46 +0700 Subject: [PATCH 13/40] most recent error only --- src/components/Shakespeare/ChatPane.tsx | 2 +- src/hooks/useErrorDetection.ts | 40 +++++++++++++++++++++---- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 9a1b372b..604679a2 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -276,7 +276,7 @@ export const ChatPane = forwardRef(({ // Function to suggest error fix // Clean alert hooks with proper interfaces const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector); - const consoleAlert = useConsoleErrorAlert(); + const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading); // Scroll to bottom when alerts appear useEffect(() => { diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts index 832472e8..9a100f85 100644 --- a/src/hooks/useErrorDetection.ts +++ b/src/hooks/useErrorDetection.ts @@ -9,26 +9,51 @@ export interface ConsoleErrorAlert { dismiss: () => void; } -export const useConsoleErrorAlert = (): ConsoleErrorAlert => { +export const useConsoleErrorAlert = ( + aiMessages: AIMessage[], + isBuilding?: boolean, + isLoading?: boolean +): ConsoleErrorAlert => { const { messages } = useConsoleMessages(); const [dismissedErrorSummary, setDismissedErrorSummary] = useState(''); const { hasError, errorSummary, errorCount } = useMemo(() => { - const errors = messages.filter(msg => msg.level === 'error'); + // Don't show alerts while building or AI is working + if (isBuilding || isLoading) { + return { hasError: false, errorSummary: null, errorCount: 0 }; + } - if (errors.length === 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 recentErrors = messages.filter(msg => + msg.level === 'error' && + msg.timestamp > recentTimeThreshold + ); + + if (recentErrors.length === 0) { return { hasError: false, errorSummary: null, errorCount: 0 }; } // Just return the raw error messages, no formatting - const summary = errors.slice(-3).map(e => e.message).join('\n'); + const summary = recentErrors.slice(-3).map(e => e.message).join('\n'); return { hasError: dismissedErrorSummary !== summary, errorSummary: summary, - errorCount: errors.length + errorCount: recentErrors.length }; - }, [messages, dismissedErrorSummary]); + }, [messages, dismissedErrorSummary, aiMessages, isBuilding, isLoading]); const dismiss = useCallback(() => { if (errorSummary) { @@ -61,6 +86,9 @@ export const useAIModelErrorAlert = ( 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 }; } From c9073bb4bd6add1294ac0a78b3c0ecb5d15b4acb Mon Sep 17 00:00:00 2001 From: sam Date: Tue, 23 Sep 2025 14:34:50 +0700 Subject: [PATCH 14/40] wip: when creating a project fails, check for auth errors with the api call to feed back to the user what/why we had an issue --- src/components/ui/toast.tsx | 4 +-- src/lib/i18n.ts | 20 +++++++++++++ src/pages/Index.tsx | 56 +++++++++++++++++++++++++++++++++---- 3 files changed, 73 insertions(+), 7 deletions(-) diff --git a/src/components/ui/toast.tsx b/src/components/ui/toast.tsx index a8224775..38fdfa25 100644 --- a/src/components/ui/toast.tsx +++ b/src/components/ui/toast.tsx @@ -14,7 +14,7 @@ const ToastViewport = React.forwardRef< , React.ComponentPropsWithoutRef & - VariantProps + VariantProps >(({ className, variant, ...props }, ref) => { return ( { // Initialize with first recently used model if available, otherwise empty return settings.recentlyUsedModels?.[0] || ''; @@ -41,6 +45,48 @@ export default function Index() { // Check if any providers are configured const hasProvidersConfigured = settings.providers.length > 0; + // Check for API key failures and show appropriate toast + const checkForKeyFailure = (error: unknown): boolean => { + if (!(error instanceof Error)) return false; + + const message = error.message.toLowerCase(); + const isAuthError = ( + message.includes('401') || + message.includes('unauthorized') || + message.includes('no auth credentials') || + message.includes('invalid api key') || + message.includes('authentication failed') + ); + + if (isAuthError) { + // Get provider name inline + let providerName = 'Provider'; + try { + const { provider } = parseProviderModel(providerModel, settings.providers); + providerName = provider.charAt(0).toUpperCase() + provider.slice(1); + } catch { + // Keep default 'Provider' + } + + toast({ + title: t('apiAuthenticationFailed'), + description: t('invalidApiKey', { provider: providerName }), + variant: 'destructive', + action: ( + navigate('/settings/ai')} + > + {t('checkApiKeySettings')} + + ), + }); + } + + return isAuthError; + }; + + useEffect(() => { if (!providerModel && settings.recentlyUsedModels?.length) { setProviderModel(settings.recentlyUsedModels[0]); @@ -185,6 +231,7 @@ export default function Index() { navigate(`/project/${project.id}?${searchParams.toString()}`); } catch (error) { console.error('Failed to create project:', error); + checkForKeyFailure(error); } finally { setIsCreating(false); } @@ -209,9 +256,8 @@ export default function Index() {
{/* Chat Input Container - matching the ChatPane style */}
Date: Tue, 23 Sep 2025 15:07:02 +0700 Subject: [PATCH 15/40] catch the error bubbled up exactly --- src/pages/Index.tsx | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index b35d3a02..6840eaae 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -13,6 +13,7 @@ import { OnboardingDialog } from '@/components/OnboardingDialog'; import { DotAI } from '@/lib/DotAI'; import { parseProviderModel } from '@/lib/parseProviderModel'; import type { AIMessage } from '@/lib/SessionManager'; +import { AuthenticationError } from 'openai'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; @@ -47,16 +48,9 @@ export default function Index() { // Check for API key failures and show appropriate toast const checkForKeyFailure = (error: unknown): boolean => { - if (!(error instanceof Error)) return false; - - const message = error.message.toLowerCase(); - const isAuthError = ( - message.includes('401') || - message.includes('unauthorized') || - message.includes('no auth credentials') || - message.includes('invalid api key') || - message.includes('authentication failed') - ); + // Check for authentication errors + // Note: useAIProjectId re-throws OpenAI errors as generic Error objects + const isAuthError = error instanceof Error && error.message === '401 No auth credentials found'; if (isAuthError) { // Get provider name inline From 8932413c2d52e159c5e7a21de255625d78982377 Mon Sep 17 00:00:00 2001 From: sam Date: Tue, 23 Sep 2025 21:08:54 +0700 Subject: [PATCH 16/40] lint fix --- src/pages/Index.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 6840eaae..7ae2fc1e 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -13,7 +13,6 @@ import { OnboardingDialog } from '@/components/OnboardingDialog'; import { DotAI } from '@/lib/DotAI'; import { parseProviderModel } from '@/lib/parseProviderModel'; import type { AIMessage } from '@/lib/SessionManager'; -import { AuthenticationError } from 'openai'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; From 3c7584943476669feda2f0d49833f641473eb76d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 13:42:35 -0500 Subject: [PATCH 17/40] Add badge.svg --- public/badge.svg | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 public/badge.svg diff --git a/public/badge.svg b/public/badge.svg new file mode 100644 index 00000000..b51e3dc3 --- /dev/null +++ b/public/badge.svg @@ -0,0 +1,27 @@ + + 🎭 Edit with: Shakespeare + + + + + + + + + + + + + + + + + + + + + + 🎭 Edit with + Shakespeare + + From db697d0a850fb9881a0582eea66610dfdcc931c8 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 15:48:35 -0500 Subject: [PATCH 18/40] Add OpenRouter app headers --- src/lib/ai-client.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/lib/ai-client.ts b/src/lib/ai-client.ts index 8b2405e8..7eb4d669 100644 --- a/src/lib/ai-client.ts +++ b/src/lib/ai-client.ts @@ -16,6 +16,11 @@ export function createAIClient(connection: { baseURL: connection.baseURL, apiKey: connection.apiKey ?? '', dangerouslyAllowBrowser: true, + defaultHeaders: { + // https://openrouter.ai/docs/app-attribution + 'HTTP-Referer': 'https://shakespeare.diy', + 'X-Title': 'Shakespeare', + }, }; // If Nostr authentication is required and we have a user, use NIP-98 From 9ea9a4ac4b2d0b47a75b65510df1c93dff646a9b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 16:14:51 -0500 Subject: [PATCH 19/40] Fix state issues navigating between projects --- src/components/Shakespeare/PreviewPane.tsx | 7 +++++++ src/pages/ProjectView.tsx | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index aa9988ea..30e72057 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -377,6 +377,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o } }, [selectedFile, loadFileContent]); + // Reset selected file when projectId changes + useEffect(() => { + setSelectedFile(null); + setFileContent(''); + setMobileCodeView('explorer'); + }, [projectId]); + useEffect(() => { checkForBuiltProject(); }, [checkForBuiltProject]); diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index aad684fe..d66124c3 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -71,6 +71,16 @@ export function ProjectView() { loadProject(); }, [loadProject]); + // Reset view state when projectId changes + useEffect(() => { + if (projectId) { + // Reset to preview tab if the new project is previewable, otherwise code + setActiveTab(isPreviewable ? 'preview' : 'code'); + // Reset mobile view to chat when switching projects + setMobileView('chat'); + } + }, [projectId, isPreviewable]); + // Switch away from preview mode if project is not previewable useEffect(() => { if (mobileView === 'preview' && !isPreviewable) { From 738b883f3b95fbaec127d360a7f2a4a4a6e9e60a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 17:04:16 -0500 Subject: [PATCH 20/40] Request workflow scope for GitHub (required to push .github directory in mkstack projects) --- src/hooks/useGitHubOAuth.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hooks/useGitHubOAuth.ts b/src/hooks/useGitHubOAuth.ts index b0458404..aa685ed6 100644 --- a/src/hooks/useGitHubOAuth.ts +++ b/src/hooks/useGitHubOAuth.ts @@ -72,7 +72,7 @@ export function useGitHubOAuth() { const params = new URLSearchParams({ client_id: clientId, redirect_uri: window.location.origin + '/oauth/github', - scope: 'repo', + scope: 'repo workflow', state: state, code_challenge: codeChallenge, code_challenge_method: 'S256', From aa35b13ad3ef19bbbe4f8ddbece1459cdf6cf0b2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 17:26:43 -0500 Subject: [PATCH 21/40] Refactor parseProviderModel, prepare to intercept chat completion params --- src/lib/SessionManager.ts | 12 +++++----- src/lib/ai-client.ts | 35 ++++++++++++++++++++---------- src/lib/parseProviderModel.test.ts | 12 +++++----- src/lib/parseProviderModel.ts | 24 ++++++-------------- 4 files changed, 43 insertions(+), 40 deletions(-) diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 6288c2a0..e6ba0281 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -203,12 +203,12 @@ export class SessionManager { try { // Parse provider and model const parsed = parseProviderModel(providerModel, this.aiSettings.providers); - const connectionConfig = parsed.connection; - const modelName = parsed.model; + const provider = parsed.provider; + const model = parsed.model; // Initialize OpenAI client const currentUser = this.getCurrentUser?.(); - const openai = createAIClient(connectionConfig, currentUser); + const openai = createAIClient(provider, currentUser); let stepCount = 0; const maxSteps = session.maxSteps || 50; @@ -237,7 +237,7 @@ export class SessionManager { // Prepare completion options const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = { - model: modelName, + model, messages, tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined, tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined, @@ -470,11 +470,11 @@ export class SessionManager { try { const parsed = parseProviderModel(providerModel, this.aiSettings.providers); const modelName = parsed.model; - const providerName = parsed.provider; + const provider = parsed.provider; // Find the model in provider models to get pricing and context length const models = this.getProviderModels(); - const model = models.find(m => m.id === modelName && m.provider === providerName); + const model = models.find(m => m.id === modelName && m.provider === provider.id); // Update input tokens for context usage tracking session.lastInputTokens = usage.prompt_tokens; diff --git a/src/lib/ai-client.ts b/src/lib/ai-client.ts index 7eb4d669..52e4872e 100644 --- a/src/lib/ai-client.ts +++ b/src/lib/ai-client.ts @@ -1,20 +1,17 @@ import OpenAI from 'openai'; import { NIP98Client } from '@nostrify/nostrify'; import type { NUser } from '@nostrify/react/login'; +import type { AIProvider } from '@/contexts/AISettingsContext'; /** * Create an OpenAI client instance with the appropriate configuration. * If the connection requires Nostr authentication (NIP-98), it will use * the NIP98Client for authenticated requests. */ -export function createAIClient(connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; -}, user?: NUser): OpenAI { +export function createAIClient(provider: AIProvider, user?: NUser): OpenAI { const baseConfig: ConstructorParameters[0] = { - baseURL: connection.baseURL, - apiKey: connection.apiKey ?? '', + baseURL: provider.baseURL, + apiKey: provider.apiKey ?? '', dangerouslyAllowBrowser: true, defaultHeaders: { // https://openrouter.ai/docs/app-attribution @@ -23,16 +20,32 @@ export function createAIClient(connection: { }, }; + let openai: OpenAI; + // If Nostr authentication is required and we have a user, use NIP-98 - if (connection.nostr && user?.signer) { + if (provider.nostr && user?.signer) { const nip98Client = new NIP98Client({ signer: user.signer }); - return new OpenAI({ + openai = new OpenAI({ ...baseConfig, fetch: (input, init) => nip98Client.fetch(input, init), }); + } else { + // Standard OpenAI client + openai = new OpenAI(baseConfig); } - // Standard OpenAI client - return new OpenAI(baseConfig); + const createCompletion = openai.chat.completions.create; + + openai.chat.completions.create = ((...[body, options]: Parameters) => { + // OpenRouter usage accounting + // https://openrouter.ai/docs/use-cases/usage-accounting + // if (provider.features?.includes('openrouter.usage_accounting')) { + // (body as { usage?: { include?: boolean } }).usage = { include: true }; + // } + + return createCompletion(body, options); + }) as typeof createCompletion; + + return openai; } \ No newline at end of file diff --git a/src/lib/parseProviderModel.test.ts b/src/lib/parseProviderModel.test.ts index 5065c819..24c64ab4 100644 --- a/src/lib/parseProviderModel.test.ts +++ b/src/lib/parseProviderModel.test.ts @@ -29,9 +29,9 @@ describe('parseProviderModel', () => { it('should parse simple provider/model format', () => { const result = parseProviderModel('openai/gpt-4o', mockProviders); - expect(result.provider).toBe('openai'); expect(result.model).toBe('gpt-4o'); - expect(result.connection).toEqual({ + expect(result.provider).toEqual({ + id: 'openai', baseURL: mockProviders[0].baseURL, apiKey: mockProviders[0].apiKey, nostr: mockProviders[0].nostr, @@ -41,9 +41,9 @@ describe('parseProviderModel', () => { it('should parse complex model names with slashes', () => { const result = parseProviderModel('openrouter/anthropic/claude-sonnet-4', mockProviders); - expect(result.provider).toBe('openrouter'); expect(result.model).toBe('anthropic/claude-sonnet-4'); - expect(result.connection).toEqual({ + expect(result.provider).toEqual({ + id: 'openrouter', baseURL: mockProviders[1].baseURL, apiKey: mockProviders[1].apiKey, nostr: mockProviders[1].nostr, @@ -53,9 +53,9 @@ describe('parseProviderModel', () => { it('should handle model names with multiple slashes', () => { const result = parseProviderModel('openrouter/meta/llama-3.1-405b-instruct', mockProviders); - expect(result.provider).toBe('openrouter'); expect(result.model).toBe('meta/llama-3.1-405b-instruct'); - expect(result.connection).toEqual({ + expect(result.provider).toEqual({ + id: 'openrouter', baseURL: mockProviders[1].baseURL, apiKey: mockProviders[1].apiKey, nostr: mockProviders[1].nostr, diff --git a/src/lib/parseProviderModel.ts b/src/lib/parseProviderModel.ts index 06ed9015..a3a49b9b 100644 --- a/src/lib/parseProviderModel.ts +++ b/src/lib/parseProviderModel.ts @@ -1,13 +1,8 @@ import type { AIProvider } from '@/contexts/AISettingsContext'; export interface ParsedProviderModel { - provider: string; model: string; - connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; - }; + provider: AIProvider; } /** @@ -25,25 +20,20 @@ export function parseProviderModel( throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")'); } - const provider = providerModelString.substring(0, firstSlashIndex); + const providerId = providerModelString.substring(0, firstSlashIndex); const model = providerModelString.substring(firstSlashIndex + 1); - if (!provider || !model) { + if (!providerId || !model) { throw new Error('Invalid format. Both provider and model must be specified'); } - const providerObj = providers.find(p => p.id === provider); - if (!providerObj) { - throw new Error(`Provider "${provider}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`); + const provider = providers.find(p => p.id === providerId); + if (!provider) { + throw new Error(`Provider "${providerId}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`); } return { - provider, model, - connection: { - baseURL: providerObj.baseURL, - apiKey: providerObj.apiKey, - nostr: providerObj.nostr, - }, + provider, }; } \ No newline at end of file From d0a520ce17a545a1baca10a45ea2e02632a59256 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 17:53:39 -0500 Subject: [PATCH 22/40] Get accurate OpenRouter pricing --- src/components/CreditsBadge.test.tsx | 22 ++++++------------- src/components/CreditsBadge.tsx | 12 ++++------- src/components/CreditsDialog.test.tsx | 24 +++++++++------------ src/components/CreditsDialog.tsx | 27 +++++++++++------------- src/components/LightningPayment.test.tsx | 14 ++++++------ src/hooks/useAICredits.ts | 12 +++++------ src/hooks/useAIProjectId.test.ts | 25 +++++++++++----------- src/hooks/useAIProjectId.ts | 4 ++-- src/lib/SessionManager.ts | 20 ++++++++++++++---- src/lib/ai-client.ts | 9 ++++---- src/pages/AISettings.tsx | 6 ++---- 11 files changed, 81 insertions(+), 94 deletions(-) diff --git a/src/components/CreditsBadge.test.tsx b/src/components/CreditsBadge.test.tsx index f5bcb70d..a8cb6e44 100644 --- a/src/components/CreditsBadge.test.tsx +++ b/src/components/CreditsBadge.test.tsx @@ -3,7 +3,6 @@ import { render, screen, fireEvent } from '@testing-library/react'; import { TestApp } from '@/test/TestApp'; import { CreditsBadge } from './CreditsBadge'; - // Mock the useAICredits hook vi.mock('@/hooks/useAICredits', () => ({ useAICredits: () => ({ @@ -16,7 +15,8 @@ vi.mock('@/hooks/useAICredits', () => ({ // Mock the fetch function global.fetch = vi.fn(); -const mockConnection = { +const mockProvider = { + id: 'test-provider', baseURL: 'https://api.test.com/v1', apiKey: 'test-key', }; @@ -25,10 +25,7 @@ describe('CreditsBadge', () => { it('renders the credits amount', () => { render( - + ); @@ -41,8 +38,7 @@ describe('CreditsBadge', () => { render( @@ -57,10 +53,7 @@ describe('CreditsBadge', () => { it('has proper styling for clickable badge', () => { render( - + ); @@ -72,10 +65,7 @@ describe('CreditsBadge', () => { it('does not render dialog directly', () => { render( - + ); diff --git a/src/components/CreditsBadge.tsx b/src/components/CreditsBadge.tsx index 5bdc9695..ee565159 100644 --- a/src/components/CreditsBadge.tsx +++ b/src/components/CreditsBadge.tsx @@ -1,13 +1,9 @@ import { Badge } from '@/components/ui/badge'; +import { AIProvider } from '@/contexts/AISettingsContext'; import { useAICredits } from '@/hooks/useAICredits'; interface CreditsBadgeProps { - providerId: string; - connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; - }; + provider: AIProvider; className?: string; onOpenDialog?: () => void; } @@ -15,8 +11,8 @@ interface CreditsBadgeProps { /** * Displays a clickable credits badge showing the remaining credits for an AI provider */ -export function CreditsBadge({ providerId, connection, className, onOpenDialog }: CreditsBadgeProps) { - const { data: credits, isLoading, error } = useAICredits(providerId, connection); +export function CreditsBadge({ provider, className, onOpenDialog }: CreditsBadgeProps) { + const { data: credits, isLoading, error } = useAICredits(provider); // Don't render anything if there's an error (provider doesn't support credits endpoint) if (error || isLoading) { diff --git a/src/components/CreditsDialog.test.tsx b/src/components/CreditsDialog.test.tsx index 0983203e..a30d3764 100644 --- a/src/components/CreditsDialog.test.tsx +++ b/src/components/CreditsDialog.test.tsx @@ -2,14 +2,16 @@ import { describe, it, expect, vi } from 'vitest'; import { render, screen } from '@testing-library/react'; import { TestApp } from '@/test/TestApp'; import { CreditsDialog } from './CreditsDialog'; - +import type { AIProvider } from '@/contexts/AISettingsContext'; // Mock the fetch function global.fetch = vi.fn(); -const mockConnection = { +const mockProvider: AIProvider = { + id: 'test-provider', baseURL: 'https://api.test.com/v1', apiKey: 'test-key', + nostr: false, }; describe('CreditsDialog', () => { @@ -19,8 +21,7 @@ describe('CreditsDialog', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -36,8 +37,7 @@ describe('CreditsDialog', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -51,8 +51,7 @@ describe('CreditsDialog', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -67,8 +66,7 @@ describe('CreditsDialog', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -89,8 +87,7 @@ describe('CreditsDialog', () => { ); @@ -101,8 +98,7 @@ describe('CreditsDialog', () => { ); diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 89ae33af..46b33e01 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -13,15 +13,12 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@ import { useToast } from '@/hooks/useToast'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { AIProvider } from '@/contexts/AISettingsContext'; + interface CreditsDialogProps { open: boolean; onOpenChange: (open: boolean) => void; - providerId: string; - connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; - }; + provider: AIProvider; } interface Payment { @@ -184,7 +181,7 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) { ); } -export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) { +export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogProps) { const { user } = useCurrentUser(); const { toast } = useToast(); const queryClient = useQueryClient(); @@ -196,9 +193,9 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Query for payment history const { data: payments, isLoading: isLoadingPayments } = useQuery({ - queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], queryFn: async (): Promise => { - const ai = createAIClient(connection, user); + const ai = createAIClient(provider, user); const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse; return data.data; }, @@ -210,7 +207,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Mutation for adding credits const addCreditsMutation = useMutation({ mutationFn: async (request: AddCreditsRequest): Promise => { - const ai = createAIClient(connection, user); + const ai = createAIClient(provider, user); return await ai.post('/credits/add', { body: request, }) as Payment; @@ -230,12 +227,12 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Refresh payments list queryClient.invalidateQueries({ - queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Refresh credits balance queryClient.invalidateQueries({ - queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); }, onError: (error: Error) => { @@ -251,7 +248,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Mutation for checking payment status const checkPaymentMutation = useMutation({ mutationFn: async (paymentId: string): Promise => { - const ai = createAIClient(connection, user); + const ai = createAIClient(provider, user); return await ai.get(`/credits/payments/${paymentId}`) as Payment; }, onMutate: async (paymentId: string) => { @@ -268,7 +265,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Update the specific payment in the cache instead of refetching queryClient.setQueryData( - ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], + ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], (oldPayments) => { if (!oldPayments) return oldPayments; return oldPayments.map(payment => @@ -280,7 +277,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // If payment completed, refresh credits balance if (updatedPayment.status === 'completed') { queryClient.invalidateQueries({ - queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); toast({ title: 'Payment completed!', diff --git a/src/components/LightningPayment.test.tsx b/src/components/LightningPayment.test.tsx index 05319747..1e17ef64 100644 --- a/src/components/LightningPayment.test.tsx +++ b/src/components/LightningPayment.test.tsx @@ -1,6 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { render, screen } from '@testing-library/react'; import { TestApp } from '@/test/TestApp'; +import type { AIProvider } from '@/contexts/AISettingsContext'; // Mock QRCode vi.mock('qrcode', () => ({ @@ -18,9 +19,11 @@ const mockWebLN = { // We need to import the component after mocking const { CreditsDialog } = await import('./CreditsDialog'); -const mockConnection = { +const mockProvider: AIProvider = { + id: 'test-provider', baseURL: 'https://api.test.com/v1', apiKey: 'test-key', + nostr: false, }; describe('Lightning Payment', () => { @@ -39,8 +42,7 @@ describe('Lightning Payment', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -61,8 +63,7 @@ describe('Lightning Payment', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -77,8 +78,7 @@ describe('Lightning Payment', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); diff --git a/src/hooks/useAICredits.ts b/src/hooks/useAICredits.ts index 5d3d90ea..8a90ce6c 100644 --- a/src/hooks/useAICredits.ts +++ b/src/hooks/useAICredits.ts @@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'; import { z } from 'zod'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { AIProvider } from '@/contexts/AISettingsContext'; // Zod schemas for the two possible response formats const creditsResponseV1Schema = z.object({ @@ -31,18 +32,14 @@ export interface CreditsResponse { * @param connection - The AI connection configuration * @returns Query result with credits information */ -export function useAICredits(providerId: string, connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; -}) { +export function useAICredits(provider: AIProvider) { const { user } = useCurrentUser(); return useQuery({ - queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], queryFn: async (): Promise => { try { - const ai = createAIClient(connection, user); + const ai = createAIClient(provider, user); const data = await ai.get('/credits'); // Validate and normalize the response @@ -68,5 +65,6 @@ export function useAICredits(providerId: string, connection: { retry: false, // Don't retry as not all providers support this endpoint refetchOnWindowFocus: false, staleTime: 5 * 60 * 1000, // 5 minutes + enabled: provider.id === 'shakespeare' && !!user, }); } \ No newline at end of file diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts index 47e25658..cea562ec 100644 --- a/src/hooks/useAIProjectId.test.ts +++ b/src/hooks/useAIProjectId.test.ts @@ -42,9 +42,8 @@ describe('useAIProjectId', () => { // Mock parseProviderModel mockParseProviderModel.mockReturnValue({ - provider: 'openai', + provider: { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }, model: 'gpt-4', - connection: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } }); // Mock createAIClient @@ -86,7 +85,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -110,7 +109,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -134,7 +133,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -157,7 +156,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -170,7 +169,7 @@ describe('useAIProjectId', () => { { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } ]); expect(mockCreateAIClient).toHaveBeenCalledWith( - { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }, + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }, undefined ); }); @@ -188,7 +187,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -241,7 +240,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -296,7 +295,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -346,7 +345,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -396,7 +395,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -453,7 +452,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); diff --git a/src/hooks/useAIProjectId.ts b/src/hooks/useAIProjectId.ts index 6fae5475..7c688c5e 100644 --- a/src/hooks/useAIProjectId.ts +++ b/src/hooks/useAIProjectId.ts @@ -28,8 +28,8 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) { try { // Initialize OpenAI client - const { model, connection } = parseProviderModel(providerModel, settings.providers); - const openai = createAIClient(connection, user); + const { model, provider } = parseProviderModel(providerModel, settings.providers); + const openai = createAIClient(provider, user); const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`; diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index e6ba0281..5bbef8f0 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -258,7 +258,7 @@ export class SessionManager { let finishReason: string | null = null; // Process the stream - let usage: { prompt_tokens: number; completion_tokens: number } | undefined; + let usage: { prompt_tokens: number; completion_tokens: number; cost?: number } | undefined; for await (const chunk of stream) { // Check if session was cancelled if (!session.isLoading) break; @@ -319,9 +319,14 @@ export class SessionManager { // Capture usage data if available (some providers include it in the final chunk) if (chunk.usage) { + const cost = 'cost' in chunk.usage && typeof chunk.usage.cost === 'number' + ? chunk.usage.cost + : undefined; + usage = { prompt_tokens: chunk.usage.prompt_tokens || 0, - completion_tokens: chunk.usage.completion_tokens || 0 + completion_tokens: chunk.usage.completion_tokens || 0, + cost, }; } } @@ -461,12 +466,20 @@ export class SessionManager { /** * Update session cost and context usage based on usage data */ - private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void { + private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void { if (!this.getProviderModels) return; const session = this.sessions.get(projectId); if (!session) return; + // If provider gives direct cost, use it + if (typeof usage.cost === 'number') { + session.totalCost = (session.totalCost || 0) + usage.cost; + this.emit('costUpdated', projectId, session.totalCost); + return; + } + + // Otherwise, get the cost from the models endpoint try { const parsed = parseProviderModel(providerModel, this.aiSettings.providers); const modelName = parsed.model; @@ -491,7 +504,6 @@ export class SessionManager { // Update session total cost session.totalCost = (session.totalCost || 0) + requestCost; - this.emit('costUpdated', projectId, session.totalCost); } catch (error) { console.warn('Failed to calculate session cost:', error); diff --git a/src/lib/ai-client.ts b/src/lib/ai-client.ts index 52e4872e..897006f1 100644 --- a/src/lib/ai-client.ts +++ b/src/lib/ai-client.ts @@ -35,14 +35,15 @@ export function createAIClient(provider: AIProvider, user?: NUser): OpenAI { openai = new OpenAI(baseConfig); } - const createCompletion = openai.chat.completions.create; + const createCompletion: typeof openai.chat.completions.create + = openai.chat.completions.create.bind(openai.chat.completions); openai.chat.completions.create = ((...[body, options]: Parameters) => { // OpenRouter usage accounting // https://openrouter.ai/docs/use-cases/usage-accounting - // if (provider.features?.includes('openrouter.usage_accounting')) { - // (body as { usage?: { include?: boolean } }).usage = { include: true }; - // } + if (provider.id === 'openrouter') { + (body as { usage?: { include?: boolean } }).usage = { include: true }; + } return createCompletion(body, options); }) as typeof createCompletion; diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index b9fd172c..5f44f3d9 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -144,8 +144,7 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
onOpenCreditsDialog(provider.id)} />
+ + {/* Onboarding Dialog */} +
); }); diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index 886217e5..94f6023a 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -98,8 +98,6 @@ const resources = { getHelp: '🔧 Get help with debugging and optimization', buildDeploy: '🚀 Build and deploy your project', aiNotConfigured: 'AI Assistant Not Configured', - configureAI: 'Please configure your AI settings to start building with AI assistance.', - useMenuForAI: 'Use the menu in the top bar to access AI Settings.', askToAddFeatures: 'Ask me to add features, edit files, or build your project...', selectModelFirst: 'Please select a model to start chatting...', sendMessage: 'Send message', @@ -394,8 +392,6 @@ const resources = { getHelp: '🔧 Obtenha ajuda com depuração e otimização', buildDeploy: '🚀 Construa e implante seu projeto', aiNotConfigured: 'Assistente de IA Não Configurado', - configureAI: 'Configure suas configurações de IA para começar a construir com assistência de IA.', - useMenuForAI: 'Use o menu na barra superior para acessar as Configurações de IA.', askToAddFeatures: 'Peça para adicionar recursos, editar arquivos ou construir seu projeto...', selectModelFirst: 'Selecione um modelo para começar a conversar...', sendMessage: 'Enviar mensagem', @@ -690,8 +686,6 @@ const resources = { getHelp: '🔧 获得调试和优化帮助', buildDeploy: '🚀 构建和部署您的项目', aiNotConfigured: 'AI助手未配置', - configureAI: '请配置您的AI设置以开始使用AI助手构建。', - useMenuForAI: '使用顶部栏中的菜单访问AI设置。', askToAddFeatures: '请我添加功能、编辑文件或构建您的项目...', selectModelFirst: '请先选择一个模型开始聊天...', sendMessage: '发送消息', @@ -986,8 +980,6 @@ const resources = { getHelp: '🔧 Sami taimako da gyara kuskure da haɓakawa', buildDeploy: '🚀 Gina da tura aikinku', aiNotConfigured: 'Mataimakin AI Ba a Saita ba', - configureAI: 'Da fatan za a saita saitunan AI don farawa ginawa da taimakon AI.', - useMenuForAI: 'Yi amfani da menu a saman mashigi don shiga Saitunan AI.', askToAddFeatures: 'Roƙe ni in ƙara fasaloli, gyara fayiloli, ko gina aikinku...', selectModelFirst: 'Da fatan za a zaɓi samfuri don farawa hira...', sendMessage: 'Aika saƙo', @@ -1282,8 +1274,6 @@ const resources = { getHelp: '🔧 Gba iranlọwọ pẹlu atunṣe ati imudara', buildDeploy: '🚀 Kọ ati gbe iṣẹ akanṣe rẹ lọ', aiNotConfigured: 'Oluranlọwọ AI Ko Tunto', - configureAI: 'Jọwọ tunto awọn eto AI rẹ lati bẹrẹ kikọ pẹlu iranlọwọ AI.', - useMenuForAI: 'Lo akojọ aṣayan ni oke ọpa lati wọle si Awọn eto AI.', askToAddFeatures: 'Beere mi lati fi awọn ẹya kun, ṣatunkọ awọn faili, tabi kọ iṣẹ akanṣe rẹ...', selectModelFirst: 'Jọwọ yan awoṣe lati bẹrẹ ibaraẹnisọrọ...', sendMessage: 'Fi ifiranṣẹ ranṣẹ', @@ -1578,8 +1568,6 @@ const resources = { getHelp: '🔧 Nweta enyemaka na debugging na optimization', buildDeploy: '🚀 Wuo ma bufee ọrụ gị', aiNotConfigured: 'Onye Enyemaka AI Ahazighị', - configureAI: 'Biko hazie ntọala AI gị iji malite iwu na enyemaka AI.', - useMenuForAI: 'Jiri menu dị n\'elu okporo iji nweta Ntọala AI.', askToAddFeatures: 'Rịọ m ka m tinye atụmatụ, dezie faịlụ, ma ọ bụ wuo ọrụ gị...', selectModelFirst: 'Biko họrọ ụdịdị iji malite ikwu okwu...', sendMessage: 'Ziga ozi', From 4881480679191c36d95bfa4f80dc9a946c5d894e Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 20:42:34 -0500 Subject: [PATCH 27/40] Add virtual unzip command to ShellTool --- src/lib/commands/index.ts | 3 +- src/lib/commands/unzip.test.ts | 303 ++++++++++++++++++++++++++++++++ src/lib/commands/unzip.ts | 220 +++++++++++++++++++++++ src/lib/tools/ShellTool.test.ts | 2 +- src/lib/tools/ShellTool.ts | 4 +- 5 files changed, 529 insertions(+), 3 deletions(-) create mode 100644 src/lib/commands/unzip.test.ts create mode 100644 src/lib/commands/unzip.ts diff --git a/src/lib/commands/index.ts b/src/lib/commands/index.ts index a5da02d3..39c52f80 100644 --- a/src/lib/commands/index.ts +++ b/src/lib/commands/index.ts @@ -25,4 +25,5 @@ export { TrCommand } from './tr'; export { UniqCommand } from './uniq'; export { WcCommand } from './wc'; export { WhoamiCommand } from './whoami'; -export { WhichCommand } from './which'; \ No newline at end of file +export { WhichCommand } from './which'; +export { UnzipCommand } from './unzip'; \ No newline at end of file diff --git a/src/lib/commands/unzip.test.ts b/src/lib/commands/unzip.test.ts new file mode 100644 index 00000000..8e073139 --- /dev/null +++ b/src/lib/commands/unzip.test.ts @@ -0,0 +1,303 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import JSZip from 'jszip'; +import { UnzipCommand } from './unzip'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const createMockFS = (): JSRuntimeFS => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + readdir: vi.fn(), + mkdir: vi.fn(), + stat: vi.fn(), + lstat: vi.fn(), + unlink: vi.fn(), + rmdir: vi.fn(), + rename: vi.fn(), + readlink: vi.fn(), + symlink: vi.fn(), +}); + +describe('UnzipCommand', () => { + let mockFS: JSRuntimeFS; + let command: UnzipCommand; + + beforeEach(() => { + mockFS = createMockFS(); + command = new UnzipCommand(mockFS); + }); + + const createTestZip = async (files: Record): Promise => { + const zip = new JSZip(); + + for (const [path, content] of Object.entries(files)) { + if (path.endsWith('/')) { + zip.folder(path.slice(0, -1)); + } else { + zip.file(path, content); + } + } + + return zip.generateAsync({ type: 'uint8array' }); + }; + + it('should show usage when no arguments provided', async () => { + const result = await command.execute([], '/home'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('missing archive operand'); + expect(result.stderr).toContain('Usage:'); + }); + + it('should show error for invalid options', async () => { + const result = await command.execute(['-x', 'test.zip'], '/home'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("invalid option '-x'"); + }); + + it('should show error for non-existent archive', async () => { + vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory')); + + const result = await command.execute(['nonexistent.zip'], '/home'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should show error when trying to unzip a directory', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const result = await command.execute(['testdir'], '/home'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should list archive contents with -l option', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World', + 'dir1/': '', + 'dir1/file2.txt': 'Test content' + }); + + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + + const result = await command.execute(['-l', 'test.zip'], '/home'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Archive: test.zip'); + expect(result.stdout).toContain('file1.txt'); + expect(result.stdout).toContain('dir1/'); + expect(result.stdout).toContain('dir1/file2.txt'); + }); + + it('should extract files to current directory', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World' + }); + + // Mock file operations - keep it simple + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await command.execute(['test.zip'], '/home'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Archive: test.zip'); + expect(result.stdout).toContain('inflating: file1.txt'); + + // Verify writeFile was called for extracted files + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array)); + }); + + it('should handle command line options correctly', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World' + }); + + // Test -d option + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await command.execute(['-d', 'extract', 'test.zip'], '/home'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('inflating: file1.txt'); + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/extract/file1.txt', expect.any(Uint8Array)); + }); + + it('should handle overwrite option', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'New content' + }); + + // Mock file exists scenario + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + // Without -o option, should fail + const resultWithoutOverwrite = await command.execute(['test.zip'], '/home'); + expect(resultWithoutOverwrite.exitCode).toBe(1); + expect(resultWithoutOverwrite.stderr).toContain('File exists (use -o to overwrite)'); + + // Reset mocks + vi.clearAllMocks(); + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + // With -o option, should succeed + const resultWithOverwrite = await command.execute(['-o', 'test.zip'], '/home'); + expect(resultWithOverwrite.exitCode).toBe(0); + expect(resultWithOverwrite.stdout).toContain('inflating: file1.txt'); + }); + + it('should prevent extraction outside allowed directories', async () => { + // Since JSZip normalizes paths during creation, we'll test the security logic + // by mocking the internal zip.files object to simulate a malicious ZIP + const zipData = await createTestZip({ + 'normal.txt': 'safe content' + }); + + // Mock the zip loading to return a ZIP with malicious paths + const originalLoadAsync = JSZip.loadAsync; + vi.spyOn(JSZip, 'loadAsync').mockImplementation(async () => { + const zip = new JSZip(); + // Simulate malicious ZIP file entries that would escape the directory + (zip as unknown as { files: Record Promise }> }).files = { + '../../../etc/passwd': { + name: '../../../etc/passwd', + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])), + }, + '../../outside.txt': { + name: '../../outside.txt', + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])), + }, + 'normal.txt': { + name: 'normal.txt', + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])), + } + }; + return zip; + }); + + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await command.execute(['test.zip'], '/home/user'); + + // Should return error because some files were skipped + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Path is outside allowed directories'); + expect(result.stderr).toContain('../../../etc/passwd'); + expect(result.stderr).toContain('../../outside.txt'); + + // Should only extract the safe file + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/user/normal.txt', expect.any(Uint8Array)); + expect(mockFS.writeFile).toHaveBeenCalledTimes(1); + + // Restore the original method + JSZip.loadAsync = originalLoadAsync; + }); + + it('should allow extraction to /tmp directory', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World' + }); + + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockRejectedValueOnce(new Error('ENOENT')) // extraction dir doesn't exist + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + + const result = await command.execute(['-d', '/tmp', 'test.zip'], '/home/user'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('inflating: file1.txt'); + expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/file1.txt', expect.any(Uint8Array)); + }); + + it('should reject extraction directory outside allowed paths', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World' + }); + + // Mock that the archive exists and provide zip data + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + + const result = await command.execute(['-d', '/etc', 'test.zip'], '/home/user'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("extraction directory '/etc' is outside allowed paths"); + }); + + it('should support quiet mode with -q flag', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World', + 'dir1/': '', + 'dir1/file2.txt': 'Test content' + }); + + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + + const result = await command.execute(['-q', 'test.zip'], '/home'); + + expect(result.exitCode).toBe(0); + // In quiet mode, should not show archive header or extraction messages + expect(result.stdout).toBe(''); + + // But files should still be extracted + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array)); + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/dir1/file2.txt', expect.any(Uint8Array)); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/unzip.ts b/src/lib/commands/unzip.ts new file mode 100644 index 00000000..d6ddb449 --- /dev/null +++ b/src/lib/commands/unzip.ts @@ -0,0 +1,220 @@ +import { join, dirname, normalize } from "path-browserify"; +import JSZip from "jszip"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'unzip' command + * Extract files from ZIP archives + */ +export class UnzipCommand implements ShellCommand { + name = 'unzip'; + description = 'Extract files from ZIP archives'; + usage = 'unzip [-d directory] [-o] [-l] [-q] archive.zip'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + if (args.length === 0) { + return createErrorResult(`${this.name}: missing archive operand\nUsage: ${this.usage}`); + } + + let archivePath = ''; + let extractDir = cwd; + let overwrite = false; + let listOnly = false; + let quiet = false; + + // Parse command line options + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '-d' && i + 1 < args.length) { + // Extract to specific directory + extractDir = args[i + 1]; + i++; // Skip next argument + } else if (arg === '-o') { + // Overwrite existing files + overwrite = true; + } else if (arg === '-l') { + // List archive contents only + listOnly = true; + } else if (arg === '-q') { + // Quiet mode - suppress output + quiet = true; + } else if (arg.startsWith('-')) { + return createErrorResult(`${this.name}: invalid option '${arg}'\nUsage: ${this.usage}`); + } else { + // This should be the archive path + archivePath = arg; + } + } + + if (!archivePath) { + return createErrorResult(`${this.name}: no archive specified\nUsage: ${this.usage}`); + } + + try { + // Resolve archive path + let absoluteArchivePath: string; + if (archivePath.startsWith('/') || archivePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(archivePath)) { + absoluteArchivePath = archivePath; + } else { + absoluteArchivePath = join(cwd, archivePath); + } + + // Check if archive exists + try { + const stats = await this.fs.stat(absoluteArchivePath); + if (stats.isDirectory()) { + return createErrorResult(`${this.name}: ${archivePath}: Is a directory`); + } + } catch { + return createErrorResult(`${this.name}: ${archivePath}: No such file or directory`); + } + + // Read the ZIP file + const zipData = await this.fs.readFile(absoluteArchivePath); + const zip = await JSZip.loadAsync(zipData); + + // Resolve extraction directory + let absoluteExtractDir: string; + if (extractDir.startsWith('/') || extractDir.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(extractDir)) { + absoluteExtractDir = extractDir; + } else { + absoluteExtractDir = join(cwd, extractDir); + } + + // Security check: ensure extraction directory is within allowed paths + if (!this.isPathAllowed(absoluteExtractDir, cwd)) { + return createErrorResult(`${this.name}: extraction directory '${extractDir}' is outside allowed paths (cwd or /tmp)`); + } + + if (listOnly) { + // List contents only + const entries: string[] = []; + zip.forEach((relativePath, file) => { + const date = file.date || new Date(); + const type = file.dir ? 'd' : '-'; + const sizeStr = file.dir ? '0' : '?'; + + entries.push(`${type}rw-r--r-- 1 user user ${sizeStr.padStart(8)} ${date.toISOString().slice(0, 19).replace('T', ' ')} ${relativePath}`); + }); + + return createSuccessResult(`Archive: ${archivePath}\n${entries.join('\n')}`); + } + + // Create extraction directory if it doesn't exist + try { + await this.fs.stat(absoluteExtractDir); + } catch { + await this.fs.mkdir(absoluteExtractDir, { recursive: true }); + } + + const extractedFiles: string[] = []; + const errors: string[] = []; + + // Extract all files + for (const [relativePath, file] of Object.entries(zip.files)) { + const extractPath = join(absoluteExtractDir, relativePath); + + // Security check: ensure each file path is within allowed directories + if (!this.isPathAllowed(extractPath, cwd)) { + errors.push(`${this.name}: ${relativePath}: Path is outside allowed directories (skipped for security)`); + continue; + } + + try { + if (file.dir) { + // Create directory + await this.fs.mkdir(extractPath, { recursive: true }); + if (!quiet) { + extractedFiles.push(` creating: ${relativePath}`); + } + } else { + // Check if file exists and handle overwrite + if (!overwrite) { + try { + await this.fs.stat(extractPath); + errors.push(`${this.name}: ${relativePath}: File exists (use -o to overwrite)`); + continue; + } catch { + // File doesn't exist, proceed with extraction + } + } + + // Create parent directories if needed + const parentDir = dirname(extractPath); + try { + await this.fs.stat(parentDir); + } catch { + await this.fs.mkdir(parentDir, { recursive: true }); + } + + // Extract file content + const content = await file.async('uint8array'); + await this.fs.writeFile(extractPath, content); + if (!quiet) { + extractedFiles.push(` inflating: ${relativePath}`); + } + } + } catch (error) { + errors.push(`${this.name}: ${relativePath}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + let output = ''; + if (!quiet) { + output = `Archive: ${archivePath}\n`; + if (extractedFiles.length > 0) { + output += extractedFiles.join('\n'); + } + } + + if (errors.length > 0) { + if (!quiet && extractedFiles.length > 0) { + output += '\n'; + } + return createErrorResult(output + '\n' + errors.join('\n')); + } + + return createSuccessResult(output); + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('corrupted') || error.message.includes('invalid')) { + return createErrorResult(`${this.name}: ${archivePath}: Archive is corrupted or invalid`); + } else { + return createErrorResult(`${this.name}: ${archivePath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${archivePath}: Unknown error`); + } + } + } + + /** + * Check if a path is within allowed extraction directories (cwd or /tmp and their subdirectories) + */ + private isPathAllowed(extractPath: string, cwd: string): boolean { + // Normalize the paths without using resolve() since we're in browser environment + const normalizedPath = normalize(extractPath); + const normalizedCwd = normalize(cwd); + const tmpPath = '/tmp'; + + // Ensure paths are absolute for comparison + const absolutePath = normalizedPath.startsWith('/') ? normalizedPath : normalize(join(normalizedCwd, normalizedPath)); + const absoluteCwd = normalizedCwd.startsWith('/') ? normalizedCwd : '/' + normalizedCwd; + + // Check if path is within cwd or /tmp + return absolutePath.startsWith(absoluteCwd + '/') || + absolutePath === absoluteCwd || + absolutePath.startsWith(tmpPath + '/') || + absolutePath === tmpPath; + } +} \ No newline at end of file diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index ba5d4e65..adf691fb 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -44,7 +44,7 @@ describe('ShellTool', () => { }); it('should have correct tool properties', () => { - expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators'); + expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip. Supports compound commands with &&, ||, ;, and | operators'); expect(shellTool.inputSchema).toBeDefined(); }); diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index d722ccf4..dbf991ac 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -28,6 +28,7 @@ import { TouchCommand, TrCommand, UniqCommand, + UnzipCommand, WcCommand, WhoamiCommand, WhichCommand @@ -46,7 +47,7 @@ export class ShellTool implements Tool { private git: Git; private commands: Map; - readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators"; + readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip. Supports compound commands with &&, ||, ;, and | operators"; readonly inputSchema = z.object({ command: z.string().describe( @@ -85,6 +86,7 @@ export class ShellTool implements Tool { this.registerCommand(new TouchCommand(fs)); this.registerCommand(new TrCommand(fs)); this.registerCommand(new UniqCommand(fs)); + this.registerCommand(new UnzipCommand(fs)); this.registerCommand(new WcCommand(fs)); this.registerCommand(new WhoamiCommand()); From 540e017074a31355dcce9d7ef31f030840edee5d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 21:06:04 -0500 Subject: [PATCH 28/40] Fix attaching a file to the initial project message --- src/pages/Index.tsx | 41 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index b45f9843..5cb51fb3 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -11,6 +11,8 @@ import { AppLayout } from '@/components/AppLayout'; import { OnboardingDialog } from '@/components/OnboardingDialog'; import { DotAI } from '@/lib/DotAI'; import type { AIMessage } from '@/lib/SessionManager'; +import { saveFileToTmp } from '@/lib/fileUtils'; +import type OpenAI from 'openai'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; @@ -164,13 +166,48 @@ export default function Index() { // Create project with AI-generated ID const project = await projectsManager.createProject(prompt.trim(), projectId); + // Build message content as text parts (same as ChatPane) + const contentParts: Array = []; + + // Add user input as text part if present + if (prompt.trim()) { + contentParts.push({ + type: 'text', + text: prompt.trim() + }); + } + + // Process attached files and add as separate text parts + if (attachedFiles.length > 0) { + const filePromises = 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); + + // Add each file as a separate text part + fileResults.forEach(fileResult => { + contentParts.push({ + type: 'text', + text: fileResult + }); + }); + } + // Store the initial message in chat history using DotAI const dotAI = new DotAI(fs, `/projects/${project.id}`); const sessionName = DotAI.generateSessionName(); - // Create initial message with content parts + + // Create initial message with content parts (same format as ChatPane) const initialMessage: AIMessage = { role: 'user', - content: prompt.trim() + content: contentParts.length === 1 ? contentParts[0].text : contentParts }; await dotAI.setHistory(sessionName, [initialMessage]); From 131566750d4f3b58d63e39f97110d627402ee77e Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 21:16:58 -0500 Subject: [PATCH 29/40] Add hexdump command --- src/lib/commands/hexdump.test.ts | 229 ++++++++++++++++++++++++++ src/lib/commands/hexdump.ts | 272 +++++++++++++++++++++++++++++++ src/lib/commands/index.ts | 1 + src/lib/tools/ShellTool.test.ts | 2 +- src/lib/tools/ShellTool.ts | 4 +- 5 files changed, 506 insertions(+), 2 deletions(-) create mode 100644 src/lib/commands/hexdump.test.ts create mode 100644 src/lib/commands/hexdump.ts diff --git a/src/lib/commands/hexdump.test.ts b/src/lib/commands/hexdump.test.ts new file mode 100644 index 00000000..5b5b9f46 --- /dev/null +++ b/src/lib/commands/hexdump.test.ts @@ -0,0 +1,229 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { HexdumpCommand } from './hexdump'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const createMockFS = (): JSRuntimeFS => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + readdir: vi.fn(), + mkdir: vi.fn(), + stat: vi.fn(), + lstat: vi.fn(), + unlink: vi.fn(), + rmdir: vi.fn(), + rename: vi.fn(), + readlink: vi.fn(), + symlink: vi.fn(), +}); + +describe('HexdumpCommand', () => { + let mockFS: JSRuntimeFS; + let command: HexdumpCommand; + const testCwd = '/test/dir'; + + beforeEach(() => { + mockFS = createMockFS(); + command = new HexdumpCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('hexdump'); + expect(command.description).toBe('Display file contents in hexadecimal format'); + expect(command.usage).toBe('hexdump [-C] [-n length] [-s skip] [file...]'); + }); + + it('should show error when no file is specified', async () => { + const result = await command.execute([], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('missing file operand'); + }); + + it('should show error for non-existent file', async () => { + vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory')); + + const result = await command.execute(['nonexistent.txt'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should show error for directory', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const result = await command.execute(['testdir'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should display hexdump in default format', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('0000000'); + expect(result.stdout).toContain('000000e'); // Final offset + }); + + it('should display hexdump in canonical format with -C', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000000'); + expect(result.stdout).toContain('|Hello, World!'); + expect(result.stdout).toContain('|'); // Should have ASCII representation + }); + + it('should handle -n length option', async () => { + const content = 'Hello, World!\nThis is a longer line.'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', '-n', '5', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('|Hello|'); + expect(result.stdout).not.toContain('World'); + }); + + it('should handle -s skip option', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', '-s', '7', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000007'); + expect(result.stdout).toContain('|World!'); + expect(result.stdout).not.toContain('Hello'); + }); + + it('should handle -n and -s together', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', '-s', '7', '-n', '5', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000007'); + expect(result.stdout).toContain('|World|'); + expect(result.stdout).not.toContain('Hello'); + expect(result.stdout).not.toContain('!'); + }); + + it('should show error for invalid -n value', async () => { + const result = await command.execute(['-n', 'invalid'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid length'); + }); + + it('should show error for invalid -s value', async () => { + const result = await command.execute(['-s', 'invalid'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid skip offset'); + }); + + it('should show error for missing -n argument', async () => { + const result = await command.execute(['-n'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('option requires an argument -- n'); + }); + + it('should show error for missing -s argument', async () => { + const result = await command.execute(['-s'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('option requires an argument -- s'); + }); + + it('should show error for invalid option', async () => { + const result = await command.execute(['-x'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid option -- x'); + }); + + it('should handle multiple files', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile) + .mockResolvedValueOnce(Buffer.from('ABC')) + .mockResolvedValueOnce(Buffer.from('XYZ')); + + const result = await command.execute(['-C', 'file1.txt', 'file2.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('==> file1.txt <=='); + expect(result.stdout).toContain('==> file2.txt <=='); + expect(result.stdout).toContain('|ABC|'); + expect(result.stdout).toContain('|XYZ|'); + }); + + it('should handle piped input', async () => { + const input = 'Hello, World!'; + const result = await command.execute(['-C'], testCwd, input); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000000'); + expect(result.stdout).toContain('|Hello, World!|'); + }); + + it('should handle binary data correctly', async () => { + // Create binary data with non-printable characters + const binaryData = Buffer.from([0x00, 0x01, 0x02, 0x7F, 0x80, 0xFF, 0x41, 0x42, 0x43]); + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(binaryData); + + const result = await command.execute(['-C', 'binary.dat'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000000'); + expect(result.stdout).toContain('00 01 02 7f 80 ff 41 42 43'); + expect(result.stdout).toContain('|......ABC|'); // Non-printable chars shown as dots + }); + + it('should handle empty file', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('')); + + const result = await command.execute(['-C', 'empty.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); // No output for empty file + }); + + it('should handle skip beyond file length', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('Hi')); + + const result = await command.execute(['-C', '-s', '10', 'short.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); // No output since skip is beyond file + }); +}); \ No newline at end of file diff --git a/src/lib/commands/hexdump.ts b/src/lib/commands/hexdump.ts new file mode 100644 index 00000000..b275a7e5 --- /dev/null +++ b/src/lib/commands/hexdump.ts @@ -0,0 +1,272 @@ +import { join } from "path-browserify"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'hexdump' command + * Display file contents in hexadecimal format + */ +export class HexdumpCommand implements ShellCommand { + name = 'hexdump'; + description = 'Display file contents in hexadecimal format'; + usage = 'hexdump [-C] [-n length] [-s skip] [file...]'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string, input?: string): Promise { + // Parse command line options + const options = this.parseOptions(args); + + if (options.error) { + return createErrorResult(options.error); + } + + // If input is provided (from pipe), process it + if (input !== undefined) { + const buffer = Buffer.from(input, 'utf8'); + const output = this.formatHexdump(buffer, options); + return createSuccessResult(output); + } + + // If no files specified, show usage + if (options.files.length === 0) { + return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`); + } + + try { + const outputs: string[] = []; + + for (const filePath of options.files) { + try { + // Handle both absolute and relative paths + let absolutePath: string; + + if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { + // It's an absolute path - use it directly + absolutePath = filePath; + } else { + // It's a relative path - resolve it relative to the current working directory + absolutePath = join(cwd, filePath); + } + + // Check if path exists and is a file + const stats = await this.fs.stat(absolutePath); + + if (stats.isDirectory()) { + return createErrorResult(`${this.name}: ${filePath}: Is a directory`); + } + + // Read file content as binary + const content = await this.fs.readFile(absolutePath); + const buffer = Buffer.from(content); + + // Format the hexdump + const hexOutput = this.formatHexdump(buffer, options); + + // Add filename header if multiple files + if (options.files.length > 1) { + outputs.push(`==> ${filePath} <==`); + outputs.push(hexOutput); + } else { + outputs.push(hexOutput); + } + + } catch (error) { + // Handle file not found or permission errors + if (error instanceof Error) { + if (error.message.includes('ENOENT') || error.message.includes('not found')) { + return createErrorResult(`${this.name}: ${filePath}: No such file or directory`); + } else if (error.message.includes('EACCES') || error.message.includes('permission')) { + return createErrorResult(`${this.name}: ${filePath}: Permission denied`); + } else { + return createErrorResult(`${this.name}: ${filePath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${filePath}: Unknown error`); + } + } + } + + const result = outputs.join('\n'); + return createSuccessResult(result); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + /** + * Parse command line options + */ + private parseOptions(args: string[]): { + canonical: boolean; + length?: number; + skip: number; + files: string[]; + error?: string; + } { + const options = { + canonical: false, + length: undefined as number | undefined, + skip: 0, + files: [] as string[], + }; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '-C') { + options.canonical = true; + } else if (arg === '-n') { + // Next argument should be the length + if (i + 1 >= args.length) { + return { ...options, error: `${this.name}: option requires an argument -- n` }; + } + const lengthStr = args[++i]; + const length = parseInt(lengthStr, 10); + if (isNaN(length) || length < 0) { + return { ...options, error: `${this.name}: invalid length: ${lengthStr}` }; + } + options.length = length; + } else if (arg === '-s') { + // Next argument should be the skip offset + if (i + 1 >= args.length) { + return { ...options, error: `${this.name}: option requires an argument -- s` }; + } + const skipStr = args[++i]; + const skip = parseInt(skipStr, 10); + if (isNaN(skip) || skip < 0) { + return { ...options, error: `${this.name}: invalid skip offset: ${skipStr}` }; + } + options.skip = skip; + } else if (arg.startsWith('-')) { + return { ...options, error: `${this.name}: invalid option -- ${arg.slice(1)}` }; + } else { + // It's a filename + options.files.push(arg); + } + } + + return options; + } + + /** + * Format buffer content as hexdump + */ + private formatHexdump(buffer: Buffer, options: { + canonical: boolean; + length?: number; + skip: number; + }): string { + const lines: string[] = []; + const bytesPerLine = 16; + + // Apply skip offset + const startOffset = options.skip; + if (startOffset >= buffer.length) { + return ''; // Nothing to display + } + + // Apply length limit + let endOffset = buffer.length; + if (options.length !== undefined) { + endOffset = Math.min(startOffset + options.length, buffer.length); + } + + for (let offset = startOffset; offset < endOffset; offset += bytesPerLine) { + const lineEnd = Math.min(offset + bytesPerLine, endOffset); + const lineBytes = buffer.subarray(offset, lineEnd); + + if (options.canonical) { + // Canonical format (-C): address, hex bytes, ASCII + lines.push(this.formatCanonicalLine(offset, lineBytes)); + } else { + // Default format: address followed by 16-bit words in hex + lines.push(this.formatDefaultLine(offset, lineBytes)); + } + } + + // Add final offset line if we have data + if (endOffset > startOffset) { + const finalOffset = endOffset; + lines.push(this.formatOffsetLine(finalOffset)); + } + + return lines.join('\n'); + } + + /** + * Format a line in canonical format (-C option) + */ + private formatCanonicalLine(offset: number, bytes: Buffer): string { + const addressStr = offset.toString(16).padStart(8, '0'); + + // Format hex bytes (2 groups of 8 bytes each) + const group1: string[] = []; + const group2: string[] = []; + + for (let i = 0; i < 16; i++) { + const hexByte = i < bytes.length + ? bytes[i].toString(16).padStart(2, '0') + : ' '; + + if (i < 8) { + group1.push(hexByte); + } else { + group2.push(hexByte); + } + } + + const hexStr = group1.join(' ') + ' ' + group2.join(' '); + + // Format ASCII representation + let asciiStr = ''; + for (let i = 0; i < bytes.length; i++) { + const byte = bytes[i]; + if (byte >= 32 && byte <= 126) { + // Printable ASCII character + asciiStr += String.fromCharCode(byte); + } else { + // Non-printable character + asciiStr += '.'; + } + } + + return `${addressStr} ${hexStr} |${asciiStr}|`; + } + + /** + * Format a line in default format + */ + private formatDefaultLine(offset: number, bytes: Buffer): string { + const addressStr = offset.toString(16).padStart(7, '0'); + + // Group bytes into 16-bit words (little-endian) + const words: string[] = []; + for (let i = 0; i < bytes.length; i += 2) { + if (i + 1 < bytes.length) { + // Full 16-bit word (little-endian) + const word = (bytes[i + 1] << 8) | bytes[i]; + words.push(word.toString(16).padStart(4, '0')); + } else { + // Partial word (only one byte) + const word = bytes[i]; + words.push(word.toString(16).padStart(2, '0') + ' '); + } + } + + return `${addressStr} ${words.join(' ')}`; + } + + /** + * Format the final offset line + */ + private formatOffsetLine(offset: number): string { + return offset.toString(16).padStart(7, '0'); + } +} \ No newline at end of file diff --git a/src/lib/commands/index.ts b/src/lib/commands/index.ts index 39c52f80..4d7d68d4 100644 --- a/src/lib/commands/index.ts +++ b/src/lib/commands/index.ts @@ -13,6 +13,7 @@ export { FindCommand } from './find'; export { GitCommand } from './git'; export { GrepCommand } from './grep'; export { HeadCommand } from './head'; +export { HexdumpCommand } from './hexdump'; export { LsCommand } from './ls'; export { MkdirCommand } from './mkdir'; export { MvCommand } from './mv'; diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index adf691fb..e3d50167 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -44,7 +44,7 @@ describe('ShellTool', () => { }); it('should have correct tool properties', () => { - expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip. Supports compound commands with &&, ||, ;, and | operators'); + expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators'); expect(shellTool.inputSchema).toBeDefined(); }); diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index dbf991ac..78d1a24e 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -18,6 +18,7 @@ import { GitCommand, GrepCommand, HeadCommand, + HexdumpCommand, LsCommand, MkdirCommand, MvCommand, @@ -47,7 +48,7 @@ export class ShellTool implements Tool { private git: Git; private commands: Map; - readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip. Supports compound commands with &&, ||, ;, and | operators"; + readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators"; readonly inputSchema = z.object({ command: z.string().describe( @@ -76,6 +77,7 @@ export class ShellTool implements Tool { this.registerCommand(new GitCommand({ git: this.git, fs, cwd: this.cwd })); this.registerCommand(new GrepCommand(fs)); this.registerCommand(new HeadCommand(fs)); + this.registerCommand(new HexdumpCommand(fs)); this.registerCommand(new LsCommand(fs)); this.registerCommand(new MkdirCommand(fs)); this.registerCommand(new MvCommand(fs)); From fc36073654bf35392ac41966b48ff8876e65512a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 21:33:08 -0500 Subject: [PATCH 30/40] Rename project --- src/components/ProjectInfoDialog.tsx | 96 ++++++++++++++++++++- src/lib/ProjectsManager.test.ts | 123 ++++++++++++++++++++++++++- src/lib/ProjectsManager.ts | 44 ++++++++++ 3 files changed, 258 insertions(+), 5 deletions(-) diff --git a/src/components/ProjectInfoDialog.tsx b/src/components/ProjectInfoDialog.tsx index 8460951a..59b638df 100644 --- a/src/components/ProjectInfoDialog.tsx +++ b/src/components/ProjectInfoDialog.tsx @@ -1,4 +1,5 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; import { type Project } from '@/lib/ProjectsManager'; import { Dialog, @@ -18,6 +19,8 @@ import { AlertDialogTrigger, } from '@/components/ui/alert-dialog'; import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; import { useToast } from '@/hooks/useToast'; import { useFS } from '@/hooks/useFS'; import { useProjectsManager } from '@/hooks/useProjectsManager'; @@ -28,8 +31,10 @@ import { Download, Loader2, Trash2, + Save, } from 'lucide-react'; import JSZip from 'jszip'; +import { Separator } from './ui/separator'; interface ProjectInfoDialogProps { project: Project; @@ -41,10 +46,19 @@ interface ProjectInfoDialogProps { export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectInfoDialogProps) { const [isExporting, setIsExporting] = useState(false); const [isDeleting, setIsDeleting] = useState(false); + const [isRenaming, setIsRenaming] = useState(false); + const [newProjectName, setNewProjectName] = useState(project.id); const { toast } = useToast(); const { fs } = useFS(); const projectsManager = useProjectsManager(); const navigate = useNavigate(); + const queryClient = useQueryClient(); + + // Reset state when project changes + useEffect(() => { + setNewProjectName(project.id); + setIsRenaming(false); + }, [project.id]); const formatDistanceToNow = (date: Date) => { const now = new Date(); @@ -58,11 +72,49 @@ export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDelete return `${Math.floor(diffInSeconds / 31536000)} years ago`; }; + const handleSaveProject = async () => { + if (!newProjectName.trim() || newProjectName === project.id) { + setNewProjectName(project.id); + return; + } + + setIsRenaming(true); + try { + await projectsManager.renameProject(project.id, newProjectName); + + // Invalidate the projects query to update the sidebar + await queryClient.invalidateQueries({ queryKey: ['projects'] }); + + toast({ + title: "Project renamed", + description: `Project renamed from "${project.id}" to "${newProjectName}".`, + }); + + // Close the dialog first + onOpenChange(false); + + // Navigate to the new URL + navigate(`/project/${newProjectName}`); + } catch (error) { + toast({ + title: "Failed to rename project", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + setNewProjectName(project.id); // Reset to original name + } finally { + setIsRenaming(false); + } + }; + const handleDeleteProject = async () => { setIsDeleting(true); try { await projectsManager.deleteProject(project.id); + // Invalidate the projects query to update the sidebar + await queryClient.invalidateQueries({ queryKey: ['projects'] }); + toast({ title: "Project deleted", description: `"${project.name}" has been permanently deleted.`, @@ -160,7 +212,7 @@ export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDelete - {project.name} + Project Info @@ -172,10 +224,46 @@ export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDelete {formatDistanceToNow(project.lastModified)}
+ {/* Project Name */} +
+ +
+ setNewProjectName(e.target.value)} + disabled={isRenaming} + onKeyDown={(e) => { + if (e.key === 'Enter') { + handleSaveProject(); + } else if (e.key === 'Escape') { + setNewProjectName(project.id); + } + }} + className="flex-1" + placeholder="Enter project name" + /> + +
+
+ + + {/* Export Project Button */} @@ -184,6 +184,7 @@ export function ProjectView() { projectId={project.id} projectName={project.name} onNewChat={handleNewChat} + onProjectDetails={() => setIsProjectDetailsOpen(true)} isLoading={isAILoading} isBuildLoading={build.isPending} onFirstInteraction={handleFirstInteraction} @@ -305,12 +306,12 @@ export function ProjectView() {
- {/* Project Info Dialog */} + {/* Project Details Dialog */} {project && ( - )} @@ -367,7 +368,7 @@ export function ProjectView() { @@ -390,6 +391,7 @@ export function ProjectView() { projectId={project.id} projectName={project.name} onNewChat={handleNewChat} + onProjectDetails={() => setIsProjectDetailsOpen(true)} isLoading={isAILoading} isBuildLoading={build.isPending} onFirstInteraction={handleFirstInteraction} @@ -457,12 +459,12 @@ export function ProjectView() { - {/* Project Info Dialog */} + {/* Project Details Dialog */} {project && ( - )} From 289caff882f5dfdc3c78264f9eec37e292639fd8 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 23:29:02 -0500 Subject: [PATCH 32/40] Generate system prompt dynamically in SessionManager --- src/components/SessionManagerProvider.tsx | 6 ++--- src/components/Shakespeare/ChatPane.tsx | 18 +------------- src/hooks/useAIChat.ts | 6 ++--- src/lib/SessionManager.ts | 29 +++++++++++++++-------- 4 files changed, 25 insertions(+), 34 deletions(-) diff --git a/src/components/SessionManagerProvider.tsx b/src/components/SessionManagerProvider.tsx index 173c250a..5030e015 100644 --- a/src/components/SessionManagerProvider.tsx +++ b/src/components/SessionManagerProvider.tsx @@ -17,13 +17,13 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps const { fs } = useFS(); const { settings } = useAISettings(); const { models } = useProviderModels(); - const { user } = useCurrentUser(); + const { user, metadata } = useCurrentUser(); const sessionManager = useMemo(() => { const getProviderModels = () => models; - const getCurrentUser = () => user; + const getCurrentUser = () => ({ user, metadata }); return new SessionManager(fs, settings, getProviderModels, getCurrentUser); - }, [fs, settings, models, user]); + }, [fs, settings, models, user, metadata]); // Cleanup on unmount useEffect(() => { diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 6e2962c0..dc835d8d 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -37,7 +37,6 @@ import { TypecheckTool } from '@/lib/tools/TypecheckTool'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; -import { makeSystemPrompt } from '@/lib/system'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection'; @@ -119,7 +118,6 @@ export const ChatPane = forwardRef(({ }, ref) => { const { t } = useTranslation(); const [input, setInput] = useState(''); - const [systemPrompt, setSystemPrompt] = useState(''); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [attachedFiles, setAttachedFiles] = useState([]); const [isDragOver, setIsDragOver] = useState(false); @@ -146,7 +144,7 @@ export const ChatPane = forwardRef(({ const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); const { git } = useGit(); - const { user, metadata } = useCurrentUser(); + const { user } = useCurrentUser(); const { models } = useProviderModels(); // Initialize AI chat with tools @@ -210,19 +208,6 @@ export const ChatPane = forwardRef(({ updateMetadata(title, description); }, [updateMetadata]); - useEffect(() => { - makeSystemPrompt({ - cwd, - fs, - mode: "agent", - name: "Shakespeare", - profession: "software extraordinaire", - tools: Object.values(tools), - user, - metadata, - }).then(setSystemPrompt) - }, [fs, cwd, tools, user, metadata]); - const { messages, streamingMessage, @@ -237,7 +222,6 @@ export const ChatPane = forwardRef(({ projectId, tools, customTools, - systemPrompt, onUpdateMetadata, }); diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index 136e43b0..ad28255f 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -10,7 +10,6 @@ interface UseAIChatSessionOptions { projectId: string; tools?: Record; customTools?: Record>; - systemPrompt?: string; maxSteps?: number; onUpdateMetadata?: (title: string, description: string) => void; } @@ -30,7 +29,6 @@ export function useAIChat({ projectId, tools = {}, customTools = {}, - systemPrompt, maxSteps = 50, onUpdateMetadata }: UseAIChatSessionOptions) { @@ -46,14 +44,14 @@ export function useAIChat({ const initSession = useCallback(async () => { // Load or update session - const session = await sessionManager.loadSession(projectId, tools, customTools, systemPrompt, maxSteps); + const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps); // Initialize individual state variables from existing session setMessages([...session.messages]); setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined); setIsLoading(session.isLoading); setTotalCost(session.totalCost || 0); setLastInputTokens(session.lastInputTokens || 0); - }, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps]); + }, [sessionManager, projectId, tools, customTools, maxSteps]); // Initialize session useEffect(() => { diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 5bbef8f0..01f538d5 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -6,6 +6,8 @@ import { createAIClient } from './ai-client'; import type { Tool } from './tools/Tool'; import type { NUser } from '@nostrify/react/login'; import type { AIProvider } from '@/contexts/AISettingsContext'; +import { makeSystemPrompt } from './system'; +import { NostrMetadata } from '@nostrify/nostrify'; export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | { role: 'assistant'; @@ -18,7 +20,6 @@ export interface SessionState { projectId: string; tools: Record; customTools: Record>; - systemPrompt?: string; maxSteps?: number; messages: AIMessage[]; streamingMessage?: { @@ -55,13 +56,13 @@ export class SessionManager { private fs: JSRuntimeFS; private aiSettings: { providers: AIProvider[] }; private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>; - private getCurrentUser?: () => NUser | undefined; + private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata }; constructor( fs: JSRuntimeFS, aiSettings: { providers: AIProvider[] }, getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>, - getCurrentUser?: () => NUser | undefined + getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata }, ) { this.fs = fs; this.aiSettings = aiSettings; @@ -76,7 +77,6 @@ export class SessionManager { projectId: string, tools: Record, customTools: Record>, - systemPrompt?: string, maxSteps?: number ): Promise { let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []; @@ -98,7 +98,6 @@ export class SessionManager { projectId, tools, customTools, - systemPrompt, maxSteps, isLoading: false, lastActivity: new Date(), @@ -114,7 +113,6 @@ export class SessionManager { session.tools = tools; session.customTools = customTools; - session.systemPrompt = systemPrompt; session.maxSteps = maxSteps; this.sessions.set(projectId, session); @@ -207,8 +205,8 @@ export class SessionManager { const model = parsed.model; // Initialize OpenAI client - const currentUser = this.getCurrentUser?.(); - const openai = createAIClient(provider, currentUser); + const { user, metadata } = this.getCurrentUser?.() ?? {}; + const openai = createAIClient(provider, user); let stepCount = 0; const maxSteps = session.maxSteps || 50; @@ -230,9 +228,20 @@ export class SessionManager { tool_calls: undefined }; + const systemPrompt = await makeSystemPrompt({ + cwd: `/projects/${projectId}`, + fs: this.fs, + mode: "agent", + name: "Shakespeare", + profession: "software extraordinaire", + tools: Object.values(session.tools), + user, + metadata, + }); + // Prepare messages for AI - const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = session.systemPrompt - ? [{ role: 'system', content: session.systemPrompt }, ...session.messages] + const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt + ? [{ role: 'system', content: systemPrompt }, ...session.messages] : session.messages; // Prepare completion options From 77508ea2fcc8095ac3be164790087d0730e0251b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 23:45:37 -0500 Subject: [PATCH 33/40] Enlarge Quilly --- src/components/Shakespeare/ChatPane.tsx | 12 ++++++------ src/components/ui/QuillySVG.tsx | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index dc835d8d..f360d87a 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -8,7 +8,7 @@ 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, X } from 'lucide-react'; import { useAISettings } from '@/hooks/useAISettings'; import { useFS } from '@/hooks/useFS'; import { useCurrentUser } from '@/hooks/useCurrentUser'; @@ -55,17 +55,17 @@ function ChatIntervention({ return (
- +
-

+

Pardon the interruption

{message}

{action && ( -
+
diff --git a/src/components/ui/QuillySVG.tsx b/src/components/ui/QuillySVG.tsx index f7e7ceb3..e3a8f31a 100644 --- a/src/components/ui/QuillySVG.tsx +++ b/src/components/ui/QuillySVG.tsx @@ -9,7 +9,7 @@ export function QuillySVG({ className = "w-4 h-4", fillColor = "currentColor", . return ( From 6facf729986bff0a3342a1feb67d81a91ba8e04b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 23:49:57 -0500 Subject: [PATCH 34/40] Fix type errors --- src/pages/Index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 7ad68dbe..ba183322 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -58,7 +58,7 @@ export default function Index() { let providerName = 'Provider'; try { const { provider } = parseProviderModel(providerModel, settings.providers); - providerName = provider.charAt(0).toUpperCase() + provider.slice(1); + providerName = provider.id.charAt(0).toUpperCase() + provider.id.slice(1); } catch { // Keep default 'Provider' } From f8b8f8e61b0d3b15cbb8de21e5e51cfa8eac0216 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 23 Sep 2025 23:56:22 -0500 Subject: [PATCH 35/40] Put Quilly action inline --- src/components/Shakespeare/ChatPane.tsx | 30 ++++++++++--------------- 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index f360d87a..641544ec 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -46,7 +46,7 @@ import { QuillySVG } from '@/components/ui/QuillySVG'; function ChatIntervention({ message, onDismiss, - action + action, }: { message: string; onDismiss: () => void; @@ -58,24 +58,18 @@ function ChatIntervention({
-
-

- Pardon the interruption -

-

{message}

-
- {action && ( -
- -
- )} + + )} +

+ // Show "Current" or "Rollback" for the most recent commit + gitStatus?.hasUncommittedChanges ? ( + + + + + + + + + Discard All Changes + + +

+ This will discard all unstaged changes and reset your working directory to the current commit: +

+
+
{firstLine}
+
+ {commit.oid.substring(0, 7)} • {formatRelativeTime(commit.commit.author.timestamp)} +
+
+

+ This action cannot be undone. +

+
+
+ + Cancel + + {isRollingBack === 'HEAD' ? ( + <> +
+ Discarding... + + ) : ( + <> + + Discard Changes + + )} + + + + + ) : ( + + ) ) : ( // Show rollback button for older commits