Normalized for Mintlify from
knowledge-base/neurigraph-memory-architecture/neurigraph-tool-references/08-Conversational-AI-App-Shell-Framework.mdx.Clean-Room Specification: Conversational AI App Shell Framework
Purpose of This Document
This document specifies the architecture for a full-stack conversational AI application framework built with React 19, Next.js (App Router), and a streaming AI backend. While Spec 07 covers headless UI primitives, this specification covers the complete application shell: authentication, database persistence, real-time streaming with recovery, multi-model routing, tool execution with human approval, document artifact management, and the patterns needed to ship a production AI chat product. This specification enables independent implementation from scratch.1. Technology Stack and Architecture
1.1 Stack Overview
1.2 Application Architecture
2. Database Schema (Drizzle ORM)
2.1 Users and Authentication
2.2 Chats
2.3 Messages (Version 2 — Multimodal)
2.4 Documents (Artifacts)
2.5 Suggestions
2.6 Votes (Message Feedback)
3. Authentication System
3.1 NextAuth v5 Configuration
3.2 Middleware
3.3 Password Hashing
4. AI Chat Route Handler
4.1 Main Chat Endpoint
4.2 Streaming with createUIMessageStream
4.3 Resumable Streams via Redis
For production reliability, streams can be buffered in Redis so clients can reconnect and resume:5. Tool System
5.1 Tool Definition Pattern
5.2 Tool Approval Flow
5.3 Built-in Application Tools
The framework provides four reference tool implementations: Tool 1: getWeather (auto-execute, server-side)6. Client-Side Chat Integration
6.1 useChat Hook Integration
6.2 Data Stream Provider Pattern
Custom data can be sent alongside the AI stream using a provider component:7. Application Layout and Routing
7.1 Route Structure
7.2 Chat Layout (Three-Panel)
7.3 Sidebar Component
8. Document Artifact System
8.1 Artifact Panel Architecture
The artifact panel displays documents created by the AI, supporting live editing and version history:8.2 Document Version Navigation
8.3 Inline Suggestions
9. Model Selection and Multi-Provider Routing
9.1 Model Registry
9.2 Model Instance Factory
9.3 Model Picker Component
10. Chat History API
10.1 History Endpoint
10.2 Auto-Title Generation
11. Visibility and Sharing
11.1 Chat Visibility Model
Chats have two visibility levels:private(default): Only the owner can view. All API access requiresuserIdmatch.public: Anyone with the URL can view (read-only). Only owner can send messages.
11.2 Share Dialog
12. Message Feedback (Voting)
13. Optimistic UI Updates
13.1 Pattern: useOptimistic for Sidebar
14. Environment Configuration
15. Database Migrations
16. Behavioral Test Cases
Authentication
- Guest access: Unauthenticated users can create a guest session and chat; guest sessions persist across page reloads within the same browser.
- Credential login: Valid email/password combination returns a session with user ID embedded in JWT.
- Invalid credentials: Wrong password returns 401 without leaking whether email exists.
- Session expiry: Expired JWT redirects to /login via middleware.
- Route protection: All /chat/* routes require authentication; /api/chat returns 401 without valid session.
Chat CRUD
- Auto-title: First message in a new chat triggers title generation; title appears in sidebar.
- Chat ownership: Users can only access their own private chats; accessing another user’s private chat returns 403.
- Delete cascade: Deleting a chat removes all associated messages, votes, and documents.
- Rename: Renaming a chat updates the title immediately (optimistic) and persists to DB.
- History ordering: Chat history is sorted by updatedAt descending (most recent first).
Message Persistence
- User message saved before streaming: The user’s message is persisted to DB before the AI stream begins.
- Assistant message saved after streaming: The complete assistant response (including tool results) is saved after stream finishes.
- Multimodal parts: Messages with mixed content types (text + tool calls + reasoning) round-trip through DB correctly.
- Composite PK: Multiple messages in the same chat have unique (id, chatId) pairs; message IDs are UUIDs.
Streaming
- SSE format: Response uses
text/event-streamcontent type with chunked transfer encoding. - Text streaming: Individual text deltas appear in the client as they’re generated (throttled at 50ms).
- Tool call streaming: Tool name and arguments stream incrementally; client shows partial args during streaming.
- Stream cancellation: Clicking stop sends abort signal; AI generation halts; partial response is preserved.
- Error recovery: Network disconnect during streaming does not lose the user message; client can retry.
- Resumable streams: With Redis enabled, reconnecting with Last-Event-ID resumes from where the client left off.
Tool Execution
- Auto-execute tools: Tools with
executefunction run server-side without user approval. - Approval-required tools: Tools without
executesend tool-call to client; client renders approval UI. - Tool approval: Clicking “Allow” calls addToolResult, which sends the result back to the AI for continuation.
- Tool rejection: Rejecting a tool call sends an error result; AI acknowledges and continues without the tool.
- Multi-step tools: With maxSteps=5, the AI can chain multiple tool calls in sequence within a single response.
Document Artifacts
- Create document: createDocument tool creates a new Document row and opens the artifact panel.
- Update document (versioning): updateDocument creates a new (id, createdAt) row, preserving the previous version.
- Version navigation: Users can navigate between document versions using the timeline dots.
- Document kinds: Text, code, image, and sheet documents each render with their specialized editor.
- Suggestions: requestSuggestions generates inline suggestions that can be accepted or rejected.
Sharing and Visibility
- Default private: New chats are created with visibility=“private”.
- Public sharing: Setting visibility to “public” allows anyone with the URL to view (read-only).
- Read-only enforcement: Public viewers cannot send messages or modify the chat.
- Share link: Sharing copies the canonical URL; the URL works for any authenticated or unauthenticated user.
Voting
- Upvote/downvote: Users can vote on assistant messages; votes are upserted (one vote per user per message).
- Vote toggle: Voting again with a different type changes the vote (up→down or vice versa).
- Vote persistence: Votes survive page reload and are fetched alongside messages.
UI/UX
- Model picker: Users can select from available models before sending; selection persists for the chat.
- Sidebar grouping: Chats are grouped by time period (Today, Yesterday, This Week, This Month, Older).
- Optimistic updates: Rename and delete operations appear instant; failed operations revert automatically.
- Empty state: New chats show welcome message with suggested conversation starters.
- Responsive layout: Sidebar collapses on mobile; artifact panel overlays on narrow screens.
- Theme support: Light/dark mode toggle via
next-themes; persists preference. - Keyboard shortcuts: Enter to send, Shift+Enter for newline, Escape to close artifact panel.