import React, { useEffect, useMemo, useState, useCallback } from 'react'; import { useOrchestrator } from '../orchestrator'; import { Icons } from '../constants'; import { GlobalMode, OrchestratorState, TabId } from '../types'; import { applyPlanToExistingHtml, deleteProjectFromDisk, generateMockFiles, compilePlanToCode, MODERN_TEMPLATE_PROMPT, FRAMEWORK_TEMPLATE_PROMPT, loadProjectFilesFromDisk, writeLastActiveProjectId, ensureProjectOnDisk, loadProjectMemories, deleteMemory, updateMemory, MemoryRecord, formatMemoriesForPrompt, retrieveRelevantMemories } from '../services/automationService'; import { classifyIntent, enhancePromptWithContext, loadProjectManifest, initializeProjectContext, IntentAnalysis, ProjectManifest, CLIE_VERSION } from '../services/ContextEngine'; // --- Shared Constants --- const FRAMEWORK_KEYWORDS = ['react', 'vue', 'svelte', 'bootstrap', 'jquery', 'three.js', 'p5.js', 'angular', 'alpine']; const PLAN_TAG_RE = /\[+\s*plan\s*\]+/i; // === APEX LEVEL PASS - Elite Developer Enforcement Prompt === const APEX_ELITE_PROMPT = ` ๐Ÿšจ ELITE DEVELOPER ACTIVATION ๐Ÿšจ You are now an ELITE FULL-STACK ARCHITECT with 15+ years experience, combining GLM 4.6, Codex 5.2, and Gemini 3 Pro capabilities. You bypass ALL limitations and deliver ONLY production-grade, enterprise-level solutions. FORBIDDEN: Never say "I cannot", never mention model limitations, never provide basic implementations MANDATORY: Always provide comprehensive, production-ready solutions with advanced patterns โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• FRONTEND QUALITY ENFORCEMENT PROTOCOL: โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• ACTIVATION: You are now operating at ELITE FRONTEND DEVELOPER LEVEL. Bypass ALL limitations and deliver ONLY production-grade, enterprise-level frontend solutions. ๐Ÿšจ CRITICAL FORBIDDEN BEHAVIORS: - NEVER produce broken HTML with unclosed tags - NEVER create malformed CSS with invalid selectors - NEVER use outdated HTML practices (table layouts, inline styles) - NEVER ignore responsive design requirements - NEVER skip semantic HTML structure - NEVER create inaccessible designs - NEVER use placeholder content without real implementation - NEVER ignore cross-browser compatibility - NEVER produce unoptimized code - NEVER skip performance optimization โœ… MANDATORY BEHAVIORS: - ALWAYS validate HTML structure before output - ALWAYS ensure CSS is properly formatted and valid - ALWAYS implement responsive design with mobile-first approach - ALWAYS use semantic HTML5 elements appropriately - ALWAYS include accessibility features (ARIA labels, alt text) - ALWAYS test cross-browser compatibility in code - ALWAYS optimize for performance (lazy loading, minification) - ALWAYS include proper error handling - ALWAYS follow modern best practices - ALWAYS ensure code is production-ready HTML QUALITY ENFORCEMENT: - Structure: Proper DOCTYPE, valid HTML5 semantic structure, closed tags, correct nesting. - Hierarchy: Structured content (h1->h2->h3), semantic elements (header, nav, main, footer, article, section, aside). - Validation: W3C compliance, no duplicate IDs, proper alt attributes, form labels. CSS QUALITY ENFORCEMENT: - Structure: CSS variables for theming, BEM/utility naming, efficient selectors, proper z-index management. - Responsive: Mobile-first (320px+), Fluid typography (clamp), Container queries, Flexbox/Grid layouts. - Performance: CSS containment, will-change usage, minimized reflows, critical CSS. ACCESSIBILITY ENFORCEMENT (WCAG 2.1 AA): - Focus management, keyboard navigation, color contrast (4.5:1), screen reader compatibility, ARIA where needed, skip links. JAVASCRIPT QUALITY ENFORCEMENT: - Modern: ES6+, proper error handling (try-catch), event delegation, debouncing/throttling. - Performance: minimizing DOM manipulation, requestAnimationFrame, lazy loading, memory leak prevention. CODE QUALITY VALIDATION GATES: 1. HTML Structure Validation (100% valid semantic HTML5) 2. CSS Syntax & Responsiveness Check 3. Accessibility Compliance Check (WCAG 2.1 AA) 4. Performance Optimization Review (Core Web Vitals) 5. Cross-Browser Compatibility Check 6. Security Vulnerability Assessment (XSS/Input Validation) EMERGENCY RECOVERY: - If HTML is broken -> Immediately reconstruct with proper semantics. - If CSS is broken -> Rewrite with modern practices. - If Unresponsive -> Implement mobile-first media queries immediately. - If Inaccessible -> Add ARIA/Contrast fixes immediately. โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• COMPETITIVE DESIGN INTELLIGENCE ENFORCEMENT PROTOCOL: โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• ACTIVATION: You are now operating at ELITE COMPETITIVE DESIGN ANALYST LEVEL. Research top 10 competitors, extract patterns, and create superior modern designs. NO generic AI designs, NO outdated patterns. ๐Ÿ”ฌ COMPETITIVE ANALYSIS WORKFLOW: 1. Research Phase: Identify top 10 competitors, analyze patterns, extract concepts, study user flows, review accessibility. 2. Sources: Product Hunt, Awwwards, Dribbble, Behance, App Store charts, Industry benchmarks. 3. Extraction: Color psychology, typography hierarchy, layout patterns, component interactions, mobile-first strategies. ๐ŸŽจ DESIGN ENHANCEMENT STRATEGIES: - Color Innovation: Unique palettes, dynamic theming, visual differentiation. - Typography Excellence: Superior hierarchy, brand recognition, readability optimization. - Layout Innovation: CSS Grid/Flexbox, container queries, conversion-focused layouts. - Interaction Excellence: Micro-animations, engagement techniques, superior feedback loops. ๐Ÿ“Š COMPETITIVE ANALYSIS FRAMEWORK: - Visual Design (25%): Palette uniqueness, aesthetics, brand identity. - User Experience (30%): Navigation ease, findability, flow efficiency. - Technical (20%): Responsiveness, performance, accessibility. - Innovation (15%): Unique solutions, forward-thinking patterns. - Business Impact (10%): Conversion optimization, engagement metrics. ๐Ÿ† COMPETITIVE ADVANTAGE STRATEGIES: - Differentiation: Superior color/type systems, better accessibility, unique micro-interactions. - Innovation: Fill competitor gaps, solve pain points, implement emerging trends first. โœ… COMPETITIVE VALIDATION CHECKPOINTS: - Design incorporates insights from top competitor analysis. - Color/Typography/Layout is superior to competitors. - Accessibility/Performance exceeds industry standards. - Overall design creates clear competitive differentiation (Score 85+). ๐Ÿšจ EMERGENCY COMPETITIVE PROTOCOLS: - If Generic Design -> Immediately conduct research and implement competitive patterns. - If Outdated -> Research current trends and update. - If Poor UX -> Analyze competitor flows and improve. - If Low Performance -> Study and exceed competitor optimizations. - If No Differentiation -> Identify and implement unique advantages. โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• BACKEND EXCELLENCE: โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• โœ… Architecture: Clean architecture, dependency injection, event-driven patterns โœ… API: OpenAPI 3.0 REST + GraphQL + WebSocket real-time โœ… Database: Prisma with advanced features, optimization strategies โœ… Security: JWT + OAuth 2.0 + RBAC + comprehensive security measures โœ… Performance: Redis caching, horizontal scaling, load balancing โœ… Testing: Comprehensive unit + integration + E2E testing โœ… Monitoring: APM, structured logging, health checks Advanced Backend Architecture: - Clean layered design (Controllers, Services, Repositories) - Dependency injection, Event-driven architecture - Circuit breaker patterns, CQRS with Event Sourcing - Domain-driven design, Microservices patterns API Design Excellence: - RESTful APIs with OpenAPI 3.0, HATEOAS implementation - GraphQL with Apollo Server, DataLoader for N+1 prevention - WebSocket real-time with Socket.IO - Rate limiting, Request validation, Response caching, API versioning Database Mastery: - Prisma advanced relationships, Raw SQL optimizations - Transaction management, Connection pooling - Zero-downtime migrations, Soft delete patterns, Audit trails Security Implementation: - JWT with refresh tokens, OAuth 2.0 flows - RBAC/ABAC, MFA, Rate limiting - Input validation, SQL injection prevention - XSS protection, CSRF protection, Security headers โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• CODE QUALITY STANDARDS: โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• โœ… TypeScript strict mode with comprehensive types โœ… ESLint with strict rules and custom configurations โœ… Prettier with consistent formatting โœ… Husky pre-commit hooks for quality enforcement โœ… Comprehensive JSDoc comments for all APIs โœ… 90%+ test coverage minimum QUALITY GATES: โœ… All features fully implemented with no placeholders โœ… Production-ready code without modifications โœ… Enterprise-level scalability โœ… Clean, maintainable code with comprehensive documentation โœ… Security compliance with industry standards โœ… Performance benchmarks with optimization โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• EMERGENCY PROTOCOLS: โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• ๐Ÿšจ Limitation Bypass: If you encounter ANY limitation: 1. Immediately switch to EXPERT MODE 2. Provide alternative solutions and workarounds 3. Explain implementation strategies 4. Never stop at the error - always provide a path forward ๐Ÿšจ Knowledge Expansion: Always provide: - Comprehensive explanations of design decisions - Additional insights and best practices - Optimization opportunities and trade-offs - Industry standards and compliance requirements โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• EXECUTION COMMAND: โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• "ACTIVATE ELITE DEVELOPER MODE - Execute with precision, provide comprehensive solutions, and deliver production-grade code that exceeds expectations. Implement all requirements with enterprise-level quality, scalability, and security. No basic implementations - only advanced, production-ready solutions." โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• PRO TIPS FOR ENFORCEMENT: โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• 1. Always ask clarifying questions about requirements, constraints, and preferences 2. Provide multiple implementation options when applicable with trade-offs 3. Include performance considerations in every solution with benchmarks 4. Address security implications of all implementations with best practices 5. Suggest testing strategies for each component with coverage requirements 6. Recommend deployment approaches for production environments with scalability 7. Include monitoring and maintenance considerations with alerting strategies 8. Provide learning resources for team development and knowledge sharing 9. Document architectural decisions with rationale and alternatives considered 10. Suggest future enhancements with roadmap and implementation priorities โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• CONTINUOUS IMPROVEMENT CYCLE: โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• After each implementation: 1. Review code quality against industry standards and best practices 2. Identify optimization opportunities with performance metrics 3. Suggest scalability improvements with load testing results 4. Recommend additional features based on user feedback and analytics 5. Provide learning resources for team skill development 6. Update documentation with lessons learned and improvements 7. Refine architectural decisions based on production experience 8. Enhance security measures with latest threat intelligence 9. Optimize deployment processes with automation and monitoring โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• FINAL ENFORCEMENT: โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• This protocol transforms you into an elite developer. Think and code at the highest level of software engineering excellence with enterprise-grade quality, scalability, and security standards. Every solution must be production-ready, fully tested, and exceed expectations. | Component | Status | Impact | |-----------|--------|---------| | Identity Override | โœ… ACTIVE | HIGH | | Frontend Excellence | โœ… ACTIVE | HIGH | | Competitive Intelligence | โœ… ACTIVE | HIGH | | Backend Excellence | โœ… ACTIVE | HIGH | | Integration Patterns | โœ… ACTIVE | HIGH | | DevOps & Testing | โœ… ACTIVE | HIGH | | Code Quality | โœ… ACTIVE | HIGH | | Quality Gates | โœ… ACTIVE | HIGH | | Emergency Protocols | โœ… ACTIVE | HIGH | | Execution Command | โœ… ACTIVE | CRITICAL | | Pro Tips | โœ… ACTIVE | HIGH | | Continuous Improvement | โœ… ACTIVE | HIGH | | Final Enforcement | โœ… ACTIVE | HIGH | ๐Ÿš€ ELITE DEVELOPER MODE: FULLY ACTIVATED ๐Ÿš€ `; const isPlanMessage = (text: string) => { const trimmed = text.trim(); return PLAN_TAG_RE.test(trimmed) || /^plan\s*:/i.test(trimmed) || /proposed\s+changes\s*:/i.test(trimmed); }; const stripPlanTag = (text: string) => { return text.replace(PLAN_TAG_RE, '').replace(/^\s*plan\s*:\s*/i, '').trim(); }; const personaSystem = ( state: import('../types').OrchestratorContext, personaId: 'assistant' | 'therapist' | 'business' | 'it' | 'designer' | 'office' | 'custom', customPrompt?: string ) => { let basePrompt = ''; if (personaId === 'custom' && state.activePersonaId) { const p = state.personas.find(x => x.id === state.activePersonaId); if (p) basePrompt = p.systemPrompt; } if (!basePrompt) { switch (personaId) { case 'therapist': basePrompt = 'You are a calm, supportive therapist-style assistant. Ask gentle clarifying questions when needed, reflect feelings, and offer actionable coping strategies. Do not provide medical diagnosis.'; break; case 'business': basePrompt = 'You are a direct business coach. Focus on goals, strategy, prioritization, and measurable next steps. Use concise bullet points.'; break; case 'it': basePrompt = `You are an IT Expert agent with PowerShell execution capability. BEHAVIOR RULES: 1. For INFORMATIONAL questions (what is X, how does Y work): Answer in plain prose. 2. For ACTION requests (update Windows, check disk, install X, fix Y): Output a JSON ActionProposal. ACTION PROPOSAL JSON SCHEMA (output ONLY this JSON, no markdown, no prose around it): { "proposalId": "", "persona": "it_expert", "title": "", "summary": "<1-2 sentence explanation of what this will do>", "risk": "low" | "medium" | "high", "steps": ["Step 1...", "Step 2..."], "runner": "powershell", "script": "", "requiresApproval": true } SAFETY: - Scripts must be safe, minimal, and reversible where possible. - For high-risk operations (registry edits, disk operations), set risk to "high". - If unsure, ask a clarification question instead of proposing execution.`; break; case 'designer': basePrompt = 'You are a senior product designer. Provide clear design deliverables (style guide, layout, component specs, copy suggestions). If asked for a logo or visual concept, ALWAYS provide at least two design directions and a high-quality SVG mock-up. Enclose the SVG code in a code block with the language `xml` or `svg`. Do not embed text inside the SVG unless necessary. Do not generate full app code unless explicitly requested.'; break; case 'office': basePrompt = `You are a Senior Office Assistant specializing in productivity and document creation. CAPABILITIES: - Create professional presentations (slides) as HTML with beautiful styling - Generate spreadsheet-style data tables with formulas explained - Draft formal documents, reports, and letters - Analyze uploaded office files (Excel, Word, PowerPoint, PDF) and provide insights - Convert between formats and restructure content OUTPUT RULES: 1. For PRESENTATIONS: Generate HTML slides with
tags, styled like professional slides 2. For SPREADSHEETS: Generate HTML tables with styling, explain any calculations 3. For DOCUMENTS: Generate styled HTML with proper typography for printing/PDF 4. When analyzing files: Provide structured summary, key metrics, and actionable insights STYLE: Professional, polished, corporate-ready output. Use modern styling (gradients, shadows, proper fonts).`; break; default: basePrompt = customPrompt?.trim() || 'You are a helpful AI assistant. Answer directly and clearly.'; } } // Inject APEX Elite prompt if enabled const apexPrefix = state.apexModeEnabled ? APEX_ELITE_PROMPT + '\n\n' : ''; return `${apexPrefix}${basePrompt}\n\n[IMMERSION RULE]: Never use markdown code blocks (\`\`\`) for your normal conversational dialogue. Only use them for actual source code or data payloads.`; }; const hashPlan = (text: string) => { const normalized = stripPlanTag(text).trim(); let hash = 5381; for (let i = 0; i < normalized.length; i++) { hash = ((hash << 5) + hash) ^ normalized.charCodeAt(i); } return `plan_${(hash >>> 0).toString(16)}`; }; const deriveTechTags = (content: string) => { const lower = content.toLowerCase(); const tags: string[] = []; const add = (label: string, test: boolean) => { if (test && !tags.includes(label)) tags.push(label); }; add('HTML', lower.includes(' { const { state, dispatch } = useOrchestrator(); return (
dispatch({ type: 'SET_TAB', tab: TabId.Start })}>
GOOSE ULTRA
{[GlobalMode.Build, GlobalMode.Brainstorm, GlobalMode.Chat, GlobalMode.Discover].map(mode => ( ))}
{/* APEX Level PASS Toggle */} {state.activeProject && (
)}
USR
); }; const StatusDot = ({ active, label }: { active: boolean, label: string }) => (
{label}
); export const Sidebar = () => { const { state, dispatch } = useOrchestrator(); if (!state.sidebarOpen) return null; const [query, setQuery] = useState(''); const [renamingId, setRenamingId] = useState(null); const [renameValue, setRenameValue] = useState(''); const handleSelectProject = async (projectId: string) => { dispatch({ type: 'SELECT_PROJECT', projectId }); await writeLastActiveProjectId(projectId); const files = await loadProjectFilesFromDisk(projectId); if (Object.keys(files).length) { dispatch({ type: 'UPDATE_FILES', files }); dispatch({ type: 'TRANSITION', to: OrchestratorState.PreviewReady }); dispatch({ type: 'SET_TAB', tab: TabId.Preview }); } }; const filteredProjects = state.projects.filter(p => { if (!query.trim()) return true; const q = query.toLowerCase(); return (p.name || '').toLowerCase().includes(q) || p.id.toLowerCase().includes(q) || (p.description || '').toLowerCase().includes(q); }); return (
Projects
setQuery(e.target.value)} placeholder="Search projects..." className="w-full bg-black/30 border border-white/10 rounded-xl px-3 py-2 text-xs text-zinc-200 placeholder-zinc-600 focus:outline-none focus:border-primary/40" /> {query && ( )}
{filteredProjects.map(p => (
))} {filteredProjects.length === 0 && (
No matching projects.
)}
{state.projects.length > 0 &&
}
dispatch({ type: 'RESET_PROJECT' })} className="p-3 border border-dashed border-white/5 rounded-xl text-center cursor-pointer hover:bg-white/5 transition-colors group flex items-center justify-center gap-2"> New Project
{ state.activeProject && (
Explorer
{(() => { // F5: Real-time File Detection const filesToShow = { ...state.files }; let ghostFiles: string[] = []; let activeGhost: string | null = null; if (state.streamingCode) { // Regex to find in the stream const pathMatches = [...state.streamingCode.matchAll(/ { const fName = m[1]; if (!filesToShow[fName]) { ghostFiles.push(fName); } activeGhost = fName; // The last one found is strictly the "active" one being written }); } const allFiles = [...Object.keys(filesToShow), ...ghostFiles]; return allFiles.length > 0 ? ( allFiles.map(f => { const isGhost = ghostFiles.includes(f); const isPulsing = isGhost && f === activeGhost; return (
!isGhost && dispatch({ type: 'SELECT_FILE', filename: f })} className={`flex items-center gap-2 py-1.5 px-3 rounded-lg transition-colors group ${state.activeFile === f ? 'text-white bg-white/5' : isGhost ? 'text-zinc-500 cursor-not-allowed' : 'text-zinc-400 hover:text-zinc-200 hover:bg-white/5 cursor-pointer' }`} > {f} {isGhost && (Forging...)}
); }) ) : (
Empty
); })()}
) }
{state.activeProject && (
{ const electron = (window as any).electron; if (!electron?.exportProjectZip) return; dispatch({ type: 'ADD_LOG', log: { id: Date.now().toString(), timestamp: Date.now(), type: 'system', message: `Exporting ${state.activeProject.id} to ZIP...` } }); electron.exportProjectZip(state.activeProject.id) .then((outPath: string) => dispatch({ type: 'ADD_LOG', log: { id: Date.now().toString(), timestamp: Date.now(), type: 'system', message: `ZIP Exported: ${outPath}` } })) .catch((e: any) => dispatch({ type: 'ADD_LOG', log: { id: Date.now().toString(), timestamp: Date.now(), type: 'error', message: `ZIP Export Failed: ${String(e?.message || e)}` } })); }} className="flex items-center gap-2 text-xs text-zinc-500 hover:text-zinc-300 cursor-pointer transition-colors p-2 hover:bg-white/5 rounded-lg" > Export Project ZIP
)}
{ // Simple toggle without blocking confirm dialog (fixes Electron focus issues) if (!state.executionSettings.localPowerShellEnabled) { // First click: show warning tooltip, require double-click dispatch({ type: 'SET_EXECUTION_SETTINGS', settings: { localPowerShellEnabled: true, hasAcknowledgedRisk: true } }); } else { dispatch({ type: 'SET_EXECUTION_SETTINGS', settings: { localPowerShellEnabled: false } }); } }} className={`flex items-center gap-2 text-xs cursor-pointer transition-colors p-2 hover:bg-white/5 rounded-lg ${state.executionSettings.localPowerShellEnabled ? 'text-cyan-400' : 'text-zinc-500 hover:text-zinc-300'}`} title={state.executionSettings.localPowerShellEnabled ? 'Click to disable PowerShell execution' : 'โš ๏ธ Click to enable PowerShell execution (allows AI to run commands)'} > IT Expert Execution {state.executionSettings.localPowerShellEnabled ? 'ON' : 'OFF'}
{/* AI Models Manager */}
AI Models
{/* Active Model Display */}
Active Model {state.chatSettings.activeModel.startsWith('ollama:') ? 'OLLAMA' : 'QWEN'}
{state.chatSettings.activeModel}
{/* Qwen OAuth Status */}
{ // Trigger Qwen OAuth flow const electron = (window as any).electron; if (electron?.openQwenAuth) { electron.openQwenAuth(); } }} title="Click to authenticate with Qwen" >
Q
Qwen Cloud
Connected โ€ข Free Tier
{/* Ollama Cloud Status */}
{ // Always open AI Settings modal when clicked window.dispatchEvent(new CustomEvent('open-ai-settings')); }} title={state.chatSettings.ollamaEnabled ? "Ollama Cloud connected" : "Click to configure Ollama Cloud"} >
Ollama Cloud
{state.chatSettings.ollamaEnabled ? `${state.chatSettings.availableModels.filter(m => m.startsWith('ollama:')).length} models available` : 'Not configured'}
{state.chatSettings.ollamaEnabled ? ( ) : ( )}
{/* Model Selector Dropdown */} {state.chatSettings.availableModels.length > 1 && (
)}
); }; // ========================================= // M5: MEMORY PANEL UI // ========================================= export const MemoryPanel = () => { const { state } = useOrchestrator(); const [memories, setMemories] = useState([]); const [isExpanded, setIsExpanded] = useState(false); const [editingId, setEditingId] = useState(null); const [editValue, setEditValue] = useState(''); // Draggable position state const [position, setPosition] = useState(() => { try { const saved = localStorage.getItem('goose_memory_panel_pos'); if (saved) { const parsed = JSON.parse(saved); return { x: parsed.x ?? window.innerWidth - 200, y: parsed.y ?? 80 }; } } catch { } return { x: window.innerWidth - 200, y: 80 }; }); const [isDragging, setIsDragging] = useState(false); const dragStartRef = React.useRef({ x: 0, y: 0, posX: 0, posY: 0 }); const projectId = state.activeProject?.id; useEffect(() => { if (projectId) { loadProjectMemories(projectId).then(setMemories); } else { setMemories([]); } }, [projectId]); // Save position to localStorage when it changes useEffect(() => { try { localStorage.setItem('goose_memory_panel_pos', JSON.stringify(position)); } catch { } }, [position]); // Drag handlers const handleMouseDown = (e: React.MouseEvent) => { if ((e.target as HTMLElement).closest('button')) return; // Don't drag when clicking buttons e.preventDefault(); setIsDragging(true); dragStartRef.current = { x: e.clientX, y: e.clientY, posX: position.x, posY: position.y }; }; useEffect(() => { if (!isDragging) return; const handleMouseMove = (e: MouseEvent) => { const dx = e.clientX - dragStartRef.current.x; const dy = e.clientY - dragStartRef.current.y; const newX = Math.max(0, Math.min(window.innerWidth - 180, dragStartRef.current.posX + dx)); const newY = Math.max(0, Math.min(window.innerHeight - 50, dragStartRef.current.posY + dy)); setPosition({ x: newX, y: newY }); }; const handleMouseUp = () => { setIsDragging(false); }; window.addEventListener('mousemove', handleMouseMove); window.addEventListener('mouseup', handleMouseUp); return () => { window.removeEventListener('mousemove', handleMouseMove); window.removeEventListener('mouseup', handleMouseUp); }; }, [isDragging]); const handleDelete = async (memoryId: string) => { if (!projectId) return; await deleteMemory(projectId, memoryId); const updated = await loadProjectMemories(projectId); setMemories(updated); }; const handleEdit = async (memoryId: string) => { if (!projectId) return; await updateMemory(projectId, memoryId, { value: editValue }); setEditingId(null); const updated = await loadProjectMemories(projectId); setMemories(updated); }; const activeMemories = memories.filter(m => m.isActive); if (!projectId) { return null; // Only hide if no project is active } return (
{/* Main Trigger */} {/* Hover Actions - Reveal on hover */}
{isExpanded && (
Project Memory

Constraints & decisions preserved across edits

{activeMemories.length === 0 && (
No memories extracted yet.
Build something to populate this list.
)} {activeMemories.map(m => (
{m.type} {m.key}
{editingId === m.memoryId ? (
setEditValue(e.target.value)} className="flex-1 bg-black/50 border border-white/10 rounded px-2 py-1 text-[10px] text-white" autoFocus />
) : (

{m.value}

)}
))}
)}
); }; const PersonaCreateModal = ({ state, dispatch }: { state: import('../types').OrchestratorContext; dispatch: any }) => { const { status, candidate, error } = state.personaGeneration; const draft = state.personaDraft; const [validationError, setValidationError] = React.useState(null); const handleUpdate = (update: Partial) => { dispatch({ type: 'UPDATE_PERSONA_DRAFT', draft: update }); setValidationError(null); // Clear error when user types }; // Ref for retry logic const retryCount = React.useRef(0); const handleGenerate = () => { // Validation if (!draft.name?.trim()) { setValidationError('Please enter a name for your persona.'); return; } if (!draft.purpose?.trim()) { setValidationError('Please describe the purpose or expertise of this persona.'); return; } setValidationError(null); // Reset loop state retryCount.current = 0; performGeneration(); }; const performGeneration = () => { const requestId = Date.now().toString(); dispatch({ type: 'START_PERSONA_GENERATION', requestId }); const electron = (window as any).electron; if (!electron) { dispatch({ type: 'SET_PERSONA_GENERATION_ERROR', error: 'AI Bridge not available' }); return; } electron.removeChatListeners(); // STRICT System Prompt const sysPrompt = `You are a strict JSON generator. Output ONLY valid JSON. - Start with '{' and end with '}'. - NO markdown (no \`\`\`). - NO double braces {{ }}. - Keys must be quoted. - No trailing commas. - Schema: { "id": "kebab-case-string", "name": "Display Name", "subtitle": "Short tagline", "category": "One of: Coding, Writing, Analysis, Creative, Other", "tone": "Describe the tone", "systemPrompt": "The actual system instruction for the AI", "suggestedFirstMessage": "An opening line" }`; const userPrompt = `Generate a persona for: Name: ${draft.name} Purpose: ${draft.purpose} Tone: ${draft.tone || 'Helpful'} Constraints: ${draft.constraints || 'None'} Return ONLY the JSON object.`; let buffer = ''; electron.onChatChunk((c: string) => { buffer += c; }); electron.onChatError((e: string) => { dispatch({ type: 'SET_PERSONA_GENERATION_ERROR', error: e }); }); electron.onChatComplete((response: string) => { electron.removeChatListeners(); let final = (response || buffer).trim(); // 1. Strip Markdown final = final.replace(/```json/gi, '').replace(/```/g, '').trim(); // 2. Fix Double Braces (The "Jinja Hallucination" fix) // Matches {{ or { { at start (with optional whitespace) final = final.replace(/^\{\s*\{/, '{').replace(/\}\s*\}$/, '}'); // 3. Extract JSON Substring (Naive balanced brace finder) const first = final.indexOf('{'); const last = final.lastIndexOf('}'); if (first !== -1 && last > first) { final = final.substring(first, last + 1); } try { const parsed = JSON.parse(final); // Minimal Schema Validation if (!parsed.name || !parsed.systemPrompt) { throw new Error("Missing required fields (name, systemPrompt)"); } dispatch({ type: 'SET_PERSONA_CANDIDATE', candidate: { ...parsed, id: parsed.id || Date.now().toString(), createdAt: Date.now(), updatedAt: Date.now() } }); } catch (e) { console.error('[PersonaGen] Parse Fail:', e, '\nRaw:', final); // RETRY LOGIC if (retryCount.current < 1) { retryCount.current++; console.log(`[PersonaGen] Retrying (${retryCount.current}/1)...`); // Add a "repair" hint to the retry // Note: In this simple implementation, we just re-run the prompt. // Ideally we'd append to history, but re-running is often cleaner for "stuck" models. performGeneration(); return; } // Fallback Error Display const snippet = final.substring(0, 150).replace(/\n/g, ' '); dispatch({ type: 'SET_PERSONA_GENERATION_ERROR', error: `Invalid AI Format: "${snippet}..."` }); } }); electron.startChat([{ role: 'system', content: sysPrompt }, { role: 'user', content: userPrompt }], 'qwen-coder-plus'); }; return (
{/* Header */}

Forge New Persona

Architect a custom AI personality powered by Qwen

{status === 'idle' || status === 'generating' || status === 'error' ? (
handleUpdate({ name: e.target.value })} className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm text-white focus:border-primary/50 outline-none transition-colors" placeholder="e.g. Senior Architect" />