Persist Atlas chat history; fix re-greeting on refresh

- GET /api/projects/[id]/atlas-chat returns stored user+assistant messages
- POST handles __atlas_init__ trigger: runs once when no history exists,
  not stored as a user turn so Atlas intro appears cleanly
- Rewrite AtlasChat.tsx: fully self-contained component with own message
  state; loads history from DB on mount, only greets on first open
- Remove assistant-ui runtime dependency for message persistence
- Add Vision & Success Metrics, Integrations & Dependencies, Open Questions
  to PRD section tracker (now 12 sections matching the PDF)

Made-with: Cursor
This commit is contained in:
2026-03-02 16:55:10 -08:00
parent 9fc643f9b6
commit 0146ae7df6
3 changed files with 313 additions and 68 deletions

View File

@@ -6,13 +6,16 @@ import { useParams } from "next/navigation";
const PRD_SECTIONS = [ const PRD_SECTIONS = [
{ id: "executive_summary", label: "Executive Summary" }, { id: "executive_summary", label: "Executive Summary" },
{ id: "problem_statement", label: "Problem Statement" }, { id: "problem_statement", label: "Problem Statement" },
{ id: "vision_metrics", label: "Vision & Success Metrics" },
{ id: "users_personas", label: "Users & Personas" }, { id: "users_personas", label: "Users & Personas" },
{ id: "user_flows", label: "User Flows" }, { id: "user_flows", label: "User Flows" },
{ id: "feature_requirements", label: "Feature Requirements" }, { id: "feature_requirements", label: "Feature Requirements" },
{ id: "screen_specs", label: "Screen Specs" }, { id: "screen_specs", label: "Screen Specs" },
{ id: "business_model", label: "Business Model" }, { id: "business_model", label: "Business Model" },
{ id: "integrations", label: "Integrations & Dependencies" },
{ id: "non_functional", label: "Non-Functional Reqs" }, { id: "non_functional", label: "Non-Functional Reqs" },
{ id: "risks", label: "Risks" }, { id: "risks", label: "Risks & Mitigations" },
{ id: "open_questions", label: "Open Questions" },
]; ];
interface PRDSection { interface PRDSection {

View File

@@ -66,6 +66,30 @@ async function savePrd(projectId: string, prdContent: string): Promise<void> {
} }
} }
// ---------------------------------------------------------------------------
// GET — load stored conversation messages for display
// ---------------------------------------------------------------------------
export async function GET(
_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 history = await loadAtlasHistory(projectId);
// Filter to only user/assistant messages (no system prompts) for display
const messages = history
.filter((m: any) => m.role === "user" || m.role === "assistant")
.map((m: any) => ({ role: m.role as "user" | "assistant", content: m.content as string }));
return NextResponse.json({ messages });
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// POST — send message to Atlas // POST — send message to Atlas
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -90,14 +114,25 @@ export async function POST(
// Load conversation history from DB to persist across agent runner restarts // Load conversation history from DB to persist across agent runner restarts
const history = await loadAtlasHistory(projectId); const history = await loadAtlasHistory(projectId);
// __init__ is a special internal trigger used only when there is no existing history.
// If history already exists, ignore the init request (conversation already started).
const isInit = message.trim() === "__atlas_init__";
if (isInit && history.length > 0) {
return NextResponse.json({ reply: null, alreadyStarted: true });
}
try { try {
const res = await fetch(`${AGENT_RUNNER_URL}/atlas/chat`, { const res = await fetch(`${AGENT_RUNNER_URL}/atlas/chat`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
message, // For init, send the greeting prompt but don't store it as a user message
message: isInit
? "Begin the conversation. Introduce yourself as Atlas and ask what the user is building. Do not acknowledge this as an internal trigger."
: message,
session_id: sessionId, session_id: sessionId,
history, history,
is_init: isInit,
}), }),
signal: AbortSignal.timeout(120_000), signal: AbortSignal.timeout(120_000),
}); });

View File

@@ -1,34 +1,129 @@
"use client"; "use client";
import { useEffect, useRef } from "react"; import { useEffect, useRef, useState, useCallback } from "react";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import {
AssistantRuntimeProvider, interface ChatMessage {
useLocalRuntime, role: "user" | "assistant";
type ChatModelAdapter, content: string;
} from "@assistant-ui/react"; }
import { Thread } from "@/components/assistant-ui/thread";
interface AtlasChatProps { interface AtlasChatProps {
projectId: string; projectId: string;
projectName?: string; projectName?: string;
} }
function makeAtlasAdapter(projectId: string): ChatModelAdapter { // ---------------------------------------------------------------------------
return { // Markdown-lite renderer — handles **bold**, newlines, numbered/bullet lists
async run({ messages, abortSignal }) { // ---------------------------------------------------------------------------
const lastUser = [...messages].reverse().find((m) => m.role === "user"); function renderContent(text: string) {
const text = return text.split("\n").map((line, i) => {
lastUser?.content const parts = line.split(/(\*\*.*?\*\*)/g).map((seg, j) =>
.filter((p) => p.type === "text") seg.startsWith("**") && seg.endsWith("**")
.map((p) => (p as { type: "text"; text: string }).text) ? <strong key={j} style={{ fontWeight: 600, color: "#1a1a1a" }}>{seg.slice(2, -2)}</strong>
.join("") ?? ""; : <span key={j}>{seg}</span>
);
return <div key={i} style={{ minHeight: line.length ? undefined : "0.75em" }}>{parts}</div>;
});
}
// ---------------------------------------------------------------------------
// Message row
// ---------------------------------------------------------------------------
function MessageRow({ msg, userInitial }: { msg: ChatMessage; userInitial: string }) {
const isAtlas = msg.role === "assistant";
return (
<div style={{ display: "flex", gap: 12, marginBottom: 22, animation: "enter 0.3s ease both" }}>
{/* Avatar */}
<div style={{
width: 28, height: 28, borderRadius: 7, flexShrink: 0, marginTop: 2,
background: isAtlas ? "#1a1a1a" : "#e8e4dc",
display: "flex", alignItems: "center", justifyContent: "center",
fontSize: "0.68rem", fontWeight: 700,
color: isAtlas ? "#fff" : "#8a8478",
fontFamily: isAtlas ? "Newsreader, serif" : "Outfit, sans-serif",
}}>
{isAtlas ? "A" : userInitial}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
{/* Label */}
<div style={{
fontSize: "0.68rem", fontWeight: 600, color: "#a09a90",
marginBottom: 5, textTransform: "uppercase", letterSpacing: "0.04em",
fontFamily: "Outfit, sans-serif",
}}>
{isAtlas ? "Atlas" : "You"}
</div>
{/* Content */}
<div style={{
fontSize: "0.88rem", color: "#2a2824", lineHeight: 1.72,
fontFamily: "Outfit, sans-serif",
whiteSpace: isAtlas ? "normal" : "pre-wrap",
}}>
{renderContent(msg.content)}
</div>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Typing indicator
// ---------------------------------------------------------------------------
function TypingIndicator() {
return (
<div style={{ display: "flex", gap: 12, marginBottom: 22, animation: "enter 0.2s ease" }}>
<div style={{
width: 28, height: 28, borderRadius: 7, flexShrink: 0, marginTop: 2,
background: "#1a1a1a", display: "flex", alignItems: "center", justifyContent: "center",
fontSize: "0.68rem", fontWeight: 700, color: "#fff", fontFamily: "Newsreader, serif",
}}>A</div>
<div style={{ display: "flex", gap: 5, paddingTop: 10 }}>
{[0, 1, 2].map(d => (
<div key={d} style={{
width: 5, height: 5, borderRadius: "50%", background: "#b5b0a6",
animation: `blink 1s ease ${d * 0.15}s infinite`,
}} />
))}
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------
export function AtlasChat({ projectId }: AtlasChatProps) {
const { data: session } = useSession();
const userInitial =
session?.user?.name?.[0]?.toUpperCase() ??
session?.user?.email?.[0]?.toUpperCase() ??
"Y";
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState("");
const [isStreaming, setIsStreaming] = useState(false);
const [historyLoaded, setHistoryLoaded] = useState(false);
const initTriggered = useRef(false);
const endRef = useRef<HTMLDivElement>(null);
// Scroll to bottom whenever messages change
useEffect(() => {
endRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages, isStreaming]);
// Send a message to Atlas — optionally hidden from UI (for init trigger)
const sendToAtlas = useCallback(async (text: string, hideUserMsg = false) => {
if (!hideUserMsg) {
setMessages(prev => [...prev, { role: "user", content: text }]);
}
setIsStreaming(true);
try {
const res = await fetch(`/api/projects/${projectId}/atlas-chat`, { const res = await fetch(`/api/projects/${projectId}/atlas-chat`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: text }), body: JSON.stringify({ message: text }),
signal: abortSignal,
}); });
if (!res.ok) { if (!res.ok) {
@@ -37,60 +132,172 @@ function makeAtlasAdapter(projectId: string): ChatModelAdapter {
} }
const data = await res.json(); const data = await res.json();
return { content: [{ type: "text", text: data.reply || "…" }] };
},
};
}
function AtlasChatInner({ // alreadyStarted means the init was called but history already exists — ignore
projectId, if (data.alreadyStarted) return;
projectName,
userInitial,
runtime,
}: AtlasChatProps & {
userInitial: string;
runtime: ReturnType<typeof useLocalRuntime>;
}) {
const greeted = useRef(false);
if (data.reply) {
setMessages(prev => [...prev, { role: "assistant", content: data.reply }]);
}
} catch (e) {
const msg = e instanceof Error ? e.message : "Something went wrong.";
setMessages(prev => [...prev, { role: "assistant", content: msg }]);
} finally {
setIsStreaming(false);
}
}, [projectId]);
// On mount: load stored history; if empty, trigger Atlas greeting
useEffect(() => { useEffect(() => {
if (greeted.current) return; if (historyLoaded) return;
greeted.current = true;
const opener = `Hey — I'm starting a new project called "${projectName || "my project"}". I'd love your help defining what we're building.`; fetch(`/api/projects/${projectId}/atlas-chat`)
const t = setTimeout(() => { .then(r => r.json())
runtime.thread.composer.setText(opener); .then((data: { messages: ChatMessage[] }) => {
runtime.thread.composer.send(); const stored = data.messages ?? [];
}, 300); setMessages(stored);
return () => clearTimeout(t); setHistoryLoaded(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // Only trigger greeting if there's genuinely no history yet
if (stored.length === 0 && !initTriggered.current) {
initTriggered.current = true;
sendToAtlas("__atlas_init__", true);
}
})
.catch(() => {
setHistoryLoaded(true);
// If we can't load, still try to greet on first open
if (!initTriggered.current) {
initTriggered.current = true;
sendToAtlas("__atlas_init__", true);
}
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projectId]);
const handleSend = () => {
const text = input.trim();
if (!text || isStreaming) return;
setInput("");
sendToAtlas(text, false);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
const isEmpty = messages.length === 0 && !isStreaming;
return ( return (
// No card — fills the layout space directly <div style={{
<div style={{ height: "100%", display: "flex", flexDirection: "column" }}> display: "flex", flexDirection: "column", height: "100%",
<Thread userInitial={userInitial} /> background: "#f6f4f0", fontFamily: "Outfit, sans-serif",
}}>
<style>{`
@keyframes blink { 0%,100%{opacity:.2} 50%{opacity:.8} }
@keyframes enter { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:translateY(0); } }
`}</style>
{/* Empty state */}
{isEmpty && (
<div style={{
flex: 1, display: "flex", flexDirection: "column",
alignItems: "center", justifyContent: "center",
gap: 12, padding: "40px 32px",
}}>
<div style={{
width: 44, height: 44, borderRadius: 11, background: "#1a1a1a",
display: "flex", alignItems: "center", justifyContent: "center",
fontFamily: "Newsreader, serif", fontSize: "1.2rem", fontWeight: 500, color: "#fff",
animation: "breathe 2.5s ease infinite",
}}>A</div>
<style>{`@keyframes breathe { 0%,100%{transform:scale(1)} 50%{transform:scale(1.08)} }`}</style>
<div style={{ textAlign: "center" }}>
<p style={{ fontSize: "0.88rem", fontWeight: 600, color: "#1a1a1a", marginBottom: 4 }}>Atlas</p>
<p style={{ fontSize: "0.78rem", color: "#a09a90", maxWidth: 260, lineHeight: 1.5 }}>
Your product strategist. Let&apos;s define what you&apos;re building.
</p>
</div>
</div>
)}
{/* Messages */}
{!isEmpty && (
<div style={{ flex: 1, overflowY: "auto", padding: "28px 32px" }}>
{messages.map((msg, i) => (
<MessageRow key={i} msg={msg} userInitial={userInitial} />
))}
{isStreaming && <TypingIndicator />}
<div ref={endRef} />
</div>
)}
{/* Loading history state */}
{isEmpty && isStreaming && (
<div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
<TypingIndicator />
</div>
)}
{/* Input bar */}
<div style={{ padding: "14px 32px 22px", flexShrink: 0 }}>
<div style={{
display: "flex", gap: 8, padding: "5px 5px 5px 16px",
background: "#fff", border: "1px solid #e0dcd4", borderRadius: 10,
alignItems: "center", boxShadow: "0 1px 4px #1a1a1a06",
}}>
<textarea
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Describe your thinking..."
rows={1}
disabled={isStreaming}
style={{
flex: 1, border: "none", background: "none",
fontSize: "0.86rem", fontFamily: "Outfit, sans-serif",
color: "#1a1a1a", padding: "8px 0",
resize: "none", outline: "none",
minHeight: 24, maxHeight: 120,
}}
/>
{isStreaming ? (
<button
onClick={() => setIsStreaming(false)}
style={{
padding: "9px 16px", borderRadius: 7, border: "none",
background: "#eae6de", color: "#8a8478",
fontSize: "0.78rem", fontWeight: 600, fontFamily: "Outfit, sans-serif",
cursor: "pointer", flexShrink: 0,
display: "flex", alignItems: "center", gap: 6,
}}
>
<span style={{ width: 10, height: 10, background: "#8a8478", borderRadius: 2, display: "inline-block" }} />
Stop
</button>
) : (
<button
onClick={handleSend}
disabled={!input.trim()}
style={{
padding: "9px 16px", borderRadius: 7, border: "none",
background: input.trim() ? "#1a1a1a" : "#eae6de",
color: input.trim() ? "#fff" : "#b5b0a6",
fontSize: "0.78rem", fontWeight: 600, fontFamily: "Outfit, sans-serif",
cursor: input.trim() ? "pointer" : "default",
flexShrink: 0, transition: "all 0.15s",
}}
onMouseEnter={e => { if (input.trim()) (e.currentTarget.style.opacity = "0.8"); }}
onMouseLeave={e => { (e.currentTarget.style.opacity = "1"); }}
>
Send
</button>
)}
</div>
</div>
</div> </div>
); );
} }
export function AtlasChat({ projectId, projectName }: AtlasChatProps) {
const { data: session } = useSession();
const userInitial =
session?.user?.name?.[0]?.toUpperCase() ??
session?.user?.email?.[0]?.toUpperCase() ??
"Y";
const adapter = makeAtlasAdapter(projectId);
const runtime = useLocalRuntime(adapter);
return (
<AssistantRuntimeProvider runtime={runtime}>
<AtlasChatInner
projectId={projectId}
projectName={projectName}
userInitial={userInitial}
runtime={runtime}
/>
</AssistantRuntimeProvider>
);
}