:   Cpu,\n4:   Plus,\n5:   Send,\n6:   ShieldCheck,\n7:   Zap,\n8:   Sparkles,\n9:   BotMessageSquare,\n10:   MessageSquare,\n11:   DollarSign,\n12:   Activity,\n13:   Key,\n14:   X,\n15:   RefreshCw,\n16:   Sliders,\n17: } from 'lucide-react';\n18: \n19: interface AIAgentItem {\n20:   id: string;\n21:   name: string;\n22:   provider: 'openai' | 'openrouter';\n23:   model: string;\n24:   systemPrompt: string;\n25:   temperature: number;\n26:   maxTokens: number;\n27:   isActive: boolean;\n28:   totalTokens: number;\n29: }\n30: \n31: interface ChatMessage {\n32:   role: 'user' | 'assistant';\n33:   content: string;\n34:   tokens?: number;\n35:   costCents?: number;\n36: }\n37: \n38: const INITIAL_AGENTS: AIAgentItem[] = [\n39:   {\n40:     id: 'agent-1',\n41:     name: 'Customer Concierge & Support',\n42:     provider: 'openai',\n43:     model: 'gpt-4o-mini',\n44:     systemPrompt: 'You are a luxury customer concierge for our Telegram bot SaaS platform. Be concise, polite, and helpful.',\n45:     temperature: 0.6,\n46:     maxTokens: 800,\n47:     isActive: true,\n48:     totalTokens: 421000,\n49:   },\n50:   {\n51:     id: 'agent-2',\n52:     name: 'Autonomous Sales & Onboarding',\n53:     provider: 'openrouter',\n54:     model: 'anthropic/claude-3.5-sonnet',\n55:     systemPrompt: 'You are an enterprise sales advisor. Explain subscription tiers, pricing, and bot automation capabilities.',\n56:     temperature: 0.7,\n57:     maxTokens: 1200,\n58:     isActive: true,\n59:     totalTokens: 229000,\n60:   },\n61: ];\n62: \n63: export const AIAgentsPage: React.FC = () => {\n64:   const [agents, setAgents] = useState<AIAgentItem[]>(INITIAL_AGENTS);\n65:   const [selectedAgent, setSelectedAgent] = useState<AIAgentItem>(INITIAL_AGENTS[0]);\n66:   const [isNewAgentOpen, setIsNewAgentOpen] = useState(false);\n67:   const [isKeysVaultOpen, setIsKeysVaultOpen] = useState(false);\n68: \n69:   // Key vault state\n70:   const [keys, setKeys] = useState([\n71:     { id: 'k-1', provider: 'openai', name: 'OpenAI Production Key', masked: 'sk-proj...9f21' },\n72:     { id: 'k-2', provider: 'openrouter', name: 'OpenRouter Claude Key', masked: 'sk-or...b401' },\n73:   ]);\n74: \n75:   // Chat testing console state\n76:   const [chatMessages, setChatMessages] = useState<ChatMessage[]>([\n77:     {\n78:       role: 'assistant',\n79:       content: 'Greetings. I am your autonomous AI Concierge. How may I assist your Telegram bot subscribers today?',\n80:       tokens: 28,\n81:       costCents: 0.001,\n82:     },\n83:   ]);\n84:   const [chatInput, setChatInput] = useState('');\n85:   const [isChatting, setIsChatting] = useState(false);\n86: \n87:   const handleSendMessage = async (e: React.FormEvent) => {\n88:     e.preventDefault();\n89:     if (!chatInput.trim() || isChatting) return;\n90: \n91:     const userText = chatInput.trim();\n92:     setChatInput('');\n93:     setChatMessages((prev) => [...prev, { role: 'user', content: userText }]);\n94:     setIsChatting(true);\n95: \n96:     try {\n97:       const res = await fetch(`/api/v1/ai/agents/${selectedAgent.id}/chat`, {\n98:         method: 'POST',\n99:         headers: { 'Content-Type': 'application/json' },\n100:         body: JSON.stringify({ message: userText }),"}
{"step_index":5452,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T15:31:48Z","model":"gemini-3.8-flash-high","input_tokens":2620,"cache_read_tokens":167133,"output_tokens":131,"tool_calls":[{"name":"read_file","args":{"EndLine":80,"Path":"/root/telegram-saas/apps/frontend/src/components/pages/PluginsPage.tsx","StartLine":1}}]}
{"step_index":5453,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T15:31:52Z","content":"Created At: 2026-11-18T15:31:52Z\nCompleted At: 2026-11-18T15:31:53Z\nCreated At: 2026-11-18T15:31:52Z\nCompleted At: 2026-11-18T15:31:53Z\nShowing lines 1-80 of 290\n1: import React, { useState } from 'react';\n2: import {\n3:   ToyBrick,\n4:   CheckCircle2,\n5:   Sliders,\n6:   Play,\n7:   ShieldCheck,\n8:   Terminal,\n9:   Activity,\n10:   Layers,\n11:   Sparkles,\n12:   RefreshCw,\n13:   X,\n14: } from 'lucide-react';\n15: \n16: interface PluginCard {\n17:   id: string;\n18:   name: string;\n19:   category: string;\n20:   version: string;\n21:   description: string;\n22:   permissions: string[];\n23:   isInstalled: boolean;\n24:   defaultConfig: any;\n25: }\n26: \n27: const CORE_PLUGINS: PluginCard[] = [\n28:   {\n29:     id: 'welcome_captcha',\n30:     name: 'Welcome Math & Button CAPTCHA',\n31:     category: 'security',\n32:     version: '1.2.0',\n33:     description: 'Enforces interactive anti-bot verification when new members join Telegram groups before unmuting.',\n34:     permissions: ['messages:write', 'users:read'],\n35:     isInstalled: true,\n36:     defaultConfig: { timeout_seconds: 60, difficulty: 'easy' },\n37:   },\n38:   {\n39:     id: 'crypto_price_tracker',\n40:     name: 'Crypto Price & Threshold Alerts',\n41:     category: 'finance',\n42:     version: '2.0.1',\n43:     description: 'Provides live /price <symbol> command quotes and automated broadcast alerts for BTC, ETH, and TON.',\n44:     permissions: ['messages:write', 'external:http'],\n45:     isInstalled: true,\n46:     defaultConfig: { default_currency: 'USD', coins: ['BTC', 'ETH', 'TON'] },\n47:   },\n48:   {\n49:     id: 'sentiment_analyzer',\n50:     name: 'Real-Time Sentiment & Escalate',\n51:     category: 'ai',\n52:     version: '1.0.4',\n53:     description: 'Analyzes user chat sentiment (positive, neutral, negative) and auto-flags angry messages for VIP support.',\n54:     permissions: ['messages:read', 'messages:write'],\n55:     isInstalled: false,\n56:     defaultConfig: { negative_threshold: 0.7, auto_escalate: true },\n57:   },\n58:   {\n59:     id: 'auto_support_router',\n60:     name: 'Intelligent Support FAQ Router',\n61:     category: 'support',\n62:     version: '1.4.0',\n63:     description: 'Keyword-based dynamic FAQ matching with instant handoff to live human operator queue.',\n64:     permissions: ['messages:read', 'messages:write'],\n65:     isInstalled: false,\n66:     defaultConfig: { trigger_keywords: ['help', 'refund', 'agent'] },\n67:   },\n68: ];\n69: \n70: export const PluginsPage: React.FC = () => {\n71:   const [plugins, setPlugins] = useState<PluginCard[]>(CORE_PLUGINS);\n72:   const [selectedPlugin, setSelectedPlugin] = useState<PluginCard>(CORE_PLUGINS[1]);\n73:   const [hookCommand, setHookCommand] = useState('price');\n74:   const [hookArg, setHookArg] = useState('BTC');\n75:   const [hookOutput, setHookOutput] = useState<any>({\n76:     symbol: 'BTC',\n77:     price_usd: 96450.0,\n78:     formatted: '$96,450.00',\n79:     '24h_change': '+3.45%',\n80:     source: 'Sandboxed In-Memory Crypto Mock Engine',"}
{"step_index":5454,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T15:31:53Z","model":"gemini-3.8-flash-high","input_tokens":170967,"cache_read_tokens":0,"output_tokens":87,"tool_calls":[{"name":"read_file","args":{"EndLine":100,"Path":"/root/telegram-saas/apps/frontend/src/components/pages/BotBuilderPage.tsx","StartLine":1}}]}
{"step_index":5455,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T15:31:58Z","content":"Created At: 2026-11-18T15:31:58Z\nCompleted At: 2026-11-18T15:31:59Z\nCreated At: 2026-11-18T15:31:58Z\nCompleted At: 2026-11-18T15:31:59Z\nShowing lines 1-100 of 640\n1: import React, { useState } from 'react';\n2: import {\n3:   Wand2,\n4:   Workflow,\n5:   Sparkles,\n6:   Bot,\n7:   Play,\n8:   CheckCircle2,\n9:   ArrowRight,\n10:   Server,\n11:   Cpu,\n12:   Layers,\n13:   Send,\n14:   Sliders,\n15:   Shield,\n16:   Activity,\n17:   AlertCircle,\n18:   Copy,\n19:   Check,\n20:   Zap,\n21: } from 'lucide-react';\n22: \n23: interface WorkflowNodeData {\n24:   id: string;\n25:   type: 'trigger' | 'ai_agent' | 'mcp_tool' | 'channel_action';\n26:   label: string;\n27:   subtitle: string;\n28:   config: Record<string, any>;\n29:   status?: 'idle' | 'running' | 'success' | 'failed';\n30:   latency_ms?: number;\n31: }\n32: \n33: interface ProposalData {\n34:   bot_name: string;\n35:   headline: string;\n36:   category: string;\n37:   matched_blueprint: string;\n38:   system_prompt: string;\n39:   selected_modules: string[];\n40:   selected_mcp_tools: string[];\n41:   preview_text: string;\n42: }\n43: \n44: const SAMPLE_PROPOSALS: Record<string, ProposalData> = {\n45:   support: {\n46:     bot_name: 'Customer Support Desk',\n47:     headline: 'Automated 24/7 Telegram customer helpdesk with instant answers and human escalation.',\n48:     category: 'Business Operations',\n49:     matched_blueprint: 'bot_customer_support',\n50:     system_prompt:\n51:       'You are the Customer Support Assistant for our Telegram SaaS platform. Greet customers warmly, resolve billing or account inquiries, and create escalation tickets for human support when requested.',\n52:     selected_modules: ['welcome_message', 'user_management', 'ai_assistant'],\n53:     selected_mcp_tools: ['message.send', 'analytics.report', 'tickets.create'],\n54:     preview_text:\n55:       '🎧 <b>Customer Support Portal</b>\\n\\n' +\n56:       'Hello <b>{first_name}</b>! How can we help you today?\\n\\n' +\n57:       '• <b>Agent Status</b>: 🟢 24/7 Online\\n' +\n58:       '• <b>Average Response</b>: ⚡ Instant (< 1s)\\n' +\n59:       '• <b>Ticket SLA</b>: Under 15 minutes\\n\\n' +\n60:       'Type your query below or tap an option to proceed:',\n61:   },\n62:   ecommerce: {\n63:     bot_name: 'Digital Store & Checkout Bot',\n64:     headline: 'High-converting Telegram storefront with catalog browsing and Razorpay/Stripe checkout.',\n65:     category: 'E-Commerce',\n66:     matched_blueprint: 'bot_ecommerce_concierge',\n67:     system_prompt:\n68:       'You are the Digital Store Concierge. Guide shoppers through product tiers, compute discounts with valid coupon codes, and issue secure payment invoices using server-side webhook confirmation.',\n69:     selected_modules: ['welcome_message', 'payments', 'subscriptions'],\n70:     selected_mcp_tools: ['payments.checkout', 'message.send'],\n71:     preview_text:\n72:       '🛍️ <b>Welcome to Digital Store</b>\\n\\n' +\n73:       'Browse our catalog and checkout in seconds without leaving Telegram:\\n\\n' +\n74:       '• <b>Catalog</b>: 120 Products Available\\n' +\n75:       '• <b>Payments</b>: 💳 UPI, Razorpay & Stripe\\n' +\n76:       '• <b>Delivery</b>: Instant Digital Access\\n\\n' +\n77:       'Tap below to browse the store catalog:',\n78:   },\n79:   crypto: {\n80:     bot_name: 'Market Sentinel & Price Alerts',\n81:     headline: 'Real-time multi-exchange rate tracker with customizable Telegram volatility alerts.',\n82:     category: 'Fintech & Tools',\n83:     matched_blueprint: 'bot_uptime_monitor',\n84:     system_prompt:\n85:       'You are the Market Sentinel. Monitor BTC, ETH, and SOL liquidity pools, execute automated price checks via verified MCP servers, and broadcast instantaneous breakout alerts.',\n86:     selected_modules: ['broadcasts', 'auto_filter', 'user_management'],\n87:     selected_mcp_tools: ['analytics.report', 'message.send'],\n88:     preview_text:\n89:       '📈 <b>Market Sentinel 24/7</b>\\n\\n' +\n90:       'Live crypto market telemetry active:\\n\\n' +\n91:       '• <b>BTC/USDT</b>: 🟢 $94,210 (+3.4% 24h)\\n' +\n92:       '• <b>ETH/USDT</b>: 🟢 $3,180 (+2.1% 24h)\\n' +\n93:       '• <b>Alert Threshold</b>: ±2.5% Volatility\\n\\n' +\n94:       'Tap below to configure customized price notifications:',\n95:   },\n96: };\n97: \n98: const DEFAULT_FLOW_NODES: WorkflowNodeData[] = [\n99:   {\n100:     id: 'node-1',"}
{"step_index":5456,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T15:31:59Z","model":"gemini-3.8-flash-high","input_tokens":2663,"cache_read_tokens":169887,"output_tokens":909,"thinking":"The `BotBuilderPage.tsx` component appears to be a visual workflow tool linked to the active bot context. The user's request highlights an issue related to \"all page\" functionality, indicating a potential problem with how this component handles navigation or interaction across different pages. Examining how the tool interacts with the specified URLs might reveal the issue.\n\n\nThe marketplace page presents styling and functionality issues; it lacks the expected bot context integration and exhibits outdated theming. The studio page has a double header, hardcoded color schemes, and responsiveness problems. All remaining pages within the SaaS need to be audited for consistent Telegram styling, bot context integration, and layout responsiveness.\n\n\n","tool_calls":[{"name":"read_file","args":{"EndLine":700,"Path":"/root/telegram-saas/apps/frontend/src/components/pages/MarketplacePage.tsx","StartLine":580}}]}
{"step_index":5457,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T15:32:09Z","content":"Created At: 2026-11-18T15:32:09Z\nCompleted At: 2026-11-18T15:32:09Z\nCreated At: 2026-11-18T15:32:09Z\nCompleted At: 2026-11-18T15:32:09Z\nShowing lines 580-700 of 1043\n580:     const botUser = selectedTargetBot === 'new_bot' ? '@new_cloud_bot' : `@${selectedTargetBot}`;\n581:     const newInst: InstalledInstance = {\n582:       id: `inst-${Date.now()}`,\n583:       name: instanceNameInput || installingBlueprint.name,\n584:       templateId: installingBlueprint.id,\n585:       templateName: installingBlueprint.name,\n586:       category: installingBlueprint.category,\n587:       status: 'deployed',\n588:       botUsername: botUser,\n589:       uptimePct: 100.0,\n590:       interactionsCount: 0,\n591:       installedAt: new Date().toISOString(),\n592:     };\n593:     setInstalledList([newInst, ...installedList]);\n594:     setInstallingBlueprint(null);\n595:     setInstallSuccessMessage(`Template \"${installingBlueprint.name}\" successfully deployed to ${botUser} with 24/7 cloud runtime & modules provisioned!`);\n596:     setTimeout(() => setInstallSuccessMessage(null), 5000);\n597:   };\n598: \n599:   return (\n600:     <div className=\"space-y-6 sm:space-y-8 animate-fadeIn w-full max-w-full min-w-0\">\n601:       {/* Header Banner */}\n602:       <div className=\"relative overflow-hidden rounded-2xl bg-gradient-to-r from-[#0C1222] via-[#0F172A] to-[#0A0E1A] border border-white/10 p-4 sm:p-6 md:p-8 shadow-2xl\">\n603:         <div className=\"absolute -right-16 -top-16 w-80 h-80 bg-[#D4AF37]/10 rounded-full blur-3xl pointer-events-none\" />\n604:         <div className=\"relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-4 sm:gap-6\">\n605:           <div>\n606:             <div className=\"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-amber-500/10 border border-amber-400/30 text-amber-300 text-xs font-medium uppercase tracking-wider mb-2 sm:mb-3\">\n607:               <Sparkles className=\"w-3.5 h-3.5\" />\n608:               Telegram Bot Cloud Platform\n609:             </div>\n610:             <h1 className=\"text-2xl sm:text-3xl font-semibold tracking-tight text-white\">\n611:               Ready-Made Bot <span className=\"text-amber-400 font-semibold\">Templates</span>\n612:             </h1>\n613:             <p className=\"text-slate-300 text-xs sm:text-sm mt-1 max-w-2xl font-normal leading-relaxed\">\n614:               No VPS, no server configuration, zero coding headaches. Choose from 25 production-ready bot blueprints, customize credentials, and launch on managed cloud infrastructure with 24/7 uptime.\n615:             </p>\n616:           </div>\n617:           <div className=\"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3 w-full md:w-auto shrink-0\">\n618:             <button\n619:               onClick={() => setActiveTab('catalog')}\n620:               className={`px-4 sm:px-5 py-2.5 rounded-xl text-xs font-medium uppercase tracking-wider transition-all flex items-center justify-center gap-2 ${\n621:                 activeTab === 'catalog'\n622:                   ? 'bg-[#D4AF37] text-black shadow-lg shadow-[#D4AF37]/20 font-semibold'\n623:                   : 'bg-white/5 text-white/70 hover:bg-white/10 border border-white/10'\n624:               }`}\n625:             >\n626:               <Store className=\"w-4 h-4\" />\n627:               <span>Explore Catalog ({BLUEPRINTS_CATALOG.length})</span>\n628:             </button>\n629:             <button\n630:               onClick={() => setActiveTab('installed')}\n631:               className={`px-4 sm:px-5 py-2.5 rounded-xl text-xs font-medium uppercase tracking-wider transition-all flex items-center justify-center gap-2 ${\n632:                 activeTab === 'installed'\n633:                   ? 'bg-[#D4AF37] text-black shadow-lg shadow-[#D4AF37]/20 font-semibold'\n634:                   : 'bg-white/5 text-white/70 hover:bg-white/10 border border-white/10'\n635:               }`}\n636:             >\n637:               <PackageCheck className=\"w-4 h-4\" />\n638:               <span>Active Deployments ({installedList.length})</span>\n639:             </button>\n640:           </div>\n641:         </div>\n642: \n643:         {/* Global Key Metrics */}\n644:         <div className=\"grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mt-6 sm:mt-8 pt-5 sm:pt-6 border-t border-white/10\">\n645:           <div>\n646:             <p className=\"text-[10px] sm:text-xs text-white/40 uppercase tracking-wider\">Production Blueprints</p>\n647:             <p className=\"text-lg sm:text-xl font-light text-white mt-1\">25 Verified</p>\n648:           </div>\n649:           <div>\n650:             <p className=\"text-[10px] sm:text-xs text-white/40 uppercase tracking-wider\">Reusable Modules</p>\n651:             <p className=\"text-lg sm:text-xl font-light text-[#D4AF37] mt-1\">8 Plug-and-Play</p>\n652:           </div>\n653:           <div>\n654:             <p className=\"text-[10px] sm:text-xs text-white/40 uppercase tracking-wider\">Cloud Runtime SLA</p>\n655:             <p className=\"text-lg sm:text-xl font-light text-emerald-400 mt-1\">99.98% 24/7</p>\n656:           </div>\n657:           <div>\n658:             <p className=\"text-[10px] sm:text-xs text-white/40 uppercase tracking-wider\">Setup Overhead</p>\n659:             <p className=\"text-lg sm:text-xl font-light text-white mt-1\">0 Server / VPS</p>\n660:           </div>\n661:         </div>\n662:       </div>\n663: \n664:       {/* Success Alert Banner */}\n665:       {installSuccessMessage && (\n666:         <div className=\"p-3.5 sm:p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-xs sm:text-sm flex items-center justify-between\">\n667:           <div className=\"flex items-center gap-2\">\n668:             <CheckCircle2 className=\"w-5 h-5 text-emerald-400 shrink-0\" />\n669:             <span>{installSuccessMessage}</span>\n670:           </div>\n671:           <button onClick={() => setInstallSuccessMessage(null)} className=\"text-emerald-400 hover:text-white p-1\">\n672:             <X className=\"w-4 h-4\" />\n673:           </button>\n674:         </div>\n675:       )}\n676: \n677:       {/* TAB 1: BROWSE CATALOG */}\n678:       {activeTab === 'catalog' && (\n679:         <div className=\"space-y-6\">\n680:           {/* Search & Categories Bar */}\n681:           <div className=\"flex flex-col md:flex-row items-stretch md:items-center justify-between gap-3 sm:gap-4\">\n682:             {/* Category Pills */}\n683:             <div className=\"flex items-center gap-2 overflow-x-auto w-full md:w-auto pb-2 md:pb-0 scrollbar-none\">\n684:               {categories.map((cat) => (\n685:                 <button\n686:                   key={cat.id}\n687:                   onClick={() => setSelectedCategory(cat.id)}\n688:                   className={`px-3.5 sm:px-4 py-2 rounded-xl text-xs whitespace-nowrap tracking-wider uppercase transition-all shrink-0 ${\n689:                     selectedCategory === cat.id\n690:                       ? 'bg-white/15 text-white font-medium border border-[#D4AF37]/50 shadow-sm'\n691:                       : 'bg-[#0B0F19]/40 text-white/50 hover:text-white hover:bg-white/5 border border-white/5'\n692:                   }`}\n693:                 >\n694:                   {cat.name} ({cat.count})\n695:                 </button>\n696:               ))}\n697:             </div>\n698: \n699:             {/* Search Input */}\n700:             <div className=\"relative w-full md:w-72 shrink-0\">"}
{"step_index":5458,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T15:32:09Z","model":"gemini-3.8-flash-high","input_tokens":3411,"cache_read_tokens":172562,"output_tokens":111,"tool_calls":[{"name":"read_file","args":{"EndLine":1043,"Path":"/root/telegram-saas/apps/frontend/src/components/pages/MarketplacePage.tsx","StartLine":850}}]}
{"step_index":5459,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T15:32:14Z","content":"Created At: 2026-11-18T15:32:14Z\nCompleted At: 2026-11-18T15:32:14Z\nCreated At: 2026-11-18T15:32:14Z\nCompleted At: 2026-11-18T15:32:14Z\nShowing lines 850-1043 of 1043\n850:           </div>\n851:         </div>\n852:       )}\n853: \n854:       {/* QUICK PREVIEW MODAL */}\n855:       {selectedBlueprint && (\n856:         <div className=\"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md animate-fadeIn\">\n857:           <div className=\"relative w-full max-w-2xl rounded-2xl bg-[#0B0F19] border border-white/15 p-4 sm:p-6 md:p-8 shadow-2xl overflow-y-auto max-h-[90vh]\">\n858:             <button\n859:               onClick={() => setSelectedBlueprint(null)}\n860:               className=\"absolute right-3 sm:right-5 top-3 sm:top-5 p-2 rounded-xl bg-white/5 hover:bg-white/10 text-white/60 hover:text-white transition-all\"\n861:             >\n862:               <X className=\"w-4 h-4\" />\n863:             </button>\n864: \n865:             <div className=\"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6 pr-8\">\n866:               <div className=\"w-12 h-12 sm:w-14 sm:h-14 rounded-2xl bg-[#D4AF37]/10 border border-[#D4AF37]/30 flex items-center justify-center text-[#D4AF37] shrink-0\">\n867:                 <selectedBlueprint.icon className=\"w-6 h-6 sm:w-7 sm:h-7\" />\n868:               </div>\n869:               <div className=\"min-w-0\">\n870:                 <span className=\"text-[10px] sm:text-xs uppercase tracking-wider text-[#D4AF37] font-medium\">\n871:                   {selectedBlueprint.category.replace('_', ' ')}\n872:                 </span>\n873:                 <h2 className=\"text-lg sm:text-xl font-light text-white truncate\">{selectedBlueprint.name}</h2>\n874:                 <p className=\"text-[11px] sm:text-xs text-white/50 mt-0.5\">Version {selectedBlueprint.version} • Verified Blueprint</p>\n875:               </div>\n876:             </div>\n877: \n878:             <div className=\"space-y-4 sm:space-y-6 text-xs text-white/80 font-light leading-relaxed\">\n879:               <div>\n880:                 <h4 className=\"text-white uppercase tracking-wider text-[11px] font-medium mb-1.5\">Overview</h4>\n881:                 <p className=\"text-white/60\">{selectedBlueprint.description}</p>\n882:               </div>\n883: \n884:               <div>\n885:                 <h4 className=\"text-white uppercase tracking-wider text-[11px] font-medium mb-1.5\">Required Permissions</h4>\n886:                 <div className=\"flex flex-wrap gap-1.5 sm:gap-2\">\n887:                   {selectedBlueprint.permissions.map((p) => (\n888:                     <span key={p} className=\"px-2.5 py-1 rounded-md bg-white/5 border border-white/10 text-white/70 font-mono text-[10px] sm:text-[11px]\">\n889:                       {p}\n890:                     </span>\n891:                   ))}\n892:                 </div>\n893:               </div>\n894: \n895:               {selectedBlueprint.mcpTools.length > 0 && (\n896:                 <div>\n897:                   <h4 className=\"text-white uppercase tracking-wider text-[11px] font-medium mb-1.5\">Recommended MCP Tools</h4>\n898:                   <div className=\"flex flex-wrap gap-1.5 sm:gap-2\">\n899:                     {selectedBlueprint.mcpTools.map((t) => (\n900:                       <span key={t} className=\"px-2.5 py-1 rounded-md bg-[#D4AF37]/10 border border-[#D4AF37]/30 text-[#D4AF37] font-mono text-[10px] sm:text-[11px]\">\n901:                         ⚡ {t}\n902:                       </span>\n903:                     ))}\n904:                   </div>\n905:                 </div>\n906:               )}\n907: \n908:               <div className=\"p-3.5 sm:p-4 rounded-xl bg-white/[0.02] border border-white/5\">\n909:                 <h4 className=\"text-white uppercase tracking-wider text-[11px] font-medium mb-1\">Telegram System Templates</h4>\n910:                 <p className=\"text-white/40 text-[11px] mb-2\">Pre-styled decorative templates provided with this bot:</p>\n911:                 <div className=\"flex flex-wrap gap-1.5\">\n912:                   {selectedBlueprint.systemTemplates.map((t) => (\n913:                     <span key={t} className=\"px-2 py-0.5 rounded bg-white/5 text-white/60 text-[10px]\">\n914:                       {t}\n915:                     </span>\n916:                   ))}\n917:                 </div>\n918:               </div>\n919:             </div>\n920: \n921:             <div className=\"mt-6 sm:mt-8 pt-4 sm:pt-6 border-t border-white/10 flex flex-col-reverse sm:flex-row items-stretch sm:items-center sm:justify-end gap-2 sm:gap-3\">\n922:               <button\n923:                 onClick={() => setSelectedBlueprint(null)}\n924:                 className=\"px-5 py-2.5 rounded-xl text-xs text-white/60 hover:text-white text-center\"\n925:               >\n926:                 Close\n927:               </button>\n928:               <button\n929:                 onClick={() => {\n930:                   const b = selectedBlueprint;\n931:                   setSelectedBlueprint(null);\n932:                   handleLaunchInstall(b);\n933:                 }}\n934:                 className=\"px-6 py-2.5 rounded-xl bg-[#D4AF37] text-black text-xs font-semibold uppercase tracking-wider hover:bg-[#F3E5AB] transition-all text-center\"\n935:               >\n936:                 Continue to Deployment →\n937:               </button>\n938:             </div>\n939:           </div>\n940:         </div>\n941:       )}\n942: \n943:       {/* 1-CLICK CLOUD DEPLOY WIZARD MODAL */}\n944:       {installingBlueprint && (\n945:         <div className=\"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md animate-fadeIn\">\n946:           <div className=\"relative w-full max-w-lg rounded-2xl bg-[#0B0F19] border border-white/15 p-4 sm:p-6 md:p-8 shadow-2xl\">\n947:             <button\n948:               onClick={() => setInstallingBlueprint(null)}\n949:               className=\"absolute right-3 sm:right-5 top-3 sm:top-5 p-2 rounded-xl bg-white/5 hover:bg-white/10 text-white/60 hover:text-white transition-all\"\n950:             >\n951:               <X className=\"w-4 h-4\" />\n952:             </button>\n953: \n954:             <div className=\"flex items-center gap-3 mb-4 sm:mb-6 pr-8\">\n955:               <div className=\"w-10 h-10 sm:w-12 sm:h-12 rounded-xl bg-[#D4AF37]/10 border border-[#D4AF37]/30 flex items-center justify-center text-[#D4AF37] shrink-0\">\n956:                 <installingBlueprint.icon className=\"w-5 h-5 sm:w-6 sm:h-6\" />\n957:               </div>\n958:               <div className=\"min-w-0\">\n959:                 <h3 className=\"text-base sm:text-lg font-light text-white truncate\">Deploy to Cloud Runtime</h3>\n960:                 <p className=\"text-xs text-white/50 truncate\">{installingBlueprint.name}</p>\n961:               </div>\n962:             </div>\n963: \n964:             <div className=\"space-y-4\">\n965:               <div>\n966:                 <label className=\"block text-xs font-medium text-white/70 uppercase tracking-wider mb-1.5\">\n967:                   Target Telegram Bot\n968:                 </label>\n969:                 <select\n970:                   value={selectedTargetBot}\n971:                   onChange={(e) => setSelectedTargetBot(e.target.value)}\n972:                   className=\"w-full px-4 py-2.5 rounded-xl bg-[#0F172A] border border-white/10 text-xs text-white focus:outline-none focus:border-[#D4AF37]/50\"\n973:                 >\n974:                   <option value=\"astraea_flagship_bot\">Astraea Flagship Super Bot (@astraea_flagship_bot)</option>\n975:                   <option value=\"vip_concierge_bot\">VIP Concierge & Support (@vip_concierge_bot)</option>\n976:                   <option value=\"flash_billing_bot\">Automated Flash Billing (@flash_billing_bot)</option>\n977:                   <option value=\"omni_broadcast_bot\">Omni Broadcast Announcer (@omni_broadcast_bot)</option>\n978:                   <option value=\"new_bot\">+ Create New Standalone Bot</option>\n979:                 </select>\n980:                 <p className=\"text-[10px] text-[#D4AF37] mt-1 font-mono\">\n981:                   All blueprint modules, triggers & system templates will be provisioned directly to this bot.\n982:                 </p>\n983:               </div>\n984: \n985:               <div>\n986:                 <label className=\"block text-xs font-medium text-white/70 uppercase tracking-wider mb-1.5\">\n987:                   Bot Instance Name\n988:                 </label>\n989:                 <input\n990:                   type=\"text\"\n991:                   value={instanceNameInput}\n992:                   onChange={(e) => setInstanceNameInput(e.target.value)}\n993:                   className=\"w-full px-4 py-2.5 rounded-xl bg-white/5 border border-white/10 text-xs text-white focus:outline-none focus:border-[#D4AF37]/50\"\n994:                   placeholder=\"e.g., My Luxury Boutique Store\"\n995:                 />\n996:               </div>\n997: \n998:               <div>\n999:                 <label className=\"block text-xs font-medium text-white/70 uppercase tracking-wider mb-1.5\">\n1000:                   Cloud Infrastructure Tier\n1001:                 </label>\n1002:                 <div className=\"p-3 rounded-xl bg-white/[0.02] border border-white/10 flex items-center justify-between gap-2\">\n1003:                   <div>\n1004:                     <p className=\"text-xs text-white font-medium\">Shared Cloud Worker Pool</p>\n1005:                     <p className=\"text-[10px] sm:text-[11px] text-white/40\">24/7 Managed Supervisor Loop (Included in Plan)</p>\n1006:                   </div>\n1007:                   <span className=\"text-[10px] px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 font-medium shrink-0\">\n1008:                     ACTIVE\n1009:                   </span>\n1010:                 </div>\n1011:               </div>\n1012: \n1013:               <div className=\"p-3 rounded-xl bg-white/[0.02] border border-white/5 space-y-2\">\n1014:                 <p className=\"text-xs text-white/70 font-medium\">What happens next:</p>\n1015:                 <ul className=\"text-[11px] text-white/50 space-y-1 list-disc pl-4 font-light\">\n1016:                   <li>Blueprint manifest and state tables will be isolated for your tenant.</li>\n1017:                   <li>System templates will be loaded into Message Studio.</li>\n1018:                   <li>Runtime supervisor will auto-recover bot if Telegram restarts.</li>\n1019:                 </ul>\n1020:               </div>\n1021:             </div>\n1022: \n1023:             <div className=\"mt-6 sm:mt-8 pt-4 sm:pt-6 border-t border-white/10 flex flex-col-reverse sm:flex-row items-stretch sm:items-center sm:justify-end gap-2 sm:gap-3\">\n1024:               <button\n1025:                 onClick={() => setInstallingBlueprint(null)}\n1026:                 className=\"px-5 py-2.5 rounded-xl text-xs text-white/60 hover:text-white text-center\"\n1027:               >\n1028:                 Cancel\n1029:               </button>\n1030:               <button\n1031:                 onClick={handleConfirmDeploy}\n1032:                 className=\"px-6 py-2.5 rounded-xl bg-[#D4AF37] text-black text-xs font-semibold uppercase tracking-wider hover:bg-[#F3E5AB] transition-all flex items-center justify-center gap-2 shadow-lg shadow-[#D4AF37]/20\"\n1033:               >\n1034:                 <Play className=\"w-4 h-4 fill-black\" />\n1035:                 <span>Launch 24/7 Cloud Bot</span>\n1036:               </button>\n1037:             </div>\n1038:           </div>\n1039:         </div>\n1040:       )}\n1041:     </div>\n1042:   );\n1043: };"}
{"step_index":5460,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T15:32:14Z","model":"gemini-3.8-flash-high","input_tokens":3879,"cache_read_tokens":175988,"output_tokens":15418,"thinking":"The `MarketplacePage.tsx` component requires integration with the `useBot()` hook. Deployment logic uses the current bot's ID or username as the default target. Deploying a blueprint involves applying its template to the target bot, then replacing specific hex codes and button class names for consistent styling.\n\n\nTelegram-specific styling requires updating the marketplace and message studio components. The marketplace will be updated to use Telegram's blue, slate, and astraea styling conventions. The message studio will undergo similar style replacements, focusing on button, card, and modal theming with the Telegram design system.\n\nThe nested modals within the message studio component will be checked and styled to align with the Telegram theme. This includes button matrix editors, live previews, bot styling, version history, import/export, and emoji custom picker modals.\n\n\n","tool_calls":[{"name":"write_file","args":{"Content":"import React, { useState } from 'react';\nimport { Link, useSearchParams } from 'react-router-dom';\nimport {\n  Store,\n  Sparkles,\n  ShoppingBag,\n  Headphones,\n  UserCheck,\n  Calendar,\n  Receipt,\n  Crown,\n  ShieldAlert,\n  ShieldCheck,\n  KeyRound,\n  Trophy,\n  EyeOff,\n  Share2,\n  Bot,\n  FileText,\n  Image,\n  Code,\n  Database,\n  Mic,\n  GitBranch,\n  Activity,\n  Zap,\n  Terminal,\n  Rss,\n  Newspaper,\n  CheckCircle2,\n  Play,\n  Sliders,\n  X,\n  ExternalLink,\n  Layers,\n  Search,\n  Filter,\n  Cpu,\n  Flame,\n  ArrowUpRight,\n  PackageCheck,\n  Radio,\n  ChevronRight,\n  Check,\n} from 'lucide-react';\nimport { useBot } from '../../context/BotContext';\n\ninterface BotBlueprint {\n  id: string;\n  name: string;\n  headline: string;\n  description: string;\n  category: 'business' | 'community' | 'ai_specialist' | 'developer_tools' | 'content_media';\n  icon: React.ElementType;\n  version: string;\n  rating: number;\n  installCount: number;\n  isFeatured: boolean;\n  tags: string[];\n  permissions: string[];\n  mcpTools: string[];\n  systemTemplates: string[];\n  defaultConfig: Record<string, any>;\n}\n\nconst BLUEPRINTS_CATALOG: BotBlueprint[] = [\n  // 1. Business\n  {\n    id: 'bot_ecommerce_concierge',\n    name: 'E-Commerce & Digital Store Concierge',\n    headline: 'Interactive shopping catalog, cart management & instant Telegram checkout.',\n    description: 'Transforms your Telegram bot into an automated 24/7 digital storefront. Customers can browse categorized products with images, add items to cart, select delivery address, and pay via integrated Razorpay/Stripe checkout without leaving Telegram.',\n    category: 'business',\n    icon: ShoppingBag,\n    version: '1.2.0',\n    rating: 4.95,\n    installCount: 1420,\n    isFeatured: true,\n    tags: ['ecommerce', 'store', 'payments', 'shopping', 'cart'],\n    permissions: ['messages.send', 'payments.create', 'database.read_write'],\n    mcpTools: ['shopify.products.search', 'payments.order.verify', 'shipping.status.get'],\n    systemTemplates: ['welcome', 'catalog', 'cart_view', 'invoice', 'order_status'],\n    defaultConfig: { store_name: 'Astraea Boutique', currency: 'INR', shipping_fee: 0 },\n  },\n  {\n    id: 'bot_customer_support',\n    name: 'AI Customer Support Desk',\n    headline: 'Tier-1 AI resolution with seamless human agent ticket escalation.',\n    description: 'Automate 80% of customer inquiries with smart contextual AI answers. Detects frustrated users and automatically opens priority tickets with notification alerts to your human support team.',\n    category: 'business',\n    icon: Headphones,\n    version: '1.1.0',\n    rating: 4.92,\n    installCount: 980,\n    isFeatured: true,\n    tags: ['support', 'tickets', 'helpdesk', 'ai', 'crm'],\n    permissions: ['messages.send', 'notifications.dispatch', 'ai.completion'],\n    mcpTools: ['zendesk.ticket.create', 'crm.contact.lookup'],\n    systemTemplates: ['welcome', 'ticket_created', 'ticket_resolved'],\n    defaultConfig: { company_name: 'Acme Cloud', escalation_threshold: 0.35 },\n  },\n  {\n    id: 'bot_lead_crm',\n    name: 'Lead Generation & CRM Collector',\n    headline: 'Conversational qualification funnel that captures leads directly into your database.',\n    description: 'Replaces tedious web forms with natural in-chat qualification. Collects verified phone numbers via Telegram 1-tap contact sharing, qualifies budgets, and syncs immediately to HubSpot/Google Sheets.',\n    category: 'business',\n    icon: UserCheck,\n    version: '1.0.4',\n    rating: 4.88,\n    installCount: 750,\n    isFeatured: false,\n    tags: ['leads', 'crm', 'forms', 'hubspot', 'sales'],\n    permissions: ['messages.send', 'users.contact.request'],\n    mcpTools: ['hubspot.contact.create', 'sheets.append_row'],\n    systemTemplates: ['welcome', 'ask_question', 'lead_thankyou'],\n    defaultConfig: { target_sheet_id: '', notify_admin_chat_id: '' },\n  },\n  {\n    id: 'bot_appointment_booking',\n    name: 'Calendar & Appointment Scheduler',\n    headline: 'Real-time time-slot booking with Google Calendar / Cal.com sync.',\n    description: 'Eliminates back-and-forth scheduling messages. Clients select available dates directly from an inline calendar matrix, receive automated reminder pings, and can reschedule in 1 tap.',\n    category: 'business',\n    icon: Calendar,\n    version: '1.3.1',\n    rating: 4.91,\n    installCount: 620,\n    isFeatured: false,\n    tags: ['calendar', 'booking', 'appointments', 'reminders'],\n    permissions: ['messages.send', 'notifications.schedule'],\n    mcpTools: ['google.calendar.events.list', 'google.calendar.events.create'],\n    systemTemplates: ['welcome', 'select_slot', 'booking_confirmed'],\n    defaultConfig: { slot_duration_minutes: 30, buffer_minutes: 10 },\n  },\n  {\n    id: 'bot_invoice_billing',\n    name: 'Invoice Generation & Ledger Bot',\n    headline: 'Generate itemized PDF bills and collect UPI/card payments instantly.',\n    description: 'Instant billing tool for service providers, freelancers, and agencies. Send /invoice <amount> to generate professional branded invoices with payment deep-links and verified status tracking.',\n    category: 'business',\n    icon: Receipt,\n    version: '1.1.2',\n    rating: 4.89,\n    installCount: 890,\n    isFeatured: true,\n    tags: ['invoicing', 'billing', 'accounting', 'pdf', 'payments'],\n    permissions: ['messages.send', 'payments.create', 'files.upload'],\n    mcpTools: ['payments.invoice.create', 'pdf.invoice.render'],\n    systemTemplates: ['welcome', 'invoice_summary', 'payment_success'],\n    defaultConfig: { company_tax_id: '', currency: 'INR' },\n  },\n  {\n    id: 'bot_subscription_vip',\n    name: 'VIP Club & Community Gatekeeper',\n    headline: 'Paid subscription channels with automated invite links and expiry kick.',\n    description: 'Monetize exclusive Telegram channels and groups. Accepts recurring monthly/yearly payments, generates single-use join links, and auto-removes users upon membership expiration.',\n    category: 'business',\n    icon: Crown,\n    version: '2.0.0',\n    rating: 4.98,\n    installCount: 2310,\n    isFeatured: true,\n    tags: ['subscriptions', 'vip', 'monetization', 'channels', 'paywall'],\n    permissions: ['channels.manage', 'invite_links.create', 'members.restrict'],\n    mcpTools: ['telegram.chat.create_invite_link', 'telegram.chat.kick_member'],\n    systemTemplates: ['welcome', 'plans_list', 'vip_welcome', 'expiry_warning'],\n    defaultConfig: { channel_id: '', monthly_price: 499, currency: 'INR' },\n  },\n\n  // 2. Community & Moderation\n  {\n    id: 'bot_group_admin_pro',\n    name: 'Group Admin & Moderation Shield',\n    headline: 'Comprehensive Telegram group guard with anti-flood and auto-mute.',\n    description: 'Keep large Telegram supergroups civilized 24/7. Automatically cleans join/leave spam messages, enforces message rate limits, silences spammers, and provides extensive moderator command toolkits.',\n    category: 'community',\n    icon: ShieldAlert,\n    version: '2.4.0',\n    rating: 4.96,\n    installCount: 3450,\n    isFeatured: true,\n    tags: ['moderation', 'admin', 'anti-spam', 'groups', 'security'],\n    permissions: ['messages.delete', 'members.restrict', 'members.promote'],\n    mcpTools: ['telegram.group.delete_message', 'telegram.group.ban_member'],\n    systemTemplates: ['warn_message', 'ban_notice', 'rules_display'],\n    defaultConfig: { max_warns: 3, delete_service_messages: true, flood_limit: 5 },\n  },\n  {\n    id: 'bot_anti_spam',\n    name: 'AI Anti-Spam & Link Filter',\n    headline: 'Neural network spam detector that blocks unauthorized advertising and phishing.',\n    description: 'Protects communities from crypto scams, fake airdrop bots, and unwanted external links. Evaluates message text and usernames using machine learning before users can fall for scams.',\n    category: 'community',\n    icon: ShieldCheck,\n    version: '1.3.0',\n    rating: 4.94,\n    installCount: 1890,\n    isFeatured: false,\n    tags: ['antispam', 'phishing', 'security', 'links', 'crypto-shield'],\n    permissions: ['messages.delete', 'members.restrict'],\n    mcpTools: ['ai.spam.classify', 'url.reputation.check'],\n    systemTemplates: ['spam_deleted_notice'],\n    defaultConfig: { allow_whitelisted_domains_only: true, ban_on_crypto_scam: true },\n  },\n  {\n    id: 'bot_welcome_verification',\n    name: 'Captcha Gate & Welcome Verifier',\n    headline: 'Stop userbot raids with interactive math and button CAPTCHAs.',\n    description: 'Requires all newly joined members to tap the matching emoji or solve a simple 1-click CAPTCHA within 60 seconds before they are allowed to send messages in the group.',\n    category: 'community',\n    icon: KeyRound,\n    version: '1.2.5',\n    rating: 4.92,\n    installCount: 2100,\n    isFeatured: true,\n    tags: ['captcha', 'verification', 'onboarding', 'antiraid'],\n    permissions: ['members.restrict', 'messages.send', 'messages.delete'],\n    mcpTools: ['captcha.generate', 'telegram.chat.unmute'],\n    systemTemplates: ['captcha_prompt', 'welcome_verified'],\n    defaultConfig: { captcha_timeout_sec: 60, fail_action: 'kick' },\n  },\n  {\n    id: 'bot_reputation_leaderboard',\n    name: 'Community Karma & Leaderboard',\n    headline: 'Reward helpful group members with +1 karma and weekly rank badges.',\n    description: 'Fosters active community engagement. Members award thanks to each other by replying +1 or /thanks. Automatically calculates daily top contributors and grants custom Telegram admin titles.',\n    category: 'community',\n    icon: Trophy,\n    version: '1.1.0',\n    rating: 4.87,\n    installCount: 840,\n    isFeatured: false,\n    tags: ['karma', 'reputation', 'gamification', 'leaderboard', 'community'],\n    permissions: ['messages.read', 'messages.send'],\n    mcpTools: ['database.karma.increment', 'database.leaderboard.get'],\n    systemTemplates: ['karma_awarded', 'weekly_leaderboard'],\n    defaultConfig: { cooldown_minutes: 5, weekly_reset: false },\n  },\n  {\n    id: 'bot_anonymous_feedback',\n    name: 'Anonymous Feedback & Confessions Box',\n    headline: 'Allows group members to ask questions or submit feedback anonymously.',\n    description: 'Encourages honest team or community feedback. Users message the bot in private, and the bot publishes the query into the group or admin channel with full author anonymity preserved.',\n    category: 'community',\n    icon: EyeOff,\n    version: '1.0.8',\n    rating: 4.85,\n    installCount: 510,\n    isFeatured: false,\n    tags: ['anonymous', 'feedback', 'confessions', 'qa', 'privacy'],\n    permissions: ['messages.send'],\n    mcpTools: ['message.send_anonymous'],\n    systemTemplates: ['private_welcome', 'group_published_post'],\n    defaultConfig: { destination_chat_id: '', moderation_queue: true },\n  },\n  {\n    id: 'bot_referral_rewards',\n    name: 'Viral Referral & Contest Engine',\n    headline: 'Grow your Telegram channel rapidly with trackable subscriber invite links.',\n    description: 'Generates personal deep-link invite links (/start ref_12345). Tracks valid channel joins, detects fraudulent multi-accounts, and distributes rewards or entry tickets automatically.',\n    category: 'community',\n    icon: Share2,\n    version: '2.1.0',\n    rating: 4.97,\n    installCount: 2890,\n    isFeatured: true,\n    tags: ['referral', 'viral', 'growth', 'contests', 'giveaways'],\n    permissions: ['messages.send', 'channels.members.verify'],\n    mcpTools: ['referral.code.generate', 'referral.signup.track'],\n    systemTemplates: ['welcome', 'my_referrals', 'reward_unlocked'],\n    defaultConfig: { points_per_referral: 10, min_payout_points: 100 },\n  },\n\n  // 3. AI Specialists\n  {\n    id: 'bot_chatgpt_assistant',\n    name: 'Multi-LLM Conversational Brain',\n    headline: 'Intelligent multi-turn AI assistant powered by OpenAI GPT-4o and Claude 3.5.',\n    description: 'Deploy a versatile smart AI bot in your group or direct messages. Handles contextual Q&A, brainstorming, language translation, and summaries with custom persona instructions.',\n    category: 'ai_specialist',\n    icon: Bot,\n    version: '2.5.0',\n    rating: 4.99,\n    installCount: 4200,\n    isFeatured: true,\n    tags: ['ai', 'chatgpt', 'claude', 'gemini', 'assistant'],\n    permissions: ['messages.send', 'ai.tokens.consume'],\n    mcpTools: ['openai.chat.completion', 'openrouter.chat.completion'],\n    systemTemplates: ['welcome', 'ai_typing', 'context_cleared'],\n    defaultConfig: { model: 'gpt-4o-mini', temperature: 0.7, memory_turns: 10 },\n  },\n  {\n    id: 'bot_pdf_research',\n    name: 'Document & PDF Research RAG',\n    headline: 'Upload PDF/DOCX files in chat and query them with semantic vector search.',\n    description: 'Transform documents into interactive knowledge bases. Users simply upload a whitepaper, contract, or textbook to Telegram and ask questions; the bot cites exact pages with answers.',\n    category: 'ai_specialist',\n    icon: FileText,\n    version: '1.4.0',\n    rating: 4.93,\n    installCount: 1650,\n    isFeatured: true,\n    tags: ['rag', 'pdf', 'documents', 'search', 'embeddings'],\n    permissions: ['files.download', 'messages.send'],\n    mcpTools: ['embeddings.document.index', 'vector.similarity.search'],\n    systemTemplates: ['welcome', 'document_indexed', 'rag_answer'],\n    defaultConfig: { chunk_size: 500, top_k_matches: 4 },\n  },\n  {\n    id: 'bot_image_gen',\n    name: 'AI Image & Artwork Generator',\n    headline: 'Text-to-image studio using Flux.1 and Stable Diffusion directly in Telegram.',\n    description: 'Generate stunning photorealistic artwork, marketing banners, and avatars on demand. Send /imagine <prompt> to receive 4 variations with upscaling and re-roll inline buttons.',\n    category: 'ai_specialist',\n    icon: Image,\n    version: '1.3.2',\n    rating: 4.91,\n    installCount: 1980,\n    isFeatured: false,\n    tags: ['images', 'art', 'flux', 'midjourney', 'diffusion'],\n    permissions: ['photos.send', 'payments.credits.deduct'],\n    mcpTools: ['image.flux.generate', 'image.upscale'],\n    systemTemplates: ['welcome', 'generating_progress', 'image_delivered'],\n    defaultConfig: { default_aspect_ratio: '1:1', credits_per_gen: 1 },\n  },\n  {\n    id: 'bot_code_interpreter',\n    name: 'Sandboxed Code Runner & Tutor',\n    headline: 'Execute Python, JavaScript, and SQL securely inside Telegram messages.',\n    description: 'Run code snippets, debug errors, and visualize charts directly within chat. Secure firewalled WebAssembly execution sandbox with syntax highlighting and instant outputs.',\n    category: 'ai_specialist',\n    icon: Code,\n    version: '1.2.0',\n    rating: 4.88,\n    installCount: 780,\n    isFeatured: false,\n    tags: ['code', 'python', 'developer', 'sandbox', 'interpreter'],\n    permissions: ['messages.send'],\n    mcpTools: ['sandbox.code.execute'],\n    systemTemplates: ['welcome', 'execution_result'],\n    defaultConfig: { execution_timeout_ms: 3000, memory_limit_mb: 64 },\n  },\n  {\n    id: 'bot_voice_transcriber',\n    name: 'Voice Note Transcriber & Summarizer',\n    headline: 'Converts long Telegram audio messages to clean text with bullet summaries.',\n    description: 'Never listen to a 5-minute voice note again. Powered by Whisper AI, converts incoming voice recordings and video notes into clean formatted transcripts with executive summaries.',\n    category: 'ai_specialist',\n    icon: Mic,\n    version: '1.5.0',\n    rating: 4.96,\n    installCount: 2450,\n    isFeatured: true,\n    tags: ['voice', 'audio', 'transcription', 'whisper', 'summary'],\n    permissions: ['voice.download', 'messages.send'],\n    mcpTools: ['audio.whisper.transcribe', 'ai.summary.generate'],\n    systemTemplates: ['transcript_ready'],\n    defaultConfig: { auto_detect_language: true, generate_summary: true },\n  },\n  {\n    id: 'bot_sql_query_assistant',\n    name: 'Text-to-SQL Analytics Assistant',\n    headline: 'Ask business questions in plain English and receive instant database metrics.',\n    description: 'Empower executive teams to query production read-replicas safely. Send \"How many VIP signups this week?\" and the bot writes verified SQL queries and returns a table or chart.',\n    category: 'ai_specialist',\n    icon: Database,\n    version: '1.1.0',\n    rating: 4.89,\n    installCount: 430,\n    isFeatured: false,\n    tags: ['sql', 'database', 'bi', 'analytics', 'charts'],\n    permissions: ['database.read_only', 'messages.send'],\n    mcpTools: ['db.schema.inspect', 'db.readonly.query'],\n    systemTemplates: ['welcome', 'query_result'],\n    defaultConfig: { max_rows: 50, enforce_read_only: true },\n  },\n\n  // 4. Developer Tools & DevOps\n  {\n    id: 'bot_github_notifier',\n    name: 'GitHub DevOps Sentinel',\n    headline: 'Real-time repository alerts for commits, pull requests, issues, and releases.',\n    description: 'Bridge engineering workflows with Telegram. Sends interactive cards for incoming PRs with 1-click \"Approve\" or \"Comment\" buttons linked directly to your GitHub organization.',\n    category: 'developer_tools',\n    icon: GitBranch,\n    version: '2.1.0',\n    rating: 4.94,\n    installCount: 1540,\n    isFeatured: true,\n    tags: ['github', 'devops', 'git', 'pr', 'alerts'],\n    permissions: ['messages.send', 'webhooks.receive'],\n    mcpTools: ['github.repo.subscribe', 'github.pr.merge'],\n    systemTemplates: ['pr_opened', 'commit_alert', 'release_published'],\n    defaultConfig: { filter_branches: ['main', 'master', 'staging'] },\n  },\n  {\n    id: 'bot_server_monitor',\n    name: 'Server Uptime & Sentry Error Monitor',\n    headline: 'Instant Telegram pings when your API endpoints or Docker servers experience downtime.',\n    description: 'Reliable heartbeat monitoring for APIs, VPS nodes, and databases. Detects 5xx spikes and unhandled exceptions from Sentry and alerts on-call engineers within 2 seconds.',\n    category: 'developer_tools',\n    icon: Activity,\n    version: '1.6.0',\n    rating: 4.98,\n    installCount: 2210,\n    isFeatured: true,\n    tags: ['monitoring', 'uptime', 'sentry', 'devops', 'infra'],\n    permissions: ['notifications.dispatch', 'webhooks.receive'],\n    mcpTools: ['health.endpoint.ping', 'sentry.incident.notify'],\n    systemTemplates: ['outage_alert', 'recovery_notice'],\n    defaultConfig: { check_interval_sec: 30, retry_count: 2 },\n  },\n  {\n    id: 'bot_crypto_whale',\n    name: 'On-Chain Whale & DEX Swap Alert',\n    headline: 'Real-time tracking for large transactions on Ethereum, Solana, and TON.',\n    description: 'Catch large crypto movements before the market reacts. Streams customizable alerts for transactions over $100,000, new liquidity pool creations, and contract deployments.',\n    category: 'developer_tools',\n    icon: Zap,\n    version: '1.3.0',\n    rating: 4.87,\n    installCount: 1120,\n    isFeatured: false,\n    tags: ['crypto', 'whale-alerts', 'ton', 'solana', 'dex'],\n    permissions: ['messages.send'],\n    mcpTools: ['blockchain.whale.subscribe'],\n    systemTemplates: ['whale_swap_alert'],\n    defaultConfig: { min_usd_value: 100000, chains: ['TON', 'ETH', 'SOL'] },\n  },\n  {\n    id: 'bot_ssh_sysadmin',\n    name: 'SSH Command Runner & Cloud Console',\n    headline: 'Authorized 2FA terminal shell to inspect logs and restart Docker containers.',\n    description: 'Manage remote servers safely from your phone. Authenticated through Telegram biometrics and hardware keys. Execute safe whitelisted commands like `docker restart api` or `df -h`.',\n    category: 'developer_tools',\n    icon: Terminal,\n    version: '1.0.5',\n    rating: 4.84,\n    installCount: 390,\n    isFeatured: false,\n    tags: ['ssh', 'terminal', 'docker', 'sysadmin', 'devops'],\n    permissions: ['admin.hardware_auth', 'messages.send'],\n    mcpTools: ['server.ssh.execute_whitelisted'],\n    systemTemplates: ['auth_required', 'command_output'],\n    defaultConfig: { allowed_commands: ['status', 'restart', 'logs'], require_pin: true },\n  },\n\n  // 5. Content & Media\n  {\n    id: 'bot_rss_reader',\n    name: 'RSS Feed & News Auto-Broadcaster',\n    headline: 'Auto-publish articles and YouTube videos to your Telegram channels within 60s.',\n    description: 'Keep your broadcast channels populated effortlessly. Watches unlimited RSS/Atom feeds, formats incoming news with custom headers and instant-view previews, and auto-posts.',\n    category: 'content_media',\n    icon: Rss,\n    version: '1.4.2',\n    rating: 4.90,\n    installCount: 1780,\n    isFeatured: false,\n    tags: ['rss', 'news', 'youtube', 'blog', 'autopost'],\n    permissions: ['channels.post'],\n    mcpTools: ['rss.feed.fetch', 'telegram.channel.post'],\n    systemTemplates: ['feed_item_post'],\n    defaultConfig: { check_interval_min: 5, include_source_link: true },\n  },\n  {\n    id: 'bot_newsletter_publisher',\n    name: 'Substack & Medium Syndicator',\n    headline: 'Syndicate your published newsletters with rich buttons and instant member polls.',\n    description: 'Grow a cross-platform media audience. Syncs newsletters automatically with instant formatting and provides member reaction buttons to gather engagement statistics.',\n    category: 'content_media',\n    icon: Newspaper,\n    version: '1.1.0',\n    rating: 4.86,\n    installCount: 640,\n    isFeatured: false,\n    tags: ['newsletter', 'substack', 'medium', 'publishing'],\n    permissions: ['channels.post', 'messages.send'],\n    mcpTools: ['publishing.syndicate'],\n    systemTemplates: ['newsletter_edition'],\n    defaultConfig: { append_footer: true },\n  },\n  {\n    id: 'bot_media_watermarker',\n    name: 'Bulk Photo & Video Watermarker',\n    headline: 'Automatically stamp your brand logo or channel handle onto uploaded media.',\n    description: 'Essential for media creators and community managers. Automatically overlays semi-transparent brand watermarks, protects intellectual property, and outputs high-quality compressed media.',\n    category: 'content_media',\n    icon: Image,\n    version: '1.2.1',\n    rating: 4.92,\n    installCount: 1410,\n    isFeatured: true,\n    tags: ['watermark', 'branding', 'media', 'photos', 'video'],\n    permissions: ['files.download', 'files.upload'],\n    mcpTools: ['media.watermark.apply'],\n    systemTemplates: ['welcome', 'processing_media', 'media_ready'],\n    defaultConfig: { watermark_text: '@MyBrand', position: 'bottom_right', opacity: 0.7 },\n  },\n];\n\ninterface InstalledInstance {\n  id: string;\n  name: string;\n  templateId: string;\n  templateName: string;\n  category: string;\n  status: 'configured' | 'deployed';\n  botUsername?: string;\n  uptimePct: number;\n  interactionsCount: number;\n  installedAt: string;\n}\n\nconst INITIAL_INSTALLED: InstalledInstance[] = [\n  {\n    id: 'inst-1',\n    name: 'VIP Boutique Shop',\n    templateId: 'bot_ecommerce_concierge',\n    templateName: 'E-Commerce & Digital Store Concierge',\n    category: 'business',\n    status: 'deployed',\n    botUsername: '@astraea_shop_bot',\n    uptimePct: 100.0,\n    interactionsCount: 1240,\n    installedAt: '2026-11-17T14:30:00Z',\n  },\n  {\n    id: 'inst-2',\n    name: 'DevOps GitHub Sentinel',\n    templateId: 'bot_github_notifier',\n    templateName: 'GitHub DevOps Notifier',\n    category: 'developer_tools',\n    status: 'deployed',\n    botUsername: '@devops_sentinel_bot',\n    uptimePct: 99.98,\n    interactionsCount: 840,\n    installedAt: '2026-11-18T08:15:00Z',\n  },\n];\n\nexport const MarketplacePage: React.FC = () => {\n  const { currentBot, bots, selectBot, applyTemplateToBot } = useBot();\n  const [searchParams, setSearchParams] = useSearchParams();\n  const activeTab = searchParams.get('tab') === 'installed' ? 'installed' : 'catalog';\n  const setActiveTab = (tab: 'catalog' | 'installed') => {\n    setSearchParams(tab === 'installed' ? { tab: 'installed' } : {});\n  };\n  const [selectedCategory, setSelectedCategory] = useState<string>('all');\n  const [searchTerm, setSearchTerm] = useState<string>('');\n  const [selectedBlueprint, setSelectedBlueprint] = useState<BotBlueprint | null>(null);\n  const [installingBlueprint, setInstallingBlueprint] = useState<BotBlueprint | null>(null);\n  const [instanceNameInput, setInstanceNameInput] = useState<string>('');\n  const [selectedTargetBot, setSelectedTargetBot] = useState<string>(currentBot?.id || 'b-001');\n  const [installedList, setInstalledList] = useState<InstalledInstance[]>(INITIAL_INSTALLED);\n  const [installSuccessMessage, setInstallSuccessMessage] = useState<string | null>(null);\n\n  const categories = [\n    { id: 'all', name: 'All Blueprints', count: BLUEPRINTS_CATALOG.length },\n    { id: 'business', name: 'Business & Store', count: 6 },\n    { id: 'community', name: 'Community Guard', count: 6 },\n    { id: 'ai_specialist', name: 'AI Specialists', count: 6 },\n    { id: 'developer_tools', name: 'Developer & DevOps', count: 4 },\n    { id: 'content_media', name: 'Content & Media', count: 3 },\n  ];\n\n  const filteredBlueprints = BLUEPRINTS_CATALOG.filter((b) => {\n    const matchesCat = selectedCategory === 'all' || b.category === selectedCategory;\n    const matchesSearch =\n      b.name.toLowerCase().includes(searchTerm.toLowerCase()) ||\n      b.headline.toLowerCase().includes(searchTerm.toLowerCase()) ||\n      b.tags.some((t) => t.toLowerCase().includes(searchTerm.toLowerCase()));\n    return matchesCat && matchesSearch;\n  });\n\n  const handleLaunchInstall = (blueprint: BotBlueprint) => {\n    setInstallingBlueprint(blueprint);\n    setInstanceNameInput(blueprint.name);\n    setSelectedTargetBot(currentBot?.id || 'b-001');\n  };\n\n  const handleConfirmDeploy = () => {\n    if (!installingBlueprint) return;\n    \n    // Apply template to chosen bot in BotContext\n    const target = bots.find((b) => b.id === selectedTargetBot) || currentBot;\n    applyTemplateToBot(target.id, installingBlueprint.name, installingBlueprint.systemTemplates);\n\n    const botUser = `@${target.username}`;\n    const newInst: InstalledInstance = {\n      id: `inst-${Date.now()}`,\n      name: instanceNameInput || installingBlueprint.name,\n      templateId: installingBlueprint.id,\n      templateName: installingBlueprint.name,\n      category: installingBlueprint.category,\n      status: 'deployed',\n      botUsername: botUser,\n      uptimePct: 100.0,\n      interactionsCount: 0,\n      installedAt: new Date().toISOString(),\n    };\n    setInstalledList([newInst, ...installedList]);\n    setInstallingBlueprint(null);\n    setInstallSuccessMessage(`Template \"${installingBlueprint.name}\" successfully deployed to ${botUser} with 24/7 cloud runtime & modules provisioned!`);\n    setTimeout(() => setInstallSuccessMessage(null), 5000);\n  };\n\n  return (\n    <div className=\"space-y-6 sm:space-y-8 animate-in fade-in duration-300 w-full max-w-full min-w-0\">\n      {/* Play Console Chosen Bot Context Banner */}\n      <div className=\"astraea-card rounded-2xl p-4 sm:p-5 border border-white/10 flex flex-col sm:flex-row sm:items-center justify-between gap-4\">\n        <div className=\"flex items-center gap-3\">\n          <div className=\"w-10 h-10 rounded-xl bg-[#2481CC]/15 border border-[#2481CC]/40 flex items-center justify-center text-[#2481CC] shadow-telegram shrink-0\">\n            <Bot className=\"w-5 h-5\" />\n          </div>\n          <div>\n            <div className=\"flex items-center gap-1.5 text-[10px] font-mono text-emerald-400 font-semibold uppercase\">\n              <span className=\"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse\" />\n              <span>ACTIVE BOT WORKSPACE</span>\n            </div>\n            <div className=\"text-sm font-bold text-pearl-50\">\n              {currentBot?.name} <span className=\"text-xs text-[#2481CC] font-mono\">(@{currentBot?.username})</span>\n            </div>\n          </div>\n        </div>\n        <div className=\"flex items-center gap-2\">\n          <span className=\"text-xs text-pearl-300 font-sans hidden md:inline\">\n            1-Click install any turnkey template directly into this bot:\n          </span>\n          <Link\n            to=\"/dashboard\"\n            className=\"btn-telegram-secondary py-1.5 px-3 text-xs inline-flex items-center gap-1.5 shrink-0\"\n          >\n            <span>Open Bot Console</span>\n            <ChevronRight className=\"w-3.5 h-3.5\" />\n          </Link>\n        </div>\n      </div>\n\n      {/* Header Banner */}\n      <div className=\"astraea-panel rounded-2xl border border-white/10 p-4 sm:p-6 md:p-8 shadow-sm relative overflow-hidden\">\n        <div className=\"absolute -right-16 -top-16 w-80 h-80 bg-[#2481CC]/10 rounded-full blur-3xl pointer-events-none\" />\n        <div className=\"relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-4 sm:gap-6\">\n          <div>\n            <div className=\"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#2481CC]/10 border border-[#2481CC]/30 text-[#2481CC] text-xs font-medium uppercase tracking-wider mb-2 sm:mb-3\">\n              <Sparkles className=\"w-3.5 h-3.5\" />\n              Telegram Bot Template Marketplace\n            </div>\n            <h1 className=\"text-2xl sm:text-3xl font-bold tracking-tight text-pearl-50\">\n              Ready-Made Bot <span className=\"text-[#2481CC]\">Templates</span>\n            </h1>\n            <p className=\"text-pearl-300 text-xs sm:text-sm mt-1 max-w-2xl font-normal leading-relaxed\">\n              No VPS, no server configuration, zero coding headaches. Choose from 25 production-ready bot blueprints, customize credentials, and launch on managed cloud infrastructure with 24/7 uptime.\n            </p>\n          </div>\n          <div className=\"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3 w-full md:w-auto shrink-0\">\n            <button\n              onClick={() => setActiveTab('catalog')}\n              className={`px-4 sm:px-5 py-2.5 rounded-xl text-xs font-semibold uppercase tracking-wider transition-all flex items-center justify-center gap-2 ${\n                activeTab === 'catalog'\n                  ? 'btn-telegram-primary shadow-telegram'\n                  : 'btn-telegram-secondary'\n              }`}\n            >\n              <Store className=\"w-4 h-4\" />\n              <span>Explore Catalog ({BLUEPRINTS_CATALOG.length})</span>\n            </button>\n            <button\n              onClick={() => setActiveTab('installed')}\n              className={`px-4 sm:px-5 py-2.5 rounded-xl text-xs font-semibold uppercase tracking-wider transition-all flex items-center justify-center gap-2 ${\n                activeTab === 'installed'\n                  ? 'btn-telegram-primary shadow-telegram'\n                  : 'btn-telegram-secondary'\n              }`}\n            >\n              <PackageCheck className=\"w-4 h-4\" />\n              <span>Active Deployments ({installedList.length})</span>\n            </button>\n          </div>\n        </div>\n\n        {/* Global Key Metrics */}\n        <div className=\"grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mt-6 sm:mt-8 pt-5 sm:pt-6 border-t border-white/10\">\n          <div>\n            <p className=\"text-[10px] sm:text-xs text-pearl-400 uppercase tracking-wider\">Production Blueprints</p>\n            <p className=\"text-lg sm:text-xl font-bold text-pearl-50 mt-1\">25 Verified</p>\n          </div>\n          <div>\n            <p className=\"text-[10px] sm:text-xs text-pearl-400 uppercase tracking-wider\">Reusable Modules</p>\n            <p className=\"text-lg sm:text-xl font-bold text-[#2481CC] mt-1\">9 Plug-and-Play</p>\n          </div>\n          <div>\n            <p className=\"text-[10px] sm:text-xs text-pearl-400 uppercase tracking-wider\">Cloud Runtime SLA</p>\n            <p className=\"text-lg sm:text-xl font-bold text-emerald-400 mt-1\">99.98% 24/7</p>\n          </div>\n          <div>\n            <p className=\"text-[10px] sm:text-xs text-pearl-400 uppercase tracking-wider\">Setup Overhead</p>\n            <p className=\"text-lg sm:text-xl font-bold text-pearl-50 mt-1\">0 Server / VPS</p>\n          </div>\n        </div>\n      </div>\n\n      {/* Success Alert Banner */}\n      {installSuccessMessage && (\n        <div className=\"p-3.5 sm:p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-xs sm:text-sm flex items-center justify-between shadow-sm animate-in fade-in\">\n          <div className=\"flex items-center gap-2\">\n            <CheckCircle2 className=\"w-5 h-5 text-emerald-400 shrink-0\" />\n            <span>{installSuccessMessage}</span>\n          </div>\n          <button onClick={() => setInstallSuccessMessage(null)} className=\"text-emerald-400 hover:text-white p-1\">\n            <X className=\"w-4 h-4\" />\n          </button>\n        </div>\n      )}\n\n      {/* TAB 1: BROWSE CATALOG */}\n      {activeTab === 'catalog' && (\n        <div className=\"space-y-6\">\n          {/* Search & Categories Bar */}\n          <div className=\"flex flex-col md:flex-row items-stretch md:items-center justify-between gap-3 sm:gap-4\">\n            {/* Category Pills */}\n            <div className=\"flex items-center gap-2 overflow-x-auto w-full md:w-auto pb-2 md:pb-0 scrollbar-none\">\n              {categories.map((cat) => (\n                <button\n                  key={cat.id}\n                  onClick={() => setSelectedCategory(cat.id)}\n                  className={`px-3.5 sm:px-4 py-2 rounded-xl text-xs whitespace-nowrap tracking-wider uppercase transition-all shrink-0 font-medium ${\n                    selectedCategory === cat.id\n                      ? 'bg-[#2481CC] text-white shadow-telegram'\n                      : 'bg-space-850 hover:bg-space-800 text-pearl-300 hover:text-white border border-white/10'\n                  }`}\n                >\n                  {cat.name} ({cat.count})\n                </button>\n              ))}\n            </div>\n\n            {/* Search Input */}\n            <div className=\"relative w-full md:w-72 shrink-0\">\n              <Search className=\"w-4 h-4 text-pearl-400 absolute left-3.5 top-1/2 -translate-y-1/2\" />\n              <input\n                type=\"text\"\n                placeholder=\"Search bot blueprints, tags...\"\n                value={searchTerm}\n                onChange={(e) => setSearchTerm(e.target.value)}\n                className=\"w-full pl-10 pr-4 py-2 rounded-xl bg-space-900 border border-white/10 text-xs text-pearl-100 placeholder-pearl-500 focus:outline-none focus:border-[#2481CC] transition-all font-mono\"\n              />\n            </div>\n          </div>\n\n          {/* Blueprints Grid */}\n          <div className=\"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6\">\n            {filteredBlueprints.map((bot) => {\n              const IconComp = bot.icon;\n              return (\n                <div\n                  key={bot.id}\n                  className=\"astraea-card group relative rounded-2xl border border-white/10 hover:border-[#2481CC]/50 p-4 sm:p-6 flex flex-col justify-between transition-all duration-200 hover:shadow-lg\"\n                >\n                  <div>\n                    {/* Top Row: Icon + Category + Version */}\n                    <div className=\"flex items-start justify-between gap-3 mb-4\">\n                      <Link\n                        to={`/marketplace/bots/${bot.id.replace('bot_', '').replace(/_/g, '-')}`}\n                        className=\"w-12 h-12 rounded-xl bg-[#2481CC]/15 border border-[#2481CC]/35 flex items-center justify-center text-[#2481CC] group-hover:scale-105 transition-transform shadow-sm\"\n                      >\n                        <IconComp className=\"w-6 h-6\" />\n                      </Link>\n                      <div className=\"flex flex-col items-end gap-1\">\n                        <span className=\"text-[10px] px-2.5 py-0.5 rounded-full bg-space-850 border border-white/10 text-pearl-300 uppercase tracking-wider font-mono\">\n                          {bot.category.replace('_', ' ')}\n                        </span>\n                        <div className=\"flex items-center gap-1 text-[11px] text-[#2481CC] font-mono\">\n                          <span>⭐</span>\n                          <span className=\"font-semibold\">{bot.rating.toFixed(2)}</span>\n                          <span className=\"text-pearl-400\">({bot.installCount})</span>\n                        </div>\n                      </div>\n                    </div>\n\n                    {/* Bot Name & Headline */}\n                    <Link\n                      to={`/marketplace/bots/${bot.id.replace('bot_', '').replace(/_/g, '-')}`}\n                      className=\"text-base font-bold text-pearl-50 group-hover:text-[#2481CC] transition-colors block leading-snug\"\n                    >\n                      {bot.name}\n                    </Link>\n                    <p className=\"text-xs text-pearl-400 font-sans mt-1.5 leading-relaxed line-clamp-2\">\n                      {bot.headline}\n                    </p>\n\n                    {/* Tags */}\n                    <div className=\"flex flex-wrap gap-1.5 mt-4\">\n                      {bot.tags.slice(0, 3).map((tag) => (\n                        <span\n                          key={tag}\n                          className=\"text-[10px] px-2 py-0.5 rounded-md bg-space-850 text-pearl-300 border border-white/5 font-mono\"\n                        >\n                          #{tag}\n                        </span>\n                      ))}\n                    </div>\n                  </div>\n\n                  {/* Bottom Actions */}\n                  <div className=\"pt-4 sm:pt-6 mt-4 sm:mt-6 border-t border-white/10 flex flex-wrap sm:flex-nowrap items-center justify-between gap-2\">\n                    <Link\n                      to={`/marketplace/bots/${bot.id.replace('bot_', '').replace(/_/g, '-')}`}\n                      className=\"px-3 py-1.5 rounded-lg text-xs text-[#2481CC] hover:underline transition-all font-mono font-medium\"\n                    >\n                      Inspect →\n                    </Link>\n                    <button\n                      onClick={() => handleLaunchInstall(bot)}\n                      className=\"btn-telegram-primary py-1.5 px-3.5 text-xs font-semibold uppercase tracking-wider inline-flex items-center gap-1.5 shadow-telegram\"\n                    >\n                      <Play className=\"w-3.5 h-3.5 fill-white\" />\n                      <span>Deploy Cloud</span>\n                    </button>\n                  </div>\n                </div>\n              );\n            })}\n          </div>\n        </div>\n      )}\n\n      {/* TAB 2: INSTALLED INSTANCES */}\n      {activeTab === 'installed' && (\n        <div className=\"space-y-6 min-w-0 max-w-full\">\n          <div className=\"astraea-panel rounded-2xl border border-white/10 overflow-hidden min-w-0 max-w-full\">\n            <div className=\"p-4 sm:p-6 border-b border-white/10 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4\">\n              <div>\n                <h3 className=\"text-base font-bold text-pearl-50\">Active Tenant Bot Fleet</h3>\n                <p className=\"text-xs text-pearl-400 mt-0.5 font-sans\">\n                  Bots running 24/7 on our managed cloud runtime. Real-time telemetry and health monitoring.\n                </p>\n              </div>\n              <button\n                onClick={() => setActiveTab('catalog')}\n                className=\"btn-telegram-primary py-2 px-4 text-xs font-semibold uppercase tracking-wider shadow-telegram w-full sm:w-auto text-center shrink-0\"\n              >\n                + Install New Blueprint\n              </button>\n            </div>\n\n            <div className=\"overflow-x-auto w-full max-w-full\">\n              <table className=\"w-full min-w-[650px] text-left text-xs font-mono\">\n                <thead>\n                  <tr className=\"border-b border-white/10 text-pearl-400 uppercase tracking-wider text-[10px]\">\n                    <th className=\"py-4 px-6 font-medium\">Instance Name</th>\n                    <th className=\"py-4 px-6 font-medium\">Blueprint</th>\n                    <th className=\"py-4 px-6 font-medium\">Runtime Status</th>\n                    <th className=\"py-4 px-6 font-medium\">Telegram Bot</th>\n                    <th className=\"py-4 px-6 font-medium\">Uptime</th>\n                    <th className=\"py-4 px-6 font-medium\">Interactions</th>\n                    <th className=\"py-4 px-6 font-medium text-right\">Actions</th>\n                  </tr>\n                </thead>\n                <tbody className=\"divide-y divide-white/5\">\n                  {installedList.map((inst) => (\n                    <tr key={inst.id} className=\"hover:bg-white/[0.02] transition-colors\">\n                      <td className=\"py-4 px-6 font-medium text-pearl-50 flex items-center gap-2\">\n                        <Bot className=\"w-4 h-4 text-[#2481CC]\" />\n                        <span>{inst.name}</span>\n                      </td>\n                      <td className=\"py-4 px-6 text-pearl-300\">{inst.templateName}</td>\n                      <td className=\"py-4 px-6\">\n                        <span className=\"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-[10px] font-medium uppercase tracking-wider font-semibold\">\n                          <span className=\"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse\" />\n                          24/7 Running\n                        </span>\n                      </td>\n                      <td className=\"py-4 px-6 text-[#2481CC] font-mono text-[11px] font-medium\">\n                        {inst.botUsername || 'Unlinked'}\n                      </td>\n                      <td className=\"py-4 px-6 text-pearl-200 font-mono\">{inst.uptimePct}%</td>\n                      <td className=\"py-4 px-6 text-pearl-200 font-mono\">{inst.interactionsCount.toLocaleString()}</td>\n                      <td className=\"py-4 px-6 text-right space-x-2\">\n                        <Link\n                          to=\"/dashboard\"\n                          className=\"btn-telegram-secondary py-1 px-2.5 text-[10px] inline-flex items-center gap-1\"\n                        >\n                          <Sliders className=\"w-3 h-3\" />\n                          <span>Console</span>\n                        </Link>\n                      </td>\n                    </tr>\n                  ))}\n                </tbody>\n              </table>\n            </div>\n          </div>\n        </div>\n      )}\n\n      {/* QUICK PREVIEW MODAL */}\n      {selectedBlueprint && (\n        <div className=\"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md animate-in fade-in\">\n          <div className=\"relative w-full max-w-2xl rounded-2xl astraea-card border border-white/15 p-4 sm:p-6 md:p-8 shadow-2xl overflow-y-auto max-h-[90vh]\">\n            <button\n              onClick={() => setSelectedBlueprint(null)}\n              className=\"absolute right-3 sm:right-5 top-3 sm:top-5 p-2 rounded-xl bg-white/5 hover:bg-white/10 text-pearl-400 hover:text-white transition-all\"\n            >\n              <X className=\"w-4 h-4\" />\n            </button>\n\n            <div className=\"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6 pr-8\">\n              <div className=\"w-12 h-12 sm:w-14 sm:h-14 rounded-2xl bg-[#2481CC]/15 border border-[#2481CC]/30 flex items-center justify-center text-[#2481CC] shrink-0\">\n                <selectedBlueprint.icon className=\"w-6 h-6 sm:w-7 sm:h-7\" />\n              </div>\n              <div className=\"min-w-0\">\n                <span className=\"text-[10px] sm:text-xs uppercase tracking-wider text-[#2481CC] font-semibold font-mono\">\n                  {selectedBlueprint.category.replace('_', ' ')}\n                </span>\n                <h2 className=\"text-lg sm:text-xl font-bold text-pearl-50 truncate\">{selectedBlueprint.name}</h2>\n                <p className=\"text-[11px] sm:text-xs text-pearl-400 mt-0.5 font-mono\">Version {selectedBlueprint.version} • Verified Blueprint</p>\n              </div>\n            </div>\n\n            <div className=\"space-y-4 sm:space-y-6 text-xs text-pearl-300 font-sans leading-relaxed\">\n              <div>\n                <h4 className=\"text-pearl-100 uppercase tracking-wider text-[11px] font-semibold mb-1.5\">Overview</h4>\n                <p className=\"text-pearl-300\">{selectedBlueprint.description}</p>\n              </div>\n\n              <div>\n                <h4 className=\"text-pearl-100 uppercase tracking-wider text-[11px] font-semibold mb-1.5\">Required Permissions</h4>\n                <div className=\"flex flex-wrap gap-1.5 sm:gap-2\">\n                  {selectedBlueprint.permissions.map((p) => (\n                    <span key={p} className=\"px-2.5 py-1 rounded-md bg-space-850 border border-white/10 text-emerald-400 font-mono text-[10px] sm:text-[11px]\">\n                      {p}\n                    </span>\n                  ))}\n                </div>\n              </div>\n\n              {selectedBlueprint.mcpTools.length > 0 && (\n                <div>\n                  <h4 className=\"text-pearl-100 uppercase tracking-wider text-[11px] font-semibold mb-1.5\">Recommended MCP Tools</h4>\n                  <div className=\"flex flex-wrap gap-1.5 sm:gap-2\">\n                    {selectedBlueprint.mcpTools.map((t) => (\n                      <span key={t} className=\"px-2.5 py-1 rounded-md bg-[#2481CC]/10 border border-[#2481CC]/30 text-[#2481CC] font-mono text-[10px] sm:text-[11px]\">\n                        ⚡ {t}\n                      </span>\n                    ))}\n                  </div>\n                </div>\n              )}\n\n              <div className=\"p-3.5 sm:p-4 rounded-xl bg-space-850 border border-white/5\">\n                <h4 className=\"text-pearl-100 uppercase tracking-wider text-[11px] font-semibold mb-1\">Telegram System Templates</h4>\n                <p className=\"text-pearl-400 text-[11px] mb-2 font-sans\">Pre-styled decorative templates provided with this bot:</p>\n                <div className=\"flex flex-wrap gap-1.5\">\n                  {selectedBlueprint.systemTemplates.map((t) => (\n                    <span key={t} className=\"px-2 py-0.5 rounded bg-space-900 text-pearl-300 text-[10px] font-mono\">\n                      /{t}\n                    </span>\n                  ))}\n                </div>\n              </div>\n            </div>\n\n            <div className=\"mt-6 sm:mt-8 pt-4 sm:pt-6 border-t border-white/10 flex flex-col-reverse sm:flex-row items-stretch sm:items-center sm:justify-end gap-2 sm:gap-3\">\n              <button\n                onClick={() => setSelectedBlueprint(null)}\n                className=\"px-5 py-2.5 rounded-xl text-xs text-pearl-400 hover:text-white text-center font-mono\"\n              >\n                Close\n              </button>\n              <button\n                onClick={() => {\n                  const b = selectedBlueprint;\n                  setSelectedBlueprint(null);\n                  handleLaunchInstall(b);\n                }}\n                className=\"btn-telegram-primary py-2.5 px-6 text-xs font-semibold uppercase tracking-wider shadow-telegram text-center\"\n              >\n                Continue to Deployment →\n              </button>\n            </div>\n          </div>\n        </div>\n      )}\n\n      {/* 1-CLICK CLOUD DEPLOY WIZARD MODAL */}\n      {installingBlueprint && (\n        <div className=\"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md animate-in fade-in\">\n          <div className=\"relative w-full max-w-lg rounded-2xl astraea-card border border-white/15 p-4 sm:p-6 md:p-8 shadow-2xl\">\n            <button\n              onClick={() => setInstallingBlueprint(null)}\n              className=\"absolute right-3 sm:right-5 top-3 sm:top-5 p-2 rounded-xl bg-white/5 hover:bg-white/10 text-pearl-400 hover:text-white transition-all\"\n            >\n              <X className=\"w-4 h-4\" />\n            </button>\n\n            <div className=\"flex items-center gap-3 mb-4 sm:mb-6 pr-8\">\n              <div className=\"w-10 h-10 sm:w-12 sm:h-12 rounded-xl bg-[#2481CC]/15 border border-[#2481CC]/40 flex items-center justify-center text-[#2481CC] shrink-0\">\n                <installingBlueprint.icon className=\"w-5 h-5 sm:w-6 sm:h-6\" />\n              </div>\n              <div className=\"min-w-0\">\n                <h3 className=\"text-base sm:text-lg font-bold text-pearl-50 truncate\">Deploy Template to Bot</h3>\n                <p className=\"text-xs text-[#2481CC] font-mono truncate\">{installingBlueprint.name}</p>\n              </div>\n            </div>\n\n            <div className=\"space-y-4\">\n              <div>\n                <label className=\"block text-xs font-semibold text-pearl-300 uppercase tracking-wider mb-1.5 font-mono\">\n                  Target Telegram Bot (Play Console Workspace)\n                </label>\n                <select\n                  value={selectedTargetBot}\n                  onChange={(e) => setSelectedTargetBot(e.target.value)}\n                  className=\"w-full px-4 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs text-pearl-100 focus:outline-none focus:border-[#2481CC] font-mono\"\n                >\n                  {(bots || []).map((b) => (\n                    <option key={b.id} value={b.id}>\n                      {b.name} (@{b.username}) {b.id === currentBot?.id ? '★ CURRENT CHOSEN' : ''}\n                    </option>\n                  ))}\n                </select>\n                <p className=\"text-[10px] text-pearl-400 mt-1 font-mono\">\n                  All blueprint modules, triggers & system templates will be provisioned directly into this bot.\n                </p>\n              </div>\n\n              <div>\n                <label className=\"block text-xs font-semibold text-pearl-300 uppercase tracking-wider mb-1.5 font-mono\">\n                  Custom Instance Name\n                </label>\n                <input\n                  type=\"text\"\n                  value={instanceNameInput}\n                  onChange={(e) => setInstanceNameInput(e.target.value)}\n                  className=\"w-full px-4 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs text-pearl-100 focus:outline-none focus:border-[#2481CC] font-mono\"\n                  placeholder=\"e.g., My Luxury Boutique Store\"\n                />\n              </div>\n\n              <div>\n                <label className=\"block text-xs font-semibold text-pearl-300 uppercase tracking-wider mb-1.5 font-mono\">\n                  Cloud Infrastructure Tier\n                </label>\n                <div className=\"p-3 rounded-xl bg-space-850 border border-white/10 flex items-center justify-between gap-2\">\n                  <div>\n                    <p className=\"text-xs text-pearl-50 font-semibold\">Shared Cloud Worker Pool</p>\n                    <p className=\"text-[10px] sm:text-[11px] text-pearl-400\">24/7 Managed Supervisor Loop (Included in Plan)</p>\n                  </div>\n                  <span className=\"text-[10px] px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 font-semibold shrink-0\">\n                    ACTIVE\n                  </span>\n                </div>\n              </div>\n\n              <div className=\"p-3 rounded-xl bg-space-850 border border-white/5 space-y-2\">\n                <p className=\"text-xs text-pearl-300 font-semibold font-mono\">What happens next:</p>\n                <ul className=\"text-[11px] text-pearl-400 space-y-1 list-disc pl-4 font-sans\">\n                  <li>Blueprint manifest and state tables will be isolated for your tenant.</li>\n                  <li>System templates will be loaded into Message Studio for this bot.</li>\n                  <li>Runtime supervisor will auto-recover bot if Telegram restarts.</li>\n                </ul>\n              </div>\n            </div>\n\n            <div className=\"mt-6 sm:mt-8 pt-4 sm:pt-6 border-t border-white/10 flex flex-col-reverse sm:flex-row items-stretch sm:items-center sm:justify-end gap-2 sm:gap-3\">\n              <button\n                onClick={() => setInstallingBlueprint(null)}\n                className=\"btn-telegram-secondary py-2 px-5 text-xs font-mono\"\n              >\n                Cancel\n              </button>\n              <button\n                onClick={handleConfirmDeploy}\n                className=\"btn-telegram-primary py-2.5 px-6 text-xs font-semibold uppercase tracking-wider shadow-telegram flex items-center justify-center gap-2\"\n              >\n                <Play className=\"w-4 h-4 fill-white\" />\n                <span>Launch 24/7 Cloud Bot</span>\n              </button>\n            </div>\n          </div>\n        </div>\n      )}\n    </div>\n  );\n};\n","Overwrite":true,"Path":"/root/telegram-saas/apps/frontend/src/components/pages/MarketplacePage.tsx"}}]}
{"step_index":5461,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T15:33:53Z","content":"Created At: 2026-11-18T15:33:53Z\nCompleted At: 2026-11-18T15:33:54Z\nCreated At: 2026-11-18T15:33:53Z\nCompleted At: 2026-11-18T15:33:54Z\nCreated file."}
{"step_index":5462,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T15:33:54Z","model":"gemini-3.8-flash-high","input_tokens":15402,"cache_read_tokens":179949,"output_tokens":309,"thinking":"The Marketplace page is updated, ensuring the Telegram theme and direct deployment functionality. Shifting focus to the MessageStudio component located at the specified file path. The component's related files have been identified.\n\n\n","tool_calls":[{"name":"read_file","args":{"EndLine":450,"Path":"/root/telegram-saas/apps/frontend/src/components/MessageStudio/MessageStudio.tsx","StartLine":380}}]}
{"step_index":5463,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T15:34:00Z","content":"Created At: 2026-11-18T15:34:00Z\nCompleted At: 2026-11-18T15:34:00Z\nCreated At: 2026-11-18T15:34:00Z\nCompleted At: 2026-11-18T15:34:00Z\nShowing lines 380-450 of 900\n380:         );\n381:       }\n382:     } catch (err: any) {\n383:       showToast(err.message || 'Failed to save template', 'error');\n384:     } finally {\n385:       setIsSaving(false);\n386:     }\n387:   };\n388: \n389:   return (\n390:     <div className=\"flex flex-col min-h-screen bg-slate-950 text-slate-100 font-sans selection:bg-indigo-500 selection:text-white\">\n391:       {/* Toast Notification */}\n392:       {notification && (\n393:         <div\n394:           className={`fixed top-4 right-4 z-50 flex items-center gap-2 px-4 py-2.5 rounded-xl shadow-xl border text-xs font-semibold animate-slideDown ${\n395:             notification.type === 'success'\n396:               ? 'bg-emerald-950/90 border-emerald-500/50 text-emerald-300'\n397:               : notification.type === 'error'\n398:               ? 'bg-rose-950/90 border-rose-500/50 text-rose-300'\n399:               : 'bg-indigo-950/90 border-indigo-500/50 text-indigo-300'\n400:           }`}\n401:         >\n402:           {notification.type === 'success' && <CheckCircle2 className=\"w-4 h-4 text-emerald-400\" />}\n403:           {notification.type === 'error' && <AlertTriangle className=\"w-4 h-4 text-rose-400\" />}\n404:           {notification.type === 'info' && <Sparkles className=\"w-4 h-4 text-indigo-400\" />}\n405:           <span>{notification.message}</span>\n406:         </div>\n407:       )}\n408: \n409:       {/* Top Navbar */}\n410:       <header className=\"bg-slate-900 border-b border-slate-800 px-3 sm:px-6 py-3.5 sticky top-0 z-40 backdrop-blur-md bg-opacity-95\">\n411:         <div className=\"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4\">\n412:           {/* Left: Branding & Active Bot */}\n413:           <div className=\"flex items-center gap-3\">\n414:             <div className=\"w-8 h-8 rounded-lg bg-indigo-600 flex items-center justify-center text-white shadow-md shrink-0\">\n415:               <Sparkles className=\"w-4 h-4\" />\n416:             </div>\n417:             <div>\n418:               <h1 className=\"text-sm font-bold text-white tracking-tight flex items-center gap-2\">\n419:                 Telegram Bot Message Studio\n420:                 <span className=\"text-[10px] bg-indigo-500/20 text-indigo-400 px-2 py-0.5 rounded-full font-mono\">\n421:                   v2.0\n422:                 </span>\n423:               </h1>\n424:               <span className=\"text-xs text-slate-400 font-mono\">\n425:                 Bot: <strong className=\"text-slate-200\">@{botUsername}</strong>\n426:               </span>\n427:             </div>\n428:           </div>\n429: \n430:           {/* Middle: Template & Preset Selectors */}\n431:           <div className=\"flex flex-wrap items-center gap-2 w-full sm:w-auto\">\n432:             {/* Template Selector */}\n433:             <div className=\"relative flex-1 sm:flex-initial\">\n434:               <select\n435:                 value={selectedTemplateId}\n436:                 onChange={(e) => {\n437:                   const tmpl = templates.find((t) => t.id === e.target.value);\n438:                   if (tmpl) handleSelectTemplate(tmpl);\n439:                 }}\n440:                 className=\"w-full sm:w-auto bg-slate-800 border border-slate-700 rounded-lg pl-3 pr-8 py-1.5 text-xs text-slate-200 font-medium focus:outline-none focus:border-indigo-500 cursor-pointer\"\n441:               >\n442:                 <option value=\"\">-- Active Template: {messageKey} --</option>\n443:                 {templates.map((t) => (\n444:                   <option key={t.id} value={t.id}>\n445:                     {t.title} ({t.message_key}) {t.is_draft ? '[Draft]' : '[Live]'}\n446:                   </option>\n447:                 ))}\n448:               </select>\n449:             </div>\n450: "}
{"step_index":5464,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T15:34:01Z","model":"gemini-3.8-flash-high","input_tokens":3717,"cache_read_tokens":193313,"output_tokens":915,"thinking":"The `MessageStudio.tsx` component appears to have a redundant structure, creating conflicting headers and color styles. Specifically, the root `div` includes `min-h-screen` and slate colors, which duplicates the effect of the sticky header. The suggested solution involves streamlining the layout with a `space-y-6` container and adjusting the toolbar's presentation within. This could resolve the double header issue and improve visual consistency.\n\n\nObserved that the component's styling utilizes a mix of utility classes and custom theme colors, leading to potential inconsistencies. The intention is to standardize the color palette, replacing generic shades with Telegram-specific blues and ensuring a consistent visual appearance across the editor. The layout should be responsive using a grid system for a clearer presentation of metadata, the button matrix, and the live preview.\n\n\n","tool_calls":[{"name":"read_file","args":{"EndLine":100,"Path":"/root/telegram-saas/apps/frontend/src/components/MessageStudio/ButtonMatrixEditor.tsx","StartLine":1}}]}
{"step_index":5465,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T15:34:12Z","content":"Created At: 2026-11-18T15:34:12Z\nCompleted At: 2026-11-18T15:34:13Z\nCreated At: 2026-11-18T15:34:12Z\nCompleted At: 2026-11-18T15:34:13Z\nShowing lines 1-100 of 257\n1: import React from 'react';\n2: import { ButtonSchema } from '../../types/messageStudio';\n3: import { Plus, Trash2, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, ExternalLink, Link2, Sparkles } from 'lucide-react';\n4: \n5: interface ButtonMatrixEditorProps {\n6:   buttons: ButtonSchema[];\n7:   onChange: (buttons: ButtonSchema[]) => void;\n8:   onOpenEmojiPicker?: (targetIndex: number) => void;\n9: }\n10: \n11: export const ButtonMatrixEditor: React.FC<ButtonMatrixEditorProps> = ({\n12:   buttons,\n13:   onChange,\n14: }) => {\n15:   // Group buttons by row_position\n16:   const rowsMap = new Map<number, ButtonSchema[]>();\n17:   buttons.forEach((btn) => {\n18:     const r = btn.row_position ?? 0;\n19:     if (!rowsMap.has(r)) {\n20:       rowsMap.set(r, []);\n21:     }\n22:     rowsMap.get(r)!.push(btn);\n23:   });\n24: \n25:   // Sort rows and columns\n26:   const sortedRowKeys = Array.from(rowsMap.keys()).sort((a, b) => a - b);\n27:   sortedRowKeys.forEach((r) => {\n28:     rowsMap.get(r)!.sort((a, b) => (a.column_position ?? 0) - (b.column_position ?? 0));\n29:   });\n30: \n31:   const updateButtonsNormalized = (newButtons: ButtonSchema[]) => {\n32:     // Re-normalize row and column indices\n33:     onChange(newButtons);\n34:   };\n35: \n36:   const handleAddRow = () => {\n37:     const nextRow = sortedRowKeys.length > 0 ? Math.max(...sortedRowKeys) + 1 : 0;\n38:     const newBtn: ButtonSchema = {\n39:       text: 'New Button',\n40:       button_type: 'callback_data',\n41:       action_value: `act:action_${Date.now()}`,\n42:       row_position: nextRow,\n43:       column_position: 0,\n44:       sort_order: 0,\n45:     };\n46:     updateButtonsNormalized([...buttons, newBtn]);\n47:   };\n48: \n49:   const handleAddColumn = (rowIdx: number) => {\n50:     const existingInRow = rowsMap.get(rowIdx) || [];\n51:     const nextCol = existingInRow.length;\n52:     const newBtn: ButtonSchema = {\n53:       text: `Button ${nextCol + 1}`,\n54:       button_type: 'callback_data',\n55:       action_value: `act:btn_${rowIdx}_${nextCol}`,\n56:       row_position: rowIdx,\n57:       column_position: nextCol,\n58:       sort_order: nextCol,\n59:     };\n60:     updateButtonsNormalized([...buttons, newBtn]);\n61:   };\n62: \n63:   const handleUpdateBtn = (\n64:     rowIdx: number,\n65:     colIdx: number,\n66:     field: keyof ButtonSchema,\n67:     val: any\n68:   ) => {\n69:     const nextButtons = buttons.map((b) => {\n70:       if (b.row_position === rowIdx && b.column_position === colIdx) {\n71:         return { ...b, [field]: val };\n72:       }\n73:       return b;\n74:     });\n75:     updateButtonsNormalized(nextButtons);\n76:   };\n77: \n78:   const handleDeleteBtn = (rowIdx: number, colIdx: number) => {\n79:     const filtered = buttons.filter(\n80:       (b) => !(b.row_position === rowIdx && b.column_position === colIdx)\n81:     );\n82:     // Re-index columns in this row\n83:     const rowRemaining = filtered.filter((b) => b.row_position === rowIdx);\n84:     rowRemaining.sort((a, b) => (a.column_position ?? 0) - (b.column_position ?? 0));\n85:     rowRemaining.forEach((b, idx) => {\n86:       b.column_position = idx;\n87:     });\n88:     updateButtonsNormalized([...filtered]);\n89:   };\n90: \n91:   const handleMoveCol = (rowIdx: number, colIdx: number, direction: 'left' | 'right') => {\n92:     const targetRow = rowsMap.get(rowIdx) || [];\n93:     const targetIdx = direction === 'left' ? colIdx - 1 : colIdx + 1;\n94:     if (targetIdx < 0 || targetIdx >= targetRow.length) return;\n95: \n96:     const currentBtn = targetRow.find((b) => b.column_position === colIdx);\n97:     const adjacentBtn = targetRow.find((b) => b.column_position === targetIdx);\n98:     if (!currentBtn || !adjacentBtn) return;\n99: \n100:     currentBtn.column_position = targetIdx;"}
{"step_index":5466,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T15:34:13Z","model":"gemini-3.8-flash-high","input_tokens":2345,"cache_read_tokens":197034,"output_tokens":74,"tool_calls":[{"name":"read_file","args":{"EndLine":257,"Path":"/root/telegram-saas/apps/frontend/src/components/MessageStudio/ButtonMatrixEditor.tsx","StartLine":101}}]}
{"step_index":5467,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T15:34:17Z","content":"Created At: 2026-11-18T15:34:17Z\nCompleted At: 2026-11-18T15:34:17Z\nCreated At: 2026-11-18T15:34:17Z\nCompleted At: 2026-11-18T15:34:17Z\nShowing lines 101-257 of 257\n101:     adjacentBtn.column_position = colIdx;\n102:     updateButtonsNormalized([...buttons]);\n103:   };\n104: \n105:   return (\n106:     <div className=\"bg-slate-800/80 rounded-xl border border-slate-700 p-4 space-y-4 shadow-sm\">\n107:       <div className=\"flex items-center justify-between\">\n108:         <div>\n109:           <h3 className=\"text-sm font-semibold text-white flex items-center gap-2\">\n110:             <Sparkles className=\"w-4 h-4 text-amber-400\" />\n111:             Inline Keyboard Designer\n112:           </h3>\n113:           <p className=\"text-xs text-slate-400\">\n114:             Design interactive URL and callback buttons in dynamic rows and columns\n115:           </p>\n116:         </div>\n117:         <button\n118:           onClick={handleAddRow}\n119:           className=\"flex items-center gap-1.5 px-3 py-1.5 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg text-xs font-medium transition shadow-sm\"\n120:         >\n121:           <Plus className=\"w-3.5 h-3.5\" />\n122:           Add Row\n123:         </button>\n124:       </div>\n125: \n126:       {sortedRowKeys.length === 0 ? (\n127:         <div className=\"text-center py-6 border-2 border-dashed border-slate-700 rounded-lg\">\n128:           <p className=\"text-xs text-slate-400\">No inline keyboard buttons configured.</p>\n129:           <button\n130:             onClick={handleAddRow}\n131:             className=\"mt-2 text-xs text-indigo-400 hover:text-indigo-300 font-medium inline-flex items-center gap-1\"\n132:           >\n133:             <Plus className=\"w-3 h-3\" />\n134:             Add First Button Row\n135:           </button>\n136:         </div>\n137:       ) : (\n138:         <div className=\"space-y-4\">\n139:           {sortedRowKeys.map((rowKey, rowDisplayIdx) => {\n140:             const rowButtons = rowsMap.get(rowKey) || [];\n141:             return (\n142:               <div\n143:                 key={rowKey}\n144:                 className=\"bg-slate-900/90 rounded-lg p-3 border border-slate-700/60 space-y-2\"\n145:               >\n146:                 <div className=\"flex items-center justify-between text-xs text-slate-400 pb-1 border-b border-slate-800\">\n147:                   <span className=\"font-semibold text-slate-300\">\n148:                     Row {rowDisplayIdx + 1} ({rowButtons.length} {rowButtons.length === 1 ? 'button' : 'buttons'})\n149:                   </span>\n150:                   <button\n151:                     onClick={() => handleAddColumn(rowKey)}\n152:                     className=\"flex items-center gap-1 text-xs text-indigo-400 hover:text-indigo-300\"\n153:                     title=\"Add column button in this row\"\n154:                   >\n155:                     <Plus className=\"w-3 h-3\" />\n156:                     Add Column\n157:                   </button>\n158:                 </div>\n159: \n160:                 <div className=\"grid gap-2 grid-cols-1 sm:grid-cols-2 lg:grid-cols-1\">\n161:                   {rowButtons.map((btn, colIdx) => (\n162:                     <div\n163:                       key={`${rowKey}-${colIdx}`}\n164:                       className=\"bg-slate-800 rounded-md p-2.5 border border-slate-700 space-y-2 relative group hover:border-slate-600 transition\"\n165:                     >\n166:                       <div className=\"flex items-center justify