From e9c73693cedb72a7738ecc022ab737aa2d1198bc Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 14:29:18 -0500 Subject: [PATCH 001/105] Move email newsletter into Settings --- src/AppRouter.tsx | 3 +- src/components/EmailSubscription.tsx | 204 +++++++++++++++++++ src/components/SettingsLayout.tsx | 9 +- src/lib/i18n.ts | 18 -- src/pages/AboutSettings.tsx | 95 ++++----- src/pages/EmailSettings.tsx | 292 --------------------------- src/pages/Settings.tsx | 9 +- 7 files changed, 257 insertions(+), 373 deletions(-) create mode 100644 src/components/EmailSubscription.tsx delete mode 100644 src/pages/EmailSettings.tsx diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index c0d70908..5558d2db 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -11,7 +11,7 @@ import AISettings from "./pages/AISettings"; import GitSettings from "./pages/GitSettings"; import DataSettings from "./pages/DataSettings"; import AboutSettings from "./pages/AboutSettings"; -import EmailSettings from "./pages/EmailSettings"; + import GitHubOAuth from "./pages/GitHubOAuth"; import { NIP19Page } from "./pages/NIP19Page"; import NotFound from "./pages/NotFound"; @@ -34,7 +34,6 @@ export function AppRouter() { } /> } /> } /> - } /> } /> } /> diff --git a/src/components/EmailSubscription.tsx b/src/components/EmailSubscription.tsx new file mode 100644 index 00000000..3337864a --- /dev/null +++ b/src/components/EmailSubscription.tsx @@ -0,0 +1,204 @@ +import { useState, useEffect } from 'react'; +import { Mail, CheckCircle } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useToast } from '@/hooks/useToast'; +import { nip19 } from 'nostr-tools'; + +export function EmailSubscription() { + const { t } = useTranslation(); + const { user } = useCurrentUser(); + const { toast } = useToast(); + + const [email, setEmail] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + const [isSubmitted, setIsSubmitted] = useState(false); + + const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0'); + const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`; + const tag = '8982396'; + + // Check localStorage on component mount + useEffect(() => { + const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed'); + if (hasSubscribed === 'true') { + setIsSubmitted(true); + } + }, []); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + + if (!email.trim()) { + toast({ + title: "Email required", + description: "Please enter your email address", + variant: "destructive", + }); + return; + } + + // Basic email validation + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + toast({ + title: "Invalid email", + description: "Please enter a valid email address", + variant: "destructive", + }); + return; + } + + setIsSubmitting(true); + + try { + // Submit to Mailchimp + const form = document.createElement('form'); + form.method = 'POST'; + form.action = url.href; + form.target = '_blank'; // Open in new tab + form.style.display = 'none'; + + // Add email field + const emailInput = document.createElement('input'); + emailInput.type = 'email'; + emailInput.name = 'EMAIL'; + emailInput.value = email.trim(); + form.appendChild(emailInput); + + // Add tag field with the new Shakespeare tag ID + const tagInput = document.createElement('input'); + tagInput.type = 'hidden'; + tagInput.name = 'tags'; + tagInput.value = tag; + form.appendChild(tagInput); + + // Add npub if available + if (user?.pubkey) { + const npubInput = document.createElement('input'); + npubInput.type = 'text'; + npubInput.name = 'NPUB'; + npubInput.value = nip19.npubEncode(user.pubkey); + npubInput.style.display = 'none'; + form.appendChild(npubInput); + } + + // Add honeypot field + const honeypotInput = document.createElement('input'); + honeypotInput.type = 'text'; + honeypotInput.name = honeypot; + honeypotInput.tabIndex = -1; + honeypotInput.style.position = 'absolute'; + honeypotInput.style.left = '-5000px'; + form.appendChild(honeypotInput); + + // Add form to document and submit + document.body.appendChild(form); + form.submit(); + + // Clean up after a short delay + setTimeout(() => { + document.body.removeChild(form); + }, 1000); + + // Save subscription status to localStorage + localStorage.setItem('shakespeare-email-subscribed', 'true'); + + setIsSubmitted(true); + toast({ + title: "Successfully subscribed!", + description: "You'll receive Shakespeare updates and resources occasionally.", + }); + } catch (error) { + console.error('Email signup error:', error); + toast({ + title: "Subscription failed", + description: "There was an error subscribing you to updates. Please try again.", + variant: "destructive", + }); + } finally { + setIsSubmitting(false); + } + }; + + if (isSubmitted) { + return ( + + +
+ +
+

+ Thanks for subscribing! +

+

+ You can opt out at any time using the unsubscribe link in our emails. +

+
+ +
+
+
+ ); + } + + return ( + + + + + {t('emailUpdates')} + + + {t('emailUpdatesDescription')} + + + +
+
+ + setEmail(e.target.value)} + disabled={isSubmitting} + required + /> +
+ +
+ + +

+ You can opt out at any time using the unsubscribe link in our emails. +

+
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index 200fff49..6cf9ea0c 100644 --- a/src/components/SettingsLayout.tsx +++ b/src/components/SettingsLayout.tsx @@ -3,7 +3,7 @@ import { useNavigate, useLocation, Outlet } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { ScrollArea } from '@/components/ui/scroll-area'; -import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react'; +import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -56,13 +56,6 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [ icon: Database, href: '/settings/data', }, - { - id: 'email', - title: t('emailUpdates'), - description: t('emailUpdatesDescription'), - icon: Mail, - href: '/settings/email', - }, { id: 'about', title: t('aboutShakespeare'), diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index c10614a4..e3c9b300 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -81,9 +81,6 @@ const resources = { dataSettingsDescription: 'Export files and manage local data', emailUpdates: 'Email Updates', emailUpdatesDescription: 'Subscribe to Shakespeare updates and resources', - emailUpdatesDescriptionLong: 'Stay updated with the latest Shakespeare features, tutorials, and resources.', - aboutShakespeareSettings: 'About Shakespeare', - aboutShakespeareSettingsDescription: 'Information about Shakespeare', // Project Sidebar newProject: 'New Project', @@ -393,9 +390,6 @@ const resources = { dataSettingsDescription: 'Exporte arquivos e gerencie dados locais', emailUpdates: 'Atualizações por Email', emailUpdatesDescription: 'Inscreva-se para receber atualizações e recursos do Shakespeare', - emailUpdatesDescriptionLong: 'Mantenha-se atualizado com os recursos mais recentes do Shakespeare, tutoriais e recursos. Enviamos apenas atualizações ocasionais e você pode cancelar a inscrição a qualquer momento.', - aboutShakespeareSettings: 'Sobre o Shakespeare', - aboutShakespeareSettingsDescription: 'Informações sobre o Shakespeare', // Project Sidebar newProject: 'Novo Projeto', @@ -705,9 +699,6 @@ const resources = { dataSettingsDescription: '导出文件和管理本地数据', emailUpdates: '邮件更新', emailUpdatesDescription: '订阅Shakespeare更新和资源', - emailUpdatesDescriptionLong: '及时了解最新的Shakespeare功能、教程和资源。我们只会偶尔发送更新,您可以随时取消订阅。', - aboutShakespeareSettings: '关于Shakespeare', - aboutShakespeareSettingsDescription: '关于Shakespeare的信息', // Project Sidebar newProject: '新项目', @@ -1017,9 +1008,6 @@ const resources = { dataSettingsDescription: 'Fitar da fayiloli da sarrafa bayanan gida', emailUpdates: 'Sabuntawar Imel', emailUpdatesDescription: 'Yi rajista don karbar sabuntawar Shakespeare da albarkatu', - emailUpdatesDescriptionLong: 'Kasance da sabuntawa game da sabbin fasalolin Shakespeare, koyarwa, da albarkatu. Muna aika sabuntawa lokaci-lokaci kawai kuma kuna iya dakatar da rajista koyaushe.', - aboutShakespeareSettings: 'Game da Shakespeare', - aboutShakespeareSettingsDescription: 'Bayani game da Shakespeare', // Project Sidebar newProject: 'Sabon Aikin', @@ -1329,9 +1317,6 @@ const resources = { dataSettingsDescription: 'Gbe awọn faili jade ati ṣakoso data agbegbe', emailUpdates: 'Awọn Imudojuiwọn Imeeli', emailUpdatesDescription: 'Forukọsilẹ fun awọn imudojuiwọn Shakespeare ati awọn ohun elo', - emailUpdatesDescriptionLong: 'Wa pẹlu imudojuiwọn pẹlu awọn ẹya Shakespeare tuntun, awọn ikẹkọ, ati awọn ohun elo. A nfi awọn imudojuiwọn lọọrọọ nikan ranṣẹ ati pe o le da forukọsilẹ duro nigbakugba.', - aboutShakespeareSettings: 'Nipa Shakespeare', - aboutShakespeareSettingsDescription: 'Alaye nipa Shakespeare', // Project Sidebar newProject: 'Iṣẹ akanṣe Tuntun', @@ -1636,9 +1621,6 @@ const resources = { dataSettingsDescription: 'Bupụta faịlụ na jikwaa data mpaghara', emailUpdates: 'Nmelite Email', emailUpdatesDescription: 'Debanye aha maka nmelite Shakespeare na akụrụngwa', - emailUpdatesDescriptionLong: 'Nọrọ na-emelite na atụmatụ Shakespeare ọhụrụ, nkuzi, na akụrụngwa. Anyị na-eziga naanị nmelite mgbe ụfọdụ ma ị nwere ike ịkwụsị ndebanye aha mgbe ọ bụla.', - aboutShakespeareSettings: 'Gbasara Shakespeare', - aboutShakespeareSettingsDescription: 'Ozi gbasara Shakespeare', // Project Sidebar newProject: 'Ọrụ Ọhụrụ', diff --git a/src/pages/AboutSettings.tsx b/src/pages/AboutSettings.tsx index 8c577b8f..8e5e86dd 100644 --- a/src/pages/AboutSettings.tsx +++ b/src/pages/AboutSettings.tsx @@ -1,11 +1,12 @@ import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft } from 'lucide-react'; +import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { useIsMobile } from '@/hooks/useIsMobile'; +import { EmailSubscription } from '@/components/EmailSubscription'; export function AboutSettings() { const { t } = useTranslation(); @@ -77,52 +78,56 @@ export function AboutSettings() { )} -
- {/* Project Information */} - +
+ {/* Email Updates */} + - {/* License */} - - - -
- - {t('license')} -
-
- - {isLoading ? ( -
- - {t('loadingLicense')} +
+ {/* Project Information */} + + + {/* License */} + + + +
+ + {t('license')}
- ) : error ? ( - - - - {t('failedToLoadLicense')}: {error} - - - ) : license ? ( -
- ) : null} - - - + + + {isLoading ? ( +
+ + {t('loadingLicense')} +
+ ) : error ? ( + + + + {t('failedToLoadLicense')}: {error} + + + ) : license ? ( +
+ ) : null} + + + +
); diff --git a/src/pages/EmailSettings.tsx b/src/pages/EmailSettings.tsx deleted file mode 100644 index efff3f35..00000000 --- a/src/pages/EmailSettings.tsx +++ /dev/null @@ -1,292 +0,0 @@ -import { useState, useEffect } from 'react'; -import { ArrowLeft, Mail, CheckCircle } from 'lucide-react'; -import { useTranslation } from 'react-i18next'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; -import { useIsMobile } from '@/hooks/useIsMobile'; -import { useNavigate } from 'react-router-dom'; -import { useCurrentUser } from '@/hooks/useCurrentUser'; -import { useToast } from '@/hooks/useToast'; -import { nip19 } from 'nostr-tools'; - -export function EmailSettings() { - const { t } = useTranslation(); - const isMobile = useIsMobile(); - const navigate = useNavigate(); - const { user } = useCurrentUser(); - const { toast } = useToast(); - - const [email, setEmail] = useState(''); - const [isSubmitting, setIsSubmitting] = useState(false); - const [isSubmitted, setIsSubmitted] = useState(false); - - const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0'); - const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`; - const tag = '8982396'; - - // Check localStorage on component mount - useEffect(() => { - const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed'); - if (hasSubscribed === 'true') { - setIsSubmitted(true); - } - }, []); - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - - if (!email.trim()) { - toast({ - title: "Email required", - description: "Please enter your email address", - variant: "destructive", - }); - return; - } - - // Basic email validation - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(email)) { - toast({ - title: "Invalid email", - description: "Please enter a valid email address", - variant: "destructive", - }); - return; - } - - setIsSubmitting(true); - - try { - // Submit to Mailchimp - const form = document.createElement('form'); - form.method = 'POST'; - form.action = url.href; - form.target = '_blank'; // Open in new tab - form.style.display = 'none'; - - // Add email field - const emailInput = document.createElement('input'); - emailInput.type = 'email'; - emailInput.name = 'EMAIL'; - emailInput.value = email.trim(); - form.appendChild(emailInput); - - // Add tag field with the new Shakespeare tag ID - const tagInput = document.createElement('input'); - tagInput.type = 'hidden'; - tagInput.name = 'tags'; - tagInput.value = tag; - form.appendChild(tagInput); - - // Add npub if available - if (user?.pubkey) { - const npubInput = document.createElement('input'); - npubInput.type = 'text'; - npubInput.name = 'NPUB'; - npubInput.value = nip19.npubEncode(user.pubkey); - npubInput.style.display = 'none'; - form.appendChild(npubInput); - } - - // Add honeypot field - const honeypotInput = document.createElement('input'); - honeypotInput.type = 'text'; - honeypotInput.name = honeypot; - honeypotInput.tabIndex = -1; - honeypotInput.style.position = 'absolute'; - honeypotInput.style.left = '-5000px'; - form.appendChild(honeypotInput); - - // Add form to document and submit - document.body.appendChild(form); - form.submit(); - - // Clean up after a short delay - setTimeout(() => { - document.body.removeChild(form); - }, 1000); - - // Save subscription status to localStorage - localStorage.setItem('shakespeare-email-subscribed', 'true'); - - setIsSubmitted(true); - toast({ - title: "Successfully subscribed!", - description: "You'll receive Shakespeare updates and resources occasionally.", - }); - } catch (error) { - console.error('Email signup error:', error); - toast({ - title: "Subscription failed", - description: "There was an error subscribing you to updates. Please try again.", - variant: "destructive", - }); - } finally { - setIsSubmitting(false); - } - }; - - if (isSubmitted) { - return ( -
- {isMobile && ( -
- -
-

- - {t('emailUpdates')} -

-

- {t('emailUpdatesDescriptionLong')} -

-
-
- )} - - {!isMobile && ( -
-

- - {t('emailUpdates')} -

-

- {t('emailUpdatesDescriptionLong')} -

-
- )} - -
- - -
- -
-

- Thanks for subscribing! -

-

- You can opt out at any time using the unsubscribe link in our emails. -

-
-
- - -
-
-
-
-
-
- ); - } - - return ( -
- {isMobile && ( -
- -
-

- - {t('emailUpdates')} -

-

- {t('emailUpdatesDescriptionLong')} -

-
-
- )} - - {!isMobile && ( -
-

- - {t('emailUpdates')} -

-

- {t('emailUpdatesDescriptionLong')} -

-
- )} - -
- - - - Stay Updated with Shakespeare - - - -
-
- - setEmail(e.target.value)} - disabled={isSubmitting} - required - /> -
- -
- - -

- You can opt out at any time using the unsubscribe link in our emails. -

-
-
-
-
-
-
- ); -} - -export default EmailSettings; \ No newline at end of file diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index ecb29350..cf978600 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -1,6 +1,6 @@ import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react'; +import { Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; interface SettingsItem { @@ -48,13 +48,6 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [ icon: Database, href: '/settings/data', }, - { - id: 'email', - title: t('emailUpdates'), - description: t('emailUpdatesDescription'), - icon: Mail, - href: '/settings/email', - }, { id: 'about', title: t('aboutShakespeare'), From e8156243d023629250d18130aee7d04d2ce6d754 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 14:48:06 -0500 Subject: [PATCH 002/105] Simplify Nostr Settings loading skeleton --- src/pages/NostrSettings.tsx | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/pages/NostrSettings.tsx b/src/pages/NostrSettings.tsx index cf8112a9..41de533e 100644 --- a/src/pages/NostrSettings.tsx +++ b/src/pages/NostrSettings.tsx @@ -92,15 +92,13 @@ export function NostrSettings() { {isLoading ? (
{/* Loading skeleton for accounts */} - {[...Array(2)].map((_, i) => ( -
- -
- -
- +
+ +
+
- ))} + +
{/* Add account button skeleton */}
From 2db9d5e513f8d342e791f919d6008b6a729ef60d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 15:32:26 -0500 Subject: [PATCH 003/105] Move Import ZIP File to Clone page --- src/components/ProjectSidebar.tsx | 42 +++--------------------- src/pages/Clone.tsx | 53 +++++++++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 40 deletions(-) diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 3d6782a0..58d8d00a 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,7 +1,7 @@ -import React, { useEffect, useState } from 'react'; +import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; @@ -9,9 +9,7 @@ import { useProjects } from '@/hooks/useProjects'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; -import { ZipImportDialog } from '@/components/ZipImportDialog'; -import { useProjectsManager } from '@/hooks/useProjectsManager'; -import { useToast } from '@/hooks/useToast'; + import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; @@ -95,9 +93,6 @@ export function ProjectSidebar({ const queryClient = useQueryClient(); const { data: projects = [], isLoading, error } = useProjects(); const [favorites] = useLocalStorage('project-favorites', []); - const projectsManager = useProjectsManager(); - const { toast } = useToast(); - const [isZipDialogOpen, setIsZipDialogOpen] = useState(false); const isMobile = useIsMobile(); const navigate = useNavigate(); @@ -123,24 +118,7 @@ export function ProjectSidebar({ } }; - const handleImportZip = async (file: File, overwrite = false, projectId?: string) => { - try { - // Import project from zip file - const project = await projectsManager.importProjectFromZip(file, projectId, overwrite); - // Show success toast - toast({ - title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully", - description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`, - }); - - // Navigate to the imported project - navigate(`/project/${project.id}`); - } catch (error) { - console.error('Failed to import project:', error); - throw error; // Re-throw to let the dialog handle the error display - } - }; useEffect(() => { queryClient.invalidateQueries({ queryKey: ['projects'] }); @@ -211,13 +189,6 @@ export function ProjectSidebar({ {t('importRepository')} - setIsZipDialogOpen(true)} - className="flex items-center gap-2 w-full" - > - - Import ZIP File -
@@ -281,12 +252,7 @@ export function ProjectSidebar({
- {/* ZIP Import Dialog */} - +
); } \ No newline at end of file diff --git a/src/pages/Clone.tsx b/src/pages/Clone.tsx index 01ec43ca..ac4b54e6 100644 --- a/src/pages/Clone.tsx +++ b/src/pages/Clone.tsx @@ -4,11 +4,12 @@ import { useTranslation } from 'react-i18next'; import { AppLayout } from '@/components/AppLayout'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; -import { GitBranch, Loader2, AlertCircle } from 'lucide-react'; +import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useToast } from '@/hooks/useToast'; - +import { ZipImportDialog } from '@/components/ZipImportDialog'; import { useSeoMeta } from '@unhead/react'; +import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu'; export default function Clone() { const { t } = useTranslation(); @@ -20,6 +21,7 @@ export default function Clone() { const projectsManager = useProjectsManager(); const { toast } = useToast(); const autoCloneInitiatedRef = useRef(false); + const [isZipDialogOpen, setIsZipDialogOpen] = useState(false); useSeoMeta({ title: `${t('importRepository')} - Shakespeare`, @@ -171,6 +173,25 @@ export default function Clone() { } }, [handleClone, searchParams]); + const handleImportZip = async (file: File, overwrite = false, projectId?: string) => { + try { + // Import project from zip file + const project = await projectsManager.importProjectFromZip(file, projectId, overwrite); + + // Show success toast + toast({ + title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully", + description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`, + }); + + // Navigate to the imported project + navigate(`/project/${project.id}`); + } catch (error) { + console.error('Failed to import project:', error); + throw error; // Re-throw to let the dialog handle the error display + } + }; + return (
@@ -226,7 +247,35 @@ export default function Clone() { )}
+ + {/* Import ZIP File Link */} +
+ + + + + + setIsZipDialogOpen(true)} + > + + Import ZIP File + + + +
+ + {/* ZIP Import Dialog */} + ); } \ No newline at end of file From a9a5cafcac967f705cd4df11a374fba8f0453c96 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 16:26:07 -0500 Subject: [PATCH 004/105] Don't hardcode gitnostr.com --- src/components/GitDialog.tsx | 2 +- src/components/NostrProvider.tsx | 1 - src/lib/git.ts | 2 -- 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index b2c4d6b5..e53629ee 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -47,7 +47,7 @@ import { cn } from '@/lib/utils'; import { findCredentialsForRepo } from '@/lib/gitCredentials'; import { nip19 } from 'nostr-tools'; -const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"]; +const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"]; interface GitDialogProps { projectId: string; diff --git a/src/components/NostrProvider.tsx b/src/components/NostrProvider.tsx index 7b89ae81..b902f297 100644 --- a/src/components/NostrProvider.tsx +++ b/src/components/NostrProvider.tsx @@ -18,7 +18,6 @@ const GIT_KINDS = [ const GIT_RELAYS = [ 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/', - 'wss://gitnostr.com/', ]; const NostrProvider: React.FC = (props) => { diff --git a/src/lib/git.ts b/src/lib/git.ts index 93dcc008..2504755a 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -911,7 +911,6 @@ export class Git { const gitRelays = new Set([ 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/', - 'wss://gitnostr.com/', 'wss://relay.nostr.band/', // General purpose relay as fallback ]); @@ -1396,7 +1395,6 @@ export class Git { relayUrls.push( 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/', - 'wss://gitnostr.com/', 'wss://relay.nostr.band/' ); } From b064c9ff8619fa69f5c2a439470337a86ac0f455 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 20:17:10 -0500 Subject: [PATCH 005/105] Mock "sonner" and "next-themes" when building --- src/lib/build/index.ts | 2 + src/lib/build/shakespearePlugin.ts | 131 +++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 src/lib/build/shakespearePlugin.ts diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index fc9dbd1c..956aa6a7 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,6 +1,7 @@ import { getEsbuild } from "@/lib/esbuild"; import { copyFiles } from "@/lib/copyFiles"; +import { shakespearePlugin } from "./shakespearePlugin"; import { esmPlugin } from "./esmPlugin"; import { fsPlugin } from "./fsPlugin"; @@ -49,6 +50,7 @@ async function bundle( outdir: "/", jsx: "automatic", plugins: [ + shakespearePlugin(), // Takes precedence over esmPlugin fsPlugin(fs, `${projectPath}/src`), esmPlugin(JSON.parse(packageLockText), target), ], diff --git a/src/lib/build/shakespearePlugin.ts b/src/lib/build/shakespearePlugin.ts new file mode 100644 index 00000000..06841907 --- /dev/null +++ b/src/lib/build/shakespearePlugin.ts @@ -0,0 +1,131 @@ +import type { Plugin } from "esbuild-wasm"; + +/** + * Shakespeare plugin for dependency polyfills and workarounds. + * This plugin handles specific dependencies that need custom implementations + * or dummy APIs to work correctly in the browser environment. + */ +export function shakespearePlugin(): Plugin { + return { + name: "shakespeare", + + setup(build) { + // Handle "sonner" imports with a dummy API + build.onResolve({ filter: /^sonner$/ }, (args) => { + return { + path: args.path, + namespace: "shakespeare-sonner", + }; + }); + + // Provide dummy sonner implementation + build.onLoad({ filter: /.*/, namespace: "shakespeare-sonner" }, () => { + return { + contents: ` + // Dummy implementation of sonner toast library + + // Toast function that does nothing + const toast = (message, options) => { + console.log('[Shakespeare Sonner Mock]:', message, options); + return { id: Math.random().toString(36) }; + }; + + // Add common toast methods + toast.success = (message, options) => { + console.log('[Shakespeare Sonner Mock] Success:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.error = (message, options) => { + console.log('[Shakespeare Sonner Mock] Error:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.info = (message, options) => { + console.log('[Shakespeare Sonner Mock] Info:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.warning = (message, options) => { + console.log('[Shakespeare Sonner Mock] Warning:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.loading = (message, options) => { + console.log('[Shakespeare Sonner Mock] Loading:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.promise = (promise, options) => { + console.log('[Shakespeare Sonner Mock] Promise:', promise, options); + return promise; + }; + + toast.dismiss = (id) => { + console.log('[Shakespeare Sonner Mock] Dismiss:', id); + }; + + // Toaster component (dummy React component) + const Toaster = (props) => { + console.log('[Shakespeare Sonner Mock] Toaster component rendered:', props); + return null; + }; + + // Export both named and default exports to match sonner API + export { toast, Toaster }; + export default toast; + `, + loader: "js", + }; + }); + + // Handle "next-themes" imports with a dummy API + build.onResolve({ filter: /^next-themes$/ }, (args) => { + return { + path: args.path, + namespace: "shakespeare-next-themes", + }; + }); + + // Provide dummy next-themes implementation + build.onLoad({ filter: /.*/, namespace: "shakespeare-next-themes" }, () => { + return { + contents: ` + // Dummy implementation of next-themes + + // useTheme hook that returns system theme + const useTheme = () => { + return { theme: "system" }; + }; + + // ThemeProvider component (dummy React component) + const ThemeProvider = ({ children, ...props }) => { + console.log('[Shakespeare next-themes Mock] ThemeProvider rendered:', props); + return children; + }; + + // Export both named and default exports to match next-themes API + export { useTheme, ThemeProvider }; + `, + loader: "js", + }; + }); + + // Add more dependency polyfills here as needed + // Example structure for future dependencies: + // build.onResolve({ filter: /^some-other-package$/ }, (args) => { + // return { + // path: args.path, + // namespace: "shakespeare-other-package", + // }; + // }); + // + // build.onLoad({ filter: /.*/, namespace: "shakespeare-other-package" }, () => { + // return { + // contents: `// Custom implementation for some-other-package`, + // loader: "js", + // }; + // }); + }, + }; +} \ No newline at end of file From 124e9d5937d52d8794f785d35e6a8180b83f2ed2 Mon Sep 17 00:00:00 2001 From: sam Date: Sun, 28 Sep 2025 08:37:45 +0700 Subject: [PATCH 006/105] wip, bring error handling up to the project level to exist across mobile tabs --- src/components/Shakespeare/ChatPane.tsx | 37 +++++++++++++------------ src/pages/ProjectView.tsx | 22 +++++++++++++-- 2 files changed, 40 insertions(+), 19 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index f9d724c0..4fb8905a 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -34,7 +34,7 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool'; import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; -import { ReadConsoleMessagesTool, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; @@ -51,6 +51,8 @@ interface ChatPaneProps { onLoadingChange?: (isLoading: boolean) => void; isLoading?: boolean; isBuildLoading?: boolean; + consoleError?: ProjectPreviewConsoleError | null; + onDismissConsoleError?: () => void; } export interface ChatPaneRef { @@ -64,6 +66,8 @@ export const ChatPane = forwardRef(({ onLoadingChange, isLoading: externalIsLoading, isBuildLoading: externalIsBuildLoading, + consoleError, + onDismissConsoleError, }, ref) => { const { t } = useTranslation(); const [searchParams, setSearchParams] = useSearchParams(); @@ -80,18 +84,8 @@ export const ChatPane = forwardRef(({ const [isStuck, setIsStuck] = useState(false); const [aiError, setAIError] = useState(null); - // Console error handling - useEffect(() => { - const handleConsoleError = (error: ProjectPreviewConsoleError) => { - // Only show console errors if there's no existing AI error - if (!aiError) { - setAIError(error); - } - }; - - addErrorListener(handleConsoleError); - return () => removeErrorListener(handleConsoleError); - }, [aiError]); + // Determine which error to show - console error takes priority over AI errors + const displayError = consoleError || aiError; // Use external state if provided, otherwise default to false const isBuildLoading = externalIsBuildLoading || false; @@ -225,6 +219,15 @@ export const ChatPane = forwardRef(({ sendMessage('Read the console messages and fix any errors present.', providerModel); }, [sendMessage, providerModel]); + // Handle error dismissal + const handleErrorDismiss = useCallback(() => { + if (consoleError && onDismissConsoleError) { + onDismissConsoleError(); + } else { + setAIError(null); + } + }, [consoleError, onDismissConsoleError]); + // Use external loading state if provided, otherwise use internal state const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading; @@ -608,11 +611,11 @@ export const ChatPane = forwardRef(({
)} - {/* AI Error Alert */} - {aiError && ( + {/* Error Alert (Console or AI) */} + {displayError && ( setAIError(null)} + error={displayError} + onDismiss={handleErrorDismiss} onNewChat={onNewChat} onOpenModelSelector={openModelSelector} onRequestConsoleErrorHelp={handleConsoleErrorHelp} diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 8dd43d1c..f73f3a3b 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -18,7 +18,7 @@ import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { StarButton } from '@/components/StarButton'; import { useBuildProject } from '@/hooks/useBuildProject'; import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable'; -import { clearConsoleMessages } from '@/lib/tools/ReadConsoleMessagesTool'; +import { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool'; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); @@ -29,6 +29,7 @@ export function ProjectView() { const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat'); const [isAILoading, setIsAILoading] = useState(false); const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false); + const [consoleError, setConsoleError] = useState(null); const projectsManager = useProjectsManager(); const chatPaneRef = useRef(null); @@ -46,8 +47,9 @@ export function ProjectView() { try { const projectData = await projectsManager.getProject(projectId); setProject(projectData); - // Clear console messages when switching projects + // Clear console messages and error state when switching projects clearConsoleMessages(); + setConsoleError(null); } catch (error) { console.error('Failed to load project:', error); } finally { @@ -79,6 +81,16 @@ export function ProjectView() { } }, [isPreviewable, mobileView, activeTab]); + // Global console error listener (always active regardless of current tab) + useEffect(() => { + const handleConsoleError = (error: ProjectPreviewConsoleError) => { + setConsoleError(error); + }; + + addErrorListener(handleConsoleError); + return () => removeErrorListener(handleConsoleError); + }, []); + const handleNewChat = () => { // Reset to chat view on mobile when starting new chat if (isMobile) { @@ -100,6 +112,10 @@ export function ProjectView() { // when isAILoading becomes true after user interaction }; + const handleDismissConsoleError = () => { + setConsoleError(null); + }; + const handleProjectDeleted = async () => { setProject(null); navigate('/'); @@ -212,6 +228,8 @@ export function ProjectView() { onLoadingChange={handleAILoadingChange} isLoading={isAILoading} isBuildLoading={build.isPending} + consoleError={consoleError} + onDismissConsoleError={handleDismissConsoleError} /> ) : (
From 2ec32f55377c5f9daa132327dc089c2db7415933 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 20:39:51 -0500 Subject: [PATCH 007/105] Polyfill virtual:pwa-register/react --- src/lib/build/shakespearePlugin.ts | 37 ++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/lib/build/shakespearePlugin.ts b/src/lib/build/shakespearePlugin.ts index 06841907..c315be66 100644 --- a/src/lib/build/shakespearePlugin.ts +++ b/src/lib/build/shakespearePlugin.ts @@ -111,6 +111,43 @@ export function shakespearePlugin(): Plugin { }; }); + // Handle "virtual:pwa-register/react" imports with a dummy API + build.onResolve({ filter: /^virtual:pwa-register\/react$/ }, (args) => { + return { + path: args.path, + namespace: "shakespeare-pwa-register", + }; + }); + + // Provide dummy PWA register implementation + build.onLoad({ filter: /.*/, namespace: "shakespeare-pwa-register" }, () => { + return { + contents: ` + // Dummy implementation of virtual:pwa-register/react + + // useRegisterSW hook that returns dummy functions + const useRegisterSW = (options = {}) => { + console.log('[Shakespeare PWA Mock] useRegisterSW called:', options); + + return { + needRefresh: [false, () => {}], + offlineReady: [false, () => {}], + updateServiceWorker: (reloadPage) => { + console.log('[Shakespeare PWA Mock] updateServiceWorker called:', reloadPage); + if (reloadPage) { + window.location.reload(); + } + }, + }; + }; + + // Export the hook + export { useRegisterSW }; + `, + loader: "js", + }; + }); + // Add more dependency polyfills here as needed // Example structure for future dependencies: // build.onResolve({ filter: /^some-other-package$/ }, (args) => { From 939deabb5b5118ec5a62e0a6d1d9e7916eb34176 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 21:07:28 -0500 Subject: [PATCH 008/105] Support Vite query params of local imports, specifically ?raw --- src/lib/build/fsPlugin.ts | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index 5e914752..28856e45 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -1,4 +1,4 @@ -import path from "path-browserify"; +import { join, dirname, extname } from "path-browserify"; import type { Loader, Plugin } from "esbuild-wasm"; import type { JSRuntimeFS } from '@/lib/JSRuntime'; @@ -12,23 +12,26 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { let resolved: string; if (args.path.startsWith("@/")) { - resolved = path.join(cwd, args.path.slice(2)); + resolved = join(cwd, args.path.slice(2)); } else if (args.kind === "entry-point") { - resolved = path.join(cwd, args.path); + resolved = join(cwd, args.path); } else if (args.importer) { - resolved = path.join(path.dirname(args.importer), args.path); + resolved = join(dirname(args.importer), args.path); } else { return; } + // Vite query parameters https://vite.dev/guide/assets + const [cleaned, query] = resolved.split("?"); + try { - resolved = await tryFileVariants(fs, resolved); + resolved = await tryFileVariants(fs, cleaned); } catch { return; // Let other plugins handle this } return { - path: resolved, + path: resolved + (typeof query === "string" ? "?" + query : ""), namespace: "fs", }; }); @@ -36,14 +39,25 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { build.onLoad( { filter: /.*/, namespace: "fs" }, async (args) => { - const ext = path.extname(args.path).slice(1); + const [path, query] = args.path.split("?"); + const params = new URLSearchParams(query); + + // https://vite.dev/guide/assets.html#importing-asset-as-string + if (params.has("raw")) { + return { + contents: await fs.readFile(path, "utf8"), + loader: "text", + }; + } + + const ext = extname(path).slice(1); if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) { return; } return { - contents: await fs.readFile(args.path, "utf8"), + contents: await fs.readFile(path, "utf8"), loader: ext as Loader, }; }, @@ -67,7 +81,7 @@ async function tryFileVariants( // If it's a directory, try index files if (stat.isDirectory()) { for (const ext of extensions) { - const indexFile = path.join(basePath, "index" + ext); + const indexFile = join(basePath, "index" + ext); const indexStat = await statSafe(fs, indexFile); if (indexStat.isFile()) { return indexFile; From 8c60a3a8bced8a5d6d4db50fc0aaa3c5a57d8920 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 21:23:45 -0500 Subject: [PATCH 009/105] Externalize static assets like fonts --- src/lib/build/esmPlugin.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index ce95e7c0..abc9f816 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -131,6 +131,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { } } + // Skip static assets + if (/\.(woff2?|ttf|otf|eot)$/.test(fullURL.pathname)) { + return { + path: fullURL.toString(), + external: true, + }; + } + return { path: fullURL.toString(), namespace: "esm", From eba609ae7337a4aa0e935e4751658e969feb2e07 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 21:40:07 -0500 Subject: [PATCH 010/105] NpmAddPackageTool should not bump the package version --- src/lib/tools/NpmAddPackageTool.test.ts | 23 +++++++++++++++++++++-- src/lib/tools/NpmAddPackageTool.ts | 15 +++++++++++---- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/lib/tools/NpmAddPackageTool.test.ts b/src/lib/tools/NpmAddPackageTool.test.ts index 65ddd3c6..0e4a8917 100644 --- a/src/lib/tools/NpmAddPackageTool.test.ts +++ b/src/lib/tools/NpmAddPackageTool.test.ts @@ -195,6 +195,25 @@ describe('NpmAddPackageTool', () => { } }; + vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2)); + + const result = await tool.execute({ name: 'lodash' }); + + // Should not fetch from registry when no version specified and package already installed + expect(mockFetch).not.toHaveBeenCalled(); + expect(mockFS.writeFile).not.toHaveBeenCalled(); + expect(result).toContain('ℹ️ Package lodash is already installed in dependencies with version ^4.17.21.'); + }); + + it('should handle package already installed with specific version', async () => { + const packageJson = { + name: 'test-project', + version: '1.0.0', + dependencies: { + 'lodash': '^4.17.21' + } + }; + vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2)); mockFetch.mockResolvedValue({ ok: true, @@ -208,10 +227,10 @@ describe('NpmAddPackageTool', () => { }) }); - const result = await tool.execute({ name: 'lodash' }); + const result = await tool.execute({ name: 'lodash', version: '4.17.21' }); expect(mockFS.writeFile).not.toHaveBeenCalled(); - expect(result).toContain('ℹ️ Package lodash@4.17.21 is already installed'); + expect(result).toContain('ℹ️ Package lodash@4.17.21 is already installed in dependencies.'); }); it('should handle missing package.json', async () => { diff --git a/src/lib/tools/NpmAddPackageTool.ts b/src/lib/tools/NpmAddPackageTool.ts index d29865c8..a911d657 100644 --- a/src/lib/tools/NpmAddPackageTool.ts +++ b/src/lib/tools/NpmAddPackageTool.ts @@ -88,6 +88,16 @@ export class NpmAddPackageTool implements Tool { throw new Error(`❌ Invalid package.json format. Could not parse JSON.`); } + // Check if package already exists + const dependencyKey = dev ? 'devDependencies' : 'dependencies'; + const otherKey = dev ? 'dependencies' : 'devDependencies'; + + // If no version is specified and package is already installed, it's a no-op + if (!version && packageJson[dependencyKey]?.[name]) { + const currentVersion = packageJson[dependencyKey][name]; + return `ℹ️ Package ${name} is already installed in ${dependencyKey} with version ${currentVersion}.`; + } + // Determine version to use and fetch package metadata let targetVersion = version; let packageMetadata: NpmRegistryResponse; @@ -107,10 +117,7 @@ export class NpmAddPackageTool implements Tool { } } - // Check if package already exists - const dependencyKey = dev ? 'devDependencies' : 'dependencies'; - const otherKey = dev ? 'dependencies' : 'devDependencies'; - + // Check if package already exists with the specific version if (packageJson[dependencyKey]?.[name]) { const currentVersion = packageJson[dependencyKey][name]; if (currentVersion === `^${targetVersion}`) { From 93a636589d753f9161dc265bac63432616b24f39 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 22:22:49 -0500 Subject: [PATCH 011/105] Fix Tailwind styles --- src/lib/build/index.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 956aa6a7..6817bcb2 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -73,7 +73,7 @@ async function bundle( } // Update index.html with proper script and link tags - updateIndexHtml(doc); + updateIndexHtml(doc, dist); const updatedHtml = "\n" + doc.documentElement.outerHTML; dist["index.html"] = new TextEncoder().encode(updatedHtml); @@ -156,7 +156,7 @@ export async function buildProject(options: BuildProjectOptions): Promise<{ }; } -function updateIndexHtml(doc: Document): void { +function updateIndexHtml(doc: Document, dist: Record): void { const entrypoint = doc.querySelector('script[src="/src/main.tsx"]'); if (!entrypoint) { @@ -165,8 +165,11 @@ function updateIndexHtml(doc: Document): void { entrypoint.setAttribute("src", "/main.js"); - const style = doc.createElement("link"); - style.setAttribute("rel", "stylesheet"); - style.setAttribute("href", "/main.css"); - doc.head.appendChild(style); + const css = dist["main.css"]; + if (css) { + const style = doc.createElement("style"); + style.setAttribute("type", "text/tailwindcss"); + style.textContent = new TextDecoder().decode(css); + doc.head.appendChild(style); + } } \ No newline at end of file From 3529d43b91cb04a31b0e39825288b3ea3bdeed1e Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 22:28:21 -0500 Subject: [PATCH 012/105] Support json imports --- src/lib/build/fsPlugin.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index 28856e45..7d35b0eb 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -52,7 +52,7 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { const ext = extname(path).slice(1); - if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) { + if (!["ts", "tsx", "js", "jsx", "css", "json"].includes(ext)) { return; } From 4e0625721e913533b5cec59296ca368a74cea892 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 22:42:16 -0500 Subject: [PATCH 013/105] Fix compatibility with leaflet --- src/lib/build/esmPlugin.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index abc9f816..9651ae3b 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -61,6 +61,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { } }); + // Legacy (Internet Explorer) "behavior" syntax + build.onResolve({ filter: /^#default#/, namespace: "esm" }, (args) => { + return { + path: args.path, + external: true, + }; + }); + // Handle bare imports like "react" build.onResolve({ filter: /^[^./].*/ }, (args) => { const packageName = args.path.startsWith("@") From 8b62ba8e7e32c0a18f0a1a9451cc91f2cd7f7e19 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Sat, 27 Sep 2025 01:36:54 -0700 Subject: [PATCH 014/105] Updated logos, default theme, onboard modals, and mobile browser fixes --- src/App.tsx | 2 +- src/components/AppLayout.tsx | 4 -- src/components/CreditsDialog.tsx | 2 +- src/components/OnboardingDialog.test.tsx | 2 +- src/components/OnboardingDialog.tsx | 69 +++++++++++++----------- src/components/ProjectSidebar.test.tsx | 2 +- src/components/ProjectSidebar.tsx | 6 ++- src/components/Shakespeare/ChatPane.tsx | 8 ++- src/pages/Index.tsx | 8 ++- 9 files changed, 61 insertions(+), 42 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index b3944f7d..45c68be2 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -38,7 +38,7 @@ const queryClient = new QueryClient({ }); const defaultConfig: AppConfig = { - theme: "light", + theme: "system", relayUrl: "wss://relay.primal.net", deployServer: "shakespeare.wtf", }; diff --git a/src/components/AppLayout.tsx b/src/components/AppLayout.tsx index f58455e0..cc9552ed 100644 --- a/src/components/AppLayout.tsx +++ b/src/components/AppLayout.tsx @@ -18,7 +18,6 @@ interface AppLayoutProps { export function AppLayout({ children, selectedProject = null, - title = "Shakespeare", showSidebar = true, headerContent }: AppLayoutProps) { @@ -85,9 +84,6 @@ export function AppLayout({ )} -

- {title} -

{headerContent} diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 64dd1f30..4b33517c 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -399,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro return ( - + e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none"> {lightningInvoice ? ( diff --git a/src/components/OnboardingDialog.test.tsx b/src/components/OnboardingDialog.test.tsx index cbf028e4..79bd7d2c 100644 --- a/src/components/OnboardingDialog.test.tsx +++ b/src/components/OnboardingDialog.test.tsx @@ -42,7 +42,7 @@ describe('OnboardingDialog', () => { ); - expect(screen.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading + expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument(); expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument(); }); diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 4fa385a1..a38f07a8 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -8,7 +8,6 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; -import { ScrollArea } from '@/components/ui/scroll-area'; import { useAISettings } from '@/hooks/useAISettings'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; @@ -119,8 +118,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) return ( <> - - + + {step === 'model-selection' && ( )} + {step === 'conclusion' && ( + + )} - {step === 'welcome' && 'Welcome to Shakespeare!'} {step === 'model-selection' && 'Choose Your AI Model'} - {step === 'conclusion' && "You're All Set!"} -
+
{step === 'welcome' && (
-
🎭
+
+ Shakespeare +

Welcome to Shakespeare! @@ -191,15 +204,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) )} {step === 'model-selection' && ( -
-
-

- Choose an AI model to power your development experience. - Different models offer various capabilities and pricing. -

-
- - +
+
{isLoadingModels ? ( <> @@ -232,6 +238,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) shakespeareModels.map((model) => { const isSelected = selectedModel === model.fullId; const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0); + const isPremium = !isFree; return (
- - {model.description || model.name || model.id} + + { model.name || model.description || model.id} {model.description && (

- {model.name || model.id} + {model.description || model.id}

)}
@@ -259,6 +266,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) Free )} + {isPremium && ( + + Premium + + )} {isSelected && (
@@ -268,12 +280,12 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
-
+
{model.pricing && ( - <> - Input: {formatPrice(model.pricing.prompt)} - Output: {formatPrice(model.pricing.completion)} - +
+
Input: {formatPrice(model.pricing.prompt)}
+
Output: {formatPrice(model.pricing.completion)}
+
)} {model.contextLength && ( Context: {model.contextLength.toLocaleString()} tokens @@ -285,9 +297,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) }) )}
- +
-
+
-
-

- "Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..." -

-
diff --git a/src/index.css b/src/index.css index 3fd0e105..b09c5aa2 100644 --- a/src/index.css +++ b/src/index.css @@ -260,6 +260,10 @@ padding-top: env(safe-area-inset-top); } + .bottom-safe-nav { + bottom: calc(env(safe-area-inset-bottom) + 3.75rem); + } + /* Mobile navigation button styles - text/icon highlighting only */ .mobile-nav-button, .mobile-nav-button:hover, From 0b269f78a406fd99b5393f8f439fac7c0a4faab6 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 23:11:22 -0500 Subject: [PATCH 017/105] Resolve from peerDependencies, then just fallback to the latest version --- src/lib/build/esmPlugin.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index 9651ae3b..cea8dba4 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -5,6 +5,7 @@ interface PackageLock { [key: string]: { name?: string; version: string; + peerDependencies?: { [key: string]: string }; } | undefined; }; } @@ -77,8 +78,9 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { // Handle transitive dependency versions const keys: string[] = []; + let importerPackage: string | undefined; try { - const importerPackage = extractPackageName(args.importer); + importerPackage = extractPackageName(args.importer); keys.push( `node_modules/${importerPackage}/node_modules/${packageName}`, ); @@ -97,12 +99,13 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { .find((info) => info); const packagePath = args.path.slice(packageName.length); - const version = packageInfo?.version; + const version = packageInfo?.version + || packageLock.packages[`node_modules/${importerPackage}`]?.peerDependencies?.[packageName]; - if (!version) return; - - const name = packageInfo.name ?? packageName; - const specifier = `${name}@${version}${packagePath}`; + const name = packageInfo?.name ?? packageName; + const specifier = version + ? `${name}@${version}${packagePath}` + : `${name}${packagePath}`; const url = new URL(`https://esm.sh/*${specifier}`); From 787877d2c750f1c280547144b960a5f5db7912b4 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 23:15:58 -0500 Subject: [PATCH 018/105] Handle `data:` URLs --- src/lib/build/fsPlugin.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index 7d35b0eb..cb53dd4e 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -8,6 +8,13 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { name: "fs", setup(build) { + build.onResolve({ filter: /^data:/ }, (args) => { + return { + path: args.path, + external: true, + }; + }); + build.onResolve({ filter: /.*/ }, async (args) => { let resolved: string; From f0223325955077cf12e5257f39ff0dfde79d2f61 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 27 Sep 2025 23:47:53 -0500 Subject: [PATCH 019/105] Add shakespeare.svg and ShakespeareLogo component --- index.html | 2 +- public/manifest.webmanifest | 4 +- public/{favicon.png => shakespeare.png} | Bin public/shakespeare.svg | 63 ++++++++++++++++++++++++ src/components/OnboardingDialog.tsx | 8 ++- src/components/ProjectSidebar.tsx | 8 +-- src/components/Shakespeare/ChatPane.tsx | 9 ++-- src/components/ShakespeareLogo.tsx | 13 +++++ src/pages/Index.tsx | 7 +-- 9 files changed, 89 insertions(+), 25 deletions(-) rename public/{favicon.png => shakespeare.png} (100%) create mode 100644 public/shakespeare.svg create mode 100644 src/components/ShakespeareLogo.tsx diff --git a/index.html b/index.html index 752478ff..61806719 100644 --- a/index.html +++ b/index.html @@ -9,7 +9,7 @@ - + diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest index f30b2c96..ed0d3952 100644 --- a/public/manifest.webmanifest +++ b/public/manifest.webmanifest @@ -8,12 +8,12 @@ "theme_color": "#000000", "icons": [ { - "src": "/favicon.png", + "src": "/shakespeare.png", "sizes": "192x192", "type": "image/png" }, { - "src": "/favicon.png", + "src": "/shakespeare.png", "sizes": "512x512", "type": "image/png" } diff --git a/public/favicon.png b/public/shakespeare.png similarity index 100% rename from public/favicon.png rename to public/shakespeare.png diff --git a/public/shakespeare.svg b/public/shakespeare.svg new file mode 100644 index 00000000..7eba08b6 --- /dev/null +++ b/public/shakespeare.svg @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index a38f07a8..e1d2ae0c 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -13,6 +13,8 @@ import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; import { useProviderModels } from '@/hooks/useProviderModels'; import { CreditsDialog } from '@/components/CreditsDialog'; +import { ShakespeareLogo } from '@/components/ShakespeareLogo'; + interface OnboardingDialogProps { open: boolean; onOpenChange: (open: boolean) => void; @@ -151,11 +153,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {step === 'welcome' && (
- Shakespeare +

diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 0cf0ae77..ec800bc0 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -9,10 +9,10 @@ import { useProjects } from '@/hooks/useProjects'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; - import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; +import { ShakespeareLogo } from '@/components/ShakespeareLogo'; interface ProjectItemProps { project: Project; @@ -137,11 +137,7 @@ export function ProjectSidebar({ onClick={() => navigateAndClose('/')} className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left" > - Shakespeare +

Shakespeare

diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 0a7cecd6..298e2ef6 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -41,6 +41,7 @@ import OpenAI from 'openai'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; import { Quilly } from '@/components/Quilly'; +import { ShakespeareLogo } from '@/components/ShakespeareLogo'; // Clean interfaces now handled by proper hooks @@ -185,7 +186,7 @@ export const ChatPane = forwardRef(({ artist: `Working on ${projectId}...`, artwork: [ { - src: '/favicon.png', + src: '/shakespeare.png', sizes: '512x512', type: 'image/png' } @@ -526,11 +527,7 @@ export const ChatPane = forwardRef(({
- Shakespeare +

diff --git a/src/components/ShakespeareLogo.tsx b/src/components/ShakespeareLogo.tsx new file mode 100644 index 00000000..44230c1a --- /dev/null +++ b/src/components/ShakespeareLogo.tsx @@ -0,0 +1,13 @@ +export interface ShakespeareLogoProps { + className?: string; +} + +export function ShakespeareLogo({ className }: ShakespeareLogoProps) { + return ( + Shakespeare + ); +} \ No newline at end of file diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 5e87f3cf..2803d804 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -21,6 +21,7 @@ import { ModelSelector } from '@/components/ModelSelector'; import { FileAttachment } from '@/components/ui/file-attachment'; import { Plus } from 'lucide-react'; import { useSeoMeta } from '@unhead/react'; +import { ShakespeareLogo } from '@/components/ShakespeareLogo'; export default function Index() { const { t } = useTranslation(); @@ -268,11 +269,7 @@ export default function Index() {
- Shakespeare +

{t('buildNostrApps')} From bb8912dd579da83f2971b1b13571be6ca69bcb09 Mon Sep 17 00:00:00 2001 From: sam Date: Sun, 28 Sep 2025 16:10:59 +0700 Subject: [PATCH 020/105] show git failure toasts indefinitely --- src/components/GitDialog.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index e53629ee..08f76ce4 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -335,6 +335,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog title: "Push to Nostr failed", description: errorMessage, variant: "destructive", + duration: Infinity, }); } finally { setIsPushingToNostr(false); @@ -396,6 +397,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog title: "Push failed", description: errorMessage, variant: "destructive", + duration: Infinity, }); } finally { setIsPushing(false); @@ -474,6 +476,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog title: "Pull failed", description: errorMessage, variant: "destructive", + duration: Infinity, }); } finally { setIsPulling(false); From d1d8f1dd15e51b2bcfe13e845dc02bf277ec7287 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 28 Sep 2025 10:16:22 -0500 Subject: [PATCH 021/105] Fix CSS relative imports --- src/lib/build/esmPlugin.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index cea8dba4..d41f50de 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -80,6 +80,10 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { const keys: string[] = []; let importerPackage: string | undefined; try { + const { pathname } = new URL(args.importer); + if (/\.css$/.test(pathname)) { + return; // CSS imports don't have external dependencies + } importerPackage = extractPackageName(args.importer); keys.push( `node_modules/${importerPackage}/node_modules/${packageName}`, From bdcaa2ef76010818328179c986f93a53b77aac4a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 28 Sep 2025 17:27:41 -0500 Subject: [PATCH 022/105] When a package imports itself, use the same version as the importer --- src/lib/build/esmPlugin.ts | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index d41f50de..1ac790c7 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -78,15 +78,18 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { // Handle transitive dependency versions const keys: string[] = []; - let importerPackage: string | undefined; + let importerPkg: string | undefined; + let importerVersion: string | undefined; try { const { pathname } = new URL(args.importer); if (/\.css$/.test(pathname)) { return; // CSS imports don't have external dependencies } - importerPackage = extractPackageName(args.importer); + const result = extractPackageName(args.importer); + importerPkg = result.pkg; + importerVersion = result.version; keys.push( - `node_modules/${importerPackage}/node_modules/${packageName}`, + `node_modules/${importerPkg}/node_modules/${packageName}`, ); } catch { // fallthrough @@ -103,8 +106,15 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { .find((info) => info); const packagePath = args.path.slice(packageName.length); - const version = packageInfo?.version - || packageLock.packages[`node_modules/${importerPackage}`]?.peerDependencies?.[packageName]; + + let version: string | undefined; + + if (importerPkg === packageName && importerVersion) { + version = importerVersion; + } else { + version = packageInfo?.version + || packageLock.packages[`node_modules/${importerPkg}`]?.peerDependencies?.[packageName]; + } const name = packageInfo?.name ?? packageName; const specifier = version @@ -197,7 +207,7 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { } /** Extract package name from esm.sh-style URL */ -function extractPackageName(esmShURL: string): string { +function extractPackageName(esmShURL: string): { pkg?: string; version?: string } { const full = new URL(esmShURL) .pathname .slice(1) @@ -207,7 +217,15 @@ function extractPackageName(esmShURL: string): string { ? full.split("/").slice(0, 2).join("/") : full.split("/")[0]; - return full.startsWith("@") + const pkg = full.startsWith("@") ? base.split("@").splice(0, 2).join("@") : base.split("@")[0]; + + let version: string | undefined; + + if (full.slice(pkg.length).startsWith("@")) { + version = full.slice(pkg.length + 1).split("/")[0]; + } + + return { pkg, version }; } From ba0ec1f4204b995a8f4ca1fb964362c1de747381 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 13:33:04 -0500 Subject: [PATCH 023/105] Add Open Source section to OnboardingDialog --- src/components/OnboardingDialog.tsx | 100 ++++++++++++++++++++++++++-- 1 file changed, 96 insertions(+), 4 deletions(-) diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index e1d2ae0c..9a754a76 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -8,6 +8,7 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; +import { Checkbox } from '@/components/ui/checkbox'; import { useAISettings } from '@/hooks/useAISettings'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; @@ -20,7 +21,7 @@ interface OnboardingDialogProps { onOpenChange: (open: boolean) => void; } -type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion'; +type OnboardingStep = 'welcome' | 'open-source' | 'model-selection' | 'conclusion'; const SHAKESPEARE_PROVIDER = { id: "shakespeare", @@ -33,6 +34,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) const [selectedModel, setSelectedModel] = useState(''); const [isSettingUp, setIsSettingUp] = useState(false); const [showCreditsDialog, setShowCreditsDialog] = useState(false); + const [agreedToTerms, setAgreedToTerms] = useState(false); const { setProvider, addRecentlyUsedModel } = useAISettings(); const { user } = useCurrentUser(); @@ -42,7 +44,13 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) // Filter models to only show Shakespeare provider models const shakespeareModels = models.filter(model => model.provider === 'shakespeare'); - const handleGetStarted = async () => { + const handleGetStarted = () => { + setStep('open-source'); + }; + + const handleContinueFromOpenSource = async () => { + if (!agreedToTerms) return; + setIsSettingUp(true); try { @@ -114,16 +122,17 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) setSelectedModel(''); setIsSettingUp(false); setShowCreditsDialog(false); + setAgreedToTerms(false); } }, [open]); return ( <> - + - {step === 'model-selection' && ( + {step === 'open-source' && ( )} + {step === 'model-selection' && ( + + )} {step === 'conclusion' && ( +

+
+ )} + {step === 'model-selection' && (
From 92483728d0d0a8925a17719b5f53bfee6dd583a2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 13:37:45 -0500 Subject: [PATCH 024/105] Scroll OnboardingDialog to top when navigating between steps --- src/components/OnboardingDialog.tsx | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 9a754a76..14c6834c 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -1,5 +1,5 @@ import { Decimal } from 'decimal.js'; -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { generateSecretKey } from 'nostr-tools'; import { nip19 } from 'nostr-tools'; import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react'; @@ -36,6 +36,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) const [showCreditsDialog, setShowCreditsDialog] = useState(false); const [agreedToTerms, setAgreedToTerms] = useState(false); + // Ref for the scrollable content area + const scrollableContentRef = useRef(null); + const { setProvider, addRecentlyUsedModel } = useAISettings(); const { user } = useCurrentUser(); const login = useLoginActions(); @@ -126,10 +129,17 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) } }, [open]); + // Scroll to top when step changes + useEffect(() => { + if (scrollableContentRef.current) { + scrollableContentRef.current.scrollTop = 0; + } + }, [step]); + return ( <> - + {step === 'open-source' && ( @@ -168,7 +178,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) -
+
{step === 'welcome' && (
From 2477b5417cd4c55ba10023b0bd0939b6780dc4ee Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 14:48:44 -0500 Subject: [PATCH 025/105] Add provider step to onboarding --- src/components/OnboardingDialog.tsx | 211 +++++++++++++++++++++++----- src/lib/aiProviderPresets.test.ts | 62 ++++++++ src/lib/aiProviderPresets.ts | 72 ++++++++++ src/pages/AISettings.tsx | 64 +-------- 4 files changed, 310 insertions(+), 99 deletions(-) create mode 100644 src/lib/aiProviderPresets.test.ts create mode 100644 src/lib/aiProviderPresets.ts diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 14c6834c..cc8db615 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -2,35 +2,34 @@ import { Decimal } from 'decimal.js'; import { useState, useEffect, useRef } from 'react'; import { generateSecretKey } from 'nostr-tools'; import { nip19 } from 'nostr-tools'; -import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react'; +import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } from 'lucide-react'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; import { Checkbox } from '@/components/ui/checkbox'; +import { PasswordInput } from '@/components/ui/password-input'; import { useAISettings } from '@/hooks/useAISettings'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; import { useProviderModels } from '@/hooks/useProviderModels'; import { CreditsDialog } from '@/components/CreditsDialog'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; +import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets'; +import { cn } from '@/lib/utils'; interface OnboardingDialogProps { open: boolean; onOpenChange: (open: boolean) => void; } -type OnboardingStep = 'welcome' | 'open-source' | 'model-selection' | 'conclusion'; - -const SHAKESPEARE_PROVIDER = { - id: "shakespeare", - baseURL: "https://ai.shakespeare.diy/v1", - nostr: true, -}; +type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'model-selection' | 'conclusion'; export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) { const [step, setStep] = useState('welcome'); + const [selectedProvider, setSelectedProvider] = useState(null); + const [providerApiKey, setProviderApiKey] = useState(''); const [selectedModel, setSelectedModel] = useState(''); const [isSettingUp, setIsSettingUp] = useState(false); const [showCreditsDialog, setShowCreditsDialog] = useState(false); @@ -44,28 +43,51 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) const login = useLoginActions(); const { models, isLoading: isLoadingModels } = useProviderModels(); - // Filter models to only show Shakespeare provider models - const shakespeareModels = models.filter(model => model.provider === 'shakespeare'); + // Filter models to only show selected provider models + const providerModels = selectedProvider + ? models.filter(model => model.provider === selectedProvider.id) + : []; const handleGetStarted = () => { setStep('open-source'); }; - const handleContinueFromOpenSource = async () => { + const handleContinueFromOpenSource = () => { if (!agreedToTerms) return; + setStep('provider-selection'); + }; + + const handleProviderSelect = (provider: PresetProvider) => { + setSelectedProvider(provider); + // Clear API key when switching providers + setProviderApiKey(''); + }; + + const handleContinueFromProviderSelection = async () => { + if (!selectedProvider) return; + + // Check if provider requires API key and if it's provided + const requiresApiKey = selectedProvider.apiKeysURL && !selectedProvider.nostr; + if (requiresApiKey && !providerApiKey.trim()) return; setIsSettingUp(true); try { - // If user is not logged in, generate and login with secret key - if (!user) { + // If user is not logged in and provider uses Nostr auth, generate and login with secret key + if (!user && selectedProvider.nostr) { const secretKey = generateSecretKey(); const nsec = nip19.nsecEncode(secretKey); login.nsec(nsec); } - // Add Shakespeare provider to their config - setProvider(SHAKESPEARE_PROVIDER); + // Add selected provider to their config + const providerConfig = { + id: selectedProvider.id, + baseURL: selectedProvider.baseURL, + nostr: selectedProvider.nostr || undefined, + apiKey: requiresApiKey ? providerApiKey.trim() : undefined, + }; + setProvider(providerConfig); // Move to model selection setStep('model-selection'); @@ -87,7 +109,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) addRecentlyUsedModel(selectedModel); // Find the selected model to check if it's free - const model = shakespeareModels.find(m => m.fullId === selectedModel); + const model = providerModels.find(m => m.fullId === selectedModel); const isFreeModel = !model?.pricing || ( model.pricing.prompt.equals(0) && model.pricing.completion.equals(0) ); @@ -122,6 +144,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) useEffect(() => { if (open) { setStep('welcome'); + setSelectedProvider(null); + setProviderApiKey(''); setSelectedModel(''); setIsSettingUp(false); setShowCreditsDialog(false); @@ -152,7 +176,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) )} - {step === 'model-selection' && ( + {step === 'provider-selection' && ( )} + {step === 'model-selection' && ( + + )} {step === 'conclusion' && ( +
+
+ )} + + {step === 'provider-selection' && ( +
+
+

Choose your AI provider

+

+ Select an AI provider to power your development assistant. You can add more providers later in settings. +

+
+ +
+ {AI_PROVIDER_PRESETS.map((provider) => { + const isSelected = selectedProvider?.id === provider.id; + const isShakespeare = provider.id === 'shakespeare'; + + return ( + handleProviderSelect(provider)} + > +
+
+ + {provider.name} + +
+
+ {isSelected && ( +
+ +
+ )} +
+
+
+ ); + })} +
+ + {/* API Key Input Section */} + {selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && ( +
+
+

+ {selectedProvider.id === 'routstr' ? 'Enter Cashu Token' : 'Enter API Key'} +

+

+ {selectedProvider.id === 'routstr' ? ( + <>{selectedProvider.name} requires a Cashu token + ) : ( + <> + {selectedProvider.name} requires an {selectedProvider.apiKeysURL ? ( + + API key + + + ) : ( + <>API key + )} + + )} +

+
+ setProviderApiKey(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && providerApiKey.trim()) { + handleContinueFromProviderSelection(); + } + }} + /> +
+ )} + +
+
-
+
) : ( -
- {!preset.nostr && ( - setPresetApiKeys(prev => ({ +
+
+ {!preset.nostr && ( + setPresetApiKeys(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && + presetApiKeys[preset.id]?.trim() && + presetTermsAgreements[preset.id]) { + handleAddPresetProvider(preset); + } + }} + /> + )} + +
+ + {/* Terms of Service Agreement */} +
+ setPresetTermsAgreements(prev => ({ ...prev, - [preset.id]: e.target.value, + [preset.id]: checked === true, }))} - onKeyDown={(e) => { - if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) { - handleAddPresetProvider(preset); - } - }} + className="h-3 w-3" /> - )} - + +
)}
From cb4cc16760348f242723f133e431e4dd5a2af376 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 15:41:57 -0500 Subject: [PATCH 029/105] Don't configure users through the Act1Dialog, still force them to go through the normal onboarding flow --- src/components/Act1Dialog.tsx | 70 ++++++++++------------------------- 1 file changed, 20 insertions(+), 50 deletions(-) diff --git a/src/components/Act1Dialog.tsx b/src/components/Act1Dialog.tsx index 5cdeade2..e31611b7 100644 --- a/src/components/Act1Dialog.tsx +++ b/src/components/Act1Dialog.tsx @@ -5,9 +5,9 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; -import { useAISettings } from '@/hooks/useAISettings'; +// import { useAISettings } from '@/hooks/useAISettings'; import { useAICredits } from '@/hooks/useAICredits'; -import { useLocalStorage } from '@/hooks/useLocalStorage'; +// import { useLocalStorage } from '@/hooks/useLocalStorage'; interface Act1DialogProps { open: boolean; @@ -22,44 +22,39 @@ const SHAKESPEARE_PROVIDER = { nostr: true, }; -const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack'; +// const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack'; export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { const [step, setStep] = useState('welcome'); - const [isSettingUp, setIsSettingUp] = useState(false); - const { setProvider, updateSettings } = useAISettings(); + // const { setProvider, updateSettings } = useAISettings(); - // Get the selectedNSPAddr from localStorage - const [selectedNSPAddr] = useLocalStorage('selectedNSPAddr', null); + // // Get the selectedNSPAddr from localStorage + // const [selectedNSPAddr] = useLocalStorage('selectedNSPAddr', null); // Get user's credits const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER); const handleGetStarted = async () => { - setIsSettingUp(true); - try { - // Add Shakespeare provider to their config - setProvider(SHAKESPEARE_PROVIDER); + // // Add Shakespeare provider to their config + // setProvider(SHAKESPEARE_PROVIDER); - // Configure recently used models based on credits or NSP - const hasCredits = creditsData?.amount && creditsData.amount > 0; - const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR; + // // Configure recently used models based on credits or NSP + // const hasCredits = creditsData?.amount && creditsData.amount > 0; + // const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR; - if (hasCredits || hasMKStackNSP) { - // User has credits or MKStack NSP - set to shakespeare model - updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] }); - } else { - // No credits - set to tybalt model (free) - updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] }); - } + // if (hasCredits || hasMKStackNSP) { + // // User has credits or MKStack NSP - set to shakespeare model + // updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] }); + // } else { + // // No credits - set to tybalt model (free) + // updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] }); + // } // Move to migration step setStep('migration'); } catch (error) { console.error('Failed to configure Shakespeare provider:', error); - } finally { - setIsSettingUp(false); } }; @@ -87,7 +82,6 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { useEffect(() => { if (open) { setStep('welcome'); - setIsSettingUp(false); } }, [open]); @@ -126,12 +120,6 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { )} - - {step === 'welcome' && 'Welcome to Shakespeare: Act 2! 🎭'} - {step === 'migration' && 'Migrating Your Projects'} - {step === 'credits' && 'Your Credits'} - {step === 'conclusion' && "You're All Set!"} - @@ -197,21 +185,10 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
)} @@ -343,14 +320,7 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {

Welcome to the Future!

- You're all set up with Act 2! Your AI assistant is configured - and ready to help you build amazing Nostr applications. -

-
- -
-

- "Create a decentralized social media app with custom feeds and real-time messaging..." + You're all up to speed with Act 2! Get ready to build amazing Nostr applications.

From 7b438bae347f49b56878761df4827e5377ef0527 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:00:43 -0500 Subject: [PATCH 030/105] Display credits badge in Onboarding if the user is coming from Act1 --- .../OnboardingCreditsBadge.test.tsx | 103 ++++++++++++++++++ src/components/OnboardingCreditsBadge.tsx | 42 +++++++ src/components/OnboardingDialog.tsx | 6 +- src/hooks/useAICredits.ts | 2 +- 4 files changed, 151 insertions(+), 2 deletions(-) create mode 100644 src/components/OnboardingCreditsBadge.test.tsx create mode 100644 src/components/OnboardingCreditsBadge.tsx diff --git a/src/components/OnboardingCreditsBadge.test.tsx b/src/components/OnboardingCreditsBadge.test.tsx new file mode 100644 index 00000000..9fcff5a8 --- /dev/null +++ b/src/components/OnboardingCreditsBadge.test.tsx @@ -0,0 +1,103 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { TestApp } from '@/test/TestApp'; +import { OnboardingCreditsBadge } from './OnboardingCreditsBadge'; +import type { UseQueryResult } from '@tanstack/react-query'; +import type { CreditsResponse } from '@/hooks/useAICredits'; + +// Mock the useAICredits hook +vi.mock('@/hooks/useAICredits', () => ({ + useAICredits: vi.fn(), +})); + +import { useAICredits } from '@/hooks/useAICredits'; + +const mockUseAICredits = vi.mocked(useAICredits); + +describe('OnboardingCreditsBadge', () => { + const mockProvider = { + id: 'shakespeare', + baseURL: 'https://ai.shakespeare.diy/v1', + nostr: true, + }; + + it('renders credits badge when data is available', () => { + mockUseAICredits.mockReturnValue({ + data: { object: 'credits', amount: 25.50 }, + isLoading: false, + error: null, + } as UseQueryResult); + + render( + + + + ); + + expect(screen.getByText('$25.50')).toBeInTheDocument(); + }); + + it('does not render when loading', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: true, + error: null, + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('does not render when there is an error', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: false, + error: new Error('Provider does not support credits'), + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('does not render when no credits data is available', () => { + mockUseAICredits.mockReturnValue({ + data: undefined, + isLoading: false, + error: null, + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('does not render when credits amount is 0', () => { + mockUseAICredits.mockReturnValue({ + data: { object: 'credits', amount: 0 }, + isLoading: false, + error: null, + } as UseQueryResult); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); +}); \ No newline at end of file diff --git a/src/components/OnboardingCreditsBadge.tsx b/src/components/OnboardingCreditsBadge.tsx new file mode 100644 index 00000000..f2eaae42 --- /dev/null +++ b/src/components/OnboardingCreditsBadge.tsx @@ -0,0 +1,42 @@ +import { Badge } from '@/components/ui/badge'; +import { AIProvider } from '@/contexts/AISettingsContext'; +import { useAICredits } from '@/hooks/useAICredits'; + +interface OnboardingCreditsBadgeProps { + provider: AIProvider; + className?: string; +} + +/** + * Displays a non-clickable credits badge for onboarding showing the remaining credits for an AI provider + */ +export function OnboardingCreditsBadge({ provider, className }: OnboardingCreditsBadgeProps) { + 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) { + return null; + } + + // Don't render if no credits data is available or if amount is 0 + if (!credits || credits.amount === 0) { + return null; + } + + // Format the amount as currency + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }).format(credits.amount); + + return ( + + {formattedAmount} + + ); +} \ No newline at end of file diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index fb693003..f7f72df4 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -15,6 +15,7 @@ import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; import { useProviderModels } from '@/hooks/useProviderModels'; import { CreditsDialog } from '@/components/CreditsDialog'; +import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets'; import { cn } from '@/lib/utils'; @@ -359,11 +360,14 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) >
- + {provider.name}
+ {isSelected && (
diff --git a/src/hooks/useAICredits.ts b/src/hooks/useAICredits.ts index 8652e772..6091283f 100644 --- a/src/hooks/useAICredits.ts +++ b/src/hooks/useAICredits.ts @@ -36,6 +36,6 @@ export function useAICredits(provider: AIProvider) { 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, + enabled: !!provider.nostr && !!user, }); } \ No newline at end of file From 3e8d5fb87c8882626d3a48e18eb3026d77715ee8 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:06:12 -0500 Subject: [PATCH 031/105] Fix tiny checkboxes on AI Settings page --- src/pages/AISettings.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index d4cc53ec..7519fabf 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -412,7 +412,7 @@ export function AISettings() { ...prev, [preset.id]: checked === true, }))} - className="h-3 w-3" + className="size-3 [&_svg]:size-3" />
-

Quality of output depends on models used and is not guaranteed

+

Quality of output depends on quality of input and models used and is not guaranteed

From 24c8525360b9f8ae589421c3c979ab4f911e6033 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:20:36 -0500 Subject: [PATCH 033/105] Fix OnboardingDialog height, remove scrollbar customizations, add comma --- src/components/OnboardingDialog.tsx | 4 ++-- src/index.css | 19 ------------------- 2 files changed, 2 insertions(+), 21 deletions(-) diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 38a0f09d..3a62b183 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -171,7 +171,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) return ( <> - + {step === 'open-source' && ( @@ -297,7 +297,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
-

Quality of output depends on quality of input and models used and is not guaranteed

+

Quality of output depends on quality of input and models used, and is not guaranteed

diff --git a/src/index.css b/src/index.css index b09c5aa2..b98d00b9 100644 --- a/src/index.css +++ b/src/index.css @@ -120,25 +120,6 @@ font-feature-settings: "rlig" 1, "calt" 1; } - /* GitHub-style scrollbars */ - ::-webkit-scrollbar { - width: 8px; - height: 8px; - } - - ::-webkit-scrollbar-track { - background: transparent; - } - - ::-webkit-scrollbar-thumb { - background: hsl(var(--border)); - border-radius: 4px; - } - - ::-webkit-scrollbar-thumb:hover { - background: hsl(var(--muted-foreground) / 0.5); - } - /* GitHub-style focus rings */ .focus-ring:focus-visible { outline: none; From 1abc37f38867a02e5acda1798ec883d0a5ebdd23 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:29:58 -0500 Subject: [PATCH 034/105] Actually, bring back the custom scrollbars --- src/index.css | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/index.css b/src/index.css index b98d00b9..b09c5aa2 100644 --- a/src/index.css +++ b/src/index.css @@ -120,6 +120,25 @@ font-feature-settings: "rlig" 1, "calt" 1; } + /* GitHub-style scrollbars */ + ::-webkit-scrollbar { + width: 8px; + height: 8px; + } + + ::-webkit-scrollbar-track { + background: transparent; + } + + ::-webkit-scrollbar-thumb { + background: hsl(var(--border)); + border-radius: 4px; + } + + ::-webkit-scrollbar-thumb:hover { + background: hsl(var(--muted-foreground) / 0.5); + } + /* GitHub-style focus rings */ .focus-ring:focus-visible { outline: none; From 75cab68281c3a2944162fb047d6f17e46a646e48 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:48:35 -0500 Subject: [PATCH 035/105] Clean up directory if cloning fails --- src/lib/ProjectsManager.test.ts | 62 +++++++++++++++++++++++++++++++++ src/lib/ProjectsManager.ts | 62 ++++++++++++++++++++------------- 2 files changed, 99 insertions(+), 25 deletions(-) diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index f823c200..b7239ad5 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -440,6 +440,68 @@ describe('ProjectsManager', () => { }); }); + describe('cloneProject', () => { + it('should clean up project directory when clone fails', async () => { + await projectsManager.init(); + + // Mock git.clone to fail + const mockGit = { + clone: vi.fn().mockRejectedValue(new Error('Clone failed')), + } as Partial; + + // Replace git instance + Object.assign(projectsManager, { git: mockGit }); + + // Attempt to clone a project + await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git')) + .rejects.toThrow('Clone failed'); + + // Verify that the project directory was cleaned up + const project = await projectsManager.getProject('test-project'); + expect(project).toBeNull(); + + // Verify directory doesn't exist in filesystem + await expect(fs.stat('/projects/test-project')).rejects.toThrow('ENOENT'); + }); + + it('should handle cleanup errors gracefully', async () => { + await projectsManager.init(); + + // Mock git.clone to fail + const mockGit = { + clone: vi.fn().mockRejectedValue(new Error('Clone failed')), + } as Partial; + + // Replace git instance + Object.assign(projectsManager, { git: mockGit }); + + // Spy on console.warn to check for cleanup warnings + const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + // Mock deleteDirectory to also fail (simulate cleanup error) + type ProjectsManagerWithPrivate = ProjectsManager & { deleteDirectory: (path: string) => Promise }; + const originalDeleteDirectory = (projectsManager as ProjectsManagerWithPrivate).deleteDirectory; + (projectsManager as ProjectsManagerWithPrivate).deleteDirectory = vi.fn().mockRejectedValue(new Error('Cleanup failed')); + + try { + // Attempt to clone a project + await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git')) + .rejects.toThrow('Clone failed'); + + // Should have logged a cleanup warning + expect(consoleSpy).toHaveBeenCalledWith( + 'Failed to clean up directory after clone failure:', + expect.any(Error) + ); + + } finally { + // Restore mocks + consoleSpy.mockRestore(); + (projectsManager as ProjectsManagerWithPrivate).deleteDirectory = originalDeleteDirectory; + } + }); + }); + describe('renameProject', () => { it('should rename a project directory', async () => { await projectsManager.init(); diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 486d4207..11b57787 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -290,33 +290,45 @@ export class ProjectsManager { await this.fs.mkdir(projectPath); - // Clone the repository (Git class now handles Nostr URIs automatically) - await this.git.clone({ - dir: projectPath, - url: repoUrl, - singleBranch: true, - depth: options?.depth, // Use depth if provided, otherwise clone full history - }); - - // Get filesystem stats for timestamps - const stats = await this.fs.stat(projectPath); - const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); - - // Automatically request persistent storage after project cloning try { - await ensurePersistentStorage(); - } catch (error) { - // Don't fail project cloning if persistent storage request fails - console.warn('Failed to request persistent storage after project cloning:', error); - } + // Clone the repository (Git class now handles Nostr URIs automatically) + await this.git.clone({ + dir: projectPath, + url: repoUrl, + singleBranch: true, + depth: options?.depth, // Use depth if provided, otherwise clone full history + }); - // Return the full project object with dynamically generated properties - return { - id, - name: this.formatProjectName(id), // Use formatted directory name - path: projectPath, - lastModified: timestamp, - }; + // Get filesystem stats for timestamps + const stats = await this.fs.stat(projectPath); + const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); + + // Automatically request persistent storage after project cloning + try { + await ensurePersistentStorage(); + } catch (error) { + // Don't fail project cloning if persistent storage request fails + console.warn('Failed to request persistent storage after project cloning:', error); + } + + // Return the full project object with dynamically generated properties + return { + id, + name: this.formatProjectName(id), // Use formatted directory name + path: projectPath, + lastModified: timestamp, + }; + } catch (error) { + // Clean up the directory that was created if cloning fails + try { + await this.deleteDirectory(projectPath); + } catch (cleanupError) { + // Log cleanup error but don't mask the original clone error + console.warn('Failed to clean up directory after clone failure:', cleanupError); + } + // Re-throw the original clone error + throw error; + } } async getProjects(): Promise { From a87063f6e9867e34e1945463af33a2ecb6cf8179 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 16:55:28 -0500 Subject: [PATCH 036/105] Fix types in test --- src/lib/ProjectsManager.test.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index b7239ad5..5e43cf2a 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -478,10 +478,9 @@ describe('ProjectsManager', () => { // Spy on console.warn to check for cleanup warnings const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); - // Mock deleteDirectory to also fail (simulate cleanup error) - type ProjectsManagerWithPrivate = ProjectsManager & { deleteDirectory: (path: string) => Promise }; - const originalDeleteDirectory = (projectsManager as ProjectsManagerWithPrivate).deleteDirectory; - (projectsManager as ProjectsManagerWithPrivate).deleteDirectory = vi.fn().mockRejectedValue(new Error('Cleanup failed')); + // Mock fs.rmdir to fail (simulate cleanup error) + const originalRmdir = fs.rmdir; + fs.rmdir = vi.fn().mockRejectedValue(new Error('Cleanup failed')); try { // Attempt to clone a project @@ -497,7 +496,7 @@ describe('ProjectsManager', () => { } finally { // Restore mocks consoleSpy.mockRestore(); - (projectsManager as ProjectsManagerWithPrivate).deleteDirectory = originalDeleteDirectory; + fs.rmdir = originalRmdir; } }); }); From 3da2075539cb4e6e1ccb9045432e7d4330171959 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 17:01:30 -0500 Subject: [PATCH 037/105] Ensure console errors get passed to Quilly on desktop --- src/pages/ProjectView.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index f73f3a3b..4b5d926b 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -409,6 +409,8 @@ export function ProjectView() { onLoadingChange={handleAILoadingChange} isLoading={isAILoading} isBuildLoading={build.isPending} + consoleError={consoleError} + onDismissConsoleError={handleDismissConsoleError} /> ) : (
From 795eaa50c2cdb3026c4865e8ddd4511422a55440 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 17:19:02 -0500 Subject: [PATCH 038/105] Make Quilly's "fix error" add assistant messages --- src/components/AIMessageItem.tsx | 7 +++++- src/components/Shakespeare/ChatPane.tsx | 31 ++++++++++++++++++++++--- src/lib/SessionManager.ts | 4 ---- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index f850d900..2287ac82 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -1,6 +1,6 @@ import { memo, useState } from 'react'; import { Streamdown } from 'streamdown'; -import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2 } from 'lucide-react'; +import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs } from 'lucide-react'; import type { AIMessage } from '@/lib/SessionManager'; import { cn } from '@/lib/utils'; import { UserMessage } from '@/components/UserMessage'; @@ -150,6 +150,11 @@ export const AIMessageItem = memo(({ icon: CheckCircle, title: 'TypeScript' }; + case 'read_console_messages': + return { + icon: Logs, + title: 'Read Console' + }; default: return { icon: Wrench, diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 02721a19..913011ad 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -203,6 +203,7 @@ export const ChatPane = forwardRef(({ isLoading: internalIsLoading, totalCost, lastInputTokens, + addMessage, sendMessage, startGeneration, stopGeneration, @@ -216,9 +217,33 @@ export const ChatPane = forwardRef(({ }); // Handle console error help requests - const handleConsoleErrorHelp = useCallback(() => { - sendMessage('Read the console messages and fix any errors present.', providerModel); - }, [sendMessage, providerModel]); + const handleConsoleErrorHelp = useCallback(async () => { + const tool = new ReadConsoleMessagesTool(); + const toolCallId = `call_${crypto.randomUUID().replace(/-/g, '')}`; + + await addMessage({ + role: 'assistant', + content: 'Let me take a look at the console messages to help diagnose the issue.', + tool_calls: [ + { + id: toolCallId, + type: 'function', + function: { + name: 'read_console_messages', + arguments: '{}', + } + } + ] + }); + + await addMessage({ + role: 'tool', + content: await tool.execute({ filter: 'error' }), + tool_call_id: toolCallId, + }); + + await startGeneration(providerModel); + }, [addMessage, providerModel, startGeneration]); // Handle error dismissal const handleErrorDismiss = useCallback(() => { diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index fde41dd3..22f416c1 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -188,10 +188,6 @@ export class SessionManager { throw new Error('No messages in session'); } - // Check if last message is from user - const lastMessage = session.messages[session.messages.length - 1]; - if (lastMessage.role !== 'user') return; - session.isLoading = true; session.abortController = new AbortController(); session.lastActivity = new Date(); From 5fa16115fd4a6bcfc1e84136873976ab02f9ffd2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 17:51:25 -0500 Subject: [PATCH 039/105] Rebuild project after saving file Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/53 --- src/components/Shakespeare/PreviewPane.tsx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 03783f08..751e87e9 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -497,6 +497,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o try { await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content); setFileContent(content); + + // Automatically trigger a rebuild after saving a file + if (isPreviewable) { + console.log('File saved, triggering rebuild...'); + handleBuildProject(); + } } catch (error) { console.error('Failed to save file:', error); } From b04c1440b5a12081cd6325efe0d940a62c3b6d3c Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 29 Sep 2025 18:01:49 -0500 Subject: [PATCH 040/105] Improve display of buttons --- src/components/Shakespeare/PreviewPane.tsx | 2 +- src/components/ui/button-variants.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 751e87e9..959c9eaa 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -532,7 +532,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o -
+ +
+ setCustomValue(e.target.value)} + onKeyDown={handleCustomKeyDown} + onBlur={handleCustomSubmit} + placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)" + className="h-8 text-xs" + autoFocus + /> + +
+
); } return ( - - - - + +
+ {isCurrentModelFree && ( + + + + + +

You are using a free model. For better results, switch to a premium model.

+
+
+ )} + + + + {(isConfigured && models.length >= 5) && ( @@ -289,5 +378,7 @@ export function ModelSelector({ +
+
); } \ No newline at end of file From cb794b5719fbc98839731a2dbc4a2b2936dbd6e4 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 1 Oct 2025 17:08:31 -0500 Subject: [PATCH 058/105] We do a little discord coding --- src/components/ModelSelector.tsx | 236 ++++++++++++------------ src/components/Shakespeare/ChatPane.tsx | 1 - 2 files changed, 118 insertions(+), 119 deletions(-) diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index 76257bba..2e674c00 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -189,7 +189,7 @@ export function ModelSelector({ return ( -
+
{isCurrentModelFree && ( - - - {(isConfigured && models.length >= 5) && ( - - )} - - -
-

{t('noModelsFound')}

-

{t('tryCustomModel')}

-
-
- - {shouldShowRecentlyUsed && ( - - {recentlyUsedModels.map((model) => ( - handleSelect(model)} - className="cursor-pointer" - > - - {model} - - ))} - - )} - - {shouldShowRecentlyUsed && } - - {/* Loading state */} - {isLoading && ( - -
-
- - - + + + {(isConfigured && models.length >= 5) && ( + + )} + + +
+

{t('noModelsFound')}

+

{t('tryCustomModel')}

-
- - )} + - {/* Error state */} - {error && !isLoading && ( - -
-
- -
-

{error}

- -
-
-
-
- )} + + {model} + + ))} + + )} - {/* Provider models */} - {!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => ( -
+ {shouldShowRecentlyUsed && } + + {/* Loading state */} + {isLoading && ( + +
+
+ + + +
+
+
+ )} + + {/* Error state */} + {error && !isLoading && ( + +
+
+ +
+

{error}

+ +
+
+
+
+ )} + + {/* Provider models */} + {!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => ( +
+ + + {providerModels.map((model) => ( + handleSelect(model.fullId)} + className="cursor-pointer" + > + + {model.fullId} + + ))} + +
+ ))} + + {/* Custom model option and manage providers - moved to bottom */} - - {providerModels.map((model) => ( + + {isConfigured && ( handleSelect(model.fullId)} + value="__custom_model_option__" + onSelect={() => handleSelect('__custom__')} className="cursor-pointer" > - - {model.fullId} + + {t('enterCustomModel')} - ))} + )} + handleSelect('__manage_providers__')} + className="cursor-pointer" + > + + {t('manageProviders')} + -
- ))} - - {/* Custom model option and manage providers - moved to bottom */} - - - {isConfigured && ( - handleSelect('__custom__')} - className="cursor-pointer" - > - - {t('enterCustomModel')} - - )} - handleSelect('__manage_providers__')} - className="cursor-pointer" - > - - {t('manageProviders')} - - - - - - + + + +
); diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index d6d740f4..e8626112 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -763,7 +763,6 @@ export const ChatPane = forwardRef(({ Date: Wed, 1 Oct 2025 17:13:23 -0500 Subject: [PATCH 059/105] Fix ModelSelector test --- src/components/ModelSelector.test.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/components/ModelSelector.test.tsx b/src/components/ModelSelector.test.tsx index 56d15fb9..ca350262 100644 --- a/src/components/ModelSelector.test.tsx +++ b/src/components/ModelSelector.test.tsx @@ -384,7 +384,7 @@ describe('ModelSelector', () => { // Wait for tooltip to appear await waitFor(() => { - expect(screen.getAllByText('You are using a free model. For better results, switch to a premium model.').length).toBeGreaterThan(0); + expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0); }); }); @@ -424,7 +424,7 @@ describe('ModelSelector', () => { // Tooltip should appear await waitFor(() => { - expect(screen.getAllByText('You are using a free model. For better results, switch to a premium model.').length).toBeGreaterThan(0); + expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0); }); // The button should still be clickable (no errors) From 3fba26ddb7e5ddff3c8f2d6a4cc761651b858fa6 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 1 Oct 2025 17:24:22 -0500 Subject: [PATCH 060/105] Switch payment method to a tabbed UI instead of dropdown --- src/components/CreditsDialog.tsx | 35 +++++++++++++------------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 4b33517c..8b4de085 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -9,7 +9,7 @@ import { Label } from '@/components/ui/label'; import { Badge } from '@/components/ui/badge'; import { Separator } from '@/components/ui/separator'; import { Skeleton } from '@/components/ui/skeleton'; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { useToast } from '@/hooks/useToast'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; @@ -464,26 +464,19 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
- - + + setPaymentMethod(value)} className="w-full"> + + + + Credit Card + + + + Lightning + + +
@@ -555,7 +574,21 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o

Messages from your project will appear here

) : ( - consoleMessages.map((msg, index) => ( + <> + {/* Clear button when messages exist */} + {messageCount > 0 && ( +
+ +
+ )} + {messages.map((msg, index) => (
- )) + ))} + )}
diff --git a/src/contexts/ConsoleErrorContext.ts b/src/contexts/ConsoleErrorContext.ts new file mode 100644 index 00000000..ed576ce4 --- /dev/null +++ b/src/contexts/ConsoleErrorContext.ts @@ -0,0 +1,11 @@ +import { createContext } from 'react'; +import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; + +export interface ConsoleErrorContextValue { + hasErrors: boolean; + consoleError: ProjectPreviewConsoleError | null; + clearErrors: () => void; + dismissConsoleError: () => void; +} + +export const ConsoleErrorContext = createContext(undefined); \ No newline at end of file diff --git a/src/hooks/useConsoleError.test.ts b/src/hooks/useConsoleError.test.ts new file mode 100644 index 00000000..d1560f5e --- /dev/null +++ b/src/hooks/useConsoleError.test.ts @@ -0,0 +1,12 @@ +import { describe, it, expect } from 'vitest'; +import { renderHook } from '@testing-library/react'; +import { useConsoleError } from './useConsoleError'; + +describe('useConsoleError', () => { + it('should throw error when used outside ConsoleErrorProvider', () => { + // Expect the hook to throw when not wrapped in provider + expect(() => { + renderHook(() => useConsoleError()); + }).toThrow('useConsoleError must be used within a ConsoleErrorProvider'); + }); +}); \ No newline at end of file diff --git a/src/hooks/useConsoleError.ts b/src/hooks/useConsoleError.ts new file mode 100644 index 00000000..12141dbc --- /dev/null +++ b/src/hooks/useConsoleError.ts @@ -0,0 +1,16 @@ +import { useContext } from 'react'; +import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext'; + +/** + * Hook to access console error state from the ConsoleErrorProvider. + * Provides boolean error state and console error information for Quilly. + */ +export function useConsoleError() { + const context = useContext(ConsoleErrorContext); + + if (context === undefined) { + throw new Error('useConsoleError must be used within a ConsoleErrorProvider'); + } + + return context; +} \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.test.ts b/src/lib/tools/ReadConsoleMessagesTool.test.ts index 1b2647ef..d31c11f0 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.test.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.test.ts @@ -4,8 +4,9 @@ import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError, - addErrorListener, - removeErrorListener + addErrorStateListener, + removeErrorStateListener, + getHasConsoleErrors } from './ReadConsoleMessagesTool'; describe('ReadConsoleMessagesTool', () => { @@ -80,58 +81,83 @@ describe('ProjectPreviewConsoleError', () => { }); }); -describe('Console Error Listeners', () => { +describe('Console Error State Management', () => { beforeEach(() => { clearConsoleMessages(); }); - it('should trigger error listener when console error is added', async () => { - const errorListener = vi.fn(); - addErrorListener(errorListener); + it('should track error state with boolean', () => { + expect(getHasConsoleErrors()).toBe(false); - // Add an error message + // Add non-error messages - should not change state + addConsoleMessage('log', 'Test log message'); + addConsoleMessage('warn', 'Test warning message'); + expect(getHasConsoleErrors()).toBe(false); + + // Add error message - should change state addConsoleMessage('error', 'Test error message'); - - // Wait a bit for the listener to be called - await new Promise(resolve => setTimeout(resolve, 10)); - - expect(errorListener).toHaveBeenCalledTimes(1); - expect(errorListener).toHaveBeenCalledWith( - expect.objectContaining({ - message: 'Console error detected: Test error message', - logs: expect.arrayContaining([ - expect.objectContaining({ - level: 'error', - message: 'Test error message' - }) - ]) - }) - ); + expect(getHasConsoleErrors()).toBe(true); - removeErrorListener(errorListener); + // Add another error - should remain true + addConsoleMessage('error', 'Another error'); + expect(getHasConsoleErrors()).toBe(true); }); - it('should not trigger error listener for non-error messages', async () => { - const errorListener = vi.fn(); - addErrorListener(errorListener); + it('should trigger error state listener when error state changes', async () => { + const errorStateListener = vi.fn(); + addErrorStateListener(errorStateListener); - // Add non-error messages + // Add non-error messages - should not trigger addConsoleMessage('log', 'Test log message'); addConsoleMessage('warn', 'Test warning message'); - addConsoleMessage('info', 'Test info message'); // Wait a bit await new Promise(resolve => setTimeout(resolve, 10)); + expect(errorStateListener).not.toHaveBeenCalled(); - expect(errorListener).not.toHaveBeenCalled(); + // Add error message - should trigger with true + addConsoleMessage('error', 'Test error message'); - removeErrorListener(errorListener); + // Wait a bit + await new Promise(resolve => setTimeout(resolve, 10)); + expect(errorStateListener).toHaveBeenCalledTimes(1); + expect(errorStateListener).toHaveBeenCalledWith(true); + + // Add another error - should not trigger again (already true) + addConsoleMessage('error', 'Another error'); + + // Wait a bit + await new Promise(resolve => setTimeout(resolve, 10)); + expect(errorStateListener).toHaveBeenCalledTimes(1); // Still only called once + + removeErrorStateListener(errorStateListener); }); - it('should remove error listener correctly', async () => { - const errorListener = vi.fn(); - addErrorListener(errorListener); - removeErrorListener(errorListener); + it('should reset error state when clearing messages', async () => { + const errorStateListener = vi.fn(); + addErrorStateListener(errorStateListener); + + // Add error to set state to true + addConsoleMessage('error', 'Test error message'); + expect(getHasConsoleErrors()).toBe(true); + + // Clear messages - should reset state and notify + clearConsoleMessages(); + expect(getHasConsoleErrors()).toBe(false); + + // Wait a bit + await new Promise(resolve => setTimeout(resolve, 10)); + expect(errorStateListener).toHaveBeenCalledTimes(2); + expect(errorStateListener).toHaveBeenNthCalledWith(1, true); // First call when error added + expect(errorStateListener).toHaveBeenNthCalledWith(2, false); // Second call when cleared + + removeErrorStateListener(errorStateListener); + }); + + it('should remove error state listener correctly', async () => { + const errorStateListener = vi.fn(); + addErrorStateListener(errorStateListener); + removeErrorStateListener(errorStateListener); // Add an error message addConsoleMessage('error', 'Test error message'); @@ -139,7 +165,7 @@ describe('Console Error Listeners', () => { // Wait a bit await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorListener).not.toHaveBeenCalled(); + expect(errorStateListener).not.toHaveBeenCalled(); }); it('should handle listener errors gracefully', async () => { @@ -148,8 +174,8 @@ describe('Console Error Listeners', () => { }); const workingListener = vi.fn(); - addErrorListener(faultyListener); - addErrorListener(workingListener); + addErrorStateListener(faultyListener); + addErrorStateListener(workingListener); // Should not throw despite faulty listener expect(() => { @@ -162,7 +188,7 @@ describe('Console Error Listeners', () => { expect(faultyListener).toHaveBeenCalled(); expect(workingListener).toHaveBeenCalled(); - removeErrorListener(faultyListener); - removeErrorListener(workingListener); + removeErrorStateListener(faultyListener); + removeErrorStateListener(workingListener); }); }); \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index f2396b40..a7cbb26c 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -25,7 +25,10 @@ export class ProjectPreviewConsoleError extends Error { // Simple global console messages storage const consoleMessages: ConsoleMessage[] = []; -const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = []; + +// Boolean-based error detection system +let hasConsoleErrors = false; +const errorStateListeners: Array<(hasErrors: boolean) => void> = []; export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { const consoleMessage: ConsoleMessage = { @@ -35,18 +38,16 @@ export const addConsoleMessage = (level: ConsoleMessage['level'], message: strin consoleMessages.push(consoleMessage); - // If this is an error, notify listeners - if (level === 'error') { - const error = new ProjectPreviewConsoleError( - `Console error detected: ${message}`, - consoleMessages.filter(msg => msg.level === 'error') - ); + // If this is an error, update boolean state + if (level === 'error' && !hasConsoleErrors) { + hasConsoleErrors = true; - errorListeners.forEach(listener => { + // Notify boolean state listeners + errorStateListeners.forEach(listener => { try { - listener(error); + listener(true); } catch (err) { - console.warn('Error listener failed:', err); + console.warn('Error state listener failed:', err); } }); } @@ -56,19 +57,38 @@ export const getConsoleMessages = (): ConsoleMessage[] => { return [...consoleMessages]; }; -export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - errorListeners.push(listener); +export const addErrorStateListener = (listener: (hasErrors: boolean) => void) => { + errorStateListeners.push(listener); }; -export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - const index = errorListeners.indexOf(listener); +export const removeErrorStateListener = (listener: (hasErrors: boolean) => void) => { + const index = errorStateListeners.indexOf(listener); if (index > -1) { - errorListeners.splice(index, 1); + errorStateListeners.splice(index, 1); } }; +export const getHasConsoleErrors = (): boolean => { + return hasConsoleErrors; +}; + export const clearConsoleMessages = () => { consoleMessages.length = 0; + + // Reset error state + const hadErrors = hasConsoleErrors; + hasConsoleErrors = false; + + // Notify listeners if state changed + if (hadErrors) { + errorStateListeners.forEach(listener => { + try { + listener(false); + } catch (err) { + console.warn('Error state listener failed:', err); + } + }); + } }; export class ReadConsoleMessagesTool implements Tool { diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 4b5d926b..a2b23c9e 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -18,7 +18,7 @@ import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { StarButton } from '@/components/StarButton'; import { useBuildProject } from '@/hooks/useBuildProject'; import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable'; -import { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool'; +import { useConsoleError } from '@/hooks/useConsoleError'; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); @@ -29,7 +29,9 @@ export function ProjectView() { const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat'); const [isAILoading, setIsAILoading] = useState(false); const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false); - const [consoleError, setConsoleError] = useState(null); + + // Use console error state from provider + const { consoleError, dismissConsoleError, clearErrors } = useConsoleError(); const projectsManager = useProjectsManager(); const chatPaneRef = useRef(null); @@ -48,14 +50,13 @@ export function ProjectView() { const projectData = await projectsManager.getProject(projectId); setProject(projectData); // Clear console messages and error state when switching projects - clearConsoleMessages(); - setConsoleError(null); + clearErrors(); } catch (error) { console.error('Failed to load project:', error); } finally { setIsLoading(false); } - }, [projectId, projectsManager]); + }, [projectId, projectsManager, clearErrors]); useEffect(() => { loadProject(); @@ -81,15 +82,7 @@ export function ProjectView() { } }, [isPreviewable, mobileView, activeTab]); - // Global console error listener (always active regardless of current tab) - useEffect(() => { - const handleConsoleError = (error: ProjectPreviewConsoleError) => { - setConsoleError(error); - }; - - addErrorListener(handleConsoleError); - return () => removeErrorListener(handleConsoleError); - }, []); + // Console error handling is now managed by useQuillyConsoleErrors hook const handleNewChat = () => { // Reset to chat view on mobile when starting new chat @@ -113,7 +106,7 @@ export function ProjectView() { }; const handleDismissConsoleError = () => { - setConsoleError(null); + dismissConsoleError(); }; const handleProjectDeleted = async () => { From 945c4209e875554621a78d3dce3ba5b99e678d2e Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:02:16 +0000 Subject: [PATCH 062/105] Remove frivilous UI updates. --- src/components/Shakespeare/PreviewPane.tsx | 25 ++-------------------- 1 file changed, 2 insertions(+), 23 deletions(-) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index c45a2da2..6c0d43c7 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -537,12 +537,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o } }; - const handleClearMessages = () => { - clearErrors(); - setMessages([]); - setCopiedMessageIndex(null); - }; - const messageCount = messages.length; return ( @@ -574,21 +568,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o

Messages from your project will appear here

) : ( - <> - {/* Clear button when messages exist */} - {messageCount > 0 && ( -
- -
- )} - {messages.map((msg, index) => ( + messages.map((msg, index) => (
- ))} - + )) )}
From 23c3cead899d7a3082dd3ff21e1affc484fae45b Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:09:09 +0000 Subject: [PATCH 063/105] Move non-tool logic out of tool file. --- src/components/ConsoleErrorProvider.test.tsx | 48 ++--- src/components/ConsoleErrorProvider.tsx | 16 +- src/components/Quilly.tsx | 2 +- src/components/Shakespeare/ChatPane.tsx | 3 +- src/components/Shakespeare/PreviewPane.tsx | 2 +- src/contexts/ConsoleErrorContext.ts | 2 +- src/lib/consoleMessages.test.ts | 168 ++++++++++++++++++ src/lib/consoleMessages.ts | 90 ++++++++++ src/lib/tools/ReadConsoleMessagesTool.test.ts | 161 ++++------------- src/lib/tools/ReadConsoleMessagesTool.ts | 103 ++--------- 10 files changed, 345 insertions(+), 250 deletions(-) create mode 100644 src/lib/consoleMessages.test.ts create mode 100644 src/lib/consoleMessages.ts diff --git a/src/components/ConsoleErrorProvider.test.tsx b/src/components/ConsoleErrorProvider.test.tsx index ae6445cb..44305d8d 100644 --- a/src/components/ConsoleErrorProvider.test.tsx +++ b/src/components/ConsoleErrorProvider.test.tsx @@ -3,7 +3,7 @@ import { renderHook, act, waitFor } from '@testing-library/react'; import { ReactNode } from 'react'; import { ConsoleErrorProvider } from './ConsoleErrorProvider'; import { useConsoleError } from '@/hooks/useConsoleError'; -import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages'; // Wrapper component for testing function TestWrapper({ children }: { children: ReactNode }) { @@ -23,7 +23,7 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + expect(result.current.hasErrors).toBe(false); expect(result.current.consoleError).toBeNull(); }); @@ -32,14 +32,14 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + expect(result.current.hasErrors).toBe(false); - + // Add an error message act(() => { addConsoleMessage('error', 'Test error message'); }); - + expect(result.current.hasErrors).toBe(true); expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError); expect(result.current.consoleError?.message).toBe('Console error detected: Test error message'); @@ -49,14 +49,14 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add non-error messages act(() => { addConsoleMessage('log', 'Test log message'); addConsoleMessage('warn', 'Test warning message'); addConsoleMessage('info', 'Test info message'); }); - + expect(result.current.hasErrors).toBe(false); expect(result.current.consoleError).toBeNull(); }); @@ -65,24 +65,24 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add first error act(() => { addConsoleMessage('error', 'First error'); }); - + expect(result.current.consoleError?.message).toBe('Console error detected: First error'); - + // Add second error - should update to show latest error act(() => { addConsoleMessage('error', 'Second error'); }); - + // Wait for polling to detect the new error await waitFor(() => { expect(result.current.consoleError?.message).toBe('Console error detected: Second error'); }); - + expect(result.current.consoleError?.logs).toHaveLength(2); }); @@ -90,20 +90,20 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add error to set state act(() => { addConsoleMessage('error', 'Test error message'); }); - + expect(result.current.hasErrors).toBe(true); expect(result.current.consoleError).not.toBeNull(); - + // Clear errors act(() => { result.current.clearErrors(); }); - + expect(result.current.hasErrors).toBe(false); expect(result.current.consoleError).toBeNull(); }); @@ -112,19 +112,19 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add error to create console error act(() => { addConsoleMessage('error', 'Test error message'); }); - + expect(result.current.consoleError).not.toBeNull(); - + // Dismiss console error (this only clears the Quilly error, not the global state) act(() => { result.current.dismissConsoleError(); }); - + expect(result.current.consoleError).toBeNull(); // hasErrors should still be true since we only dismissed the Quilly display expect(result.current.hasErrors).toBe(true); @@ -134,7 +134,7 @@ describe('ConsoleErrorProvider', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); - + // Add multiple errors and non-errors act(() => { addConsoleMessage('log', 'Log message'); @@ -144,16 +144,16 @@ describe('ConsoleErrorProvider', () => { addConsoleMessage('info', 'Info message'); addConsoleMessage('error', 'Third error'); }); - + // Wait for polling to detect all the new errors await waitFor(() => { expect(result.current.consoleError?.message).toBe('Console error detected: Third error'); }); - + expect(result.current.consoleError?.logs).toHaveLength(3); expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([ 'First error', - 'Second error', + 'Second error', 'Third error' ]); }); diff --git a/src/components/ConsoleErrorProvider.tsx b/src/components/ConsoleErrorProvider.tsx index b94297e5..da0ad912 100644 --- a/src/components/ConsoleErrorProvider.tsx +++ b/src/components/ConsoleErrorProvider.tsx @@ -1,12 +1,12 @@ import { useState, useEffect, useRef, useCallback, ReactNode } from 'react'; -import { - addErrorStateListener, +import { + addErrorStateListener, removeErrorStateListener, getHasConsoleErrors, getConsoleMessages, clearConsoleMessages, ProjectPreviewConsoleError -} from '@/lib/tools/ReadConsoleMessagesTool'; +} from '@/lib/consoleMessages'; import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext'; interface ConsoleErrorProviderProps { @@ -22,7 +22,7 @@ export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { const updateConsoleError = useCallback(() => { const messages = getConsoleMessages(); const errorMessages = messages.filter(msg => msg.level === 'error'); - + if (errorMessages.length > 0) { const error = new ProjectPreviewConsoleError( `Console error detected: ${errorMessages[errorMessages.length - 1].message}`, @@ -40,7 +40,7 @@ export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { useEffect(() => { const handleErrorStateChange = (hasErrors: boolean) => { setHasErrors(hasErrors); - + if (hasErrors) { // Always update when we get an error state change updateConsoleError(); @@ -55,7 +55,7 @@ export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { const checkForNewErrors = () => { const messages = getConsoleMessages(); const errorMessages = messages.filter(msg => msg.level === 'error'); - + if (errorMessages.length > lastErrorCountRef.current) { // New errors detected - update the console error updateConsoleError(); @@ -64,11 +64,11 @@ export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { // Listen for error state changes addErrorStateListener(handleErrorStateChange); - + // Initial sync setHasErrors(getHasConsoleErrors()); updateConsoleError(); - + // Poll for new errors (handles multiple errors being added) const interval = setInterval(checkForNewErrors, 100); diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index b0b97f05..adb087b7 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -7,7 +7,7 @@ import { useAISettings } from '@/hooks/useAISettings'; import { parseProviderModel } from '@/lib/parseProviderModel'; import { useAICredits } from '@/hooks/useAICredits'; import { CreditsDialog } from './CreditsDialog'; -import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { useState } from 'react'; export interface QuillyProps { diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index e8626112..4b743237 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -34,7 +34,8 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool'; import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; -import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 6c0d43c7..3d48cb77 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -3,7 +3,7 @@ import { useState, useEffect, useCallback, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useFS } from '@/hooks/useFS'; -import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool'; +import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages'; import { useConsoleError } from '@/hooks/useConsoleError'; import { useBuildProject } from '@/hooks/useBuildProject'; import { Tabs, TabsContent } from '@/components/ui/tabs'; diff --git a/src/contexts/ConsoleErrorContext.ts b/src/contexts/ConsoleErrorContext.ts index ed576ce4..d01ea220 100644 --- a/src/contexts/ConsoleErrorContext.ts +++ b/src/contexts/ConsoleErrorContext.ts @@ -1,5 +1,5 @@ import { createContext } from 'react'; -import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; export interface ConsoleErrorContextValue { hasErrors: boolean; diff --git a/src/lib/consoleMessages.test.ts b/src/lib/consoleMessages.test.ts new file mode 100644 index 00000000..31a895ba --- /dev/null +++ b/src/lib/consoleMessages.test.ts @@ -0,0 +1,168 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { + addConsoleMessage, + clearConsoleMessages, + getConsoleMessages, + getHasConsoleErrors, + addErrorStateListener, + removeErrorStateListener, + ProjectPreviewConsoleError +} from './consoleMessages'; + +describe('Console Messages System', () => { + beforeEach(() => { + clearConsoleMessages(); + }); + + describe('addConsoleMessage', () => { + it('should add messages to the global store', () => { + addConsoleMessage('log', 'Test log message'); + addConsoleMessage('error', 'Test error message'); + + const messages = getConsoleMessages(); + expect(messages).toHaveLength(2); + expect(messages[0]).toEqual({ level: 'log', message: 'Test log message' }); + expect(messages[1]).toEqual({ level: 'error', message: 'Test error message' }); + }); + + it('should update error state when error message is added', () => { + expect(getHasConsoleErrors()).toBe(false); + + addConsoleMessage('log', 'Log message'); + expect(getHasConsoleErrors()).toBe(false); + + addConsoleMessage('error', 'Error message'); + expect(getHasConsoleErrors()).toBe(true); + }); + + it('should only trigger error state once for multiple errors', () => { + const listener = vi.fn(); + addErrorStateListener(listener); + + addConsoleMessage('error', 'First error'); + expect(listener).toHaveBeenCalledTimes(1); + expect(listener).toHaveBeenCalledWith(true); + + addConsoleMessage('error', 'Second error'); + expect(listener).toHaveBeenCalledTimes(1); // Should not be called again + + removeErrorStateListener(listener); + }); + }); + + describe('getConsoleMessages', () => { + it('should return a copy of messages array', () => { + addConsoleMessage('info', 'Test message'); + + const messages1 = getConsoleMessages(); + const messages2 = getConsoleMessages(); + + expect(messages1).toEqual(messages2); + expect(messages1).not.toBe(messages2); // Different array instances + }); + + it('should return empty array when no messages', () => { + const messages = getConsoleMessages(); + expect(messages).toEqual([]); + }); + }); + + describe('clearConsoleMessages', () => { + it('should clear all messages and reset error state', () => { + addConsoleMessage('error', 'Error message'); + addConsoleMessage('log', 'Log message'); + + expect(getConsoleMessages()).toHaveLength(2); + expect(getHasConsoleErrors()).toBe(true); + + clearConsoleMessages(); + + expect(getConsoleMessages()).toHaveLength(0); + expect(getHasConsoleErrors()).toBe(false); + }); + + it('should notify listeners when error state changes', () => { + const listener = vi.fn(); + addErrorStateListener(listener); + + addConsoleMessage('error', 'Error message'); + expect(listener).toHaveBeenCalledWith(true); + + clearConsoleMessages(); + expect(listener).toHaveBeenCalledWith(false); + expect(listener).toHaveBeenCalledTimes(2); + + removeErrorStateListener(listener); + }); + + it('should not notify listeners if no error state change', () => { + const listener = vi.fn(); + addErrorStateListener(listener); + + // No errors added, so clearing should not trigger listener + clearConsoleMessages(); + expect(listener).not.toHaveBeenCalled(); + + removeErrorStateListener(listener); + }); + }); + + describe('Error State Listeners', () => { + it('should add and remove listeners correctly', () => { + const listener1 = vi.fn(); + const listener2 = vi.fn(); + + addErrorStateListener(listener1); + addErrorStateListener(listener2); + + addConsoleMessage('error', 'Test error'); + + expect(listener1).toHaveBeenCalledWith(true); + expect(listener2).toHaveBeenCalledWith(true); + + removeErrorStateListener(listener1); + clearConsoleMessages(); + + expect(listener1).toHaveBeenCalledTimes(1); // Only called once (not for clear) + expect(listener2).toHaveBeenCalledTimes(2); // Called for both add and clear + + removeErrorStateListener(listener2); + }); + + it('should handle listener errors gracefully', () => { + const faultyListener = vi.fn(() => { + throw new Error('Listener error'); + }); + const workingListener = vi.fn(); + + addErrorStateListener(faultyListener); + addErrorStateListener(workingListener); + + // Should not throw despite faulty listener + expect(() => { + addConsoleMessage('error', 'Test error'); + }).not.toThrow(); + + expect(faultyListener).toHaveBeenCalled(); + expect(workingListener).toHaveBeenCalled(); + + removeErrorStateListener(faultyListener); + removeErrorStateListener(workingListener); + }); + }); + + describe('ProjectPreviewConsoleError', () => { + it('should create error with console logs', () => { + const logs = [ + { level: 'error' as const, message: 'Test error' } + ]; + const error = new ProjectPreviewConsoleError('Test message', logs); + + expect(error.message).toBe('Test message'); + expect(error.name).toBe('ProjectPreviewConsoleError'); + expect(error.logs).toEqual(logs); + expect(error instanceof Error).toBe(true); + expect(error instanceof ProjectPreviewConsoleError).toBe(true); + }); + }); +}); \ No newline at end of file diff --git a/src/lib/consoleMessages.ts b/src/lib/consoleMessages.ts new file mode 100644 index 00000000..f22f7a61 --- /dev/null +++ b/src/lib/consoleMessages.ts @@ -0,0 +1,90 @@ +/** + * Global console message storage and state management. + * This module handles the core console message system that the AI tool reads from. + */ + +export interface ConsoleMessage { + level: 'log' | 'warn' | 'error' | 'info' | 'debug'; + message: string; +} + +/** + * Custom error class for project preview console errors + */ +export class ProjectPreviewConsoleError extends Error { + public readonly logs: ConsoleMessage[]; + + constructor(message: string, logs: ConsoleMessage[]) { + super(message); + this.name = 'ProjectPreviewConsoleError'; + this.logs = logs; + } +} + +// Global console messages storage +const consoleMessages: ConsoleMessage[] = []; + +// Boolean-based error detection system +let hasConsoleErrors = false; +const errorStateListeners: Array<(hasErrors: boolean) => void> = []; + +export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { + const consoleMessage: ConsoleMessage = { + level, + message, + }; + + consoleMessages.push(consoleMessage); + + // Only update boolean state on first error + if (level === 'error' && !hasConsoleErrors) { + hasConsoleErrors = true; + + // Notify boolean state listeners + errorStateListeners.forEach(listener => { + try { + listener(true); + } catch (err) { + console.warn('Error state listener failed:', err); + } + }); + } +}; + +export const addErrorStateListener = (listener: (hasErrors: boolean) => void) => { + errorStateListeners.push(listener); +}; + +export const removeErrorStateListener = (listener: (hasErrors: boolean) => void) => { + const index = errorStateListeners.indexOf(listener); + if (index > -1) { + errorStateListeners.splice(index, 1); + } +}; + +export const getHasConsoleErrors = (): boolean => { + return hasConsoleErrors; +}; + +export const getConsoleMessages = (): ConsoleMessage[] => { + return [...consoleMessages]; +}; + +export const clearConsoleMessages = () => { + consoleMessages.length = 0; + + // Reset error state + const hadErrors = hasConsoleErrors; + hasConsoleErrors = false; + + // Notify listeners if state changed + if (hadErrors) { + errorStateListeners.forEach(listener => { + try { + listener(false); + } catch (err) { + console.warn('Error state listener failed:', err); + } + }); + } +}; \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.test.ts b/src/lib/tools/ReadConsoleMessagesTool.test.ts index d31c11f0..256570c7 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.test.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.test.ts @@ -1,13 +1,6 @@ -import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { - ReadConsoleMessagesTool, - addConsoleMessage, - clearConsoleMessages, - ProjectPreviewConsoleError, - addErrorStateListener, - removeErrorStateListener, - getHasConsoleErrors -} from './ReadConsoleMessagesTool'; +import { describe, it, expect, beforeEach } from 'vitest'; +import { ReadConsoleMessagesTool } from './ReadConsoleMessagesTool'; +import { addConsoleMessage, clearConsoleMessages } from '@/lib/consoleMessages'; describe('ReadConsoleMessagesTool', () => { beforeEach(() => { @@ -64,131 +57,47 @@ describe('ReadConsoleMessagesTool', () => { expect(result).toBe('No console messages found for level: debug.'); }); -}); -describe('ProjectPreviewConsoleError', () => { - it('should create error with console logs', () => { - const logs = [ - { level: 'error' as const, message: 'Test error' } - ]; - const error = new ProjectPreviewConsoleError('Test message', logs); + it('should handle all filter levels', async () => { + const tool = new ReadConsoleMessagesTool(); - expect(error.message).toBe('Test message'); - expect(error.name).toBe('ProjectPreviewConsoleError'); - expect(error.logs).toEqual(logs); - expect(error instanceof Error).toBe(true); - expect(error instanceof ProjectPreviewConsoleError).toBe(true); + // Test each filter level + const errorResult = await tool.execute({ filter: 'error' }); + expect(errorResult).toContain('[ERROR] Network request failed'); + + const warnResult = await tool.execute({ filter: 'warn' }); + expect(warnResult).toContain('[WARN] Deprecated API used'); + + const logResult = await tool.execute({ filter: 'log' }); + expect(logResult).toContain('[LOG] App started'); + + const infoResult = await tool.execute({ filter: 'info' }); + expect(infoResult).toContain('[INFO] User logged in'); }); -}); -describe('Console Error State Management', () => { - beforeEach(() => { + it('should format messages correctly', async () => { clearConsoleMessages(); + addConsoleMessage('error', 'Test error with special chars: <>&"'); + + const tool = new ReadConsoleMessagesTool(); + const result = await tool.execute({}); + + expect(result).toContain('[ERROR] Test error with special chars: <>&"'); }); - it('should track error state with boolean', () => { - expect(getHasConsoleErrors()).toBe(false); + it('should handle limit edge cases', async () => { + const tool = new ReadConsoleMessagesTool(); - // Add non-error messages - should not change state - addConsoleMessage('log', 'Test log message'); - addConsoleMessage('warn', 'Test warning message'); - expect(getHasConsoleErrors()).toBe(false); + // Limit of 0 should return no messages + const zeroResult = await tool.execute({ limit: 0 }); + expect(zeroResult).toBe('No console messages found.'); - // Add error message - should change state - addConsoleMessage('error', 'Test error message'); - expect(getHasConsoleErrors()).toBe(true); + // Negative limit should return all messages + const negativeResult = await tool.execute({ limit: -1 }); + expect(negativeResult).toContain('Found 4 console messages'); - // Add another error - should remain true - addConsoleMessage('error', 'Another error'); - expect(getHasConsoleErrors()).toBe(true); - }); - - it('should trigger error state listener when error state changes', async () => { - const errorStateListener = vi.fn(); - addErrorStateListener(errorStateListener); - - // Add non-error messages - should not trigger - addConsoleMessage('log', 'Test log message'); - addConsoleMessage('warn', 'Test warning message'); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorStateListener).not.toHaveBeenCalled(); - - // Add error message - should trigger with true - addConsoleMessage('error', 'Test error message'); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorStateListener).toHaveBeenCalledTimes(1); - expect(errorStateListener).toHaveBeenCalledWith(true); - - // Add another error - should not trigger again (already true) - addConsoleMessage('error', 'Another error'); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorStateListener).toHaveBeenCalledTimes(1); // Still only called once - - removeErrorStateListener(errorStateListener); - }); - - it('should reset error state when clearing messages', async () => { - const errorStateListener = vi.fn(); - addErrorStateListener(errorStateListener); - - // Add error to set state to true - addConsoleMessage('error', 'Test error message'); - expect(getHasConsoleErrors()).toBe(true); - - // Clear messages - should reset state and notify - clearConsoleMessages(); - expect(getHasConsoleErrors()).toBe(false); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - expect(errorStateListener).toHaveBeenCalledTimes(2); - expect(errorStateListener).toHaveBeenNthCalledWith(1, true); // First call when error added - expect(errorStateListener).toHaveBeenNthCalledWith(2, false); // Second call when cleared - - removeErrorStateListener(errorStateListener); - }); - - it('should remove error state listener correctly', async () => { - const errorStateListener = vi.fn(); - addErrorStateListener(errorStateListener); - removeErrorStateListener(errorStateListener); - - // Add an error message - addConsoleMessage('error', 'Test error message'); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - - expect(errorStateListener).not.toHaveBeenCalled(); - }); - - it('should handle listener errors gracefully', async () => { - const faultyListener = vi.fn(() => { - throw new Error('Listener error'); - }); - const workingListener = vi.fn(); - - addErrorStateListener(faultyListener); - addErrorStateListener(workingListener); - - // Should not throw despite faulty listener - expect(() => { - addConsoleMessage('error', 'Test error message'); - }).not.toThrow(); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 10)); - - expect(faultyListener).toHaveBeenCalled(); - expect(workingListener).toHaveBeenCalled(); - - removeErrorStateListener(faultyListener); - removeErrorStateListener(workingListener); + // Limit larger than available should return all + const largeResult = await tool.execute({ limit: 100 }); + expect(largeResult).toContain('Found 4 console messages'); }); }); \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index a7cbb26c..52853686 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -1,9 +1,5 @@ import { Tool } from './Tool'; - -export interface ConsoleMessage { - level: 'log' | 'warn' | 'error' | 'info' | 'debug'; - message: string; -} +import { getConsoleMessages } from '@/lib/consoleMessages'; export interface ReadConsoleMessagesParams { filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all'; @@ -11,94 +7,25 @@ export interface ReadConsoleMessagesParams { } /** - * Custom error class for project preview console errors + * AI tool for reading console messages from the project preview. + * This tool allows AI assistants to access console logs for debugging assistance. */ -export class ProjectPreviewConsoleError extends Error { - public readonly logs: ConsoleMessage[]; - - constructor(message: string, logs: ConsoleMessage[]) { - super(message); - this.name = 'ProjectPreviewConsoleError'; - this.logs = logs; - } -} - -// Simple global console messages storage -const consoleMessages: ConsoleMessage[] = []; - -// Boolean-based error detection system -let hasConsoleErrors = false; -const errorStateListeners: Array<(hasErrors: boolean) => void> = []; - -export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { - const consoleMessage: ConsoleMessage = { - level, - message, - }; - - consoleMessages.push(consoleMessage); - - // If this is an error, update boolean state - if (level === 'error' && !hasConsoleErrors) { - hasConsoleErrors = true; - - // Notify boolean state listeners - errorStateListeners.forEach(listener => { - try { - listener(true); - } catch (err) { - console.warn('Error state listener failed:', err); - } - }); - } -}; - -export const getConsoleMessages = (): ConsoleMessage[] => { - return [...consoleMessages]; -}; - -export const addErrorStateListener = (listener: (hasErrors: boolean) => void) => { - errorStateListeners.push(listener); -}; - -export const removeErrorStateListener = (listener: (hasErrors: boolean) => void) => { - const index = errorStateListeners.indexOf(listener); - if (index > -1) { - errorStateListeners.splice(index, 1); - } -}; - -export const getHasConsoleErrors = (): boolean => { - return hasConsoleErrors; -}; - -export const clearConsoleMessages = () => { - consoleMessages.length = 0; - - // Reset error state - const hadErrors = hasConsoleErrors; - hasConsoleErrors = false; - - // Notify listeners if state changed - if (hadErrors) { - errorStateListeners.forEach(listener => { - try { - listener(false); - } catch (err) { - console.warn('Error state listener failed:', err); - } - }); - } -}; - export class ReadConsoleMessagesTool implements Tool { async execute(params: ReadConsoleMessagesParams): Promise { const { filter = 'all', limit } = params; - // Filter and limit messages in one chain - const filteredMessages = getConsoleMessages() - .filter(msg => filter === 'all' || msg.level === filter) - .slice(limit && limit > 0 ? -limit : 0); + // Filter messages first + let filteredMessages = getConsoleMessages() + .filter(msg => filter === 'all' || msg.level === filter); + + // Apply limit if specified and positive + if (limit !== undefined && limit >= 0) { + if (limit === 0) { + filteredMessages = []; + } else { + filteredMessages = filteredMessages.slice(-limit); + } + } if (filteredMessages.length === 0) { return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`; From 111ab724e5c07818e02d81393bf2b8ba4ecf0b71 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:13:25 +0000 Subject: [PATCH 064/105] Remove and simplify some logic. --- src/components/ConsoleErrorProvider.test.tsx | 18 ++--- src/components/ConsoleErrorProvider.tsx | 70 +++++-------------- src/components/Shakespeare/PreviewPane.tsx | 8 +-- src/lib/consoleMessages.test.ts | 59 ++++++---------- src/lib/consoleMessages.ts | 63 +++++------------ src/lib/tools/ReadConsoleMessagesTool.test.ts | 18 ++--- src/lib/tools/ReadConsoleMessagesTool.ts | 22 ++---- 7 files changed, 78 insertions(+), 180 deletions(-) diff --git a/src/components/ConsoleErrorProvider.test.tsx b/src/components/ConsoleErrorProvider.test.tsx index 44305d8d..3ef2b767 100644 --- a/src/components/ConsoleErrorProvider.test.tsx +++ b/src/components/ConsoleErrorProvider.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach } from 'vitest'; -import { renderHook, act, waitFor } from '@testing-library/react'; +import { renderHook, act } from '@testing-library/react'; import { ReactNode } from 'react'; import { ConsoleErrorProvider } from './ConsoleErrorProvider'; import { useConsoleError } from '@/hooks/useConsoleError'; @@ -61,7 +61,7 @@ describe('ConsoleErrorProvider', () => { expect(result.current.consoleError).toBeNull(); }); - it('should update consoleError with latest error message', async () => { + it('should update consoleError with latest error message', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); @@ -78,11 +78,7 @@ describe('ConsoleErrorProvider', () => { addConsoleMessage('error', 'Second error'); }); - // Wait for polling to detect the new error - await waitFor(() => { - expect(result.current.consoleError?.message).toBe('Console error detected: Second error'); - }); - + expect(result.current.consoleError?.message).toBe('Console error detected: Second error'); expect(result.current.consoleError?.logs).toHaveLength(2); }); @@ -130,7 +126,7 @@ describe('ConsoleErrorProvider', () => { expect(result.current.hasErrors).toBe(true); }); - it('should include all error messages in console error logs', async () => { + it('should include all error messages in console error logs', () => { const { result } = renderHook(() => useConsoleError(), { wrapper: TestWrapper, }); @@ -145,11 +141,7 @@ describe('ConsoleErrorProvider', () => { addConsoleMessage('error', 'Third error'); }); - // Wait for polling to detect all the new errors - await waitFor(() => { - expect(result.current.consoleError?.message).toBe('Console error detected: Third error'); - }); - + expect(result.current.consoleError?.message).toBe('Console error detected: Third error'); expect(result.current.consoleError?.logs).toHaveLength(3); expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([ 'First error', diff --git a/src/components/ConsoleErrorProvider.tsx b/src/components/ConsoleErrorProvider.tsx index da0ad912..b033ed64 100644 --- a/src/components/ConsoleErrorProvider.tsx +++ b/src/components/ConsoleErrorProvider.tsx @@ -1,7 +1,7 @@ -import { useState, useEffect, useRef, useCallback, ReactNode } from 'react'; +import { useState, useEffect, useCallback, ReactNode } from 'react'; import { - addErrorStateListener, - removeErrorStateListener, + addConsoleMessageListener, + removeConsoleMessageListener, getHasConsoleErrors, getConsoleMessages, clearConsoleMessages, @@ -16,67 +16,29 @@ interface ConsoleErrorProviderProps { export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) { const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors()); const [consoleError, setConsoleError] = useState(null); - const lastErrorCountRef = useRef(0); - // Update console error with latest error information - const updateConsoleError = useCallback(() => { - const messages = getConsoleMessages(); - const errorMessages = messages.filter(msg => msg.level === 'error'); + const updateState = useCallback(() => { + const hasConsoleErrors = getHasConsoleErrors(); + setHasErrors(hasConsoleErrors); - if (errorMessages.length > 0) { - const error = new ProjectPreviewConsoleError( - `Console error detected: ${errorMessages[errorMessages.length - 1].message}`, + if (hasConsoleErrors) { + const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error'); + const latestError = errorMessages[errorMessages.length - 1]; + setConsoleError(new ProjectPreviewConsoleError( + `Console error detected: ${latestError.message}`, errorMessages - ); - setConsoleError(error); - lastErrorCountRef.current = errorMessages.length; + )); } else { setConsoleError(null); - lastErrorCountRef.current = 0; } }, []); - // Handle error state changes from the global console system useEffect(() => { - const handleErrorStateChange = (hasErrors: boolean) => { - setHasErrors(hasErrors); + addConsoleMessageListener(updateState); + updateState(); // Initial sync - if (hasErrors) { - // Always update when we get an error state change - updateConsoleError(); - } else { - // Clear console error when state resets - setConsoleError(null); - lastErrorCountRef.current = 0; - } - }; - - // Check for new errors periodically when we have errors - const checkForNewErrors = () => { - const messages = getConsoleMessages(); - const errorMessages = messages.filter(msg => msg.level === 'error'); - - if (errorMessages.length > lastErrorCountRef.current) { - // New errors detected - update the console error - updateConsoleError(); - } - }; - - // Listen for error state changes - addErrorStateListener(handleErrorStateChange); - - // Initial sync - setHasErrors(getHasConsoleErrors()); - updateConsoleError(); - - // Poll for new errors (handles multiple errors being added) - const interval = setInterval(checkForNewErrors, 100); - - return () => { - removeErrorStateListener(handleErrorStateChange); - clearInterval(interval); - }; - }, [updateConsoleError]); + return () => removeConsoleMessageListener(updateState); + }, [updateState]); const clearErrors = useCallback(() => { clearConsoleMessages(); diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 3d48cb77..3b23828e 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -518,14 +518,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o const ConsoleDropdown = () => { const [isOpen, setIsOpen] = useState(false); const [copiedMessageIndex, setCopiedMessageIndex] = useState(null); - const [messages, setMessages] = useState([]); - // Only fetch messages when dropdown opens - useEffect(() => { - if (isOpen) { - setMessages(getConsoleMessages()); - } - }, [isOpen]); + const messages = isOpen ? getConsoleMessages() : []; const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => { try { diff --git a/src/lib/consoleMessages.test.ts b/src/lib/consoleMessages.test.ts index 31a895ba..7b402c0d 100644 --- a/src/lib/consoleMessages.test.ts +++ b/src/lib/consoleMessages.test.ts @@ -4,8 +4,8 @@ import { clearConsoleMessages, getConsoleMessages, getHasConsoleErrors, - addErrorStateListener, - removeErrorStateListener, + addConsoleMessageListener, + removeConsoleMessageListener, ProjectPreviewConsoleError } from './consoleMessages'; @@ -35,28 +35,27 @@ describe('Console Messages System', () => { expect(getHasConsoleErrors()).toBe(true); }); - it('should only trigger error state once for multiple errors', () => { + it('should notify listeners when messages are added', () => { const listener = vi.fn(); - addErrorStateListener(listener); + addConsoleMessageListener(listener); addConsoleMessage('error', 'First error'); expect(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveBeenCalledWith(true); addConsoleMessage('error', 'Second error'); - expect(listener).toHaveBeenCalledTimes(1); // Should not be called again + expect(listener).toHaveBeenCalledTimes(2); - removeErrorStateListener(listener); + removeConsoleMessageListener(listener); }); }); describe('getConsoleMessages', () => { it('should return a copy of messages array', () => { addConsoleMessage('info', 'Test message'); - + const messages1 = getConsoleMessages(); const messages2 = getConsoleMessages(); - + expect(messages1).toEqual(messages2); expect(messages1).not.toBe(messages2); // Different array instances }); @@ -81,52 +80,40 @@ describe('Console Messages System', () => { expect(getHasConsoleErrors()).toBe(false); }); - it('should notify listeners when error state changes', () => { + it('should notify listeners when messages are cleared', () => { const listener = vi.fn(); - addErrorStateListener(listener); + addConsoleMessageListener(listener); addConsoleMessage('error', 'Error message'); - expect(listener).toHaveBeenCalledWith(true); + expect(listener).toHaveBeenCalledTimes(1); clearConsoleMessages(); - expect(listener).toHaveBeenCalledWith(false); expect(listener).toHaveBeenCalledTimes(2); - removeErrorStateListener(listener); - }); - - it('should not notify listeners if no error state change', () => { - const listener = vi.fn(); - addErrorStateListener(listener); - - // No errors added, so clearing should not trigger listener - clearConsoleMessages(); - expect(listener).not.toHaveBeenCalled(); - - removeErrorStateListener(listener); + removeConsoleMessageListener(listener); }); }); - describe('Error State Listeners', () => { + describe('Message Listeners', () => { it('should add and remove listeners correctly', () => { const listener1 = vi.fn(); const listener2 = vi.fn(); - addErrorStateListener(listener1); - addErrorStateListener(listener2); + addConsoleMessageListener(listener1); + addConsoleMessageListener(listener2); addConsoleMessage('error', 'Test error'); - expect(listener1).toHaveBeenCalledWith(true); - expect(listener2).toHaveBeenCalledWith(true); + expect(listener1).toHaveBeenCalledTimes(1); + expect(listener2).toHaveBeenCalledTimes(1); - removeErrorStateListener(listener1); + removeConsoleMessageListener(listener1); clearConsoleMessages(); expect(listener1).toHaveBeenCalledTimes(1); // Only called once (not for clear) expect(listener2).toHaveBeenCalledTimes(2); // Called for both add and clear - removeErrorStateListener(listener2); + removeConsoleMessageListener(listener2); }); it('should handle listener errors gracefully', () => { @@ -135,8 +122,8 @@ describe('Console Messages System', () => { }); const workingListener = vi.fn(); - addErrorStateListener(faultyListener); - addErrorStateListener(workingListener); + addConsoleMessageListener(faultyListener); + addConsoleMessageListener(workingListener); // Should not throw despite faulty listener expect(() => { @@ -146,8 +133,8 @@ describe('Console Messages System', () => { expect(faultyListener).toHaveBeenCalled(); expect(workingListener).toHaveBeenCalled(); - removeErrorStateListener(faultyListener); - removeErrorStateListener(workingListener); + removeConsoleMessageListener(faultyListener); + removeConsoleMessageListener(workingListener); }); }); diff --git a/src/lib/consoleMessages.ts b/src/lib/consoleMessages.ts index f22f7a61..a707e463 100644 --- a/src/lib/consoleMessages.ts +++ b/src/lib/consoleMessages.ts @@ -23,47 +23,36 @@ export class ProjectPreviewConsoleError extends Error { // Global console messages storage const consoleMessages: ConsoleMessage[] = []; +const listeners: Array<() => void> = []; -// Boolean-based error detection system -let hasConsoleErrors = false; -const errorStateListeners: Array<(hasErrors: boolean) => void> = []; +const notifyListeners = () => { + listeners.forEach(listener => { + try { + listener(); + } catch (err) { + console.warn('Console message listener failed:', err); + } + }); +}; export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { - const consoleMessage: ConsoleMessage = { - level, - message, - }; - - consoleMessages.push(consoleMessage); - - // Only update boolean state on first error - if (level === 'error' && !hasConsoleErrors) { - hasConsoleErrors = true; - - // Notify boolean state listeners - errorStateListeners.forEach(listener => { - try { - listener(true); - } catch (err) { - console.warn('Error state listener failed:', err); - } - }); - } + consoleMessages.push({ level, message }); + notifyListeners(); }; -export const addErrorStateListener = (listener: (hasErrors: boolean) => void) => { - errorStateListeners.push(listener); +export const addConsoleMessageListener = (listener: () => void) => { + listeners.push(listener); }; -export const removeErrorStateListener = (listener: (hasErrors: boolean) => void) => { - const index = errorStateListeners.indexOf(listener); +export const removeConsoleMessageListener = (listener: () => void) => { + const index = listeners.indexOf(listener); if (index > -1) { - errorStateListeners.splice(index, 1); + listeners.splice(index, 1); } }; export const getHasConsoleErrors = (): boolean => { - return hasConsoleErrors; + return consoleMessages.some(msg => msg.level === 'error'); }; export const getConsoleMessages = (): ConsoleMessage[] => { @@ -72,19 +61,5 @@ export const getConsoleMessages = (): ConsoleMessage[] => { export const clearConsoleMessages = () => { consoleMessages.length = 0; - - // Reset error state - const hadErrors = hasConsoleErrors; - hasConsoleErrors = false; - - // Notify listeners if state changed - if (hadErrors) { - errorStateListeners.forEach(listener => { - try { - listener(false); - } catch (err) { - console.warn('Error state listener failed:', err); - } - }); - } + notifyListeners(); }; \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.test.ts b/src/lib/tools/ReadConsoleMessagesTool.test.ts index 256570c7..bf2de6c6 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.test.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.test.ts @@ -85,19 +85,15 @@ describe('ReadConsoleMessagesTool', () => { expect(result).toContain('[ERROR] Test error with special chars: <>&"'); }); - it('should handle limit edge cases', async () => { + it('should handle limit correctly', async () => { const tool = new ReadConsoleMessagesTool(); - // Limit of 0 should return no messages - const zeroResult = await tool.execute({ limit: 0 }); - expect(zeroResult).toBe('No console messages found.'); + // Limit should return only the most recent messages + const limitedResult = await tool.execute({ limit: 2 }); + expect(limitedResult).toContain('Found 2 console messages'); - // Negative limit should return all messages - const negativeResult = await tool.execute({ limit: -1 }); - expect(negativeResult).toContain('Found 4 console messages'); - - // Limit larger than available should return all - const largeResult = await tool.execute({ limit: 100 }); - expect(largeResult).toContain('Found 4 console messages'); + // No limit should return all messages + const allResult = await tool.execute({}); + expect(allResult).toContain('Found 4 console messages'); }); }); \ No newline at end of file diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index 52853686..1f8e5904 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -14,31 +14,23 @@ export class ReadConsoleMessagesTool implements Tool async execute(params: ReadConsoleMessagesParams): Promise { const { filter = 'all', limit } = params; - // Filter messages first - let filteredMessages = getConsoleMessages() + let messages = getConsoleMessages() .filter(msg => filter === 'all' || msg.level === filter); - // Apply limit if specified and positive - if (limit !== undefined && limit >= 0) { - if (limit === 0) { - filteredMessages = []; - } else { - filteredMessages = filteredMessages.slice(-limit); - } + if (limit && limit > 0) { + messages = messages.slice(-limit); } - if (filteredMessages.length === 0) { + if (messages.length === 0) { return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`; } - const formattedMessages = filteredMessages + const formatted = messages .map(msg => `[${msg.level.toUpperCase()}] ${msg.message}`) .join('\n'); - const plural = filteredMessages.length !== 1 ? 's' : ''; - const levelInfo = filter !== 'all' ? ` (level: ${filter})` : ''; - - return `Found ${filteredMessages.length} console message${plural}${levelInfo}:\n\n${formattedMessages}`; + const suffix = filter !== 'all' ? ` (level: ${filter})` : ''; + return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}:\n\n${formatted}`; } description = 'Read console messages from the project preview. Can filter by level and limit results.'; From c72170f19cdb7daf35f0628d6abb54f06065f9b1 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 15:05:09 -0500 Subject: [PATCH 065/105] Build by actually mimicking Vite's handling of index.html --- src/lib/build/fsPlugin.ts | 16 ++++- src/lib/build/index.ts | 96 +++++++++++++++++++----------- src/lib/build/shakespearePlugin.ts | 20 +++++++ 3 files changed, 96 insertions(+), 36 deletions(-) diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index cb53dd4e..1352e274 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -16,9 +16,15 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { }); build.onResolve({ filter: /.*/ }, async (args) => { - let resolved: string; + // Skip resolving paths from external URLs + if (/^https?:\/\//.test(args.importer)) { + return; + } - if (args.path.startsWith("@/")) { + let resolved: string; + if (args.path.startsWith("/")) { + resolved = args.path; + } else if (args.path.startsWith("@/")) { resolved = join(cwd, args.path.slice(2)); } else if (args.kind === "entry-point") { resolved = join(cwd, args.path); @@ -28,6 +34,12 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { return; } + // Security: prevent accessing files outside the project directory + const projectDir = join(cwd, ".."); + if (resolved.startsWith("/") && !resolved.startsWith(projectDir)) { + throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`); + } + // Vite query parameters https://vite.dev/guide/assets const [cleaned, query] = resolved.split("?"); diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 6817bcb2..9d6a0d1a 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,3 +1,4 @@ +import { join } from "path-browserify"; import { getEsbuild } from "@/lib/esbuild"; import { copyFiles } from "@/lib/copyFiles"; @@ -32,25 +33,47 @@ async function bundle( ); const doc = domParser.parseFromString(indexHtmlText, "text/html"); + const entryPoints: string[] = []; + const entryScripts: Record = {}; + + // Find all module scripts with relative paths in index.html + for (const script of doc.scripts) { + const scriptSrc = script.getAttribute("src"); + + if (scriptSrc && script.type === "module" && /^[./]/.test(scriptSrc)) { + const path = join(projectPath, scriptSrc); + + // Files in the public directory take precedence over source files + if (scriptSrc.startsWith("/")) { + if (await fileExists(fs, join(projectPath, "public", scriptSrc))) { + continue; + } + } + + entryPoints.push(path); + entryScripts[path] = script; + } + } + + // Enable Tailwind CSS if a config file is present + for (const path of ["tailwind.config.ts", "tailwind.config.js"]) { + if (await fileExists(fs, join(projectPath, path))) { + entryPoints.push(`shakespeare:${path}`); + break; + } + } const results = await esbuild.build({ - stdin: { - contents: ` - import "@/main.tsx"; - import tailwindConfig from "@/../tailwind.config.ts"; - import "https://esm.sh/tailwindcss-cdn@3"; - tailwind.config = tailwindConfig; - `, - loader: "tsx", - }, + entryPoints, bundle: true, write: false, format: "esm", target, outdir: "/", jsx: "automatic", + metafile: true, plugins: [ - shakespearePlugin(), // Takes precedence over esmPlugin + shakespearePlugin(), fsPlugin(fs, `${projectPath}/src`), esmPlugin(JSON.parse(packageLockText), target), ], @@ -62,18 +85,32 @@ async function bundle( const dist: Record = {}; for (const file of results.outputFiles) { - const relativePath = file.path.replace(/^\//, ""); - if (relativePath === "stdin.js") { - dist["main.js"] = file.contents; - } else if (relativePath === "stdin.css") { - dist["main.css"] = file.contents; - } else { - dist[relativePath] = file.contents; + const ext = file.path.split('.').pop(); + const filename = `${file.path.split('/').pop()?.split('.')?.[0] || "chunk"}-${file.hash}.${ext}`; + const entryPoint = results.metafile.outputs[file.path.slice(1)]?.entryPoint?.replace(/^fs:/, ''); + const script = entryPoint ? entryScripts[entryPoint] : null; + + if (script) { + script.setAttribute("src", "/" + filename); + dist[filename] = file.contents; + } else if (ext === "js") { + const script = document.createElement("script"); + script.type = "module"; + script.src = "/" + filename; + doc.head.appendChild(script); + dist[filename] = file.contents; + } else if (ext === "css") { + // Embed stylesheets as Tailwind CSS styles + const style = doc.createElement("style"); + style.setAttribute("type", "text/tailwindcss"); + style.textContent = file.text; + doc.head.appendChild(style); } } - // Update index.html with proper script and link tags - updateIndexHtml(doc, dist); + // HACK: Remove existing CSP header for now. + // TODO: Parse CSP and ensure esm.sh is allowed. + doc.querySelector("meta[http-equiv=\"content-security-policy\"]")?.remove(); const updatedHtml = "\n" + doc.documentElement.outerHTML; dist["index.html"] = new TextEncoder().encode(updatedHtml); @@ -156,20 +193,11 @@ export async function buildProject(options: BuildProjectOptions): Promise<{ }; } -function updateIndexHtml(doc: Document, dist: Record): void { - const entrypoint = doc.querySelector('script[src="/src/main.tsx"]'); - - if (!entrypoint) { - throw new Error("No entrypoint script found in index.html"); - } - - entrypoint.setAttribute("src", "/main.js"); - - const css = dist["main.css"]; - if (css) { - const style = doc.createElement("style"); - style.setAttribute("type", "text/tailwindcss"); - style.textContent = new TextDecoder().decode(css); - doc.head.appendChild(style); +async function fileExists(fs: JSRuntimeFS, path: string): Promise { + try { + const stat = await fs.stat(path); + return stat.isFile(); + } catch { + return false; } } \ No newline at end of file diff --git a/src/lib/build/shakespearePlugin.ts b/src/lib/build/shakespearePlugin.ts index c315be66..ec272afc 100644 --- a/src/lib/build/shakespearePlugin.ts +++ b/src/lib/build/shakespearePlugin.ts @@ -10,6 +10,26 @@ export function shakespearePlugin(): Plugin { name: "shakespeare", setup(build) { + // Handle Tailwind CSS configuration files + build.onResolve({ filter: /^shakespeare:tailwind\.config\.(js|ts)$/ }, (args) => { + return { + path: args.path, + namespace: "shakespeare-tailwind", + }; + }); + + build.onLoad({ filter: /.*/, namespace: "shakespeare-tailwind" }, async (args) => { + const { pathname } = new URL(args.path); + return { + contents: ` + import tailwindConfig from "@/../${pathname}"; + import "https://esm.sh/tailwindcss-cdn@3"; + tailwind.config = tailwindConfig; + `, + loader: "js", + }; + }); + // Handle "sonner" imports with a dummy API build.onResolve({ filter: /^sonner$/ }, (args) => { return { From 51ce9c61efd1dd9b575c26f607a80a7379c6d03e Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:30:02 +0000 Subject: [PATCH 066/105] Remove spurrious migration comment. --- src/pages/ProjectView.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index a2b23c9e..212191f8 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -82,8 +82,6 @@ export function ProjectView() { } }, [isPreviewable, mobileView, activeTab]); - // Console error handling is now managed by useQuillyConsoleErrors hook - const handleNewChat = () => { // Reset to chat view on mobile when starting new chat if (isMobile) { From 225c90f5564a3c9ae3de0264ad038237c0d55811 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 15:42:15 -0500 Subject: [PATCH 067/105] Surgically add esm.sh to existing CSP of index.html --- src/lib/build/index.test.ts | 64 ++++++++++++---- src/lib/build/index.ts | 27 ++++++- src/lib/csp.test.ts | 145 ++++++++++++++++++++++++++++++++++++ src/lib/csp.ts | 87 ++++++++++++++++++++++ 4 files changed, 306 insertions(+), 17 deletions(-) create mode 100644 src/lib/csp.test.ts create mode 100644 src/lib/csp.ts diff --git a/src/lib/build/index.test.ts b/src/lib/build/index.test.ts index 8934a324..fe2d7ef0 100644 --- a/src/lib/build/index.test.ts +++ b/src/lib/build/index.test.ts @@ -11,12 +11,26 @@ vi.mock('../esbuild', () => ({ { path: '/stdin.js', contents: new Uint8Array([1, 2, 3]), + text: '', + hash: 'abc123', }, { path: '/stdin.css', contents: new Uint8Array([4, 5, 6]), + text: 'body { margin: 0; }', + hash: 'def456', }, ], + metafile: { + outputs: { + 'stdin.js': { + entryPoint: 'fs:/test/project/src/main.tsx', + }, + 'stdin.css': { + entryPoint: undefined, + }, + }, + }, })), })), })); @@ -52,9 +66,25 @@ describe('buildProject', () => { documentElement: { outerHTML: '', }, - querySelector: vi.fn(() => ({ - setAttribute: vi.fn(), - })), + querySelector: vi.fn((selector: string) => { + if (selector === 'meta[http-equiv="content-security-policy"]') { + // Return null for CSP meta tag (no CSP present in test) + return null; + } + return { + setAttribute: vi.fn(), + getAttribute: vi.fn(), + }; + }), + scripts: [ + { + getAttribute: vi.fn((attr: string) => { + if (attr === 'src') return '/src/main.tsx'; + return null; + }), + type: 'module', + }, + ], head: { appendChild: vi.fn(), }, @@ -133,11 +163,13 @@ describe('buildProject', () => { domParser: mockDOMParser, }); - // Should include built files - expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); - expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6])); + // Should include built files with hashed names + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['index.html']).toBeDefined(); + // CSS should be embedded in HTML, not as separate file + expect(Object.keys(result.files)).not.toContain('stdin-def456.css'); + // Public files should be copied to filesystem, not included in files object // Verify copyFiles was called for public directory expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public'); @@ -190,11 +222,13 @@ describe('buildProject', () => { domParser: mockDOMParser, }); - // Should still include built files - expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); - expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6])); + // Should still include built files with hashed names + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['index.html']).toBeDefined(); + // CSS should be embedded in HTML, not as separate file + expect(Object.keys(result.files)).not.toContain('stdin-def456.css'); + // Should not include any public files in bundle expect(Object.keys(result.files)).not.toContain('favicon.ico'); @@ -246,13 +280,15 @@ describe('buildProject', () => { domParser: mockDOMParser, }); - // Should include built files - expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); - expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6])); + // Should include built files with hashed names + expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['index.html']).toBeDefined(); - // Should have exactly 3 files (main.js, main.css, index.html) - expect(Object.keys(result.files)).toHaveLength(3); + // CSS should be embedded in HTML, not as separate file + expect(Object.keys(result.files)).not.toContain('stdin-def456.css'); + + // Should have exactly 2 files (stdin-abc123.js, index.html) + expect(Object.keys(result.files)).toHaveLength(2); // Should try to copy public files but directory is empty expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist'); diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 9d6a0d1a..8dd0bb96 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,6 +1,7 @@ import { join } from "path-browserify"; import { getEsbuild } from "@/lib/esbuild"; import { copyFiles } from "@/lib/copyFiles"; +import { addDomainToCSP } from "@/lib/csp"; import { shakespearePlugin } from "./shakespearePlugin"; import { esmPlugin } from "./esmPlugin"; @@ -108,9 +109,15 @@ async function bundle( } } - // HACK: Remove existing CSP header for now. - // TODO: Parse CSP and ensure esm.sh is allowed. - doc.querySelector("meta[http-equiv=\"content-security-policy\"]")?.remove(); + // Parse CSP and ensure esm.sh is allowed for necessary directives + const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]"); + if (cspMeta) { + const cspContent = cspMeta.getAttribute("content"); + if (cspContent) { + const updatedCSP = updateCSPForEsmSh(cspContent); + cspMeta.setAttribute("content", updatedCSP); + } + } const updatedHtml = "\n" + doc.documentElement.outerHTML; dist["index.html"] = new TextEncoder().encode(updatedHtml); @@ -200,4 +207,18 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise { } catch { return false; } +} + +/** Updates CSP to allow esm.sh for scripts, assets, fonts, and CSS */ +export function updateCSPForEsmSh(csp: string): string { + const esmShDirectives = [ + 'script-src', // For JavaScript modules + 'img-src', // For images + 'media-src', // For video/audio + 'font-src', // For fonts + 'style-src', // For CSS + 'connect-src' // For fetch/XHR requests to esm.sh + ]; + + return addDomainToCSP(csp, 'https://esm.sh', esmShDirectives); } \ No newline at end of file diff --git a/src/lib/csp.test.ts b/src/lib/csp.test.ts new file mode 100644 index 00000000..8702eba2 --- /dev/null +++ b/src/lib/csp.test.ts @@ -0,0 +1,145 @@ +import { describe, it, expect } from 'vitest'; +import { + parseCSP, + stringifyCSP, + addSourceToDirective, + addDomainToCSP, + type CSPDirectives +} from './csp'; + +describe('parseCSP', () => { + it('should parse basic CSP with multiple directives', () => { + const csp = "default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *"; + const result = parseCSP(csp); + + expect(result).toEqual({ + 'default-src': ["'self'"], + 'script-src': ["'self'", "'unsafe-inline'"], + 'img-src': ['*'] + }); + }); + + it('should handle directives without sources', () => { + const csp = "upgrade-insecure-requests; block-all-mixed-content"; + const result = parseCSP(csp); + + expect(result).toEqual({ + 'upgrade-insecure-requests': [], + 'block-all-mixed-content': [] + }); + }); + + it('should handle empty or whitespace-only CSP', () => { + expect(parseCSP('')).toEqual({}); + expect(parseCSP(' ')).toEqual({}); + expect(parseCSP(';;;')).toEqual({}); + }); + + it('should handle extra whitespace and semicolons', () => { + const csp = " default-src 'self' ; script-src 'self' ; "; + const result = parseCSP(csp); + + expect(result).toEqual({ + 'default-src': ["'self'"], + 'script-src': ["'self'"] + }); + }); +}); + +describe('stringifyCSP', () => { + it('should convert directives back to CSP string', () => { + const directives: CSPDirectives = { + 'default-src': ["'self'"], + 'script-src': ["'self'", "'unsafe-inline'"], + 'img-src': ['*'] + }; + + const result = stringifyCSP(directives); + expect(result).toBe("default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *"); + }); + + it('should handle directives without sources', () => { + const directives: CSPDirectives = { + 'upgrade-insecure-requests': [], + 'default-src': ["'self'"] + }; + + const result = stringifyCSP(directives); + expect(result).toBe("upgrade-insecure-requests; default-src 'self'"); + }); + + it('should handle empty directives object', () => { + expect(stringifyCSP({})).toBe(''); + }); +}); + +describe('addSourceToDirective', () => { + it('should add new source to existing sources', () => { + const sources = ["'self'", "'unsafe-inline'"]; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(["'self'", "'unsafe-inline'", 'https://example.com']); + }); + + it('should not duplicate existing sources', () => { + const sources = ["'self'", 'https://example.com']; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(["'self'", 'https://example.com']); + }); + + it('should replace none with new source', () => { + const sources = ["'none'"]; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(['https://example.com']); + }); + + it('should replace none even with other sources present', () => { + const sources = ["'self'", "'none'", "'unsafe-inline'"]; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(["'self'", 'https://example.com', "'unsafe-inline'"]); + }); + + it('should handle empty sources array', () => { + const sources: string[] = []; + const result = addSourceToDirective(sources, 'https://example.com'); + + expect(result).toEqual(['https://example.com']); + }); +}); + +describe('addDomainToCSP', () => { + it('should add domain to specified directives', () => { + const csp = "default-src 'self'; script-src 'self'; img-src 'self'"; + const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']); + + expect(result).toContain('script-src \'self\' https://cdn.example.com'); + expect(result).toContain('img-src \'self\' https://cdn.example.com'); + expect(result).toContain('default-src \'self\''); // unchanged + }); + + it('should not modify directives that do not exist', () => { + const csp = "default-src 'self'"; + const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']); + + expect(result).toBe("default-src 'self'"); + }); + + it('should handle multiple domains being added', () => { + const csp = "script-src 'self'"; + let result = addDomainToCSP(csp, 'https://cdn1.example.com', ['script-src']); + result = addDomainToCSP(result, 'https://cdn2.example.com', ['script-src']); + + expect(result).toBe("script-src 'self' https://cdn1.example.com https://cdn2.example.com"); + }); + + it('should replace none in specified directives', () => { + const csp = "default-src 'self'; script-src 'none'; img-src 'self'"; + const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src']); + + expect(result).toContain('script-src https://cdn.example.com'); + expect(result).toContain('img-src \'self\''); // unchanged + }); +}); \ No newline at end of file diff --git a/src/lib/csp.ts b/src/lib/csp.ts new file mode 100644 index 00000000..bd42baed --- /dev/null +++ b/src/lib/csp.ts @@ -0,0 +1,87 @@ +/** + * Content Security Policy (CSP) utilities for managing and updating CSP directives + */ + +export interface CSPDirectives { + [directive: string]: string[]; +} + +/** + * Parses a CSP string into a structured format + */ +export function parseCSP(csp: string): CSPDirectives { + const directives: CSPDirectives = {}; + + // Split by semicolon and parse each directive + csp.split(';').forEach(directive => { + const trimmed = directive.trim(); + if (!trimmed) return; + + const parts = trimmed.split(/\s+/); + const directiveName = parts[0]; + const sources = parts.slice(1); + + directives[directiveName] = sources; + }); + + return directives; +} + +/** + * Converts CSP directives back to a string format + */ +export function stringifyCSP(directives: CSPDirectives): string { + const directiveStrings: string[] = []; + + Object.entries(directives).forEach(([directiveName, sources]) => { + if (sources.length > 0) { + directiveStrings.push(`${directiveName} ${sources.join(' ')}`); + } else { + directiveStrings.push(directiveName); + } + }); + + return directiveStrings.join('; '); +} + +/** + * Adds a source to a CSP directive, handling special cases + */ +export function addSourceToDirective(sources: string[], newSource: string): string[] { + // Don't add if already present + if (sources.includes(newSource)) { + return sources; + } + + // If 'none' is present, replace it with the new source + if (sources.includes("'none'")) { + const noneIndex = sources.indexOf("'none'"); + const newSources = [...sources]; + newSources[noneIndex] = newSource; + return newSources; + } + + // Add to existing sources + return [...sources, newSource]; +} + +/** + * Updates CSP directives to allow a specific domain for multiple directive types + */ +export function addDomainToCSP( + csp: string, + domain: string, + directiveTypes: string[] +): string { + const directives = parseCSP(csp); + + // Add domain to each relevant directive if it exists + directiveTypes.forEach(directiveName => { + const sources = directives[directiveName]; + if (sources) { + directives[directiveName] = addSourceToDirective(sources, domain); + } + }); + + return stringifyCSP(directives); +} From 97f5481ec7e5256215bbe583fceb66965d469c31 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 2 Oct 2025 20:58:56 +0000 Subject: [PATCH 068/105] Only clear console messages when project actually changes. --- src/components/Shakespeare/PreviewPane.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 3b23828e..3d93a3e1 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -457,6 +457,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o }, [selectedFile, loadFileContent]); // Reset selected file and navigation history when projectId changes + const prevProjectIdRef = useRef(); useEffect(() => { setSelectedFile(null); setFileContent(''); @@ -468,8 +469,11 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o setNavigationHistory(['/']); setHistoryIndex(0); - // Clear console messages for new project - clearErrors(); + // Only clear console messages when projectId actually changes (not on initial mount) + if (prevProjectIdRef.current && prevProjectIdRef.current !== projectId) { + clearErrors(); + } + prevProjectIdRef.current = projectId; }, [projectId, clearErrors]); useEffect(() => { From 0b7f9cd2cbe60f07a75cc2bec1f0f33a3d158c4a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 16:24:03 -0500 Subject: [PATCH 069/105] Update browserlist --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2d331915..e2fec05c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4668,9 +4668,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001716", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001716.tgz", - "integrity": "sha512-49/c1+x3Kwz7ZIWt+4DvK3aMJy9oYXXG6/97JKsnjdCk/6n9vVyWL8NAwVt95Lwt9eigI10Hl782kDfZUUlRXw==", + "version": "1.0.30001746", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001746.tgz", + "integrity": "sha512-eA7Ys/DGw+pnkWWSE/id29f2IcPHVoE8wxtvE5JdvD2V28VTDPy1yEeo11Guz0sJ4ZeGRcm3uaTcAqK1LXaphA==", "dev": true, "funding": [ { From cbf85313af09d186f1459bd297dc8efbfa04e6f8 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:30:12 -0500 Subject: [PATCH 070/105] Enable sourcemap, fix output filenames --- src/lib/build/index.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 8dd0bb96..a424c05b 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -73,6 +73,10 @@ async function bundle( outdir: "/", jsx: "automatic", metafile: true, + sourcemap: true, + entryNames: "[name]-[hash]", + chunkNames: "[name]-[hash]", + assetNames: "[name]-[hash]", plugins: [ shakespearePlugin(), fsPlugin(fs, `${projectPath}/src`), @@ -87,8 +91,8 @@ async function bundle( for (const file of results.outputFiles) { const ext = file.path.split('.').pop(); - const filename = `${file.path.split('/').pop()?.split('.')?.[0] || "chunk"}-${file.hash}.${ext}`; - const entryPoint = results.metafile.outputs[file.path.slice(1)]?.entryPoint?.replace(/^fs:/, ''); + const filename = `${file.path.slice(1)}`; + const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, ''); const script = entryPoint ? entryScripts[entryPoint] : null; if (script) { @@ -106,6 +110,8 @@ async function bundle( style.setAttribute("type", "text/tailwindcss"); style.textContent = file.text; doc.head.appendChild(style); + } else { + dist[filename] = file.contents; } } From d4c775828f45eea31b1b6827253c3f12d3567dee Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:36:42 -0500 Subject: [PATCH 071/105] Fix build tests --- src/lib/build/index.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib/build/index.test.ts b/src/lib/build/index.test.ts index fe2d7ef0..b8f52ac9 100644 --- a/src/lib/build/index.test.ts +++ b/src/lib/build/index.test.ts @@ -9,13 +9,13 @@ vi.mock('../esbuild', () => ({ build: vi.fn(() => ({ outputFiles: [ { - path: '/stdin.js', + path: '/stdin-abc123.js', contents: new Uint8Array([1, 2, 3]), text: '', hash: 'abc123', }, { - path: '/stdin.css', + path: '/stdin-def456.css', contents: new Uint8Array([4, 5, 6]), text: 'body { margin: 0; }', hash: 'def456', @@ -23,10 +23,10 @@ vi.mock('../esbuild', () => ({ ], metafile: { outputs: { - 'stdin.js': { + 'stdin-abc123.js': { entryPoint: 'fs:/test/project/src/main.tsx', }, - 'stdin.css': { + 'stdin-def456.css': { entryPoint: undefined, }, }, From aaf30db257005b54922cb7c107198012330a6724 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:46:08 -0500 Subject: [PATCH 072/105] Add DeepSeek as a preset provider Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/58 --- src/lib/aiProviderPresets.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/lib/aiProviderPresets.ts b/src/lib/aiProviderPresets.ts index 108a2fc9..55cf204e 100644 --- a/src/lib/aiProviderPresets.ts +++ b/src/lib/aiProviderPresets.ts @@ -64,6 +64,13 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [ apiKeysURL: "https://console.x.ai", tosURL: "https://x.ai/legal", }, + { + id: "deepseek", + name: "Deepseek", + baseURL: "https://api.deepseek.com/v1", + apiKeysURL: "https://platform.deepseek.com/api_keys", + tosURL: "https://cdn.deepseek.com/policies/en-US/deepseek-open-platform-terms-of-service.html", + }, ]; // Helper function to get a specific preset by ID From 5f2faaad61920e79a448bd971cda5d29f6a44edc Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:57:36 -0500 Subject: [PATCH 073/105] Fix xAI tool definitions Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/57 --- src/lib/tools/openai-adapter.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/lib/tools/openai-adapter.ts b/src/lib/tools/openai-adapter.ts index 3ae99d7c..e10d2a41 100644 --- a/src/lib/tools/openai-adapter.ts +++ b/src/lib/tools/openai-adapter.ts @@ -16,6 +16,8 @@ export function toolToOpenAI(name: string, tool: Tool): OpenAI if (tool.inputSchema) { functionDef.parameters = zodSchemaToJsonSchema(tool.inputSchema); + } else { + functionDef.parameters = {}; } return { From 388afd0b1675226ce954d44f25d109962ed0441b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 17:59:29 -0500 Subject: [PATCH 074/105] Enable sourcemap in Shakespeare itself --- vite.config.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/vite.config.ts b/vite.config.ts index 7eb55ca5..b8a44cc8 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -13,6 +13,7 @@ export default defineConfig(() => ({ react(), ], build: { + sourcemap: true, rollupOptions: { output: { manualChunks(id) { From 39adaef4c4c6394d54e3182fc396ee4f3094819b Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 18:50:34 +0700 Subject: [PATCH 075/105] while any project session is 'busy', keep the favicon spinning --- src/App.tsx | 16 ++-- src/components/DynamicFavicon.tsx | 151 ++++++++++++++++++++++++++++++ src/hooks/useAnyProjectBusy.ts | 35 +++++++ 3 files changed, 195 insertions(+), 7 deletions(-) create mode 100644 src/components/DynamicFavicon.tsx create mode 100644 src/hooks/useAnyProjectBusy.ts diff --git a/src/App.tsx b/src/App.tsx index 45b189bf..bd3cd3eb 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -19,6 +19,7 @@ import { FSProvider } from '@/components/FSProvider'; import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider'; import { LightningFSAdapter } from '@/lib/LightningFSAdapter'; import { cleanupTmpDirectory } from '@/lib/tmpCleanup'; +import { DynamicFavicon } from '@/components/DynamicFavicon'; import AppRouter from './AppRouter'; @@ -80,13 +81,14 @@ export function App() { - - - - - - - + + + + + + + + diff --git a/src/components/DynamicFavicon.tsx b/src/components/DynamicFavicon.tsx new file mode 100644 index 00000000..8a2af7eb --- /dev/null +++ b/src/components/DynamicFavicon.tsx @@ -0,0 +1,151 @@ +import { useEffect, useRef } from 'react'; +import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy'; + +/** + * Component that dynamically updates the favicon when any project is busy with AI + * Rotates the favicon counter-clockwise when busy + */ +export function DynamicFavicon() { + const isBusy = useAnyProjectBusy(); + const canvasRef = useRef(null); + const animationRef = useRef(null); + const rotationRef = useRef(0); + const originalFaviconRef = useRef(null); + const originalImageRef = useRef(null); + + // Initialize canvas and save original favicon + useEffect(() => { + // Create canvas element for drawing the favicon + if (!canvasRef.current) { + canvasRef.current = document.createElement('canvas'); + canvasRef.current.width = 32; + canvasRef.current.height = 32; + } + + // Store the original favicon URL + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement && !originalFaviconRef.current) { + originalFaviconRef.current = faviconElement.getAttribute('href'); + } + + // Preload the favicon image + if (!originalImageRef.current) { + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.src = originalFaviconRef.current || '/shakespeare.png'; + img.onload = () => { + originalImageRef.current = img; + }; + } + + return () => { + // Restore original favicon on unmount + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } + + // Cancel any ongoing animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + } + }; + }, []); + + // Handle busy state changes + useEffect(() => { + if (!canvasRef.current) return; + + // If busy, start rotation animation + if (isBusy) { + const startRotationAnimation = () => { + if (!canvasRef.current || !originalImageRef.current) { + // If image isn't loaded yet, try again in a moment + setTimeout(startRotationAnimation, 100); + return; + } + + const canvas = canvasRef.current; + const ctx = canvas.getContext('2d'); + if (!ctx) return; + + const img = originalImageRef.current; + + const animate = () => { + if (!ctx || !canvas) return; + + // Clear canvas + ctx.clearRect(0, 0, canvas.width, canvas.height); + + // Save context state + ctx.save(); + + // Translate to center for rotation + ctx.translate(canvas.width / 2, canvas.height / 2); + + // Rotate counter-clockwise + ctx.rotate(-rotationRef.current); + + // Draw the image centered + ctx.drawImage( + img, + -canvas.width / 2, + -canvas.height / 2, + canvas.width, + canvas.height + ); + + // Restore context state + ctx.restore(); + + // Update rotation for next frame (slower rotation) + rotationRef.current += 0.05; + + // Update favicon + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', canvas.toDataURL('image/png')); + } + + // Continue animation + animationRef.current = requestAnimationFrame(animate); + }; + + // Start animation loop + animate(); + }; + + startRotationAnimation(); + } else { + // If not busy, restore original favicon and stop animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } + + // Reset rotation + rotationRef.current = 0; + + // Restore original favicon + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } + } + + return () => { + // Cancel animation on effect cleanup + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } + }; + }, [isBusy]); + + // This component doesn't render anything visible + return null; +} diff --git a/src/hooks/useAnyProjectBusy.ts b/src/hooks/useAnyProjectBusy.ts new file mode 100644 index 00000000..24b3aae6 --- /dev/null +++ b/src/hooks/useAnyProjectBusy.ts @@ -0,0 +1,35 @@ +import { useState, useEffect } from 'react'; +import { useSessionManager } from './useSessionManager'; + +/** + * Hook to check if any project has running AI sessions + * @returns {boolean} True if any project has a running AI session + */ +export function useAnyProjectBusy(): boolean { + const sessionManager = useSessionManager(); + const [anyProjectBusy, setAnyProjectBusy] = useState(false); + + useEffect(() => { + const updateStatus = () => { + const sessions = sessionManager.getAllSessions(); + const hasBusyProject = sessions.some(session => session.isLoading); + setAnyProjectBusy(hasBusyProject); + }; + + // Initial update + updateStatus(); + + // Subscribe to session changes + sessionManager.on('sessionCreated', updateStatus); + sessionManager.on('sessionDeleted', updateStatus); + sessionManager.on('loadingChanged', updateStatus); + + return () => { + sessionManager.off('sessionCreated', updateStatus); + sessionManager.off('sessionDeleted', updateStatus); + sessionManager.off('loadingChanged', updateStatus); + }; + }, [sessionManager]); + + return anyProjectBusy; +} From 7abb0ace5a9662aca79432ca93bd8789ed9ce2ba Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 12:42:13 +0700 Subject: [PATCH 076/105] define lint spec for spaces > tabs and complete vscode/cursor setup for auto linting lint drop over zealous rule --- .vscode/settings.json | 8 +- src/components/DynamicFavicon.tsx | 234 +++++++++++++++--------------- 2 files changed, 123 insertions(+), 119 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 0a770118..0bd0fcd9 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,7 @@ { - "editor.tabSize": 2 -} \ No newline at end of file + "editor.tabSize": 2, + "editor.insertSpaces": true, + "editor.codeActionsOnSave": { + "source.fixAll.eslint": true + } +} diff --git a/src/components/DynamicFavicon.tsx b/src/components/DynamicFavicon.tsx index 8a2af7eb..9e02c0f5 100644 --- a/src/components/DynamicFavicon.tsx +++ b/src/components/DynamicFavicon.tsx @@ -6,146 +6,146 @@ import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy'; * Rotates the favicon counter-clockwise when busy */ export function DynamicFavicon() { - const isBusy = useAnyProjectBusy(); - const canvasRef = useRef(null); - const animationRef = useRef(null); - const rotationRef = useRef(0); - const originalFaviconRef = useRef(null); - const originalImageRef = useRef(null); + const isBusy = useAnyProjectBusy(); + const canvasRef = useRef(null); + const animationRef = useRef(null); + const rotationRef = useRef(0); + const originalFaviconRef = useRef(null); + const originalImageRef = useRef(null); - // Initialize canvas and save original favicon - useEffect(() => { - // Create canvas element for drawing the favicon - if (!canvasRef.current) { - canvasRef.current = document.createElement('canvas'); - canvasRef.current.width = 32; - canvasRef.current.height = 32; - } + // Initialize canvas and save original favicon + useEffect(() => { + // Create canvas element for drawing the favicon + if (!canvasRef.current) { + canvasRef.current = document.createElement('canvas'); + canvasRef.current.width = 32; + canvasRef.current.height = 32; + } - // Store the original favicon URL - const faviconElement = document.querySelector('link[rel="icon"]'); - if (faviconElement && !originalFaviconRef.current) { - originalFaviconRef.current = faviconElement.getAttribute('href'); - } + // Store the original favicon URL + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement && !originalFaviconRef.current) { + originalFaviconRef.current = faviconElement.getAttribute('href'); + } - // Preload the favicon image - if (!originalImageRef.current) { - const img = new Image(); - img.crossOrigin = 'anonymous'; - img.src = originalFaviconRef.current || '/shakespeare.png'; - img.onload = () => { - originalImageRef.current = img; - }; - } + // Preload the favicon image + if (!originalImageRef.current) { + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.src = originalFaviconRef.current || '/shakespeare.png'; + img.onload = () => { + originalImageRef.current = img; + }; + } - return () => { - // Restore original favicon on unmount - if (originalFaviconRef.current) { - const faviconElement = document.querySelector('link[rel="icon"]'); - if (faviconElement) { - faviconElement.setAttribute('href', originalFaviconRef.current); - } - } + return () => { + // Restore original favicon on unmount + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } - // Cancel any ongoing animation - if (animationRef.current !== null) { - cancelAnimationFrame(animationRef.current); - } - }; - }, []); + // Cancel any ongoing animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + } + }; + }, []); - // Handle busy state changes - useEffect(() => { - if (!canvasRef.current) return; + // Handle busy state changes + useEffect(() => { + if (!canvasRef.current) return; - // If busy, start rotation animation - if (isBusy) { - const startRotationAnimation = () => { - if (!canvasRef.current || !originalImageRef.current) { - // If image isn't loaded yet, try again in a moment - setTimeout(startRotationAnimation, 100); - return; - } + // If busy, start rotation animation + if (isBusy) { + const startRotationAnimation = () => { + if (!canvasRef.current || !originalImageRef.current) { + // If image isn't loaded yet, try again in a moment + setTimeout(startRotationAnimation, 100); + return; + } - const canvas = canvasRef.current; - const ctx = canvas.getContext('2d'); - if (!ctx) return; + const canvas = canvasRef.current; + const ctx = canvas.getContext('2d'); + if (!ctx) return; - const img = originalImageRef.current; + const img = originalImageRef.current; - const animate = () => { - if (!ctx || !canvas) return; + const animate = () => { + if (!ctx || !canvas) return; - // Clear canvas - ctx.clearRect(0, 0, canvas.width, canvas.height); + // Clear canvas + ctx.clearRect(0, 0, canvas.width, canvas.height); - // Save context state - ctx.save(); + // Save context state + ctx.save(); - // Translate to center for rotation - ctx.translate(canvas.width / 2, canvas.height / 2); + // Translate to center for rotation + ctx.translate(canvas.width / 2, canvas.height / 2); - // Rotate counter-clockwise - ctx.rotate(-rotationRef.current); + // Rotate counter-clockwise + ctx.rotate(-rotationRef.current); - // Draw the image centered - ctx.drawImage( - img, - -canvas.width / 2, - -canvas.height / 2, - canvas.width, - canvas.height - ); + // Draw the image centered + ctx.drawImage( + img, + -canvas.width / 2, + -canvas.height / 2, + canvas.width, + canvas.height + ); - // Restore context state - ctx.restore(); + // Restore context state + ctx.restore(); - // Update rotation for next frame (slower rotation) - rotationRef.current += 0.05; + // Update rotation for next frame (slower rotation) + rotationRef.current += 0.05; - // Update favicon - const faviconElement = document.querySelector('link[rel="icon"]'); - if (faviconElement) { - faviconElement.setAttribute('href', canvas.toDataURL('image/png')); - } + // Update favicon + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', canvas.toDataURL('image/png')); + } - // Continue animation - animationRef.current = requestAnimationFrame(animate); - }; + // Continue animation + animationRef.current = requestAnimationFrame(animate); + }; - // Start animation loop - animate(); - }; + // Start animation loop + animate(); + }; - startRotationAnimation(); - } else { - // If not busy, restore original favicon and stop animation - if (animationRef.current !== null) { - cancelAnimationFrame(animationRef.current); - animationRef.current = null; - } + startRotationAnimation(); + } else { + // If not busy, restore original favicon and stop animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } - // Reset rotation - rotationRef.current = 0; + // Reset rotation + rotationRef.current = 0; - // Restore original favicon - if (originalFaviconRef.current) { - const faviconElement = document.querySelector('link[rel="icon"]'); - if (faviconElement) { - faviconElement.setAttribute('href', originalFaviconRef.current); - } - } - } + // Restore original favicon + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } + } - return () => { - // Cancel animation on effect cleanup - if (animationRef.current !== null) { - cancelAnimationFrame(animationRef.current); - animationRef.current = null; - } - }; - }, [isBusy]); + return () => { + // Cancel animation on effect cleanup + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } + }; + }, [isBusy]); - // This component doesn't render anything visible - return null; + // This component doesn't render anything visible + return null; } From 3f5667d62a8d3045c7ad0b1deae8171d85229c55 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 15:01:23 +0700 Subject: [PATCH 077/105] warn but don't fail on lint errors --- eslint.config.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/eslint.config.js b/eslint.config.js index 1e1fc7fd..b5b839f5 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -40,6 +40,8 @@ export default tseslint.config( "ignoreRestSiblings": true, }, ], + "indent": ["warn", 2], + "no-tabs": "warn", "custom/no-placeholder-comments": "error", "no-warning-comments": [ "error", From b419f88571c5bc9921288f8a72dfaf7faec19718 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 15:01:30 +0700 Subject: [PATCH 078/105] lint --- src/hooks/useAnyProjectBusy.ts | 42 +++++++++++++++++----------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/hooks/useAnyProjectBusy.ts b/src/hooks/useAnyProjectBusy.ts index 24b3aae6..1ff33004 100644 --- a/src/hooks/useAnyProjectBusy.ts +++ b/src/hooks/useAnyProjectBusy.ts @@ -6,30 +6,30 @@ import { useSessionManager } from './useSessionManager'; * @returns {boolean} True if any project has a running AI session */ export function useAnyProjectBusy(): boolean { - const sessionManager = useSessionManager(); - const [anyProjectBusy, setAnyProjectBusy] = useState(false); + const sessionManager = useSessionManager(); + const [anyProjectBusy, setAnyProjectBusy] = useState(false); - useEffect(() => { - const updateStatus = () => { - const sessions = sessionManager.getAllSessions(); - const hasBusyProject = sessions.some(session => session.isLoading); - setAnyProjectBusy(hasBusyProject); - }; + useEffect(() => { + const updateStatus = () => { + const sessions = sessionManager.getAllSessions(); + const hasBusyProject = sessions.some(session => session.isLoading); + setAnyProjectBusy(hasBusyProject); + }; - // Initial update - updateStatus(); + // Initial update + updateStatus(); - // Subscribe to session changes - sessionManager.on('sessionCreated', updateStatus); - sessionManager.on('sessionDeleted', updateStatus); - sessionManager.on('loadingChanged', updateStatus); + // Subscribe to session changes + sessionManager.on('sessionCreated', updateStatus); + sessionManager.on('sessionDeleted', updateStatus); + sessionManager.on('loadingChanged', updateStatus); - return () => { - sessionManager.off('sessionCreated', updateStatus); - sessionManager.off('sessionDeleted', updateStatus); - sessionManager.off('loadingChanged', updateStatus); - }; - }, [sessionManager]); + return () => { + sessionManager.off('sessionCreated', updateStatus); + sessionManager.off('sessionDeleted', updateStatus); + sessionManager.off('loadingChanged', updateStatus); + }; + }, [sessionManager]); - return anyProjectBusy; + return anyProjectBusy; } From c48288f9e6e17fe437141e34fb7197f9eec8101e Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 16:27:46 +0700 Subject: [PATCH 079/105] adapt console error type to simplify quillys understand --- src/lib/tools/ReadConsoleMessagesTool.ts | 59 ++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index 1f8e5904..c7624be2 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -10,6 +10,65 @@ export interface ReadConsoleMessagesParams { * AI tool for reading console messages from the project preview. * This tool allows AI assistants to access console logs for debugging assistance. */ +export class ProjectPreviewConsoleError extends Error { + public readonly code = 'console_error' as const; + public readonly logs: ConsoleMessage[]; + + constructor(message: string, logs: ConsoleMessage[]) { + super(message); + this.name = 'ProjectPreviewConsoleError'; + this.logs = logs; + } +} + +// Simple global console messages storage +const consoleMessages: ConsoleMessage[] = []; +const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = []; + +export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { + const consoleMessage: ConsoleMessage = { + level, + message, + }; + + consoleMessages.push(consoleMessage); + + // If this is an error, notify listeners + if (level === 'error') { + const error = new ProjectPreviewConsoleError( + `Console error detected: ${message}`, + consoleMessages.filter(msg => msg.level === 'error') + ); + + errorListeners.forEach(listener => { + try { + listener(error); + } catch (err) { + console.warn('Error listener failed:', err); + } + }); + } +}; + +export const getConsoleMessages = (): ConsoleMessage[] => { + return [...consoleMessages]; +}; + +export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { + errorListeners.push(listener); +}; + +export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { + const index = errorListeners.indexOf(listener); + if (index > -1) { + errorListeners.splice(index, 1); + } +}; + +export const clearConsoleMessages = () => { + consoleMessages.length = 0; +}; + export class ReadConsoleMessagesTool implements Tool { async execute(params: ReadConsoleMessagesParams): Promise { const { filter = 'all', limit } = params; From 8b5cf72356c772bcf8844b36c0ffb6c42e33752c Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 16:29:02 +0700 Subject: [PATCH 080/105] define and surface an error for malformed tool responses --- src/lib/SessionManager.ts | 35 ++++++++++++++++++++++-- src/lib/errors/MalformedToolCallError.ts | 22 +++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 src/lib/errors/MalformedToolCallError.ts diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 22f416c1..7f9431ee 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -8,6 +8,7 @@ import type { NUser } from '@nostrify/react/login'; import type { AIProvider } from '@/contexts/AISettingsContext'; import { makeSystemPrompt } from './system'; import { NostrMetadata } from '@nostrify/nostrify'; +import { MalformedToolCallError } from './errors/MalformedToolCallError'; export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | { role: 'assistant'; @@ -283,7 +284,7 @@ export class SessionManager { // LiteLLM, Z.ai, etc. use 'reasoning_content' if (delta && 'reasoning_content' in delta && typeof delta.reasoning_content === 'string') { reasoningContent = delta.reasoning_content; - // ollama uses 'reasoning' + // ollama uses 'reasoning' } else if (delta && 'reasoning' in delta && typeof delta.reasoning === 'string') { reasoningContent = delta.reasoning; } @@ -336,10 +337,20 @@ export class SessionManager { } } - // Fix tool calls with empty arguments + // Fix tool calls with empty arguments or names for (const toolCall of accumulatedToolCalls) { if (toolCall.type === 'function') { toolCall.function.arguments = toolCall.function.arguments || '{}'; + + // Log and handle empty tool names (malformed AI response) + if (!toolCall.function.name || toolCall.function.name.trim() === '') { + console.error('Malformed tool call detected: missing function name', { + projectId, + providerModel, + toolCallId: toolCall.id, + toolCall: JSON.stringify(toolCall), + }); + } } } @@ -366,10 +377,28 @@ export class SessionManager { const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall; const toolName = functionToolCall.function.name; + + // Check for missing/empty tool name (malformed AI response) + if (!toolName || toolName.trim() === '') { + // Add detailed technical error to tool message for debugging + await this.addToolMessage( + projectId, + functionToolCall.id, + `Error: Malformed tool call received from AI provider (missing function name). This is likely a provider-specific issue. Tool call ID: ${functionToolCall.id}` + ); + + // Throw custom error to trigger Quilly UI with user-friendly message + throw new MalformedToolCallError( + 'The AI provider sent an incomplete response. This may be due to a network interruption or provider issue.', + functionToolCall.id, + providerModel + ); + } + const tool = session.customTools[toolName]; if (!tool) { - await this.addToolMessage(projectId, functionToolCall.id, `Tool ${toolName} not found`); + await this.addToolMessage(projectId, functionToolCall.id, `Tool "${toolName}" not found`); continue; } diff --git a/src/lib/errors/MalformedToolCallError.ts b/src/lib/errors/MalformedToolCallError.ts new file mode 100644 index 00000000..d2ef93b7 --- /dev/null +++ b/src/lib/errors/MalformedToolCallError.ts @@ -0,0 +1,22 @@ +/** + * Error thrown when an AI provider sends a malformed tool call response + * (e.g., missing function name in the streaming response) + */ +export class MalformedToolCallError extends Error { + public readonly code = 'malformed_tool_call' as const; + public readonly toolCallId: string; + public readonly providerModel: string; + + constructor(message: string, toolCallId: string, providerModel: string) { + super(message); + this.name = 'MalformedToolCallError'; + this.toolCallId = toolCallId; + this.providerModel = providerModel; + + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, MalformedToolCallError); + } + } +} + From 1416c5d0179c3be25a5dd8f7bbff1de208d6a24c Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 16:29:35 +0700 Subject: [PATCH 081/105] let quilly opine on tool call errors, and streamline handling errors --- src/components/Quilly.tsx | 166 ++++++++++++++++++++------------------ 1 file changed, 88 insertions(+), 78 deletions(-) diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index adb087b7..c3342b28 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -1,4 +1,3 @@ -import OpenAI from 'openai'; import { useNavigate } from 'react-router-dom'; import { X } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -44,95 +43,106 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq const [showCreditsDialog, setShowCreditsDialog] = useState(false); const renderBody = (error: Error): ErrorBody => { - // Handle Project Preview Console Errors - if (error instanceof ProjectPreviewConsoleError) { + // Handle errors with a code property (custom errors and API errors) + const errorCode = (error as Error & { code?: string }).code; + + if (!errorCode) { + // Generic error fallback for errors without a code property return { - message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', - action: { - label: 'Help fix errors', - onClick: () => { - onRequestConsoleErrorHelp?.(error); - onDismiss(); - }, - }, + message: error.message + ? `AI service error: ${error.message}` + : 'Sorry, I encountered an unexpected error. Please try again.', }; } - // Handle OpenAI API errors with specific error codes - if (error instanceof OpenAI.APIError) { - switch (error.code) { - case 'invalid_api_key': - case 'invalid_request_error': + switch (errorCode) { + // Application-specific error codes + case 'console_error': + return { + message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', + action: { + label: 'Help fix errors', + onClick: () => { + onRequestConsoleErrorHelp?.(error as ProjectPreviewConsoleError); + onDismiss(); + }, + }, + }; + + case 'malformed_tool_call': + return { + message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.', + action: { + label: 'Change model', + onClick: onOpenModelSelector, + }, + }; + + // OpenAI API error codes + case 'invalid_api_key': + case 'invalid_request_error': + return { + message: 'Authentication error: Please check your API key in AI settings.', + action: { + label: 'Check API key', + onClick: () => navigate('/settings/ai'), + } + }; + + case 'insufficient_quota': { + if (credits.data) { return { - message: 'Authentication error: Please check your API key in AI settings.', + message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, action: { - label: 'Check API key', + label: 'Add credits', + onClick: () => setShowCreditsDialog(true), + } + }; + } else { + return { + message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', + action: { + label: 'Check AI settings', onClick: () => navigate('/settings/ai'), } }; - - case 'insufficient_quota': { - if (credits.data) { - return { - message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, - action: { - label: 'Add credits', - onClick: () => setShowCreditsDialog(true), - } - }; - } else { - return { - message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', - action: { - label: 'Check AI settings', - onClick: () => navigate('/settings/ai'), - } - }; - } } - - case 'rate_limit_exceeded': - return { - message: 'Rate limit exceeded. Please wait a moment before trying again.', - }; - - case 'model_not_found': - return { - message: 'The selected AI model is not available. Please choose a different model.', - action: { - label: 'Choose model', - onClick: onOpenModelSelector, - }, - }; - - case 'context_length_exceeded': - return { - 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: { - label: 'New chat', - onClick: onNewChat, - }, - }; - - case 'server_error': - case 'service_unavailable': - return { - message: 'The AI service is temporarily unavailable. Please try again in a moment.', - }; - - default: - return { - message: `AI service error: ${error.message}`, - }; } - } - // Default fallback - return { - message: error.message - ? `AI service error: ${error.message}` - : 'Sorry, I encountered an unexpected error. Please try again.', - }; + case 'rate_limit_exceeded': + return { + message: 'Rate limit exceeded. Please wait a moment before trying again.', + }; + + case 'model_not_found': + return { + message: 'The selected AI model is not available. Please choose a different model.', + action: { + label: 'Choose model', + onClick: onOpenModelSelector, + }, + }; + + case 'context_length_exceeded': + return { + 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: { + label: 'New chat', + onClick: onNewChat, + }, + }; + + case 'server_error': + case 'service_unavailable': + return { + message: 'The AI service is temporarily unavailable. Please try again in a moment.', + }; + + default: + return { + message: `AI service error: ${error.message}`, + }; + } }; const { message, action } = renderBody(error); From d2971fcdb9333e51ebf785c694e67c73a4c1f42e Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 16:55:32 +0700 Subject: [PATCH 082/105] test quilly renders the error --- src/components/Quilly.test.tsx | 80 ++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/components/Quilly.test.tsx diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx new file mode 100644 index 00000000..2df8be2a --- /dev/null +++ b/src/components/Quilly.test.tsx @@ -0,0 +1,80 @@ +import { render, screen } from '@testing-library/react'; +import { describe, it, expect, vi } from 'vitest'; +import { Quilly } from './Quilly'; +import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError'; +import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; + +// Mock all required hooks and components +vi.mock('@/hooks/useAISettings', () => ({ + useAISettings: () => ({ + settings: { + providers: [] + } + }) +})); + +vi.mock('@/hooks/useAICredits', () => ({ + useAICredits: () => ({ + data: null + }) +})); + +vi.mock('react-router-dom', () => ({ + useNavigate: () => vi.fn() +})); + +// Mock CreditsDialog to avoid NostrProvider dependency +vi.mock('./CreditsDialog', () => ({ + CreditsDialog: () => null +})); + +describe('Quilly', () => { + const defaultProps = { + error: new Error('Generic error'), + onDismiss: vi.fn(), + onNewChat: vi.fn(), + onOpenModelSelector: vi.fn(), + providerModel: 'test/model' + }; + + it('renders generic error message', () => { + render(); + + expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument(); + }); + + it('renders correctly for malformed tool call errors', () => { + const error = new MalformedToolCallError( + 'The AI provider sent an incomplete response.', + 'call_abc123', + 'test/model' + ); + + render( + + ); + + expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument(); + expect(screen.getByText(/Change model/)).toBeInTheDocument(); + }); + + it('renders correctly for console errors', () => { + const error = new ProjectPreviewConsoleError( + 'Console error', + [] + ); + + render( + + ); + + expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument(); + expect(screen.getByText(/Help fix errors/)).toBeInTheDocument(); + }); +}); From 4ebca7f077de5f53424972dfd1acdc6e4e465554 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 15:37:50 +0700 Subject: [PATCH 083/105] lint --- src/components/Quilly.test.tsx | 100 ++++++++-------- src/components/Quilly.tsx | 142 +++++++++++------------ src/lib/errors/MalformedToolCallError.ts | 26 ++--- 3 files changed, 134 insertions(+), 134 deletions(-) diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx index 2df8be2a..dfad2479 100644 --- a/src/components/Quilly.test.tsx +++ b/src/components/Quilly.test.tsx @@ -6,75 +6,75 @@ import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool' // Mock all required hooks and components vi.mock('@/hooks/useAISettings', () => ({ - useAISettings: () => ({ - settings: { - providers: [] - } - }) + useAISettings: () => ({ + settings: { + providers: [] + } + }) })); vi.mock('@/hooks/useAICredits', () => ({ - useAICredits: () => ({ - data: null - }) + useAICredits: () => ({ + data: null + }) })); vi.mock('react-router-dom', () => ({ - useNavigate: () => vi.fn() + useNavigate: () => vi.fn() })); // Mock CreditsDialog to avoid NostrProvider dependency vi.mock('./CreditsDialog', () => ({ - CreditsDialog: () => null + CreditsDialog: () => null })); describe('Quilly', () => { - const defaultProps = { - error: new Error('Generic error'), - onDismiss: vi.fn(), - onNewChat: vi.fn(), - onOpenModelSelector: vi.fn(), - providerModel: 'test/model' - }; + const defaultProps = { + error: new Error('Generic error'), + onDismiss: vi.fn(), + onNewChat: vi.fn(), + onOpenModelSelector: vi.fn(), + providerModel: 'test/model' + }; - it('renders generic error message', () => { - render(); + it('renders generic error message', () => { + render(); - expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument(); - }); + expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument(); + }); - it('renders correctly for malformed tool call errors', () => { - const error = new MalformedToolCallError( - 'The AI provider sent an incomplete response.', - 'call_abc123', - 'test/model' - ); + it('renders correctly for malformed tool call errors', () => { + const error = new MalformedToolCallError( + 'The AI provider sent an incomplete response.', + 'call_abc123', + 'test/model' + ); - render( - - ); + render( + + ); - expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument(); - expect(screen.getByText(/Change model/)).toBeInTheDocument(); - }); + expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument(); + expect(screen.getByText(/Change model/)).toBeInTheDocument(); + }); - it('renders correctly for console errors', () => { - const error = new ProjectPreviewConsoleError( - 'Console error', - [] - ); + it('renders correctly for console errors', () => { + const error = new ProjectPreviewConsoleError( + 'Console error', + [] + ); - render( - - ); + render( + + ); - expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument(); - expect(screen.getByText(/Help fix errors/)).toBeInTheDocument(); - }); + expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument(); + expect(screen.getByText(/Help fix errors/)).toBeInTheDocument(); + }); }); diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index c3342b28..248274b0 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -56,92 +56,92 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq } switch (errorCode) { - // Application-specific error codes - case 'console_error': - return { - message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', - action: { - label: 'Help fix errors', - onClick: () => { - onRequestConsoleErrorHelp?.(error as ProjectPreviewConsoleError); - onDismiss(); - }, + // Application-specific error codes + case 'console_error': + return { + message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', + action: { + label: 'Help fix errors', + onClick: () => { + onRequestConsoleErrorHelp?.(error as ProjectPreviewConsoleError); + onDismiss(); }, - }; + }, + }; - case 'malformed_tool_call': - return { - message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.', - action: { - label: 'Change model', - onClick: onOpenModelSelector, - }, - }; + case 'malformed_tool_call': + return { + message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.', + action: { + label: 'Change model', + onClick: onOpenModelSelector, + }, + }; // OpenAI API error codes - case 'invalid_api_key': - case 'invalid_request_error': + case 'invalid_api_key': + case 'invalid_request_error': + return { + message: 'Authentication error: Please check your API key in AI settings.', + action: { + label: 'Check API key', + onClick: () => navigate('/settings/ai'), + } + }; + + case 'insufficient_quota': { + if (credits.data) { return { - message: 'Authentication error: Please check your API key in AI settings.', + message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, action: { - label: 'Check API key', + label: 'Add credits', + onClick: () => setShowCreditsDialog(true), + } + }; + } else { + return { + message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', + action: { + label: 'Check AI settings', onClick: () => navigate('/settings/ai'), } }; - - case 'insufficient_quota': { - if (credits.data) { - return { - message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, - action: { - label: 'Add credits', - onClick: () => setShowCreditsDialog(true), - } - }; - } else { - return { - message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', - action: { - label: 'Check AI settings', - onClick: () => navigate('/settings/ai'), - } - }; - } } + } - case 'rate_limit_exceeded': - return { - message: 'Rate limit exceeded. Please wait a moment before trying again.', - }; + case 'rate_limit_exceeded': + return { + message: 'Rate limit exceeded. Please wait a moment before trying again.', + }; - case 'model_not_found': - return { - message: 'The selected AI model is not available. Please choose a different model.', - action: { - label: 'Choose model', - onClick: onOpenModelSelector, - }, - }; + case 'model_not_found': + return { + message: 'The selected AI model is not available. Please choose a different model.', + action: { + label: 'Choose model', + onClick: onOpenModelSelector, + }, + }; - case 'context_length_exceeded': - return { - 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: { - label: 'New chat', - onClick: onNewChat, - }, - }; + case 'context_length_exceeded': + return { + 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: { + label: 'New chat', + onClick: onNewChat, + }, + }; - case 'server_error': - case 'service_unavailable': - return { - message: 'The AI service is temporarily unavailable. Please try again in a moment.', - }; + case 'server_error': + case 'service_unavailable': + return { + message: 'The AI service is temporarily unavailable. Please try again in a moment.', + }; - default: - return { - message: `AI service error: ${error.message}`, - }; + default: + return { + message: `AI service error: ${error.message}`, + }; } }; diff --git a/src/lib/errors/MalformedToolCallError.ts b/src/lib/errors/MalformedToolCallError.ts index d2ef93b7..1bd79d89 100644 --- a/src/lib/errors/MalformedToolCallError.ts +++ b/src/lib/errors/MalformedToolCallError.ts @@ -3,20 +3,20 @@ * (e.g., missing function name in the streaming response) */ export class MalformedToolCallError extends Error { - public readonly code = 'malformed_tool_call' as const; - public readonly toolCallId: string; - public readonly providerModel: string; + public readonly code = 'malformed_tool_call' as const; + public readonly toolCallId: string; + public readonly providerModel: string; - constructor(message: string, toolCallId: string, providerModel: string) { - super(message); - this.name = 'MalformedToolCallError'; - this.toolCallId = toolCallId; - this.providerModel = providerModel; + constructor(message: string, toolCallId: string, providerModel: string) { + super(message); + this.name = 'MalformedToolCallError'; + this.toolCallId = toolCallId; + this.providerModel = providerModel; - // Maintains proper stack trace for where our error was thrown (only available on V8) - if (Error.captureStackTrace) { - Error.captureStackTrace(this, MalformedToolCallError); - } - } + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, MalformedToolCallError); + } + } } From 76979c615098e1c0af1566c252f4fb27289d67d6 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 16:03:09 +0700 Subject: [PATCH 084/105] revert to handle individual error types explicitly ++ ++ ++ --- src/components/Quilly.tsx | 155 +++++++++++++++++++------------------- 1 file changed, 78 insertions(+), 77 deletions(-) diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index 248274b0..a951d6ef 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -1,3 +1,4 @@ +import OpenAI from 'openai'; import { useNavigate } from 'react-router-dom'; import { X } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -8,6 +9,7 @@ import { useAICredits } from '@/hooks/useAICredits'; import { CreditsDialog } from './CreditsDialog'; import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { useState } from 'react'; +import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError'; export interface QuillyProps { error: Error; @@ -43,33 +45,21 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq const [showCreditsDialog, setShowCreditsDialog] = useState(false); const renderBody = (error: Error): ErrorBody => { - // Handle errors with a code property (custom errors and API errors) - const errorCode = (error as Error & { code?: string }).code; - - if (!errorCode) { - // Generic error fallback for errors without a code property - return { - message: error.message - ? `AI service error: ${error.message}` - : 'Sorry, I encountered an unexpected error. Please try again.', - }; - } - - switch (errorCode) { - // Application-specific error codes - case 'console_error': + // Handle Project Preview Console Errors + if (error instanceof ProjectPreviewConsoleError) { return { message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', action: { label: 'Help fix errors', onClick: () => { - onRequestConsoleErrorHelp?.(error as ProjectPreviewConsoleError); + onRequestConsoleErrorHelp?.(error); onDismiss(); }, }, }; + } - case 'malformed_tool_call': + if (error instanceof MalformedToolCallError) { return { message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.', action: { @@ -77,72 +67,83 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq onClick: onOpenModelSelector, }, }; + } - // OpenAI API error codes - case 'invalid_api_key': - case 'invalid_request_error': - return { - message: 'Authentication error: Please check your API key in AI settings.', - action: { - label: 'Check API key', - onClick: () => navigate('/settings/ai'), + // Handle OpenAI API errors with specific error codes + if (error instanceof OpenAI.APIError) { + switch (error.code) { + case 'invalid_api_key': + case 'invalid_request_error': + return { + message: 'Authentication error: Please check your API key in AI settings.', + action: { + label: 'Check API key', + onClick: () => navigate('/settings/ai'), + } + }; + + case 'insufficient_quota': { + if (credits.data) { + return { + message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, + action: { + label: 'Add credits', + onClick: () => setShowCreditsDialog(true), + } + }; + } else { + return { + message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', + action: { + label: 'Check AI settings', + onClick: () => navigate('/settings/ai'), + } + }; + } } - }; - case 'insufficient_quota': { - if (credits.data) { - return { - message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, - action: { - label: 'Add credits', - onClick: () => setShowCreditsDialog(true), - } - }; - } else { - return { - message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', - action: { - label: 'Check AI settings', - onClick: () => navigate('/settings/ai'), - } - }; + case 'rate_limit_exceeded': + return { + message: 'Rate limit exceeded. Please wait a moment before trying again.', + }; + + case 'model_not_found': + return { + message: 'The selected AI model is not available. Please choose a different model.', + action: { + label: 'Choose model', + onClick: onOpenModelSelector, + }, + }; + + case 'context_length_exceeded': + return { + 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: { + label: 'New chat', + onClick: onNewChat, + }, + }; + + case 'server_error': + case 'service_unavailable': + return { + message: 'The AI service is temporarily unavailable. Please try again in a moment.', + }; + + default: + return { + message: `AI service error: ${error.message}`, + }; } } - case 'rate_limit_exceeded': - return { - message: 'Rate limit exceeded. Please wait a moment before trying again.', - }; - - case 'model_not_found': - return { - message: 'The selected AI model is not available. Please choose a different model.', - action: { - label: 'Choose model', - onClick: onOpenModelSelector, - }, - }; - - case 'context_length_exceeded': - return { - 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: { - label: 'New chat', - onClick: onNewChat, - }, - }; - - case 'server_error': - case 'service_unavailable': - return { - message: 'The AI service is temporarily unavailable. Please try again in a moment.', - }; - - default: - return { - message: `AI service error: ${error.message}`, - }; - } + // Default fallback + return { + message: error.message + ? `AI service error: ${error.message}` + : 'Sorry, I encountered an unexpected error. Please try again.', + }; }; const { message, action } = renderBody(error); From 1eebef173f41357216dbb6a86ffc41aaa936d61e Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 16:21:43 +0700 Subject: [PATCH 085/105] merge --- src/lib/tools/ReadConsoleMessagesTool.ts | 59 ------------------------ 1 file changed, 59 deletions(-) diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index c7624be2..1f8e5904 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -10,65 +10,6 @@ export interface ReadConsoleMessagesParams { * AI tool for reading console messages from the project preview. * This tool allows AI assistants to access console logs for debugging assistance. */ -export class ProjectPreviewConsoleError extends Error { - public readonly code = 'console_error' as const; - public readonly logs: ConsoleMessage[]; - - constructor(message: string, logs: ConsoleMessage[]) { - super(message); - this.name = 'ProjectPreviewConsoleError'; - this.logs = logs; - } -} - -// Simple global console messages storage -const consoleMessages: ConsoleMessage[] = []; -const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = []; - -export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { - const consoleMessage: ConsoleMessage = { - level, - message, - }; - - consoleMessages.push(consoleMessage); - - // If this is an error, notify listeners - if (level === 'error') { - const error = new ProjectPreviewConsoleError( - `Console error detected: ${message}`, - consoleMessages.filter(msg => msg.level === 'error') - ); - - errorListeners.forEach(listener => { - try { - listener(error); - } catch (err) { - console.warn('Error listener failed:', err); - } - }); - } -}; - -export const getConsoleMessages = (): ConsoleMessage[] => { - return [...consoleMessages]; -}; - -export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - errorListeners.push(listener); -}; - -export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - const index = errorListeners.indexOf(listener); - if (index > -1) { - errorListeners.splice(index, 1); - } -}; - -export const clearConsoleMessages = () => { - consoleMessages.length = 0; -}; - export class ReadConsoleMessagesTool implements Tool { async execute(params: ReadConsoleMessagesParams): Promise { const { filter = 'all', limit } = params; From 2d8d5aa7289efe789e2721c206c4499bf054cf30 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 17:41:32 +0700 Subject: [PATCH 086/105] fix tests --- src/components/Quilly.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx index dfad2479..59d388e1 100644 --- a/src/components/Quilly.test.tsx +++ b/src/components/Quilly.test.tsx @@ -2,7 +2,7 @@ import { render, screen } from '@testing-library/react'; import { describe, it, expect, vi } from 'vitest'; import { Quilly } from './Quilly'; import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError'; -import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; // Mock all required hooks and components vi.mock('@/hooks/useAISettings', () => ({ From a4c0498e5bc54556f8b76eba86aa0b8ebb13df4f Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 3 Oct 2025 13:04:10 -0500 Subject: [PATCH 087/105] Send { type: "object" } tool parameters when we don't care about the input Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/60 --- src/lib/tools/openai-adapter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/tools/openai-adapter.ts b/src/lib/tools/openai-adapter.ts index e10d2a41..b485e9fb 100644 --- a/src/lib/tools/openai-adapter.ts +++ b/src/lib/tools/openai-adapter.ts @@ -17,7 +17,7 @@ export function toolToOpenAI(name: string, tool: Tool): OpenAI if (tool.inputSchema) { functionDef.parameters = zodSchemaToJsonSchema(tool.inputSchema); } else { - functionDef.parameters = {}; + functionDef.parameters = { type: "object" }; } return { From abecdaa5cc94fdd862bd39c7c1de6ee1611961a3 Mon Sep 17 00:00:00 2001 From: sam Date: Sat, 4 Oct 2025 07:13:38 +0700 Subject: [PATCH 088/105] git commit, support -am flag --- src/lib/commands/git/commit.ts | 54 ++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/src/lib/commands/git/commit.ts b/src/lib/commands/git/commit.ts index 073aed05..f928767f 100644 --- a/src/lib/commands/git/commit.ts +++ b/src/lib/commands/git/commit.ts @@ -7,7 +7,7 @@ import type { Git } from "../../git"; export class GitCommitCommand implements GitSubcommand { name = 'commit'; description = 'Record changes to the repository'; - usage = 'git commit [-m ] [--amend] [--allow-empty]'; + usage = 'git commit [-m ] [-a | --all] [-am ] [--amend] [--allow-empty]'; private git: Git; private fs: JSRuntimeFS; @@ -33,6 +33,11 @@ export class GitCommitCommand implements GitSubcommand { if (!message && !options.amend) { return createErrorResult('Aborting commit due to empty commit message.'); } + + // If -a flag is provided, stage all tracked files with modifications + if (options.addAll) { + await this.stageTrackedChanges(); + } // Get current status const statusMatrix = await this.git.statusMatrix({ @@ -169,11 +174,46 @@ export class GitCommitCommand implements GitSubcommand { } } + /** + * Stage all tracked files with modifications + * This is used when the -a flag is provided + */ + private async stageTrackedChanges(): Promise { + try { + // Get the status matrix + const statusMatrix = await this.git.statusMatrix({ + dir: this.pwd, + }); + + // Process each file based on its status + for (const [filepath, headStatus, workdirStatus] of statusMatrix) { + // Only process tracked files (headStatus === 1) with changes + if (headStatus === 1 && workdirStatus !== headStatus) { + if (workdirStatus === 0) { + // File was deleted, use remove + await this.git.remove({ + dir: this.pwd, + filepath, + }); + } else { + // File was modified, use add + await this.git.add({ + dir: this.pwd, + filepath, + }); + } + } + } + } catch (error) { + throw new Error(`Failed to stage tracked changes: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + private parseArgs(args: string[]): { - options: { amend: boolean; allowEmpty: boolean }; + options: { amend: boolean; allowEmpty: boolean; addAll: boolean }; message?: string } { - const options = { amend: false, allowEmpty: false }; + const options = { amend: false, allowEmpty: false, addAll: false }; let message: string | undefined; for (let i = 0; i < args.length; i++) { @@ -192,6 +232,14 @@ export class GitCommitCommand implements GitSubcommand { options.amend = true; } else if (arg === '--allow-empty') { options.allowEmpty = true; + } else if (arg === '-a' || arg === '--all') { + options.addAll = true; + } else if (arg === '-am') { + options.addAll = true; + if (i + 1 < args.length) { + message = args[i + 1]; + i++; // Skip next argument as it's the message + } } } From 83b4fe54c77328fde6a60016b72b66cad6db7f69 Mon Sep 17 00:00:00 2001 From: sam Date: Sat, 4 Oct 2025 07:55:27 +0700 Subject: [PATCH 089/105] test commit command --- src/lib/commands/git/commit.test.ts | 230 ++++++++++++++++++++++++++++ 1 file changed, 230 insertions(+) create mode 100644 src/lib/commands/git/commit.test.ts diff --git a/src/lib/commands/git/commit.test.ts b/src/lib/commands/git/commit.test.ts new file mode 100644 index 00000000..9f2d941a --- /dev/null +++ b/src/lib/commands/git/commit.test.ts @@ -0,0 +1,230 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { GitCommitCommand } from './commit'; +import type { Git } from '../../git'; +import type { JSRuntimeFS } from '../../JSRuntime'; + +describe('GitCommitCommand', () => { + let commitCommand: GitCommitCommand; + let mockGit: Partial; + let mockFS: Partial; + const mockPwd = '/projects/test'; + + beforeEach(() => { + // Mock the filesystem + mockFS = { + stat: vi.fn().mockResolvedValue({}), + }; + + // Mock Git methods + mockGit = { + statusMatrix: vi.fn().mockResolvedValue([ + // filepath, HEAD status, workdir status, stage status + ['file1.txt', 1, 2, 1], // modified in workdir + ['file2.txt', 1, 1, 2], // modified in index + ['file3.txt', 0, 2, 2], // new file + ['file4.txt', 1, 0, 1], // deleted file + ]), + + currentBranch: vi.fn().mockResolvedValue('main'), + + resolveRef: vi.fn().mockResolvedValue('headcommit'), + + log: vi.fn().mockResolvedValue([ + { + oid: 'headcommit', + commit: { + message: 'Previous commit', + parent: ['parentcommit'], + tree: 'tree1', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1600000000, + }, + }, + }, + { + oid: 'parentcommit', + commit: { + message: 'Parent commit', + parent: [], + tree: 'tree2', + author: { + name: 'Test User', + email: 'test@example.com', + timestamp: 1599000000, + }, + }, + }, + ]), + + getConfig: vi.fn().mockImplementation(({ path }) => { + if (path === 'user.name') return Promise.resolve('Test User'); + if (path === 'user.email') return Promise.resolve('test@example.com'); + return Promise.resolve(null); + }), + + commit: vi.fn().mockResolvedValue('newcommit'), + + add: vi.fn().mockResolvedValue(undefined), + + remove: vi.fn().mockResolvedValue(undefined), + }; + + // Create the command instance with mocks + commitCommand = new GitCommitCommand({ + git: mockGit as Git, + fs: mockFS as JSRuntimeFS, + pwd: mockPwd, + }); + }); + + it('should commit with a message', async () => { + const result = await commitCommand.execute(['-m', 'Test commit']); + + expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({ + dir: mockPwd, + message: 'Test commit', + })); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Test commit'); + }); + + it('should fail without a message', async () => { + const result = await commitCommand.execute([]); + + expect(mockGit.commit).not.toHaveBeenCalled(); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain('Aborting commit due to empty commit message'); + }); + + it('should handle --amend flag', async () => { + const result = await commitCommand.execute(['--amend', '-m', 'Amended commit']); + + expect(mockGit.log).toHaveBeenCalledWith({ + dir: mockPwd, + depth: 2, + }); + + expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({ + dir: mockPwd, + message: 'Amended commit', + parent: ['parentcommit'], + })); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Amended commit'); + }); + + it('should handle --amend flag without message', async () => { + const result = await commitCommand.execute(['--amend']); + + expect(mockGit.log).toHaveBeenCalledWith({ + dir: mockPwd, + depth: 1, + }); + + expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({ + dir: mockPwd, + message: 'Previous commit', + })); + + expect(result.exitCode).toBe(0); + }); + + it('should handle -a flag to stage all tracked modified files', async () => { + const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage']); + + // Should call add for the modified tracked file + expect(mockGit.add).toHaveBeenCalledWith({ + dir: mockPwd, + filepath: 'file1.txt', + }); + + // Should not call add for already staged files + expect(mockGit.add).not.toHaveBeenCalledWith({ + dir: mockPwd, + filepath: 'file2.txt', + }); + + // Should call remove for deleted files + expect(mockGit.remove).toHaveBeenCalledWith({ + dir: mockPwd, + filepath: 'file4.txt', + }); + + expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({ + dir: mockPwd, + message: 'Commit with auto-stage', + })); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Commit with auto-stage'); + }); + + it('should handle -am flag for combined auto-stage and message', async () => { + const result = await commitCommand.execute(['-am', 'Combined flag commit']); + + // Should call add for the modified tracked file + expect(mockGit.add).toHaveBeenCalledWith({ + dir: mockPwd, + filepath: 'file1.txt', + }); + + // Should call remove for deleted files + expect(mockGit.remove).toHaveBeenCalledWith({ + dir: mockPwd, + filepath: 'file4.txt', + }); + + expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({ + dir: mockPwd, + message: 'Combined flag commit', + })); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Combined flag commit'); + }); + + it('should handle --allow-empty flag', async () => { + // Mock empty status + mockGit.statusMatrix = vi.fn().mockResolvedValue([]); + + const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit']); + + expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({ + dir: mockPwd, + message: 'Empty commit', + })); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Empty commit'); + }); + + it('should fail if there are no staged changes', async () => { + // Mock status with only unstaged changes + mockGit.statusMatrix = vi.fn().mockResolvedValue([ + ['file1.txt', 1, 2, 1], // modified in workdir only + ]); + + const result = await commitCommand.execute(['-m', 'Should fail']); + + expect(mockGit.commit).not.toHaveBeenCalled(); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain('nothing to commit'); + }); + + it('should handle not being in a git repository', async () => { + mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory')); + + const result = await commitCommand.execute(['-m', 'Test commit']); + + expect(mockGit.commit).not.toHaveBeenCalled(); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain('not a git repository'); + }); +}); From d9956e60ebd92d78ffde075c2367135f690aedd3 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 3 Oct 2025 23:53:10 -0500 Subject: [PATCH 090/105] Accept options object in JSRuntimeFS --- src/lib/JSRuntime.ts | 10 ++++++---- src/lib/LightningFSAdapter.ts | 14 +++++++++----- src/lib/ProjectsManager.test.ts | 10 +++++++--- src/lib/fileUtils.test.ts | 12 ++++++++---- src/lib/tmpCleanup.test.ts | 12 ++++++++---- src/lib/tools/TextEditorStrReplaceTool.test.ts | 13 ++++++++----- src/lib/tools/TextEditorViewTool.test.ts | 13 ++++++++----- src/lib/tools/TextEditorWriteTool.test.ts | 13 ++++++++----- 8 files changed, 62 insertions(+), 35 deletions(-) diff --git a/src/lib/JSRuntime.ts b/src/lib/JSRuntime.ts index 349d789c..54aefebd 100644 --- a/src/lib/JSRuntime.ts +++ b/src/lib/JSRuntime.ts @@ -5,11 +5,13 @@ export interface JSRuntimeFS { // Core file operations with proper overloads for type safety readFile(path: string): Promise; - readFile(path: string, encoding: 'utf8'): Promise; - readFile(path: string, encoding: string): Promise; - readFile(path: string, encoding?: string): Promise; + readFile(path: string, options: 'utf8'): Promise; + readFile(path: string, options: string): Promise; + readFile(path: string, options: { encoding: 'utf8' }): Promise; + readFile(path: string, options: { encoding: string }): Promise; + readFile(path: string, options?: string | { encoding?: string }): Promise; - writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise; + writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise; // readdir overloads for different return types readdir(path: string): Promise; diff --git a/src/lib/LightningFSAdapter.ts b/src/lib/LightningFSAdapter.ts index 77dfedfb..413944b6 100644 --- a/src/lib/LightningFSAdapter.ts +++ b/src/lib/LightningFSAdapter.ts @@ -9,14 +9,18 @@ export class LightningFSAdapter implements JSRuntimeFS { constructor(private lightningFS: LightningFS.PromisifiedFS) {} async readFile(path: string): Promise; - async readFile(path: string, encoding: 'utf8'): Promise; - async readFile(path: string, encoding: string): Promise; - async readFile(path: string, encoding?: string): Promise; - async readFile(path: string, encoding?: string): Promise { + async readFile(path: string, options: 'utf8'): Promise; + async readFile(path: string, options: string): Promise; + async readFile(path: string, options: { encoding: 'utf8' }): Promise; + async readFile(path: string, options: { encoding: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise { + const encoding = typeof options === 'string' ? options : options?.encoding; return this.lightningFS.readFile(path, encoding); } - async writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise { + async writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise { + const encoding = typeof options === 'string' ? options : options?.encoding; return this.lightningFS.writeFile(path, data, encoding); } diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index 5e43cf2a..22b59ea6 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -41,15 +41,19 @@ class MockFS implements JSRuntimeFS { private dirs: Set = new Set(); async readFile(path: string): Promise; - async readFile(path: string, encoding: "utf8"): Promise; - async readFile(path: string, encoding: string): Promise; - async readFile(path: string, encoding?: string): Promise { + async readFile(path: string, options: 'utf8'): Promise; + async readFile(path: string, options: string): Promise; + async readFile(path: string, options: { encoding: 'utf8' }): Promise; + async readFile(path: string, options: { encoding: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise { const content = this.files.get(path); if (content === undefined) { const error = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException; error.code = 'ENOENT'; throw error; } + const encoding = typeof options === 'string' ? options : options?.encoding; if (encoding === 'utf8') { if (typeof content === 'string') { return content; diff --git a/src/lib/fileUtils.test.ts b/src/lib/fileUtils.test.ts index e75495e1..801fe30d 100644 --- a/src/lib/fileUtils.test.ts +++ b/src/lib/fileUtils.test.ts @@ -13,12 +13,16 @@ class MockFS implements JSRuntimeFS { } async readFile(path: string): Promise; - async readFile(path: string, encoding: 'utf8'): Promise; - async readFile(path: string, encoding: string): Promise; - async readFile(path: string, encoding?: string): Promise { + async readFile(path: string, options: 'utf8'): Promise; + async readFile(path: string, options: string): Promise; + async readFile(path: string, options: { encoding: 'utf8' }): Promise; + async readFile(path: string, options: { encoding: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise { const data = this.files.get(path); if (!data) throw new Error(`File not found: ${path}`); + const encoding = typeof options === 'string' ? options : options?.encoding; if (encoding === 'utf8') { return typeof data === 'string' ? data : new TextDecoder().decode(data); } @@ -26,7 +30,7 @@ class MockFS implements JSRuntimeFS { return data; } - async writeFile(path: string, data: string | Uint8Array): Promise { + async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise { this.files.set(path, data); } diff --git a/src/lib/tmpCleanup.test.ts b/src/lib/tmpCleanup.test.ts index 9ba27c96..eabf2f42 100644 --- a/src/lib/tmpCleanup.test.ts +++ b/src/lib/tmpCleanup.test.ts @@ -26,15 +26,19 @@ class MockFS implements JSRuntimeFS { } async readFile(path: string): Promise; - async readFile(path: string, encoding: 'utf8'): Promise; - async readFile(path: string, encoding: string): Promise; - async readFile(path: string, encoding?: string): Promise { + async readFile(path: string, options: 'utf8'): Promise; + async readFile(path: string, options: string): Promise; + async readFile(path: string, options: { encoding: 'utf8' }): Promise; + async readFile(path: string, options: { encoding: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise { const file = this.files.get(path); if (!file || file.isDir) throw new Error(`File not found: ${path}`); + const encoding = typeof options === 'string' ? options : options?.encoding; return encoding === 'utf8' ? file.content.toString() : new Uint8Array(); } - async writeFile(path: string, data: string | Uint8Array): Promise { + async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise { this.files.set(path, { content: data, mtimeMs: Date.now(), isDir: false }); } diff --git a/src/lib/tools/TextEditorStrReplaceTool.test.ts b/src/lib/tools/TextEditorStrReplaceTool.test.ts index 3b7df782..b439282d 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.test.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.test.ts @@ -14,18 +14,21 @@ class MockFS implements JSRuntimeFS { } async readFile(path: string): Promise; - async readFile(path: string, encoding: 'utf8'): Promise; - async readFile(path: string, encoding: string): Promise; - async readFile(path: string, encoding?: string): Promise; - async readFile(path: string, encoding?: string): Promise { + async readFile(path: string, options: 'utf8'): Promise; + async readFile(path: string, options: string): Promise; + async readFile(path: string, options: { encoding: 'utf8' }): Promise; + async readFile(path: string, options: { encoding: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise { const content = this.files.get(path); if (content === undefined) { throw new Error(`File not found: ${path}`); } + const encoding = typeof options === 'string' ? options : options?.encoding; return encoding ? content : new TextEncoder().encode(content); } - async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise { + async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise { const content = typeof data === 'string' ? data : new TextDecoder().decode(data); this.files.set(path, content); } diff --git a/src/lib/tools/TextEditorViewTool.test.ts b/src/lib/tools/TextEditorViewTool.test.ts index 03e81b73..eddabc93 100644 --- a/src/lib/tools/TextEditorViewTool.test.ts +++ b/src/lib/tools/TextEditorViewTool.test.ts @@ -41,15 +41,18 @@ class MockFS implements JSRuntimeFS { } async readFile(path: string): Promise; - async readFile(path: string, encoding: 'utf8'): Promise; - async readFile(path: string, encoding: string): Promise; - async readFile(path: string, encoding?: string): Promise; - async readFile(path: string, encoding?: string): Promise { + async readFile(path: string, options: 'utf8'): Promise; + async readFile(path: string, options: string): Promise; + async readFile(path: string, options: { encoding: 'utf8' }): Promise; + async readFile(path: string, options: { encoding: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise { const content = this.files.get(path); if (content === undefined) { throw new Error(`File not found: ${path}`); } + const encoding = typeof options === 'string' ? options : options?.encoding; // If no encoding specified, return Uint8Array if (!encoding) { // For binary files, return mock binary data with null bytes @@ -70,7 +73,7 @@ class MockFS implements JSRuntimeFS { return content; } - async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise { + async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise { const content = typeof data === 'string' ? data : new TextDecoder().decode(data); this.files.set(path, content); } diff --git a/src/lib/tools/TextEditorWriteTool.test.ts b/src/lib/tools/TextEditorWriteTool.test.ts index 34c1ffc9..17169b4f 100644 --- a/src/lib/tools/TextEditorWriteTool.test.ts +++ b/src/lib/tools/TextEditorWriteTool.test.ts @@ -13,18 +13,21 @@ class MockFS implements JSRuntimeFS { } async readFile(path: string): Promise; - async readFile(path: string, encoding: 'utf8'): Promise; - async readFile(path: string, encoding: string): Promise; - async readFile(path: string, encoding?: string): Promise; - async readFile(path: string, encoding?: string): Promise { + async readFile(path: string, options: 'utf8'): Promise; + async readFile(path: string, options: string): Promise; + async readFile(path: string, options: { encoding: 'utf8' }): Promise; + async readFile(path: string, options: { encoding: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise; + async readFile(path: string, options?: string | { encoding?: string }): Promise { const content = this.files.get(path); if (content === undefined) { throw new Error(`File not found: ${path}`); } + const encoding = typeof options === 'string' ? options : options?.encoding; return encoding ? content : new TextEncoder().encode(content); } - async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise { + async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise { const content = typeof data === 'string' ? data : new TextDecoder().decode(data); this.files.set(path, content); } From 4e163a032f8d306a88b5fa90e8c7119a4e428256 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 3 Oct 2025 23:53:33 -0500 Subject: [PATCH 091/105] Safe area inset improvements --- package-lock.json | 16 +++ package.json | 1 + src/components/AppLayout.tsx | 28 ++-- src/components/CreditsDialog.tsx | 2 +- src/components/OnboardingDialog.tsx | 10 +- src/components/ProjectSidebar.tsx | 64 ++++----- src/components/SettingsLayout.tsx | 6 +- src/components/Shakespeare/PreviewPane.tsx | 144 ++++++++++----------- src/components/ui/toast.tsx | 2 +- src/index.css | 19 +-- src/pages/ProjectView.tsx | 94 +++++++------- 11 files changed, 201 insertions(+), 185 deletions(-) diff --git a/package-lock.json b/package-lock.json index e2fec05c..8aea64c8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -79,6 +79,7 @@ "streamdown": "~1.0.0", "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", + "tailwindcss-safe-area": "^0.8.0", "turndown": "^7.2.1", "uri-templates": "^0.2.0", "use-stick-to-bottom": "^1.1.1", @@ -10092,6 +10093,21 @@ "tailwindcss": ">=3.0.0 || insiders" } }, + "node_modules/tailwindcss-safe-area": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/tailwindcss-safe-area/-/tailwindcss-safe-area-0.8.0.tgz", + "integrity": "sha512-OIKZfSvinI9kZ3hduoSxqP8EfW2rXoKvHnNyTDY2zwem06IIRtLcKdMe0nF98o+Xluk5Fy7mmesr1rSXg/wkhA==", + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/mvllow" + }, + "peerDependencies": { + "tailwindcss": "^2.0.0 || >=3.0.0" + } + }, "node_modules/tailwindcss/node_modules/postcss-selector-parser": { "version": "6.1.2", "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", diff --git a/package.json b/package.json index 8761be75..cfb24d13 100644 --- a/package.json +++ b/package.json @@ -82,6 +82,7 @@ "streamdown": "~1.0.0", "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", + "tailwindcss-safe-area": "^0.8.0", "turndown": "^7.2.1", "uri-templates": "^0.2.0", "use-stick-to-bottom": "^1.1.1", diff --git a/src/components/AppLayout.tsx b/src/components/AppLayout.tsx index cc9552ed..69311d9a 100644 --- a/src/components/AppLayout.tsx +++ b/src/components/AppLayout.tsx @@ -72,20 +72,22 @@ export function AppLayout({ return (
{/* Mobile Header */} -
-
- {showSidebar && ( - - )} +
+
+
+ {showSidebar && ( + + )} +
+ {headerContent}
- {headerContent}
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */} diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 8b4de085..a9ac5295 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -399,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro return ( - e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none"> + e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-dvh-safe max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none"> {lightningInvoice ? ( diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index ba098e24..1ab8e51e 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -171,7 +171,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) return ( <> - + {step === 'open-source' && ( @@ -275,13 +275,15 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {step === 'open-source' && (
-

Shakespeare is Open Source software that runs entirely in your web browser

+

+ Shakespeare is Open Source software that runs entirely in your web browser +

-

Your browser connects directly to third-party AI providers of your choice

+

Your device connects directly to third-party AI providers of your choice

@@ -303,7 +305,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)

- Shakespeare is not a cloud service. It's Open Source software that runs in your web browser. + Shakespeare is not a cloud service. It's Open Source software that runs on your device. You agree to the Terms of Service of AI providers you interact with. Shakespeare is provided "as is" without warranty of any kind.

diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index ec800bc0..03022f82 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -131,34 +131,36 @@ export function ProjectSidebar({ return (
{/* Header with Logo */} -
-
- - {(onToggleSidebar || (onClose && isMobile)) && ( -
- -
- )} +
+
+
+ + {(onToggleSidebar || (onClose && isMobile)) && ( +
+ +
+ )} +
@@ -229,8 +231,8 @@ export function ProjectSidebar({
{/* Settings and Help at Bottom */} -
-
+
+
- -
); } \ No newline at end of file diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index 6cf9ea0c..ba1fe434 100644 --- a/src/components/SettingsLayout.tsx +++ b/src/components/SettingsLayout.tsx @@ -120,10 +120,10 @@ export function SettingsLayout() { if (isMobile) { return ( -
+
{/* Mobile Header */} -
-
+
+
+ )} + + +
+ )} + /> +
+ + {/* Content area */} +
+ {hasBuiltProject ? ( +