feat: update project dashboard UI for Vibn architecture

- project layout.tsx: replace Firebase Admin SDK with direct Postgres
  query to resolve project name; removes firebase/admin dependency
- overview page: full rewrite — fetches from /api/projects/:id, shows
  Gitea repo + last commit, branch, clone URLs; deployment status badge;
  open PRs and issues from contextSnapshot; recent commits list;
  resources section; Open IDE button; context freshness timestamp
- projects list page: cards now show Gitea repo + last commit inline,
  deploy status dot, IDE quick-link; updated empty state copy to reflect
  auto-provisioning; removed Firebase imports

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-02-18 14:57:16 -08:00
parent 373bcee8c1
commit 8bf69e1ae2
3 changed files with 661 additions and 570 deletions

View File

@@ -1,18 +1,20 @@
import { AppShell } from "@/components/layout/app-shell";
import { getAdminDb } from "@/lib/firebase/admin";
import { query } from "@/lib/db-postgres";
async function getProjectName(projectId: string): Promise<string> {
try {
const adminDb = getAdminDb();
const projectDoc = await adminDb.collection('projects').doc(projectId).get();
if (projectDoc.exists) {
const data = projectDoc.data();
return data?.productName || data?.name || "Product";
const rows = await query<{ data: any }>(
`SELECT data FROM fs_projects WHERE id = $1 LIMIT 1`,
[projectId]
);
if (rows.length > 0) {
const data = rows[0].data;
return data?.productName || data?.name || "Project";
}
} catch (error) {
console.error("Error fetching project name:", error);
}
return "Product";
return "Project";
}
export default async function ProjectLayout({
@@ -31,4 +33,3 @@ export default async function ProjectLayout({
</AppShell>
);
}

View File

@@ -1,172 +1,161 @@
"use client";
import { useEffect, useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Activity, Clock, DollarSign, FolderOpen, Settings, Loader2, Github, MessageSquare, CheckCircle2, AlertCircle, Link as LinkIcon } from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { db, auth } from "@/lib/firebase/config";
import { doc, getDoc, collection, query, where, getDocs } from "firebase/firestore";
import { useSession } from "next-auth/react";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
GitBranch,
GitCommit,
GitPullRequest,
CircleDot,
ExternalLink,
Terminal,
Rocket,
Database,
Loader2,
CheckCircle2,
XCircle,
Clock,
AlertCircle,
Code2,
RefreshCw,
} from "lucide-react";
import Link from "next/link";
import { toast } from "sonner";
interface ContextSnapshot {
lastCommit?: {
sha: string;
message: string;
author?: string;
timestamp?: string;
url?: string;
};
currentBranch?: string;
recentCommits?: { sha: string; message: string; author?: string; timestamp?: string }[];
openPRs?: { number: number; title: string; url: string; from: string; into: string }[];
openIssues?: { number: number; title: string; url: string; labels?: string[] }[];
lastDeployment?: {
status: string;
url?: string;
timestamp?: string;
deploymentUuid?: string;
};
updatedAt?: string;
}
interface Project {
id: string;
name: string;
productName: string;
productVision?: string;
workspacePath?: string;
workspaceName?: string;
githubRepo?: string;
githubRepoUrl?: string;
chatgptUrl?: string;
projectType: 'scratch' | 'existing';
status: string;
createdAt: any;
slug?: string;
workspace?: string;
status?: string;
currentPhase?: string;
projectType?: string;
// Gitea
giteaRepo?: string;
giteaRepoUrl?: string;
giteaCloneUrl?: string;
giteaSshUrl?: string;
giteaWebhookId?: number;
giteaError?: string;
// Coolify
coolifyProjectUuid?: string;
coolifyAppUuid?: string;
coolifyDbUuid?: string;
deploymentUrl?: string;
// Theia
theiaWorkspaceUrl?: string;
// Context
contextSnapshot?: ContextSnapshot;
stats?: { sessions: number; costs: number };
createdAt?: string;
updatedAt?: string;
}
interface Stats {
totalSessions: number;
totalCost: number;
totalTokens: number;
totalDuration: number;
function timeAgo(ts?: string): string {
if (!ts) return "—";
const d = new Date(ts);
if (isNaN(d.getTime())) return "—";
const diff = (Date.now() - d.getTime()) / 1000;
if (diff < 60) return "just now";
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
return `${Math.floor(diff / 86400)}d ago`;
}
interface UnassociatedSession {
id: string;
workspacePath: string;
workspaceName: string;
count: number;
function DeployBadge({ status }: { status?: string }) {
if (!status) return <Badge variant="secondary">No deployments</Badge>;
const map: Record<string, { label: string; icon: React.ElementType; className: string }> = {
finished: { label: "Deployed", icon: CheckCircle2, className: "bg-green-500/10 text-green-600 border-green-500/20" },
in_progress: { label: "Deploying", icon: Loader2, className: "bg-blue-500/10 text-blue-600 border-blue-500/20" },
queued: { label: "Queued", icon: Clock, className: "bg-yellow-500/10 text-yellow-600 border-yellow-500/20" },
failed: { label: "Failed", icon: XCircle, className: "bg-red-500/10 text-red-600 border-red-500/20" },
cancelled: { label: "Cancelled", icon: XCircle, className: "bg-gray-500/10 text-gray-500 border-gray-500/20" },
};
const cfg = map[status] ?? { label: status, icon: AlertCircle, className: "bg-gray-500/10 text-gray-500" };
const Icon = cfg.icon;
return (
<span className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium border ${cfg.className}`}>
<Icon className="h-3 w-3" />
{cfg.label}
</span>
);
}
export default function ProjectOverviewPage() {
const params = useParams();
const projectId = params.projectId as string;
const workspace = params.workspace as string;
const { status: authStatus } = useSession();
const [project, setProject] = useState<Project | null>(null);
const [stats, setStats] = useState<Stats | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [unassociatedSessions, setUnassociatedSessions] = useState<number>(0);
const [linkingSessions, setLinkingSessions] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const fetchProject = async () => {
try {
const res = await fetch(`/api/projects/${projectId}`);
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Failed to load project");
}
const data = await res.json();
setProject(data.project);
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : "Unknown error");
} finally {
setLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
const fetchProjectData = async () => {
try {
const user = auth.currentUser;
if (!user) {
setError('Not authenticated');
setLoading(false);
return;
}
if (authStatus === "authenticated") fetchProject();
else if (authStatus === "unauthenticated") setLoading(false);
}, [authStatus, projectId]);
// Fetch project details
const projectDoc = await getDoc(doc(db, 'projects', projectId));
if (!projectDoc.exists()) {
setError('Project not found');
setLoading(false);
return;
}
const projectData = projectDoc.data() as Project;
setProject({ ...projectData, id: projectDoc.id });
// Fetch stats
const statsResponse = await fetch(`/api/stats?projectId=${projectId}`);
if (statsResponse.ok) {
const statsData = await statsResponse.json();
setStats(statsData);
}
// If project has a workspace path, check for unassociated sessions
if (projectData.workspacePath) {
try {
const sessionsRef = collection(db, 'sessions');
const unassociatedQuery = query(
sessionsRef,
where('userId', '==', user.uid),
where('workspacePath', '==', projectData.workspacePath),
where('needsProjectAssociation', '==', true)
);
const unassociatedSnap = await getDocs(unassociatedQuery);
setUnassociatedSessions(unassociatedSnap.size);
} catch (err) {
// Index might not be ready yet, silently fail
console.log('Could not check for unassociated sessions:', err);
}
}
} catch (err: any) {
console.error('Error fetching project:', err);
setError(err.message);
} finally {
setLoading(false);
}
};
const unsubscribe = auth.onAuthStateChanged((user) => {
if (user) {
fetchProjectData();
} else {
setError('Not authenticated');
setLoading(false);
}
});
return () => unsubscribe();
}, [projectId]);
const handleLinkSessions = async () => {
if (!project?.workspacePath) return;
setLinkingSessions(true);
try {
const user = auth.currentUser;
if (!user) {
toast.error('You must be signed in');
return;
}
const token = await user.getIdToken();
const response = await fetch('/api/sessions/associate-project', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
projectId,
workspacePath: project.workspacePath,
workspaceName: project.workspaceName,
}),
});
if (response.ok) {
const data = await response.json();
toast.success(`✅ Linked ${unassociatedSessions} sessions to this project!`);
setUnassociatedSessions(0);
// Refresh stats
const statsResponse = await fetch(`/api/stats?projectId=${projectId}`);
if (statsResponse.ok) {
const statsData = await statsResponse.json();
setStats(statsData);
}
} else {
toast.error('Failed to link sessions');
}
} catch (error) {
console.error('Error linking sessions:', error);
toast.error('An error occurred');
} finally {
setLinkingSessions(false);
}
const handleRefresh = () => {
setRefreshing(true);
fetchProject();
};
if (loading) {
return (
<div className="flex h-full items-center justify-center">
<div className="flex items-center justify-center py-32">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
@@ -174,303 +163,323 @@ export default function ProjectOverviewPage() {
if (error || !project) {
return (
<div className="flex h-full flex-col items-center justify-center gap-4">
<div className="rounded-full bg-red-500/10 p-6">
<Activity className="h-12 w-12 text-red-500" />
</div>
<h2 className="text-2xl font-bold">Error Loading Project</h2>
<p className="text-muted-foreground">{error || 'Project not found'}</p>
<Link href={`/${workspace}/projects`}>
<Button>Back to Projects</Button>
</Link>
<div className="container mx-auto py-8 px-6 max-w-5xl">
<Card className="border-red-500/30 bg-red-500/5">
<CardContent className="py-8 text-center">
<p className="text-sm text-red-600">{error ?? "Project not found"}</p>
</CardContent>
</Card>
</div>
);
}
const snap = project.contextSnapshot;
const gitea_url = process.env.NEXT_PUBLIC_GITEA_URL ?? "https://git.vibnai.com";
return (
<div className="flex h-full flex-col overflow-auto">
{/* Header */}
<div className="border-b px-6 py-4">
<div className="flex items-start justify-between">
<div>
<div className="flex items-center gap-3 mb-2">
<div className="text-4xl">📦</div>
<div>
<h1 className="text-3xl font-bold">{project.productName}</h1>
<p className="text-sm text-muted-foreground">{project.name}</p>
</div>
</div>
{project.productVision && (
<p className="text-muted-foreground mt-2 max-w-2xl">{project.productVision}</p>
)}
{project.workspacePath && (
<div className="flex items-center gap-2 mt-3 text-sm text-muted-foreground">
<FolderOpen className="h-4 w-4" />
<code className="font-mono">{project.workspacePath}</code>
</div>
<div className="container mx-auto py-8 px-6 max-w-5xl space-y-6">
{/* ── Header ── */}
<div className="flex items-start justify-between">
<div>
<h1 className="text-2xl font-bold">{project.productName}</h1>
{project.productVision && (
<p className="text-muted-foreground text-sm mt-1 max-w-xl">{project.productVision}</p>
)}
<div className="flex items-center gap-2 mt-2">
<Badge variant={project.status === "active" ? "default" : "secondary"}>
{project.status ?? "active"}
</Badge>
{project.currentPhase && (
<Badge variant="outline">{project.currentPhase}</Badge>
)}
</div>
<Link href={`/${workspace}/project/${projectId}/settings`}>
<Button variant="outline" size="sm">
<Settings className="h-4 w-4 mr-2" />
Settings
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={handleRefresh} disabled={refreshing}>
<RefreshCw className={`h-4 w-4 mr-1.5 ${refreshing ? "animate-spin" : ""}`} />
Refresh
</Button>
{project.theiaWorkspaceUrl ? (
<Button size="sm" asChild>
<a href={project.theiaWorkspaceUrl} target="_blank" rel="noopener noreferrer">
<Terminal className="h-4 w-4 mr-1.5" />
Open IDE
</a>
</Button>
</Link>
) : (
<Button size="sm" variant="outline" disabled>
<Terminal className="h-4 w-4 mr-1.5" />
IDE provisioning
</Button>
)}
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-auto p-6">
<div className="mx-auto max-w-6xl space-y-6">
{/* ── Quick Stats ── */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{[
{ label: "Sessions", value: project.stats?.sessions ?? 0 },
{ label: "AI Cost", value: `$${(project.stats?.costs ?? 0).toFixed(2)}` },
{ label: "Open PRs", value: snap?.openPRs?.length ?? 0 },
{ label: "Open Issues", value: snap?.openIssues?.length ?? 0 },
].map(({ label, value }) => (
<Card key={label}>
<CardContent className="pt-5 pb-4">
<p className="text-2xl font-bold">{value}</p>
<p className="text-xs text-muted-foreground mt-0.5">{label}</p>
</CardContent>
</Card>
))}
</div>
{/* 🔗 Link Unassociated Sessions - Show this FIRST if available */}
{unassociatedSessions > 0 && (
<Card className="border-blue-500/50 bg-blue-50/50 dark:bg-blue-950/20">
<CardHeader>
<div className="flex items-start justify-between">
<div>
<CardTitle className="flex items-center gap-2">
<LinkIcon className="h-5 w-5 text-blue-600" />
Sessions Detected!
</CardTitle>
<CardDescription className="mt-2">
We found <strong>{unassociatedSessions} coding session{unassociatedSessions > 1 ? 's' : ''}</strong> from this workspace that {unassociatedSessions > 1 ? 'aren\'t' : 'isn\'t'} linked to any project yet.
</CardDescription>
<div className="grid md:grid-cols-2 gap-6">
{/* ── Code / Gitea ── */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-semibold flex items-center gap-2">
<Code2 className="h-4 w-4" />
Code Repository
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{project.giteaRepo ? (
<>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 text-sm font-mono text-muted-foreground">
<GitBranch className="h-3.5 w-3.5" />
{snap?.currentBranch ?? "main"}
</div>
<Button
onClick={handleLinkSessions}
disabled={linkingSessions}
className="bg-blue-600 hover:bg-blue-700"
<a
href={project.giteaRepoUrl ?? `${gitea_url}/${project.giteaRepo}`}
target="_blank"
rel="noopener noreferrer"
className="text-xs text-primary flex items-center gap-1 hover:underline"
>
{linkingSessions ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Linking...
</>
) : (
<>
<LinkIcon className="mr-2 h-4 w-4" />
Link {unassociatedSessions} Session{unassociatedSessions > 1 ? 's' : ''}
</>
)}
</Button>
{project.giteaRepo}
<ExternalLink className="h-3 w-3" />
</a>
</div>
</CardHeader>
<CardContent>
<div className="rounded-lg bg-white dark:bg-gray-900 p-4">
<p className="text-sm text-muted-foreground">
<strong>Workspace:</strong> <code className="font-mono text-xs">{project.workspacePath}</code>
</p>
<p className="text-sm text-muted-foreground mt-2">
Linking these sessions will add their costs, time, and activity to this project's stats.
</p>
{snap?.lastCommit ? (
<div className="rounded-md border bg-muted/30 p-3 space-y-1">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<GitCommit className="h-3.5 w-3.5" />
<span className="font-mono">{snap.lastCommit.sha.slice(0, 8)}</span>
<span>·</span>
<span>{timeAgo(snap.lastCommit.timestamp)}</span>
{snap.lastCommit.author && <span>· {snap.lastCommit.author}</span>}
</div>
<p className="text-sm font-medium line-clamp-1">{snap.lastCommit.message}</p>
</div>
) : (
<p className="text-xs text-muted-foreground">No commits yet push to get started</p>
)}
<div className="text-xs text-muted-foreground space-y-1 pt-1 border-t">
<p className="font-medium text-foreground">Clone</p>
<p className="font-mono break-all">{project.giteaCloneUrl}</p>
{project.giteaSshUrl && (
<p className="font-mono break-all">{project.giteaSshUrl}</p>
)}
</div>
</CardContent>
</Card>
)}
</>
) : (
<div className="text-center py-4">
<p className="text-sm text-muted-foreground">
{project.giteaError
? `Repo provisioning failed: ${project.giteaError}`
: "No repository linked"}
</p>
</div>
)}
</CardContent>
</Card>
{/* Stats Cards - Only show if there are sessions */}
{stats && stats.totalSessions > 0 && (
<div className="grid gap-4 md:grid-cols-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<Activity className="h-4 w-4" />
Total Sessions
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{stats.totalSessions}</div>
</CardContent>
</Card>
{/* ── Deployment ── */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-semibold flex items-center gap-2">
<Rocket className="h-4 w-4" />
Deployment
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{snap?.lastDeployment ? (
<>
<div className="flex items-center justify-between">
<DeployBadge status={snap.lastDeployment.status} />
<span className="text-xs text-muted-foreground">{timeAgo(snap.lastDeployment.timestamp)}</span>
</div>
{snap.lastDeployment.url && (
<a
href={snap.lastDeployment.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 text-sm text-primary hover:underline"
>
<ExternalLink className="h-3.5 w-3.5" />
{snap.lastDeployment.url}
</a>
)}
</>
) : (
<div className="text-center py-4 space-y-3">
<p className="text-sm text-muted-foreground">No deployments yet</p>
<Button size="sm" variant="outline" asChild>
<Link href={`/${workspace}/project/${projectId}/deployment`}>
Set up deployment
</Link>
</Button>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<Clock className="h-4 w-4" />
Total Time
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{stats.totalDuration}m</div>
</CardContent>
</Card>
{/* ── Open PRs ── */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-semibold flex items-center gap-2">
<GitPullRequest className="h-4 w-4" />
Pull Requests
{(snap?.openPRs?.length ?? 0) > 0 && (
<Badge variant="secondary" className="ml-auto">{snap!.openPRs!.length} open</Badge>
)}
</CardTitle>
</CardHeader>
<CardContent>
{snap?.openPRs?.length ? (
<ul className="space-y-2">
{snap.openPRs.map(pr => (
<li key={pr.number}>
<a
href={pr.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-start gap-2 text-sm hover:bg-accent rounded-md p-2 -mx-2 transition-colors"
>
<span className="text-muted-foreground font-mono text-xs mt-0.5">#{pr.number}</span>
<div className="flex-1 min-w-0">
<p className="font-medium line-clamp-1">{pr.title}</p>
<p className="text-xs text-muted-foreground">{pr.from} {pr.into}</p>
</div>
<ExternalLink className="h-3.5 w-3.5 text-muted-foreground shrink-0 mt-0.5" />
</a>
</li>
))}
</ul>
) : (
<p className="text-sm text-muted-foreground text-center py-4">No open pull requests</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<DollarSign className="h-4 w-4" />
Total Cost
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">${stats.totalCost.toFixed(2)}</div>
</CardContent>
</Card>
{/* ── Open Issues ── */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-semibold flex items-center gap-2">
<CircleDot className="h-4 w-4" />
Issues
{(snap?.openIssues?.length ?? 0) > 0 && (
<Badge variant="secondary" className="ml-auto">{snap!.openIssues!.length} open</Badge>
)}
</CardTitle>
</CardHeader>
<CardContent>
{snap?.openIssues?.length ? (
<ul className="space-y-2">
{snap.openIssues.map(issue => (
<li key={issue.number}>
<a
href={issue.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-start gap-2 text-sm hover:bg-accent rounded-md p-2 -mx-2 transition-colors"
>
<span className="text-muted-foreground font-mono text-xs mt-0.5">#{issue.number}</span>
<div className="flex-1 min-w-0">
<p className="font-medium line-clamp-1">{issue.title}</p>
{issue.labels?.length ? (
<div className="flex gap-1 flex-wrap mt-0.5">
{issue.labels.map(l => (
<span key={l} className="text-[10px] px-1.5 py-0.5 bg-muted rounded-full">{l}</span>
))}
</div>
) : null}
</div>
<ExternalLink className="h-3.5 w-3.5 text-muted-foreground shrink-0 mt-0.5" />
</a>
</li>
))}
</ul>
) : (
<p className="text-sm text-muted-foreground text-center py-4">No open issues</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<Activity className="h-4 w-4" />
Tokens Used
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{stats.totalTokens.toLocaleString()}</div>
</CardContent>
</Card>
</div>
{/* ── Recent Commits ── */}
{snap?.recentCommits && snap.recentCommits.length > 1 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-semibold flex items-center gap-2">
<GitCommit className="h-4 w-4" />
Recent Commits
</CardTitle>
</CardHeader>
<CardContent>
<ul className="space-y-2">
{snap.recentCommits.map((c, i) => (
<li key={i} className="flex items-center gap-3 text-sm py-1.5 border-b last:border-0">
<span className="font-mono text-xs text-muted-foreground w-16 shrink-0">{c.sha.slice(0, 8)}</span>
<span className="flex-1 line-clamp-1">{c.message}</span>
<span className="text-xs text-muted-foreground shrink-0">{c.author ?? ""}</span>
<span className="text-xs text-muted-foreground shrink-0 w-16 text-right">{timeAgo(c.timestamp)}</span>
</li>
))}
</ul>
</CardContent>
</Card>
)}
{/* ── Resources ── */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-semibold flex items-center gap-2">
<Database className="h-4 w-4" />
Resources
</CardTitle>
<CardDescription className="text-xs">Databases and services linked to this project</CardDescription>
</CardHeader>
<CardContent>
{project.coolifyDbUuid ? (
<div className="flex items-center gap-2 text-sm">
<CheckCircle2 className="h-4 w-4 text-green-500" />
<span>Database provisioned</span>
<Badge variant="outline" className="text-xs ml-auto">{project.coolifyDbUuid}</Badge>
</div>
) : (
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">No databases provisioned yet</p>
<Button size="sm" variant="outline">
<Database className="h-3.5 w-3.5 mr-1.5" />
Add Database
</Button>
</div>
)}
</CardContent>
</Card>
{/* Quick Actions */}
<div className="grid gap-4 md:grid-cols-3">
<Link href={`/${workspace}/project/${projectId}/sessions`}>
<Card className="hover:border-primary transition-all cursor-pointer h-full">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Activity className="h-5 w-5" />
Sessions
</CardTitle>
<CardDescription>View all coding sessions</CardDescription>
</CardHeader>
</Card>
</Link>
{/* ── Context snapshot freshness ── */}
{snap?.updatedAt && (
<p className="text-xs text-muted-foreground text-right">
Context updated {timeAgo(snap.updatedAt)} via webhooks
</p>
)}
<Link href={`/${workspace}/project/${projectId}/analytics`}>
<Card className="hover:border-primary transition-all cursor-pointer h-full">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<DollarSign className="h-5 w-5" />
Analytics
</CardTitle>
<CardDescription>Cost & usage analytics</CardDescription>
</CardHeader>
</Card>
</Link>
<Link href={`/${workspace}/connections`}>
<Card className="hover:border-primary transition-all cursor-pointer h-full">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Settings className="h-5 w-5" />
Connections
</CardTitle>
<CardDescription>Manage integrations</CardDescription>
</CardHeader>
</Card>
</Link>
</div>
{/* Getting Started - Show if no sessions and no unassociated */}
{stats && stats.totalSessions === 0 && unassociatedSessions === 0 && (
<Card className="border-dashed">
<CardContent className="py-12">
<div className="text-center space-y-4">
{/* Show different icons based on project type */}
<div className="rounded-full bg-primary/10 p-6 mx-auto w-fit">
{project.workspacePath && <FolderOpen className="h-12 w-12 text-primary" />}
{project.githubRepo && <Github className="h-12 w-12 text-primary" />}
{project.chatgptUrl && <MessageSquare className="h-12 w-12 text-primary" />}
{!project.workspacePath && !project.githubRepo && !project.chatgptUrl && (
<Activity className="h-12 w-12 text-primary" />
)}
</div>
<div>
{/* Dynamic title based on project type */}
{project.workspacePath && (
<>
<h3 className="text-2xl font-bold mb-2">Start Coding in This Workspace!</h3>
<p className="text-muted-foreground max-w-md mx-auto">
Open <code className="bg-muted px-2 py-1 rounded">{project.workspacePath}</code> in Cursor and start coding.
Sessions from this workspace will automatically appear here.
</p>
</>
)}
{project.githubRepo && (
<>
<h3 className="text-2xl font-bold mb-2">Clone & Start Coding!</h3>
<p className="text-muted-foreground max-w-md mx-auto">
Clone your repository and open it in Cursor to start tracking your development.
</p>
<div className="mt-4">
<a
href={project.githubRepoUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 text-sm text-blue-600 hover:underline"
>
<Github className="h-4 w-4" />
View on GitHub
</a>
</div>
</>
)}
{project.chatgptUrl && (
<>
<h3 className="text-2xl font-bold mb-2">Turn Your Idea Into Code!</h3>
<p className="text-muted-foreground max-w-md mx-auto">
Start building based on your ChatGPT conversation. Open your project in Cursor to begin tracking.
</p>
<div className="mt-4">
<a
href={project.chatgptUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 text-sm text-green-600 hover:underline"
>
<MessageSquare className="h-4 w-4" />
View ChatGPT Conversation
</a>
</div>
</>
)}
{!project.workspacePath && !project.githubRepo && !project.chatgptUrl && (
<>
<h3 className="text-2xl font-bold mb-2">Start Building!</h3>
<p className="text-muted-foreground max-w-md mx-auto">
Create your project directory and open it in Cursor to start tracking your development.
</p>
</>
)}
</div>
<div className="flex gap-4 justify-center pt-4">
<Link href={`/${workspace}/connections`}>
<Button size="lg">
Setup Cursor Extension
</Button>
</Link>
</div>
{/* Setup status */}
<div className="mt-8 pt-6 border-t">
<h4 className="text-sm font-medium mb-3">Setup Checklist</h4>
<div className="flex flex-col gap-2 max-w-md mx-auto text-left">
<div className="flex items-center gap-2 text-sm">
<CheckCircle2 className="h-4 w-4 text-green-600" />
<span>Project created</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<AlertCircle className="h-4 w-4" />
<span>Install Cursor Monitor extension</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<AlertCircle className="h-4 w-4" />
<span>Start coding in your workspace</span>
</div>
</div>
</div>
</div>
</CardContent>
</Card>
)}
</div>
</div>
</div>
);
}

View File

@@ -5,12 +5,26 @@ import { useSession } from "next-auth/react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Plus, Sparkles, Loader2, MoreVertical, Trash2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import {
Plus,
Sparkles,
Loader2,
MoreVertical,
Trash2,
GitBranch,
GitCommit,
Rocket,
Terminal,
CheckCircle2,
XCircle,
Clock,
} from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ProjectCreationModal } from "@/components/project-creation-modal";
@@ -32,6 +46,14 @@ import {
} from "@/components/ui/alert-dialog";
import { toast } from "sonner";
interface ContextSnapshot {
lastCommit?: { sha: string; message: string; author?: string; timestamp?: string };
currentBranch?: string;
openPRs?: { number: number; title: string }[];
openIssues?: { number: number; title: string }[];
lastDeployment?: { status: string; url?: string };
}
interface ProjectWithStats {
id: string;
name: string;
@@ -42,25 +64,45 @@ interface ProjectWithStats {
status?: string;
createdAt: string | null;
updatedAt: string | null;
giteaRepo?: string;
giteaRepoUrl?: string;
theiaWorkspaceUrl?: string;
contextSnapshot?: ContextSnapshot;
stats: {
sessions: number;
costs: number;
};
}
function getTimeAgo(dateStr: string | null | undefined): string {
if (!dateStr) return "Unknown";
function timeAgo(dateStr?: string | null): string {
if (!dateStr) return "";
const date = new Date(dateStr);
if (isNaN(date.getTime())) return "Unknown";
const now = new Date();
const diff = now.getTime() - date.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days === 0) return "Today";
if (isNaN(date.getTime())) return "";
const diff = (Date.now() - date.getTime()) / 1000;
if (diff < 60) return "just now";
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
const days = Math.floor(diff / 86400);
if (days === 1) return "Yesterday";
if (days < 7) return `${days} days ago`;
if (days < 30) return `${Math.floor(days / 7)} weeks ago`;
if (days < 365) return `${Math.floor(days / 30)} months ago`;
return `${Math.floor(days / 365)} years ago`;
if (days < 7) return `${days}d ago`;
if (days < 30) return `${Math.floor(days / 7)}w ago`;
return `${Math.floor(days / 30)}mo ago`;
}
function DeployDot({ status }: { status?: string }) {
if (!status) return null;
const map: Record<string, string> = {
finished: "bg-green-500",
in_progress: "bg-blue-500 animate-pulse",
queued: "bg-yellow-400",
failed: "bg-red-500",
};
return (
<span
className={`inline-block h-2 w-2 rounded-full ${map[status] ?? "bg-gray-400"}`}
title={status}
/>
);
}
export default function ProjectsPage() {
@@ -87,7 +129,6 @@ export default function ProjectsPage() {
setProjects(data.projects || []);
setError(null);
} catch (err: unknown) {
console.error("Error fetching projects:", err);
setError(err instanceof Error ? err.message : "Unknown error");
} finally {
setLoading(false);
@@ -95,11 +136,8 @@ export default function ProjectsPage() {
};
useEffect(() => {
if (status === "authenticated") {
fetchProjects();
} else if (status === "unauthenticated") {
setLoading(false);
}
if (status === "authenticated") fetchProjects();
else if (status === "unauthenticated") setLoading(false);
}, [status]);
const handleDeleteProject = async () => {
@@ -111,7 +149,6 @@ export default function ProjectsPage() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ projectId: projectToDelete.id }),
});
if (res.ok) {
toast.success("Project deleted");
setProjectToDelete(null);
@@ -120,8 +157,7 @@ export default function ProjectsPage() {
const err = await res.json();
toast.error(err.error || "Failed to delete project");
}
} catch (err) {
console.error("Delete error:", err);
} catch {
toast.error("An error occurred");
} finally {
setIsDeleting(false);
@@ -139,12 +175,11 @@ export default function ProjectsPage() {
return (
<>
<div className="container mx-auto py-8 px-4 max-w-6xl">
{/* Header */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-2xl font-bold">Projects</h1>
<p className="text-muted-foreground text-sm mt-1">
{session?.user?.email}
</p>
<p className="text-muted-foreground text-sm mt-1">{session?.user?.email}</p>
</div>
<Button onClick={() => setShowCreationModal(true)}>
<Plus className="mr-2 h-4 w-4" />
@@ -152,136 +187,173 @@ export default function ProjectsPage() {
</Button>
</div>
<div className="space-y-6">
{loading && (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)}
{/* States */}
{loading && (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)}
{error && (
<Card className="border-red-500/50 bg-red-500/5">
<CardContent className="py-6">
<p className="text-sm text-red-600">Error: {error}</p>
</CardContent>
</Card>
)}
{error && (
<Card className="border-red-500/30 bg-red-500/5">
<CardContent className="py-6">
<p className="text-sm text-red-600">Error: {error}</p>
</CardContent>
</Card>
)}
{!loading && !error && projects.length > 0 && (
<section>
<h2 className="text-base font-semibold mb-4">Your Projects</h2>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{projects.map((project) => {
const projectHref = `/${workspace}/project/${project.id}/overview`;
return (
<div key={project.id} className="relative">
<Link href={projectHref}>
<Card className="hover:border-primary transition-all cursor-pointer h-full">
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div className="text-3xl">📦</div>
<div>
<CardTitle className="text-base">{project.productName}</CardTitle>
<CardDescription className="text-xs mt-0.5">
{getTimeAgo(project.updatedAt)}
</CardDescription>
</div>
</div>
<div className="flex items-center gap-2">
<div
className={`px-2 py-0.5 rounded-full text-xs font-medium ${
project.status === "active"
? "bg-green-500/10 text-green-600"
: "bg-gray-500/10 text-gray-600"
}`}
{/* Projects Grid */}
{!loading && !error && projects.length > 0 && (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{projects.map((project) => {
const href = `/${workspace}/project/${project.id}/overview`;
const snap = project.contextSnapshot;
const deployStatus = snap?.lastDeployment?.status;
return (
<div key={project.id} className="relative group">
<Link href={href}>
<Card className="hover:border-primary/50 hover:shadow-sm transition-all cursor-pointer h-full">
<CardHeader className="pb-3">
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<CardTitle className="text-base truncate">{project.productName}</CardTitle>
<CardDescription className="text-xs mt-0.5">
{timeAgo(project.updatedAt)}
</CardDescription>
</div>
<div className="flex items-center gap-1.5 shrink-0">
<Badge
variant={project.status === "active" ? "default" : "secondary"}
className="text-[10px] px-1.5 py-0"
>
{project.status ?? "active"}
</Badge>
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e: React.MouseEvent) => e.preventDefault()}>
<Button variant="ghost" size="icon" className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity">
<MoreVertical className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
className="text-red-600 focus:text-red-600"
onClick={(e: React.MouseEvent) => {
e.preventDefault();
setProjectToDelete(project);
}}
>
{project.status}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e: React.MouseEvent) => e.preventDefault()}>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
className="text-red-600 focus:text-red-600"
onClick={(e: React.MouseEvent) => {
e.preventDefault();
setProjectToDelete(project);
}}
>
<Trash2 className="mr-2 h-4 w-4" />
Delete Project
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</CardHeader>
<CardContent className="space-y-3">
{/* Vision */}
{project.productVision && (
<p className="text-xs text-muted-foreground line-clamp-2">
{project.productVision}
</p>
)}
{/* Gitea repo + last commit */}
{project.giteaRepo && (
<div className="rounded-md border bg-muted/20 p-2 space-y-1">
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<GitBranch className="h-3 w-3" />
<span className="font-mono truncate">{project.giteaRepo}</span>
{snap?.currentBranch && (
<span className="text-[10px] px-1.5 py-0 bg-muted rounded-full shrink-0">
{snap.currentBranch}
</span>
)}
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4 line-clamp-2">
{project.productVision || "No description"}
</p>
{project.workspacePath && (
<p className="text-xs text-muted-foreground font-mono mb-4 truncate" title={project.workspacePath}>
📁 {project.workspacePath.split("/").pop()}
</p>
{snap?.lastCommit ? (
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<GitCommit className="h-3 w-3 shrink-0" />
<span className="font-mono text-[10px]">{snap.lastCommit.sha.slice(0, 7)}</span>
<span className="truncate flex-1">{snap.lastCommit.message}</span>
<span className="shrink-0">{timeAgo(snap.lastCommit.timestamp)}</span>
</div>
) : (
<p className="text-[10px] text-muted-foreground">No commits yet</p>
)}
<div className="flex items-center justify-between text-xs">
<div>
<span className="text-muted-foreground">Sessions:</span>{" "}
<span className="font-medium">{project.stats.sessions}</span>
</div>
<div>
<span className="text-muted-foreground">Costs:</span>{" "}
<span className="font-medium">${project.stats.costs.toFixed(2)}</span>
</div>
</div>
</CardContent>
</Card>
</Link>
</div>
);
})}
</div>
)}
<Card
className="hover:border-primary transition-all cursor-pointer border-dashed h-full"
onClick={() => setShowCreationModal(true)}
>
<CardContent className="flex flex-col items-center justify-center h-full min-h-[200px] p-6">
<div className="rounded-full bg-muted p-4 mb-4">
<Plus className="h-6 w-6 text-muted-foreground" />
</div>
<h3 className="font-semibold mb-1">Create New Project</h3>
<p className="text-sm text-muted-foreground text-center">
Start tracking a new product
</p>
</CardContent>
</Card>
</div>
</section>
)}
{!loading && !error && projects.length === 0 && (
<Card className="border-dashed">
<CardContent className="flex flex-col items-center justify-center py-16">
<div className="rounded-full bg-muted p-6 mb-4">
<Sparkles className="h-12 w-12 text-muted-foreground" />
{/* Footer row: deploy + stats + IDE */}
<div className="flex items-center justify-between pt-1 border-t">
<div className="flex items-center gap-3 text-xs text-muted-foreground">
{deployStatus && (
<span className="flex items-center gap-1">
<DeployDot status={deployStatus} />
{deployStatus === "finished" ? "Live" : deployStatus}
</span>
)}
<span>{project.stats.sessions} sessions</span>
<span>${project.stats.costs.toFixed(2)}</span>
</div>
{project.theiaWorkspaceUrl && (
<a
href={project.theiaWorkspaceUrl}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="flex items-center gap-1 text-[10px] text-primary hover:underline"
>
<Terminal className="h-3 w-3" />
IDE
</a>
)}
</div>
</CardContent>
</Card>
</Link>
</div>
<h3 className="text-lg font-semibold mb-2">No projects yet</h3>
<p className="text-sm text-muted-foreground text-center max-w-md mb-6">
Create your first project to start tracking your AI-powered development workflow.
);
})}
{/* Create card */}
<Card
className="hover:border-primary/50 transition-all cursor-pointer border-dashed"
onClick={() => setShowCreationModal(true)}
>
<CardContent className="flex flex-col items-center justify-center h-full min-h-[220px] p-6">
<div className="rounded-full bg-muted p-4 mb-3">
<Plus className="h-6 w-6 text-muted-foreground" />
</div>
<h3 className="font-semibold mb-1 text-sm">New Project</h3>
<p className="text-xs text-muted-foreground text-center">
Auto-provisions a Gitea repo and workspace
</p>
<Button size="lg" onClick={() => setShowCreationModal(true)}>
<Plus className="mr-2 h-4 w-4" />
Create Your First Project
</Button>
</CardContent>
</Card>
)}
</div>
</div>
)}
{/* Empty state */}
{!loading && !error && projects.length === 0 && (
<Card className="border-dashed">
<CardContent className="flex flex-col items-center justify-center py-16">
<div className="rounded-full bg-muted p-6 mb-4">
<Sparkles className="h-12 w-12 text-muted-foreground" />
</div>
<h3 className="text-lg font-semibold mb-2">No projects yet</h3>
<p className="text-sm text-muted-foreground text-center max-w-md mb-6">
Create your first project. Vibn will automatically provision a Gitea repo,
register webhooks, and prepare your IDE workspace.
</p>
<Button size="lg" onClick={() => setShowCreationModal(true)}>
<Plus className="mr-2 h-4 w-4" />
Create Your First Project
</Button>
</CardContent>
</Card>
)}
</div>
<ProjectCreationModal
@@ -296,15 +368,24 @@ export default function ProjectsPage() {
<AlertDialog open={!!projectToDelete} onOpenChange={(open) => !open && setProjectToDelete(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogTitle>Delete &quot;{projectToDelete?.productName}&quot;?</AlertDialogTitle>
<AlertDialogDescription>
This will delete &quot;{projectToDelete?.productName}&quot;. Sessions will be preserved but unlinked.
This will remove the project record. Sessions will be preserved but unlinked.
The Gitea repo will not be deleted automatically.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDeleteProject} disabled={isDeleting} className="bg-red-600 hover:bg-red-700">
{isDeleting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Trash2 className="mr-2 h-4 w-4" />}
<AlertDialogAction
onClick={handleDeleteProject}
disabled={isDeleting}
className="bg-red-600 hover:bg-red-700"
>
{isDeleting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Trash2 className="mr-2 h-4 w-4" />
)}
Delete Project
</AlertDialogAction>
</AlertDialogFooter>