feat: add Atlas discovery chat UI and API route

- components/AtlasChat.tsx — conversational PRD discovery UI (violet theme)
- app/api/projects/[projectId]/atlas-chat/route.ts — proxy + DB persistence
- overview/page.tsx — show Atlas for new projects, Orchestrator once PRD done

Made-with: Cursor
This commit is contained in:
2026-03-01 15:56:32 -08:00
parent 35675b7d86
commit 26a11412b5
3 changed files with 495 additions and 5 deletions

View File

@@ -13,6 +13,7 @@ import {
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { OrchestratorChat } from "@/components/OrchestratorChat";
import { AtlasChat } from "@/components/AtlasChat";
import {
GitBranch,
GitCommit,
@@ -78,6 +79,9 @@ interface Project {
deploymentUrl?: string;
// Theia
theiaWorkspaceUrl?: string;
// Stage
stage?: 'discovery' | 'architecture' | 'building' | 'active';
prd?: string;
// Context
contextSnapshot?: ContextSnapshot;
stats?: { sessions: number; costs: number };
@@ -199,11 +203,18 @@ export default function ProjectOverviewPage() {
return (
<div className="container mx-auto py-8 px-6 max-w-5xl space-y-6">
{/* ── Orchestrator Chat ── */}
{/* ── Agent Panel — Atlas for discovery, Orchestrator once PRD is done ── */}
{(!project.stage || project.stage === 'discovery') ? (
<AtlasChat
projectId={projectId}
projectName={project.productName}
/>
) : (
<OrchestratorChat
projectId={projectId}
projectName={project.productName}
/>
)}
{/* ── Header ── */}
<div className="flex items-start justify-between">

View File

@@ -0,0 +1,164 @@
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth/authOptions";
import { query } from "@/lib/db-postgres";
const AGENT_RUNNER_URL = process.env.AGENT_RUNNER_URL ?? "http://localhost:3333";
// ---------------------------------------------------------------------------
// DB helpers — atlas_conversations table
// ---------------------------------------------------------------------------
let tableReady = false;
async function ensureTable() {
if (tableReady) return;
await query(`
CREATE TABLE IF NOT EXISTS atlas_conversations (
project_id TEXT PRIMARY KEY,
messages JSONB NOT NULL DEFAULT '[]'::jsonb,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
tableReady = true;
}
async function loadAtlasHistory(projectId: string): Promise<any[]> {
try {
await ensureTable();
const rows = await query<{ messages: any[] }>(
`SELECT messages FROM atlas_conversations WHERE project_id = $1`,
[projectId]
);
return rows[0]?.messages ?? [];
} catch {
return [];
}
}
async function saveAtlasHistory(projectId: string, messages: any[]): Promise<void> {
try {
await ensureTable();
await query(
`INSERT INTO atlas_conversations (project_id, messages, updated_at)
VALUES ($1, $2::jsonb, NOW())
ON CONFLICT (project_id) DO UPDATE
SET messages = $2::jsonb, updated_at = NOW()`,
[projectId, JSON.stringify(messages)]
);
} catch (e) {
console.error("[atlas-chat] Failed to save history:", e);
}
}
async function savePrd(projectId: string, prdContent: string): Promise<void> {
try {
await query(
`UPDATE fs_projects
SET data = data || jsonb_build_object('prd', $2, 'stage', 'architecture'),
updated_at = NOW()
WHERE id = $1`,
[projectId, prdContent]
);
console.log(`[atlas-chat] PRD saved for project ${projectId}`);
} catch (e) {
console.error("[atlas-chat] Failed to save PRD:", e);
}
}
// ---------------------------------------------------------------------------
// POST — send message to Atlas
// ---------------------------------------------------------------------------
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ projectId: string }> }
) {
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { projectId } = await params;
const { message } = await req.json();
if (!message?.trim()) {
return NextResponse.json({ error: "message is required" }, { status: 400 });
}
const sessionId = `atlas_${projectId}`;
// Load conversation history from DB to persist across agent runner restarts
const history = await loadAtlasHistory(projectId);
try {
const res = await fetch(`${AGENT_RUNNER_URL}/atlas/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message,
session_id: sessionId,
history,
}),
signal: AbortSignal.timeout(120_000),
});
if (!res.ok) {
const text = await res.text();
console.error("[atlas-chat] Agent runner error:", text);
return NextResponse.json(
{ error: "Atlas is unavailable. Please try again." },
{ status: 502 }
);
}
const data = await res.json();
// Persist updated history
await saveAtlasHistory(projectId, data.history ?? []);
// If Atlas finalized the PRD, save it to the project
if (data.prdContent) {
await savePrd(projectId, data.prdContent);
}
return NextResponse.json({
reply: data.reply,
sessionId,
prdContent: data.prdContent ?? null,
model: data.model ?? null,
});
} catch (err) {
console.error("[atlas-chat] Error:", err);
return NextResponse.json(
{ error: "Request timed out or failed. Please try again." },
{ status: 500 }
);
}
}
// ---------------------------------------------------------------------------
// DELETE — clear Atlas conversation for this project
// ---------------------------------------------------------------------------
export async function DELETE(
_req: NextRequest,
{ params }: { params: Promise<{ projectId: string }> }
) {
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { projectId } = await params;
const sessionId = `atlas_${projectId}`;
try {
await fetch(`${AGENT_RUNNER_URL}/atlas/sessions/${sessionId}`, { method: "DELETE" });
} catch { /* runner may be down */ }
try {
await query(`DELETE FROM atlas_conversations WHERE project_id = $1`, [projectId]);
} catch { /* table may not exist yet */ }
return NextResponse.json({ cleared: true });
}

315
components/AtlasChat.tsx Normal file
View File

@@ -0,0 +1,315 @@
"use client";
import { useState, useRef, useEffect, useCallback } from "react";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Send,
Loader2,
User,
RotateCcw,
FileText,
CheckCircle2,
ChevronDown,
ChevronUp,
} from "lucide-react";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface Message {
role: "user" | "assistant";
content: string;
}
interface AtlasChatProps {
projectId: string;
projectName?: string;
initialMessage?: string;
}
// ---------------------------------------------------------------------------
// Atlas avatar — distinct from orchestrator
// ---------------------------------------------------------------------------
function AtlasAvatar() {
return (
<div className="w-7 h-7 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center text-white text-xs font-bold shrink-0 shadow-sm">
A
</div>
);
}
// ---------------------------------------------------------------------------
// PRD preview panel
// ---------------------------------------------------------------------------
function PrdPanel({ content }: { content: string }) {
const [expanded, setExpanded] = useState(false);
const preview = content.split("\n").slice(0, 6).join("\n");
return (
<div className="mt-4 border border-violet-200 dark:border-violet-800 rounded-xl overflow-hidden bg-violet-50/50 dark:bg-violet-950/20">
<div className="flex items-center gap-2 px-4 py-3 bg-violet-100/60 dark:bg-violet-900/30">
<CheckCircle2 className="w-4 h-4 text-violet-600 dark:text-violet-400" />
<span className="text-sm font-semibold text-violet-700 dark:text-violet-300">
PRD Generated
</span>
<span className="text-xs text-muted-foreground ml-auto">
Ready for architecture phase
</span>
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs text-violet-600"
onClick={() => setExpanded(!expanded)}
>
{expanded ? (
<ChevronUp className="w-3 h-3" />
) : (
<ChevronDown className="w-3 h-3" />
)}
</Button>
</div>
<div className="px-4 py-3">
<pre className={`text-xs text-muted-foreground whitespace-pre-wrap font-mono leading-relaxed ${expanded ? "" : "line-clamp-4"}`}>
{expanded ? content : preview}
</pre>
{!expanded && (
<button
onClick={() => setExpanded(true)}
className="text-xs text-violet-600 hover:underline mt-1"
>
View full PRD
</button>
)}
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------
export function AtlasChat({ projectId, projectName, initialMessage }: AtlasChatProps) {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState("");
const [loading, setLoading] = useState(false);
const [prdContent, setPrdContent] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [started, setStarted] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Auto-scroll to latest message
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages, loading]);
// Kick off Atlas with its opening message on first load
useEffect(() => {
if (started) return;
setStarted(true);
sendMessage(
initialMessage ||
`Hey — I'm starting a new project called "${projectName || "my project"}". I'd love your help defining what we're building.`
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const sendMessage = useCallback(
async (text: string) => {
if (!text.trim() || loading) return;
setError(null);
const userMsg: Message = { role: "user", content: text };
setMessages((prev) => [...prev, userMsg]);
setInput("");
setLoading(true);
try {
const res = await fetch(
`/api/projects/${projectId}/atlas-chat`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: text }),
}
);
const data = await res.json();
if (!res.ok) {
setError(data.error || "Something went wrong. Please try again.");
setMessages((prev) => prev.slice(0, -1));
return;
}
const assistantMsg: Message = {
role: "assistant",
content: data.reply || "...",
};
setMessages((prev) => [...prev, assistantMsg]);
if (data.prdContent) {
setPrdContent(data.prdContent);
}
} catch {
setError("Couldn't reach Atlas. Check your connection and try again.");
setMessages((prev) => prev.slice(0, -1));
} finally {
setLoading(false);
setTimeout(() => textareaRef.current?.focus(), 50);
}
},
[loading, projectId]
);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendMessage(input);
}
};
const handleReset = async () => {
if (!confirm("Start the discovery conversation over from scratch?")) return;
await fetch(`/api/projects/${projectId}/atlas-chat`, { method: "DELETE" });
setMessages([]);
setPrdContent(null);
setStarted(false);
setError(null);
};
return (
<div className="flex flex-col rounded-2xl border border-border/60 bg-card shadow-sm overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-5 py-3.5 border-b border-border/60 bg-gradient-to-r from-violet-50/80 to-indigo-50/50 dark:from-violet-950/30 dark:to-indigo-950/20">
<div className="flex items-center gap-3">
<AtlasAvatar />
<div>
<p className="text-sm font-semibold text-foreground">Atlas</p>
<p className="text-xs text-muted-foreground">Product Requirements</p>
</div>
</div>
<div className="flex items-center gap-2">
{prdContent && (
<div className="flex items-center gap-1.5 text-xs text-violet-600 dark:text-violet-400 bg-violet-100 dark:bg-violet-900/40 px-2.5 py-1 rounded-full">
<FileText className="w-3 h-3" />
PRD ready
</div>
)}
<Button
variant="ghost"
size="sm"
onClick={handleReset}
className="h-7 w-7 p-0 text-muted-foreground hover:text-foreground"
title="Start over"
>
<RotateCcw className="w-3.5 h-3.5" />
</Button>
</div>
</div>
{/* Messages */}
<ScrollArea className="flex-1 max-h-[500px]">
<div className="px-5 py-4 space-y-5">
{messages.map((msg, i) => (
<div
key={i}
className={`flex gap-3 ${msg.role === "user" ? "justify-end" : "justify-start"}`}
>
{msg.role === "assistant" && <AtlasAvatar />}
<div
className={`max-w-[82%] ${
msg.role === "user"
? "bg-violet-600 text-white rounded-2xl rounded-tr-sm px-4 py-2.5"
: "bg-muted/60 rounded-2xl rounded-tl-sm px-4 py-3"
}`}
>
<p className="text-sm leading-relaxed whitespace-pre-wrap">
{msg.content}
</p>
</div>
{msg.role === "user" && (
<div className="w-7 h-7 rounded-full bg-muted flex items-center justify-center shrink-0">
<User className="w-3.5 h-3.5 text-muted-foreground" />
</div>
)}
</div>
))}
{/* Typing indicator */}
{loading && (
<div className="flex gap-3 justify-start">
<AtlasAvatar />
<div className="bg-muted/60 rounded-2xl rounded-tl-sm px-4 py-3">
<div className="flex gap-1.5 items-center h-4">
<span className="w-1.5 h-1.5 bg-violet-400 rounded-full animate-bounce [animation-delay:0ms]" />
<span className="w-1.5 h-1.5 bg-violet-400 rounded-full animate-bounce [animation-delay:150ms]" />
<span className="w-1.5 h-1.5 bg-violet-400 rounded-full animate-bounce [animation-delay:300ms]" />
</div>
</div>
</div>
)}
{/* Error */}
{error && (
<div className="text-xs text-destructive bg-destructive/10 rounded-lg px-3 py-2">
{error}
</div>
)}
{/* PRD panel */}
{prdContent && <PrdPanel content={prdContent} />}
<div ref={bottomRef} />
</div>
</ScrollArea>
{/* Input */}
<div className="px-4 py-3 border-t border-border/60 bg-muted/20">
{prdContent ? (
<p className="text-xs text-center text-muted-foreground py-1">
PRD complete the platform is now architecting your solution.
</p>
) : (
<div className="flex gap-2 items-end">
<Textarea
ref={textareaRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Reply to Atlas…"
rows={1}
className="resize-none min-h-[40px] max-h-[120px] text-sm rounded-xl border-border/60 focus-visible:ring-violet-500/30 bg-background"
style={{ overflow: "hidden" }}
onInput={(e) => {
const t = e.currentTarget;
t.style.height = "auto";
t.style.height = Math.min(t.scrollHeight, 120) + "px";
}}
/>
<Button
onClick={() => sendMessage(input)}
disabled={!input.trim() || loading}
size="sm"
className="h-10 w-10 p-0 rounded-xl bg-violet-600 hover:bg-violet-700 text-white shrink-0"
>
{loading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Send className="w-4 h-4" />
)}
</Button>
</div>
)}
</div>
</div>
);
}