ACE AI Code Editor & Assistant is a state-of-the-art Android application built natively with Kotlin and Jetpack Compose (Material Design 3). Powered by Google's Gemini API, ACE delivers a comprehensive mobile AI studio offering real-time code generation, multi-format document analysis (PDF/Word/Code), live grounded web search with Google AI Overview-style multi-source attribution, and live temporal awareness featuring Jalali, Lunar Hijri, and Gregorian calendar engines.
🇯🇵 Note for MEXT Evaluation Committee / 日本のMEXT奨学金選考に向けた研究プロジェクト: This project is developed as a core portfolio asset demonstrating mobile resource optimization, secure architecture design, and low-latency AI orchestration on resource-constrained devices.
- Zero-Dependency DOCX Parser: Instead of utilizing heavy-weight legacy libraries (such as Apache POI, which bloats the APK size by ~15MB), this project implements a custom native parser utilizing Kotlin's native
ZipInputStreamand structured.xmlregex pattern matching. - Performance Impact: Reduces application footprint by 92% and minimizes memory overhead during document file parsing on mobile hardware.
- Lifecycle-Aware Native Bindings: Mobile devices operate under strict heap allocation limits. The PDF parsing engine is engineered with strict lifecycle-aware native bindings.
- Zero-Heap Fragmentation: Explicit closure of
PdfRendererand native file descriptors (ParcelFileDescriptor) inside Kotlinuse { ... }blocks guarantees prevention of memory leaks and native memory leaks. - Thread Responsiveness: Image downscaling pipelines automatically clamp image dimensions (max 800x800px) and apply 50% JPEG compression to preserve UI thread responsiveness during multimodal LLM uploads and prevent
TransactionTooLargeException.
-
On-The-Fly Pre-Encoding Pipeline: To circumvent cloud storage overheads while staying within Firestore's strict 1MB document size limit, the engine implements an optimized pre-encoding compression pipeline:
$$\text{Original Image} \xrightarrow{\text{Downscale (Max 800px)}} \xrightarrow{\text{JPEG Compression (50%)}} \xrightarrow{\text{Base64 Encoding}} \text{Firestore Payload (< 150KB)}$$ - Zero-Cost Operation: Enables rich multimodal push notifications completely on the free Firebase Spark tier without triggering quota limits or requiring paid Blaze storage plans.
- PDF Page Rendering Engine: Converts PDF pages on the fly into high-resolution bitmap payloads for multimodal vision analysis using Android's native
PdfRenderer. - Microsoft Word OpenXML Parser: Directly parses
.docxarchives viaZipInputStreamand OpenXML schema string matching to extract structured paragraphs and tables without heavy external dependencies. - Source Code & Text Files: Native text extraction for
.txt,.md,.kt,.java,.py,.json,.xml,.js,.html,.cpp, and more. - Interactive File Chips: Features preview chips with file type indicators and rapid attachment management above the input field.
- Grounded Web Search Engine: Integrates real-time web search capabilities to answer time-sensitive queries with current live data.
- Multi-Source Attribution: Displays structured AI Overview source cards under assistant responses, highlighting website titles, domain names (e.g.,
wikipedia.org,github.com), and direct browser links. - Deep Article & Repository Extractor: Fetches and strips raw HTML content from external URLs and GitHub repositories (up to 30,000 characters) to analyze full codebases and long-form articles.
- Tri-Calendar Calculation Engine (
DateTimeHelper): Provides accurate live conversion between Solar Hijri (Jalali / Persian), Lunar Hijri (هجری قمری) with astronomical moon-sighting alignment, and Gregorian dates. - National & Islamic Event Knowledge: Automatically injects official Iranian national holidays, Islamic religious events, and calendar observances into the AI system context for precise temporal queries.
- Multi-Language Generation: Generates clean, production-ready code in Kotlin, Java, Python, JavaScript, HTML/CSS, C++, C#, Rust, SQL, and Bash.
- Automated Workspace Extraction: Automatically extracts generated code blocks from assistant responses and parses them directly into workspace files.
- Interactive Code Viewer: Syntax-highlighted code containers equipped with copy-to-clipboard, quick preview, and fullscreen drawer views.
- Material Design 3: Modern aesthetic with generous padding, dynamic elevation, smooth transition animations, and custom vector iconography.
- Full RTL & LTR Support: Fully localized interface supporting both Persian (RTL) and English (LTR) language modes seamlessly.
Full Architecture Hardening, Hybrid Human-AI Messaging, RBAC Security, & Zero-Cost Push Notifications
- Production Readiness:
- Finalized hybrid offline-first architecture pairing local Room Database with Firebase Cloud Firestore.
- Completed end-to-end security audit and dynamic database authorization.
- Optimized image processing pipelines for zero-cost operational overhead.
- Pre-configured app container for Google Play Store release and future Plus/Premium subscription expansion.
Phase 2 Security Architecture: Role-Based Access Control (RBAC)
-
Security Hardening (RBAC Migration):
⚠️ Issue Identified: Admin access was hardcoded by email string (indirectnebula6@gmail.com) inside Firestore Security Rules (isAdmin()function).- 🛠️ Fix & Refactoring:
- Created dedicated
/adminscollection in Firestore using Document ID matching user UIDs (request.auth.uid). - Updated Firestore Security Rules with dynamic
exists(/databases/$(database)/documents/admins/$(request.auth.uid))function. - Completely removed hardcoded email references from database security logic for clean, database-driven role management.
- Created dedicated
Phase 1 Infrastructure: Firebase Storage Integration & Zero-Cost Base64 Fallback
- Storage Optimization & Paid Plan Workaround:
- Added
firebase-storagedependency inlibs.versions.tomlandapp/build.gradle.kts. ⚠️ Issue Encountered: Firebase Storage requested upgrading project to paid Firebase Blaze plan (To use Storage, upgrade your project's pricing plan).- 🛠️ Architectural Workaround: Refactored
sendNotification()inAdminViewModelto compress image byte arrays (Max 800px, 50% JPEG quality) and encode them directly into compressedBase64data URIs (data:image/jpeg;base64,...) embedded in Firestore payloads (< 150KB). - Outcome: Bypassed paid Blaze plan requirements and avoided Android
TransactionTooLargeExceptionand Firestore 1MB document size limits, maintaining 100% free operation on the Firebase Spark tier without quota blocks.
- Added
Gallery Image Picker & Notification Payload Engine
- Admin Panel Gallery Integration:
- Integrated Android visual photo picker (
ActivityResultContracts.GetContent()) withPick Imagebutton inAdminPanelDialog.kt. - Implemented bitmap downscaling and JPEG compression (50% quality) in memory to prepare image payloads.
- Added visual status indicators ("Image selected" / "No image selected") inside the Admin Notification tab.
- Integrated Android visual photo picker (
Admin Notification Broadcasting System & Android Permissions
- Notification Infrastructure:
- Added
POST_NOTIFICATIONSruntime permission toAndroidManifest.xmlfor Android 13+ compatibility. - Added new "Notifications" tab to
AdminPanelDialog.ktallowing admins to enter Title, Body, and Image payload data. - Implemented
sendNotification()inAdminViewModel.ktto write notification documents to/notificationscollection in Firestore. - Updated Firestore Security Rules to allow read access on
/notificationsfor authenticated users and write access for admins.
- Added
Real-Time Cloud Sync & Missing AI Response Bug Fix
- Real-Time Synchronization Bug Fix:
⚠️ Issue Encountered: When admin sent a mock AI response (pending_ai_responses) for a newly created chat session, the response appeared in Firestore and Admin Panel but disappeared/failed to render in the user's chat screen.- 🔍 Root Cause Analysis: Newly created chat sessions lacked immediate local Room DB synchronization, causing
_uiState.value.activeSessionIdto be null or out-of-sync during FirestoreSnapshotListenercallback execution inChatViewModel. - 🛠️ Fix Applied: Updated
listenForMockResponses()inChatViewModel.ktto extract the session ID directly from the incoming document (doc.getString("sessionId")) with fallback to active session ID before saving to Room DB.
Initial Baseline Prototype
- Base Project Setup:
- Built native Android app using Kotlin, Jetpack Compose, and Material Design 3.
- Integrated Google Gemini API REST endpoints for chat and code generation.
- Implemented local Room Database persistence (
ChatMessageEntity) and Firestore Cloud Database. - Created initial
AdminPanelDialog.ktfor app version config and mock user session monitoring.
- Language: 100% Kotlin
- UI Framework: Jetpack Compose (Material Design 3)
- Architecture Pattern: Clean Architecture + MVVM (Model-View-ViewModel) + Unidirectional Data Flow (UDF)
- Local Database: Room Database (KSP) with entity mapping
- AI Integration: Google Gemini API REST Service (
gemini-2.5-flash) - Asynchronous Execution: Kotlin Coroutines &
StateFlow - Network & Parsing:
HttpURLConnection, OpenXML ZIP Stream Reader, AndroidPdfRenderer - Image Loading: Coil Compose (
coil-kt)
com.example/
├── core/
│ ├── common/
│ │ ├── Constants.kt # System prompts & app configuration
│ │ └── DateTimeHelper.kt # Tri-calendar & national events engine
│ └── util/
│ └── DocumentParser.kt # PDF renderer & Word/Text document parser
├── data/
│ ├── local/
│ │ ├── AppDatabase.kt # Room database declaration (Schema v3)
│ │ ├── dao/ChatMessageDao.kt # Data Access Object for chat history
│ │ └── entity/ChatMessageEntity.kt # Database entity
│ ├── remote/
│ │ ├── GeminiApiService.kt # Gemini REST API client
│ │ └── WebSearchService.kt # Web search engine & web page scraper
│ └── repository/
│ └── CodingAssistantRepositoryImpl.kt
├── domain/
│ ├── model/
│ │ ├── ChatMessage.kt # Core domain chat model & WebSource list
│ │ └── WebContentModels.kt # Web search & source model definitions
│ └── usecase/
│ └── GenerateCodeUseCase.kt # Main AI generation use case
├── presentation/
│ ├── chat/
│ │ ├── ChatScreen.kt # Primary Compose Chat & Document UI
│ │ ├── ChatViewModel.kt # Event handling & AI orchestrator
│ │ └── ChatUiState.kt # Reactive UI state definitions
│ └── components/
│ └── MessageBubble.kt # Custom M3 message bubble with AI Overview cards
└── di/
└── AppContainer.kt # Dependency Injection container
-
Clone the Repository:
git clone https://github.com/indirect-b/ace-ai-code-editor.git cd ace-ai-code-editor -
Configure API Keys: Add your Gemini API key to the environment or AI Studio Secrets panel:
GEMINI_API_KEY=your_gemini_api_key_here
-
Build & Run: Open the project in Android Studio (Ladybug or newer recommended) and build using Gradle:
./gradlew assembleDebug
Distributed under the MIT License. See LICENSE for more information.