mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a94f3fbde6 |
No files matched your search
@@ -16,6 +16,7 @@ import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
import { TextChatView } from "./pages/TextChatView";
|
||||
import { SettingsLayout } from "./components/SettingsLayout";
|
||||
|
||||
export function AppRouter() {
|
||||
@@ -37,6 +38,7 @@ export function AppRouter() {
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
<Route path="/chat/:chatId" element={<TextChatView />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { type ChatItem } from '@/lib/ProjectsManager';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -9,7 +9,7 @@ import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
interface AppLayoutProps {
|
||||
children: React.ReactNode;
|
||||
selectedProject?: Project | null;
|
||||
selectedProject?: ChatItem | null;
|
||||
title?: string;
|
||||
showSidebar?: boolean;
|
||||
headerContent?: React.ReactNode;
|
||||
@@ -21,7 +21,7 @@ export function AppLayout({
|
||||
showSidebar = true,
|
||||
headerContent
|
||||
}: AppLayoutProps) {
|
||||
const [_projects, setProjects] = useState<Project[]>([]);
|
||||
const [_projects, setProjects] = useState<ChatItem[]>([]);
|
||||
const projectsManager = useProjectsManager();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
@@ -34,7 +34,7 @@ export function AppLayout({
|
||||
const loadProjects = useCallback(async () => {
|
||||
try {
|
||||
await projectsManager.init();
|
||||
const projectList = await projectsManager.getProjects();
|
||||
const projectList = await projectsManager.getAllChatItems();
|
||||
setProjects(projectList);
|
||||
|
||||
// Set initial sidebar state based on projects and device type
|
||||
@@ -59,10 +59,14 @@ export function AppLayout({
|
||||
loadProjects();
|
||||
}, [loadProjects]);
|
||||
|
||||
const handleProjectSelect = (project: Project | null) => {
|
||||
if (project) {
|
||||
const handleProjectSelect = (item: ChatItem | null) => {
|
||||
if (item) {
|
||||
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
|
||||
navigate(`/project/${project.id}`);
|
||||
if (item.type === 'project') {
|
||||
navigate(`/project/${item.id}`);
|
||||
} else {
|
||||
navigate(`/chat/${item.id}`);
|
||||
}
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
@@ -101,10 +105,10 @@ export function AppLayout({
|
||||
{/* Sidebar - positioned above the backdrop */}
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={(project) => {
|
||||
selectedItem={selectedProject}
|
||||
onSelectItem={(item) => {
|
||||
setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation
|
||||
handleProjectSelect(project);
|
||||
handleProjectSelect(item);
|
||||
}}
|
||||
onClose={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
@@ -125,8 +129,8 @@ export function AppLayout({
|
||||
{showSidebar && isSidebarVisible && (
|
||||
<div className="w-80 border-r bg-sidebar transition-all duration-300">
|
||||
<ProjectSidebar
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={handleProjectSelect}
|
||||
selectedItem={selectedProject}
|
||||
onSelectItem={handleProjectSelect}
|
||||
className="h-screen sticky top-0"
|
||||
onToggleSidebar={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
|
||||
@@ -54,8 +54,8 @@ describe('ProjectSidebar', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
selectedItem={null}
|
||||
onSelectItem={vi.fn()}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -70,8 +70,8 @@ describe('ProjectSidebar', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
selectedItem={null}
|
||||
onSelectItem={vi.fn()}
|
||||
onToggleSidebar={mockToggle}
|
||||
/>
|
||||
</TestApp>
|
||||
@@ -88,8 +88,8 @@ describe('ProjectSidebar', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
selectedItem={null}
|
||||
onSelectItem={vi.fn()}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -101,8 +101,8 @@ describe('ProjectSidebar', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
selectedItem={null}
|
||||
onSelectItem={vi.fn()}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -115,8 +115,8 @@ describe('ProjectSidebar', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
selectedItem={null}
|
||||
onSelectItem={vi.fn()}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -128,8 +128,8 @@ describe('ProjectSidebar', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
selectedItem={null}
|
||||
onSelectItem={vi.fn()}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, MessageSquare } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
@@ -9,25 +9,29 @@ import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import type { ChatItem } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
interface ProjectItemProps {
|
||||
project: Project;
|
||||
interface ChatItemProps {
|
||||
item: ChatItem;
|
||||
isSelected: boolean;
|
||||
onSelect: (project: Project) => void;
|
||||
onSelect: (item: ChatItem) => void;
|
||||
isFavorite?: boolean;
|
||||
}
|
||||
|
||||
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
|
||||
const ChatItemComponent: React.FC<ChatItemProps> = ({ item, isSelected, onSelect, isFavorite }) => {
|
||||
const navigate = useNavigate();
|
||||
const { hasRunningSessions } = useProjectSessionStatus(project.id);
|
||||
const { hasRunningSessions } = useProjectSessionStatus(item.id);
|
||||
|
||||
const handleClick = () => {
|
||||
onSelect(project);
|
||||
navigate(`/project/${project.id}`);
|
||||
onSelect(item);
|
||||
if (item.type === 'project') {
|
||||
navigate(`/project/${item.id}`);
|
||||
} else {
|
||||
navigate(`/chat/${item.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -46,6 +50,8 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
|
||||
<div className="flex-shrink-0">
|
||||
{hasRunningSessions ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
) : item.type === 'chat' ? (
|
||||
<MessageSquare className="h-4 w-4 text-accent" />
|
||||
) : (
|
||||
<Folder className="h-4 w-4 text-primary" />
|
||||
)}
|
||||
@@ -53,7 +59,7 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
|
||||
<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">
|
||||
{project.name}
|
||||
{item.name}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
@@ -72,26 +78,26 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
|
||||
);
|
||||
};
|
||||
|
||||
ProjectItem.displayName = 'ProjectItem';
|
||||
ChatItemComponent.displayName = 'ChatItemComponent';
|
||||
|
||||
interface ProjectSidebarProps {
|
||||
selectedProject: Project | null;
|
||||
onSelectProject: (project: Project | null) => void;
|
||||
selectedItem: ChatItem | null;
|
||||
onSelectItem: (item: ChatItem | null) => void;
|
||||
className?: string;
|
||||
onToggleSidebar?: () => void;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
export function ProjectSidebar({
|
||||
selectedProject,
|
||||
onSelectProject,
|
||||
selectedItem,
|
||||
onSelectItem,
|
||||
className,
|
||||
onToggleSidebar,
|
||||
onClose
|
||||
}: ProjectSidebarProps) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
const { data: items = [], isLoading, error } = useProjects();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
|
||||
const isMobile = useIsMobile();
|
||||
@@ -106,10 +112,15 @@ export function ProjectSidebar({
|
||||
};
|
||||
|
||||
const handleNewProject = () => {
|
||||
onSelectProject(null);
|
||||
onSelectItem(null);
|
||||
navigateAndClose('/');
|
||||
};
|
||||
|
||||
const handleNewChat = () => {
|
||||
onSelectItem(null);
|
||||
navigateAndClose('/?mode=chat');
|
||||
};
|
||||
|
||||
const handleToggleSidebar = () => {
|
||||
if (onToggleSidebar) {
|
||||
onToggleSidebar();
|
||||
@@ -166,7 +177,7 @@ export function ProjectSidebar({
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="p-2">
|
||||
<div className="mb-2">
|
||||
<div className="mb-2 space-y-2">
|
||||
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
|
||||
<div className="flex">
|
||||
<button
|
||||
@@ -195,6 +206,14 @@ export function ProjectSidebar({
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleNewChat}
|
||||
className="w-full bg-gradient-to-r from-accent to-primary hover:from-accent/90 hover:to-primary/90 transition-all duration-200"
|
||||
size="sm"
|
||||
>
|
||||
<MessageSquare className="h-4 w-4 mr-2" />
|
||||
{t('newChat')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
@@ -208,7 +227,7 @@ export function ProjectSidebar({
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : projects.length === 0 ? (
|
||||
) : items.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>
|
||||
@@ -216,13 +235,13 @@ export function ProjectSidebar({
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{projects.map((project) => (
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
project={project}
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
isFavorite={favorites.includes(project.id)}
|
||||
{items.map((item) => (
|
||||
<ChatItemComponent
|
||||
key={item.id}
|
||||
item={item}
|
||||
isSelected={selectedItem?.id === item.id}
|
||||
onSelect={onSelectItem}
|
||||
isFavorite={favorites.includes(item.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-re
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { type ChatItem } from '@/lib/ProjectsManager';
|
||||
import { useCallback } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -72,14 +72,14 @@ export function SettingsLayout() {
|
||||
const isMobile = useIsMobile();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const [_projects, setProjects] = useState<Project[]>([]);
|
||||
const [_projects, setProjects] = useState<ChatItem[]>([]);
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
const [hasSetInitialState, setHasSetInitialState] = useState(false);
|
||||
|
||||
const loadProjects = useCallback(async () => {
|
||||
try {
|
||||
await projectsManager.init();
|
||||
const projectList = await projectsManager.getProjects();
|
||||
const projectList = await projectsManager.getAllChatItems();
|
||||
setProjects(projectList);
|
||||
|
||||
// Set initial sidebar state based on projects and device type
|
||||
@@ -104,10 +104,14 @@ export function SettingsLayout() {
|
||||
loadProjects();
|
||||
}, [loadProjects]);
|
||||
|
||||
const handleProjectSelect = (project: Project | null) => {
|
||||
if (project) {
|
||||
const handleProjectSelect = (item: ChatItem | null) => {
|
||||
if (item) {
|
||||
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
|
||||
navigate(`/project/${project.id}`);
|
||||
if (item.type === 'project') {
|
||||
navigate(`/project/${item.id}`);
|
||||
} else {
|
||||
navigate(`/chat/${item.id}`);
|
||||
}
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
@@ -145,10 +149,10 @@ export function SettingsLayout() {
|
||||
/>
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={(project) => {
|
||||
selectedItem={null}
|
||||
onSelectItem={(item) => {
|
||||
setIsSidebarVisible(false);
|
||||
handleProjectSelect(project);
|
||||
handleProjectSelect(item);
|
||||
}}
|
||||
onClose={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
@@ -168,8 +172,8 @@ export function SettingsLayout() {
|
||||
{isSidebarVisible && (
|
||||
<div className="w-80 border-r bg-sidebar flex-shrink-0">
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={handleProjectSelect}
|
||||
selectedItem={null}
|
||||
onSelectItem={handleProjectSelect}
|
||||
className="h-full"
|
||||
onToggleSidebar={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
|
||||
@@ -55,6 +55,7 @@ interface ChatPaneProps {
|
||||
isBuildLoading?: boolean;
|
||||
consoleError?: ProjectPreviewConsoleError | null;
|
||||
onDismissConsoleError?: () => void;
|
||||
isTextChat?: boolean; // Whether this is a text chat (no tools) vs a project chat
|
||||
}
|
||||
|
||||
export interface ChatPaneRef {
|
||||
@@ -70,6 +71,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
isBuildLoading: externalIsBuildLoading,
|
||||
consoleError,
|
||||
onDismissConsoleError,
|
||||
isTextChat = false,
|
||||
}, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -132,8 +134,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}, [projectId, providerModel]);
|
||||
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `/projects/${projectId}`;
|
||||
const cwd = isTextChat ? `/chats/${projectId}` : `/projects/${projectId}`;
|
||||
const customTools = useMemo(() => {
|
||||
// For text chats, return empty tools object
|
||||
if (isTextChat) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const baseTools = {
|
||||
git_commit: new GitCommitTool(fs, cwd, git),
|
||||
text_editor_view: new TextEditorViewTool(fs, cwd),
|
||||
@@ -163,7 +170,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return baseTools;
|
||||
}, [fs, git, cwd, user, projectId]);
|
||||
}, [fs, git, cwd, user, projectId, isTextChat]);
|
||||
|
||||
// Convert tools to OpenAI format
|
||||
const tools = useMemo(() => {
|
||||
@@ -215,6 +222,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
customTools,
|
||||
onUpdateMetadata,
|
||||
onAIError,
|
||||
isTextChat,
|
||||
});
|
||||
|
||||
// Handle console error help requests
|
||||
|
||||
@@ -13,6 +13,7 @@ interface UseAIChatSessionOptions {
|
||||
maxSteps?: number;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
onAIError?: (error: Error) => void;
|
||||
isTextChat?: boolean;
|
||||
}
|
||||
|
||||
interface StreamingMessage {
|
||||
@@ -32,7 +33,8 @@ export function useAIChat({
|
||||
customTools = {},
|
||||
maxSteps = 50,
|
||||
onUpdateMetadata,
|
||||
onAIError
|
||||
onAIError,
|
||||
isTextChat = false
|
||||
}: 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, isTextChat);
|
||||
// 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, isTextChat]);
|
||||
|
||||
// Initialize session
|
||||
useEffect(() => {
|
||||
|
||||
@@ -25,21 +25,24 @@ function createTestWrapper() {
|
||||
vi.mock('./useProjectsManager', () => ({
|
||||
useProjectsManager: () => ({
|
||||
init: vi.fn().mockResolvedValue(undefined),
|
||||
getProjects: vi.fn().mockResolvedValue([
|
||||
getAllChatItems: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'project-1',
|
||||
name: 'Project 1',
|
||||
lastModified: new Date('2023-01-01'),
|
||||
type: 'project' as const,
|
||||
},
|
||||
{
|
||||
id: 'project-2',
|
||||
name: 'Project 2',
|
||||
lastModified: new Date('2023-01-02'),
|
||||
type: 'project' as const,
|
||||
},
|
||||
{
|
||||
id: 'project-3',
|
||||
name: 'Project 3',
|
||||
lastModified: new Date('2023-01-03'),
|
||||
type: 'project' as const,
|
||||
},
|
||||
] as Project[]),
|
||||
}),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import type { ChatItem } from '@/lib/ProjectsManager';
|
||||
|
||||
export function useProjects() {
|
||||
const projectsManager = useProjectsManager();
|
||||
@@ -9,12 +9,12 @@ export function useProjects() {
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['projects'],
|
||||
queryFn: async (): Promise<Project[]> => {
|
||||
queryFn: async (): Promise<ChatItem[]> => {
|
||||
await projectsManager.init();
|
||||
const projects = await projectsManager.getProjects();
|
||||
|
||||
// Sort projects: favorites first, then by lastModified (newest first)
|
||||
return projects.sort((a, b) => {
|
||||
const items = await projectsManager.getAllChatItems();
|
||||
|
||||
// Sort items: favorites first, then by lastModified (newest first)
|
||||
return items.sort((a, b) => {
|
||||
const aIsFavorite = favorites.includes(a.id);
|
||||
const bIsFavorite = favorites.includes(b.id);
|
||||
|
||||
|
||||
+2
-2
@@ -8,10 +8,10 @@ export class DotAI {
|
||||
readonly historyDir: string;
|
||||
readonly workingDir: string;
|
||||
|
||||
constructor(fs: JSRuntimeFS, workingDir: string = "/") {
|
||||
constructor(fs: JSRuntimeFS, workingDir: string = "/", customHistoryDir?: string) {
|
||||
this.fs = fs;
|
||||
this.workingDir = workingDir;
|
||||
this.historyDir = join(workingDir, ".git", "ai", "history");
|
||||
this.historyDir = customHistoryDir || join(workingDir, ".git", "ai", "history");
|
||||
}
|
||||
|
||||
/** Generate a unique session name based on the current date and time */
|
||||
|
||||
@@ -17,8 +17,19 @@ export interface Project {
|
||||
name: string;
|
||||
path: string;
|
||||
lastModified: Date;
|
||||
type: 'project';
|
||||
}
|
||||
|
||||
export interface TextChat {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
lastModified: Date;
|
||||
type: 'chat';
|
||||
}
|
||||
|
||||
export type ChatItem = Project | TextChat;
|
||||
|
||||
export interface ProjectsManagerOptions {
|
||||
fs: JSRuntimeFS;
|
||||
git: Git;
|
||||
@@ -28,11 +39,13 @@ export class ProjectsManager {
|
||||
fs: JSRuntimeFS;
|
||||
git: Git;
|
||||
dir: string;
|
||||
chatsDir: string;
|
||||
|
||||
constructor(options: ProjectsManagerOptions) {
|
||||
this.fs = options.fs;
|
||||
this.git = options.git;
|
||||
this.dir = '/projects';
|
||||
this.chatsDir = '/chats';
|
||||
}
|
||||
|
||||
async init() {
|
||||
@@ -41,6 +54,11 @@ export class ProjectsManager {
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
try {
|
||||
await this.fs.mkdir(this.chatsDir);
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
}
|
||||
|
||||
async createProject(name: string, customId?: string): Promise<Project> {
|
||||
@@ -264,6 +282,7 @@ export class ProjectsManager {
|
||||
name: projectName,
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
type: 'project' as const,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up on error (only if this was a new project creation)
|
||||
@@ -317,6 +336,7 @@ export class ProjectsManager {
|
||||
name: this.formatProjectName(id), // Use formatted directory name
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
type: 'project' as const,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up the directory that was created if cloning fails
|
||||
@@ -348,6 +368,7 @@ export class ProjectsManager {
|
||||
name: this.formatProjectName(dir), // Convert directory name to readable format
|
||||
path: projectPath,
|
||||
lastModified: modifiedDate,
|
||||
type: 'project' as const,
|
||||
};
|
||||
|
||||
projects.push(project);
|
||||
@@ -375,6 +396,7 @@ export class ProjectsManager {
|
||||
name: this.formatProjectName(id), // Convert directory name to readable format
|
||||
path: projectPath,
|
||||
lastModified: modifiedDate,
|
||||
type: 'project' as const,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -508,6 +530,7 @@ export class ProjectsManager {
|
||||
name: this.formatProjectName(newId),
|
||||
path: newPath,
|
||||
lastModified: timestamp,
|
||||
type: 'project' as const,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -658,4 +681,180 @@ export class ProjectsManager {
|
||||
|
||||
return '/' + normalized.join('/');
|
||||
}
|
||||
|
||||
// Text Chat Methods
|
||||
|
||||
async createTextChat(name: string): Promise<TextChat> {
|
||||
const id = await this.generateUniqueChatId(name);
|
||||
const chatPath = `${this.chatsDir}/${id}`;
|
||||
|
||||
// Create the chat directory
|
||||
await this.fs.mkdir(chatPath, { recursive: true });
|
||||
|
||||
// Create a metadata file
|
||||
const metadata = {
|
||||
name,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
await this.fs.writeFile(`${chatPath}/metadata.json`, JSON.stringify(metadata, null, 2));
|
||||
|
||||
const stats = await this.fs.stat(chatPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
path: chatPath,
|
||||
lastModified: timestamp,
|
||||
type: 'chat',
|
||||
};
|
||||
}
|
||||
|
||||
async getTextChats(): Promise<TextChat[]> {
|
||||
try {
|
||||
const chatDirs = await this.fs.readdir(this.chatsDir);
|
||||
const chats: TextChat[] = [];
|
||||
|
||||
for (const dir of chatDirs) {
|
||||
const chatPath = `${this.chatsDir}/${dir}`;
|
||||
|
||||
try {
|
||||
const stats = await this.fs.stat(chatPath);
|
||||
if (stats.isDirectory()) {
|
||||
// Try to read metadata
|
||||
let name = this.formatProjectName(dir);
|
||||
try {
|
||||
const metadataContent = await this.fs.readFile(`${chatPath}/metadata.json`, 'utf8');
|
||||
const metadata = JSON.parse(metadataContent);
|
||||
name = metadata.name || name;
|
||||
} catch {
|
||||
// If metadata doesn't exist, use formatted directory name
|
||||
}
|
||||
|
||||
const modifiedDate = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
const chat: TextChat = {
|
||||
id: dir,
|
||||
name,
|
||||
path: chatPath,
|
||||
lastModified: modifiedDate,
|
||||
type: 'chat',
|
||||
};
|
||||
|
||||
chats.push(chat);
|
||||
}
|
||||
} catch {
|
||||
// Skip if we can't stat the directory
|
||||
}
|
||||
}
|
||||
|
||||
return chats.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async getTextChat(id: string): Promise<TextChat | null> {
|
||||
try {
|
||||
const chatPath = `${this.chatsDir}/${id}`;
|
||||
const stats = await this.fs.stat(chatPath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
// Try to read metadata
|
||||
let name = this.formatProjectName(id);
|
||||
try {
|
||||
const metadataContent = await this.fs.readFile(`${chatPath}/metadata.json`, 'utf8');
|
||||
const metadata = JSON.parse(metadataContent);
|
||||
name = metadata.name || name;
|
||||
} catch {
|
||||
// If metadata doesn't exist, use formatted directory name
|
||||
}
|
||||
|
||||
const modifiedDate = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
path: chatPath,
|
||||
lastModified: modifiedDate,
|
||||
type: 'chat',
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteTextChat(chatId: string): Promise<void> {
|
||||
const chatPath = `${this.chatsDir}/${chatId}`;
|
||||
await this.deleteDirectory(chatPath);
|
||||
}
|
||||
|
||||
async renameTextChat(oldId: string, newName: string): Promise<TextChat> {
|
||||
const oldChat = await this.getTextChat(oldId);
|
||||
if (!oldChat) {
|
||||
throw new Error(`Chat with ID "${oldId}" does not exist`);
|
||||
}
|
||||
|
||||
const chatPath = `${this.chatsDir}/${oldId}`;
|
||||
|
||||
// Update metadata with new name
|
||||
const metadata = {
|
||||
name: newName,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
await this.fs.writeFile(`${chatPath}/metadata.json`, JSON.stringify(metadata, null, 2));
|
||||
|
||||
// Use current timestamp for modification time
|
||||
const timestamp = new Date();
|
||||
|
||||
return {
|
||||
id: oldId,
|
||||
name: newName,
|
||||
path: chatPath,
|
||||
lastModified: timestamp,
|
||||
type: 'chat',
|
||||
};
|
||||
}
|
||||
|
||||
async getAllChatItems(): Promise<ChatItem[]> {
|
||||
const [projects, textChats] = await Promise.all([
|
||||
this.getProjects(),
|
||||
this.getTextChats(),
|
||||
]);
|
||||
|
||||
// Add type field to projects
|
||||
const projectsWithType: Project[] = projects.map(p => ({ ...p, type: 'project' as const }));
|
||||
|
||||
// Combine and sort by lastModified
|
||||
const allItems: ChatItem[] = [...projectsWithType, ...textChats];
|
||||
return allItems.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
|
||||
}
|
||||
|
||||
private async generateUniqueChatId(name: string): Promise<string> {
|
||||
const baseSlug = name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
|
||||
let slug = baseSlug;
|
||||
let counter = 1;
|
||||
|
||||
while (await this.chatExists(slug)) {
|
||||
slug = `${baseSlug}-${counter}`;
|
||||
counter++;
|
||||
}
|
||||
|
||||
return slug;
|
||||
}
|
||||
|
||||
private async chatExists(id: string): Promise<boolean> {
|
||||
try {
|
||||
const chatPath = `${this.chatsDir}/${id}`;
|
||||
await this.fs.stat(chatPath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ export interface SessionState {
|
||||
abortController?: AbortController;
|
||||
totalCost?: number; // Total cost in USD for this session
|
||||
lastInputTokens?: number; // Input tokens from the last AI request
|
||||
isTextChat?: boolean; // Whether this is a text chat (no tools) vs a project chat
|
||||
}
|
||||
|
||||
export interface SessionManagerEvents {
|
||||
@@ -72,20 +73,23 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new session for a project
|
||||
* Create a new session for a project or text chat
|
||||
*/
|
||||
async loadSession(
|
||||
projectId: string,
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>,
|
||||
customTools: Record<string, Tool<unknown>>,
|
||||
maxSteps?: number
|
||||
maxSteps?: number,
|
||||
isTextChat?: boolean
|
||||
): Promise<SessionState> {
|
||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||
let sessionName = DotAI.generateSessionName();
|
||||
|
||||
// Try to load existing history
|
||||
try {
|
||||
const dotAI = new DotAI(this.fs, `/projects/${projectId}`);
|
||||
const workingDir = isTextChat ? `/chats/${projectId}` : `/projects/${projectId}`;
|
||||
const historyDir = isTextChat ? `${workingDir}/history` : undefined;
|
||||
const dotAI = new DotAI(this.fs, workingDir, historyDir);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
if (lastSession) {
|
||||
messages = lastSession.messages;
|
||||
@@ -104,6 +108,7 @@ export class SessionManager {
|
||||
lastActivity: new Date(),
|
||||
totalCost: 0,
|
||||
lastInputTokens: 0,
|
||||
isTextChat,
|
||||
...this.sessions.get(projectId),
|
||||
messages,
|
||||
sessionName,
|
||||
@@ -226,8 +231,9 @@ export class SessionManager {
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
const cwd = session.isTextChat ? `/chats/${projectId}` : `/projects/${projectId}`;
|
||||
const systemPrompt = await makeSystemPrompt({
|
||||
cwd: `/projects/${projectId}`,
|
||||
cwd,
|
||||
fs: this.fs,
|
||||
mode: "agent",
|
||||
name: "Shakespeare",
|
||||
@@ -549,7 +555,9 @@ export class SessionManager {
|
||||
if (!session) return;
|
||||
|
||||
try {
|
||||
const dotAI = new DotAI(this.fs, `/projects/${session.projectId}`);
|
||||
const workingDir = session.isTextChat ? `/chats/${session.projectId}` : `/projects/${session.projectId}`;
|
||||
const historyDir = session.isTextChat ? `${workingDir}/history` : undefined;
|
||||
const dotAI = new DotAI(this.fs, workingDir, historyDir);
|
||||
await dotAI.setHistory(session.sessionName, session.messages);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save session history:', error);
|
||||
|
||||
@@ -84,6 +84,7 @@ const resources = {
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'New Project',
|
||||
newChat: 'New Chat',
|
||||
importRepository: 'Import Repository',
|
||||
noProjectsYet: 'No projects yet',
|
||||
createFirstProject: 'Create your first project to get started',
|
||||
@@ -395,6 +396,7 @@ const resources = {
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Novo Projeto',
|
||||
newChat: 'Nova Conversa',
|
||||
importRepository: 'Importar Repositório',
|
||||
noProjectsYet: 'Nenhum projeto ainda',
|
||||
createFirstProject: 'Crie seu primeiro projeto para começar',
|
||||
@@ -706,6 +708,7 @@ const resources = {
|
||||
|
||||
// Project Sidebar
|
||||
newProject: '新项目',
|
||||
newChat: '新对话',
|
||||
importRepository: '导入仓库',
|
||||
noProjectsYet: '还没有项目',
|
||||
createFirstProject: '创建您的第一个项目开始使用',
|
||||
@@ -1017,6 +1020,7 @@ const resources = {
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Sabon Aikin',
|
||||
newChat: 'Sabuwar Hira',
|
||||
importRepository: 'Shigo da Repository',
|
||||
noProjectsYet: 'Babu ayyuka har yanzu',
|
||||
createFirstProject: 'Ƙirƙiri aikin farko don farawa',
|
||||
@@ -1328,6 +1332,7 @@ const resources = {
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Iṣẹ akanṣe Tuntun',
|
||||
newChat: 'Ibaraẹnisọrọ Tuntun',
|
||||
importRepository: 'Gbe Repository wọle',
|
||||
noProjectsYet: 'Ko si awọn iṣẹ akanṣe sibẹsibẹ',
|
||||
createFirstProject: 'Ṣẹda iṣẹ akanṣe akọkọ rẹ lati bẹrẹ',
|
||||
@@ -1634,6 +1639,7 @@ const resources = {
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Ọrụ Ọhụrụ',
|
||||
newChat: 'Mkparịta Ụka Ọhụrụ',
|
||||
importRepository: 'Bubata Repository',
|
||||
noProjectsYet: 'Enwebeghị ọrụ ọ bụla',
|
||||
createFirstProject: 'Mepụta ọrụ mbụ gị iji malite',
|
||||
|
||||
+71
-4
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useAIProjectId } from '@/hooks/useAIProjectId';
|
||||
@@ -25,6 +25,8 @@ import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useTranslation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const mode = searchParams.get('mode'); // 'chat' for text chat, null for project
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
||||
@@ -184,11 +186,76 @@ 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 {
|
||||
// For text chat mode, create a text chat instead of a project
|
||||
if (mode === 'chat') {
|
||||
// Create text chat
|
||||
const chat = await projectsManager.createTextChat(prompt.trim());
|
||||
|
||||
// Build message content as text parts
|
||||
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
|
||||
|
||||
// Add user input as text part if present
|
||||
if (prompt.trim()) {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: prompt.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// Process attached files and add as separate text parts
|
||||
if (attachedFiles.length > 0) {
|
||||
const filePromises = attachedFiles.map(async (file) => {
|
||||
try {
|
||||
const savedPath = await saveFileToTmp(fs, file);
|
||||
return `Added file: ${savedPath}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
return `Failed to save file: ${file.name}`;
|
||||
}
|
||||
});
|
||||
|
||||
const fileResults = await Promise.all(filePromises);
|
||||
|
||||
// Add each file as a separate text part
|
||||
fileResults.forEach(fileResult => {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: fileResult
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Store the initial message in chat history using DotAI
|
||||
const dotAI = new DotAI(fs, chat.path);
|
||||
const sessionName = DotAI.generateSessionName();
|
||||
|
||||
// Create initial message with content parts
|
||||
const initialMessage: AIMessage = {
|
||||
role: 'user',
|
||||
content: contentParts.length === 1 ? contentParts[0].text : contentParts
|
||||
};
|
||||
await dotAI.setHistory(sessionName, [initialMessage]);
|
||||
|
||||
// Add model to recently used
|
||||
addRecentlyUsedModel(providerModel.trim());
|
||||
|
||||
// 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/${chat.id}?${searchParams.toString()}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Use AI to generate project ID
|
||||
const projectId = await generateProjectId(providerModel, prompt.trim());
|
||||
|
||||
@@ -272,10 +339,10 @@ export default function Index() {
|
||||
<ShakespeareLogo className="w-20 h-20 md:w-24 md:h-24 mx-auto" />
|
||||
</div>
|
||||
<h1 className="text-3xl md:text-4xl font-bold mb-3 md:mb-4 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('buildNostrApps')}
|
||||
{mode === 'chat' ? 'Start a new chat' : t('buildNostrApps')}
|
||||
</h1>
|
||||
<p className="text-lg md:text-xl text-muted-foreground">
|
||||
{t('whatToBuild')}
|
||||
{mode === 'chat' ? 'What would you like to talk about?' : t('whatToBuild')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
+19
-11
@@ -193,13 +193,17 @@ export function ProjectView() {
|
||||
{/* Sidebar - positioned above the backdrop */}
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={project}
|
||||
onSelectProject={(selectedProject) => {
|
||||
setProject(selectedProject);
|
||||
selectedItem={project}
|
||||
onSelectItem={(selectedItem) => {
|
||||
setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation
|
||||
if (selectedProject) {
|
||||
setMobileView('chat'); // Switch to chat view when selecting a project
|
||||
navigate(`/project/${selectedProject.id}`);
|
||||
if (selectedItem) {
|
||||
if (selectedItem.type === 'project') {
|
||||
setProject(selectedItem);
|
||||
setMobileView('chat'); // Switch to chat view when selecting a project
|
||||
navigate(`/project/${selectedItem.id}`);
|
||||
} else {
|
||||
navigate(`/chat/${selectedItem.id}`);
|
||||
}
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
@@ -308,11 +312,15 @@ export function ProjectView() {
|
||||
{/* Fixed Sidebar */}
|
||||
<div className={`w-80 border-r bg-sidebar duration-300 ${isSidebarVisible ? 'block' : 'hidden'}`}>
|
||||
<ProjectSidebar
|
||||
selectedProject={project}
|
||||
onSelectProject={(selectedProject) => {
|
||||
setProject(selectedProject);
|
||||
if (selectedProject) {
|
||||
navigate(`/project/${selectedProject.id}`);
|
||||
selectedItem={project}
|
||||
onSelectItem={(selectedItem) => {
|
||||
if (selectedItem) {
|
||||
if (selectedItem.type === 'project') {
|
||||
setProject(selectedItem);
|
||||
navigate(`/project/${selectedItem.id}`);
|
||||
} else {
|
||||
navigate(`/chat/${selectedItem.id}`);
|
||||
}
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import type { TextChat } from '@/lib/ProjectsManager';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
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 { useNavigate } from 'react-router-dom';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
export function TextChatView() {
|
||||
const { chatId } = useParams<{ chatId: string }>();
|
||||
const [chat, setChat] = useState<TextChat | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
|
||||
const projectsManager = useProjectsManager();
|
||||
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 projectsManager.getTextChat(chatId);
|
||||
setChat(chatData);
|
||||
} catch (error) {
|
||||
console.error('Failed to load chat:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [chatId, projectsManager]);
|
||||
|
||||
useEffect(() => {
|
||||
loadChat();
|
||||
}, [loadChat]);
|
||||
|
||||
const handleNewChat = () => {
|
||||
if (chatPaneRef.current) {
|
||||
chatPaneRef.current.startNewSession();
|
||||
}
|
||||
};
|
||||
|
||||
const handleAILoadingChange = (loading: boolean) => {
|
||||
setIsAILoading(loading);
|
||||
};
|
||||
|
||||
if (!chat && !isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold mb-2">Chat Not Found</h1>
|
||||
<Button onClick={() => navigate('/')} variant="outline">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Home
|
||||
</Button>
|
||||
</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 ? (
|
||||
<h1 className="text-sm font-semibold truncate">
|
||||
{chat.name}
|
||||
</h1>
|
||||
) : (
|
||||
<Skeleton className="h-5 w-32" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</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="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedItem={chat}
|
||||
onSelectItem={(selectedItem) => {
|
||||
setIsSidebarVisible(false);
|
||||
if (selectedItem) {
|
||||
if (selectedItem.type === 'project') {
|
||||
navigate(`/project/${selectedItem.id}`);
|
||||
} else {
|
||||
navigate(`/chat/${selectedItem.id}`);
|
||||
}
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
}}
|
||||
onClose={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{chat ? (
|
||||
<ChatPane
|
||||
ref={chatPaneRef}
|
||||
projectId={chat.id}
|
||||
onNewChat={handleNewChat}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
isTextChat={true}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
<Skeleton className="h-12 w-full" />
|
||||
<Skeleton className="h-8 w-3/4" />
|
||||
<Skeleton className="h-8 w-1/2" />
|
||||
<Skeleton className="h-32 w-full" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-screen flex bg-background">
|
||||
{/* Fixed Sidebar */}
|
||||
<div className={`w-80 border-r bg-sidebar duration-300 ${isSidebarVisible ? 'block' : 'hidden'}`}>
|
||||
<ProjectSidebar
|
||||
selectedItem={chat}
|
||||
onSelectItem={(selectedItem) => {
|
||||
if (selectedItem) {
|
||||
if (selectedItem.type === 'project') {
|
||||
navigate(`/project/${selectedItem.id}`);
|
||||
} else {
|
||||
navigate(`/chat/${selectedItem.id}`);
|
||||
}
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
}}
|
||||
onToggleSidebar={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
className="h-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-background">
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Chat Header */}
|
||||
<div className="h-12 px-4 border-b flex-shrink-0">
|
||||
<div className="flex items-center justify-between h-12">
|
||||
<div className="flex items-center gap-3 overflow-hidden">
|
||||
{!isSidebarVisible && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(true)}
|
||||
className="h-8 w-8 p-0"
|
||||
aria-label="Open sidebar"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="flex flex-1 min-w-0 truncate">
|
||||
{chat ? (
|
||||
<h1 className="font-semibold text-lg truncate">
|
||||
{chat.name}
|
||||
</h1>
|
||||
) : (
|
||||
<Skeleton className="h-6 w-40" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chat Content */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{chat ? (
|
||||
<ChatPane
|
||||
ref={chatPaneRef}
|
||||
projectId={chat.id}
|
||||
onNewChat={handleNewChat}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
isTextChat={true}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
<Skeleton className="h-12 w-full" />
|
||||
<Skeleton className="h-8 w-3/4" />
|
||||
<Skeleton className="h-8 w-1/2" />
|
||||
<Skeleton className="h-32 w-full" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user