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

@@ -1,34 +1,129 @@
"use client";
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState, useCallback } from "react";
import { useSession } from "next-auth/react";
import {
AssistantRuntimeProvider,
useLocalRuntime,
type ChatModelAdapter,
} from "@assistant-ui/react";
import { Thread } from "@/components/assistant-ui/thread";
interface ChatMessage {
role: "user" | "assistant";
content: string;
}
interface AtlasChatProps {
projectId: string;
projectName?: string;
}
function makeAtlasAdapter(projectId: string): ChatModelAdapter {
return {
async run({ messages, abortSignal }) {
const lastUser = [...messages].reverse().find((m) => m.role === "user");
const text =
lastUser?.content
.filter((p) => p.type === "text")
.map((p) => (p as { type: "text"; text: string }).text)
.join("") ?? "";
// ---------------------------------------------------------------------------
// Markdown-lite renderer — handles **bold**, newlines, numbered/bullet lists
// ---------------------------------------------------------------------------
function renderContent(text: string) {
return text.split("\n").map((line, i) => {
const parts = line.split(/(\*\*.*?\*\*)/g).map((seg, j) =>
seg.startsWith("**") && seg.endsWith("**")
? <strong key={j} style={{ fontWeight: 600, color: "#1a1a1a" }}>{seg.slice(2, -2)}</strong>
: <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`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: text }),
signal: abortSignal,
});
if (!res.ok) {
@@ -37,60 +132,172 @@ function makeAtlasAdapter(projectId: string): ChatModelAdapter {
}
const data = await res.json();
return { content: [{ type: "text", text: data.reply || "…" }] };
},
};
}
function AtlasChatInner({
projectId,
projectName,
userInitial,
runtime,
}: AtlasChatProps & {
userInitial: string;
runtime: ReturnType<typeof useLocalRuntime>;
}) {
const greeted = useRef(false);
// alreadyStarted means the init was called but history already exists — ignore
if (data.alreadyStarted) return;
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(() => {
if (greeted.current) 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.`;
const t = setTimeout(() => {
runtime.thread.composer.setText(opener);
runtime.thread.composer.send();
}, 300);
return () => clearTimeout(t);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (historyLoaded) return;
fetch(`/api/projects/${projectId}/atlas-chat`)
.then(r => r.json())
.then((data: { messages: ChatMessage[] }) => {
const stored = data.messages ?? [];
setMessages(stored);
setHistoryLoaded(true);
// 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 (
// No card — fills the layout space directly
<div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
<Thread userInitial={userInitial} />
<div style={{
display: "flex", flexDirection: "column", height: "100%",
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>
);
}
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>
);
}