> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zeus.agentspro.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Coding Mode

> Zeus Coding Mode - AI-powered web application development with live preview

## Overview

Coding Mode is a specialized agent mode that enables AI-powered web application development directly in the browser. When a user selects the **Website** category on the home page, Zeus enters Coding Mode — the AI writes code in a remote sandbox, and changes appear in real-time via an iframe-based live preview panel.

This mode is powered by a **configurable Sandbox Provider (E2B / OpenSandbox / Daytona)** with a pre-installed **Next.js 15 + Tailwind CSS + shadcn/ui** tech stack.

***

## Architecture

```mermaid theme={null}
sequenceDiagram
    participant Home as HomePage
    participant HCI as HomeChatInput
    participant Chat as ChatPage
    participant SSE as StreamProcessor
    participant Backend as AI_Backend
    participant Sandbox as SandboxProvider
    participant Preview as IframePreview

    Home->>HCI: selectedCategory="website"
    HCI->>HCI: "setSettings(mode=coding)"
    HCI->>Chat: "navigate with pending mode"
    Chat->>SSE: "sendMessage(mode=coding)"
    SSE->>Backend: "POST /api/agent/invoke (mode=coding)"
    Backend->>Sandbox: "provider.create(template)"
    Sandbox-->>Backend: sandbox ready port 3000
    Backend-->>SSE: "SSE event coding_ready(previewUrl)"
    SSE-->>Chat: "codingStore.setPreviewUrl(url)"
    Chat->>Preview: "render iframe(previewUrl)"
    
    Note over Backend,Sandbox: AI writes files via coding tools
    Backend->>Sandbox: "provider.write_file(page.tsx)"
    Sandbox->>Sandbox: Next.js HMR detects change
    Preview->>Preview: iframe auto-refreshes
```

### Key Components

| Component                | Location                                                                       | Role                                            |
| ------------------------ | ------------------------------------------------------------------------------ | ----------------------------------------------- |
| **Sandbox Template**     | `ai-backend/sandbox-templates/e2b/nextjs/` or `sandbox-templates/opensandbox/` | Pre-built sandbox image with Next.js + deps     |
| **Coding Sandbox Tools** | `ai-backend/src/utils/tools/built_in/coding_sandbox.py`                        | File operations and shell execution in sandbox  |
| **Coding Mode Prompt**   | `ai-backend/src/repository/prompts/modes/coding_mode.md`                       | System prompt for coding behavior               |
| **CodingPreview**        | `web/src/components/agent/coding-preview/`                                     | Iframe-based live preview component             |
| **codingStore**          | `web/src/store/codingStore.ts`                                                 | Zustand store for preview URL and sandbox state |

***

## Sandbox Templates

To avoid slow startup times from running `npm install` on every session, Zeus uses **pre-built sandbox templates** that include:

* **Node.js 22**
* **pnpm** (global install)
* **Next.js 15** (App Router, TypeScript, Tailwind CSS, ESLint, src dir)
* **shadcn/ui** (commonly used components pre-installed)
* **Extra deps**: lucide-react, framer-motion, clsx, tailwind-merge
* **Code intelligence tools**: typescript, typescript-language-server, pyright, @biomejs/biome (globally pre-installed for LSP diagnostics and CLI linting)
* **Start command**: `npx next dev --turbo` (waits for port 3000)

### E2B Template

```bash theme={null}
cd apps/ai-backend/sandbox-templates/e2b
bun install
# Production template
bun run build:nextjs
# Dev template (lower resources)
bun run build:nextjs:dev
```

Once built, new sandboxes start in \~3-5 seconds with everything pre-installed.

### OpenSandbox Image

```bash theme={null}
cd apps/ai-backend/sandbox-templates/opensandbox/zeus-base
docker build -t zeus-base:latest .
```

### Template Files (E2B)

| File                | Purpose                                                            |
| ------------------- | ------------------------------------------------------------------ |
| `template.ts`       | E2B template definition (base image, install steps, start command) |
| `build.ts`          | Production build script                                            |
| `build.dev.ts`      | Development build script                                           |
| `files/page.tsx`    | Default landing page scaffold                                      |
| `files/layout.tsx`  | Root layout with Inter font                                        |
| `files/globals.css` | Global styles with shadcn CSS variables                            |

***

## Coding Sandbox Tools

When in Coding Mode, the agent has access to a dedicated set of tools that operate on the sandbox filesystem:

| Tool                | Description                                                                                                    |
| ------------------- | -------------------------------------------------------------------------------------------------------------- |
| `coding_write_file` | Create or overwrite files in the project. Supports upsert — Next.js HMR auto-refreshes the preview.            |
| `coding_read_file`  | Read file contents from the project.                                                                           |
| `coding_grep`       | Search file contents using regex patterns (similar to grep/ripgrep). Excludes `node_modules`, `.next`, `.git`. |
| `coding_exec_sh`    | Execute shell commands in the project directory (e.g., `pnpm add dayjs`).                                      |
| `coding_list_files` | List project directory structure (excludes `node_modules`, `.next`, `.git`).                                   |

These tools are separate from the standard `sandbox_*` tools (which are Python-oriented). The coding tools always operate on the `/home/user/project/` directory inside the sandbox container.

### Code Intelligence (LSP)

In Agent mode, Zeus provides the `lsp` tool for code intelligence, supporting:

| Operation           | Description                                                   |
| ------------------- | ------------------------------------------------------------- |
| `diagnostics`       | Get type errors and warnings for a file (like `tsc --noEmit`) |
| `definition`        | Jump to a symbol's definition                                 |
| `references`        | Find all references to a symbol                               |
| `hover`             | Get type information and documentation for a symbol           |
| `document_symbols`  | List all symbols in a file                                    |
| `workspace_symbols` | Search for symbols across the project                         |

Supported language servers: TypeScript (typescript-language-server), Python (pyright), Go (gopls), Rust (rust-analyzer).

Additionally, the `write` and `edit` tools automatically run CLI linters (tsc, pyright, biome, eslint) after saving files, appending diagnostics to the tool output.

***

## Mode Flow

### Entry Point

1. User selects the **Website** category on the Home page
2. `HomeChatInput` stores `zeus_pending_mode = 'coding'` in sessionStorage
3. User submits a query, project and session are created
4. Navigation to chat page occurs

### Chat Page Initialization

1. Chat page reads `zeus_pending_mode` from sessionStorage
2. Sets `chatStore.settings.mode = 'coding'`
3. Clears the sessionStorage key
4. Right panel renders `CodingPreview` instead of `Workspace`

### Backend Flow

1. Agent service detects `mode == 'coding'`
2. Initializes coding sandbox via `init_coding_sandbox()` (uses `zeus-nextjs` template)
3. Retrieves preview URL from sandbox (`sandbox.get_host(3000)`)
4. Sends `coding_ready` SSE event with `preview_url` and `sandbox_id`
5. Injects `CODING_SANDBOX_TOOLS` into agent tool list
6. Loads `coding_mode.md` system prompt
7. Agent begins processing user request with coding tools

### Frontend SSE Handling

1. `stream-processor.ts` receives `coding_ready` event
2. Updates `codingStore` with preview URL and sandbox ID
3. `CodingPreview` component renders iframe with the preview URL
4. Subsequent file writes trigger Next.js HMR — iframe auto-refreshes

***

## Preview Panel

The `CodingPreview` component provides:

* **Iframe display** of the running Next.js dev server
* **Live indicator** showing dev server status (green dot)
* **Refresh button** to manually reload the preview
* **Open in new tab** button for full-screen viewing
* **Loading state** while the sandbox initializes
* **Collapsed state** when the panel is minimized

The preview relies on Next.js Hot Module Replacement (HMR) — when the AI writes a file to the sandbox, the dev server detects the change and pushes updates to the iframe automatically.

***

## Session Isolation

Zeus ensures that workspace state (sandbox files, website preview, tool executions, todos, agent trajectories) is fully isolated per chat session. Switching between conversations never leaks data from one session into another.

### Mechanism

The workspace state is managed by `trajectoryStore`, which maintains an in-memory cache of `SessionWorkspaceSnapshot` objects keyed by session ID:

* **Save / Restore**: When the user navigates away from session A to session B, session A's full workspace state is saved into `_sessionCache`. If session B has a cached snapshot, it is instantly restored; otherwise a clean workspace is initialized.
* **SSE Session Guard**: SSE event streams from the backend are not aborted when switching sessions (to allow the backend agent to continue executing in the background). Instead, a guard in `stream-processor.ts` checks each incoming event's session ID against `_currentSessionId`. Events belonging to a background session are still consumed and saved to the database via `RealtimeEventSaver`, but all store updates (UI state changes) are skipped.
* **State Recovery**: When the user returns to a previous session, the cached snapshot provides instant workspace restoration. Additionally, `loadEventsFromDb` rebuilds the full state from persisted events, including any work the agent completed while the session was in the background.

### Background Agent Execution

When a user switches away from a session where the agent is actively executing:

1. The SSE stream continues consuming events (the backend `StreamingResponse` generator is not interrupted).
2. The backend sandbox stays alive — `sandbox_manager.set_session()` calls `_detach_unlocked()`, which clears the in-memory provider reference without killing the container.
3. Events are persisted to the database by `RealtimeEventSaver` regardless of whether the session is in the foreground.
4. When the user returns, the sandbox can be reconnected via its `sandbox_id` stored in Redis.

### Sandbox ID

The `sandboxId` is part of the session-scoped workspace snapshot. Each session maintains its own sandbox identity, and switching sessions automatically saves and restores the correct `sandboxId`.

***

## Tool Injection & Mode Filtering

Coding mode has its own tool set that replaces the standard sandbox tools:

| Tool Category               | Agent Mode | Ask Mode  | Plan Mode | Coding Mode |
| --------------------------- | ---------- | --------- | --------- | ----------- |
| Filesystem (read/write)     | All        | Read-only | Read-only | Disabled    |
| TodoList                    | All        | All       | All       | All         |
| Memory                      | Read/write | Disabled  | Read-only | Read/write  |
| RAG                         | All        | Read-only | All       | All         |
| Sandbox (Python)            | All        | Disabled  | Disabled  | Disabled    |
| **LSP (Code Intelligence)** | All        | Disabled  | Disabled  | Disabled    |
| **Coding Sandbox**          | Disabled   | Disabled  | Disabled  | **All**     |
| Web Search                  | All        | All       | All       | All         |
| MCP/OAuth                   | All        | Read-only | Read-only | All         |
| Browser/Desktop             | All        | Disabled  | Disabled  | Disabled    |

***

## Configuration

### Environment Variables

| Variable               | Description                                                | Default                 |
| ---------------------- | ---------------------------------------------------------- | ----------------------- |
| `SANDBOX_PROVIDER`     | Sandbox provider type                                      | `e2b`                   |
| `SANDBOX_TIMEOUT`      | Sandbox timeout in seconds                                 | `3600`                  |
| `E2B_API_KEY`          | E2B API key (required for E2B provider)                    | —                       |
| `E2B_SANDBOX_TEMPLATE` | E2B template name                                          | `zeus-nextjs`           |
| `OPENSANDBOX_API_URL`  | OpenSandbox server URL (required for OpenSandbox provider) | `http://localhost:8880` |
| `OPENSANDBOX_IMAGE`    | OpenSandbox sandbox image                                  | `zeus-base:latest`      |

### Dependencies

**Python (ai-backend)**:

* `e2b` — E2B cloud sandbox provider
* `opensandbox-sdk` — Alibaba OpenSandbox self-hosted sandbox provider (optional)

**Node.js (sandbox-templates/e2b)**:

* `e2b` — For building E2B custom templates
* `dotenv` — Environment variable loading

***

## Deployment

After building a project in Coding Mode, Zeus supports deploying it to production via the Deploy API. Three deployment targets are available:

### Vercel

Deploy the sandbox project to Vercel using their REST API.

| Field          | Type              | Description                                           |
| -------------- | ----------------- | ----------------------------------------------------- |
| `sandbox_id`   | string            | The active E2B sandbox ID                             |
| `vercel_token` | string            | Your Vercel API token                                 |
| `project_name` | string (optional) | Vercel project name (defaults to `zeus-<sandbox_id>`) |

```
POST /api/deploy/vercel
```

The flow: connect to sandbox, download source files (excluding `node_modules`, `.next`, `.git`), upload to Vercel API, return the deployment URL.

### Server (SSH)

Deploy to your own server via SSH + rsync, then run a Docker-based deploy script.

| Field             | Type   | Description                     |
| ----------------- | ------ | ------------------------------- |
| `sandbox_id`      | string | The active E2B sandbox ID       |
| `server_host`     | string | Server hostname or IP           |
| `server_port`     | int    | SSH port (default: 22)          |
| `server_user`     | string | SSH username                    |
| `server_password` | string | SSH password                    |
| `server_path`     | string | Deployment path on server       |
| `web_port`        | int    | Web access port (default: 4000) |

```
POST /api/deploy/server
```

The flow: download source from sandbox, rsync to server, execute `deploy/script/deploy-saas.sh` for containerized deployment.

### Freestyle

Deploy using the Freestyle API for persistent preview URLs (`*.style.dev`).

| Field           | Type              | Description                                     |
| --------------- | ----------------- | ----------------------------------------------- |
| `sandbox_id`    | string            | The active E2B sandbox ID                       |
| `session_id`    | string            | Session ID (used for consistent domain mapping) |
| `custom_domain` | string (optional) | Custom domain override                          |

```
POST /api/deploy/freestyle
```

Same session deployments update the same domain. Freestyle auto-detects the framework and handles build + hosting.

### Deploy Environment Variables

| Variable            | Description                                       | Default |
| ------------------- | ------------------------------------------------- | ------- |
| `FREESTYLE_API_KEY` | Freestyle API key (required for Freestyle deploy) | —       |
