From ab039d2fb7536a06e7b02ec84813a8be9723db47 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 01:05:00 -0600 Subject: [PATCH 01/12] Text chats --- src/App.tsx | 7 +- src/AppRouter.tsx | 2 + src/components/ActionsMenu.tsx | 108 +++++----- src/components/AppProvider.tsx | 2 + src/components/ProjectSidebar.tsx | 114 ++++++++-- src/components/SentryProvider.test.tsx | 4 + src/components/Shakespeare/ChatPane.tsx | 24 ++- src/contexts/AppContext.ts | 2 + src/hooks/useChats.ts | 20 ++ src/hooks/useChatsManager.ts | 16 ++ src/hooks/useFSPaths.ts | 2 + src/hooks/useGenerateProjectInfo.test.ts | 29 ++- src/hooks/useGenerateProjectInfo.ts | 156 ++++++++++---- src/hooks/useGit.test.ts | 1 + src/lib/ChatsManager.ts | 251 +++++++++++++++++++++++ src/lib/SessionManager.test.ts | 1 + src/lib/system.test.ts | 1 + src/pages/ChatView.tsx | 239 +++++++++++++++++++++ src/pages/Index.tsx | 122 +++++++---- src/test/TestApp.tsx | 1 + 20 files changed, 944 insertions(+), 158 deletions(-) create mode 100644 src/hooks/useChats.ts create mode 100644 src/hooks/useChatsManager.ts create mode 100644 src/lib/ChatsManager.ts create mode 100644 src/pages/ChatView.tsx diff --git a/src/App.tsx b/src/App.tsx index a85f19c1..29f870b1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -48,7 +48,7 @@ const queryClient = new QueryClient({ }); // Get OS-specific default paths for Electron -function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } { +function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string; fsPathChats: string } { if (!globalThis.electron) { // Browser defaults - use virtual filesystem paths return { @@ -57,6 +57,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathTmp: "/tmp", fsPathPlugins: "/plugins", fsPathTemplates: "/templates", + fsPathChats: "/chats", }; } @@ -72,6 +73,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathTmp: "~/AppData/Local/Temp/shakespeare", fsPathPlugins: "~/AppData/Local/shakespeare/plugins", fsPathTemplates: "~/AppData/Local/shakespeare/templates", + fsPathChats: "~/Documents/Chats", }; } else if (platform.includes('mac')) { // macOS @@ -81,6 +83,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathTmp: "/tmp/shakespeare", fsPathPlugins: "~/Library/Application Support/shakespeare/plugins", fsPathTemplates: "~/Library/Application Support/shakespeare/templates", + fsPathChats: "~/Chats", }; } else { // Linux and other Unix-like systems @@ -90,6 +93,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathTmp: "/tmp/shakespeare", fsPathPlugins: "~/.config/shakespeare/plugins", fsPathTemplates: "~/.config/shakespeare/templates", + fsPathChats: "~/Chats", }; } } @@ -135,6 +139,7 @@ const defaultConfig: AppConfig = { fsPathTmp: electronPaths.fsPathTmp, fsPathPlugins: electronPaths.fsPathPlugins, fsPathTemplates: electronPaths.fsPathTemplates, + fsPathChats: electronPaths.fsPathChats, sentryDsn: import.meta.env.VITE_SENTRY_DSN || "", sentryEnabled: true, }; diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index dd0f5e75..d0a75bc9 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -21,6 +21,7 @@ import VercelOAuth from "./pages/VercelOAuth"; import { NIP19Page } from "./pages/NIP19Page"; import NotFound from "./pages/NotFound"; import { ProjectView } from "./pages/ProjectView"; +import { ChatView } from "./pages/ChatView"; import { SettingsLayout } from "./components/SettingsLayout"; export function AppRouter() { @@ -51,6 +52,7 @@ export function AppRouter() { } /> } /> + } /> {/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */} } /> {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */} diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index 040fcd4d..59c2d4a3 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -27,6 +27,7 @@ interface ActionsMenuProps { isBuildLoading?: boolean; disabled?: boolean; onFirstInteraction?: () => void; + isChat?: boolean; // Flag to indicate this is a chat, not a project } export function ActionsMenu({ @@ -38,6 +39,7 @@ export function ActionsMenu({ isBuildLoading = false, disabled = false, onFirstInteraction: _onFirstInteraction, + isChat = false, }: ActionsMenuProps) { const [gitHistoryOpen, setGitHistoryOpen] = useState(false); const [gitDialogOpen, setGitDialogOpen] = useState(false); @@ -71,65 +73,73 @@ export function ActionsMenu({ New Chat - setGitHistoryOpen(true)} - disabled={isAnyLoading} - className="gap-2" - > - - Rollback - + {!isChat && ( + <> + setGitHistoryOpen(true)} + disabled={isAnyLoading} + className="gap-2" + > + + Rollback + - setGitDialogOpen(true)} - disabled={isAnyLoading} - className="gap-2" - > - - Repository - + setGitDialogOpen(true)} + disabled={isAnyLoading} + className="gap-2" + > + + Repository + - setDeployDialogOpen(true)} - disabled={isAnyLoading} - className="gap-2" - > - - Deploy - + setDeployDialogOpen(true)} + disabled={isAnyLoading} + className="gap-2" + > + + Deploy + - - - Project Details - + + + Project Details + + + )} - {/* Dialogs */} - + {/* Dialogs - only show for projects, not chats */} + {!isChat && ( + <> + - + - + + + )} ); diff --git a/src/components/AppProvider.tsx b/src/components/AppProvider.tsx index 40bdd2ba..f8526a0e 100644 --- a/src/components/AppProvider.tsx +++ b/src/components/AppProvider.tsx @@ -47,6 +47,7 @@ const AppConfigSchema = z.object({ fsPathTmp: z.string().min(1), fsPathPlugins: z.string().min(1), fsPathTemplates: z.string().min(1), + fsPathChats: z.string().min(1), sentryDsn: z.string(), sentryEnabled: z.boolean(), }) satisfies z.ZodType; @@ -85,6 +86,7 @@ export function AppProvider(props: AppProviderProps) { config.fsPathTmp = expandPath(config.fsPathTmp); config.fsPathPlugins = expandPath(config.fsPathPlugins); config.fsPathTemplates = expandPath(config.fsPathTemplates); + config.fsPathChats = expandPath(config.fsPathChats); const appContextValue: AppContextType = { config, diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index f2cd9c7d..980ba8e5 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,16 +1,18 @@ import React, { useEffect, useState, useMemo } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Search } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Search, MessageSquare } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { Input } from '@/components/ui/input'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import { useProjects } from '@/hooks/useProjects'; +import { useChats } from '@/hooks/useChats'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; import type { Project } from '@/lib/ProjectsManager'; +import type { Chat } from '@/lib/ChatsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; @@ -75,6 +77,51 @@ const ProjectItem: React.FC = ({ project, isSelected, onSelect ProjectItem.displayName = 'ProjectItem'; +interface ChatItemProps { + chat: Chat; + isSelected: boolean; + onSelect: (chat: Chat) => void; +} + +const ChatItem: React.FC = ({ chat, isSelected, onSelect }) => { + const navigate = useNavigate(); + + const handleClick = () => { + onSelect(chat); + navigate(`/chat/${chat.id}`); + }; + + return ( +
+
+
+
+ ); +}; + +ChatItem.displayName = 'ChatItem'; + interface ProjectSidebarProps { selectedProject: Project | null; onSelectProject: (project: Project | null) => void; @@ -92,14 +139,18 @@ export function ProjectSidebar({ }: ProjectSidebarProps) { const { t } = useTranslation(); const queryClient = useQueryClient(); - const { data: projects = [], isLoading, error } = useProjects(); + const { data: projects = [], isLoading: isLoadingProjects, error: projectsError } = useProjects(); + const { data: chats = [], isLoading: isLoadingChats, error: chatsError } = useChats(); const [favorites] = useLocalStorage('project-favorites', []); const [searchQuery, setSearchQuery] = useState(''); const isMobile = useIsMobile(); const navigate = useNavigate(); - // Fast in-memory search filtering + const isLoading = isLoadingProjects || isLoadingChats; + const error = projectsError || chatsError; + + // Fast in-memory search filtering for projects const filteredProjects = useMemo(() => { if (!searchQuery.trim()) { return projects; @@ -112,6 +163,30 @@ export function ProjectSidebar({ ); }, [projects, searchQuery]); + // Fast in-memory search filtering for chats + const filteredChats = useMemo(() => { + if (!searchQuery.trim()) { + return chats; + } + + const query = searchQuery.toLowerCase(); + return chats.filter(chat => + chat.id.toLowerCase().includes(query) || + chat.name.toLowerCase().includes(query) + ); + }, [chats, searchQuery]); + + // Combine projects and chats, sorted by lastModified + const combinedItems = useMemo(() => { + const items: Array<{ type: 'project' | 'chat'; item: Project | Chat; lastModified: Date }> = [ + ...filteredProjects.map(p => ({ type: 'project' as const, item: p, lastModified: p.lastModified })), + ...filteredChats.map(c => ({ type: 'chat' as const, item: c, lastModified: c.lastModified })), + ]; + + // Sort by lastModified (newest first) + return items.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime()); + }, [filteredProjects, filteredChats]); + // Custom navigate function that closes sidebar on mobile const navigateAndClose = (path: string) => { navigate(path); @@ -212,7 +287,7 @@ export function ProjectSidebar({ {/* Search Input */} - {projects.length > 0 && ( + {(projects.length > 0 || chats.length > 0) && (
))}
- ) : projects.length === 0 ? ( + ) : combinedItems.length === 0 && projects.length === 0 && chats.length === 0 ? (

{t('noProjectsYet')}

{t('createFirstProject')}

- ) : filteredProjects.length === 0 ? ( + ) : combinedItems.length === 0 ? (

{t('noProjectsFound')}

@@ -251,15 +326,24 @@ export function ProjectSidebar({
) : (
- {filteredProjects.map((project) => ( - - ))} + {combinedItems.map(({ type, item }) => + type === 'project' ? ( + + ) : ( + {}} + /> + ) + )}
)} diff --git a/src/components/SentryProvider.test.tsx b/src/components/SentryProvider.test.tsx index 9af8c289..33db2239 100644 --- a/src/components/SentryProvider.test.tsx +++ b/src/components/SentryProvider.test.tsx @@ -40,6 +40,7 @@ describe('SentryProvider', () => { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', }; render( @@ -77,6 +78,7 @@ describe('SentryProvider', () => { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', }; render( @@ -115,6 +117,7 @@ describe('SentryProvider', () => { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', }; render( @@ -156,6 +159,7 @@ describe('SentryProvider', () => { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', }; render( diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 884d8e67..c3f244b9 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -59,6 +59,7 @@ interface ChatPaneProps { isBuildLoading?: boolean; consoleError?: ProjectPreviewConsoleError | null; onDismissConsoleError?: () => void; + isChat?: boolean; // Flag to indicate this is a chat session, not a project } export interface ChatPaneRef { @@ -72,6 +73,7 @@ export const ChatPane = forwardRef(({ onLoadingChange, isLoading: externalIsLoading, isBuildLoading: externalIsBuildLoading, + isChat = false, consoleError, onDismissConsoleError, }, ref) => { @@ -143,7 +145,8 @@ export const ChatPane = forwardRef(({ }, [projectId, providerModel]); // Initialize AI chat with tools - const cwd = `${projectsPath}/${projectId}`; + const { chatsPath } = useFSPaths(); + const cwd = isChat ? `${chatsPath}/${projectId}` : `${projectsPath}/${projectId}`; const esmUrlRef = useRef(config.esmUrl); const sessionManager = useSessionManager(); @@ -158,6 +161,23 @@ export const ChatPane = forwardRef(({ // Separate built-in tools from MCP tools for clarity const builtInTools = useMemo(() => { + // For chat mode, provide minimal tools (no project-specific tools) + if (isChat) { + const tools: Record> = { + nostr_read_nip: new NostrReadNipTool(), + nostr_fetch_event: new NostrFetchEventTool(), + nostr_read_kind: new NostrReadKindTool(), + nostr_read_tag: new NostrReadTagTool(), + nostr_read_protocol: new NostrReadProtocolTool(), + nostr_read_nips_index: new NostrReadNipsIndexTool(), + nostr_generate_kind: new NostrGenerateKindTool(), + nostr_publish_events: new NostrPublishEventsTool(), + // TODO: Add start_project tool here + }; + return tools; + } + + // For project mode, provide full set of tools const tools: Record> = { git_commit: new GitCommitTool(fs, cwd, git), text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }), @@ -186,7 +206,7 @@ export const ChatPane = forwardRef(({ } return tools; - }, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]); + }, [isChat, fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]); // MCP tools wrapped for execution const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]); diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index 68ad6c78..a3f1ff91 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -51,6 +51,8 @@ export interface AppConfig { fsPathPlugins: string; /** VFS path for templates directory */ fsPathTemplates: string; + /** VFS path for chats directory */ + fsPathChats: string; /** Sentry DSN for error reporting (empty string = disabled) */ sentryDsn: string; /** Whether the user has enabled Sentry error reporting */ diff --git a/src/hooks/useChats.ts b/src/hooks/useChats.ts new file mode 100644 index 00000000..485283de --- /dev/null +++ b/src/hooks/useChats.ts @@ -0,0 +1,20 @@ +import { useQuery } from '@tanstack/react-query'; +import { useChatsManager } from '@/hooks/useChatsManager'; +import type { Chat } from '@/lib/ChatsManager'; + +export function useChats() { + const chatsManager = useChatsManager(); + + return useQuery({ + queryKey: ['chats'], + queryFn: async (): Promise => { + await chatsManager.init(); + const chats = await chatsManager.getChats(); + + // Sort chats by lastModified (newest first) + return chats.sort((a, b) => { + return b.lastModified.getTime() - a.lastModified.getTime(); + }); + }, + }); +} diff --git a/src/hooks/useChatsManager.ts b/src/hooks/useChatsManager.ts new file mode 100644 index 00000000..5fcf9465 --- /dev/null +++ b/src/hooks/useChatsManager.ts @@ -0,0 +1,16 @@ +import { useMemo } from 'react'; +import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; +import { ChatsManager } from '@/lib/ChatsManager'; + +export function useChatsManager() { + const { fs } = useFS(); + const { chatsPath } = useFSPaths(); + + return useMemo(() => { + return new ChatsManager({ + fs, + chatsPath, + }); + }, [fs, chatsPath]); +} diff --git a/src/hooks/useFSPaths.ts b/src/hooks/useFSPaths.ts index 9fd95618..4f99d34a 100644 --- a/src/hooks/useFSPaths.ts +++ b/src/hooks/useFSPaths.ts @@ -19,5 +19,7 @@ export function useFSPaths() { pluginsPath: config.fsPathPlugins, /** Templates directory path (default: /templates) */ templatesPath: config.fsPathTemplates, + /** Chats directory path (default: /chats) */ + chatsPath: config.fsPathChats, }; } diff --git a/src/hooks/useGenerateProjectInfo.test.ts b/src/hooks/useGenerateProjectInfo.test.ts index b20f6437..32d3dd6b 100644 --- a/src/hooks/useGenerateProjectInfo.test.ts +++ b/src/hooks/useGenerateProjectInfo.test.ts @@ -73,6 +73,7 @@ describe('useGenerateProjectInfo', () => { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', sentryDsn: '', sentryEnabled: false, }; @@ -226,6 +227,7 @@ describe('useGenerateProjectInfo', () => { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', sentryDsn: '', sentryEnabled: false, }; @@ -330,10 +332,13 @@ describe('useGenerateProjectInfo', () => { const { result } = renderHook(() => useGenerateProjectInfo()); - const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); + const generatedInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); - expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); - expect(projectInfo.projectId).toBe('untitled'); + expect(generatedInfo.type).toBe('project'); + if (generatedInfo.type === 'project') { + expect(generatedInfo.info.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); + expect(generatedInfo.info.projectId).toBe('untitled'); + } }); it('should increment AI-generated ID when project already exists', async () => { @@ -363,10 +368,13 @@ describe('useGenerateProjectInfo', () => { const { result } = renderHook(() => useGenerateProjectInfo()); - const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); + const generatedInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); - expect(projectInfo.projectId).toBe('test-project-name-1'); - expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); + expect(generatedInfo.type).toBe('project'); + if (generatedInfo.type === 'project') { + expect(generatedInfo.info.projectId).toBe('test-project-name-1'); + expect(generatedInfo.info.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); + } expect(mockGetProject).toHaveBeenCalledTimes(2); expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name'); expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1'); @@ -400,10 +408,13 @@ describe('useGenerateProjectInfo', () => { const { result } = renderHook(() => useGenerateProjectInfo()); - const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); + const generatedInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); - expect(projectInfo.projectId).toBe('test-project-name-2'); - expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); + expect(generatedInfo.type).toBe('project'); + if (generatedInfo.type === 'project') { + expect(generatedInfo.info.projectId).toBe('test-project-name-2'); + expect(generatedInfo.info.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); + } expect(mockGetProject).toHaveBeenCalledTimes(3); expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name'); expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1'); diff --git a/src/hooks/useGenerateProjectInfo.ts b/src/hooks/useGenerateProjectInfo.ts index 68dbd689..89a4fe6a 100644 --- a/src/hooks/useGenerateProjectInfo.ts +++ b/src/hooks/useGenerateProjectInfo.ts @@ -20,6 +20,14 @@ interface ProjectInfo { }; } +interface ChatInfo { + chatId: string; +} + +type GeneratedInfo = + | { type: 'project'; info: ProjectInfo } + | { type: 'chat'; info: ChatInfo }; + export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOptions = {}) { const [isLoading, setIsLoading] = useState(false); const { settings, isConfigured } = useAISettings(); @@ -59,7 +67,7 @@ export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOption }; }, [projectsManager]); - const generateProjectInfo = useCallback(async (providerModel: string, prompt: string): Promise => { + const generateProjectInfo = useCallback(async (providerModel: string, prompt: string): Promise => { if (!isConfigured) { throw new Error('AI settings not configured'); } @@ -80,11 +88,11 @@ export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOption const openai = createAIClient(provider, user, config.corsProxy); // Create project creation tool - const createProjectTool: ChatCompletionTool = { + const startProjectTool: ChatCompletionTool = { type: 'function', function: { - name: 'create_project', - description: 'Create a new project by choosing a name and selecting the most appropriate template. You must call this tool to create the project.', + name: 'start_project', + description: 'Start a new project by choosing a name and selecting the most appropriate template. Call this when the user wants to build an app or website.', parameters: { type: 'object', properties: { @@ -103,66 +111,136 @@ export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOption }, }; - const systemPrompt = `You are a product expert helping users create new projects. Given the user's project description, you must: + // Create chat start tool + const startChatTool: ChatCompletionTool = { + type: 'function', + function: { + name: 'start_chat', + description: 'Start a general conversation or chat session. Call this when the user wants to have a conversation, ask questions, or discuss ideas without building a specific app.', + parameters: { + type: 'object', + properties: { + chat_name: { + type: 'string', + description: 'A short, descriptive name for the chat. Should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens.', + }, + }, + required: ['chat_name'], + }, + }, + }; -1. Generate a short, unique, and memorable name for their product or brand. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores. + const systemPrompt = `You are an AI assistant helping users either create projects or start conversations. -2. Select the most appropriate template from the available options: -${config.templates.map(t => ` - ${t.name}: ${t.description} (${t.url})`).join('\n')} +**First and foremost, you must decide whether to create a project or start a chat:** +- If the user expresses a desire to build, create, develop, or launch an app, website, or software product, they want to start a project. +- If the user wants to have a discussion, ask questions, brainstorm ideas, or seek advice without building a specific app, they want to start a chat. -You MUST call the create_project tool with your choices.`; +1. If the user wants to **create a project** (build an app or website) - use start_project tool + - Generate a short, unique, and memorable name for their product or brand + - Name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens + - Select the most appropriate template from: +${config.templates.map(t => ` - ${t.name}: ${t.description} (${t.url})`).join('\n')} + +2. If the user wants to **start a chat** (general conversation, questions, brainstorming) - use start_chat tool + - Generate a short, descriptive name for the chat topic + - Name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens + +You MUST call either start_project or start_chat based on the user's intent.`; const messages: ChatCompletionMessageParam[] = [ { role: 'system', content: systemPrompt }, { role: 'user', content: prompt } ]; - // Call AI with tool + // Call AI with both tools const completion = await openai.chat.completions.create({ model, messages, - tools: [createProjectTool], - tool_choice: { type: 'function', function: { name: 'create_project' } }, + tools: [startProjectTool, startChatTool], + tool_choice: "required", temperature: 1, }); const toolCall = completion.choices[0]?.message?.tool_calls?.[0]; - if (!toolCall || toolCall.type !== 'function' || toolCall.function.name !== 'create_project') { - throw new Error('AI failed to create the project'); + if (!toolCall || toolCall.type !== 'function') { + throw new Error('AI failed to determine action'); } const args = JSON.parse(toolCall.function.arguments); - const templateUrl = args.template_url as string; - const projectId = args.project_name as string; - // Validate template URL - const selectedTemplate = config.templates.find(t => t.url === templateUrl); - if (!selectedTemplate) { - // Fallback to first template if invalid URL selected - console.warn(`Invalid template URL selected: ${templateUrl}, falling back to first template`); - return await generateIncrementedId('untitled', config.templates[0], false); - } + // Handle start_chat tool call + if (toolCall.function.name === 'start_chat') { + const chatId = args.chat_name as string; - // Validate the generated project ID - const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/; - if (projectId && projectId.length <= 50 && validIdRegex.test(projectId)) { - // Check if project exists - const existingProject = await projectsManager.getProject(projectId); - if (existingProject === null) { - // Valid and unique project ID + // Validate the generated chat ID + const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/; + if (chatId && chatId.length <= 50 && validIdRegex.test(chatId)) { return { - projectId, - template: selectedTemplate, + type: 'chat', + info: { chatId }, }; } - // Project already exists - increment the AI-generated ID (baseExists = true) - return await generateIncrementedId(projectId, selectedTemplate, true); + // Fallback to auto-generated chat ID if validation fails + return { + type: 'chat', + info: { chatId: 'chat' }, + }; } - // If we reach here, the regex failed - fall back to "untitled" with number suffixes - return await generateIncrementedId('untitled', selectedTemplate, false); + // Handle start_project tool call + if (toolCall.function.name === 'start_project') { + const templateUrl = args.template_url as string; + const projectId = args.project_name as string; + + // Validate template URL + const selectedTemplate = config.templates.find(t => t.url === templateUrl); + if (!selectedTemplate) { + // Fallback to first template if invalid URL selected + console.warn(`Invalid template URL selected: ${templateUrl}, falling back to first template`); + const fallbackInfo = await generateIncrementedId('untitled', config.templates[0], false); + return { + type: 'project', + info: fallbackInfo, + }; + } + + // Validate the generated project ID + const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/; + if (projectId && projectId.length <= 50 && validIdRegex.test(projectId)) { + // Check if project exists + const existingProject = await projectsManager.getProject(projectId); + if (existingProject === null) { + // Valid and unique project ID + return { + type: 'project', + info: { + projectId, + template: selectedTemplate, + }, + }; + } + + // Project already exists - increment the AI-generated ID (baseExists = true) + const fallbackInfo = await generateIncrementedId(projectId, selectedTemplate, true); + return { + type: 'project', + info: fallbackInfo, + }; + } + + // If we reach here, the regex failed - fall back to "untitled" with number suffixes + const fallbackInfo = await generateIncrementedId('untitled', selectedTemplate, false); + return { + type: 'project', + info: fallbackInfo, + }; + } + + // Unknown tool call + throw new Error(`Unknown tool call: ${toolCall.function.name}`); } catch (error) { // On any error, fall back to first template with untitled name console.error('Error generating project info:', error); @@ -173,7 +251,11 @@ You MUST call the create_project tool with your choices.`; throw new Error(errorMessage); } - return await generateIncrementedId('untitled', config.templates[0], false); + const fallbackInfo = await generateIncrementedId('untitled', config.templates[0], false); + return { + type: 'project', + info: fallbackInfo, + }; } finally { setIsLoading(false); } diff --git a/src/hooks/useGit.test.ts b/src/hooks/useGit.test.ts index 03c26442..06dcf85f 100644 --- a/src/hooks/useGit.test.ts +++ b/src/hooks/useGit.test.ts @@ -50,6 +50,7 @@ function createWrapper(corsProxy: string) { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/lib/ChatsManager.ts b/src/lib/ChatsManager.ts new file mode 100644 index 00000000..d101e481 --- /dev/null +++ b/src/lib/ChatsManager.ts @@ -0,0 +1,251 @@ +import type { JSRuntimeFS } from '@/lib/JSRuntime'; +import { DotAI } from '@/lib/DotAI'; +import type OpenAI from 'openai'; + +export interface Chat { + id: string; + name: string; + path: string; + lastModified: Date; +} + +export interface ChatsManagerOptions { + fs: JSRuntimeFS; + /** Chats directory path (default: /chats) */ + chatsPath: string; +} + +export class ChatsManager { + fs: JSRuntimeFS; + dir: string; + + constructor(options: ChatsManagerOptions) { + this.fs = options.fs; + this.dir = options.chatsPath; + } + + async init() { + try { + await this.fs.mkdir(this.dir); + } catch { + // Directory might already exist + } + } + + /** + * Get all chats + */ + async getChats(): Promise { + try { + const chatDirs = await this.fs.readdir(this.dir); + const chats: Chat[] = []; + + for (const chatId of chatDirs) { + const chatPath = `${this.dir}/${chatId}`; + try { + const stat = await this.fs.stat(chatPath); + if (stat.isDirectory()) { + chats.push({ + id: chatId, + name: chatId, + path: chatPath, + lastModified: new Date(stat.mtimeMs || Date.now()), + }); + } + } catch { + // Skip if we can't stat this directory + continue; + } + } + + return chats; + } catch { + return []; + } + } + + /** + * Get a single chat by ID + */ + async getChat(chatId: string): Promise { + try { + const chatPath = `${this.dir}/${chatId}`; + const stat = await this.fs.stat(chatPath); + + if (!stat.isDirectory()) { + return null; + } + + return { + id: chatId, + name: chatId, + path: chatPath, + lastModified: new Date(stat.mtimeMs || Date.now()), + }; + } catch { + return null; + } + } + + /** + * Create a new chat with an initial message + */ + async createChat( + chatId: string, + initialMessage: string, + ): Promise { + const chatPath = `${this.dir}/${chatId}`; + + // Create the chat directory + await this.fs.mkdir(chatPath, { recursive: true }); + + // Create messages file with initial user message + const messagesPath = `${chatPath}/messages.jsonl`; + const userMessage: OpenAI.Chat.Completions.ChatCompletionMessageParam = { + role: 'user', + content: initialMessage, + }; + await this.fs.writeFile(messagesPath, JSON.stringify(userMessage) + '\n'); + + const stat = await this.fs.stat(chatPath); + + return { + id: chatId, + name: chatId, + path: chatPath, + lastModified: new Date(stat.mtimeMs || Date.now()), + }; + } + + /** + * Delete a chat + */ + async deleteChat(chatId: string): Promise { + const chatPath = `${this.dir}/${chatId}`; + + try { + // Recursively delete the chat directory + await this.deleteChatDirectory(chatPath); + } catch (error) { + console.error(`Failed to delete chat ${chatId}:`, error); + throw error; + } + } + + /** + * Recursively delete a directory and all its contents + */ + private async deleteChatDirectory(dirPath: string): Promise { + try { + const entries = await this.fs.readdir(dirPath); + + for (const entry of entries) { + const entryPath = `${dirPath}/${entry}`; + const stat = await this.fs.stat(entryPath); + + if (stat.isDirectory()) { + await this.deleteChatDirectory(entryPath); + } else { + await this.fs.unlink(entryPath); + } + } + + await this.fs.rmdir(dirPath); + } catch (error) { + console.error(`Failed to delete directory ${dirPath}:`, error); + throw error; + } + } + + /** + * Read messages from a chat + */ + async readMessages(chatId: string): Promise { + const messagesPath = `${this.dir}/${chatId}/messages.jsonl`; + + try { + const content = await this.fs.readFile(messagesPath, 'utf8'); + const lines = content.trim().split('\n').filter(line => line.trim()); + const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []; + + for (const line of lines) { + try { + const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam; + messages.push(message); + } catch (parseError) { + console.warn('Failed to parse message from chat:', parseError); + } + } + + return messages; + } catch { + return []; + } + } + + /** + * Write messages to a chat + */ + async writeMessages( + chatId: string, + messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[], + ): Promise { + const messagesPath = `${this.dir}/${chatId}/messages.jsonl`; + + try { + // Convert messages to JSONL format + const jsonlContent = messages.map(message => JSON.stringify(message)).join('\n'); + const finalContent = jsonlContent + (messages.length > 0 ? '\n' : ''); + + // Write the entire file + await this.fs.writeFile(messagesPath, finalContent); + } catch (error) { + console.warn(`Failed to write messages to chat: ${error}`); + throw error; + } + } + + /** + * Append a message to a chat + */ + async appendMessage( + chatId: string, + message: OpenAI.Chat.Completions.ChatCompletionMessageParam, + ): Promise { + const messagesPath = `${this.dir}/${chatId}/messages.jsonl`; + + try { + const messageJson = JSON.stringify(message) + '\n'; + + // Append to the file + try { + const existingContent = await this.fs.readFile(messagesPath, 'utf8'); + await this.fs.writeFile(messagesPath, existingContent + messageJson); + } catch { + // File doesn't exist, create it + await this.fs.writeFile(messagesPath, messageJson); + } + } catch (error) { + console.warn(`Failed to append message to chat: ${error}`); + throw error; + } + } + + /** + * Generate a unique chat ID + */ + static generateChatId(): string { + const now = new Date(); + const dateString = now.toISOString(); + + // Generate a random 3-character suffix to avoid collisions + const randomSuffix = Math.random().toString(36).substring(2, 5); + + // Format: YYYY-MM-DDTHH-MM-SSZ-suffix + const chatId = `${ + dateString.replace(/:/g, "-").slice(0, dateString.indexOf(".")) + }Z-${randomSuffix}`; + + return chatId; + } +} diff --git a/src/lib/SessionManager.test.ts b/src/lib/SessionManager.test.ts index bea3f769..8a30e55f 100644 --- a/src/lib/SessionManager.test.ts +++ b/src/lib/SessionManager.test.ts @@ -54,6 +54,7 @@ const testConfig: AppConfig = { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/lib/system.test.ts b/src/lib/system.test.ts index c6f7cfd4..0819f0cb 100644 --- a/src/lib/system.test.ts +++ b/src/lib/system.test.ts @@ -41,6 +41,7 @@ const testConfig: AppConfig = { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/pages/ChatView.tsx b/src/pages/ChatView.tsx new file mode 100644 index 00000000..2b34a33b --- /dev/null +++ b/src/pages/ChatView.tsx @@ -0,0 +1,239 @@ +import { useState, useEffect, useCallback, useRef } from 'react'; +import { useParams, useNavigate } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { type Chat } from '@/lib/ChatsManager'; +import { useChatsManager } from '@/hooks/useChatsManager'; +import { ChatPane, type ChatPaneRef } from '@/components/Shakespeare/ChatPane'; +import { ProjectSidebar } from '@/components/ProjectSidebar'; +import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable'; +import { Button } from '@/components/ui/button'; +import { Skeleton } from '@/components/ui/skeleton'; +import { ArrowLeft, Menu } from 'lucide-react'; +import { ActionsMenu } from '@/components/ActionsMenu'; +import { useIsMobile } from '@/hooks/useIsMobile'; + +export function ChatView() { + const { chatId } = useParams<{ chatId: string }>(); + const { t } = useTranslation(); + const [chat, setChat] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [isAILoading, setIsAILoading] = useState(false); + + const chatsManager = useChatsManager(); + const chatPaneRef = useRef(null); + const navigate = useNavigate(); + const isMobile = useIsMobile(); + + const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile); + + const loadChat = useCallback(async () => { + if (!chatId) return; + + try { + const chatData = await chatsManager.getChat(chatId); + setChat(chatData); + } catch (error) { + console.error('Failed to load chat:', error); + } finally { + setIsLoading(false); + } + }, [chatId, chatsManager]); + + useEffect(() => { + loadChat(); + }, [loadChat]); + + const handleNewChat = () => { + // Call the ChatPane's startNewSession function + if (chatPaneRef.current) { + chatPaneRef.current.startNewSession(); + } + }; + + const handleAILoadingChange = (loading: boolean) => { + setIsAILoading(loading); + }; + + // Handle first user interaction to enable audio context + const handleFirstInteraction = () => { + // This will be handled automatically by the useKeepAlive hook + // when isAILoading becomes true after user interaction + }; + + const handleChatDeleted = async () => { + setChat(null); + navigate('/'); + }; + + if (!chat && !isLoading) { + return ( +
+
+

Chat Not Found

+ +
+
+ ); + } + + if (isMobile) { + return ( +
+
+
+
+ +
+ {chat ? ( +
+ {chat.name} +
+ ) : ( + + )} +
+
+ +
+ {chat ? ( + + ) : ( + + )} +
+
+
+ + {/* Mobile Sidebar Overlay */} + {isSidebarVisible && ( +
+ {/* Backdrop - only covers the area not occupied by the sidebar */} +
setIsSidebarVisible(false)} + /> + + {/* Sidebar */} +
+ {}} + onClose={() => setIsSidebarVisible(false)} + /> +
+
+ )} + +
+ {chat && ( + + )} +
+
+ ); + } + + // Desktop layout + return ( +
+ + {isSidebarVisible && ( + <> + + {}} + onToggleSidebar={() => setIsSidebarVisible(false)} + /> + + + + )} + + +
+
+
+
+ {!isSidebarVisible && ( + + )} +
+ {chat ? ( +
+ {chat.name} +
+ ) : ( + + )} +
+
+ +
+ {chat ? ( + + ) : ( + + )} +
+
+
+ +
+ {chat && ( + + )} +
+
+
+
+
+ ); +} diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index ea6f731c..6f9973ad 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -2,12 +2,14 @@ import { useState, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; +import { useChatsManager } from '@/hooks/useChatsManager'; import { useGenerateProjectInfo } from '@/hooks/useGenerateProjectInfo'; import { useFS } from '@/hooks/useFS'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; import { useAISettings } from '@/hooks/useAISettings'; import { useAppContext } from '@/hooks/useAppContext'; +import { ChatsManager } from '@/lib/ChatsManager'; import { AppLayout } from '@/components/AppLayout'; import { OnboardingDialog } from '@/components/OnboardingDialog'; import { Act1Dialog } from '@/components/Act1Dialog'; @@ -40,6 +42,7 @@ export default function Index() { const navigate = useNavigate(); const location = useLocation(); const projectsManager = useProjectsManager(); + const chatsManager = useChatsManager(); const { fs } = useFS(); const { generateProjectInfo, isLoading: isGeneratingInfo } = useGenerateProjectInfo(); const { settings, addRecentlyUsedModel } = useAISettings(); @@ -218,64 +221,93 @@ export default function Index() { const handleCreateProject = async () => { if (!prompt.trim() || !providerModel.trim()) return; - // Clear stored prompt when creating project + // Clear stored prompt when creating project/chat setStoredPrompt(''); setIsCreating(true); try { - // Use AI to generate project ID and select template - const { projectId, template } = await generateProjectInfo(providerModel, prompt.trim()); + // Use AI to determine whether to create a project or start a chat + const result = await generateProjectInfo(providerModel, prompt.trim()); - // Add model to recently used when creating project with AI + // Add model to recently used addRecentlyUsedModel(providerModel.trim()); - // Create project with AI-generated ID and selected template - const project = await projectsManager.createProject( - prompt.trim(), - template.url, - projectId, - () => { - // Show a toast if template update fails (non-critical) - toast({ - title: t('templateUpdateFailed'), - description: t('templateUpdateFailedDescription'), - variant: 'default', - }); - }, - { name: template.name, description: template.description } - ); + if (result.type === 'chat') { + // Create a chat + const { chatId } = result.info; - // Build message content from input and attached files - // Images are converted to base64-encoded data URLs - const messageContent = await buildMessageContent( - prompt.trim(), - attachedFiles, - fs, - undefined - ); + // Generate unique chat ID with timestamp if needed + let finalChatId = chatId; + const existingChat = await chatsManager.getChat(chatId); + if (existingChat !== null) { + // Chat exists, generate unique ID with timestamp + finalChatId = ChatsManager.generateChatId(); + } - // Store the initial message in chat history using DotAI - const dotAI = new DotAI(fs, `${config.fsPathProjects}/${project.id}`); - const sessionName = DotAI.generateSessionName(); + // Create chat with initial message + await chatsManager.createChat(finalChatId, prompt.trim()); - const initialMessage: AIMessage = { - role: 'user', - content: messageContent - }; - await dotAI.setHistory(sessionName, [initialMessage]); + // Clear attached files after successful creation + setAttachedFiles([]); - // Clear attached files after successful creation - setAttachedFiles([]); + // Navigate to the chat with autostart parameter and model + const searchParams = new URLSearchParams({ + autostart: 'true', + ...(providerModel.trim() && { model: providerModel.trim() }) + }); + navigate(`/chat/${finalChatId}?${searchParams.toString()}`); + } else { + // Create a project + const { projectId, template } = result.info; - // Navigate to the project with autostart parameter and model - const searchParams = new URLSearchParams({ - autostart: 'true', - build: 'true', - ...(providerModel.trim() && { model: providerModel.trim() }) - }); - navigate(`/project/${project.id}?${searchParams.toString()}`); + // Create project with AI-generated ID and selected template + const project = await projectsManager.createProject( + prompt.trim(), + template.url, + projectId, + () => { + // Show a toast if template update fails (non-critical) + toast({ + title: t('templateUpdateFailed'), + description: t('templateUpdateFailedDescription'), + variant: 'default', + }); + }, + { name: template.name, description: template.description } + ); + + // Build message content from input and attached files + // Images are converted to base64-encoded data URLs + const messageContent = await buildMessageContent( + prompt.trim(), + attachedFiles, + fs, + undefined + ); + + // Store the initial message in chat history using DotAI + const dotAI = new DotAI(fs, `${config.fsPathProjects}/${project.id}`); + const sessionName = DotAI.generateSessionName(); + + const initialMessage: AIMessage = { + role: 'user', + content: messageContent + }; + await dotAI.setHistory(sessionName, [initialMessage]); + + // Clear attached files after successful creation + setAttachedFiles([]); + + // Navigate to the project with autostart parameter and model + const searchParams = new URLSearchParams({ + autostart: 'true', + build: 'true', + ...(providerModel.trim() && { model: providerModel.trim() }) + }); + navigate(`/project/${project.id}?${searchParams.toString()}`); + } } catch (error) { - console.error('Failed to create project:', error); + console.error('Failed to create project/chat:', error); setQuillyError(error instanceof Error ? error : new Error("An unexpected error occurred")); } finally { setIsCreating(false); diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index 660418e4..32acc0be 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -55,6 +55,7 @@ export function TestApp({ children }: TestAppProps) { fsPathTmp: '/tmp', fsPathPlugins: '/plugins', fsPathTemplates: '/templates', + fsPathChats: '/chats', sentryDsn: '', sentryEnabled: false, }; From d3187d8c77397f9648bd572f10a6cff76282a2e9 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 01:11:39 -0600 Subject: [PATCH 02/12] Improve chats icon --- src/components/ProjectSidebar.tsx | 4 +- src/components/Shakespeare/ChatPane.tsx | 1 + src/hooks/useAIChat.ts | 8 ++-- src/lib/SessionManager.ts | 62 +++++++++++++++++++++---- 4 files changed, 60 insertions(+), 15 deletions(-) diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 980ba8e5..7532306c 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,7 +1,7 @@ import React, { useEffect, useState, useMemo } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Search, MessageSquare } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Search, MessageSquareText } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { Input } from '@/components/ui/input'; @@ -105,7 +105,7 @@ const ChatItem: React.FC = ({ chat, isSelected, onSelect }) => { />
- +
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index c3f244b9..fce517b7 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -273,6 +273,7 @@ export const ChatPane = forwardRef(({ customTools, onUpdateMetadata, onAIError, + workingDir: isChat ? cwd : undefined, // Pass working dir for chats }); // Check if we should show the template info banner diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index 5a2d3ac5..81dd7704 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -13,6 +13,7 @@ interface UseAIChatSessionOptions { maxSteps?: number; onUpdateMetadata?: (title: string, description: string) => void; onAIError?: (error: Error) => void; + workingDir?: string; // Optional working directory (for chats) } interface StreamingMessage { @@ -32,7 +33,8 @@ export function useAIChat({ customTools = {}, maxSteps = 50, onUpdateMetadata, - onAIError + onAIError, + workingDir }: UseAIChatSessionOptions) { const sessionManager = useSessionManager(); const { isConfigured } = useAISettings(); @@ -46,14 +48,14 @@ export function useAIChat({ const initSession = useCallback(async () => { // Load or update session - const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps); + const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps, workingDir); // Initialize individual state variables from existing session setMessages([...session.messages]); setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined); setIsLoading(session.isLoading); setTotalCost(session.totalCost || 0); setLastInputTokens(session.lastInputTokens || 0); - }, [sessionManager, projectId, tools, customTools, maxSteps]); + }, [sessionManager, projectId, tools, customTools, maxSteps, workingDir]); // Initialize session useEffect(() => { diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index a007c939..4c20b10b 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -41,6 +41,7 @@ export interface SessionState { totalCost?: number; // Total cost in USD for this session lastInputTokens?: number; // Input tokens from the last AI request imagesNotSupported?: boolean; // Track if this session's model doesn't support images + workingDir?: string; // Working directory (for chats, different from projects) } export interface SessionManagerEvents { @@ -93,13 +94,14 @@ export class SessionManager { } /** - * Create a new session for a project + * Create a new session for a project or chat */ async loadSession( projectId: string, tools: Record, customTools: Record>, - maxSteps?: number + maxSteps?: number, + workingDir?: string // Optional working directory (for chats, use chatsPath instead of projectsPath) ): Promise { let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []; let sessionName = DotAI.generateSessionName(); @@ -107,11 +109,36 @@ export class SessionManager { // Try to load existing history try { const config = this.getConfig(); - const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`); - const lastSession = await dotAI.readLastSessionHistory(); - if (lastSession) { - messages = lastSession.messages; - sessionName = lastSession.sessionName; + const dir = workingDir || `${config.fsPathProjects}/${projectId}`; + + // For chats, load messages from messages.jsonl directly + if (workingDir && workingDir.includes(config.fsPathChats)) { + const messagesPath = `${dir}/messages.jsonl`; + try { + const content = await this.fs.readFile(messagesPath, 'utf8'); + const lines = content.trim().split('\n').filter(line => line.trim()); + + for (const line of lines) { + try { + const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam; + messages.push(message); + } catch (parseError) { + console.warn('Failed to parse message from chat:', parseError); + } + } + + sessionName = 'messages'; // Use a fixed session name for chats + } catch (readError) { + console.warn('Failed to read chat messages:', readError); + } + } else { + // For projects, use DotAI to load from .git/ai/history + const dotAI = new DotAI(this.fs, dir); + const lastSession = await dotAI.readLastSessionHistory(); + if (lastSession) { + messages = lastSession.messages; + sessionName = lastSession.sessionName; + } } } catch (error) { console.warn('Failed to load session history:', error); @@ -129,6 +156,7 @@ export class SessionManager { ...this.sessions.get(projectId), messages, sessionName, + workingDir, }; // Update session configuration @@ -732,9 +760,23 @@ export class SessionManager { try { const config = this.getConfig(); - const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`); - // Cast to ChatCompletionMessageParam[] - user messages with image arrays are valid - await dotAI.setHistory(session.sessionName, session.messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[]); + + // For chats, save directly to messages.jsonl + if (session.workingDir && session.workingDir.includes(config.fsPathChats)) { + const messagesPath = `${session.workingDir}/messages.jsonl`; + + // Convert messages to JSONL format + const jsonlContent = session.messages.map(message => JSON.stringify(message)).join('\n'); + const finalContent = jsonlContent + (session.messages.length > 0 ? '\n' : ''); + + // Write the entire file + await this.fs.writeFile(messagesPath, finalContent); + } else { + // For projects, use DotAI to save to .git/ai/history + const dotAI = new DotAI(this.fs, session.workingDir || `${config.fsPathProjects}/${session.projectId}`); + // Cast to ChatCompletionMessageParam[] - user messages with image arrays are valid + await dotAI.setHistory(session.sessionName, session.messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[]); + } } catch (error) { console.warn('Failed to save session history:', error); } From 2c42efd4e15224ea77353c6639526b7fc5498898 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 01:27:37 -0600 Subject: [PATCH 03/12] Skip somethings for chats idk --- src/components/Shakespeare/ChatPane.tsx | 1 + src/hooks/useAIChat.ts | 8 ++-- src/lib/SessionManager.ts | 57 ++++++++++++++++--------- 3 files changed, 44 insertions(+), 22 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index fce517b7..3dc8956d 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -274,6 +274,7 @@ export const ChatPane = forwardRef(({ onUpdateMetadata, onAIError, workingDir: isChat ? cwd : undefined, // Pass working dir for chats + isChat, // Pass isChat flag }); // Check if we should show the template info banner diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index 81dd7704..3fe6589e 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -14,6 +14,7 @@ interface UseAIChatSessionOptions { onUpdateMetadata?: (title: string, description: string) => void; onAIError?: (error: Error) => void; workingDir?: string; // Optional working directory (for chats) + isChat?: boolean; // Whether this is a chat session (vs a project session) } interface StreamingMessage { @@ -34,7 +35,8 @@ export function useAIChat({ maxSteps = 50, onUpdateMetadata, onAIError, - workingDir + workingDir, + isChat }: UseAIChatSessionOptions) { const sessionManager = useSessionManager(); const { isConfigured } = useAISettings(); @@ -48,14 +50,14 @@ export function useAIChat({ const initSession = useCallback(async () => { // Load or update session - const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps, workingDir); + const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps, workingDir, isChat); // Initialize individual state variables from existing session setMessages([...session.messages]); setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined); setIsLoading(session.isLoading); setTotalCost(session.totalCost || 0); setLastInputTokens(session.lastInputTokens || 0); - }, [sessionManager, projectId, tools, customTools, maxSteps, workingDir]); + }, [sessionManager, projectId, tools, customTools, maxSteps, workingDir, isChat]); // Initialize session useEffect(() => { diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 4c20b10b..dec8e2e1 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -42,6 +42,7 @@ export interface SessionState { lastInputTokens?: number; // Input tokens from the last AI request imagesNotSupported?: boolean; // Track if this session's model doesn't support images workingDir?: string; // Working directory (for chats, different from projects) + isChat?: boolean; // Whether this is a chat session (vs a project session) } export interface SessionManagerEvents { @@ -101,7 +102,8 @@ export class SessionManager { tools: Record, customTools: Record>, maxSteps?: number, - workingDir?: string // Optional working directory (for chats, use chatsPath instead of projectsPath) + workingDir?: string, // Optional working directory (for chats, use chatsPath instead of projectsPath) + isChat?: boolean // Whether this is a chat session (vs a project session) ): Promise { let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []; let sessionName = DotAI.generateSessionName(); @@ -112,7 +114,7 @@ export class SessionManager { const dir = workingDir || `${config.fsPathProjects}/${projectId}`; // For chats, load messages from messages.jsonl directly - if (workingDir && workingDir.includes(config.fsPathChats)) { + if (isChat) { const messagesPath = `${dir}/messages.jsonl`; try { const content = await this.fs.readFile(messagesPath, 'utf8'); @@ -157,14 +159,16 @@ export class SessionManager { messages, sessionName, workingDir, + isChat, }; // Update session configuration session.projectId = projectId; session.tools = tools; - session.customTools = customTools; session.maxSteps = maxSteps; + session.workingDir = workingDir; + session.isChat = isChat; this.sessions.set(projectId, session); @@ -285,27 +289,33 @@ export class SessionManager { tool_calls: undefined }; - // Get repository URL if available + const workingDir = session.workingDir || `${config.fsPathProjects}/${projectId}`; + + // Get repository URL if available (skip for chats) let repositoryUrl: string | undefined; - try { - const remoteUrl = await this.git.getRemoteURL(`${config.fsPathProjects}/${projectId}`, 'origin'); - repositoryUrl = remoteUrl || undefined; - } catch { - // No repository URL available + if (!session.isChat) { + try { + const remoteUrl = await this.git.getRemoteURL(workingDir, 'origin'); + repositoryUrl = remoteUrl || undefined; + } catch { + // No repository URL available + } } - // Get project template metadata if available + // Get project template metadata if available (skip for chats) let projectTemplate: { name: string; description: string; url: string } | undefined; - try { - const dotai = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`); - const template = await dotai.readTemplate(); - projectTemplate = template || undefined; - } catch { - // Template metadata not available + if (!session.isChat) { + try { + const dotai = new DotAI(this.fs, workingDir); + const template = await dotai.readTemplate(); + projectTemplate = template || undefined; + } catch { + // Template metadata not available + } } const systemPrompt = await makeSystemPrompt({ - cwd: `${config.fsPathProjects}/${projectId}`, + cwd: workingDir, fs: this.fs, mode: "agent", tools: Object.values(session.tools), @@ -762,7 +772,7 @@ export class SessionManager { const config = this.getConfig(); // For chats, save directly to messages.jsonl - if (session.workingDir && session.workingDir.includes(config.fsPathChats)) { + if (session.isChat) { const messagesPath = `${session.workingDir}/messages.jsonl`; // Convert messages to JSONL format @@ -786,9 +796,18 @@ export class SessionManager { * Accumulate request cost to the project's total cost file */ private async accumulateProjectCost(projectId: string, requestCost: number): Promise { + const session = this.sessions.get(projectId); + if (!session) return; + try { const config = this.getConfig(); - const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`); + + // Skip cost accumulation for chats (they don't have .git/shakespeare/COST files) + if (session.isChat) { + return; + } + + const dotAI = new DotAI(this.fs, session.workingDir || `${config.fsPathProjects}/${projectId}`); // Read current project total const currentTotal = await dotAI.readCost(); From bb9245118c940e18ce52913fcbb16fa1ae92de46 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 01:33:34 -0600 Subject: [PATCH 04/12] Refresh sidebar when starting new chat, allow more characters in chat title --- src/hooks/useGenerateProjectInfo.ts | 24 ++++++++++++++---------- src/pages/Index.tsx | 5 +++++ 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/hooks/useGenerateProjectInfo.ts b/src/hooks/useGenerateProjectInfo.ts index 89a4fe6a..6a12dd0b 100644 --- a/src/hooks/useGenerateProjectInfo.ts +++ b/src/hooks/useGenerateProjectInfo.ts @@ -122,7 +122,7 @@ export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOption properties: { chat_name: { type: 'string', - description: 'A short, descriptive name for the chat. Should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens.', + description: 'A short, descriptive name for the chat (2-50 characters). Use natural language with spaces, capitalization, and common punctuation. Avoid special characters that are invalid in filenames (/, \\, :, *, ?, ", <, >, |).', }, }, required: ['chat_name'], @@ -143,8 +143,10 @@ export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOption ${config.templates.map(t => ` - ${t.name}: ${t.description} (${t.url})`).join('\n')} 2. If the user wants to **start a chat** (general conversation, questions, brainstorming) - use start_chat tool - - Generate a short, descriptive name for the chat topic - - Name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens + - Generate a short, descriptive name for the chat (2-50 characters) + - Use natural, readable language with proper capitalization and spaces + - Examples: "Answer to your question", "JavaScript help", "Recipe ideas" + - Avoid special characters that are invalid in filenames: / \\ : * ? " < > | You MUST call either start_project or start_chat based on the user's intent.`; @@ -172,21 +174,23 @@ You MUST call either start_project or start_chat based on the user's intent.`; // Handle start_chat tool call if (toolCall.function.name === 'start_chat') { - const chatId = args.chat_name as string; + const chatName = args.chat_name as string; - // Validate the generated chat ID - const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/; - if (chatId && chatId.length <= 50 && validIdRegex.test(chatId)) { + // Validate the chat name - allow most characters except filesystem-invalid ones + // Invalid characters: / \ : * ? " < > | + const invalidCharsRegex = /[\/\\:*?"<>|]/; + + if (chatName && chatName.length >= 2 && chatName.length <= 50 && !invalidCharsRegex.test(chatName)) { return { type: 'chat', - info: { chatId }, + info: { chatId: chatName.trim() }, }; } - // Fallback to auto-generated chat ID if validation fails + // Fallback to descriptive name if validation fails return { type: 'chat', - info: { chatId: 'chat' }, + info: { chatId: 'New chat' }, }; } diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 6f9973ad..0571cd98 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -10,6 +10,7 @@ import { useIsMobile } from '@/hooks/useIsMobile'; import { useAISettings } from '@/hooks/useAISettings'; import { useAppContext } from '@/hooks/useAppContext'; import { ChatsManager } from '@/lib/ChatsManager'; +import { useQueryClient } from '@tanstack/react-query'; import { AppLayout } from '@/components/AppLayout'; import { OnboardingDialog } from '@/components/OnboardingDialog'; import { Act1Dialog } from '@/components/Act1Dialog'; @@ -41,6 +42,7 @@ export default function Index() { const [giftCardCode, setGiftCardCode] = useState(''); const navigate = useNavigate(); const location = useLocation(); + const queryClient = useQueryClient(); const projectsManager = useProjectsManager(); const chatsManager = useChatsManager(); const { fs } = useFS(); @@ -247,6 +249,9 @@ export default function Index() { // Create chat with initial message await chatsManager.createChat(finalChatId, prompt.trim()); + // Invalidate chats query to update sidebar + queryClient.invalidateQueries({ queryKey: ['chats'] }); + // Clear attached files after successful creation setAttachedFiles([]); From 4f552334b231d8608ecee51b4d212e8eed24f893 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 01:40:28 -0600 Subject: [PATCH 05/12] Allow deleting a chat --- src/components/ActionsMenu.tsx | 46 ++++++++--- src/components/DeleteChatDialog.tsx | 99 +++++++++++++++++++++++ src/pages/ChatView.tsx | 118 +++++++++++++++++++++++++--- 3 files changed, 240 insertions(+), 23 deletions(-) create mode 100644 src/components/DeleteChatDialog.tsx diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index 59c2d4a3..638d118c 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -13,10 +13,12 @@ import { History, Folder, Rocket, + Trash2, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { GitDialog } from '@/components/GitDialog'; import { DeployDialog } from '@/components/DeployDialog'; +import { DeleteChatDialog } from '@/components/DeleteChatDialog'; interface ActionsMenuProps { projectId: string; @@ -28,6 +30,7 @@ interface ActionsMenuProps { disabled?: boolean; onFirstInteraction?: () => void; isChat?: boolean; // Flag to indicate this is a chat, not a project + onChatDeleted?: () => void; // Callback when a chat is deleted } export function ActionsMenu({ @@ -40,10 +43,12 @@ export function ActionsMenu({ disabled = false, onFirstInteraction: _onFirstInteraction, isChat = false, + onChatDeleted, }: ActionsMenuProps) { const [gitHistoryOpen, setGitHistoryOpen] = useState(false); const [gitDialogOpen, setGitDialogOpen] = useState(false); const [deployDialogOpen, setDeployDialogOpen] = useState(false); + const [deleteChatOpen, setDeleteChatOpen] = useState(false); const isAnyLoading = isLoading || isBuildLoading; @@ -64,17 +69,26 @@ export function ActionsMenu({ - - - New Chat - - - {!isChat && ( + {isChat ? ( + setDeleteChatOpen(true)} + disabled={isLoading} + className="gap-2 text-destructive focus:text-destructive" + > + + Delete Chat + + ) : ( <> + + + New Chat + + setGitHistoryOpen(true)} disabled={isAnyLoading} @@ -112,8 +126,6 @@ export function ActionsMenu({ )} - - @@ -141,6 +153,16 @@ export function ActionsMenu({ )} + {/* Delete Chat Dialog - only show for chats */} + {isChat && ( + + )} ); } \ No newline at end of file diff --git a/src/components/DeleteChatDialog.tsx b/src/components/DeleteChatDialog.tsx new file mode 100644 index 00000000..f36fc92c --- /dev/null +++ b/src/components/DeleteChatDialog.tsx @@ -0,0 +1,99 @@ +import { useState } from 'react'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog'; +import { useChatsManager } from '@/hooks/useChatsManager'; +import { useToast } from '@/hooks/useToast'; +import { useQueryClient } from '@tanstack/react-query'; +import { Loader2 } from 'lucide-react'; + +interface DeleteChatDialogProps { + chatId: string; + chatName: string; + open: boolean; + onOpenChange: (open: boolean) => void; + onDeleted?: () => void; +} + +export function DeleteChatDialog({ + chatId, + chatName, + open, + onOpenChange, + onDeleted, +}: DeleteChatDialogProps) { + const [isDeleting, setIsDeleting] = useState(false); + const chatsManager = useChatsManager(); + const { toast } = useToast(); + const queryClient = useQueryClient(); + + const handleDelete = async () => { + setIsDeleting(true); + + try { + await chatsManager.deleteChat(chatId); + + // Invalidate the chats query to refresh the sidebar + await queryClient.invalidateQueries({ queryKey: ['chats'] }); + + toast({ + title: 'Chat deleted', + description: `${chatName} has been deleted successfully.`, + }); + + onOpenChange(false); + + // Call the onDeleted callback if provided + if (onDeleted) { + onDeleted(); + } + } catch (error) { + console.error('Failed to delete chat:', error); + toast({ + title: 'Error', + description: 'Failed to delete chat. Please try again.', + variant: 'destructive', + }); + } finally { + setIsDeleting(false); + } + }; + + return ( + + + + Delete Chat + + Are you sure you want to delete "{chatName}"? This action cannot be undone and all + messages will be permanently deleted. + + + + Cancel + + {isDeleting ? ( + <> + + Deleting... + + ) : ( + 'Delete' + )} + + + + + ); +} diff --git a/src/pages/ChatView.tsx b/src/pages/ChatView.tsx index 2b34a33b..b6a00ea2 100644 --- a/src/pages/ChatView.tsx +++ b/src/pages/ChatView.tsx @@ -60,21 +60,115 @@ export function ChatView() { // when isAILoading becomes true after user interaction }; - const handleChatDeleted = async () => { - setChat(null); + const handleChatDeleted = () => { + // Navigate to home page after chat is deleted navigate('/'); }; + // Chat not found - show in app layout with sidebar if (!chat && !isLoading) { - return ( -
-
-

Chat Not Found

- + if (isMobile) { + return ( +
+
+
+
+ +
Chat Not Found
+
+
+
+ + {/* Mobile Sidebar Overlay */} + {isSidebarVisible && ( +
+
setIsSidebarVisible(false)} + /> +
+ {}} + onClose={() => setIsSidebarVisible(false)} + /> +
+
+ )} + +
+
+

Chat Not Found

+

+ This chat may have been deleted or doesn't exist. +

+ +
+
+ ); + } + + // Desktop layout for not found + return ( +
+ + {isSidebarVisible && ( + <> + + {}} + onToggleSidebar={() => setIsSidebarVisible(false)} + /> + + + + )} + + +
+
+
+
+ {!isSidebarVisible && ( + + )} +
Chat Not Found
+
+
+
+ +
+
+

Chat Not Found

+

+ This chat may have been deleted or doesn't exist. +

+ +
+
+
+
+
); } @@ -113,6 +207,7 @@ export function ChatView() { isBuildLoading={false} onFirstInteraction={handleFirstInteraction} isChat={true} + onChatDeleted={handleChatDeleted} /> ) : ( @@ -129,7 +224,7 @@ export function ChatView() { className="absolute inset-0" onClick={() => setIsSidebarVisible(false)} /> - + {/* Sidebar */}
) : ( From 0c42af082a04ede3db0dd96e3c8fe6c00c5ac7b0 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 01:41:10 -0600 Subject: [PATCH 06/12] Improve Chat Not Found design --- src/pages/ChatView.tsx | 47 ++++++++++++++++++------------------------ 1 file changed, 20 insertions(+), 27 deletions(-) diff --git a/src/pages/ChatView.tsx b/src/pages/ChatView.tsx index b6a00ea2..57fe2414 100644 --- a/src/pages/ChatView.tsx +++ b/src/pages/ChatView.tsx @@ -72,16 +72,13 @@ export function ChatView() {
-
- -
Chat Not Found
-
+
@@ -137,24 +134,20 @@ export function ChatView() {
-
-
-
- {!isSidebarVisible && ( - - )} -
Chat Not Found
-
-
-
-
+ {/* Menu button when sidebar is collapsed */} + {!isSidebarVisible && ( +
+ +
+ )} +

Chat Not Found

From 300fd262680605d96f5f3f4ad4f3b385791ad3f5 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 01:45:16 -0600 Subject: [PATCH 07/12] Add max width to text chats --- src/components/Shakespeare/ChatInput.tsx | 2 +- src/components/Shakespeare/ChatPane.tsx | 46 ++++++++++++------------ 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/src/components/Shakespeare/ChatInput.tsx b/src/components/Shakespeare/ChatInput.tsx index fe917d4b..d08cc2b3 100644 --- a/src/components/Shakespeare/ChatInput.tsx +++ b/src/components/Shakespeare/ChatInput.tsx @@ -117,7 +117,7 @@ export const ChatInput = memo(function ChatInput({ }, []); return ( -

+
{/* Chat Input Container */}
(({
-
+
{/* Template info banner - shown when conditions are met */} {showTemplateInfo && templateInfo && (
@@ -710,27 +710,29 @@ export const ChatPane = forwardRef(({
)} - +
+ +
{/* Onboarding Dialog */} Date: Wed, 3 Dec 2025 01:53:05 -0600 Subject: [PATCH 08/12] No useless escape --- src/hooks/useGenerateProjectInfo.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hooks/useGenerateProjectInfo.ts b/src/hooks/useGenerateProjectInfo.ts index 6a12dd0b..4fc39d00 100644 --- a/src/hooks/useGenerateProjectInfo.ts +++ b/src/hooks/useGenerateProjectInfo.ts @@ -178,7 +178,7 @@ You MUST call either start_project or start_chat based on the user's intent.`; // Validate the chat name - allow most characters except filesystem-invalid ones // Invalid characters: / \ : * ? " < > | - const invalidCharsRegex = /[\/\\:*?"<>|]/; + const invalidCharsRegex = /[/\\:*?"<>|]/; if (chatName && chatName.length >= 2 && chatName.length <= 50 && !invalidCharsRegex.test(chatName)) { return { From ca0ae22cd35013f97523e56eb5993ace84588794 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 02:00:47 -0600 Subject: [PATCH 09/12] Add start_project tool to text chats --- src/components/Shakespeare/ChatPane.tsx | 31 ++++++- src/lib/ChatsManager.ts | 3 +- src/lib/tools/StartProjectTool.ts | 102 ++++++++++++++++++++++++ src/pages/ChatView.tsx | 2 - 4 files changed, 131 insertions(+), 7 deletions(-) create mode 100644 src/lib/tools/StartProjectTool.ts diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index e215609a..ef51bcb0 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -1,5 +1,5 @@ import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo, useCallback } from 'react'; -import { useSearchParams } from 'react-router-dom'; +import { useSearchParams, useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; @@ -36,12 +36,15 @@ import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool'; import { SkillTool } from '@/lib/tools/SkillTool'; +import { StartProjectTool } from '@/lib/tools/StartProjectTool'; import { createMCPTools } from '@/lib/tools/MCPTool'; import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; import { useGit } from '@/hooks/useGit'; +import { useProjectsManager } from '@/hooks/useProjectsManager'; +import type { StartProjectResult } from '@/lib/tools/StartProjectTool'; import { Quilly } from '@/components/Quilly'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; import { ChatInput } from '@/components/Shakespeare/ChatInput'; @@ -78,12 +81,14 @@ export const ChatPane = forwardRef(({ onDismissConsoleError, }, ref) => { const { t } = useTranslation(); + const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); const { git } = useGit(); const { user } = useCurrentUser(); const { models } = useProviderModels(); const { config } = useAppContext(); + const projectsManager = useProjectsManager(); const { projectsPath, tmpPath, pluginsPath } = useFSPaths(); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [isDragOver, setIsDragOver] = useState(false); @@ -136,6 +141,7 @@ export const ChatPane = forwardRef(({ const newSearchParams = new URLSearchParams(searchParams); newSearchParams.delete('autostart'); newSearchParams.delete('model'); + newSearchParams.delete('message'); setSearchParams(newSearchParams, { replace: true }); }, [providerModel, searchParams, setSearchParams]) @@ -156,6 +162,15 @@ export const ChatPane = forwardRef(({ sessionManager.emit('fileChanged', projectId, filePath); }, [sessionManager, projectId]); + // Callback for when a project is created via start_project tool + const handleProjectCreated = useCallback((result: StartProjectResult) => { + // Stop current chat generation + sessionManager.stopGeneration(projectId); + + // Navigate to the new project with the initial message and autostart + navigate(`/project/${result.projectId}?message=${encodeURIComponent(result.initialMessage)}&autostart=true`); + }, [sessionManager, projectId, navigate]); + // Fetch MCP tools const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools(); @@ -172,7 +187,7 @@ export const ChatPane = forwardRef(({ nostr_read_nips_index: new NostrReadNipsIndexTool(), nostr_generate_kind: new NostrGenerateKindTool(), nostr_publish_events: new NostrPublishEventsTool(), - // TODO: Add start_project tool here + start_project: new StartProjectTool(projectsManager, config, handleProjectCreated), }; return tools; } @@ -206,7 +221,7 @@ export const ChatPane = forwardRef(({ } return tools; - }, [isChat, fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]); + }, [isChat, fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config, projectsManager, handleProjectCreated, handleFileChanged]); // MCP tools wrapped for execution const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]); @@ -277,6 +292,16 @@ export const ChatPane = forwardRef(({ isChat, // Pass isChat flag }); + // Handle initial message from URL parameter + useEffect(() => { + const initialMessage = searchParams.get('message'); + + // Only add the initial message if there are no existing messages + if (initialMessage && messages.length === 0) { + addMessage({ role: 'user', content: initialMessage }); + } + }, [searchParams, messages.length, addMessage]); + // Check if we should show the template info banner useEffect(() => { const checkTemplateInfo = async () => { diff --git a/src/lib/ChatsManager.ts b/src/lib/ChatsManager.ts index d101e481..f681729d 100644 --- a/src/lib/ChatsManager.ts +++ b/src/lib/ChatsManager.ts @@ -1,5 +1,4 @@ import type { JSRuntimeFS } from '@/lib/JSRuntime'; -import { DotAI } from '@/lib/DotAI'; import type OpenAI from 'openai'; export interface Chat { @@ -216,7 +215,7 @@ export class ChatsManager { try { const messageJson = JSON.stringify(message) + '\n'; - + // Append to the file try { const existingContent = await this.fs.readFile(messagesPath, 'utf8'); diff --git a/src/lib/tools/StartProjectTool.ts b/src/lib/tools/StartProjectTool.ts new file mode 100644 index 00000000..6cce68e0 --- /dev/null +++ b/src/lib/tools/StartProjectTool.ts @@ -0,0 +1,102 @@ +import { z } from "zod"; +import type { Tool } from "./Tool"; +import type { ProjectsManager } from "@/lib/ProjectsManager"; +import type { AppConfig } from "@/contexts/AppContext"; + +const startProjectSchema = z.object({ + project_name: z.string().describe('A short, unique, and memorable name for the project. Should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens.'), + template_url: z.string().describe('The Git URL of the selected template.'), + initial_message: z.string().describe('The initial user message that will start the project chat session.'), +}); + +type StartProjectParams = z.infer; + +export interface StartProjectResult { + projectId: string; + initialMessage: string; +} + +export class StartProjectTool implements Tool { + private projectsManager: ProjectsManager; + private config: AppConfig; + private onProjectCreated: (result: StartProjectResult) => void; + + readonly description: string; + readonly inputSchema = startProjectSchema; + + constructor( + projectsManager: ProjectsManager, + config: AppConfig, + onProjectCreated: (result: StartProjectResult) => void + ) { + this.projectsManager = projectsManager; + this.config = config; + this.onProjectCreated = onProjectCreated; + + // Build description with available templates + const templatesList = config.templates.map(t => ` - ${t.name}: ${t.description} (${t.url})`).join('\n'); + + this.description = `Start a new project by choosing a name and selecting the most appropriate template. Call this when the user wants to build an app or website. + +Available templates: +${templatesList} + +After creating the project, the chat session will be stopped and the new project will be opened with the initial message.`; + } + + async execute(args: StartProjectParams): Promise { + const { project_name, template_url, initial_message } = args; + + // Validate template URL + const selectedTemplate = this.config.templates.find(t => t.url === template_url); + if (!selectedTemplate) { + throw new Error(`Invalid template URL: ${template_url}. Must be one of: ${this.config.templates.map(t => t.url).join(', ')}`); + } + + // Validate the generated project ID + const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/; + let projectId = project_name; + + if (!projectId || projectId.length > 50 || !validIdRegex.test(projectId)) { + throw new Error(`Invalid project name: ${project_name}. Must be lowercase, use hyphens instead of spaces, contain only alphanumeric characters and hyphens, and be 50 characters or less.`); + } + + // Check if project exists and generate incremented name if needed + let existingProject = await this.projectsManager.getProject(projectId); + + if (existingProject !== null) { + // Project already exists - increment the AI-generated ID + let counter = 1; + let fallbackId = `${projectId}-${counter}`; + existingProject = await this.projectsManager.getProject(fallbackId); + + while (existingProject !== null) { + counter++; + fallbackId = `${projectId}-${counter}`; + existingProject = await this.projectsManager.getProject(fallbackId); + } + + projectId = fallbackId; + } + + // Create the project + await this.projectsManager.createProject( + projectId, + template_url, + projectId, + undefined, + { + name: selectedTemplate.name, + description: selectedTemplate.description, + } + ); + + // Trigger the callback to navigate to the new project + this.onProjectCreated({ + projectId, + initialMessage: initial_message, + }); + + return `✅ Successfully created project "${projectId}" using template "${selectedTemplate.name}". Opening project now...`; + } +} diff --git a/src/pages/ChatView.tsx b/src/pages/ChatView.tsx index 57fe2414..6f3b3fcb 100644 --- a/src/pages/ChatView.tsx +++ b/src/pages/ChatView.tsx @@ -1,6 +1,5 @@ import { useState, useEffect, useCallback, useRef } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; -import { useTranslation } from 'react-i18next'; import { type Chat } from '@/lib/ChatsManager'; import { useChatsManager } from '@/hooks/useChatsManager'; import { ChatPane, type ChatPaneRef } from '@/components/Shakespeare/ChatPane'; @@ -14,7 +13,6 @@ import { useIsMobile } from '@/hooks/useIsMobile'; export function ChatView() { const { chatId } = useParams<{ chatId: string }>(); - const { t } = useTranslation(); const [chat, setChat] = useState(null); const [isLoading, setIsLoading] = useState(true); const [isAILoading, setIsAILoading] = useState(false); From f8743e3c63d5d4dad1310624a589ff7a9005f407 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 02:25:28 -0600 Subject: [PATCH 10/12] Fix chat autostart --- src/components/SessionMonitor.tsx | 11 ++++--- src/components/Shakespeare/ChatPane.tsx | 43 ++++++++++++++++--------- 2 files changed, 34 insertions(+), 20 deletions(-) diff --git a/src/components/SessionMonitor.tsx b/src/components/SessionMonitor.tsx index 302cf6fc..f3db0bf9 100644 --- a/src/components/SessionMonitor.tsx +++ b/src/components/SessionMonitor.tsx @@ -24,12 +24,13 @@ export function SessionMonitor() { const session = sessionManager.getSession(projectId); if (!session) return; - // Check if user is currently viewing this project - const currentProjectId = location.pathname.split('/')[2]; // /project/{projectId} - const isCurrentProject = session.projectId === currentProjectId; + // Check if user is currently viewing this project or chat + const pathParts = location.pathname.split('/'); + const currentId = pathParts[2]; // /project/{projectId} or /chat/{chatId} + const isCurrentView = session.projectId === currentId; - // Only show notification if user is not currently viewing this project - if (!isCurrentProject) { + // Only show notification if user is not currently viewing this project or chat + if (!isCurrentView) { toast({ title: "AI Session Complete", description: `Finished working on ${session.projectId}`, diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index ef51bcb0..909e59f8 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -141,7 +141,6 @@ export const ChatPane = forwardRef(({ const newSearchParams = new URLSearchParams(searchParams); newSearchParams.delete('autostart'); newSearchParams.delete('model'); - newSearchParams.delete('message'); setSearchParams(newSearchParams, { replace: true }); }, [providerModel, searchParams, setSearchParams]) @@ -163,13 +162,34 @@ export const ChatPane = forwardRef(({ }, [sessionManager, projectId]); // Callback for when a project is created via start_project tool - const handleProjectCreated = useCallback((result: StartProjectResult) => { + const handleProjectCreated = useCallback(async (result: StartProjectResult) => { // Stop current chat generation sessionManager.stopGeneration(projectId); - // Navigate to the new project with the initial message and autostart - navigate(`/project/${result.projectId}?message=${encodeURIComponent(result.initialMessage)}&autostart=true`); - }, [sessionManager, projectId, navigate]); + // Create a minimal set of tools for the new project session + // We don't need the full tools here, just enough to create the session + const projectTools: Record = {}; + const projectCustomTools: Record> = {}; + + // Load the new project's session + await sessionManager.loadSession( + result.projectId, + projectTools, + projectCustomTools, + 50, // maxSteps + undefined, // workingDir (will use default projectsPath) + false // isChat (this is a project, not a chat) + ); + + // Add the initial message to the new project's session + await sessionManager.addMessage(result.projectId, { + role: 'user', + content: result.initialMessage, + }); + + // Navigate to the new project with autostart + navigate(`/project/${result.projectId}?autostart=true&model=${encodeURIComponent(providerModel)}`); + }, [sessionManager, projectId, navigate, providerModel]); // Fetch MCP tools const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools(); @@ -292,15 +312,7 @@ export const ChatPane = forwardRef(({ isChat, // Pass isChat flag }); - // Handle initial message from URL parameter - useEffect(() => { - const initialMessage = searchParams.get('message'); - // Only add the initial message if there are no existing messages - if (initialMessage && messages.length === 0) { - addMessage({ role: 'user', content: initialMessage }); - } - }, [searchParams, messages.length, addMessage]); // Check if we should show the template info banner useEffect(() => { @@ -443,13 +455,14 @@ export const ChatPane = forwardRef(({ useEffect(() => { if (autostartedRef.current) return; - if (shouldAutostart && providerModel && isConfigured) { + // Only autostart if we have messages (initial message has been added) + if (shouldAutostart && providerModel && isConfigured && messages.length > 0) { // Start AI generation addRecentlyUsedModel(providerModel); startGeneration(providerModel); autostartedRef.current = true; } - }, [addRecentlyUsedModel, isConfigured, providerModel, shouldAutostart, startGeneration]); + }, [addRecentlyUsedModel, isConfigured, providerModel, shouldAutostart, startGeneration, messages.length]); // Simple scroll event listener useEffect(() => { From 8cf2b8a9d4d5807be5901a43b85d1a80ba75e3f7 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 02:31:13 -0600 Subject: [PATCH 11/12] Display spinner for text chats --- src/components/ProjectSidebar.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 7532306c..e134d022 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -85,6 +85,7 @@ interface ChatItemProps { const ChatItem: React.FC = ({ chat, isSelected, onSelect }) => { const navigate = useNavigate(); + const { hasRunningSessions } = useProjectSessionStatus(chat.id); const handleClick = () => { onSelect(chat); @@ -105,7 +106,11 @@ const ChatItem: React.FC = ({ chat, isSelected, onSelect }) => { />
- + {hasRunningSessions ? ( + + ) : ( + + )}
From b3f47d41cbe8a368814af832bc29e561c9687aff Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 02:36:40 -0600 Subject: [PATCH 12/12] Don't use flexible sidebar in ChatView --- src/hooks/useGenerateProjectInfo.test.ts | 514 ----------------------- src/pages/ChatView.tsx | 203 +++++---- 2 files changed, 97 insertions(+), 620 deletions(-) delete mode 100644 src/hooks/useGenerateProjectInfo.test.ts diff --git a/src/hooks/useGenerateProjectInfo.test.ts b/src/hooks/useGenerateProjectInfo.test.ts deleted file mode 100644 index 32d3dd6b..00000000 --- a/src/hooks/useGenerateProjectInfo.test.ts +++ /dev/null @@ -1,514 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { renderHook, waitFor } from '@testing-library/react'; -import { useGenerateProjectInfo } from './useGenerateProjectInfo'; -import { useAISettings } from './useAISettings'; -import { useCurrentUser } from './useCurrentUser'; -import { useAppContext } from './useAppContext'; -import { useProjectsManager } from './useProjectsManager'; -import { createAIClient } from '@/lib/ai-client'; -import { parseProviderModel } from '@/lib/parseProviderModel'; -import type { ProjectsManager } from '@/lib/ProjectsManager'; -import type { ProjectTemplate } from '@/contexts/AppContext'; - -// Mock the hooks and dependencies -vi.mock('./useAISettings'); -vi.mock('./useCurrentUser'); -vi.mock('./useAppContext'); -vi.mock('./useProjectsManager'); -vi.mock('@/lib/ai-client'); -vi.mock('@/lib/parseProviderModel'); - -describe('useGenerateProjectInfo', () => { - const mockUseAISettings = vi.mocked(useAISettings); - const mockUseCurrentUser = vi.mocked(useCurrentUser); - const mockUseAppContext = vi.mocked(useAppContext); - const mockUseProjectsManager = vi.mocked(useProjectsManager); - const mockCreateAIClient = vi.mocked(createAIClient); - const mockParseProviderModel = vi.mocked(parseProviderModel); - - const defaultTemplates: ProjectTemplate[] = [ - { - name: "MKStack", - description: "Build Nostr clients with React.", - url: "https://gitlab.com/soapbox-pub/mkstack.git" - }, - { - name: "VanillaJS", - description: "Simple vanilla JavaScript template.", - url: "https://github.com/example/vanilla-template.git" - } - ]; - - let mockGetProject: ReturnType; - - beforeEach(() => { - vi.clearAllMocks(); - - // Mock fetch globally - global.fetch = vi.fn(); - - // Mock useCurrentUser to return undefined user by default - mockUseCurrentUser.mockReturnValue({ - user: undefined, - users: [], - }); - - // Mock useAppContext - const config = { - theme: 'dark' as const, - relayMetadata: { - relays: [{ url: 'wss://relay.damus.io', read: true, write: true }], - updatedAt: 0, - }, - templates: defaultTemplates, - esmUrl: 'https://esm.sh', - corsProxy: 'https://proxy.example.com/{href}', - faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico', - previewDomain: 'local-shakespeare.dev', - showcaseEnabled: true, - showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc', - ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'], - fsPathProjects: '/projects', - fsPathConfig: '/config', - fsPathTmp: '/tmp', - fsPathPlugins: '/plugins', - fsPathTemplates: '/templates', - fsPathChats: '/chats', - sentryDsn: '', - sentryEnabled: false, - }; - mockUseAppContext.mockReturnValue({ - config, - defaultConfig: config, - updateConfig: vi.fn(), - }); - - // Mock useProjectsManager - mockGetProject = vi.fn().mockResolvedValue(null); - const mockProjectsManager = { - getProject: mockGetProject, - } as unknown as ProjectsManager; - mockUseProjectsManager.mockReturnValue(mockProjectsManager); - - // Mock parseProviderModel - mockParseProviderModel.mockReturnValue({ - provider: { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }, - model: 'gpt-4', - }); - - // Mock createAIClient - const mockCompletion = { - choices: [{ - message: { - tool_calls: [{ - type: 'function' as const, - function: { - name: 'create_project', - arguments: JSON.stringify({ - project_name: 'test-project-name', - template_url: 'https://gitlab.com/soapbox-pub/mkstack.git' - }) - } - }] - } - }] - }; - const mockOpenAI = { - chat: { - completions: { - create: vi.fn().mockResolvedValue(mockCompletion) - } - } - } as unknown as ReturnType; - mockCreateAIClient.mockReturnValue(mockOpenAI); - }); - - it('should return not configured when AI settings are not configured', () => { - mockUseAISettings.mockReturnValue({ - settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, - isConfigured: false, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - expect(result.current.isConfigured).toBe(false); - expect(result.current.isLoading).toBe(false); - }); - - it('should throw error when trying to generate without configuration', async () => { - mockUseAISettings.mockReturnValue({ - settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, - isConfigured: false, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - await expect(result.current.generateProjectInfo('openai/gpt-4', 'test prompt')).rejects.toThrow( - 'AI settings not configured' - ); - }); - - it('should throw error when prompt is empty', async () => { - mockUseAISettings.mockReturnValue({ - settings: { - providers: [ - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - ], - recentlyUsedModels: [], - mcpServers: {} - }, - isConfigured: true, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - await expect(result.current.generateProjectInfo('openai/gpt-4', '')).rejects.toThrow( - 'Prompt cannot be empty' - ); - }); - - it('should throw error when no templates are configured', async () => { - mockUseAISettings.mockReturnValue({ - settings: { - providers: [ - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - ], - recentlyUsedModels: [], - mcpServers: {} - }, - isConfigured: true, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - // Mock config with no templates - const config = { - theme: 'dark' as const, - relayMetadata: { - relays: [{ url: 'wss://relay.damus.io', read: true, write: true }], - updatedAt: 0, - }, - templates: [], - esmUrl: 'https://esm.sh', - corsProxy: 'https://proxy.example.com/{href}', - faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico', - previewDomain: 'local-shakespeare.dev', - showcaseEnabled: true, - showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc', - ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'], - fsPathProjects: '/projects', - fsPathConfig: '/config', - fsPathTmp: '/tmp', - fsPathPlugins: '/plugins', - fsPathTemplates: '/templates', - fsPathChats: '/chats', - sentryDsn: '', - sentryEnabled: false, - }; - mockUseAppContext.mockReturnValue({ - config, - defaultConfig: config, - updateConfig: vi.fn(), - }); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - await expect(result.current.generateProjectInfo('openai/gpt-4', 'test prompt')).rejects.toThrow( - 'No templates configured' - ); - }); - - it('should successfully generate project info with template selection', async () => { - mockUseAISettings.mockReturnValue({ - settings: { - providers: [ - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - ], - recentlyUsedModels: [], - mcpServers: {} - }, - isConfigured: true, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'A social media app for developers'); - - expect(projectInfo).toEqual({ - projectId: 'test-project-name', - template: { - name: 'MKStack', - description: 'Build Nostr clients with React.', - url: 'https://gitlab.com/soapbox-pub/mkstack.git' - } - }); - expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [ - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - ]); - expect(mockCreateAIClient).toHaveBeenCalledWith( - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }, - undefined, - 'https://proxy.example.com/{href}' - ); - }); - - it('should fallback to first template when AI selects invalid template URL', async () => { - mockUseAISettings.mockReturnValue({ - settings: { - providers: [ - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - ], - recentlyUsedModels: [], - mcpServers: {} - }, - isConfigured: true, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - // Mock AI to return invalid template URL - const mockCompletion = { - choices: [{ - message: { - tool_calls: [{ - type: 'function' as const, - function: { - name: 'create_project', - arguments: JSON.stringify({ - project_name: 'test-project', - template_url: 'https://invalid-url.com/template.git' - }) - } - }] - } - }] - }; - const mockOpenAI = { - chat: { - completions: { - create: vi.fn().mockResolvedValue(mockCompletion) - } - } - } as unknown as ReturnType; - mockCreateAIClient.mockReturnValue(mockOpenAI); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - const generatedInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); - - expect(generatedInfo.type).toBe('project'); - if (generatedInfo.type === 'project') { - expect(generatedInfo.info.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); - expect(generatedInfo.info.projectId).toBe('untitled'); - } - }); - - it('should increment AI-generated ID when project already exists', async () => { - mockUseAISettings.mockReturnValue({ - settings: { - providers: [ - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - ], - recentlyUsedModels: [], - mcpServers: {} - }, - isConfigured: true, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - // Reset and override the mock to return project on first call, null on second - mockGetProject.mockReset(); - mockGetProject - .mockResolvedValueOnce({ id: 'test-project-name', name: 'Test Project', path: '/projects/test-project-name', lastModified: new Date() }) - .mockResolvedValue(null); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - const generatedInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); - - expect(generatedInfo.type).toBe('project'); - if (generatedInfo.type === 'project') { - expect(generatedInfo.info.projectId).toBe('test-project-name-1'); - expect(generatedInfo.info.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); - } - expect(mockGetProject).toHaveBeenCalledTimes(2); - expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name'); - expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1'); - }); - - it('should increment multiple times when necessary', async () => { - mockUseAISettings.mockReturnValue({ - settings: { - providers: [ - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - ], - recentlyUsedModels: [], - mcpServers: {} - }, - isConfigured: true, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - // Reset and override the mock - base and -1 exist, -2 is available - mockGetProject.mockReset(); - mockGetProject - .mockResolvedValueOnce({ id: 'test-project-name', name: 'Test Project', path: '/projects/test-project-name', lastModified: new Date() }) - .mockResolvedValueOnce({ id: 'test-project-name-1', name: 'Test Project 1', path: '/projects/test-project-name-1', lastModified: new Date() }) - .mockResolvedValue(null); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - const generatedInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); - - expect(generatedInfo.type).toBe('project'); - if (generatedInfo.type === 'project') { - expect(generatedInfo.info.projectId).toBe('test-project-name-2'); - expect(generatedInfo.info.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); - } - expect(mockGetProject).toHaveBeenCalledTimes(3); - expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name'); - expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1'); - expect(mockGetProject).toHaveBeenNthCalledWith(3, 'test-project-name-2'); - }); - - it('should handle loading state correctly', async () => { - mockUseAISettings.mockReturnValue({ - settings: { - providers: [ - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - ], - recentlyUsedModels: [], - mcpServers: {} - }, - isConfigured: true, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - expect(result.current.isLoading).toBe(false); - - const promise = result.current.generateProjectInfo('openai/gpt-4', 'Test prompt'); - - await waitFor(() => { - expect(result.current.isLoading).toBe(false); // Should be false after completion - }); - - await promise; - }); - - it('should select second template when AI chooses it', async () => { - mockUseAISettings.mockReturnValue({ - settings: { - providers: [ - { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - ], - recentlyUsedModels: [], - mcpServers: {} - }, - isConfigured: true, - updateSettings: vi.fn(), - setProvider: vi.fn(), - removeProvider: vi.fn(), - setProviders: vi.fn(), - addRecentlyUsedModel: vi.fn(), - setMCPServer: vi.fn(), - removeMCPServer: vi.fn(), - }); - - // Mock AI to select the second template - const mockCompletion = { - choices: [{ - message: { - tool_calls: [{ - type: 'function' as const, - function: { - name: 'create_project', - arguments: JSON.stringify({ - project_name: 'vanilla-app', - template_url: 'https://github.com/example/vanilla-template.git' - }) - } - }] - } - }] - }; - const mockOpenAI = { - chat: { - completions: { - create: vi.fn().mockResolvedValue(mockCompletion) - } - } - } as unknown as ReturnType; - mockCreateAIClient.mockReturnValue(mockOpenAI); - - const { result } = renderHook(() => useGenerateProjectInfo()); - - const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'A simple vanilla JS app'); - - expect(projectInfo).toEqual({ - projectId: 'vanilla-app', - template: { - name: 'VanillaJS', - description: 'Simple vanilla JavaScript template.', - url: 'https://github.com/example/vanilla-template.git' - } - }); - }); -}); diff --git a/src/pages/ChatView.tsx b/src/pages/ChatView.tsx index 6f3b3fcb..da3c77e7 100644 --- a/src/pages/ChatView.tsx +++ b/src/pages/ChatView.tsx @@ -4,7 +4,6 @@ import { type Chat } from '@/lib/ChatsManager'; import { useChatsManager } from '@/hooks/useChatsManager'; import { ChatPane, type ChatPaneRef } from '@/components/Shakespeare/ChatPane'; import { ProjectSidebar } from '@/components/ProjectSidebar'; -import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { ArrowLeft, Menu } from 'lucide-react'; @@ -115,51 +114,47 @@ export function ChatView() { // Desktop layout for not found return ( -
- - {isSidebarVisible && ( - <> - - {}} - onToggleSidebar={() => setIsSidebarVisible(false)} - /> - - - - )} +
+ {/* Fixed Sidebar */} + {isSidebarVisible && ( +
+ {}} + className="h-screen sticky top-0" + onToggleSidebar={() => setIsSidebarVisible(false)} + /> +
+ )} - -
-
- {/* Menu button when sidebar is collapsed */} - {!isSidebarVisible && ( -
- -
- )} - -
-

Chat Not Found

-

- This chat may have been deleted or doesn't exist. -

- -
+ {/* Main Content Area */} +
+
+ {/* Menu button when sidebar is collapsed */} + {!isSidebarVisible && ( +
+
+ )} + +
+

Chat Not Found

+

+ This chat may have been deleted or doesn't exist. +

+
- - +
+
); } @@ -246,81 +241,77 @@ export function ChatView() { // Desktop layout return ( -
- - {isSidebarVisible && ( - <> - - {}} - onToggleSidebar={() => setIsSidebarVisible(false)} - /> - - - - )} +
+ {/* Fixed Sidebar */} + {isSidebarVisible && ( +
+ {}} + className="h-screen sticky top-0" + onToggleSidebar={() => setIsSidebarVisible(false)} + /> +
+ )} - -
-
-
-
- {!isSidebarVisible && ( - - )} -
- {chat ? ( -
- {chat.name} -
- ) : ( - - )} + {/* Main Content Area */} +
+
+
+
+ {!isSidebarVisible && ( + + )} +
+ {chat ? ( +
+ {chat.name}
-
- -
- {chat ? ( - - ) : ( - - )} -
+ ) : ( + + )}
-
+
-
- {chat && ( - + {chat ? ( + + ) : ( + )}
- - +
+ +
+ {chat && ( + + )} +
+
); }