# VibnCode: Cloud-Powered Agent Desktop IDE Architecture & Implementation Plan

**Project Name:** `vibncode` (formerly TalkCody)  
**Target Architecture:** Desktop Thin Client with Monaco + Native Cloud Hosting Integration  
**Backend Platform:** Vibnai Cloud Infrastructure (`vibn-frontend`, `vibn-agent-runner`, Gitea, Coolify)  
**Status File Location:** `master-ai/VIBNCODE_PLAN.md`

---

## 1. System High-Level Architecture Diagram

`vibncode` functions as a high-fidelity window into your cloud-hosted workspace, routing all actions, skills, and terminal commands to the `vibn-agent-runner` and Gitea/Coolify backend.

```mermaid
graph TD
    %% Styling
    classDef client fill:#E1F5FE,stroke:#0288D1,stroke-width:2px;
    classDef runner fill:#EDE7F6,stroke:#5E35B1,stroke-width:2px;
    classDef infra fill:#E8F5E9,stroke:#2E7D32,stroke-width:2px;

    subgraph Client [Desktop client - vibncode]
        UI[React 19 / Monaco Editor UI]
        State[Zustand Stores / Local SQLite DB Cache]
        Tauri[Tauri v2 App Wrapper]
    end

    subgraph CloudRunner [Cloud Workspace - vibn-agent-runner]
        Runner[Agent Session Runner Engine]
        Workspace[Sandboxed Project Dir: /workspaces]
        Tools[Vibn Platform & Sentry Tools]
    end

    subgraph Infrastructure [Vibnai Platform]
        DB[(PostgreSQL Database)]
        WebAPI[Next.js API Server: vibn-frontend]
        Gitea[(Gitea Git Server)]
        Coolify[Coolify Server Hosting]
    end

    %% Connections
    UI <-->|1. Event Streams & File Sync| WebAPI
    UI -->|2. Start/Cancel Execution| WebAPI
    WebAPI -->|3. Route Exec Request| Runner
    Runner <-->|4. Code Edits & Shell Runs| Workspace
    Runner -->|5. Save Output & File Changes| WebAPI
    WebAPI <-->|6. Write State & Logs| DB
    Runner <-->|7. Push/Pull/Clone Code| Gitea
    Runner -->|8. Manage & Deploy Apps| Coolify
    Workspace -->|9. Pull Guidelines| Gitea

    class UI,State,Tauri client;
    class Runner,Workspace,Tools runner;
    class DB,WebAPI,Gitea,Coolify,Workspace infra;
```

---

## 2. Structural Requirements & Feature Specification

### 2.1 Rebranding to `vibncode`
*   All codebase identifiers, folder structures, logs, config registries, and binary product properties are renamed from `talkcody` to `vibncode` / `VibnCode` to prevent trademark leaks.
*   The application bundle identifier is modified to `com.vibnai.vibncode`.

### 2.2 Preservation of the Desktop UI Experience
*   The Monaco Editor, collapsible multi-panel grid, dark theme, and rich agent step logs are preserved exactly.
*   All compiler execution and file system checks are offloaded to your secure cloud container runner.

### 2.3 Cloud-Hosted Live Browser Preview Pane
*   **Split-Screen Interface**: Adjacent to the Monaco code editor, we inject a live webview/iframe tab.
*   **Wildcard DNS Mapping**: The pane points directly to your dynamic wildcard URL generated during a dev server boot:
    `https://[projectSlug]-[devServerPort].preview.vibnai.com`
*   **Instant Hot-Module Replacement (HMR)**: As the cloud agent or the developer edits files, Vite or Next.js compiles the changes inside the cloud container in milliseconds. Traefik reverse-proxies the stream, causing the embedded browser pane to update instantly on-screen without requiring a manual refresh.

### 2.4 Autonomous Gitea & Coolify Environment Administration
*   We add tabs to the left navigation panel matching the modules of your Vibnai Web Dashboard:
    1.  **Code [📝]**: Monaco editor, virtual filesystem browser.
    2.  **Plan [📋]**: Synchronized feature checklist showing requirements directly tied to `fs_projects.phase_data`.
    3.  **Host [🚀]**: Lists running Coolify application containers, database states, environment credentials (`.env`), and displays live resource monitors (RAM, CPU, Build Logs).
    4.  **Market [📊]**: Suggests GBP categories, researches competitor domains (DataForSEO), and performs technical site scrapes.
    5.  **Preview [🌐]**: Embedded browser preview tab rendering the wildcard live deployment URL.
*   **Autonomous Agent Tools**: The AI is equipped with Gitea and Coolify administration commands (e.g. `git_commit_and_push`, `apps_create_database`, `apps_deploy`, `hosting_set_env`, `project_recent_errors`). The AI can provision databases, modify env keys, verify compiling logs, and fix its own code bugs inside the sandboxed cloud workspaces autonomously.

---

## 3. Database & Database Synchronization Specifications

### 3.1 Mapping Local Client States to PostgreSQL
We will link `vibncode`'s local state structures with your `vibn-frontend` PostgreSQL databases:

*   **Project Lists**: Retrieved via `GET /api/projects` querying the `fs_projects` and `fs_users` tables.
*   **Active Agent Session**: Instantiated via `POST /api/projects/[projectId]/agent/sessions` and updated by `vibn-agent-runner` sending `PATCH /api/projects/[projectId]/agent/sessions/[sessionId]` with `outputLine` and `changedFile` updates.
*   **Virtual File Tree**: Read via `GET /api/workspace/tree` which performs a directory scrape of `/workspaces/[giteaRepo]` and renders a visual file browser in the desktop client's sidebar.

---

## 4. Key Code Paths & Planned Refactoring

To implement this architecture elegantly, the following specific files will be refactored:

### 4.1 Client-Side Refactoring (Tauri / React)
1.  **`src/services/file-service.ts`**: Replace `@tauri-apps/plugin-fs` reads/writes with authorized cloud workspace endpoints:
    *   `GET /api/workspace/tree` $\rightarrow$ Scrapes Gitea directory tree.
    *   `POST /api/workspace/file/read` $\rightarrow$ Fetches content for Monaco.
    *   `POST /api/workspace/file/write` $\rightarrow$ Writes edits back to the cloud.
2.  **`src/services/execution-service.ts`**:
    *   Redirect `startExecution()` to trigger `POST /api/projects/[projectId]/agent/execute` on the server instead of running the loop inside the local app process.
    *   Connect to `vibn-frontend`'s SSE or session poll endpoint to map logs, changed file notifications, and status streams directly to Zustand.
3.  **`src/components/chat/embedded-preview.tsx`** (New Component):
    *   Incorporate a split-screen panel with an `<iframe src="https://[subdomain].preview.vibnai.com" />` which shows/hides adjacent to the Monaco Editor when a dev server is booted.

### 4.2 Server-Side Porting (`vibn-agent-runner`)
1.  **Incorporate Parallel Agent Brain**:
    *   Extract TalkCody's `tool-dependency-analyzer.ts` and `tool-executor.ts` (TypeScript) and port them inside `vibn-agent-runner/src/orchestration/`.
    *   This equips your cloud runner with **4-level Smart Concurrency** (batching parallel reads and serializing write reviews inside Docker).
2.  **Enable the Ralph Loop Autonomy**:
    *   Inject `ralph-loop-service.ts` into your `runSessionAgent()` background executor. This ensures that when the agent outputs self-reflection keywords, the cloud-runner automatically spawns a continuation cycle until the task is complete.

---

## 5. Component-Level Service Redirections (The Vibn Integration Bridge)

To preserve the rich desktop UI completely intact and prevent breaking any complex React views, we map all native local OS dependencies inside `src/components/` to go over our cloud services instead of rewriting the files individually:

### 5.1 Virtualizing file-editor-content.tsx & file-tree.tsx
*   **The Component**: The Monaco Editor panel and the Sidebar File Tree.
*   **Current State**: Calls `repositoryService.readFileContent(path)` and `fastDirectoryTreeService.buildDirectoryTree(rootPath)` which invoke local Rust file-readers and Tauri FS plugins.
*   **Re-engineered Bridge**: We modify `repositoryService` and `fastDirectoryTreeService` to POST to your secure Next.js `POST /api/mcp` endpoint with the actions `"fs.read"` and `"fs.tree"`. This fetches the file content and directories list directly from Gitea inside the `/workspaces` Docker environment and populates Monaco seamlessly.

### 5.2 Redirecting empty-repository-state.tsx
*   **The Component**: The welcoming dashboard panel shown when no local repository folder is opened.
*   **Current State**: Prompts the developer to select a folder on their local hard drive.
*   **Re-engineered Bridge**: When the developer logs in and selects a project on the `projects-page.tsx`, we automatically set the active project `root_path` to the cloud repository path (derived from the database) and immediately trigger the virtual directory tree, bypassing local disk queries entirely.

### 5.3 Bridging file-preview.tsx (Chat Attachments)
*   **The Component**: The attachment downloader inside your chat messages (saving images/videos locally).
*   **Current State**: Uses Tauri's `save` dialog and `plugin-fs` to write bytes to the local Downloads folder.
*   **Re-engineered Bridge**: We modify this to download attachments directly from your GCP Cloud Storage bucket / R2 CDN (`https://cdn.vibnai.com/attachments/...`) over HTTP using the native browser download manager.

---

## 6. Phased Implementation Roadmap

```
PHASE 1: System Rebranding & Desktop App Clean-up
 ├── Rebrand 'talkcody' to 'vibncode' globally across folders & package assets.
 ├── Modify Tauri config JSONs with the bundle ID 'com.vibnai.vibncode'.
 └── Disable local compilers and mock local SQLite caches.

PHASE 2: Backend API Development in Next.js
 ├── Implement virtual file endpoints (POST /api/workspace/file/read, GET /tree).
 └── Establish SSE / WebSockets stream routes for agent output lines.

PHASE 3: UI Layout & Cloud Connection Setup
 ├── Implement left-nav tabs: Plan, Host, Market, and Code.
 ├── Hook file explorer & Monaco to read/write cloud files.
 └── Embed wildcard preview tab pointing to *.preview.vibnai.com.

PHASE 4: Orchestrating the Cloud Agent Brain
 ├── Migrate TalkCody's parallel analyzer & Ralph Loop to vibn-agent-runner.
 └── Enable full, autonomous environment management (Gitea, Sentry, Coolify API).
```
