Merge branch 'text-chats' into 'main'

Text chats

See merge request soapbox-pub/shakespeare!79
This commit is contained in:
Alex Gleason committed 2025-12-03 08:40:15 +00:00
commit 7badd0113f
26 files changed
+1416 -722

No files matched your search

+6 -1
View File
@@ -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,
};
+2
View File
@@ -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() {
<Route path="about" element={<AboutSettings />} />
</Route>
<Route path="/project/:projectId" element={<ProjectView />} />
<Route path="/chat/:chatId" element={<ChatView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+91 -59
View File
@@ -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;
@@ -27,6 +29,8 @@ interface ActionsMenuProps {
isBuildLoading?: boolean;
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({
@@ -38,10 +42,13 @@ export function ActionsMenu({
isBuildLoading = false,
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;
@@ -62,75 +69,100 @@ export function ActionsMenu({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={onNewChat}
disabled={isLoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
New Chat
</DropdownMenuItem>
{isChat ? (
<DropdownMenuItem
onClick={() => setDeleteChatOpen(true)}
disabled={isLoading}
className="gap-2 text-destructive focus:text-destructive"
>
<Trash2 className="h-4 w-4" />
Delete Chat
</DropdownMenuItem>
) : (
<>
<DropdownMenuItem
onClick={onNewChat}
disabled={isLoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
New Chat
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitHistoryOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<History className="h-4 w-4" />
Rollback
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitHistoryOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<History className="h-4 w-4" />
Rollback
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<GitBranch className="h-4 w-4" />
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
className="gap-2"
>
<Folder className="h-4 w-4" />
Project Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<GitBranch className="h-4 w-4" />
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
className="gap-2"
>
<Folder className="h-4 w-4" />
Project Details
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
{/* Dialogs */}
<GitDialog
projectId={projectId}
open={gitDialogOpen}
onOpenChange={setGitDialogOpen}
/>
{/* Dialogs - only show for projects, not chats */}
{!isChat && (
<>
<GitDialog
projectId={projectId}
open={gitDialogOpen}
onOpenChange={setGitDialogOpen}
/>
<GitHistoryDialog
projectId={projectId}
open={gitHistoryOpen}
onOpenChange={setGitHistoryOpen}
/>
<GitHistoryDialog
projectId={projectId}
open={gitHistoryOpen}
onOpenChange={setGitHistoryOpen}
/>
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
</>
)}
{/* Delete Chat Dialog - only show for chats */}
{isChat && (
<DeleteChatDialog
chatId={projectId}
chatName={projectName}
open={deleteChatOpen}
onOpenChange={setDeleteChatOpen}
onDeleted={onChatDeleted}
/>
)}
</>
);
}
+2
View File
@@ -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<AppConfig>;
@@ -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,
+99
View File
@@ -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 (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Chat</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{chatName}"? This action cannot be undone and all
messages will be permanently deleted.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Deleting...
</>
) : (
'Delete'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
+104 -15
View File
@@ -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, MessageSquareText } 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,56 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
ProjectItem.displayName = 'ProjectItem';
interface ChatItemProps {
chat: Chat;
isSelected: boolean;
onSelect: (chat: Chat) => void;
}
const ChatItem: React.FC<ChatItemProps> = ({ chat, isSelected, onSelect }) => {
const navigate = useNavigate();
const { hasRunningSessions } = useProjectSessionStatus(chat.id);
const handleClick = () => {
onSelect(chat);
navigate(`/chat/${chat.id}`);
};
return (
<div
className={cn(
"group relative rounded-lg transition-all duration-200 hover:bg-gradient-to-r hover:from-primary/10 hover:to-accent/10",
isSelected && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
)}
>
<div className="w-full px-3 py-2 text-left text-sidebar-foreground">
<button
onClick={handleClick}
className="absolute inset-0"
/>
<div className="flex items-center gap-3">
<div className="flex-shrink-0">
{hasRunningSessions ? (
<Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" />
) : (
<MessageSquareText className="h-4 w-4 text-blue-600 dark:text-blue-400" />
)}
</div>
<div className="flex justify-between gap-2 flex-1 min-w-0">
<div className="min-w-0 flex-1 flex items-center">
<h3 className="font-medium text-sm truncate">
{chat.name}
</h3>
</div>
</div>
</div>
</div>
</div>
);
};
ChatItem.displayName = 'ChatItem';
interface ProjectSidebarProps {
selectedProject: Project | null;
onSelectProject: (project: Project | null) => void;
@@ -92,14 +144,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<string[]>('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 +168,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 +292,7 @@ export function ProjectSidebar({
</div>
{/* Search Input */}
{projects.length > 0 && (
{(projects.length > 0 || chats.length > 0) && (
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
<Input
@@ -237,13 +317,13 @@ export function ProjectSidebar({
</div>
))}
</div>
) : projects.length === 0 ? (
) : combinedItems.length === 0 && projects.length === 0 && chats.length === 0 ? (
<div className="text-center p-6 text-muted-foreground">
<Folder className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">{t('noProjectsYet')}</p>
<p className="text-xs">{t('createFirstProject')}</p>
</div>
) : filteredProjects.length === 0 ? (
) : combinedItems.length === 0 ? (
<div className="text-center p-6 text-muted-foreground">
<Search className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">{t('noProjectsFound')}</p>
@@ -251,15 +331,24 @@ export function ProjectSidebar({
</div>
) : (
<div className="space-y-1">
{filteredProjects.map((project) => (
<ProjectItem
key={project.id}
project={project}
isSelected={selectedProject?.id === project.id}
onSelect={onSelectProject}
isFavorite={favorites.includes(project.id)}
/>
))}
{combinedItems.map(({ type, item }) =>
type === 'project' ? (
<ProjectItem
key={`project-${item.id}`}
project={item as Project}
isSelected={selectedProject?.id === item.id}
onSelect={onSelectProject}
isFavorite={favorites.includes(item.id)}
/>
) : (
<ChatItem
key={`chat-${item.id}`}
chat={item as Chat}
isSelected={false}
onSelect={() => {}}
/>
)
)}
</div>
)}
</div>
+4
View File
@@ -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(
+6 -5
View File
@@ -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}`,
+1 -1
View File
@@ -117,7 +117,7 @@ export const ChatInput = memo(function ChatInput({
}, []);
return (
<div className="border-t p-4">
<div className="p-4">
{/* Chat Input Container */}
<div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${
+89 -27
View File
@@ -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';
@@ -59,6 +62,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,16 +76,19 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onLoadingChange,
isLoading: externalIsLoading,
isBuildLoading: externalIsBuildLoading,
isChat = false,
consoleError,
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);
@@ -143,7 +150,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}, [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();
@@ -153,11 +161,58 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
sessionManager.emit('fileChanged', projectId, filePath);
}, [sessionManager, projectId]);
// Callback for when a project is created via start_project tool
const handleProjectCreated = useCallback(async (result: StartProjectResult) => {
// Stop current chat generation
sessionManager.stopGeneration(projectId);
// 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<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
const projectCustomTools: Record<string, Tool<unknown>> = {};
// 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();
// 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<string, Tool<unknown>> = {
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(),
start_project: new StartProjectTool(projectsManager, config, handleProjectCreated),
};
return tools;
}
// For project mode, provide full set of tools
const tools: Record<string, Tool<unknown>> = {
git_commit: new GitCommitTool(fs, cwd, git),
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
@@ -186,7 +241,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return tools;
}, [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]);
@@ -253,8 +308,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
customTools,
onUpdateMetadata,
onAIError,
workingDir: isChat ? cwd : undefined, // Pass working dir for chats
isChat, // Pass isChat flag
});
// Check if we should show the template info banner
useEffect(() => {
const checkTemplateInfo = async () => {
@@ -396,13 +455,14 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
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(() => {
@@ -550,7 +610,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="h-full flex flex-col relative">
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
<div className="p-4 space-y-4">
<div className={`p-4 space-y-4 ${isChat ? 'max-w-3xl mx-auto w-full' : ''}`}>
{/* Template info banner - shown when conditions are met */}
{showTemplateInfo && templateInfo && (
<div className="flex items-center gap-3 text-xs text-muted-foreground uppercase tracking-wide">
@@ -688,27 +748,29 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
)}
<ChatInput
isLoading={isLoading}
isConfigured={isConfigured}
providerModel={providerModel}
onProviderModelChange={handleModelChange}
onSend={handleSend}
onStop={stopGeneration}
onFocus={handleTextareaFocus}
onFirstInteraction={handleFirstInteraction}
isModelSelectorOpen={isModelSelectorOpen}
onModelSelectorOpenChange={setIsModelSelectorOpen}
contextUsagePercentage={contextUsagePercentage}
currentModelContextLength={currentModel?.contextLength}
lastInputTokens={lastInputTokens}
totalCost={totalCost}
isDragOver={isDragOver}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
/>
<div className={`border-t ${isChat ? 'max-w-3xl mx-auto w-full' : ''}`}>
<ChatInput
isLoading={isLoading}
isConfigured={isConfigured}
providerModel={providerModel}
onProviderModelChange={handleModelChange}
onSend={handleSend}
onStop={stopGeneration}
onFocus={handleTextareaFocus}
onFirstInteraction={handleFirstInteraction}
isModelSelectorOpen={isModelSelectorOpen}
onModelSelectorOpenChange={setIsModelSelectorOpen}
contextUsagePercentage={contextUsagePercentage}
currentModelContextLength={currentModel?.contextLength}
lastInputTokens={lastInputTokens}
totalCost={totalCost}
isDragOver={isDragOver}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
/>
</div>
{/* Onboarding Dialog */}
<OnboardingDialog
+2
View File
@@ -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 */
+7 -3
View File
@@ -13,6 +13,8 @@ interface UseAIChatSessionOptions {
maxSteps?: number;
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 {
@@ -32,7 +34,9 @@ export function useAIChat({
customTools = {},
maxSteps = 50,
onUpdateMetadata,
onAIError
onAIError,
workingDir,
isChat
}: UseAIChatSessionOptions) {
const sessionManager = useSessionManager();
const { isConfigured } = useAISettings();
@@ -46,14 +50,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, 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]);
}, [sessionManager, projectId, tools, customTools, maxSteps, workingDir, isChat]);
// Initialize session
useEffect(() => {
+20
View File
@@ -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<Chat[]> => {
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();
});
},
});
}
+16
View File
@@ -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]);
}
+2
View File
@@ -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,
};
}
-503
View File
@@ -1,503 +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<typeof vi.fn>;
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',
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<typeof createAIClient>;
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',
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<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = 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');
});
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 projectInfo = 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(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 projectInfo = 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(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<typeof createAIClient>;
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'
}
});
});
});
+123 -37
View File
@@ -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<ProjectInfo> => {
const generateProjectInfo = useCallback(async (providerModel: string, prompt: string): Promise<GeneratedInfo> => {
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,140 @@ 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 (2-50 characters). Use natural language with spaces, capitalization, and common punctuation. Avoid special characters that are invalid in filenames (/, \\, :, *, ?, ", <, >, |).',
},
},
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 (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.`;
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 chatName = 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 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 {
projectId,
template: selectedTemplate,
type: 'chat',
info: { chatId: chatName.trim() },
};
}
// Project already exists - increment the AI-generated ID (baseExists = true)
return await generateIncrementedId(projectId, selectedTemplate, true);
// Fallback to descriptive name if validation fails
return {
type: 'chat',
info: { chatId: 'New 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 +255,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);
}
+1
View File
@@ -50,6 +50,7 @@ function createWrapper(corsProxy: string) {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
fsPathChats: '/chats',
sentryDsn: '',
sentryEnabled: false,
};
+250
View File
@@ -0,0 +1,250 @@
import type { JSRuntimeFS } from '@/lib/JSRuntime';
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<Chat[]> {
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<Chat | null> {
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<Chat> {
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<void> {
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<void> {
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<OpenAI.Chat.Completions.ChatCompletionMessageParam[]> {
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<void> {
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<void> {
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;
}
}
+1
View File
@@ -54,6 +54,7 @@ const testConfig: AppConfig = {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
fsPathChats: '/chats',
sentryDsn: '',
sentryEnabled: false,
};
+87 -26
View File
@@ -41,6 +41,8 @@ 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)
isChat?: boolean; // Whether this is a chat session (vs a project session)
}
export interface SessionManagerEvents {
@@ -93,13 +95,15 @@ 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<string, OpenAI.Chat.Completions.ChatCompletionTool>,
customTools: Record<string, Tool<unknown>>,
maxSteps?: number
maxSteps?: number,
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<SessionState> {
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
let sessionName = DotAI.generateSessionName();
@@ -107,11 +111,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 (isChat) {
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,14 +158,17 @@ export class SessionManager {
...this.sessions.get(projectId),
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);
@@ -257,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),
@@ -732,9 +770,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.isChat) {
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);
}
@@ -744,9 +796,18 @@ export class SessionManager {
* Accumulate request cost to the project's total cost file
*/
private async accumulateProjectCost(projectId: string, requestCost: number): Promise<void> {
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();
+1
View File
@@ -41,6 +41,7 @@ const testConfig: AppConfig = {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
fsPathChats: '/chats',
sentryDsn: '',
sentryEnabled: false,
};
+102
View File
@@ -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<typeof startProjectSchema>;
export interface StartProjectResult {
projectId: string;
initialMessage: string;
}
export class StartProjectTool implements Tool<StartProjectParams> {
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<string> {
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...`;
}
}
+317
View File
@@ -0,0 +1,317 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
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 { 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 [chat, setChat] = useState<Chat | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isAILoading, setIsAILoading] = useState(false);
const chatsManager = useChatsManager();
const chatPaneRef = useRef<ChatPaneRef>(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 = () => {
// Navigate to home page after chat is deleted
navigate('/');
};
// Chat not found - show in app layout with sidebar
if (!chat && !isLoading) {
if (isMobile) {
return (
<div className="h-dvh flex flex-col bg-background">
<header className="pt-safe bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur">
<div className="h-12 border-b px-4 py-3 flex items-center justify-between">
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
>
<Menu className="h-4 w-4" />
</Button>
</div>
</header>
{/* Mobile Sidebar Overlay */}
{isSidebarVisible && (
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
<div
className="absolute inset-0"
onClick={() => setIsSidebarVisible(false)}
/>
<div className="absolute left-0 top-0 bottom-0 w-64 bg-sidebar">
<ProjectSidebar
selectedProject={null}
onSelectProject={() => {}}
onClose={() => setIsSidebarVisible(false)}
/>
</div>
</div>
)}
<div className="flex-1 flex items-center justify-center p-4">
<div className="text-center">
<h1 className="text-2xl font-bold mb-2">Chat Not Found</h1>
<p className="text-muted-foreground mb-4">
This chat may have been deleted or doesn't exist.
</p>
<Button onClick={() => navigate('/')} variant="outline">
<ArrowLeft className="mr-2 h-4 w-4" />
Back to Home
</Button>
</div>
</div>
</div>
);
}
// Desktop layout for not found
return (
<div className="h-screen flex bg-background">
{/* Fixed Sidebar */}
{isSidebarVisible && (
<div className="w-72 border-r bg-sidebar">
<ProjectSidebar
selectedProject={null}
onSelectProject={() => {}}
className="h-screen sticky top-0"
onToggleSidebar={() => setIsSidebarVisible(false)}
/>
</div>
)}
{/* Main Content Area */}
<div className="flex-1 flex flex-col">
<div className="flex-1 flex items-center justify-center p-4 relative">
{/* Menu button when sidebar is collapsed */}
{!isSidebarVisible && (
<div className="absolute top-4 left-4">
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(true)}
>
<Menu className="h-4 w-4" />
</Button>
</div>
)}
<div className="text-center">
<h1 className="text-2xl font-bold mb-2">Chat Not Found</h1>
<p className="text-muted-foreground mb-4">
This chat may have been deleted or doesn't exist.
</p>
<Button onClick={() => navigate('/')} variant="outline">
<ArrowLeft className="mr-2 h-4 w-4" />
Back to Home
</Button>
</div>
</div>
</div>
</div>
);
}
if (isMobile) {
return (
<div className="h-dvh flex flex-col bg-background">
<header className="pt-safe bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur">
<div className="h-12 border-b px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-2 overflow-hidden">
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
>
<Menu className="h-4 w-4" />
</Button>
<div className="flex min-w-0 flex-1">
{chat ? (
<div className="text-sm font-semibold truncate">
{chat.name}
</div>
) : (
<Skeleton className="h-5 w-32" />
)}
</div>
</div>
<div className="flex items-center gap-2">
{chat ? (
<ActionsMenu
projectId={chat.id}
projectName={chat.name}
onNewChat={handleNewChat}
isLoading={isAILoading}
isBuildLoading={false}
onFirstInteraction={handleFirstInteraction}
isChat={true}
onChatDeleted={handleChatDeleted}
/>
) : (
<Skeleton className="h-8 w-8 rounded" />
)}
</div>
</div>
</header>
{/* Mobile Sidebar Overlay */}
{isSidebarVisible && (
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
{/* Backdrop - only covers the area not occupied by the sidebar */}
<div
className="absolute inset-0"
onClick={() => setIsSidebarVisible(false)}
/>
{/* Sidebar */}
<div className="absolute left-0 top-0 bottom-0 w-64 bg-sidebar">
<ProjectSidebar
selectedProject={null}
onSelectProject={() => {}}
onClose={() => setIsSidebarVisible(false)}
/>
</div>
</div>
)}
<div className="flex-1 overflow-hidden">
{chat && (
<ChatPane
ref={chatPaneRef}
projectId={chat.id}
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
isChat={true}
/>
)}
</div>
</div>
);
}
// Desktop layout
return (
<div className="h-screen flex bg-background">
{/* Fixed Sidebar */}
{isSidebarVisible && (
<div className="w-72 border-r bg-sidebar">
<ProjectSidebar
selectedProject={null}
onSelectProject={() => {}}
className="h-screen sticky top-0"
onToggleSidebar={() => setIsSidebarVisible(false)}
/>
</div>
)}
{/* Main Content Area */}
<div className="flex-1 flex flex-col">
<header className="pt-safe bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur">
<div className="h-12 border-b px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-2 overflow-hidden">
{!isSidebarVisible && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(true)}
>
<Menu className="h-4 w-4" />
</Button>
)}
<div className="flex min-w-0 flex-1">
{chat ? (
<div className="text-sm font-semibold truncate">
{chat.name}
</div>
) : (
<Skeleton className="h-5 w-32" />
)}
</div>
</div>
<div className="flex items-center gap-2">
{chat ? (
<ActionsMenu
projectId={chat.id}
projectName={chat.name}
onNewChat={handleNewChat}
isLoading={isAILoading}
isBuildLoading={false}
onFirstInteraction={handleFirstInteraction}
isChat={true}
onChatDeleted={handleChatDeleted}
/>
) : (
<Skeleton className="h-8 w-8 rounded" />
)}
</div>
</div>
</header>
<div className="flex-1 overflow-hidden">
{chat && (
<ChatPane
ref={chatPaneRef}
projectId={chat.id}
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
isChat={true}
/>
)}
</div>
</div>
</div>
);
}
+82 -45
View File
@@ -2,12 +2,15 @@ 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 { useQueryClient } from '@tanstack/react-query';
import { AppLayout } from '@/components/AppLayout';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { Act1Dialog } from '@/components/Act1Dialog';
@@ -39,7 +42,9 @@ 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();
const { generateProjectInfo, isLoading: isGeneratingInfo } = useGenerateProjectInfo();
const { settings, addRecentlyUsedModel } = useAISettings();
@@ -218,64 +223,96 @@ 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]);
// Invalidate chats query to update sidebar
queryClient.invalidateQueries({ queryKey: ['chats'] });
// Clear attached files after successful creation
setAttachedFiles([]);
// 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()}`);
// 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;
// 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);
+1
View File
@@ -55,6 +55,7 @@ export function TestApp({ children }: TestAppProps) {
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
fsPathChats: '/chats',
sentryDsn: '',
sentryEnabled: false,
};