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);