nextjs-chatbot
Advanced patterns for production Next.js web chatbots built with AI SDK 6 + ai-elements. Covers tool calling with human-in-the-loop (HITL) approval, PostgreSQL session persistence, GDPR consent gating, SQL-first search, per-tool UI rendering, popup widget embedding, message feedback, follow-up suggestions, scope enforcement, and evals. Use when building a customer support bot, conversational interface, or any web chatbot needing tool approval, database sessions, or custom tool output components. Not a scaffolding tool — use `/ai-app` to scaffold from scratch, `/ai-sdk-6` for general SDK questions, `/ai-elements` for chat UI components, `/vercel:chat-sdk` for multi-platform (Slack/Teams/Discord) bots.
What this skill does
# Next.js Chatbot
Opinionated blueprint for production **web** chatbots. Focuses on patterns **not** covered by `/ai-sdk-6`, `/ai-elements`, or `/nextjs-shadcn` — use those skills for general SDK, component, and framework questions. For multi-platform bots (Slack, Teams, Discord), use `/vercel:chat-sdk` instead.
## Stack defaults
- **Runtime:** bun
- **Model:** `gpt-5.4` with `reasoningEffort: "none"`
- **AI SDK:** `ai@6` — `ToolLoopAgent`, `createAgentUIStreamResponse`
- **UI:** shadcn/ui + ai-elements (see `/ai-elements` for component docs)
- **ORM:** Drizzle + PostgreSQL
- **State:** Zustand for client-side chat state (consent, session, suggestions)
- **Attachments:** See `/ai-elements` Attachments component for file upload
## Recommended MCP servers
- **next-devtools** (`next-devtools-mcp@latest` via npx) — route inspection, build diagnostics. See [nextjs.org/docs/app/guides/mcp](https://nextjs.org/docs/app/guides/mcp)
- **ai-elements** (via `mcp-remote` → `https://registry.ai-sdk.dev/api/mcp`) — component registry search
Add both to `.claude/settings.json` mcpServers.
## Agent setup
```ts
export function createAgent(opts?: { model?: LanguageModel }) {
return new ToolLoopAgent({
model: opts?.model ?? openai("gpt-5.4"),
instructions,
providerOptions: { openai: { reasoningEffort: "none" } },
tools,
stopWhen: stepCountIs(10),
});
}
export const agent = createAgent();
export type AgentUIMessage = InferAgentUIMessage<typeof agent>;
```
Export both factory and singleton — factory needed for benchmarks. Wrap with `devToolsMiddleware()` in dev.
## Route handler
```ts
export const maxDuration = 60;
export async function POST(request: Request) {
const { messages, chatId, ...consent } = await request.json();
// 1. Validate consent — return 403 if missing
// 2. Await session upsert BEFORE streaming (FK dependency)
return createAgentUIStreamResponse({
agent,
uiMessages: messages,
generateMessageId: createIdGenerator({ prefix: "msg", size: 16 }),
consumeSseStream: ({ stream }) => consumeStream({ stream }),
experimental_transform: smoothStream({ delayInMs: 15, chunking: "word" }),
onFinish: async ({ messages }) => { /* save to DB — see persistence.md */ },
});
}
```
### Azure OpenAI model routing
Non-reasoning models (gpt-4o) must use Chat Completions API (`azure.chat()`) — Responses API causes `fc_` ID errors on multi-turn tool calls. Reasoning models (gpt-5.x, o-series) use Responses API (default):
```ts
const isReasoning = /^(o[1-9]|gpt-5)/.test(deployment);
export const chatModel = isReasoning ? azure(deployment) : azure.chat(deployment);
```
Set `reasoningEffort` only for reasoning models to avoid warnings.
## Client transport patterns
### Dynamic context via transport body
Inject per-request context (e.g., a saved document for edit mode) from the client:
```ts
// Simple: body function on DefaultChatTransport
const transport = new DefaultChatTransport({
api: "/api/chat",
body: () => ({ documentContext: activeDocRef.current }),
});
// Fine-grained: prepareSendMessagesRequest (official API)
const transport = new DefaultChatTransport({
prepareSendMessagesRequest: ({ id, messages }) => ({
body: { id, message: messages.at(-1), context: extraRef.current },
}),
});
```
Server reads extra fields from the request body and passes to agent factory.
### Chat remount (new conversation)
**Always call `stop()` before clearing** — otherwise the active stream writes into the new conversation:
```ts
const { messages, sendMessage, stop, setMessages } = useChat({ transport });
const startNew = useCallback(() => {
stop(); // Cancel active stream FIRST
setMessages([]);
clearStoredMessages(); // If using localStorage
setChatId(crypto.randomUUID());
setConversationKey(k => k + 1);
}, [stop, setMessages]);
```
### localStorage persistence (no DB)
For lightweight chatbots that don't need server-side persistence:
```ts
// Load on init via messages prop (NOT useEffect + setMessages)
const initialMessages = useMemo(() => {
const stored = loadStoredMessages();
return stored?.length ? (stored as UIMessage[]) : undefined;
}, []);
const { messages, sendMessage } = useChat({
transport,
messages: initialMessages, // useChat accepts initial messages
onFinish: ({ messages: all }) => saveStoredMessages(all),
});
```
### Hydration: Zustand + localStorage
Zustand stores that read `localStorage` in `create()` cause React hydration mismatch (server: `false`, client: `true`). Fix with a `mounted` gate:
```tsx
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
// In render:
{!mounted || !hasConsented ? <ConsentGate /> : <Chat />}
```
## Adding a new tool
1. Create `lib/ai/tools/my-tool.ts` with `tool()` from `ai`
2. Export from `lib/ai/tools/index.ts`
3. Add to `tools` object in the agent file
4. Document in the agent's `instructions` string
5. Add UI renderer in `chat-message.tsx` (handle `tool-myTool` part type)
## Structured output tools (schema-as-output)
When the tool generates structured data (not query/compute), use the pass-through pattern — the Zod schema defines the output, execute just validates and returns:
```ts
const generateDocTool = tool({
description: "Generate structured documentation",
inputSchema: MyDocSchema, // Zod schema IS the output shape
execute: async (data) => data, // Validate and return
});
```
LLM-resilient enums — LLMs sometimes append extra text to enum values. Use lenient transforms:
```ts
const LenientCategory = z.string().transform((val) => {
const valid = ["Business", "Technical", "Legal"] as const;
return valid.find((c) => val.startsWith(c)) ?? "Business";
});
```
## Building a new chatbot
When scaffolding from scratch, read [checklist.md](checklist.md) for the full setup sequence.
## Theming
Always use `globals.css` oklch color variables — never hardcode colors. Define brand identity in `:root`:
```css
/* Example: warm gold brand */
:root {
--primary: oklch(0.84 0.05 85); /* brand color */
--primary-foreground: oklch(0.15 0.02 85);
--muted: oklch(0.95 0.01 85);
--muted-foreground: oklch(0.45 0.02 85);
--font-sans: var(--font-sans), system-ui, sans-serif;
}
```
Use `/nextjs-shadcn` for full theme setup. Key rules:
- All components reference CSS variables, not literal colors
- Match the brand identity across chat bubble, buttons, borders, scrollbar
- User messages: `bg-muted` rounded bubble (right-aligned)
- Assistant messages: full-width, no background
## Message streaming state & feedback visibility
Gate action icons (copy, thumbs up/down, regenerate) and inter-tool shimmers on the **chat-level stream status**, not tool-part states alone. During a multi-tool response (tool A finishes → tool B starts), all tool parts are briefly in a non-loading state and `!toolParts.some(isToolLoading)` flips true → icons and shimmers flicker on/off.
Correct pattern:
```tsx
// Parent widget — derive from useChat's status
const { messages, status } = useChat({ transport, experimental_throttle: 50 });
const isGenerating = status === "streaming" || status === "submitted";
{messages.map((m, i) => (
<ChatMessage
key={m.id}
message={m}
isGenerating={isGenerating}
isLast={i === messages.length - 1}
/>
))}
// ChatMessage
const isStreaming = isGenerating && isLast && message.role === "assistant";
const showActions = !isStreaming && hasContent;
{showActions && <MessageActions>…</MessageActions>}
```
`isGenerating` stays `true` for the entire tool-loop + text-generation span, so `isStreaming` never flips between tools. Pair with `experimental_throttle: 50` on `useChat` to smooth rapid UI updates — this is the client-side knob, distinct from the server-side `smoothStream` text transform.
## Message actions
Every assistant message renders an action toolbar below text: Copy, ThumbsUp, ThumbsDown, Regenerate, Delete — Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.