{"slug":"developers/L1_CHAT_SHELL_IMPLEMENTATION","title":"L1 Chat Shell: First-Class Chat Interface","section":"developers","sectionLabel":"Developers","status":"unclassified","type":"document","path":"developers/L1_CHAT_SHELL_IMPLEMENTATION.mdx","bytes":11264,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n> **Tier C — Historical.** This document is a point-in-time snapshot preserved for reference. For current architecture, see [CANONICAL_PLATFORM_ARCHITECTURE.md](../architecture/CANONICAL_PLATFORM_ARCHITECTURE.md).\n\n**Context-Aware AI Chat with Spine Integration**\n\n---\n\n## Overview\n\nThe **L1 Chat Shell** is a first-class Next.js chat interface that:\n- Has full context of user's Spine data (events, memory, entities)\n- Routes intelligently to multiple AI models (GPT-4o, Claude 3, etc.)\n- Generates actionable tasks from conversations\n- Maintains thread history with memory scopes\n- Syncs with OpenWebUI for multi-platform access\n- Becomes the primary entry point for \"ask AI about anything\"\n\n---\n\n## Architecture\n\n```\n┌─────────────────────────────────────────┐\n│  User Interface (Chat Shell)            │\n│  • Thread management                    │\n│  • Message display + formatting         │\n│  • Context panel (Spine, Models, Memory)│\n│  • Quick actions (Tasks, Summary, etc.) │\n└──────────────────────┬──────────────────┘\n                       │\n                       ▼\n┌─────────────────────────────────────────┐\n│  API Layer (/api/chat)                  │\n│  • Message validation                   │\n│  • Session authentication               │\n│  • Request routing                      │\n│  • Response formatting                  │\n└──────────────────────┬──────────────────┘\n                       │\n        ┌──────────────┼──────────────┐\n        ▼              ▼              ▼\n    ┌────────┐    ┌────────┐    ┌─────────────┐\n    │ Spine  │    │ Memory │    │ Core Engine │\n    │ Events │    │ Scopes │    │ (AI Router) │\n    └────────┘    └────────┘    └─────────────┘\n        │              │              │\n        └──────────────┼──────────────┘\n                       │\n                       ▼\n        ┌─────────────────────────────┐\n        │  Task Generation + Insights │\n        └─────────────────────────────┘\n```\n\n---\n\n## Files Added\n\n### 1. **Page Route**\n**Location:** `apps/web/app/(app)/chat/page.tsx`\n\n- Entry point for the chat interface\n- Validates user session (requires authentication)\n- Passes user context to chat component\n- Server-side rendering with dynamic content\n\n### 2. **Chat Shell Component**\n**Location:** `apps/web/components/views/chat-shell-view.tsx` (467 lines)\n\n**Features:**\n- **Thread Management**: Create, switch, delete conversations\n- **Message Display**: User/assistant messages with rich formatting\n- **Spine Context Panel**: Shows live connection status, memory scopes, AI models\n- **Quick Actions**: Extract tasks, summarize, find connections\n- **Multi-line Input**: Shift+Enter for long messages\n- **Auto-scroll**: Messages auto-scroll to bottom\n- **Message Metadata**: Sources, actions, suggested next steps\n\n**Key Components:**\n```typescript\ninterface Message {\n  id: string\n  role: \"user\" | \"assistant\"\n  content: string\n  timestamp: Date\n  sources?: string[]      // Where data came from\n  actions?: string[]      // Suggested next steps\n}\n\ninterface ChatThread {\n  id: string\n  title: string\n  messages: Message[]\n  createdAt: Date\n  updatedAt: Date\n}\n```\n\n### 3. **Chat API Route**\n**Location:** `apps/web/app/api/chat/route.ts`\n\n**Endpoints:**\n\n```typescript\nPOST /api/chat\n  Request: { messages: Message[], threadId, userId }\n  Response: {\n    role: \"assistant\"\n    content: string\n    sources: string[]           // Spine, Memory, Task Engine\n    actions: string[]           // Create Task, Update Memory, etc.\n    metadata: {\n      threadId, userId, model, latency, tokensUsed\n    }\n  }\n\nGET /api/chat?threadId=...&limit=50&offset=0\n  Returns paginated chat history for a thread\n```\n\n**Flow:**\n1. Validate user session (authentication required)\n2. Query Spine for context (events, memory, entities)\n3. Route to appropriate AI model based on query type\n4. Generate response with sources + actions\n5. Store in chat history (database)\n6. Return to client with metadata\n\n### 4. **Sidebar Navigation Update**\n**Location:** `apps/web/components/sidebar.tsx`\n\nAdded \"Chat with Spine\" link to Core navigation section:\n```typescript\n{renderLink(\"/chat\", <MessageSquare className=\"h-5 w-5\" />, \"Chat with Spine\")}\n```\n\n---\n\n## Integration with Core Engine\n\nThe Chat Shell connects to the **integratewise-core-engine** via:\n\n```typescript\n// 1. Event Ingestion\nGET /events              // Get recent events from all sources\nGET /events/:source      // Get events by source (Stripe, Slack, etc.)\n\n// 2. AI Routing\nPOST /ai/route           // Route to appropriate model\n                         // Input: event, context\n                         // Output: task + insights\n\n// 3. Task Generation\n// Tasks from Core Engine displayed in Chat\n// User can create tasks directly from chat responses\n\n// 4. Memory Scopes\n// Org, Work, Personal, Audit all accessible\n// Chat maintains context across scopes\n```\n\n---\n\n## Integration with Spine\n\nThe Chat Shell queries the Spine database for:\n\n```sql\n-- Recent events (all sources)\nSELECT * FROM spine_events \nORDER BY created_at DESC \nLIMIT 100;\n\n-- Events by source\nSELECT * FROM spine_events \nWHERE source = 'stripe' \nORDER BY created_at DESC;\n\n-- AI tasks generated\nSELECT * FROM ai_tasks \nWHERE event_id IN (...)\nORDER BY created_at DESC;\n\n-- Memory access\n-- (scope: org, work, personal, audit)\n```\n\n---\n\n## Context Awareness\n\n### What the Chat Knows\n\n1. **User Profile**\n   - Name, email, tenant ID\n   - Permissions + access control\n   - Preferences + settings\n\n2. **Recent Events** (Last 100)\n   - Stripe payments\n   - Slack mentions\n   - GitHub PRs\n   - Notion updates\n   - HubSpot deals\n   - + all other integrated sources\n\n3. **Memory Scopes**\n   - Org: Team insights, company goals\n   - Work: Project context, goals\n   - Personal: User reflections, goals\n   - Audit: Compliance trail\n\n4. **Generated Tasks**\n   - From events (automated)\n   - From conversations (manual)\n   - Status + priority\n\n### Example Queries\n\n**\"What are my top risks?\"**\n→ Queries Spine for negative events (churn, missed deals, errors)\n→ Routes to GPT-4o (complex analysis)\n→ Returns risks + suggested actions\n\n**\"Summarize this week\"**\n→ Gets all events from last 7 days\n→ Extracts patterns + highlights\n→ Routes to Claude 3 (fast + comprehensive)\n→ Returns weekly summary\n\n**\"Extract tasks from my messages\"**\n→ Analyzes recent Slack/Discord messages\n→ Identifies actionable items\n→ Routes to GPT-4o-mini (task extraction)\n→ Generates task objects + due dates\n\n---\n\n## OpenWebUI Sync\n\nFor OpenWebUI synchronization:\n\n```typescript\n// 1. Export Chat History\nGET /api/chat/export?threadId=...\n  Returns: Standard OpenWebUI format (JSONL)\n\n// 2. Import from OpenWebUI\nPOST /api/chat/import\n  Input: OpenWebUI thread format\n  Action: Create thread in IntegrateWise\n\n// 3. Real-time Sync\n// WebSocket connection (optional)\n// Keep chat history in sync across platforms\n```\n\n---\n\n## Features & Use Cases\n\n### 1. **Context-Aware Conversation**\n- Chat remembers all events, memory, tasks\n- Provides source citations for all statements\n- Suggests next steps automatically\n\n### 2. **Task Extraction**\n- \"Extract tasks from my last 10 messages\"\n- Auto-generates title, description, due date, priority\n- Stores in task system\n\n### 3. **Multi-Threading**\n- Start new conversations\n- Switch between threads\n- Thread history preserved\n- Quick search + filter\n\n### 4. **Quick Actions**\n```\n• Extract Tasks       → Analyze content + generate tasks\n• Summarize          → Condense long content\n• Find Connections   → Link to related entities\n• Draft Response     → AI drafts email/message\n• Create Proposal    → Generate business proposal\n```\n\n### 5. **Spine Context Panel**\n- Shows live Spine connection status\n- Displays active memory scopes\n- Shows which AI models are available\n- Token usage + latency metrics\n\n---\n\n## Deployment\n\n### Prerequisites\n- Neon database with spine_events + ai_tasks tables\n- Core Engine deployed (CF Workers)\n- Authentication configured (Clerk)\n\n### Environment Variables\n```env\n# Core Engine\nCORE_ENGINE_API_URL=https://core-engine.integratewise.com\nCORE_ENGINE_API_KEY=...\n\n# Spine Database (via gateway)\nSPINE_DATABASE_URL=...\n\n# AI Models\nOPENAI_API_KEY=...\nANTHROPIC_API_KEY=...\n\n# OpenWebUI Sync (optional)\nOPENWEBUI_API_URL=https://openwebui.integratewise.com\nOPENWEBUI_API_KEY=...\n```\n\n### Build & Deploy\n```bash\n# Install dependencies\nnpm install\n\n# Build\nnpm run build\n\n# Type check\ntsc --noEmit\n\n# Deploy to Vercel\nvercel deploy\n```\n\n---\n\n## Future Enhancements\n\n### Phase 1 (Current)\n- [x] Basic chat interface\n- [x] Thread management\n- [x] Context panel (Spine info)\n- [x] API routes (stubs)\n\n### Phase 2 (Next)\n- [ ] Wire Core Engine integration\n- [ ] Add chat history persistence\n- [ ] Implement task generation\n- [ ] Add file upload support\n\n### Phase 3 (Advanced)\n- [ ] Voice input + output\n- [ ] Image generation from chat\n- [ ] Collaborative chats (multiple users)\n- [ ] Chat analytics + insights\n- [ ] OpenWebUI full sync\n\n### Phase 4 (Enterprise)\n- [ ] Custom instructions per user\n- [ ] Chat guardrails + compliance\n- [ ] Audit logging\n- [ ] Rate limiting + quotas\n- [ ] Multi-tenant isolation\n\n---\n\n## Integration Timeline\n\n**Week 1: This Week**\n- ✓ Chat Shell UI complete\n- ✓ API routes scaffolded\n- ✓ Sidebar navigation added\n\n**Week 2**\n- Wire Core Engine /events API\n- Add Spine database queries\n- Implement AI routing selection\n\n**Week 3**\n- Add chat history persistence\n- Connect to task generation\n- Implement memory scope access\n\n**Week 4**\n- Add file upload + processing\n- Implement voice input\n- Add analytics + metrics\n\n---\n\n## Technical Stack\n\n| Component | Technology | Version |\n|-----------|-----------|---------|\n| Framework | Next.js | 16 |\n| Language | TypeScript | 5.0 |\n| UI Library | shadcn/ui | Latest |\n| Database | Neon Postgres | - |\n| API | CF Workers | - |\n| AI Models | Multi (OpenAI, Anthropic) | - |\n| State | React hooks + component state | - |\n| Styling | Tailwind CSS | Latest |\n\n---\n\n## Success Metrics\n\n- Chat becomes primary entry point for AI queries\n- 80%+ of users using chat weekly\n- Average response time < 2 seconds\n- User satisfaction > 4.5/5\n- Task generation accuracy > 90%\n- Spike in daily active users\n\n---\n\n*Implementation: L1 Chat Shell*\n*Status: UI Complete, API Scaffolded, Ready for Core Engine Integration*\n*Next: Wire Chat Shell to Core Engine (Week 2)*\n\n"}