mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 16:03:34 +00:00
Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98aef6a321 | ||
|
|
564285f244 | ||
|
|
b8b7c13e03 | ||
|
|
240f837767 | ||
|
|
01a380520c | ||
|
|
6ec3c165b3 | ||
|
|
78dd85ad50 | ||
|
|
b3d4deedc8 | ||
|
|
0445b4d0c0 | ||
|
|
24e23e4a6e | ||
|
|
e117805487 | ||
|
|
665ca097f9 | ||
|
|
0140e46894 | ||
|
|
ebc180a850 | ||
|
|
b3ce6979c4 | ||
|
|
7d423c9829 | ||
|
|
50f60e59a1 | ||
|
|
1447c8f748 | ||
|
|
16863fd209 | ||
|
|
30465d1fd1 | ||
|
|
9622a33cbd | ||
|
|
d3c4791295 | ||
|
|
84df35de2f | ||
|
|
0086f62247 | ||
|
|
7995f51c4c | ||
|
|
5bc95d19a3 | ||
|
|
91e75d8abe | ||
|
|
38d216f125 | ||
|
|
76fe297aff | ||
|
|
5515309272 | ||
|
|
5465989c6d | ||
|
|
a1eb111244 | ||
|
|
95a539c760 | ||
|
|
34aa24f395 | ||
|
|
074acb0f10 | ||
|
|
f29903fee3 | ||
|
|
f7f392e554 |
No files matched your search
@@ -6,11 +6,13 @@ yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
.ai/
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.ai-history/
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
@@ -28,3 +30,4 @@ dist-ssr
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"model": "claude-sonnet-4",
|
||||
"model": "claude-sonnet-4-0",
|
||||
"temperature": 0.2,
|
||||
"mcpServers": {
|
||||
"js-dev": {
|
||||
|
||||
Generated
+26
-4
@@ -53,12 +53,14 @@
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"input-otp": "^1.2.4",
|
||||
"isomorphic-git": "^1.32.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"next-themes": "^0.3.0",
|
||||
"nostr-tools": "^2.15.1",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"path-browserify": "^1.0.1",
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
@@ -84,6 +86,7 @@
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@types/react-syntax-highlighter": "^15.5.13",
|
||||
@@ -3745,6 +3748,13 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/path-browserify": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/path-browserify/-/path-browserify-1.0.3.tgz",
|
||||
"integrity": "sha512-ZmHivEbNCBtAfcrFeBCiTjdIc2dey0l7oCGNGpSuRTy8jP6UVND7oUowlvDujBy8r2Hoa8bfFUOCiPWfmtkfxw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/prop-types": {
|
||||
"version": "15.7.14",
|
||||
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.14.tgz",
|
||||
@@ -5433,6 +5443,18 @@
|
||||
"@esbuild/win32-x64": "0.25.5"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild-wasm": {
|
||||
"version": "0.25.8",
|
||||
"resolved": "https://registry.npmjs.org/esbuild-wasm/-/esbuild-wasm-0.25.8.tgz",
|
||||
"integrity": "sha512-VFUDMoZdf/NsyCepv5heZqvNLYj9HL+xEKG5tktsFbx+shR8Dt9MchKBEdu/5the2RfTzgxkO6B/nUfzmsWN9Q==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"esbuild": "bin/esbuild"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/escalade": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
|
||||
@@ -8204,9 +8226,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nostr-tools": {
|
||||
"version": "2.15.1",
|
||||
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.15.1.tgz",
|
||||
"integrity": "sha512-LpetHDR9ltnkpJDkva/SONgyKBbsoV+5yLB8DWc0/U3lCWGtoWJw6Nbc2vR2Ai67RIQYrBQeZLyMlhwVZRK/9A==",
|
||||
"version": "2.15.2",
|
||||
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.15.2.tgz",
|
||||
"integrity": "sha512-utmqVVS4HMDiwhIgI6Cr+KqA4aUhF3Sb755iO/qCiqxc5H9JW/9Z3N1RO/jKWpjP6q/Vx0lru7IYuiPvk+2/ng==",
|
||||
"license": "Unlicense",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^0.5.1",
|
||||
|
||||
+4
-1
@@ -55,12 +55,14 @@
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"input-otp": "^1.2.4",
|
||||
"isomorphic-git": "^1.32.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"next-themes": "^0.3.0",
|
||||
"nostr-tools": "^2.15.1",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"path-browserify": "^1.0.1",
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
@@ -86,6 +88,7 @@
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@types/react-syntax-highlighter": "^15.5.13",
|
||||
|
||||
@@ -383,6 +383,7 @@ export function ProjectSidebar({
|
||||
className="w-full p-3 text-left text-sidebar-foreground"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Folder className="h-4 w-4 text-primary flex-shrink-0" />
|
||||
<div className="flex items-start justify-between gap-2 flex-1 min-w-0">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Folder,
|
||||
GitBranch,
|
||||
Download,
|
||||
ExternalLink,
|
||||
Users,
|
||||
Globe,
|
||||
Cloud,
|
||||
HardDrive,
|
||||
RefreshCw,
|
||||
Upload
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import git from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/web';
|
||||
import type { UnifiedRepo } from '@/hooks/useRepos';
|
||||
|
||||
interface RepoCardProps {
|
||||
repo: UnifiedRepo;
|
||||
onRepoCloned?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RepoCard({ repo, onRepoCloned, className }: RepoCardProps) {
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const [isCloning, setIsCloning] = useState(false);
|
||||
|
||||
const getStatusIcon = () => {
|
||||
switch (repo.status) {
|
||||
case 'local-only':
|
||||
return <HardDrive className="h-4 w-4 text-blue-500" />;
|
||||
case 'published':
|
||||
return <Upload className="h-4 w-4 text-green-500" />;
|
||||
case 'remote-only':
|
||||
return <Cloud className="h-4 w-4 text-orange-500" />;
|
||||
case 'synced':
|
||||
return <RefreshCw className="h-4 w-4 text-emerald-500" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusText = () => {
|
||||
switch (repo.status) {
|
||||
case 'local-only':
|
||||
return 'Local only';
|
||||
case 'published':
|
||||
return 'Published';
|
||||
case 'remote-only':
|
||||
return 'Remote only';
|
||||
case 'synced':
|
||||
return 'Synced';
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusColor = () => {
|
||||
switch (repo.status) {
|
||||
case 'local-only':
|
||||
return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
|
||||
case 'published':
|
||||
return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
|
||||
case 'remote-only':
|
||||
return 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200';
|
||||
case 'synced':
|
||||
return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200';
|
||||
}
|
||||
};
|
||||
|
||||
const handleCardClick = () => {
|
||||
if (repo.localProject) {
|
||||
navigate(`/project/${repo.localProject.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCloneRepo = async () => {
|
||||
if (!repo.nostrRepo || !repo.cloneUrls.length) {
|
||||
toast({
|
||||
title: "No clone URL",
|
||||
description: "This repository doesn't have any clone URLs configured.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCloning(true);
|
||||
|
||||
try {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create project directory
|
||||
const projectPath = `/projects/${repo.id}`;
|
||||
|
||||
// Clone the repository
|
||||
const cloneUrl = repo.cloneUrls[0]; // Use the first clone URL
|
||||
await git.clone({
|
||||
fs: projectsManager.fs,
|
||||
http,
|
||||
dir: projectPath,
|
||||
url: cloneUrl,
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
});
|
||||
|
||||
// Set git config to mark this as a nostr-enabled project
|
||||
const naddr = nip19.naddrEncode({
|
||||
identifier: repo.id,
|
||||
pubkey: repo.nostrRepo.event.pubkey,
|
||||
kind: 30617,
|
||||
relays: repo.relays.length > 0 ? repo.relays : undefined,
|
||||
});
|
||||
|
||||
await git.setConfig({
|
||||
fs: projectsManager.fs,
|
||||
dir: projectPath,
|
||||
path: 'nostr.repo',
|
||||
value: naddr,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: "Repository cloned",
|
||||
description: `${repo.name} has been cloned to your projects.`,
|
||||
});
|
||||
|
||||
// Call the callback to refresh the repos list
|
||||
if (onRepoCloned) {
|
||||
onRepoCloned();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to clone repository:', error);
|
||||
toast({
|
||||
title: "Clone failed",
|
||||
description: `Failed to clone ${repo.name}. Please try again.`,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsCloning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const canOpen = repo.status === 'local-only' || repo.status === 'published' || repo.status === 'synced';
|
||||
const canClone = repo.status === 'remote-only' && repo.cloneUrls.length > 0;
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={cn(
|
||||
"transition-all duration-300 bg-gradient-to-br from-card to-card/80 border-primary/10 hover:border-primary/20",
|
||||
canOpen && "cursor-pointer hover:shadow-xl hover:shadow-primary/10 hover:scale-[1.02]",
|
||||
className
|
||||
)}
|
||||
onClick={canOpen ? handleCardClick : undefined}
|
||||
tabIndex={canOpen ? 0 : undefined}
|
||||
onKeyDown={canOpen ? (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleCardClick();
|
||||
}
|
||||
} : undefined}
|
||||
>
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<CardTitle className="text-base md:text-lg flex items-center gap-2 truncate">
|
||||
{repo.status === 'remote-only' ? (
|
||||
<GitBranch className="h-4 w-4 text-primary flex-shrink-0" />
|
||||
) : (
|
||||
<Folder className="h-4 w-4 text-primary flex-shrink-0" />
|
||||
)}
|
||||
<span className="truncate">{repo.name}</span>
|
||||
</CardTitle>
|
||||
{repo.description && (
|
||||
<CardDescription className="text-sm mt-1 line-clamp-2">
|
||||
{repo.description}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 ml-2">
|
||||
<Badge variant="outline" className={cn("text-xs", getStatusColor())}>
|
||||
<span className="flex items-center gap-1">
|
||||
{getStatusIcon()}
|
||||
{getStatusText()}
|
||||
</span>
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<CardDescription className="text-sm">
|
||||
Modified {repo.lastModified.toLocaleDateString()}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3">
|
||||
{/* Tags */}
|
||||
{repo.tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{repo.tags.slice(0, 3).map((tag) => (
|
||||
<Badge key={tag} variant="secondary" className="text-xs">
|
||||
{tag}
|
||||
</Badge>
|
||||
))}
|
||||
{repo.tags.length > 3 && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
+{repo.tags.length - 3}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Repository info */}
|
||||
{(repo.maintainers.length > 0 || repo.webUrls.length > 0) && (
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
{repo.maintainers.length > 0 && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Users className="h-3 w-3" />
|
||||
<span>{repo.maintainers.length} maintainer{repo.maintainers.length !== 1 ? 's' : ''}</span>
|
||||
</div>
|
||||
)}
|
||||
{repo.webUrls.length > 0 && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Globe className="h-3 w-3" />
|
||||
<span>Web</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
{(canClone || repo.webUrls.length > 0) && (
|
||||
<div className="flex gap-2" onClick={(e) => e.stopPropagation()}>
|
||||
{canClone && (
|
||||
<Button
|
||||
onClick={handleCloneRepo}
|
||||
disabled={isCloning}
|
||||
className="flex-1"
|
||||
size="sm"
|
||||
>
|
||||
{isCloning ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white mr-2"></div>
|
||||
Cloning...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="h-3 w-3 mr-2" />
|
||||
Clone
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{repo.webUrls.length > 0 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(repo.webUrls[0], '_blank')}
|
||||
className="px-3"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage, generateId } from 'ai';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -8,7 +7,7 @@ import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useJSRuntime } from '@/hooks/useJSRuntime';
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { copyDirectory, copyFile } from '@/lib/copyFiles';
|
||||
import { copyDirectory } from '@/lib/copyFiles';
|
||||
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
|
||||
import { bytesToHex } from 'nostr-tools/utils';
|
||||
import { MessageItem } from '@/components/ai/MessageItem';
|
||||
@@ -19,21 +18,24 @@ import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
|
||||
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
|
||||
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
|
||||
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
|
||||
import { buildProject } from "@/lib/build";
|
||||
|
||||
interface ChatPaneProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
onBuildComplete?: (projectId: string) => void;
|
||||
}
|
||||
|
||||
type AIMessage = (CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string };
|
||||
|
||||
export function ChatPane({ projectId, projectName }: ChatPaneProps) {
|
||||
export function ChatPane({ projectId, projectName, onBuildComplete }: ChatPaneProps) {
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isBuildLoading, setIsBuildLoading] = useState(false);
|
||||
const [isDeployLoading, setIsDeployLoading] = useState(false);
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
const { fs: browserFS } = useFS();
|
||||
const { runtime } = useJSRuntime();
|
||||
@@ -72,56 +74,32 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
|
||||
|
||||
setIsBuildLoading(true);
|
||||
updateMetadata('Shakespeare', `Building ${projectName}...`);
|
||||
|
||||
const dist = await buildProject({
|
||||
fs: browserFS,
|
||||
projectPath: `/projects/${projectId}`,
|
||||
domParser: new DOMParser(),
|
||||
target: "esnext",
|
||||
});
|
||||
|
||||
console.log(dist);
|
||||
|
||||
// Delete all existing files in "dist" directory
|
||||
try {
|
||||
console.log('Running build for project:', projectId);
|
||||
const runtimeFS = await runtime.fs();
|
||||
|
||||
// Copy project files to runtime filesystem
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
try {
|
||||
await copyDirectory(browserFS, runtimeFS, projectPath, '.');
|
||||
console.log('Successfully copied project to runtime');
|
||||
} catch (error) {
|
||||
console.error('Failed to copy project to runtime:', error);
|
||||
return;
|
||||
for (const file of await browserFS.readdir(`/projects/${projectId}/dist`)) {
|
||||
await browserFS.unlink(`/projects/${projectId}/dist/${file}`);
|
||||
}
|
||||
|
||||
// Install dependencies and build
|
||||
const proc = await runtime.spawn('npm', ['i']);
|
||||
await proc.exit;
|
||||
|
||||
const proc2 = await runtime.spawn('npm', ['run', 'build']);
|
||||
await proc2.exit;
|
||||
|
||||
// Copy "dist" directory from runtime back to project filesystem
|
||||
const distPath = `/projects/${projectId}/dist`;
|
||||
try {
|
||||
await copyDirectory(runtimeFS, browserFS, 'dist', distPath);
|
||||
console.log('Successfully copied dist from runtime');
|
||||
} catch (error) {
|
||||
console.error('Failed to copy dist:', error);
|
||||
}
|
||||
|
||||
// Copy package-lock.json from runtime back to project filesystem
|
||||
const packageLockPath = `/projects/${projectId}/package-lock.json`;
|
||||
try {
|
||||
await copyFile(runtimeFS, browserFS, 'package-lock.json', packageLockPath);
|
||||
console.log('Successfully copied package-lock.json from runtime');
|
||||
} catch (error) {
|
||||
console.error('Failed to copy package-lock.json:', error);
|
||||
}
|
||||
|
||||
// Dispatch build complete event to refresh the preview iframe
|
||||
const buildCompleteEvent = new CustomEvent('buildComplete', {
|
||||
detail: { projectId }
|
||||
});
|
||||
window.dispatchEvent(buildCompleteEvent);
|
||||
console.log('Build completed successfully, dispatched refresh event');
|
||||
} catch (error) {
|
||||
console.error('Build failed:', error);
|
||||
} finally {
|
||||
setIsBuildLoading(false);
|
||||
} catch {
|
||||
// Ignore errors (e.g., directory doesn't exist)
|
||||
}
|
||||
|
||||
await browserFS.mkdir(`/projects/${projectId}/dist`, { recursive: true });
|
||||
|
||||
for (const [path, contents] of Object.entries(dist)) {
|
||||
await browserFS.writeFile(`/projects/${projectId}/dist/${path}`, contents);
|
||||
}
|
||||
|
||||
setIsBuildLoading(false);
|
||||
};
|
||||
|
||||
const runDeploy = async () => {
|
||||
@@ -226,7 +204,7 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
const provider = openai(settings.model);
|
||||
const cwd = `/projects/${projectId}`;
|
||||
|
||||
return generateText({
|
||||
const result = await generateText({
|
||||
model: provider,
|
||||
messages,
|
||||
maxSteps: 100,
|
||||
@@ -281,6 +259,56 @@ The project uses:
|
||||
|
||||
When creating new components or pages, follow the existing patterns in the codebase.`
|
||||
});
|
||||
|
||||
// After the entire generation is complete, check if we should auto-build
|
||||
console.log('Agent finished with reason:', result.finishReason);
|
||||
|
||||
// Only auto-build if:
|
||||
// 1. The agent completed successfully (not stopped due to errors or limits)
|
||||
// 2. The previous response before the stop was from the assistant invoking tool calls
|
||||
// (meaning actual work was performed, not just conversational response)
|
||||
const responseMessages = result.response.messages;
|
||||
const hasToolResults = responseMessages.some(msg => msg.role === 'tool');
|
||||
|
||||
if (result.finishReason === 'stop' && hasToolResults) {
|
||||
console.log('Agent performed tool work successfully, auto-building project...');
|
||||
|
||||
setTimeout(async () => {
|
||||
if (isBuildLoading || isDeployLoading) {
|
||||
addMessage({
|
||||
id: generateId(),
|
||||
role: 'assistant',
|
||||
content: '⏸️ Build or deploy already in progress. Skipping auto-build.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await runBuild();
|
||||
if (onBuildComplete) {
|
||||
onBuildComplete(projectId);
|
||||
}
|
||||
addMessage({
|
||||
id: generateId(),
|
||||
role: 'assistant',
|
||||
content: '✅ Agent completed successfully. Project built! Switch to the "Preview" tab to see your changes.',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Auto-build failed:', error);
|
||||
addMessage({
|
||||
id: generateId(),
|
||||
role: 'assistant',
|
||||
content: `❌ Auto-build failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
});
|
||||
}
|
||||
}, 1000);
|
||||
} else if (result.finishReason === 'stop' && !hasToolResults) {
|
||||
console.log('Agent completed but no tool work was performed - skipping auto-build');
|
||||
} else {
|
||||
console.log('Agent finished with reason:', result.finishReason, '- skipping auto-build');
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const handleSend = async () => {
|
||||
@@ -303,6 +331,7 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
await createAIChat(projectId, aiMessages);
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
|
||||
const errorMessage: AIMessage = {
|
||||
id: generateId(),
|
||||
role: 'assistant',
|
||||
@@ -377,8 +406,6 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<div className="border-b bg-gradient-to-r from-primary/5 to-accent/5 px-4 py-3 flex justify-between items-center">
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { AssistantContent } from './AssistantContent';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import type { CoreToolMessage } from 'ai';
|
||||
|
||||
|
||||
describe('AssistantContent', () => {
|
||||
const mockToolResults: CoreToolMessage[] = [];
|
||||
|
||||
describe('Build Action Detection', () => {
|
||||
it('should render build action for auto-build success message', () => {
|
||||
const content = '✅ Agent completed successfully. Project built and preview updated!';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AssistantContent content={content} toolResults={mockToolResults} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Check if BuildAction component is rendered with auto-build title
|
||||
expect(screen.getByText('Auto-Build Project')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render regular markdown for non-build-action string content', () => {
|
||||
const content = 'Hello, I can help you with your project.';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AssistantContent content={content} toolResults={mockToolResults} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Hello, I can help you with your project.')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Project|Action/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render tool calls for array content with tool-call items', () => {
|
||||
const content = [
|
||||
{ type: 'tool-call' as const, toolName: 'some_custom_tool', toolCallId: 'test-id', args: { param1: 'value1' } }
|
||||
];
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AssistantContent content={content} toolResults={mockToolResults} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/some_custom_tool/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import { FileWriter } from '@/components/ai/FileWriter';
|
||||
import { ShellCommand } from '@/components/ai/ShellCommand';
|
||||
import { PackageManager } from '@/components/ai/PackageManager';
|
||||
import { GitCommit } from '@/components/ai/GitCommit';
|
||||
import { BuildAction } from '@/components/ai/BuildAction';
|
||||
import type { CoreAssistantMessage, CoreToolMessage } from 'ai';
|
||||
|
||||
interface AssistantContentProps {
|
||||
@@ -64,8 +65,64 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
|
||||
return { isError: toolResult.isError || false };
|
||||
};
|
||||
|
||||
// Helper function to check if text represents a build action
|
||||
const isBuildAction = (text: string): boolean => {
|
||||
return /(✅|❌|⏸️|🎉)/.test(text) && /(Agent completed successfully|Auto-build|Build|Deploy|Building|Deploying)/i.test(text);
|
||||
};
|
||||
|
||||
// Helper function to determine build action type
|
||||
const getActionType = (text: string): 'build' | 'deploy' | 'auto-build' => {
|
||||
if (text.includes('Auto-build') || text.includes('Auto-building') ||
|
||||
(text.includes('Agent completed successfully') && text.includes('built'))) {
|
||||
return 'auto-build';
|
||||
}
|
||||
if (text.includes('Deploy') || text.includes('Deploying')) {
|
||||
return 'deploy';
|
||||
}
|
||||
return 'build';
|
||||
};
|
||||
|
||||
// Helper function to determine build action status
|
||||
const getActionStatus = (text: string): { isError: boolean; isLoading: boolean } => {
|
||||
const icon = text.match(/(✅|❌|⏸️|🎉)/)?.[1];
|
||||
const hasFailed = icon === '❌' || text.toLowerCase().includes('failed');
|
||||
const isRunning = icon === '⏸️' || /(Building|Deploying)/i.test(text);
|
||||
|
||||
return {
|
||||
isError: hasFailed,
|
||||
isLoading: isRunning && !hasFailed
|
||||
};
|
||||
};
|
||||
|
||||
// Helper function to render build action
|
||||
const renderBuildAction = (text: string, key: number | string) => {
|
||||
if (!isBuildAction(text)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const actionType = getActionType(text);
|
||||
const { isError, isLoading } = getActionStatus(text);
|
||||
|
||||
return (
|
||||
<BuildAction
|
||||
key={key}
|
||||
action={actionType}
|
||||
result={text}
|
||||
isError={isError}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
// Handle string content (simple text messages)
|
||||
if (typeof content === 'string') {
|
||||
// Check if this is a build action message
|
||||
const buildAction = renderBuildAction(content, 'string-content');
|
||||
if (buildAction) {
|
||||
return buildAction;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="prose prose-sm max-w-none dark:prose-invert">
|
||||
<ReactMarkdown
|
||||
@@ -117,6 +174,12 @@ export const AssistantContent = memo(({ content, toolResults = [] }: AssistantCo
|
||||
<>
|
||||
{content.map((item, index) => {
|
||||
if (item.type === 'text') {
|
||||
// Check if this is a build action message
|
||||
const buildAction = renderBuildAction(item.text, index);
|
||||
if (buildAction) {
|
||||
return buildAction;
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={index} className="prose prose-sm max-w-none dark:prose-invert">
|
||||
<ReactMarkdown
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { memo } from 'react';
|
||||
import { ActionCard } from './shared/ActionCard';
|
||||
|
||||
interface BuildActionProps {
|
||||
action: 'build' | 'deploy' | 'auto-build';
|
||||
result?: string;
|
||||
status?: 'RUNNING' | 'SUCCESS' | 'FAILED' | 'PENDING';
|
||||
isError?: boolean;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export const BuildAction = memo(({ action, result, status, isError, isLoading }: BuildActionProps) => {
|
||||
const actionConfig = {
|
||||
build: { title: 'Build Project', verb: 'build' },
|
||||
deploy: { title: 'Deploy Project', verb: 'deploy' },
|
||||
'auto-build': { title: 'Auto-Build Project', verb: 'auto-build' },
|
||||
}[action] || { title: 'Build Action', verb: 'process' };
|
||||
|
||||
const getActionDescription = () => {
|
||||
const effectiveStatus = status || (
|
||||
isLoading ? 'RUNNING' :
|
||||
isError ? 'FAILED' : 'SUCCESS'
|
||||
);
|
||||
|
||||
if (effectiveStatus === 'RUNNING') return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)}ing project...`;
|
||||
if (effectiveStatus === 'FAILED') return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)} failed`;
|
||||
if (effectiveStatus === 'SUCCESS') return `${actionConfig.verb.charAt(0).toUpperCase() + actionConfig.verb.slice(1)} completed`;
|
||||
return `Starting ${actionConfig.verb} process...`;
|
||||
};
|
||||
|
||||
return (
|
||||
<ActionCard
|
||||
title={actionConfig.title}
|
||||
description={getActionDescription()}
|
||||
result={result}
|
||||
status={status}
|
||||
isError={isError}
|
||||
isLoading={isLoading}
|
||||
successLabel="Completed"
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
BuildAction.displayName = 'BuildAction';
|
||||
@@ -4,7 +4,7 @@ import { TestApp } from '@/test/TestApp';
|
||||
import { GitCommit } from './GitCommit';
|
||||
|
||||
describe('GitCommit', () => {
|
||||
it('renders commit message and shows committing state', () => {
|
||||
it('renders commit message', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitCommit message="feat: add new feature" />
|
||||
@@ -12,8 +12,6 @@ describe('GitCommit', () => {
|
||||
);
|
||||
|
||||
expect(screen.getByText('feat: add new feature')).toBeInTheDocument();
|
||||
expect(screen.getByText('Committing')).toBeInTheDocument();
|
||||
expect(screen.getByText('Git commit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows success state with commit details', () => {
|
||||
@@ -38,7 +36,7 @@ describe('GitCommit', () => {
|
||||
|
||||
expect(screen.getByText('Committed')).toBeInTheDocument();
|
||||
expect(screen.getByText('Successfully committed 3 files')).toBeInTheDocument();
|
||||
expect(screen.getByText('abc1234')).toBeInTheDocument();
|
||||
expect(screen.getByText('main branch')).toBeInTheDocument();
|
||||
expect(screen.getByText('2 added')).toBeInTheDocument();
|
||||
expect(screen.getByText('1 modified')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { GitCommit as GitCommitIcon, CheckCircle, XCircle, GitBranch, Plus, Minus, Edit } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ActionCard } from './shared/ActionCard';
|
||||
import { GitCommit as GitCommitIcon, GitBranch, Plus, Minus, Edit } from 'lucide-react';
|
||||
|
||||
interface GitCommitProps {
|
||||
message: string;
|
||||
@@ -80,61 +78,33 @@ export function GitCommit({
|
||||
const firstLine = getFirstLine(message);
|
||||
const commitEmoji = getCommitEmoji(message);
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitCommitIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg">{commitEmoji}</span>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-mono text-sm font-medium truncate">
|
||||
{firstLine}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Git commit
|
||||
{stats?.branch && (
|
||||
<span className="ml-2 inline-flex items-center gap-1">
|
||||
<GitBranch className="h-3 w-3" />
|
||||
{stats.branch}
|
||||
</span>
|
||||
)}
|
||||
{stats?.hash && (
|
||||
<span className="ml-2 font-mono">
|
||||
{stats.hash}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result !== undefined ? (
|
||||
isError ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Failed
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
Committed
|
||||
</Badge>
|
||||
)
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
|
||||
<GitCommitIcon className="h-3 w-3 mr-1" />
|
||||
Committing
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
const getCommitDescription = () => {
|
||||
let desc = 'Git commit';
|
||||
if (stats?.branch) {
|
||||
desc += ` • ${stats.branch} branch`;
|
||||
}
|
||||
if (stats?.hash) {
|
||||
desc += ` • ${stats.hash}`;
|
||||
}
|
||||
return desc;
|
||||
};
|
||||
|
||||
return (
|
||||
<ActionCard
|
||||
title={firstLine}
|
||||
description={getCommitDescription()}
|
||||
icon={<span className="text-lg">{commitEmoji}</span>}
|
||||
result={result}
|
||||
isError={isError}
|
||||
className={className}
|
||||
showResult={false}
|
||||
runningIcon={<GitCommitIcon className="h-3 w-3" />}
|
||||
runningLabel="Committing"
|
||||
successLabel="Committed"
|
||||
>
|
||||
{/* Full commit message - only show if multi-line */}
|
||||
{message.includes('\n') && (
|
||||
<CardContent className="pt-0">
|
||||
<div className="mb-3">
|
||||
<details className="group">
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
|
||||
<span className="group-open:rotate-90 transition-transform">▶</span>
|
||||
@@ -148,19 +118,14 @@ export function GitCommit({
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</CardContent>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<CardContent className={cn("pt-0", message.includes('\n') ? "pt-3" : "")}>
|
||||
<>
|
||||
{/* Summary */}
|
||||
{summary && (
|
||||
<div className={cn(
|
||||
"mb-3 p-3 rounded-md text-sm font-medium",
|
||||
isError
|
||||
? "bg-destructive/10 text-destructive border border-destructive/20"
|
||||
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
|
||||
)}>
|
||||
<div className="mb-3 p-3 rounded-md text-sm font-muted-foreground">
|
||||
{summary}
|
||||
</div>
|
||||
)}
|
||||
@@ -207,8 +172,8 @@ export function GitCommit({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
</ActionCard>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Play, CheckCircle, XCircle } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ActionCard } from './shared/ActionCard';
|
||||
import { Play } from 'lucide-react';
|
||||
|
||||
interface ScriptRunnerProps {
|
||||
script: string;
|
||||
@@ -104,52 +102,21 @@ export function ScriptRunner({ script, result, isError = false, className }: Scr
|
||||
const { summary, details } = parseOutput(result || '');
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Play className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg">{scriptInfo.icon}</span>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-mono text-sm font-medium">npm run {script}</div>
|
||||
<div className="text-xs text-muted-foreground">{scriptInfo.description}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result !== undefined ? (
|
||||
isError ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Failed
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
Success
|
||||
</Badge>
|
||||
)
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
|
||||
<Play className="h-3 w-3 mr-1" />
|
||||
Running
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<ActionCard
|
||||
title={`npm run ${script}`}
|
||||
description={scriptInfo.description}
|
||||
icon={<span className="text-lg">{scriptInfo.icon}</span>}
|
||||
result={result}
|
||||
isError={isError}
|
||||
className={className}
|
||||
runningIcon={<Play className="h-3 w-3" />}
|
||||
runningLabel="Running"
|
||||
>
|
||||
{result && (
|
||||
<CardContent className="pt-0">
|
||||
<>
|
||||
{/* Summary */}
|
||||
{summary && (
|
||||
<div className={cn(
|
||||
"mb-3 p-3 rounded-md text-sm font-medium",
|
||||
isError
|
||||
? "bg-destructive/10 text-destructive border border-destructive/20"
|
||||
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
|
||||
)}>
|
||||
<div className="mb-3 p-3 rounded-md text-sm font-muted-foreground">
|
||||
{summary}
|
||||
</div>
|
||||
)}
|
||||
@@ -201,8 +168,8 @@ export function ScriptRunner({ script, result, isError = false, className }: Scr
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
</ActionCard>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Terminal, CheckCircle, XCircle, Play } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ActionCard } from './shared/ActionCard';
|
||||
import { Terminal } from 'lucide-react';
|
||||
|
||||
interface ShellCommandProps {
|
||||
command: string;
|
||||
@@ -122,52 +120,21 @@ export function ShellCommand({ command, result, isError = false, className }: Sh
|
||||
const { summary, details } = parseOutput(result || '');
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg">{commandInfo.icon}</span>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-mono text-sm font-medium">$ {commandInfo.fullCommand}</div>
|
||||
<div className="text-xs text-muted-foreground">{commandInfo.description}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result !== undefined ? (
|
||||
isError ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Failed
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
Success
|
||||
</Badge>
|
||||
)
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
|
||||
<Play className="h-3 w-3 mr-1" />
|
||||
Running
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<ActionCard
|
||||
title={`$ ${commandInfo.fullCommand}`}
|
||||
description={commandInfo.description}
|
||||
icon={<span className="text-lg">{commandInfo.icon}</span>}
|
||||
result={result}
|
||||
isError={isError}
|
||||
className={className}
|
||||
runningIcon={<Terminal className="h-3 w-3" />}
|
||||
runningLabel="Executing"
|
||||
>
|
||||
{result && (
|
||||
<CardContent className="pt-0">
|
||||
<>
|
||||
{/* Summary */}
|
||||
{summary && (
|
||||
<div className={cn(
|
||||
"mb-3 p-3 rounded-md text-sm font-medium",
|
||||
isError
|
||||
? "bg-destructive/10 text-destructive border border-destructive/20"
|
||||
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
|
||||
)}>
|
||||
<div className="mb-3 p-3 rounded-md text-sm font-muted-foreground">
|
||||
{summary}
|
||||
</div>
|
||||
)}
|
||||
@@ -210,8 +177,8 @@ export function ShellCommand({ command, result, isError = false, className }: Sh
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
</ActionCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ActionStatus, type ActionStatusProps } from './ActionStatus';
|
||||
|
||||
export interface ActionCardProps extends Omit<ActionStatusProps, 'status'> {
|
||||
title: string;
|
||||
description?: string;
|
||||
icon?: React.ReactNode;
|
||||
result?: string;
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
showResult?: boolean;
|
||||
status?: ActionStatusProps['status'];
|
||||
}
|
||||
|
||||
export function ActionCard({
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
result,
|
||||
children,
|
||||
className,
|
||||
showResult = true,
|
||||
...statusProps
|
||||
}: ActionCardProps) {
|
||||
const { Badge, Icon, ResultClass, BorderClass } = ActionStatus({
|
||||
_result: result,
|
||||
...statusProps,
|
||||
status: statusProps.status
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", BorderClass(), className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
{icon && (
|
||||
<div className="flex items-center gap-2">
|
||||
{Icon('md')}
|
||||
{icon}
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<div className="font-mono text-sm font-medium">{title}</div>
|
||||
{description && (
|
||||
<div className="text-xs text-muted-foreground">{description}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{(children || (showResult && result)) && (
|
||||
<CardContent className="pt-0">
|
||||
{children}
|
||||
|
||||
{showResult && result && (
|
||||
<div className={ResultClass()}>
|
||||
<pre className="whitespace-pre-wrap break-words">{result}</pre>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Loader2, XCircle, CheckCircle, Play } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface ActionStatusProps {
|
||||
status?: 'RUNNING' | 'SUCCESS' | 'FAILED' | 'PENDING';
|
||||
isLoading?: boolean;
|
||||
isError?: boolean;
|
||||
_result?: string;
|
||||
runningIcon?: React.ReactNode;
|
||||
successIcon?: React.ReactNode;
|
||||
failedIcon?: React.ReactNode;
|
||||
successLabel?: string;
|
||||
failedLabel?: string;
|
||||
runningLabel?: string;
|
||||
}
|
||||
|
||||
export function ActionStatus({
|
||||
status,
|
||||
isLoading,
|
||||
isError,
|
||||
_result,
|
||||
runningIcon = <Loader2 className="h-3 w-3 animate-spin" />,
|
||||
successIcon = <CheckCircle className="h-3 w-3" />,
|
||||
failedIcon = <XCircle className="h-3 w-3" />,
|
||||
successLabel = 'Success',
|
||||
failedLabel = 'Failed',
|
||||
runningLabel = 'Running'
|
||||
}: ActionStatusProps) {
|
||||
// Handle both new status-based and old boolean-based props for compatibility
|
||||
const effectiveStatus = status || (
|
||||
isLoading ? 'RUNNING' :
|
||||
isError ? 'FAILED' : 'SUCCESS'
|
||||
) as 'RUNNING' | 'SUCCESS' | 'FAILED' | 'PENDING';
|
||||
|
||||
const getBadge = () => {
|
||||
if (effectiveStatus === 'RUNNING') {
|
||||
return (
|
||||
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
|
||||
{runningIcon}
|
||||
{runningLabel}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
if (effectiveStatus === 'FAILED') {
|
||||
return (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
{failedIcon}
|
||||
{failedLabel}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
{successIcon}
|
||||
{successLabel}
|
||||
</Badge>
|
||||
);
|
||||
};
|
||||
|
||||
const getIcon = (size: 'sm' | 'md' = 'md') => {
|
||||
const sizeClass = size === 'sm' ? 'h-3 w-3' : 'h-4 w-4';
|
||||
|
||||
if (effectiveStatus === 'RUNNING') return <Loader2 className={`${sizeClass} animate-spin`} />;
|
||||
if (effectiveStatus === 'FAILED') return <XCircle className={`${sizeClass} text-destructive`} />;
|
||||
return <Play className={sizeClass} />;
|
||||
};
|
||||
|
||||
const getResultClass = () => {
|
||||
return cn(
|
||||
"p-3 rounded-md text-sm",
|
||||
effectiveStatus === 'FAILED'
|
||||
? "bg-destructive/10 text-destructive border border-destructive/20"
|
||||
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
|
||||
);
|
||||
};
|
||||
|
||||
const getBorderClass = () => {
|
||||
return effectiveStatus === 'FAILED' ? "border-destructive/50" : "border-muted";
|
||||
};
|
||||
|
||||
return {
|
||||
Badge: getBadge,
|
||||
Icon: getIcon,
|
||||
ResultClass: getResultClass,
|
||||
BorderClass: getBorderClass,
|
||||
status: effectiveStatus
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useProjectsManager } from './useProjectsManager';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
export interface NostrRepo {
|
||||
event: NostrEvent;
|
||||
id: string; // d tag value
|
||||
name: string;
|
||||
description?: string;
|
||||
webUrls: string[];
|
||||
cloneUrls: string[];
|
||||
relays: string[];
|
||||
maintainers: string[];
|
||||
tags: string[];
|
||||
earliestCommit?: string;
|
||||
}
|
||||
|
||||
export type RepoStatus =
|
||||
| 'local-only' // Exists only locally, not published to Nostr
|
||||
| 'published' // Local project that's also published to Nostr
|
||||
| 'remote-only' // Exists on Nostr but not cloned locally
|
||||
| 'synced'; // Local and remote are in sync
|
||||
|
||||
export interface UnifiedRepo {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
status: RepoStatus;
|
||||
lastModified: Date;
|
||||
|
||||
// Local project data (if exists locally)
|
||||
localProject?: Project;
|
||||
|
||||
// Nostr repo data (if exists on Nostr)
|
||||
nostrRepo?: NostrRepo;
|
||||
|
||||
// Additional metadata
|
||||
tags: string[];
|
||||
webUrls: string[];
|
||||
cloneUrls: string[];
|
||||
maintainers: string[];
|
||||
relays: string[];
|
||||
}
|
||||
|
||||
function parseRepoEvent(event: NostrEvent): NostrRepo | null {
|
||||
// Validate that this is a repository announcement event
|
||||
if (event.kind !== 30617) return null;
|
||||
|
||||
const dTag = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
if (!dTag) return null;
|
||||
|
||||
const name = event.tags.find(([name]) => name === 'name')?.[1] || dTag;
|
||||
const description = event.tags.find(([name]) => name === 'description')?.[1];
|
||||
|
||||
const webUrls = event.tags
|
||||
.filter(([name]) => name === 'web')
|
||||
.map(([, url]) => url)
|
||||
.filter(Boolean);
|
||||
|
||||
const cloneUrls = event.tags
|
||||
.filter(([name]) => name === 'clone')
|
||||
.map(([, url]) => url)
|
||||
.filter(Boolean);
|
||||
|
||||
const relays = event.tags
|
||||
.filter(([name]) => name === 'relays')
|
||||
.map(([, relay]) => relay)
|
||||
.filter(Boolean);
|
||||
|
||||
const maintainers = event.tags
|
||||
.filter(([name]) => name === 'maintainers')
|
||||
.map(([, pubkey]) => pubkey)
|
||||
.filter(Boolean);
|
||||
|
||||
const tags = event.tags
|
||||
.filter(([name]) => name === 't')
|
||||
.map(([, tag]) => tag)
|
||||
.filter(Boolean);
|
||||
|
||||
const earliestCommit = event.tags
|
||||
.find(([name, , marker]) => name === 'r' && marker === 'euc')?.[1];
|
||||
|
||||
return {
|
||||
event,
|
||||
id: dTag,
|
||||
name,
|
||||
description,
|
||||
webUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
maintainers,
|
||||
tags,
|
||||
earliestCommit,
|
||||
};
|
||||
}
|
||||
|
||||
export function useRepos() {
|
||||
const projectsManager = useProjectsManager();
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['unified-repos', user?.pubkey],
|
||||
queryFn: async (c) => {
|
||||
try {
|
||||
if (!user?.pubkey) return [];
|
||||
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(3000)]);
|
||||
|
||||
// Fetch Nostr repos and local projects in parallel
|
||||
const [events, localProjects] = await Promise.all([
|
||||
nostr.query([
|
||||
{
|
||||
kinds: [30617], // Repository announcements
|
||||
authors: [user.pubkey],
|
||||
limit: 50,
|
||||
}
|
||||
], { signal }),
|
||||
(async () => {
|
||||
await projectsManager.init();
|
||||
return projectsManager.getProjects();
|
||||
})()
|
||||
]);
|
||||
|
||||
// Parse and validate Nostr events
|
||||
const nostrRepos = events
|
||||
.map(parseRepoEvent)
|
||||
.filter((repo): repo is NostrRepo => repo !== null)
|
||||
.sort((a, b) => b.event.created_at - a.event.created_at);
|
||||
|
||||
// Create a map to track repos by their identifier
|
||||
const repoMap = new Map<string, UnifiedRepo>();
|
||||
|
||||
// First, add all local projects
|
||||
for (const project of localProjects) {
|
||||
const naddr = await projectsManager.getNostrRepoAddress(project.id);
|
||||
let repoId = project.id;
|
||||
let status: RepoStatus = 'local-only';
|
||||
|
||||
// If this project has a Nostr address, extract the repo ID
|
||||
if (naddr) {
|
||||
try {
|
||||
const decoded = nip19.decode(naddr);
|
||||
if (decoded.type === 'naddr') {
|
||||
repoId = decoded.data.identifier;
|
||||
status = 'published';
|
||||
}
|
||||
} catch {
|
||||
// If we can't decode the naddr, treat as local-only
|
||||
}
|
||||
}
|
||||
|
||||
repoMap.set(repoId, {
|
||||
id: repoId,
|
||||
name: project.name,
|
||||
description: undefined,
|
||||
status,
|
||||
lastModified: project.lastModified,
|
||||
localProject: project,
|
||||
tags: [],
|
||||
webUrls: [],
|
||||
cloneUrls: [],
|
||||
maintainers: [],
|
||||
relays: [],
|
||||
});
|
||||
}
|
||||
|
||||
// Then, add or update with Nostr repos
|
||||
for (const nostrRepo of nostrRepos) {
|
||||
const existingRepo = repoMap.get(nostrRepo.id);
|
||||
|
||||
if (existingRepo) {
|
||||
// Update existing repo with Nostr data
|
||||
existingRepo.nostrRepo = nostrRepo;
|
||||
existingRepo.description = nostrRepo.description;
|
||||
existingRepo.tags = nostrRepo.tags;
|
||||
existingRepo.webUrls = nostrRepo.webUrls;
|
||||
existingRepo.cloneUrls = nostrRepo.cloneUrls;
|
||||
existingRepo.maintainers = nostrRepo.maintainers;
|
||||
existingRepo.relays = nostrRepo.relays;
|
||||
|
||||
// Update status based on local presence
|
||||
if (existingRepo.localProject) {
|
||||
existingRepo.status = 'synced';
|
||||
}
|
||||
} else {
|
||||
// Add new remote-only repo
|
||||
repoMap.set(nostrRepo.id, {
|
||||
id: nostrRepo.id,
|
||||
name: nostrRepo.name,
|
||||
description: nostrRepo.description,
|
||||
status: 'remote-only',
|
||||
lastModified: new Date(nostrRepo.event.created_at * 1000),
|
||||
nostrRepo,
|
||||
tags: nostrRepo.tags,
|
||||
webUrls: nostrRepo.webUrls,
|
||||
cloneUrls: nostrRepo.cloneUrls,
|
||||
maintainers: nostrRepo.maintainers,
|
||||
relays: nostrRepo.relays,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Convert map to array and sort by last modified
|
||||
const repos = Array.from(repoMap.values()).sort((a, b) =>
|
||||
b.lastModified.getTime() - a.lastModified.getTime()
|
||||
);
|
||||
|
||||
return repos;
|
||||
} catch (error) {
|
||||
console.error('Failed to load unified repos:', error);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
enabled: !!user?.pubkey,
|
||||
staleTime: 30 * 1000, // 30 seconds
|
||||
gcTime: 60 * 1000, // 1 minute
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { ProjectsManager } from './ProjectsManager';
|
||||
|
||||
// Mock filesystem for testing
|
||||
class MockFS {
|
||||
private files: Map<string, string | Uint8Array> = new Map();
|
||||
private dirs: Set<string> = new Set();
|
||||
|
||||
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||
const content = this.files.get(path);
|
||||
if (content === undefined) {
|
||||
const error = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
throw error;
|
||||
}
|
||||
if (encoding === 'utf8' && typeof content === 'string') {
|
||||
return content;
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
|
||||
this.files.set(path, data);
|
||||
// Ensure parent directory exists
|
||||
const dir = path.split('/').slice(0, -1).join('/');
|
||||
if (dir) {
|
||||
this.dirs.add(dir);
|
||||
}
|
||||
}
|
||||
|
||||
async readdir(path: string): Promise<string[]> {
|
||||
if (!this.dirs.has(path)) {
|
||||
const error = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
throw error;
|
||||
}
|
||||
|
||||
const entries: string[] = [];
|
||||
|
||||
// Find subdirectories
|
||||
for (const dir of this.dirs) {
|
||||
if (dir.startsWith(path + '/') && !dir.slice(path.length + 1).includes('/')) {
|
||||
entries.push(dir.slice(path.length + 1));
|
||||
}
|
||||
}
|
||||
|
||||
// Find files
|
||||
for (const file of this.files.keys()) {
|
||||
if (file.startsWith(path + '/') && !file.slice(path.length + 1).includes('/')) {
|
||||
entries.push(file.slice(path.length + 1));
|
||||
}
|
||||
}
|
||||
|
||||
return [...new Set(entries)];
|
||||
}
|
||||
|
||||
async mkdir(path: string): Promise<void> {
|
||||
this.dirs.add(path);
|
||||
}
|
||||
|
||||
async stat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean; mtimeMs?: number }> {
|
||||
if (this.dirs.has(path)) {
|
||||
return {
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
mtimeMs: Date.now(),
|
||||
};
|
||||
}
|
||||
if (this.files.has(path)) {
|
||||
return {
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
mtimeMs: Date.now(),
|
||||
};
|
||||
}
|
||||
const error = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
throw error;
|
||||
}
|
||||
|
||||
async unlink(path: string): Promise<void> {
|
||||
this.files.delete(path);
|
||||
}
|
||||
|
||||
async rmdir(path: string): Promise<void> {
|
||||
this.dirs.delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
describe('ProjectsManager', () => {
|
||||
let fs: MockFS;
|
||||
let projectsManager: ProjectsManager;
|
||||
|
||||
beforeEach(() => {
|
||||
fs = new MockFS();
|
||||
projectsManager = new ProjectsManager(fs as unknown as import('./JSRuntime').JSRuntimeFS);
|
||||
});
|
||||
|
||||
describe('getProjects', () => {
|
||||
it('should detect any directory as a project', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create any directory
|
||||
await fs.mkdir('/projects/cloned-repo');
|
||||
|
||||
const projects = await projectsManager.getProjects();
|
||||
expect(projects).toHaveLength(1);
|
||||
expect(projects[0].name).toBe('cloned-repo'); // Preserve original directory name
|
||||
expect(projects[0].id).toBe('cloned-repo');
|
||||
});
|
||||
|
||||
it('should detect all directories as projects', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create various directories
|
||||
await fs.mkdir('/projects/my-project');
|
||||
await fs.mkdir('/projects/another-project');
|
||||
await fs.mkdir('/projects/empty-folder');
|
||||
|
||||
const projects = await projectsManager.getProjects();
|
||||
expect(projects).toHaveLength(3);
|
||||
|
||||
const projectNames = projects.map(p => p.name).sort();
|
||||
expect(projectNames).toEqual(['another-project', 'empty-folder', 'my-project']);
|
||||
});
|
||||
|
||||
it('should preserve original project names', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create projects with various naming patterns
|
||||
await fs.mkdir('/projects/my-awesome-project');
|
||||
await fs.mkdir('/projects/my-awesome-project/.git');
|
||||
await fs.writeFile('/projects/my-awesome-project/package.json', '{}');
|
||||
|
||||
await fs.mkdir('/projects/simple-name');
|
||||
await fs.mkdir('/projects/simple-name/.git');
|
||||
await fs.writeFile('/projects/simple-name/package.json', '{}');
|
||||
|
||||
const projects = await projectsManager.getProjects();
|
||||
expect(projects).toHaveLength(2);
|
||||
|
||||
const awesomeProject = projects.find(p => p.id === 'my-awesome-project');
|
||||
const simpleProject = projects.find(p => p.id === 'simple-name');
|
||||
|
||||
expect(awesomeProject?.name).toBe('my-awesome-project');
|
||||
expect(simpleProject?.name).toBe('simple-name');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProject', () => {
|
||||
it('should get any directory as a project', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create any directory
|
||||
await fs.mkdir('/projects/cloned-repo');
|
||||
|
||||
const project = await projectsManager.getProject('cloned-repo');
|
||||
expect(project).not.toBeNull();
|
||||
expect(project?.name).toBe('cloned-repo');
|
||||
expect(project?.id).toBe('cloned-repo');
|
||||
});
|
||||
|
||||
it('should return null for non-existent projects', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
const project = await projectsManager.getProject('non-existent');
|
||||
expect(project).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
+55
-62
@@ -8,23 +8,16 @@ if (typeof window !== 'undefined') {
|
||||
(window as { Buffer?: typeof Buffer }).Buffer = Buffer;
|
||||
}
|
||||
|
||||
// const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git';
|
||||
const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/lovable-blank.git';
|
||||
const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git';
|
||||
// const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/lovable-blank.git';
|
||||
|
||||
export interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
createdAt: Date;
|
||||
lastModified: Date;
|
||||
}
|
||||
|
||||
interface ProjectMetadata {
|
||||
name: string;
|
||||
createdAt: string;
|
||||
lastModified: string;
|
||||
}
|
||||
|
||||
export class ProjectsManager {
|
||||
fs: JSRuntimeFS;
|
||||
dir: string;
|
||||
@@ -48,30 +41,19 @@ export class ProjectsManager {
|
||||
|
||||
await this.fs.mkdir(projectPath);
|
||||
|
||||
const now = new Date();
|
||||
const metadata: ProjectMetadata = {
|
||||
name,
|
||||
createdAt: now.toISOString(),
|
||||
lastModified: now.toISOString(),
|
||||
};
|
||||
|
||||
// Clone the template first
|
||||
await this.cloneTemplate(projectPath);
|
||||
|
||||
// Save project metadata in .git directory to keep it out of source tree
|
||||
const gitDir = `${projectPath}/.git`;
|
||||
await this.fs.writeFile(
|
||||
`${gitDir}/project.json`,
|
||||
JSON.stringify(metadata, null, 2)
|
||||
);
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Return the full project object with dynamically generated properties
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
name: this.formatProjectName(id), // Use formatted directory name
|
||||
path: projectPath,
|
||||
createdAt: now,
|
||||
lastModified: now,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -93,28 +75,26 @@ export class ProjectsManager {
|
||||
|
||||
for (const dir of projectDirs) {
|
||||
const projectPath = `${this.dir}/${dir}`;
|
||||
const projectFile = `${projectPath}/.git/project.json`;
|
||||
|
||||
try {
|
||||
const projectData = await this.fs.readFile(projectFile, 'utf8');
|
||||
const metadata: ProjectMetadata = JSON.parse(projectData);
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
if (stats.isDirectory()) {
|
||||
const modifiedDate = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
const project: Project = {
|
||||
id: dir, // basename of the path
|
||||
name: this.formatProjectName(dir), // Convert directory name to readable format
|
||||
path: projectPath,
|
||||
lastModified: modifiedDate,
|
||||
};
|
||||
|
||||
// Generate dynamic properties
|
||||
const project: Project = {
|
||||
id: dir, // basename of the path
|
||||
name: metadata.name,
|
||||
path: projectPath,
|
||||
createdAt: new Date(metadata.createdAt),
|
||||
lastModified: new Date(metadata.lastModified),
|
||||
};
|
||||
|
||||
projects.push(project);
|
||||
projects.push(project);
|
||||
}
|
||||
} catch {
|
||||
// Skip invalid projects
|
||||
// Skip if we can't stat the directory
|
||||
}
|
||||
}
|
||||
|
||||
return projects.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
||||
return projects.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
@@ -123,18 +103,19 @@ export class ProjectsManager {
|
||||
async getProject(id: string): Promise<Project | null> {
|
||||
try {
|
||||
const projectPath = `${this.dir}/${id}`;
|
||||
const projectFile = `${projectPath}/.git/project.json`;
|
||||
const projectData = await this.fs.readFile(projectFile, 'utf8');
|
||||
const metadata: ProjectMetadata = JSON.parse(projectData);
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
|
||||
// Generate dynamic properties
|
||||
return {
|
||||
id, // basename of the path
|
||||
name: metadata.name,
|
||||
path: projectPath,
|
||||
createdAt: new Date(metadata.createdAt),
|
||||
lastModified: new Date(metadata.lastModified),
|
||||
};
|
||||
if (stats.isDirectory()) {
|
||||
const modifiedDate = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
return {
|
||||
id, // basename of the path
|
||||
name: this.formatProjectName(id), // Convert directory name to readable format
|
||||
path: projectPath,
|
||||
lastModified: modifiedDate,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -163,15 +144,11 @@ export class ProjectsManager {
|
||||
const dir = fullPath.split('/').slice(0, -1).join('/');
|
||||
await this.fs.mkdir(dir);
|
||||
await this.fs.writeFile(fullPath, content);
|
||||
|
||||
// Update last modified
|
||||
await this.updateProjectLastModified(projectId);
|
||||
}
|
||||
|
||||
async deleteFile(projectId: string, filePath: string): Promise<void> {
|
||||
const fullPath = `${this.dir}/${projectId}/${filePath}`;
|
||||
await this.fs.unlink(fullPath);
|
||||
await this.updateProjectLastModified(projectId);
|
||||
}
|
||||
|
||||
async listFiles(projectId: string, dirPath: string = ''): Promise<string[]> {
|
||||
@@ -262,15 +239,31 @@ export class ProjectsManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async updateProjectLastModified(projectId: string): Promise<void> {
|
||||
async getNostrRepoAddress(projectId: string): Promise<string | null> {
|
||||
try {
|
||||
const projectFile = `${this.dir}/${projectId}/.git/project.json`;
|
||||
const projectData = await this.fs.readFile(projectFile, 'utf8');
|
||||
const metadata: ProjectMetadata = JSON.parse(projectData);
|
||||
metadata.lastModified = new Date().toISOString();
|
||||
await this.fs.writeFile(projectFile, JSON.stringify(metadata, null, 2));
|
||||
const projectPath = `${this.dir}/${projectId}`;
|
||||
const config = await git.getConfig({
|
||||
fs: this.fs,
|
||||
dir: projectPath,
|
||||
path: 'nostr.repo',
|
||||
});
|
||||
return config || null;
|
||||
} catch {
|
||||
// Ignore errors updating last modified
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async isNostrEnabled(projectId: string): Promise<boolean> {
|
||||
const naddr = await this.getNostrRepoAddress(projectId);
|
||||
return naddr !== null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private formatProjectName(dirName: string): string {
|
||||
// Return the original directory name without formatting
|
||||
return dirName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { Loader, Plugin } from "esbuild-wasm";
|
||||
|
||||
interface PackageLock {
|
||||
packages: {
|
||||
[key: string]: {
|
||||
name?: string;
|
||||
version: string;
|
||||
} | undefined;
|
||||
};
|
||||
}
|
||||
|
||||
export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
/** Cache of URL redirects */
|
||||
const redirectedURLs = new Map<string, string>();
|
||||
|
||||
/** Retrieve redirected URL from cache */
|
||||
const getRedirectedURL = async (url: string): Promise<string> => {
|
||||
const existing = redirectedURLs.get(url);
|
||||
if (existing) return existing;
|
||||
|
||||
const response = await fetch(url, { method: "HEAD", redirect: "manual" });
|
||||
|
||||
if (response.status === 301 || response.status === 302) {
|
||||
const location = response.headers.get("Location");
|
||||
if (location) {
|
||||
redirectedURLs.set(url, location);
|
||||
return location;
|
||||
}
|
||||
}
|
||||
|
||||
redirectedURLs.set(url, url);
|
||||
return url;
|
||||
};
|
||||
|
||||
return {
|
||||
name: "esm",
|
||||
|
||||
setup(build) {
|
||||
// http(s) imports
|
||||
build.onResolve({ filter: /^https?:\/\// }, async (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "esm",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle bare imports like "react"
|
||||
build.onResolve({ filter: /^[^./].*/ }, (args) => {
|
||||
const packageName = args.path.startsWith("@")
|
||||
? args.path.split("/").slice(0, 2).join("/")
|
||||
: args.path.split("/")[0];
|
||||
|
||||
const packageInfo = packageLock.packages["node_modules/" + packageName];
|
||||
const packagePath = args.path.slice(packageName.length);
|
||||
const version = packageInfo?.version;
|
||||
|
||||
if (!version) return;
|
||||
|
||||
const name = packageInfo.name ?? packageName;
|
||||
const specifier = `${name}@${version}${packagePath}`;
|
||||
|
||||
const url = new URL(`https://esm.sh/*${specifier}`);
|
||||
|
||||
if (target) {
|
||||
url.searchParams.set("target", target);
|
||||
}
|
||||
|
||||
return {
|
||||
path: url.toString(),
|
||||
namespace: "esm",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle relative or absolute imports inside esm.sh modules
|
||||
build.onResolve({ filter: /.*/, namespace: "esm" }, async (args) => {
|
||||
let fullURL: URL;
|
||||
|
||||
try {
|
||||
fullURL = new URL(args.path);
|
||||
} catch {
|
||||
try {
|
||||
// When resolving relative paths, it's important the baseURL is *after* any redirects.
|
||||
// For example, `https://esm.sh/@fontsource/[email protected]` redirects to `https://esm.sh/@fontsource/[email protected]/index.css`
|
||||
// and this changes the outcome of resolving paths like `./font.woff2` and `../font.woff2`
|
||||
const baseURL = args.path.startsWith("./")
|
||||
? await getRedirectedURL(args.importer)
|
||||
: args.importer;
|
||||
|
||||
fullURL = new URL(args.path, baseURL);
|
||||
} catch {
|
||||
return {
|
||||
errors: [{ text: `Could not resolve ${args.path}` }],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
path: fullURL.toString(),
|
||||
namespace: "esm",
|
||||
};
|
||||
});
|
||||
|
||||
// Load ESM modules
|
||||
build.onLoad({ filter: /.*/, namespace: "esm" }, async (args) => {
|
||||
const res = await fetch(args.path);
|
||||
|
||||
if (res.redirected) {
|
||||
redirectedURLs.set(args.path, res.url);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch ${args.path}`);
|
||||
}
|
||||
|
||||
let loader: Loader | undefined;
|
||||
const contentType = res.headers.get("Content-Type")?.split(";")[0];
|
||||
|
||||
if (contentType) {
|
||||
if (contentType === "application/javascript") {
|
||||
loader = "js";
|
||||
} else if (contentType === "text/css") {
|
||||
loader = "css";
|
||||
} else {
|
||||
loader = "text";
|
||||
}
|
||||
}
|
||||
|
||||
const contents = await res.text();
|
||||
|
||||
return {
|
||||
contents,
|
||||
loader,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import path from "path-browserify";
|
||||
|
||||
import type { Loader, Plugin } from "esbuild-wasm";
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
||||
return {
|
||||
name: "fs",
|
||||
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /.*/ }, async (args) => {
|
||||
let resolved: string;
|
||||
|
||||
if (args.path.startsWith("@/")) {
|
||||
resolved = path.join(cwd, args.path.slice(2));
|
||||
} else if (args.kind === "entry-point") {
|
||||
resolved = path.join(cwd, args.path);
|
||||
} else if (args.importer) {
|
||||
resolved = path.join(path.dirname(args.importer), args.path);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
resolved = await tryFileVariants(fs, resolved);
|
||||
} catch {
|
||||
return; // Let other plugins handle this
|
||||
}
|
||||
|
||||
return {
|
||||
path: resolved,
|
||||
namespace: "fs",
|
||||
};
|
||||
});
|
||||
|
||||
build.onLoad(
|
||||
{ filter: /.*/, namespace: "fs" },
|
||||
async (args) => {
|
||||
const ext = path.extname(args.path).slice(1);
|
||||
|
||||
if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return {
|
||||
contents: await fs.readFile(args.path, "utf8"),
|
||||
loader: ext as Loader,
|
||||
};
|
||||
},
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function tryFileVariants(
|
||||
fs: JSRuntimeFS,
|
||||
basePath: string,
|
||||
): Promise<string> {
|
||||
const extensions = [".ts", ".tsx", ".js", ".jsx", ".css"];
|
||||
|
||||
try {
|
||||
await fs.stat(basePath);
|
||||
return basePath;
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
// Try direct file with extensions
|
||||
for (const ext of extensions) {
|
||||
const full = basePath + ext;
|
||||
try {
|
||||
await fs.stat(full);
|
||||
return full;
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Try directory index files
|
||||
for (const ext of extensions) {
|
||||
const indexFile = path.join(basePath, "index" + ext);
|
||||
try {
|
||||
await fs.stat(indexFile);
|
||||
return indexFile;
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("File not found");
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { getEsbuild } from "@/lib/esbuild";
|
||||
|
||||
import { esmPlugin } from "./esmPlugin";
|
||||
import { fsPlugin } from "./fsPlugin";
|
||||
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
export interface BuildProjectOptions {
|
||||
fs: JSRuntimeFS;
|
||||
projectPath: string;
|
||||
domParser: DOMParser;
|
||||
target?: string;
|
||||
}
|
||||
|
||||
export async function buildProject(
|
||||
options: BuildProjectOptions,
|
||||
): Promise<Record<string, Uint8Array>> {
|
||||
const esbuild = await getEsbuild();
|
||||
|
||||
const { fs, projectPath, domParser, target } = options;
|
||||
|
||||
const indexHtmlText = await fs.readFile(
|
||||
`${projectPath}/index.html`,
|
||||
"utf8",
|
||||
);
|
||||
const packageLockText = await fs.readFile(
|
||||
`${projectPath}/package-lock.json`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const doc = domParser.parseFromString(indexHtmlText, "text/html");
|
||||
|
||||
const results = await esbuild.build({
|
||||
stdin: {
|
||||
contents: `
|
||||
import "@/main.tsx";
|
||||
import tailwindConfig from "@/../tailwind.config.ts";
|
||||
import "https://esm.sh/tailwindcss-cdn@3";
|
||||
tailwind.config = tailwindConfig;
|
||||
`,
|
||||
loader: "tsx",
|
||||
},
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: "esm",
|
||||
target: target ?? "esnext",
|
||||
outdir: "/",
|
||||
jsx: "automatic",
|
||||
plugins: [
|
||||
fsPlugin(fs, `${projectPath}/src`),
|
||||
esmPlugin(JSON.parse(packageLockText), target),
|
||||
],
|
||||
});
|
||||
|
||||
const dist: Record<string, Uint8Array> = {};
|
||||
|
||||
for (const file of results.outputFiles) {
|
||||
const relativePath = file.path.replace(/^\//, "");
|
||||
if (relativePath === "stdin.js") {
|
||||
dist["main.js"] = file.contents;
|
||||
} else if (relativePath === "stdin.css") {
|
||||
dist["main.css"] = file.contents;
|
||||
} else {
|
||||
dist[relativePath] = file.contents;
|
||||
}
|
||||
}
|
||||
|
||||
// Update index.html with proper script and link tags
|
||||
updateIndexHtml(doc);
|
||||
|
||||
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
|
||||
dist["index.html"] = new TextEncoder().encode(updatedHtml);
|
||||
|
||||
return dist;
|
||||
}
|
||||
|
||||
function updateIndexHtml(doc: Document): void {
|
||||
const entrypoint = doc.querySelector('script[src="/src/main.tsx"]');
|
||||
|
||||
if (!entrypoint) {
|
||||
throw new Error("No entrypoint script found in index.html");
|
||||
}
|
||||
|
||||
entrypoint.setAttribute("src", "/main.js");
|
||||
|
||||
const style = doc.createElement("link");
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
style.setAttribute("href", "/main.css");
|
||||
doc.head.appendChild(style);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type _ESBuild from "esbuild-wasm";
|
||||
|
||||
type ESBuild = typeof _ESBuild;
|
||||
|
||||
let promise: Promise<ESBuild> | undefined;
|
||||
|
||||
export function getEsbuild(): Promise<ESBuild> {
|
||||
if (!promise) {
|
||||
promise = loadEsbuild();
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function loadEsbuild(): Promise<ESBuild> {
|
||||
const { default: esbuild } = await import("esbuild-wasm");
|
||||
|
||||
await esbuild.initialize({
|
||||
worker: false,
|
||||
wasmURL: "https://esm.sh/[email protected]/esbuild.wasm",
|
||||
});
|
||||
|
||||
return esbuild;
|
||||
}
|
||||
+49
-68
@@ -4,8 +4,11 @@ import { type Project } from '@/lib/ProjectsManager';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useOnboarding } from '@/hooks/useOnboarding';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useRepos } from '@/hooks/useRepos';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { OnboardingDialog } from '@/components/onboarding';
|
||||
import { RepoCard } from '@/components/RepoCard';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
@@ -19,12 +22,13 @@ import { cn } from '@/lib/utils';
|
||||
export default function Index() {
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const isMobile = useIsMobile();
|
||||
const { user: _user } = useCurrentUser();
|
||||
const { data: repos = [], isLoading, error, refetch } = useRepos();
|
||||
const {
|
||||
hasCompletedOnboarding,
|
||||
currentStep,
|
||||
@@ -55,8 +59,6 @@ export default function Index() {
|
||||
setProjects(projectList);
|
||||
} catch (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [projectsManager]);
|
||||
|
||||
@@ -87,6 +89,8 @@ export default function Index() {
|
||||
setIsCreating(true);
|
||||
try {
|
||||
const project = await projectsManager.createProject(prompt.trim());
|
||||
// Refresh repos after creating a new project
|
||||
refetch();
|
||||
navigate(`/project/${project.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to create project:', error);
|
||||
@@ -95,8 +99,9 @@ export default function Index() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleProjectClick = (projectId: string) => {
|
||||
navigate(`/project/${projectId}`);
|
||||
const handleRepoRefresh = () => {
|
||||
refetch();
|
||||
loadProjects();
|
||||
};
|
||||
|
||||
const handleProjectSelect = (project: Project | null) => {
|
||||
@@ -128,7 +133,7 @@ export default function Index() {
|
||||
<div className="w-8" /> {/* Spacer */}
|
||||
</header>
|
||||
|
||||
{/* Mobile Sidebar Overlay - only show if user has projects */}
|
||||
{/* Mobile Sidebar Overlay - only show if user has local projects */}
|
||||
{projects.length > 0 && isSidebarVisible && (
|
||||
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
|
||||
{/* Backdrop - only covers the area not occupied by the sidebar */}
|
||||
@@ -223,7 +228,7 @@ export default function Index() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-xl md:text-2xl font-semibold mb-4 md:mb-6">Your Projects</h2>
|
||||
<h2 className="text-xl md:text-2xl font-semibold mb-4 md:mb-6">Your Repositories</h2>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
@@ -236,42 +241,29 @@ export default function Index() {
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : projects.length === 0 ? (
|
||||
) : error ? (
|
||||
<Card className="border-destructive/20">
|
||||
<CardContent className="py-6 text-center">
|
||||
<p className="text-destructive">Failed to load repositories</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : repos.length === 0 ? (
|
||||
<Card className="bg-gradient-to-br from-muted/50 to-muted/20 border-dashed border-2 border-muted-foreground/20">
|
||||
<CardContent className="text-center py-8 md:py-12">
|
||||
<div className="flex items-center justify-center gap-2 mb-4">
|
||||
<Folder className="h-10 w-10 md:h-12 md:w-12 text-muted-foreground" />
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm md:text-base">No projects yet. Create your first project above!</p>
|
||||
<p className="text-muted-foreground text-sm md:text-base">No repositories yet. Create your first project above!</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{projects.map((project) => (
|
||||
<Card
|
||||
key={project.id}
|
||||
className="cursor-pointer hover:shadow-xl hover:shadow-primary/10 transition-all duration-300 focus-ring bg-gradient-to-br from-card to-card/80 border-primary/10 hover:border-primary/20 hover:scale-[1.02]"
|
||||
onClick={() => handleProjectClick(project.id)}
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleProjectClick(project.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-base md:text-lg">{project.name}</CardTitle>
|
||||
<CardDescription className="text-sm">
|
||||
Created {project.createdAt.toLocaleDateString()}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<p className="text-xs md:text-sm text-muted-foreground">
|
||||
Last modified {project.lastModified.toLocaleDateString()}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{repos.map((repo) => (
|
||||
<RepoCard
|
||||
key={repo.id}
|
||||
repo={repo}
|
||||
onRepoCloned={handleRepoRefresh}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
@@ -290,6 +282,7 @@ export default function Index() {
|
||||
onProjectCreated={(projectId) => {
|
||||
console.log('Project created during onboarding:', projectId);
|
||||
setStoredPrompt('');
|
||||
handleRepoRefresh();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -310,24 +303,25 @@ export default function Index() {
|
||||
// Handle project creation during onboarding
|
||||
console.log('Project created during onboarding:', projectId);
|
||||
setStoredPrompt(''); // Clear stored prompt after project creation
|
||||
handleRepoRefresh();
|
||||
}}
|
||||
/>
|
||||
<div className="h-screen flex bg-background">
|
||||
{/* Fixed Sidebar - only show if user has created projects */}
|
||||
<div className="min-h-screen flex bg-background">
|
||||
{/* Fixed Sidebar - only show if user has created local projects */}
|
||||
{projects.length > 0 && (
|
||||
<div className={cn("w-80 border-r bg-sidebar transition-all duration-300", isSidebarVisible ? "block" : "hidden")}>
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={handleProjectSelect}
|
||||
className="h-full"
|
||||
className="h-screen sticky top-0"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-background">
|
||||
<div className="min-h-full bg-gradient-to-br from-primary/5 to-accent/5">
|
||||
{/* Header - only show toggle button if user has projects */}
|
||||
<div className="flex-1 flex flex-col bg-background">
|
||||
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5">
|
||||
{/* Header - only show toggle button if user has local projects */}
|
||||
{!isSidebarVisible && projects.length > 0 && (
|
||||
<header className="border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur px-4 py-3 flex items-center">
|
||||
<Button
|
||||
@@ -408,7 +402,7 @@ export default function Index() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-xl md:text-2xl font-semibold mb-4 md:mb-6">Your Projects</h2>
|
||||
<h2 className="text-xl md:text-2xl font-semibold mb-4 md:mb-6">Your Repositories</h2>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
@@ -421,42 +415,29 @@ export default function Index() {
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : projects.length === 0 ? (
|
||||
) : error ? (
|
||||
<Card className="border-destructive/20">
|
||||
<CardContent className="py-6 text-center">
|
||||
<p className="text-destructive">Failed to load repositories</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : repos.length === 0 ? (
|
||||
<Card className="bg-gradient-to-br from-muted/50 to-muted/20 border-dashed border-2 border-muted-foreground/20">
|
||||
<CardContent className="text-center py-8 md:py-12">
|
||||
<div className="flex items-center justify-center gap-2 mb-4">
|
||||
<Folder className="h-10 w-10 md:h-12 md:w-12 text-muted-foreground" />
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm md:text-base">No projects yet. Create your first project above!</p>
|
||||
<p className="text-muted-foreground text-sm md:text-base">No repositories yet. Create your first project above!</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{projects.map((project) => (
|
||||
<Card
|
||||
key={project.id}
|
||||
className="cursor-pointer hover:shadow-xl hover:shadow-primary/10 transition-all duration-300 focus-ring bg-gradient-to-br from-card to-card/80 border-primary/10 hover:border-primary/20 hover:scale-[1.02]"
|
||||
onClick={() => handleProjectClick(project.id)}
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleProjectClick(project.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-base md:text-lg">{project.name}</CardTitle>
|
||||
<CardDescription className="text-sm">
|
||||
Created {project.createdAt.toLocaleDateString()}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<p className="text-xs md:text-sm text-muted-foreground">
|
||||
Last modified {project.lastModified.toLocaleDateString()}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{repos.map((repo) => (
|
||||
<RepoCard
|
||||
key={repo.id}
|
||||
repo={repo}
|
||||
onRepoCloned={handleRepoRefresh}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -17,6 +17,16 @@ export function ProjectView() {
|
||||
const [project, setProject] = useState<Project | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview');
|
||||
|
||||
const handleBuildComplete = useCallback((projectId: string) => {
|
||||
setActiveTab('preview');
|
||||
// Dispatch custom event to notify PreviewPane that build is complete
|
||||
const event = new CustomEvent('buildComplete', {
|
||||
detail: { projectId }
|
||||
});
|
||||
window.dispatchEvent(event);
|
||||
console.log('Dispatched buildComplete event for project:', projectId);
|
||||
}, []);
|
||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||
const projectsManager = useProjectsManager();
|
||||
const navigate = useNavigate();
|
||||
@@ -117,7 +127,11 @@ export function ProjectView() {
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{mobileView === 'chat' && (
|
||||
<ChatPane projectId={project.id} projectName={project.name} />
|
||||
<ChatPane
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
onBuildComplete={handleBuildComplete}
|
||||
/>
|
||||
)}
|
||||
{(mobileView === 'preview' || mobileView === 'code') && (
|
||||
<PreviewPane
|
||||
@@ -221,7 +235,11 @@ export function ProjectView() {
|
||||
|
||||
{/* Chat Content */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<ChatPane projectId={project.id} projectName={project.name} />
|
||||
<ChatPane
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
onBuildComplete={handleBuildComplete}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
|
||||
@@ -8,10 +8,6 @@ export default defineConfig(() => ({
|
||||
server: {
|
||||
host: "::",
|
||||
port: 8080,
|
||||
headers: {
|
||||
'Cross-Origin-Embedder-Policy': 'require-corp',
|
||||
'Cross-Origin-Opener-Policy': 'same-origin',
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
react(),
|
||||
|
||||
Reference in new issue
Block a user