This contains everything you need to run CyberEditor-AI_ app locally.
Prerequisites: Node.js
- Install dependencies:
npm install - Set the
GEMINI_API_KEYin .env.local to your Gemini API key - Run the app:
npm run dev
This project, "CyberEditor AI", is a web-based, AI-powered integrated development environment (IDE) that allows users to create, modify, and manage code projects. It leverages Google's Gemini AI for code generation, explanation, refactoring, and debugging, and integrates with GitHub for version control. The application is built using React and TypeScript, providing a modern, responsive user interface with a distinctive cyberpunk aesthetic.
The primary purpose of CyberEditor AI is to provide a user-friendly interface for interacting with a large language model (LLM) to perform various software development tasks directly within a browser. It acts as a "copilot" that can:
- Generate new multi-file code projects from a high-level description (prompt).
- Explain existing code, providing insights into its purpose and architecture.
- Refactor code to improve its quality, performance, or maintainability.
- Debug code by identifying and suggesting fixes for issues.
Beyond AI capabilities, it offers basic IDE features like file browsing, code editing, and project management (creating, loading, deleting projects). It also supports reading and writing files to the local file system (via the File System Access API) and syncing with GitHub repositories.
The project follows a client-side, single-page application (SPA) architecture, primarily built with React and TypeScript.
-
Frontend (Client-Side React Application):
- Core Logic (
App.tsx): Manages the application's global state (active project, files, output, loading status, settings, modals) using React hooks. It orchestrates interactions between different UI components and services. - Component-Based UI: The user interface is composed of modular React components (e.g.,
Header,Editor,ActionPanel,FileExplorer,ProjectExplorer,OutputDisplay,SettingsPanel,Modal). This promotes reusability and maintainability. - Styling: Uses Tailwind CSS (via CDN) for utility-first styling, augmented with custom CSS for cyberpunk-themed visual effects (glows, scanlines, noise) and theme switching.
- Persistence: Uses
localStorageto save user settings and in-memory projects, allowing state to persist across browser sessions. - Local File System Access: Utilizes the experimental File System Access API (
window.showDirectoryPicker) to allow users to open local folders and save files directly to their disk. - Module Bundler: Vite is used for development server and production builds, providing fast refresh and optimized output.
- Core Logic (
-
AI Integration (External Service):
- Gemini API (
services/geminiService.ts): All AI-related functionalities are handled by calling the Google Gemini API. ThegeminiServiceprepares prompts, sends requests to thegemini-2.5-flashmodel, and processes the AI's JSON or markdown responses. It dynamically configures the Gemini API requests based on the selected AI operation (explain, refactor, debug, generate). - API Key Management: The Gemini API key is loaded from an environment variable (
GEMINI_API_KEY) and exposed to the client-side via Vite'sdefineoption during compilation.
- Gemini API (
-
Version Control Integration (External Service):
- GitHub API (
services/githubService.ts): Facilitates integration with GitHub. Users can import projects from GitHub repositories and commit changes back. This service handles token verification, fetching repository contents, and creating new commits (blobs, trees, commits, and updating references). - Personal Access Token (PAT): Relies on a GitHub Personal Access Token (PAT) with
reposcope for authentication, which users configure in the settings.
- GitHub API (
-
Data Models (
types.ts):- Defines TypeScript interfaces for various data structures used throughout the application, such as
ProjectFile,AIOperation(enum),EditorSettings,GithubUser, and differentProjectSourceInfotypes (memory, local, GitHub). This ensures type safety and clarity.
- Defines TypeScript interfaces for various data structures used throughout the application, such as
In summary, the architecture is a client-heavy web application that intelligently communicates with external AI and version control APIs to provide a rich code editing and AI interaction experience directly in the browser.
- Role: Specifies intentionally untracked files that Git should ignore. This is crucial for keeping the repository clean, preventing sensitive information (like API keys in
.env.localor build artifacts) from being committed, and allowing local development dependencies (node_modules) to be managed separately. - Contents: Includes common ignores for Node.js projects (logs,
node_modules, build outputs likedist), editor-specific directories (.vscode,.idea), and temporary/OS files (.DS_Store). It explicitly ignores*.localfor local environment variables.
- Role: This is the main application component, serving as the root of the React component tree. It manages the global state of the application, orchestrates data flow between components, handles user interactions, and integrates with the backend services (Gemini and GitHub).
- Key Responsibilities:
- State Management: Uses
useStatefor application-wide state, includingprojects(all loaded projects),activeProjectName,activeFilePath,output,isLoading,error,isSandboxed(for File System Access API),activeView(explorer/settings),settings, andmodalConfig. - Data Persistence: Uses
useEffecthooks to load initial projects and settings fromlocalStorageand save them on changes. - File System Access API: Declares global types for
WindowandFileSystem*Handleto enable browser-based local file system interactions (showDirectoryPicker,getFile,createWritable). - Project and File Operations: Contains functions for
handleNewProject,handleDeleteProject,handleOpenFolder(local file system),handleImportFromGithub, andhandleSaveActiveFile. - AI Integration: The
handleRunAIfunction is central, callinggeminiService.runAIAssistantwith the appropriate operation and project context, then updating the UI with results or errors. It handles parsing AI responses and conditionally saving changes. - GitHub Integration: Implements
handleCommitToGithubwhich usesgithubServiceto push changes to a remote repository. - Modal Management: Manages the display and behavior of a generic
Modalcomponent for user prompts, confirmations, and alerts. - UI Layout: Renders the main structure of the IDE, including the header, activity bar, project/file explorers, action panel, editor, and output display.
- State Management: Uses
- Dependencies: Imports React hooks, various types from
./types, services from./services/geminiServiceand./services/githubService, UI components from./components, and file utility from./utils/fileHelpers.
- Role: Contains the MIT License, granting permissive rights for use, modification, and distribution of the software. It specifies the conditions under which the software is provided (e.g., "as is", without warranty).
- Role: Provides basic information about the project, including how to run it locally, prerequisites (Node.js), and setup instructions (installing dependencies, setting Gemini API key, running the dev server).
- Role: Renders a row of buttons that trigger the primary AI operations (EXPLAIN, REFACTOR, DEBUG, GENERATE) and file actions (SAVE, COMMIT).
- Functionality: Each button calls the
onRunAI,onSave, oronCommitprop with the relevantAIOperationor action, disabling itself whenisLoadingor specific conditions are met (e.g., no dirty files for save/commit). - Dependencies: Imports
AIOperationenum from../typesand various SVG icon components from./icons.
- Role: Provides navigation between the "Explorer" view (for projects and files) and the "Settings" view.
- Functionality: Displays two buttons, each with an icon. Clicking a button changes the
activeViewstate inApp.tsx(viaonSetActiveViewprop), which then conditionally rendersProjectExplorer/FileExplorerorSettingsPanel. - Dependencies: Imports
FilesIconandSettingsIcon.
- Role: The main code editing area where users can view and modify file content.
- Functionality: A simple
textareathat displays thevalueprop and callsonChangewhen its content is updated. It's disabled when an AI operation is in progress or no file is active. Includes a placeholder text that adapts to the current state. - Styling: Custom CSS for scrollbar and cyberpunk glow.
- Role: Displays the active project's files and directories in a tree-like structure.
- Functionality:
buildFileTree: A utility function that takes a flat list ofProjectFileobjects and converts it into a nestedFsNode(file system node) structure, grouping files by their directories.TreeNode: A recursive React component used to render each file or folder in the tree. It handles folder expansion/collapse and file selection.- Indicates "dirty" files (those with unsaved changes) with a small colored circle.
- Disables interactions when
isLoading.
- Dependencies: Imports
ProjectFilefrom../typesand various folder/file icons.
- Role: Displays the application's title and a small tagline.
- Styling: Applies cyberpunk-themed text styling with glow effects.
- Role: These files are individual React functional components that render SVG icons (e.g.,
BugIcon,CodeIcon,FilesIcon,GithubIcon,SaveIcon,SettingsIcon,TrashIcon, etc.). - Functionality: They simply render an SVG element, making it easy to embed consistent icons throughout the application and style them using CSS props like
className.
- Role: A generic modal dialog component used for displaying prompts, confirmations, or alerts to the user.
- Functionality:
- Takes
isOpen,onClose,title, andchildrenprops. - Renders an overlay that darkens the background and a central dialog box.
- Includes a title bar with a close button.
- Uses CSS animations for fade-in and slide-in effects.
- Takes
- Dependencies: Imports
CloseIcon.
- Role: Displays the output from AI operations, loading indicators, and error messages.
- Functionality:
- Shows a
LoadingIndicatorwith a spinning animation whenisLoadingis true. - Displays
errormessages prominently in red. - Renders the
outputstring (typically AI responses in markdown or raw text) in a pre-formatted code block.
- Shows a
- Styling: Includes a custom scrollbar and cyberpunk glow.
- Role: Allows users to manage and switch between different projects.
- Functionality:
- Lists all available project names.
- Highlights the
activeProjectName. - Provides buttons for
onNewProject,onOpenFolder(local file system),onImportFromGithub, andonDeleteProject. - The "Open Folder" button has special logic to prompt the user to open in a new tab if the app is detected to be running in a sandboxed environment (e.g., an iframe), as the File System Access API might be restricted.
- Delete button appears on hover for existing projects.
- Dependencies: Imports various folder, link, and GitHub icons.
- Role: Provides a UI for users to configure application settings, specifically the theme and GitHub integration.
- Functionality:
- Theme Selection: Allows choosing between "Cyber Cyan," "Hacker Green," and "Synth Magenta" themes, dynamically updating CSS variables in
index.html. - GitHub Token Input: Enables users to enter and save their GitHub Personal Access Token.
- Token Verification: Offers a "Verify Token" button that uses
githubService.verifyTokento check token validity, scope (repo), and fetch associated user information (name, email) for commit authorship. Displays status and messages for verification.
- Theme Selection: Allows choosing between "Cyber Cyan," "Hacker Green," and "Synth Magenta" themes, dynamically updating CSS variables in
- Persistence: Changes are saved via the
onSettingsChangeprop, which updatesApp.tsx's state and subsequentlylocalStorage. - Dependencies: Imports
EditorSettings,AccentThemefrom../types, andverifyTokenfrom../services/githubService.
- Role: The main HTML file for the single-page application. It's the entry point that the browser loads.
- Contents:
- Sets up basic HTML structure, metadata, and a link to
favicon.svg. - Includes Tailwind CSS via CDN for rapid styling.
- Links to Google Fonts for
Fira Code. - Defines dynamic CSS variables (
--accent-color,--accent-glow, etc.) within a<style>block to support theme switching based onbodyclass. - Includes CSS for visual effects like
scanlinesandnoiseto achieve the cyberpunk aesthetic. - Sets up an
importmapforreact,react-dom, and@google/genaito allow direct import in the browser without a full build step during development (though Vite typically handles this anyway). - Contains the root
div(id="root") where the React application is mounted. - Imports the main React application script (
index.tsx) as a module.
- Sets up basic HTML structure, metadata, and a link to
- Role: The TypeScript entry point for the React application.
- Functionality: It imports the main
Appcomponent and renders it into therootDOM element usingReactDOM.createRoot. UsesReact.StrictModefor development-time checks.
- Role: This file likely contains metadata about the project, possibly used for deployment on a platform like Google AI Studio.
- Contents: Includes
name,description,requestFramePermissions(empty in this case), and aprompt(also empty).
- Role: The standard Node.js manifest file. It defines project metadata, scripts, and dependencies.
- Contents:
name,version,private,type(module).scripts: Defines commands fordev(start Vite development server),build(build for production), andpreview(serve production build locally).dependencies: Lists runtime dependencies for the application (e.g.,react,react-dom,@google/genai).devDependencies: Lists development-only dependencies (e.g.,typescript,vite,@types/node).
- Role: Encapsulates all logic for interacting with the Google Gemini AI API.
- Functionality:
- Initializes the
GoogleGenAIclient using an API key fromprocess.env.API_KEY(injected by Vite). formatProjectForPrompt: Helper function to convert theProjectFile[]array into a structured string format suitable for AI prompts (e.g.,// FILE: path\ncontent\n// END OF FILE).getOperationConfig: Dynamically constructs the Gemini API request configuration (model, system instruction, user prompt, response MIME type, and response schema) based on theAIOperation(EXPLAIN, REFACTOR, DEBUG, GENERATE). It's crucial for instructing the AI how to behave and format its output (especially for JSON responses).runAIAssistant: The main function to send requests to the Gemini API and return the AI's text response. Includes error handling for API communication.
- Initializes the
- Dependencies: Imports
GoogleGenAIandTypefrom@google/genai, andAIOperation,ProjectFilefrom../types.
- Role: Handles all interactions with the GitHub REST API.
- Functionality:
b64_to_utf8andutf8_to_b64: Utility functions for robust Base64 encoding/decoding of UTF-8 strings, necessary for handling GitHub API content blobs.githubFetch: A wrapper aroundfetchthat adds GitHub authentication headers and handles API error responses.isTextFile: A helper to determine if a file path suggests it's a text-based file that should be fetched and displayed.verifyToken: Checks the validity of a GitHub Personal Access Token, verifies it has the requiredreposcope, and fetches the user's name and primary verified email.getRepoContents: Fetches a GitHub repository's file structure and content (for text files only), returning a list ofProjectFileobjects and the latest commit SHA and branch.commitFiles: Implements the GitHub API flow for committing changes:- Gets the base tree SHA from the latest commit.
- Creates new "blob" objects for each changed file content.
- Creates a new "tree" object referencing the blobs.
- Creates a new "commit" object referencing the new tree and the parent commit.
- Updates the branch reference to point to the new commit.
- Dependencies: Imports
ProjectFile,GithubUserfrom../types.
- Role: TypeScript compiler configuration file. It specifies compiler options for the project, such as target JavaScript version, module resolution, JSX support, and strictness checks.
- Key Options:
target:ES2020for modern JS features.jsx:react-jsxfor React 17+ JSX transform.moduleResolution:bundlerfor compatibility with Vite.noEmit: Prevents TypeScript from emitting JavaScript files, as Vite handles the transpilation.strict: Enables all strict type-checking options.paths: Configures path aliases (e.g.,@/*maps to the project root.).
- Role: Defines TypeScript interfaces and enums used across the application. This file centralizes type definitions for consistency and type safety.
- Contents:
AIOperationenum: Lists the different AI functions (EXPLAIN, REFACTOR, DEBUG, GENERATE).ProjectFileinterface: Describes a single file within a project, including itspath,content, andisDirtystatus.Projectstype: A dictionary mapping project names to arrays ofProjectFiles.AccentThemetype: Union type for available color themes.GithubUserinterface: Defines shape for GitHub user info (name, email) for commit authorship.EditorSettingsinterface: Stores user-configurable settings like theme and GitHub token/user.ProjectSourceInfounion type: Describes where a project originates from (local file system, GitHub, or in-memory). This is crucial for determining how to save changes.
- Role: Configuration file for Vite, the build tool.
- Functionality:
define: Injects environment variables (specificallyGEMINI_API_KEY) from the.env.localfile (loaded usingloadEnv) into the client-side bundle. This makesprocess.env.API_KEYavailable in client-side code.resolve.alias: Configures path aliases, allowing imports like@/components/Headerinstead of relative paths.
- Role: Provides utility functions related to file handling.
- Functionality:
isPathTextFile: Determines if a given filepathandfileType(MIME type) are likely to contain human-readable text content. This is used when importing files from the local file system or GitHub to avoid processing binary files. It has a comprehensive list of common text file extensions and checks MIME types.