diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 957cd1545..000000000 --- a/.eslintrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["next/core-web-vitals"] -} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..e05f1d176 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,62 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + morphcode-go: + name: morphcode (Go) + runs-on: ubuntu-latest + defaults: + run: + working-directory: morphcode + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version-file: morphcode/go.mod + cache-dependency-path: morphcode/go.sum + + - name: Vet + run: go vet ./... + + - name: Test (race) + run: go test -race ./... + + - name: Build binary + run: CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o bin/morphcode ./cmd/morphcode + + macos-app: + name: Morph Code (macOS) + runs-on: macos-15 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version-file: morphcode/go.mod + cache-dependency-path: morphcode/go.sum + + - name: Install xcodegen + run: brew install xcodegen + + - name: Swift package tests (MorphCore) + working-directory: apple/Packages/MorphCore + run: swift test + + - name: Generate Xcode project + working-directory: apple + run: xcodegen generate + + - name: Build Morph Code (macOS + bundled morphcode) + working-directory: apple + run: | + xcodebuild \ + -project MorphCode.xcodeproj \ + -scheme MorphCode \ + -destination 'platform=macOS' \ + CODE_SIGNING_ALLOWED=NO \ + build diff --git a/.gitignore b/.gitignore index 94b0dad2b..deee4ce7d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,76 +1,33 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js -.yarn/install-state.gz - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc +# macOS .DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# local env files -.env*.local -.env - -# vercel -.vercel - -# typescript -*.tsbuildinfo -next-env.d.ts - -# ============================================================ -# Claudable Specific -# ============================================================ - -# SQLite database -prisma/*.db -prisma/*.db-journal -prisma/*.db-wal - -# Generated projects -data/ -/data/projects/ - -# Logs -*.log - -# IDE -.vscode/ -.idea/ *.swp *.swo -*~ -# OS -.DS_Store -Thumbs.db - -# Temporary files -tmp/ -temp/ -*.tmp - -# YoYo AI version control directory -.yoyo/ - -# Electron build artifacts (too large for GitHub) -dist/ -release/ \ No newline at end of file +# Xcode / Swift +apple/*.xcodeproj/ +apple/*.xcworkspace/ +apple/DerivedData/ +apple/.build/ +apple/Packages/MorphCore/.build/ +apple/Packages/MorphCore/.swiftpm/ +*.xcuserdata +*.xccheckout +*.moved-aside +*.hmap +*.ipa +*.dSYM.zip +*.dSYM +build/ + +# Go +morphcode/bin/ +morphcode/coverage.out +*.test + +# Local state & secrets +.env +.env.* +*.db +*.db-shm +*.db-wal +.worktrees/ diff --git a/README.md b/README.md index 391ff47e0..2fe46c28b 100644 --- a/README.md +++ b/README.md @@ -1,228 +1,141 @@ -# Claudable - -Claudable - -
-

Connect CLI Agent • Build what you want • Deploy instantly

-
- -

- -Latest Release - - -Mentioned in Awesome Claude Code - - -Follow Aaron - - -Join Discord Community - - -GitHub Stars - - -GitHub Forks - - -License - -

- -## What is Claudable? - -Claudable is an open-source Next.js web app builder that combines local AI coding CLI agents (**Claude Code**, **Codex CLI**, **Gemini** through the **Antigravity CLI**, and **OpenCode**) with a fast, **Lovable-grade** visual app-building workspace. - -Describe what you want — *"Build a minimalist habit tracker with weekly analytics"* — and watch Claudable stream code in real time, spin up an instant **Turbopack** live preview, inspect and edit elements visually, checkpoint every turn in Git, verify TypeScript diagnostics in one click, and deploy directly to **Vercel** with **Supabase** and **GitHub**. - -**No extra builder subscription.** Use the CLI agents and plans you already own, 100% locally. - -## Features - -![Claudable Demo](assets/gif/Claudable_v2_cc_4_1080p.gif) - -### Visual Builder & Live Preview -- **Instant Turbopack Preview & Auto-Dependency Sync**: Scaffolded Next.js 15 projects run with `--turbopack` for fast cold starts and HMR (`CLAUDABLE_DISABLE_TURBOPACK=1` to opt out). SHA-256 `package.json` tracking automatically installs newly added packages after AI turns. -- **Visual Element Picker (Select to Edit)**: Click any element inside the live **Desktop / Tablet / Mobile** preview to attach its tag, selector, text, and DOM path directly to your next AI prompt. -- **Preview Error Detection, Live Logs & Fix with AI**: Built-in dev server log drawer, automatic compile/runtime error detection, one-click **Fix with AI**, and an opt-in **Auto-fix** loop (capped at 2 attempts per error). -- **Real-Time Token Streaming & Instant Stop**: Live token-level streaming, a reasoning effort picker next to the model, and immediate generation cancellation at any time. - -### Code Workspace & Version Control -- **Git Checkpoints, Inline Diff & Non-Destructive Restore**: Every AI turn automatically saves a Git checkpoint. Inspect unified commit diffs inline inside Version History and restore forward or backward safely without rewriting history. -- **Multi-Tab Code Editor & `Cmd+P` Quick Search**: Open multiple files with preserved unsaved drafts, full file/folder CRUD, project-wide content search, and syntax highlighting. -- **One-Click TypeScript Check (`tsc --noEmit`)**: Run type checks right inside the Code view, jump straight to any `file:line:col` diagnostic, or click **Fix with AI** to resolve all errors. -- **Project Knowledge (`CLAUDABLE.md` / `CLAUDE.md` / `AGENTS.md`)**: Configure per-project custom instructions in Settings → Knowledge or drop a `CLAUDABLE.md` / `CLAUDE.md` / `AGENTS.md` file in your repo—automatically injected across all 4 CLI agents. -- **Project Duplicate / Remix & ZIP Export**: Duplicate any project from the sidebar (preserving Git history and Knowledge while skipping `node_modules`) or export a clean ZIP archive anytime. - -### Engineered for Speed -- **Sub-3ms Cached CLI Probing**: 30s TTL cache with concurrent in-flight deduplication (`?refresh=1` to bypass). -- **Zero-Churn Chat Rendering**: Memoized Markdown/Thinking renderer and latest-first message pagination keep long sessions smooth during token streaming. -- **SQLite WAL & Single-Request File Tree**: SQLite WAL mode with tuned cache/busy timeout, depth-2 workspace tree loading, and on-demand Settings modal lazy-loading. - -### Deploy & Desktop -- **GitHub, Vercel & Supabase Integrations**: Push to GitHub, connect PostgreSQL/Auth on Supabase, and publish to Vercel directly from the workspace. -- **Desktop App (Electron)**: Build and run natively on macOS, Windows, and Linux. - -## Demo Examples - -### Codex CLI Example - -![Codex CLI Demo](assets/gif/Claudable_v2_codex_1_1080p.gif) - -## Supported AI Coding Agents - -Claudable supports **4 AI coding agents** out of the box—switch agents or models per project anytime, and pick a reasoning effort next to the model: - -| Agent | Featured Models | Notes | -| --- | --- | --- | -| **Claude Code** *(Recommended)* | Claude Fable 5.2, Opus 5.5, Sonnet 5.5 *(default)*, Haiku 5.5 | Reasoning effort from Low to Max, multimodal images, token streaming | -| **Codex CLI** | Codex default *(default, uses your account's model)*, GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, GPT-6 Luna | OpenAI coding agent via ChatGPT subscription or API | -| **Gemini** | Gemini default *(default, uses your account's model)*, Gemini 4 Neon, Gemini 4 Carbon, Gemini 4 Hydrogen | Google's Antigravity CLI with Google account sign-in | -| **OpenCode** | OpenCode default *(default, uses your OpenCode model)*, GLM-5.4, Qwen4 Max, MiniMax M3.1 Flash | Open-source agent for models from many providers | - -The effort menu lists the levels the selected model offers, such as Low to Ultra for GPT-6.2 Sol or Low, High, and Max for GLM-5.4. **Default** leaves the level to the agent. The account default models (Codex default, Gemini default, OpenCode default) only use the agent's level, so the menu is hidden for them. Claudable remembers the level for each model in your browser. - -After you install an agent, sign in from Claudable: open **Settings → AI Agents** and click **Sign in** on the agent's card, or **Connect** on the OpenCode card. Claudable runs the agent's own sign-in and opens it in your browser. The terminal commands below still work. - -### Claude Code (Recommended) -**[Claude Code](https://docs.anthropic.com/en/docs/claude-code/setup)** — Anthropic's agentic coding CLI supporting Claude Fable 5.2, Opus 5.5, Sonnet 5.5, and Haiku 5.5. -- **Pricing**: Included with Claude Pro/Max/Team/Enterprise plans, or Anthropic API key -- **Installation**: - ```bash - npm install -g @anthropic-ai/claude-code - ``` -- **Sign in**: Click **Sign in** on the Claude Code card. If the sign-in page ends with a code, paste it into the card. In a terminal, run `claude auth login`. - -### Codex CLI -**[Codex CLI](https://github.com/openai/codex)** — OpenAI's coding agent with GPT-6.2 Astra, GPT-6.2 Sol, and other GPT models. -- **Pricing**: Included with ChatGPT Plus/Pro/Business/Edu/Enterprise plans (from $20/month) -- **Installation**: - ```bash - npm install -g @openai/codex - ``` -- **Sign in**: Click **Sign in** on the Codex CLI card to sign in with your ChatGPT account. In a terminal, run `codex login`. - -### Gemini (Antigravity CLI) -**[Antigravity CLI](https://antigravity.google/docs/getting-started?tab=cli)** — Google's coding agent CLI (`agy`), which replaces Gemini CLI for personal Google accounts. Claudable runs it in headless mode. -- **Pricing**: Gemini 4 Hydrogen is available on every plan, including free. Gemini 4 Neon and Gemini 4 Carbon need Google AI Pro, Google AI Ultra, or Gemini Enterprise. -- **Installation**: - ```bash - curl -fsSL https://antigravity.google/cli/install.sh | bash - ``` -- **Sign in**: Click **Sign in** on the Gemini card to sign in with your Google account. In a terminal, run `agy` once. - -### OpenCode -**[OpenCode](https://opencode.ai/docs/)** — Open-source coding agent that runs models from many providers, including GLM, Qwen, and MiniMax. -- **Pricing**: The CLI is free. You pay the model provider you connect. -- **Installation**: - ```bash - curl -fsSL https://opencode.ai/v2/install | bash - ``` -- **Sign in**: Click **Connect** on the OpenCode card, then sign in to a model provider or add its API key. In a terminal, run `opencode auth login`. -- **Models**: *OpenCode default* uses the model set in your OpenCode configuration. GLM-5.4 runs on the Z.AI Coding Plan provider, Qwen4 Max on the Alibaba provider, and MiniMax M3.1 Flash on the MiniMax provider, so connect the provider before you pick its model. - -## Prerequisites - -- **Node.js 20+** (`npm >= 10`) -- **Git** -- At least one supported AI CLI agent installed (Claude Code, Codex CLI, Antigravity CLI for Gemini, or OpenCode). You can sign in to it from **Settings → AI Agents**. - -## Quick Start +# Morph Code + +> **Formerly [Claudable](https://github.com/anymorph-ai/morph-code/tree/legacy/v3) — now rewritten from the ground up in SwiftUI + pure Go for v4.** + +**Morph Code** is a fast, local-first native macOS coding agent studio powered by a single-binary pure-Go daemon (`morphcode`). + +No Electron. No Node.js runtime required. Instant SQLite startup, native SwiftUI rendering, built-in live Web Preview, Git diff & worktree workflows, interactive PTY terminal, and first-class support for **Claude Code**, **OpenAI Codex**, **DeepSeek**, and any **OpenAI / Anthropic-compatible custom provider** (OpenRouter, Ollama, Groq, LM Studio, and more). + +--- + +## Why v4 (Claudable → Morph Code)? + +Claudable v1–v3 explored AI app building as a Next.js + Electron workspace. As coding agents became our daily driver for real repositories—not just greenfield web apps—Electron's memory footprint and web-wrapper latency got in the way. + +For **v4**, we rebuilt the entire stack natively and renamed the project to **Morph Code**: + +- **Native macOS UI (SwiftUI + AppKit)** with local SQLite + FTS5 caching—instant navigation and smooth token streaming. +- **Single-binary pure-Go daemon (`morphcode`)** with zero CGO (`modernc.org/sqlite`), embedded directly inside `Morph Code.app/Contents/Helpers/morphcode`. +- **Built-in Live Web Preview** inside the workspace inspector (`⌘⇧P`) so web app building and visual iteration stay right next to your agent threads. +- **Looking for Claudable v3 (Next.js / Electron / Windows & Linux)?** The complete v3.2.1 codebase is preserved on the [`legacy/v3`](https://github.com/anymorph-ai/morph-code/tree/legacy/v3) branch and [`v3.2.1`](https://github.com/anymorph-ai/morph-code/releases/tag/v3.2.1) tag. + +--- + +## Highlights + +- **Bring Your Own CLI or API Keys** + - Works out of the box with your locally installed **`claude`** (Claude Code) and **`codex`** (`codex app-server`) CLIs using your own local authentication. + - Or run directly through Morph Code's built-in pure-Go agent harness (**Morph Harness**) using your own `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `DEEPSEEK_API_KEY`, or custom OpenAI/Anthropic-compatible providers (OpenRouter, Ollama, Groq, etc.). +- **Parallel Multi-Thread Workspace** + - Run independent coding threads across multiple local repositories and Git worktrees in parallel. + - Queue follow-ups, steer active turns mid-run, fork threads, rewind/revert turns via automatic Git checkpoints, and compact long contexts. +- **Built-In Developer Inspector** + - **Git Changes (`⌘⇧G`):** file diffs, stage/unstage, hunk discard, commit, branch checkout, worktrees, PR status, and CI logs (`gh`). + - **PTY Terminal (`⌘⇧T`):** full interactive shell inside each project or worktree. + - **Web Preview (`⌘⇧P`):** live local web preview panel alongside your coding agent. +- **Safety & Approval Controls** + - Choose `Default Permissions`, `Plan`, or `Full Access` per thread, with inline tool approval cards and reusable command allowlist rules. +- **Schedules, Local MCP & CLI Session Import** + - Schedule recurring agent runs with RRULE support, attach local MCP servers, and import existing local Claude Code / Codex CLI sessions (`⌘⇧I`). + +--- + +## Architecture + +```text +morph-code/ +├─ apple/ +│ ├─ project.yml # XcodeGen specification (MorphCode macOS target) +│ ├─ Packages/MorphCore/ # Swift 6 core package (SQLite + FTS5, models, sync, syntax highlighter) +│ ├─ Apps/ +│ │ ├─ Shared/ # Native SwiftUI workspace, sidebar, inspector, terminal, web preview +│ │ └─ MorphMac/ # macOS app entry point, menu commands, local daemon lifecycle +│ └─ scripts/bundle-morphcode.sh # Builds and embeds pure-Go morphcode inside Morph Code.app +└─ morphcode/ + ├─ cmd/morphcode/ # CLI & local daemon (`serve`, `bridge`, `start`, `stop`, `status`, `doctor`) + └─ internal/ + ├─ agent/ # Built-in pure-Go coding agent loop, tools, compaction, MCP client + ├─ checkpoint/ # Automatic per-turn workspace checkpoints and revert + ├─ gitops/ # Git status, diff, worktrees, commits, GitHub PR ops + ├─ harness/ # Official Claude CLI, Codex app-server, and built-in Morph Harness adapters + ├─ model/ # Shared workspace & streaming event schema + ├─ router/ # Single-user local API key & custom provider configuration + ├─ schedule/ # Persistent RRULE scheduler + ├─ server/ # Local HTTP + SSE API (`/v1/code/*`), PTY terminal sessions + └─ store/ # Pure-Go SQLite WAL persistence +``` -```bash -# Clone the repository -git clone https://github.com/anymorph-ai/Claudable.git -cd Claudable +--- -# Install dependencies (auto-configures .env and ports) -npm install +## Quick Start (Build from Source) -# Start the development server -npm run dev -``` +### Requirements -Open **http://localhost:3000** (if port 3000 is busy, Claudable automatically picks the next available port). +- **macOS 15.0+** and **Xcode 16.4+** +- **Go 1.25+** +- **XcodeGen** (`brew install xcodegen`) +- Optional: official [`claude`](https://docs.anthropic.com/en/docs/claude-code) and/or [`codex`](https://github.com/openai/codex) CLI installed locally, or API keys configured in **Settings → Providers**. -### Production Build +### 1. Run `morphcode` Daemon Tests & Build ```bash -npm run prisma:generate -npm run build -npm run start +cd morphcode +go test -race ./... +CGO_ENABLED=0 go build -o bin/morphcode ./cmd/morphcode +./bin/morphcode doctor ``` -### Desktop App (Electron) +### 2. Build & Run the macOS App ```bash -# Development mode -npm run dev:desktop - -# Build & package for your platform -npm run package:mac # macOS -npm run package:win # Windows -npm run package:linux # Linux +cd apple +xcodegen generate +open MorphCode.xcodeproj ``` -### Useful Commands +Or build from the command line (this automatically compiles and embeds `morphcode` inside `Morph Code.app/Contents/Helpers/morphcode`): ```bash -npm run type-check # Run TypeScript check (tsc --noEmit) -npm run lint # Run ESLint -npm run prisma:push # Push Prisma schema to SQLite (data/cc.db) -npm run prisma:studio # Inspect local SQLite database in Prisma Studio -npm run prisma:reset # Reset local SQLite database (WARNING: deletes local data) -npm run check-cli # Verify installed Claude CLI environment +cd apple +xcodegen generate +xcodebuild \ + -project MorphCode.xcodeproj \ + -scheme MorphCode \ + -destination 'platform=macOS' \ + CODE_SIGNING_ALLOWED=NO \ + build ``` -## Keyboard Shortcuts +### 3. Run Swift Core Tests -| Shortcut | Action | -| --- | --- | -| `Cmd/Ctrl + P` | Switch to Code view and focus Quick File Search | -| `Cmd/Ctrl + S` | Save current file in the Code Editor | -| `Cmd/Ctrl + Enter` | Send chat prompt | -| `ArrowUp` / `ArrowDown` | Cycle through prompt history on single-line input | +```bash +cd apple/Packages/MorphCore +swift test +``` -## Integration Guide +--- -### GitHub -1. **Get Token**: [GitHub Personal Access Tokens](https://github.com/settings/tokens) → Generate new token (classic) → select `repo` scope -2. **Connect**: Settings → Services → GitHub → Add token, then create a repository from the Services tab of the project's settings +## Standalone `morphcode` CLI -### Vercel -1. **Get Token**: [Vercel Account Settings](https://vercel.com/account/tokens) → Create Token -2. **Connect**: Settings → Services → Vercel → Add token, then connect Vercel from the Services tab of the project's settings and deploy with **Publish**. Connect GitHub first, because Vercel deploys from the project's repository. +You can also run the Go daemon standalone on macOS or Linux: -### Supabase -1. **Get Token**: [Supabase Access Tokens](https://supabase.com/dashboard/account/tokens) → Generate new token -2. **Connect**: Settings → Services → Supabase → Add token, then create a Supabase project from the Services tab of the project's settings. Claudable adds the Supabase URL and keys to the project's environment variables. +```bash +cd morphcode +go build -o bin/morphcode ./cmd/morphcode -## Troubleshooting +# Check installed CLIs and configured provider keys +./bin/morphcode doctor -- **Database migration conflicts**: If you upgraded from an older version and hit Prisma schema errors, reset the local SQLite database (back up `data/cc.db` first if needed): - ```bash - npm run prisma:reset - ``` -- **Upgrading from a version with Cursor, Qwen, GLM, or MiniMax**: Projects and the default agent saved with one of these agents switch to Claude Code. GLM, Qwen, and MiniMax models now run through OpenCode. API keys saved for GLM or MiniMax stay in `data/global-settings.json` but are no longer used, so connect those providers with **Connect** on the OpenCode card in **Settings → AI Agents** instead. If `npm run prisma:push` warns that it will drop the `active_cursor_session_id` column, run `npx prisma db push --accept-data-loss`; that column only stored Cursor session IDs. -- **Port already in use**: Claudable automatically detects free ports on startup; check `.env` / `.env.local` for assigned ports. -- **Disable Turbopack for a project preview**: Set `CLAUDABLE_DISABLE_TURBOPACK=1` in your environment if a custom Next.js plugin requires webpack dev mode. -- **Claude Code permission issues (Windows / WSL)**: Do not run Claude Code as `root` or with `sudo`. Ensure directory ownership belongs to your user: - ```bash - sudo chown -R $(whoami):$(whoami) ~/Claudable - npm install -g @anthropic-ai/claude-code --unsafe-perm=false - ``` +# Start the local daemon in the background (default: http://127.0.0.1:4415) +./bin/morphcode start +./bin/morphcode status +./bin/morphcode stop +``` -## Roadmap +Configuration and state live locally under `~/.morph-code` (override with `MORPHCODE_DATA_DIR`). Local API keys and custom providers are stored in `~/.morph-code/providers.json` with `0600` permissions, or read from standard environment variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `DEEPSEEK_API_KEY`). -- **Native MCP Server Management UI** — Configure and attach Model Context Protocol tools per project -- **Website Cloning** — Bootstrap a new project from a reference URL -- **Multi-Agent Workflows** — Parallel specialized subagents for design, backend, and QA +--- ## License -[MIT License](LICENSE) - -## Star History - -[![Star History Chart](https://api.star-history.com/svg?repos=anymorph-ai/Claudable&type=Date)](https://www.star-history.com/#anymorph-ai/Claudable&Date) +MIT — see [LICENSE](LICENSE). diff --git a/app/[project_id]/chat/page.tsx b/app/[project_id]/chat/page.tsx deleted file mode 100644 index fe14f49cb..000000000 --- a/app/[project_id]/chat/page.tsx +++ /dev/null @@ -1,3994 +0,0 @@ -"use client"; -import { useEffect, useState, useRef, useCallback, useMemo, useDeferredValue, type ChangeEvent, type KeyboardEvent, type UIEvent } from 'react'; -import { AnimatePresence } from 'framer-motion'; -import { MotionDiv } from '@/lib/motion'; -import { notFound, useRouter, useSearchParams, useParams } from 'next/navigation'; -import dynamic from 'next/dynamic'; -import Image from 'next/image'; -import { FaCog, FaFolder, FaFolderOpen, FaFile, FaFileCode, FaCss3Alt, FaHtml5, FaJs, FaReact, FaPython, FaDocker, FaMarkdown, FaDatabase, FaPhp, FaJava, FaRust, FaVuejs, FaLock, FaChevronRight, FaChevronDown } from 'react-icons/fa'; -import { Tablet, History, Terminal, Download, ExternalLink, FilePlus, FolderPlus, Trash2, Search, Wrench, CheckCircle2, AlertCircle, FileDiff, X, Eye, Code2, Loader2, RotateCw, Monitor, Smartphone, MousePointerClick, Square, Settings, Rocket, Play, WifiOff } from 'lucide-react'; -import { SiTypescript, SiGo, SiRuby, SiSvelte, SiYaml, SiCplusplus } from 'react-icons/si'; -import { VscJson } from 'react-icons/vsc'; -import ChatLog from '@/components/chat/ChatLog'; -import ChatInput, { type SelectedPreviewElement } from '@/components/chat/ChatInput'; -import { ChatErrorBoundary } from '@/components/ErrorBoundary'; -import { useUserRequests } from '@/hooks/useUserRequests'; -import { useReasoningEffort } from '@/hooks/useReasoningEffort'; -import { useGlobalSettings } from '@/contexts/GlobalSettingsContext'; -import { getDefaultModelForCli, getModelDisplayName } from '@/lib/constants/cliModels'; -import { - ACTIVE_CLI_IDS, - ACTIVE_CLI_MODEL_OPTIONS, - ACTIVE_CLI_NAME_MAP, - DEFAULT_ACTIVE_CLI, - buildActiveModelOptions, - normalizeModelForCli, - sanitizeActiveCli, - type ActiveCliId, - type ActiveModelOption, -} from '@/lib/utils/cliOptions'; - -const ProjectSettings = dynamic( - () => import('@/components/settings/ProjectSettings').then((m) => m.ProjectSettings), - { ssr: false } -); - -const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? ''; - -// Keep user-typed preview routes on the preview server's origin -const resolvePreviewRoute = (previewBase: string, route: string): string => { - try { - const url = new URL(previewBase.split('?')[0]); - const target = new URL(route.startsWith('/') ? route : '/' + route, url.origin); - url.pathname = target.pathname; - url.search = target.search; - url.hash = target.hash; - return url.href; - } catch { - return previewBase; - } -}; - -const CLI_LABELS = ACTIVE_CLI_NAME_MAP; - -const CLI_ORDER = ACTIVE_CLI_IDS; - -const sanitizeCli = (cli?: string | null) => sanitizeActiveCli(cli, DEFAULT_ACTIVE_CLI); - -const sanitizeModel = (cli: string, model?: string | null) => normalizeModelForCli(cli, model, DEFAULT_ACTIVE_CLI); - -type Entry = { path: string; type: 'file'|'dir'; size?: number }; -type ProjectStatus = 'initializing' | 'active' | 'failed'; - -type CliStatusSnapshot = { - available?: boolean; - configured?: boolean; - models?: string[]; -}; - -type ModelOption = Omit & { cli: string }; - -const buildModelOptions = (statuses: Record): ModelOption[] => - buildActiveModelOptions(statuses).map(option => ({ - ...option, - cli: option.cli, - })); - -// TreeView component for VSCode-style file explorer -interface TreeViewProps { - entries: Entry[]; - selectedFile: string; - expandedFolders: Set; - folderContents: Map; - onToggleFolder: (path: string) => void; - onSelectFile: (path: string) => void; - onLoadFolder: (path: string) => Promise; - onDeleteEntry?: (path: string, type: 'file' | 'dir') => void; - level: number; - parentPath?: string; - getFileIcon: (entry: Entry) => React.ReactElement; -} - -function TreeView({ entries, selectedFile, expandedFolders, folderContents, onToggleFolder, onSelectFile, onLoadFolder, onDeleteEntry, level, parentPath = '', getFileIcon }: TreeViewProps) { - // Ensure entries is an array - if (!entries || !Array.isArray(entries)) { - return null; - } - - // Group entries by directory - const sortedEntries = [...entries].sort((a, b) => { - // Directories first - if (a.type === 'dir' && b.type === 'file') return -1; - if (a.type === 'file' && b.type === 'dir') return 1; - // Then alphabetical - return a.path.localeCompare(b.path); - }); - - return ( - <> - {sortedEntries.map((entry, index) => { - // entry.path should already be the full path from API - const fullPath = entry.path; - let entryKey = - fullPath && typeof fullPath === 'string' && fullPath.trim().length > 0 - ? fullPath.trim() - : (entry as any)?.name && typeof (entry as any).name === 'string' && (entry as any).name.trim().length > 0 - ? `${parentPath || 'root'}::__named_${(entry as any).name.trim()}` - : ''; - if (!entryKey || entryKey.trim().length === 0) { - entryKey = `${parentPath || 'root'}::__entry_${level}_${index}_${entry.type}`; - } - const isExpanded = expandedFolders.has(fullPath); - const indent = level * 8; - - return ( -
-
{ - if (entry.type === 'dir') { - // Load folder contents if not already loaded - if (!folderContents.has(fullPath)) { - await onLoadFolder(fullPath); - } - onToggleFolder(fullPath); - } else { - onSelectFile(fullPath); - } - }} - > - {/* Chevron for folders */} -
- {entry.type === 'dir' && ( - isExpanded ? - : - - )} -
- - {/* Icon */} - - {entry.type === 'dir' ? ( - isExpanded ? - : - - ) : ( - getFileIcon(entry) - )} - - - {/* File/Folder name */} - - {entry.path.split('/').pop() || entry.path} - - - {onDeleteEntry && ( - - )} -
- - {/* Render children if expanded */} - {entry.type === 'dir' && isExpanded && folderContents.has(fullPath) && ( - - )} -
- ); - })} - - ); -} - -export default function ChatPage() { - const params = useParams<{ project_id: string }>(); - const projectId = params?.project_id ?? ''; - const router = useRouter(); - const searchParams = useSearchParams(); - - // NEW: UserRequests state management - const { - hasActiveRequests, - createRequest, - startRequest, - completeRequest, - clearActiveRequests - } = useUserRequests({ projectId }); - - const [projectName, setProjectName] = useState(''); - const [projectMissing, setProjectMissing] = useState(false); - const [projectDescription, setProjectDescription] = useState(''); - const [previewUrl, setPreviewUrl] = useState(null); - const previewUrlRef = useRef(null); - const [tree, setTree] = useState([]); - const [content, setContent] = useState(''); - const [editedContent, setEditedContent] = useState(''); - const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false); - const [isSavingFile, setIsSavingFile] = useState(false); - const [saveFeedback, setSaveFeedback] = useState<'idle' | 'success' | 'error'>('idle'); - const [saveError, setSaveError] = useState(null); - const [selectedFile, setSelectedFile] = useState(''); - const [openTabs, setOpenTabs] = useState([]); - const [dirtyTabs, setDirtyTabs] = useState>(new Set()); - const tabDraftsRef = useRef>(new Map()); - const fileSearchInputRef = useRef(null); - const [currentPath, setCurrentPath] = useState('.'); - const [expandedFolders, setExpandedFolders] = useState>(new Set([''])); - const [folderContents, setFolderContents] = useState>(new Map()); - const [prompt, setPrompt] = useState(''); - - // Ref to store add/remove message handlers from ChatLog - const messageHandlersRef = useRef<{ - add: (message: any) => void; - remove: (messageId: string) => void; - } | null>(null); - - // Ref to track pending requests for deduplication - const pendingRequestsRef = useRef>(new Set()); - - // Stable message handlers to prevent reassignment issues - const stableMessageHandlers = useRef<{ - add: (message: any) => void; - remove: (messageId: string) => void; - } | null>(null); - - // Track active optimistic messages by requestId - const optimisticMessagesRef = useRef>(new Map()); - const [isRunning, setIsRunning] = useState(false); - const [isSseFallbackActive, setIsSseFallbackActive] = useState(false); - const [showPreview, setShowPreview] = useState(true); - const [deviceMode, setDeviceMode] = useState<'desktop'|'tablet'|'mobile'>('desktop'); - const [showGlobalSettings, setShowGlobalSettings] = useState(false); - const [previewError, setPreviewError] = useState(null); - const [showPreviewLogs, setShowPreviewLogs] = useState(false); - const [previewLogs, setPreviewLogs] = useState([]); - const [isLoadingPreviewLogs, setIsLoadingPreviewLogs] = useState(false); - const [isInspectorActive, setIsInspectorActive] = useState(false); - const [selectedElement, setSelectedElement] = useState(null); - const [showHistoryPanel, setShowHistoryPanel] = useState(false); - const [checkpoints, setCheckpoints] = useState< - Array<{ - sha: string; - shortSha: string; - message: string; - authorName: string; - committedAt: string; - filesChanged: string[]; - }> - >([]); - const [historyHeadSha, setHistoryHeadSha] = useState(null); - const [isLoadingHistory, setIsLoadingHistory] = useState(false); - const [restoringSha, setRestoringSha] = useState(null); - const [expandedDiffSha, setExpandedDiffSha] = useState(null); - const [checkpointDiffs, setCheckpointDiffs] = useState< - Record - >({}); - const [isCheckingTypes, setIsCheckingTypes] = useState(false); - const [typeCheckResult, setTypeCheckResult] = useState<{ - ok: boolean; - timedOut?: boolean; - errorCount: number; - errors: Array<{ file: string; line: number; column: number; code: string; message: string }>; - rawOutput?: string; - durationMs: number; - } | null>(null); - const [showTypeCheckDrawer, setShowTypeCheckDrawer] = useState(false); - const [autoFixPreviewErrors, setAutoFixPreviewErrors] = useState(false); - const autoFixAttemptsRef = useRef<{ signature: string; count: number }>({ signature: '', count: 0 }); - const [fileSearchQuery, setFileSearchQuery] = useState(''); - const [fileSearchMatches, setFileSearchMatches] = useState< - Array<{ path: string; matchType: 'path' | 'content'; lineNumber?: number; preview?: string }> - >([]); - const [isSearchingFiles, setIsSearchingFiles] = useState(false); - const [uploadedImages, setUploadedImages] = useState<{name: string; url: string; base64?: string; path?: string}[]>([]); - const [isInitializing, setIsInitializing] = useState(true); - // Initialize states with default values, will be loaded from localStorage in useEffect - const [hasInitialPrompt, setHasInitialPrompt] = useState(false); - const [agentWorkComplete, setAgentWorkComplete] = useState(false); - const [projectStatus, setProjectStatus] = useState('initializing'); - const [initializationMessage, setInitializationMessage] = useState('Starting project initialization...'); - const [initialPromptSent, setInitialPromptSent] = useState(false); - const initialPromptSentRef = useRef(false); - const [showPublishPanel, setShowPublishPanel] = useState(false); - const [publishLoading, setPublishLoading] = useState(false); - const [githubConnected, setGithubConnected] = useState(null); - const [vercelConnected, setVercelConnected] = useState(null); - const [publishedUrl, setPublishedUrl] = useState(null); - const [deploymentId, setDeploymentId] = useState(null); - const [deploymentStatus, setDeploymentStatus] = useState<'idle' | 'deploying' | 'ready' | 'error'>('idle'); - const deployPollRef = useRef(null); - const [isStartingPreview, setIsStartingPreview] = useState(false); - const [previewStartFailed, setPreviewStartFailed] = useState(false); - const [cliStatuses, setCliStatuses] = useState>({}); - const [conversationId, setConversationId] = useState(() => { - if (typeof window !== 'undefined' && window.crypto?.randomUUID) { - return window.crypto.randomUUID(); - } - return ''; - }); - const [preferredCli, setPreferredCli] = useState(DEFAULT_ACTIVE_CLI); - const [selectedModel, setSelectedModel] = useState(getDefaultModelForCli(DEFAULT_ACTIVE_CLI)); - const [usingGlobalDefaults, setUsingGlobalDefaults] = useState(true); - const { - effort: reasoningEffort, - levels: reasoningEffortLevels, - setEffort: setReasoningEffort, - } = useReasoningEffort(preferredCli, selectedModel); - const [isUpdatingModel, setIsUpdatingModel] = useState(false); - const [currentRoute, setCurrentRoute] = useState('/'); - const iframeRef = useRef(null); - const editorRef = useRef(null); - const highlightRef = useRef(null); - const lineNumberRef = useRef(null); - const editedContentRef = useRef(''); - const [isFileUpdating, setIsFileUpdating] = useState(false); - const modelOptions = useMemo(() => buildModelOptions(cliStatuses), [cliStatuses]); - const cliOptions = useMemo( - () => CLI_ORDER.map(cli => ({ - id: cli, - name: CLI_LABELS[cli] || cli, - available: Boolean(cliStatuses[cli]?.available && cliStatuses[cli]?.configured) - })), - [cliStatuses] - ); - - const updatePreferredCli = useCallback((cli: string) => { - const sanitized = sanitizeCli(cli); - setPreferredCli(sanitized); - if (typeof window !== 'undefined') { - sessionStorage.setItem('selectedAssistant', sanitized); - } - }, []); - - const updateSelectedModel = useCallback((model: string, cliOverride?: string) => { - const effectiveCli = cliOverride ? sanitizeCli(cliOverride) : preferredCli; - const sanitized = sanitizeModel(effectiveCli, model); - setSelectedModel(sanitized); - if (typeof window !== 'undefined') { - sessionStorage.setItem('selectedModel', sanitized); - } - }, [preferredCli]); - - useEffect(() => { - previewUrlRef.current = previewUrl; - }, [previewUrl]); - - const sendInitialPrompt = useCallback(async (initialPrompt: string) => { - if (initialPromptSent) { - return; - } - - setAgentWorkComplete(false); - localStorage.setItem(`project_${projectId}_taskComplete`, 'false'); - - const requestId = crypto.randomUUID(); - - try { - setIsRunning(true); - setInitialPromptSent(true); - - const requestBody = { - instruction: initialPrompt, - images: [], - isInitialPrompt: true, - cliPreference: preferredCli, - conversationId: conversationId || undefined, - requestId, - selectedModel, - reasoningEffort, - }; - - const r = await fetch(`${API_BASE}/api/chat/${projectId}/act`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(requestBody), - }); - - if (!r.ok) { - const errorText = await r.text(); - console.error('API Error:', errorText); - setInitialPromptSent(false); - return; - } - - const result = await r.json(); - const returnedConversationId = - typeof result?.conversationId === 'string' - ? result.conversationId - : typeof result?.conversation_id === 'string' - ? result.conversation_id - : undefined; - if (returnedConversationId) { - setConversationId(returnedConversationId); - } - - const resolvedRequestId = - typeof result?.requestId === 'string' - ? result.requestId - : typeof result?.request_id === 'string' - ? result.request_id - : requestId; - const userMessageId = - typeof result?.userMessageId === 'string' - ? result.userMessageId - : typeof result?.user_message_id === 'string' - ? result.user_message_id - : ''; - - createRequest(resolvedRequestId, userMessageId, initialPrompt); - setPrompt(''); - - const newUrl = new URL(window.location.href); - newUrl.searchParams.delete('initial_prompt'); - window.history.replaceState({}, '', newUrl.toString()); - } catch (error) { - console.error('Error sending initial prompt:', error); - setInitialPromptSent(false); - } finally { - setIsRunning(false); - } - }, [initialPromptSent, preferredCli, conversationId, projectId, selectedModel, reasoningEffort, createRequest]); - - // Guarded trigger that can be called from multiple places safely - const triggerInitialPromptIfNeeded = useCallback(() => { - const initialPromptFromUrl = searchParams?.get('initial_prompt'); - if (!initialPromptFromUrl) return; - if (initialPromptSentRef.current) return; - // Synchronously guard to prevent double ACT calls - initialPromptSentRef.current = true; - setInitialPromptSent(true); - - // Store the selected model and assistant in sessionStorage when returning - const cliFromUrl = searchParams?.get('cli'); - const modelFromUrl = searchParams?.get('model'); - if (cliFromUrl) { - const sanitizedCli = sanitizeCli(cliFromUrl); - sessionStorage.setItem('selectedAssistant', sanitizedCli); - if (modelFromUrl) { - sessionStorage.setItem('selectedModel', sanitizeModel(sanitizedCli, modelFromUrl)); - } - } else if (modelFromUrl) { - sessionStorage.setItem('selectedModel', sanitizeModel(preferredCli, modelFromUrl)); - } - - // Don't show the initial prompt in the input field - // setPrompt(initialPromptFromUrl); - setTimeout(() => { - sendInitialPrompt(initialPromptFromUrl); - }, 300); - }, [searchParams, sendInitialPrompt, preferredCli]); - -const loadCliStatuses = useCallback(async () => { - const optimistic: Record = {}; - ACTIVE_CLI_IDS.forEach(id => { - const models = ACTIVE_CLI_MODEL_OPTIONS[id]?.map(model => model.id) ?? []; - optimistic[id] = { - available: true, - configured: true, - models, - }; - }); - setCliStatuses(prev => (Object.keys(prev).length === 0 ? optimistic : prev)); - - try { - const response = await fetch(`${API_BASE}/api/settings/cli-status`, { cache: 'no-store' }); - if (!response.ok) return; - const raw = await response.json(); - const resolved: Record = {}; - ACTIVE_CLI_IDS.forEach(id => { - const entry = raw?.[id]; - const models = ACTIVE_CLI_MODEL_OPTIONS[id]?.map(model => model.id) ?? []; - if (entry && typeof entry === 'object') { - const installed = Boolean(entry.installed ?? entry.available ?? true); - resolved[id] = { - available: installed, - configured: Boolean(entry.configured ?? installed), - models, - }; - } else { - resolved[id] = { available: true, configured: true, models }; - } - }); - setCliStatuses(resolved); - } catch { - // Keep optimistic snapshot if cli-status probe fails - } -}, []); - -const persistProjectPreferences = useCallback( - async (changes: { preferredCli?: string; selectedModel?: string }) => { - if (!projectId) return; - const payload: Record = {}; - if (changes.preferredCli) { - const sanitizedPreferredCli = sanitizeCli(changes.preferredCli); - payload.preferredCli = sanitizedPreferredCli; - payload.preferred_cli = sanitizedPreferredCli; - } - if (changes.selectedModel) { - const targetCli = sanitizeCli(changes.preferredCli ?? preferredCli); - const normalized = sanitizeModel(targetCli, changes.selectedModel); - payload.selectedModel = normalized; - payload.selected_model = normalized; - } - if (Object.keys(payload).length === 0) return; - - const response = await fetch(`${API_BASE}/api/projects/${projectId}`, { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(payload), - }); - - if (!response.ok) { - const errorText = await response.text(); - throw new Error(errorText || 'Failed to update project preferences'); - } - - const result = await response.json().catch(() => null); - return result?.data ?? result; - }, - [projectId, preferredCli] -); - - const handleModelChange = useCallback( - async (option: ModelOption, opts?: { skipCliUpdate?: boolean; overrideCli?: string }) => { - if (!projectId || !option) return; - - const { skipCliUpdate = false, overrideCli } = opts || {}; - const targetCli = sanitizeCli(overrideCli ?? option.cli); - const sanitizedModelId = sanitizeModel(targetCli, option.id); - - const previousCli = preferredCli; - const previousModel = selectedModel; - - if (targetCli === previousCli && sanitizedModelId === previousModel) { - return; - } - - setUsingGlobalDefaults(false); - updatePreferredCli(targetCli); - updateSelectedModel(option.id, targetCli); - - setIsUpdatingModel(true); - - try { - const preferenceChanges: { preferredCli?: string; selectedModel?: string } = { - selectedModel: sanitizedModelId, - }; - if (!skipCliUpdate && targetCli !== previousCli) { - preferenceChanges.preferredCli = targetCli; - } - - await persistProjectPreferences(preferenceChanges); - - const cliLabel = CLI_LABELS[targetCli] || targetCli; - const modelLabel = getModelDisplayName(targetCli, sanitizedModelId); - try { - await fetch(`${API_BASE}/api/chat/${projectId}/messages`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - content: `Switched to ${cliLabel} (${modelLabel})`, - role: 'system', - message_type: 'info', - cli_source: targetCli, - conversation_id: conversationId || undefined, - }), - }); - } catch (messageError) { - console.warn('Failed to record model switch message:', messageError); - } - - loadCliStatuses(); - } catch (error) { - console.error('Failed to update model preference:', error); - updatePreferredCli(previousCli); - updateSelectedModel(previousModel, previousCli); - alert('Failed to update model. Please try again.'); - } finally { - setIsUpdatingModel(false); - } - }, - [projectId, preferredCli, selectedModel, conversationId, loadCliStatuses, persistProjectPreferences, updatePreferredCli, updateSelectedModel] - ); - - useEffect(() => { - loadCliStatuses(); - }, [loadCliStatuses]); - - const handleCliChange = useCallback( - async (cliId: string) => { - if (!projectId) return; - if (cliId === preferredCli) return; - - setUsingGlobalDefaults(false); - - const candidateModels = modelOptions.filter(option => option.cli === cliId); - const fallbackOption = - candidateModels.find(option => option.id === selectedModel && option.available) || - candidateModels.find(option => option.available) || - candidateModels[0]; - - if (fallbackOption) { - await handleModelChange(fallbackOption, { overrideCli: cliId }); - return; - } - - const previousCli = preferredCli; - const previousModel = selectedModel; - setIsUpdatingModel(true); - - try { - updatePreferredCli(cliId); - const defaultModel = getDefaultModelForCli(cliId); - updateSelectedModel(defaultModel, cliId); - await persistProjectPreferences({ preferredCli: cliId, selectedModel: defaultModel }); - loadCliStatuses(); - } catch (error) { - console.error('Failed to update CLI preference:', error); - updatePreferredCli(previousCli); - updateSelectedModel(previousModel, previousCli); - alert('Failed to update CLI. Please try again.'); - } finally { - setIsUpdatingModel(false); - } - }, - [projectId, preferredCli, selectedModel, modelOptions, handleModelChange, loadCliStatuses, persistProjectPreferences, updatePreferredCli, updateSelectedModel] - ); - - useEffect(() => { - if (!modelOptions.length) return; - const hasSelected = modelOptions.some(option => option.cli === preferredCli && option.id === selectedModel); - if (!hasSelected) { - const fallbackOption = modelOptions.find(option => option.cli === preferredCli && option.available) - || modelOptions.find(option => option.cli === preferredCli) - || modelOptions.find(option => option.available) - || modelOptions[0]; - if (fallbackOption) { - void handleModelChange(fallbackOption); - } - } - }, [modelOptions, preferredCli, selectedModel, handleModelChange]); - - const loadDeployStatus = useCallback(async () => { - try { - // Use the same API as ServiceSettings to check actual project service connections - const response = await fetch(`${API_BASE}/api/projects/${projectId}/services`); - if (response.status === 404) { - setGithubConnected(false); - setVercelConnected(false); - setPublishedUrl(null); - setDeploymentStatus('idle'); - return; - } - - if (response.ok) { - const connections = await response.json(); - const githubConnection = connections.find((conn: any) => conn.provider === 'github'); - const vercelConnection = connections.find((conn: any) => conn.provider === 'vercel'); - - // Check actual project connections (not just token existence) - setGithubConnected(!!githubConnection); - setVercelConnected(!!vercelConnection); - - // Set published URL only if actually deployed - if (vercelConnection && vercelConnection.service_data) { - const sd = vercelConnection.service_data; - // Only use actual deployment URLs, not predicted ones - const rawUrl = sd.last_deployment_url || null; - const url = rawUrl ? (String(rawUrl).startsWith('http') ? String(rawUrl) : `https://${rawUrl}`) : null; - setPublishedUrl(url || null); - if (url) { - setDeploymentStatus('ready'); - } else { - setDeploymentStatus('idle'); - } - } else { - setPublishedUrl(null); - setDeploymentStatus('idle'); - } - } else { - setGithubConnected(false); - setVercelConnected(false); - setPublishedUrl(null); - setDeploymentStatus('idle'); - } - - } catch (e) { - console.warn('Failed to load deploy status', e); - setGithubConnected(false); - setVercelConnected(false); - setPublishedUrl(null); - setDeploymentStatus('idle'); - } - }, [projectId]); - - const startDeploymentPolling = useCallback((depId: string) => { - if (deployPollRef.current) clearInterval(deployPollRef.current); - setDeploymentStatus('deploying'); - setDeploymentId(depId); - - deployPollRef.current = setInterval(async () => { - try { - const r = await fetch(`${API_BASE}/api/projects/${projectId}/vercel/deployment/current`); - if (r.status === 404) { - setDeploymentStatus('idle'); - setDeploymentId(null); - setPublishLoading(false); - if (deployPollRef.current) { - clearInterval(deployPollRef.current); - deployPollRef.current = null; - } - return; - } - if (!r.ok) return; - const data = await r.json(); - - // Stop polling if no active deployment (completed) - if (!data.has_deployment) { - // Set final deployment URL - if (data.last_deployment_url) { - const url = String(data.last_deployment_url).startsWith('http') ? data.last_deployment_url : `https://${data.last_deployment_url}`; - setPublishedUrl(url); - setDeploymentStatus('ready'); - } else { - setDeploymentStatus('idle'); - } - - // End publish loading state (important: release loading even if no deployment) - setPublishLoading(false); - - if (deployPollRef.current) { - clearInterval(deployPollRef.current); - deployPollRef.current = null; - } - return; - } - - // If there is an active deployment - const status = data.status; - - // Check if deployment is ready or failed - const isReady = status === 'READY'; - const isBuilding = status === 'BUILDING' || status === 'QUEUED'; - const isError = status === 'ERROR'; - - if (isError) { - console.error('Deployment failed:', status); - setDeploymentStatus('error'); - - // End publish loading state - setPublishLoading(false); - - // Close publish panel after error (with delay to show error message) - setTimeout(() => { - setShowPublishPanel(false); - }, 3000); // Show error for 3 seconds before closing - - if (deployPollRef.current) { - clearInterval(deployPollRef.current); - deployPollRef.current = null; - } - return; - } - - if (isReady && data.deployment_url) { - const url = String(data.deployment_url).startsWith('http') ? data.deployment_url : `https://${data.deployment_url}`; - setPublishedUrl(url); - setDeploymentStatus('ready'); - - // End publish loading state - setPublishLoading(false); - - // Keep panel open to show the published URL - - if (deployPollRef.current) { - clearInterval(deployPollRef.current); - deployPollRef.current = null; - } - } else if (isBuilding) { - setDeploymentStatus('deploying'); - } - } catch (error) { - console.error('Polling error:', error); - } - }, 1000); // Changed to 1 second interval - }, [projectId]); - - const checkCurrentDeployment = useCallback(async () => { - try { - const response = await fetch(`${API_BASE}/api/projects/${projectId}/vercel/deployment/current`); - if (response.status === 404) { - return; - } - - if (response.ok) { - const data = await response.json(); - if (data.has_deployment) { - setDeploymentId(data.deployment_id); - setDeploymentStatus('deploying'); - setPublishLoading(false); - setShowPublishPanel(true); - startDeploymentPolling(data.deployment_id); - } - } - } catch (e) { - console.warn('Failed to check current deployment', e); - } - }, [projectId, startDeploymentPolling]); - - const start = useCallback(async () => { - setIsStartingPreview(true); - setPreviewStartFailed(false); - try { - const r = await fetch(`${API_BASE}/api/projects/${projectId}/preview/start`, { method: 'POST' }); - const payload = await r.json().catch(() => null); - const data = payload?.data ?? {}; - - // The start call also returns when the dev server crashed during startup - if (!r.ok || data.status === 'error' || data.status === 'stopped') { - setPreviewUrl(null); - setPreviewLogs(Array.isArray(data.logs) ? data.logs : []); - setPreviewError(data.lastError || payload?.error || 'The development server stopped during startup.'); - setPreviewStartFailed(true); - return; - } - - setPreviewUrl(typeof data.url === 'string' ? data.url : null); - setPreviewError(typeof data.lastError === 'string' && data.lastError ? data.lastError : null); - setCurrentRoute('/'); // Reset to root route when starting - } catch (error) { - console.error('Error starting preview:', error); - setPreviewError(error instanceof Error ? error.message : 'Failed to start preview'); - setPreviewStartFailed(true); - } finally { - setIsStartingPreview(false); - } - }, [projectId]); - - // Navigate to specific route in iframe - const navigateToRoute = (route: string) => { - if (previewUrl && iframeRef.current) { - const normalizedRoute = route.startsWith('/') ? route : `/${route}`; - iframeRef.current.src = resolvePreviewRoute(previewUrl, normalizedRoute); - setCurrentRoute(normalizedRoute); - } - }; - - const refreshPreview = useCallback(() => { - if (!previewUrl || !iframeRef.current) { - return; - } - - try { - const normalizedRoute = - currentRoute && currentRoute.startsWith('/') - ? currentRoute - : `/${currentRoute || ''}`; - const baseUrl = previewUrl.split('?')[0] || previewUrl; - const url = new URL(baseUrl + normalizedRoute); - url.searchParams.set('_ts', Date.now().toString()); - iframeRef.current.src = url.toString(); - } catch (error) { - console.warn('Failed to refresh preview iframe:', error); - } - }, [previewUrl, currentRoute]); - - - const stop = useCallback(async () => { - try { - await fetch(`${API_BASE}/api/projects/${projectId}/preview/stop`, { method: 'POST' }); - setPreviewUrl(null); - } catch (error) { - console.error('Error stopping preview:', error); - } - }, [projectId]); - - const loadSubdirectory = useCallback(async (dir: string): Promise => { - try { - const r = await fetch(`${API_BASE}/api/repo/${projectId}/tree?dir=${encodeURIComponent(dir)}`); - const data = await r.json(); - return Array.isArray(data) ? data : []; - } catch (error) { - console.error('Failed to load subdirectory:', error); - return []; - } - }, [projectId]); - - const loadTree = useCallback(async (dir = '.') => { - try { - const r = await fetch(`${API_BASE}/api/repo/${projectId}/tree?dir=${encodeURIComponent(dir)}&depth=2`); - const data = await r.json(); - - if (data && !Array.isArray(data) && Array.isArray(data.entries)) { - setTree(data.entries); - const newFolderContents = new Map(); - if (data.folders && typeof data.folders === 'object') { - Object.entries(data.folders as Record).forEach(([folderPath, children]) => { - if (Array.isArray(children)) { - newFolderContents.set(folderPath, children); - } - }); - } - setFolderContents(newFolderContents); - } else if (Array.isArray(data)) { - setTree(data); - const newFolderContents = new Map(); - const dirs = data.filter((entry: Entry) => entry.type === 'dir'); - await Promise.all( - dirs.map(async (entry: Entry) => { - try { - const subContents = await loadSubdirectory(entry.path); - newFolderContents.set(entry.path, subContents); - } catch (err) { - console.error(`Failed to load contents for ${entry.path}:`, err); - } - }), - ); - setFolderContents(newFolderContents); - } else { - console.error('Tree data is not an array:', data); - setTree([]); - } - - setCurrentPath(dir); - } catch (error) { - console.error('Failed to load tree:', error); - setTree([]); - } - }, [projectId, loadSubdirectory]); - - // Load folder contents - const handleLoadFolder = useCallback(async (folderPath: string) => { - const contents = await loadSubdirectory(folderPath); - const nestedDirs = contents.filter((entry) => entry.type === 'dir'); - - setFolderContents(prev => { - const newMap = new Map(prev); - newMap.set(folderPath, contents); - return newMap; - }); - - if (nestedDirs.length > 0) { - const nestedResults = await Promise.all( - nestedDirs.map(async (entry) => ({ - path: entry.path, - contents: await loadSubdirectory(entry.path), - })), - ); - setFolderContents(prev => { - const newMap = new Map(prev); - for (const item of nestedResults) { - newMap.set(item.path, item.contents); - } - return newMap; - }); - } - }, [loadSubdirectory]); - - // Toggle folder expansion - function toggleFolder(path: string) { - setExpandedFolders(prev => { - const newSet = new Set(prev); - if (newSet.has(path)) { - newSet.delete(path); - } else { - newSet.add(path); - } - return newSet; - }); - } - - // Build tree structure from flat list - function buildTreeStructure(entries: Entry[]): Map { - const structure = new Map(); - - // Initialize with root - structure.set('', []); - - entries.forEach(entry => { - const parts = entry.path.split('/'); - const parentPath = parts.slice(0, -1).join('/'); - - if (!structure.has(parentPath)) { - structure.set(parentPath, []); - } - structure.get(parentPath)?.push(entry); - - // If it's a directory, ensure it exists in the structure - if (entry.type === 'dir') { - if (!structure.has(entry.path)) { - structure.set(entry.path, []); - } - } - }); - - return structure; - } - - const openFile = useCallback(async (path: string) => { - try { - // Persist current tab's draft in memory before switching (zero-friction multi-tab editing) - if (selectedFile && selectedFile !== path) { - const currentEdited = editedContentRef.current; - tabDraftsRef.current.set(selectedFile, { saved: content, edited: currentEdited }); - setDirtyTabs((prev) => { - const next = new Set(prev); - if (currentEdited !== content) next.add(selectedFile); - else next.delete(selectedFile); - return next; - }); - } - - setOpenTabs((prev) => (prev.includes(path) ? prev : [...prev, path])); - setSaveFeedback('idle'); - setSaveError(null); - - // Instant switch if this tab is already cached in memory - const cached = tabDraftsRef.current.get(path); - if (cached) { - setContent(cached.saved); - setEditedContent(cached.edited); - editedContentRef.current = cached.edited; - setHasUnsavedChanges(cached.edited !== cached.saved); - setSelectedFile(path); - setIsFileUpdating(false); - return; - } - - const r = await fetch(`${API_BASE}/api/repo/${projectId}/file?path=${encodeURIComponent(path)}`); - - if (!r.ok) { - console.error('Failed to load file:', r.status, r.statusText); - const fallback = '// Failed to load file content'; - setContent(fallback); - setEditedContent(fallback); - editedContentRef.current = fallback; - setHasUnsavedChanges(false); - setSelectedFile(path); - return; - } - - const data = await r.json(); - const fileContent = typeof data?.content === 'string' ? data.content : ''; - tabDraftsRef.current.set(path, { saved: fileContent, edited: fileContent }); - setContent(fileContent); - setEditedContent(fileContent); - editedContentRef.current = fileContent; - setHasUnsavedChanges(false); - setSelectedFile(path); - setIsFileUpdating(false); - - requestAnimationFrame(() => { - if (editorRef.current) { - editorRef.current.scrollTop = 0; - editorRef.current.scrollLeft = 0; - } - if (highlightRef.current) { - highlightRef.current.scrollTop = 0; - highlightRef.current.scrollLeft = 0; - } - if (lineNumberRef.current) { - lineNumberRef.current.scrollTop = 0; - } - }); - } catch (error) { - console.error('Error opening file:', error); - const fallback = '// Error loading file'; - setContent(fallback); - setEditedContent(fallback); - editedContentRef.current = fallback; - setHasUnsavedChanges(false); - setSelectedFile(path); - } - }, [projectId, selectedFile, content]); - - const closeTab = useCallback((tabPath: string) => { - const isDirty = tabPath === selectedFile ? hasUnsavedChanges : dirtyTabs.has(tabPath); - if (isDirty) { - const confirmClose = - typeof window !== 'undefined' - ? window.confirm(`"${tabPath.split('/').pop()}" has unsaved changes. Close without saving?`) - : true; - if (!confirmClose) { - return; - } - } - - tabDraftsRef.current.delete(tabPath); - setDirtyTabs((prev) => { - if (!prev.has(tabPath)) return prev; - const next = new Set(prev); - next.delete(tabPath); - return next; - }); - - const currentIndex = openTabs.indexOf(tabPath); - const remainingTabs = openTabs.filter((p) => p !== tabPath); - setOpenTabs(remainingTabs); - - if (tabPath === selectedFile) { - const nextTab = remainingTabs[Math.min(currentIndex, remainingTabs.length - 1)] || ''; - if (nextTab) { - const cached = tabDraftsRef.current.get(nextTab); - if (cached) { - setSelectedFile(nextTab); - setContent(cached.saved); - setEditedContent(cached.edited); - editedContentRef.current = cached.edited; - setHasUnsavedChanges(cached.edited !== cached.saved); - setSaveFeedback('idle'); - setSaveError(null); - setIsFileUpdating(false); - } else { - void openFile(nextTab); - } - } else { - setSelectedFile(''); - setContent(''); - setEditedContent(''); - editedContentRef.current = ''; - setHasUnsavedChanges(false); - setSaveFeedback('idle'); - setSaveError(null); - setIsFileUpdating(false); - } - } - }, [selectedFile, hasUnsavedChanges, dirtyTabs, openTabs, openFile]); - - // Reload currently selected file - const reloadCurrentFile = useCallback(async () => { - if (selectedFile && !showPreview && !hasUnsavedChanges) { - try { - const r = await fetch(`${API_BASE}/api/repo/${projectId}/file?path=${encodeURIComponent(selectedFile)}`); - if (r.ok) { - const data = await r.json(); - const newContent = data.content || ''; - if (newContent !== content) { - tabDraftsRef.current.set(selectedFile, { saved: newContent, edited: newContent }); - setIsFileUpdating(true); - setContent(newContent); - setEditedContent(newContent); - editedContentRef.current = newContent; - setHasUnsavedChanges(false); - setSaveFeedback('idle'); - setSaveError(null); - setTimeout(() => setIsFileUpdating(false), 500); - } - } - } catch (error) { - // Silently fail - this is a background refresh - } - } - }, [projectId, selectedFile, showPreview, hasUnsavedChanges, content]); - - // Lazy load highlight.js only when needed - const [hljs, setHljs] = useState(null); - - useEffect(() => { - if (selectedFile && !hljs) { - import('highlight.js/lib/common').then(mod => { - setHljs(mod.default); - // Load highlight.js CSS dynamically once - if (!document.getElementById('claudable-hljs-css')) { - const link = document.createElement('link'); - link.id = 'claudable-hljs-css'; - link.rel = 'stylesheet'; - link.href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css'; - document.head.appendChild(link); - } - }); - } - }, [selectedFile, hljs]); - - const deferredEditedContent = useDeferredValue(editedContent); - - const highlightedCode = useMemo(() => { - const code = deferredEditedContent ?? ''; - if (!code) { - return ' '; - } - - if (!hljs) { - return escapeHtml(code); - } - - const language = getFileLanguage(selectedFile); - try { - if (!language || language === 'plaintext') { - return escapeHtml(code); - } - return hljs.highlight(code, { language }).value; - } catch { - try { - return hljs.highlightAuto(code).value; - } catch { - return escapeHtml(code); - } - } - }, [hljs, deferredEditedContent, selectedFile]); - - const onEditorChange = useCallback((event: ChangeEvent) => { - const value = event.target.value; - setEditedContent(value); - editedContentRef.current = value; - const dirty = value !== content; - setHasUnsavedChanges(dirty); - if (selectedFile) { - tabDraftsRef.current.set(selectedFile, { saved: content, edited: value }); - setDirtyTabs((prev) => { - if (dirty === prev.has(selectedFile)) return prev; - const next = new Set(prev); - if (dirty) next.add(selectedFile); - else next.delete(selectedFile); - return next; - }); - } - setSaveFeedback('idle'); - setSaveError(null); - if (isFileUpdating) { - setIsFileUpdating(false); - } - }, [content, isFileUpdating, selectedFile]); - - const handleEditorScroll = useCallback((event: UIEvent) => { - const { scrollTop, scrollLeft } = event.currentTarget; - if (highlightRef.current) { - highlightRef.current.scrollTop = scrollTop; - highlightRef.current.scrollLeft = scrollLeft; - } - if (lineNumberRef.current) { - lineNumberRef.current.scrollTop = scrollTop; - } - }, []); - - const handleSaveFile = useCallback(async () => { - if (!selectedFile || isSavingFile || !hasUnsavedChanges) { - return; - } - - const contentToSave = editedContentRef.current; - setIsSavingFile(true); - setSaveFeedback('idle'); - setSaveError(null); - - try { - const response = await fetch(`${API_BASE}/api/repo/${projectId}/file`, { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ path: selectedFile, content: contentToSave }), - }); - - if (!response.ok) { - let errorMessage = 'Failed to save file'; - try { - const data = await response.clone().json(); - errorMessage = data?.error || data?.message || errorMessage; - } catch { - const text = await response.text().catch(() => ''); - if (text) { - errorMessage = text; - } - } - throw new Error(errorMessage); - } - - setContent(contentToSave); - setSaveFeedback('success'); - tabDraftsRef.current.set(selectedFile, { saved: contentToSave, edited: editedContentRef.current }); - - if (editedContentRef.current === contentToSave) { - setHasUnsavedChanges(false); - setDirtyTabs((prev) => { - if (!prev.has(selectedFile)) return prev; - const next = new Set(prev); - next.delete(selectedFile); - return next; - }); - setIsFileUpdating(true); - setTimeout(() => setIsFileUpdating(false), 800); - } - - refreshPreview(); - } catch (error) { - console.error('Failed to save file:', error); - setSaveFeedback('error'); - setSaveError(error instanceof Error ? error.message : 'Failed to save file'); - } finally { - setIsSavingFile(false); - } - }, [selectedFile, isSavingFile, hasUnsavedChanges, projectId, refreshPreview]); - - const handleEditorKeyDown = useCallback((event: KeyboardEvent) => { - if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') { - event.preventDefault(); - handleSaveFile(); - return; - } - - if (event.key === 'Tab') { - event.preventDefault(); - const el = event.currentTarget; - const start = el.selectionStart ?? 0; - const end = el.selectionEnd ?? 0; - const indent = ' '; - const value = editedContent; - const newValue = value.slice(0, start) + indent + value.slice(end); - - setEditedContent(newValue); - editedContentRef.current = newValue; - const dirty = newValue !== content; - setHasUnsavedChanges(dirty); - if (selectedFile) { - tabDraftsRef.current.set(selectedFile, { saved: content, edited: newValue }); - setDirtyTabs((prev) => { - if (dirty === prev.has(selectedFile)) return prev; - const next = new Set(prev); - if (dirty) next.add(selectedFile); - else next.delete(selectedFile); - return next; - }); - } - setSaveFeedback('idle'); - setSaveError(null); - if (isFileUpdating) { - setIsFileUpdating(false); - } - - requestAnimationFrame(() => { - const position = start + indent.length; - el.selectionStart = position; - el.selectionEnd = position; - if (highlightRef.current) { - highlightRef.current.scrollTop = el.scrollTop; - highlightRef.current.scrollLeft = el.scrollLeft; - } - if (lineNumberRef.current) { - lineNumberRef.current.scrollTop = el.scrollTop; - } - }); - } - }, [handleSaveFile, editedContent, content, isFileUpdating, selectedFile]); - - useEffect(() => { - if (saveFeedback === 'success') { - const timer = setTimeout(() => setSaveFeedback('idle'), 1800); - return () => clearTimeout(timer); - } - return undefined; - }, [saveFeedback]); - - useEffect(() => { - if (editorRef.current && highlightRef.current && lineNumberRef.current) { - const { scrollTop, scrollLeft } = editorRef.current; - highlightRef.current.scrollTop = scrollTop; - highlightRef.current.scrollLeft = scrollLeft; - lineNumberRef.current.scrollTop = scrollTop; - } - }, [editedContent]); - - // Get file extension for syntax highlighting - function getFileLanguage(path: string): string { - const ext = path.split('.').pop()?.toLowerCase(); - switch (ext) { - case 'tsx': - case 'ts': - return 'typescript'; - case 'jsx': - case 'js': - case 'mjs': - return 'javascript'; - case 'css': - return 'css'; - case 'scss': - case 'sass': - return 'scss'; - case 'html': - case 'htm': - return 'html'; - case 'json': - return 'json'; - case 'md': - case 'markdown': - return 'markdown'; - case 'py': - return 'python'; - case 'sh': - case 'bash': - return 'bash'; - case 'yaml': - case 'yml': - return 'yaml'; - case 'xml': - return 'xml'; - case 'sql': - return 'sql'; - case 'php': - return 'php'; - case 'java': - return 'java'; - case 'c': - return 'c'; - case 'cpp': - case 'cc': - case 'cxx': - return 'cpp'; - case 'rs': - return 'rust'; - case 'go': - return 'go'; - case 'rb': - return 'ruby'; - case 'vue': - return 'vue'; - case 'svelte': - return 'svelte'; - case 'dockerfile': - return 'dockerfile'; - case 'toml': - return 'toml'; - case 'ini': - return 'ini'; - case 'conf': - case 'config': - return 'nginx'; - default: - return 'plaintext'; - } - } - - function escapeHtml(value: string): string { - return value - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); - } - - // Get file icon based on type - function getFileIcon(entry: Entry): React.ReactElement { - if (entry.type === 'dir') { - return ; - } - - const ext = entry.path.split('.').pop()?.toLowerCase(); - const filename = entry.path.split('/').pop()?.toLowerCase(); - - // Special files - if (filename === 'package.json') return ; - if (filename === 'dockerfile') return ; - if (filename?.startsWith('.env')) return ; - if (filename === 'readme.md') return ; - if (filename?.includes('config')) return ; - - switch (ext) { - case 'tsx': - return ; - case 'ts': - return ; - case 'jsx': - return ; - case 'js': - case 'mjs': - return ; - case 'css': - return ; - case 'scss': - case 'sass': - return ; - case 'html': - case 'htm': - return ; - case 'json': - return ; - case 'md': - case 'markdown': - return ; - case 'py': - return ; - case 'sh': - case 'bash': - return ; - case 'yaml': - case 'yml': - return ; - case 'xml': - return ; - case 'sql': - return ; - case 'php': - return ; - case 'java': - return ; - case 'c': - return ; - case 'cpp': - case 'cc': - case 'cxx': - return ; - case 'rs': - return ; - case 'go': - return ; - case 'rb': - return ; - case 'vue': - return ; - case 'svelte': - return ; - case 'dockerfile': - return ; - case 'toml': - case 'ini': - case 'conf': - case 'config': - return ; - default: - return ; - } - } - - // Ensure we only trigger dependency installation once per page lifecycle - const installTriggeredRef = useRef(false); - - const startDependencyInstallation = useCallback(async () => { - if (installTriggeredRef.current) { - return; - } - installTriggeredRef.current = true; - try { - const response = await fetch(`${API_BASE}/api/projects/${projectId}/install-dependencies`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' } - }); - - if (!response.ok) { - const errorText = await response.text(); - console.warn('Failed to start dependency installation:', errorText); - // allow retry on next attempt if initial trigger failed - installTriggeredRef.current = false; - } - } catch (error) { - console.error('Error starting dependency installation:', error); - // allow retry if network error - installTriggeredRef.current = false; - } - }, [projectId]); - - const loadSettings = useCallback(async (projectSettings?: { cli?: string; model?: string }) => { - try { - const hasCliSet = projectSettings?.cli || preferredCli; - const hasModelSet = projectSettings?.model || selectedModel; - - if (!hasCliSet || !hasModelSet) { - const globalResponse = await fetch(`${API_BASE}/api/settings/global`); - if (globalResponse.ok) { - const globalSettings = await globalResponse.json(); - const defaultCli = sanitizeCli(globalSettings.default_cli || globalSettings.defaultCli); - const cliToUse = sanitizeCli(hasCliSet || defaultCli); - - if (!hasCliSet) { - updatePreferredCli(cliToUse); - } - - if (!hasModelSet) { - const cliSettings = globalSettings.cli_settings?.[cliToUse] || globalSettings.cliSettings?.[cliToUse]; - if (cliSettings?.model) { - updateSelectedModel(cliSettings.model, cliToUse); - } else { - updateSelectedModel(getDefaultModelForCli(cliToUse), cliToUse); - } - } - } else { - const response = await fetch(`${API_BASE}/api/settings`); - if (response.ok) { - const settings = await response.json(); - if (!hasCliSet) updatePreferredCli(settings.preferred_cli || settings.default_cli || DEFAULT_ACTIVE_CLI); - if (!hasModelSet) { - const cli = sanitizeCli(settings.preferred_cli || settings.default_cli || preferredCli || DEFAULT_ACTIVE_CLI); - updateSelectedModel(getDefaultModelForCli(cli), cli); - } - } - } - } - } catch (error) { - console.error('Failed to load settings:', error); - const hasCliSet = projectSettings?.cli || preferredCli; - const hasModelSet = projectSettings?.model || selectedModel; - if (!hasCliSet) updatePreferredCli(DEFAULT_ACTIVE_CLI); - if (!hasModelSet) updateSelectedModel(getDefaultModelForCli(DEFAULT_ACTIVE_CLI), DEFAULT_ACTIVE_CLI); - } - }, [preferredCli, selectedModel, updatePreferredCli, updateSelectedModel]); - - const loadProjectInfo = useCallback(async (): Promise<{ cli?: string; model?: string; status?: ProjectStatus }> => { - try { - const r = await fetch(`${API_BASE}/api/projects/${projectId}`); - if (r.status === 404) { - setProjectMissing(true); - return {}; - } - if (!r.ok) { - setProjectName(`Project ${projectId.slice(0, 8)}`); - setProjectDescription(''); - setHasInitialPrompt(false); - localStorage.setItem(`project_${projectId}_hasInitialPrompt`, 'false'); - setProjectStatus('active'); - setIsInitializing(false); - setUsingGlobalDefaults(true); - return {}; - } - - const payload = await r.json(); - const project = payload?.data ?? payload; - const rawPreferredCli = - typeof project?.preferredCli === 'string' - ? project.preferredCli - : typeof project?.preferred_cli === 'string' - ? project.preferred_cli - : undefined; - const rawSelectedModel = - typeof project?.selectedModel === 'string' - ? project.selectedModel - : typeof project?.selected_model === 'string' - ? project.selected_model - : undefined; - - setProjectName(project.name || `Project ${projectId.slice(0, 8)}`); - - const projectCli = sanitizeCli(rawPreferredCli || preferredCli); - if (rawPreferredCli) { - updatePreferredCli(projectCli); - } - if (rawSelectedModel) { - updateSelectedModel(rawSelectedModel, projectCli); - } else { - updateSelectedModel(getDefaultModelForCli(projectCli), projectCli); - } - - const followGlobal = !rawPreferredCli && !rawSelectedModel; - setUsingGlobalDefaults(followGlobal); - setProjectDescription(project.description || ''); - - if (project.initial_prompt) { - setHasInitialPrompt(true); - localStorage.setItem(`project_${projectId}_hasInitialPrompt`, 'true'); - } else { - setHasInitialPrompt(false); - localStorage.setItem(`project_${projectId}_hasInitialPrompt`, 'false'); - } - - if (project.status === 'initializing') { - setProjectStatus('initializing'); - setIsInitializing(true); - } else { - setProjectStatus('active'); - setIsInitializing(false); - startDependencyInstallation(); - triggerInitialPromptIfNeeded(); - } - - const normalizedModel = rawSelectedModel - ? sanitizeModel(projectCli, rawSelectedModel) - : getDefaultModelForCli(projectCli); - - return { - cli: rawPreferredCli ? projectCli : undefined, - model: normalizedModel, - status: project.status as ProjectStatus | undefined, - }; - } catch (error) { - console.error('Failed to load project info:', error); - setProjectName(`Project ${projectId.slice(0, 8)}`); - setProjectDescription(''); - setHasInitialPrompt(false); - localStorage.setItem(`project_${projectId}_hasInitialPrompt`, 'false'); - setProjectStatus('active'); - setIsInitializing(false); - setUsingGlobalDefaults(true); - return {}; - } - }, [ - projectId, - startDependencyInstallation, - triggerInitialPromptIfNeeded, - updatePreferredCli, - updateSelectedModel, - preferredCli, - ]); - - const loadProjectInfoRef = useRef(loadProjectInfo); - useEffect(() => { - loadProjectInfoRef.current = loadProjectInfo; - }, [loadProjectInfo]); - - useEffect(() => { - if (!searchParams) return; - const cliParam = searchParams.get('cli'); - const modelParam = searchParams.get('model'); - if (!cliParam && !modelParam) { - return; - } - const sanitizedCli = cliParam ? sanitizeCli(cliParam) : preferredCli; - if (cliParam) { - setUsingGlobalDefaults(false); - updatePreferredCli(sanitizedCli); - } - if (modelParam) { - setUsingGlobalDefaults(false); - updateSelectedModel(modelParam, sanitizedCli); - } - }, [searchParams, preferredCli, updatePreferredCli, updateSelectedModel, setUsingGlobalDefaults]); - - const loadSettingsRef = useRef(loadSettings); - useEffect(() => { - loadSettingsRef.current = loadSettings; - }, [loadSettings]); - - const loadTreeRef = useRef(loadTree); - useEffect(() => { - loadTreeRef.current = loadTree; - }, [loadTree]); - - const loadDeployStatusRef = useRef(loadDeployStatus); - useEffect(() => { - loadDeployStatusRef.current = loadDeployStatus; - }, [loadDeployStatus]); - - const checkCurrentDeploymentRef = useRef(checkCurrentDeployment); - useEffect(() => { - checkCurrentDeploymentRef.current = checkCurrentDeployment; - }, [checkCurrentDeployment]); - - // Stable message handlers with useCallback to prevent reassignment - const createStableMessageHandlers = useCallback(() => { - const addMessage = (message: any) => { - // Track optimistic messages by requestId - if (message.isOptimistic && message.requestId) { - optimisticMessagesRef.current.set(message.requestId, message); - } - - // Also call the current handlers if they exist - if (messageHandlersRef.current) { - messageHandlersRef.current.add(message); - } - }; - - const removeMessage = (messageId: string) => { - // Remove from optimistic messages tracking if it's an optimistic message - const optimisticMessage = Array.from(optimisticMessagesRef.current.values()) - .find(msg => msg.id === messageId); - if (optimisticMessage && optimisticMessage.requestId) { - optimisticMessagesRef.current.delete(optimisticMessage.requestId); - } - - // Also call the current handlers if they exist - if (messageHandlersRef.current) { - messageHandlersRef.current.remove(messageId); - } - }; - - return { add: addMessage, remove: removeMessage }; - }, []); - - // Initialize stable handlers once - useEffect(() => { - stableMessageHandlers.current = createStableMessageHandlers(); - const optimisticMessages = optimisticMessagesRef.current; - - return () => { - stableMessageHandlers.current = null; - optimisticMessages.clear(); - }; - }, [createStableMessageHandlers]); - - // Handle image upload with base64 conversion - const handleImageUpload = (event: React.ChangeEvent) => { - const files = event.target.files; - if (files) { - Array.from(files).forEach(file => { - if (file.type.startsWith('image/')) { - const url = URL.createObjectURL(file); - - // Convert to base64 - const reader = new FileReader(); - reader.onload = (e) => { - const base64 = e.target?.result as string; - setUploadedImages(prev => [...prev, { - name: file.name, - url, - base64 - }]); - }; - reader.readAsDataURL(file); - } - }); - } - }; - - // Remove uploaded image - const removeUploadedImage = (index: number) => { - setUploadedImages(prev => { - const newImages = [...prev]; - URL.revokeObjectURL(newImages[index].url); - newImages.splice(index, 1); - return newImages; - }); - }; - - async function runAct(messageOverride?: string, externalImages?: any[]) { - let finalMessage = messageOverride || prompt; - const imagesToUse = externalImages || uploadedImages; - - if (!finalMessage.trim() && imagesToUse.length === 0) { - alert('Please enter a task description or upload an image.'); - return; - } - - // Attach picked preview element context when user selected an element visually - if (selectedElement && !messageOverride?.startsWith('Please fix the following preview error')) { - const elementContext = [ - `[Selected preview element on route "${selectedElement.route || currentRoute || '/'}"]`, - `- Tag: <${selectedElement.tag}>`, - `- Selector: ${selectedElement.selector}`, - ...(selectedElement.className ? [`- Classes: ${selectedElement.className}`] : []), - ...(selectedElement.text ? [`- Text: "${selectedElement.text}"`] : []), - ].join('\n'); - finalMessage = `${elementContext}\n\n${finalMessage}`.trim(); - } - - // Create request fingerprint for deduplication - const requestFingerprint = JSON.stringify({ - message: finalMessage.trim(), - imageCount: imagesToUse.length, - cliPreference: preferredCli, - model: selectedModel, - }); - - // Check for duplicate pending requests - if (pendingRequestsRef.current.has(requestFingerprint)) { - return; - } - - setIsRunning(true); - const requestId = crypto.randomUUID(); - let tempUserMessageId: string | null = null; - - // Add to pending requests - pendingRequestsRef.current.add(requestFingerprint); - - try { - const uploadImageFromBase64 = async (img: { base64: string; name?: string }) => { - const base64String = img.base64; - const match = base64String.match(/^data:(.*?);base64,(.*)$/); - const mimeType = match && match[1] ? match[1] : 'image/png'; - const base64Data = match && match[2] ? match[2] : base64String; - - const byteString = atob(base64Data); - const buffer = new Uint8Array(byteString.length); - for (let i = 0; i < byteString.length; i += 1) { - buffer[i] = byteString.charCodeAt(i); - } - - const extension = (() => { - if (mimeType.includes('png')) return 'png'; - if (mimeType.includes('jpeg') || mimeType.includes('jpg')) return 'jpg'; - if (mimeType.includes('gif')) return 'gif'; - if (mimeType.includes('webp')) return 'webp'; - if (mimeType.includes('svg')) return 'svg'; - return 'png'; - })(); - - const inferredName = img.name && img.name.trim().length > 0 ? img.name.trim() : `image-${crypto.randomUUID()}.${extension}`; - const hasExtension = /\.[a-zA-Z0-9]+$/.test(inferredName); - const filename = hasExtension ? inferredName : `${inferredName}.${extension}`; - - const file = new File([buffer], filename, { type: mimeType }); - const formData = new FormData(); - formData.append('file', file); - - const response = await fetch(`${API_BASE}/api/assets/${projectId}/upload`, { - method: 'POST', - body: formData - }); - - if (!response.ok) { - const errorText = await response.text(); - throw new Error(errorText || 'Upload failed'); - } - - const result = await response.json(); - return { - name: result.filename || filename, - path: result.absolute_path, - url: `/api/assets/${projectId}/${result.filename}`, - public_url: typeof result.public_url === 'string' ? result.public_url : undefined, - publicUrl: typeof result.public_url === 'string' ? result.public_url : undefined, - }; - }; - - const processedImages: { name: string; path: string; url?: string; public_url?: string; publicUrl?: string }[] = []; - - for (let i = 0; i < imagesToUse.length; i += 1) { - const image = imagesToUse[i]; - if (image?.path) { - const name = image.filename || image.name || `Image ${i + 1}`; - const candidateUrl = typeof image.assetUrl === 'string' ? image.assetUrl : undefined; - const candidatePublicUrl = typeof image.publicUrl === 'string' ? image.publicUrl : undefined; - const processedImage = { - name, - path: image.path, - url: candidateUrl && candidateUrl.startsWith('/') ? candidateUrl : undefined, - public_url: candidatePublicUrl, - publicUrl: candidatePublicUrl, - }; - processedImages.push(processedImage); - continue; - } - - if (image?.base64) { - try { - const uploaded = await uploadImageFromBase64({ base64: image.base64, name: image.name }); - processedImages.push(uploaded); - } catch (uploadError) { - console.error('Image upload failed:', uploadError); - alert('Failed to upload image. Please try again.'); - setIsRunning(false); - // Remove from pending requests - pendingRequestsRef.current.delete(requestFingerprint); - return; - } - } - } - - const requestBody = { - instruction: finalMessage, - images: processedImages, - isInitialPrompt: false, - cliPreference: preferredCli, - conversationId: conversationId || undefined, - requestId, - selectedModel, - reasoningEffort, - }; - - // Optimistically add user message to UI BEFORE API call for instant feedback - tempUserMessageId = requestId + '-user-temp'; - if (messageHandlersRef.current) { - const optimisticUserMessage = { - id: tempUserMessageId, - projectId: projectId, - role: 'user' as const, - messageType: 'chat' as const, - content: finalMessage, - conversationId: conversationId || null, - requestId: requestId, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - isStreaming: false, - isFinal: false, - isOptimistic: true, - metadata: - processedImages.length > 0 - ? { - attachments: processedImages.map((img) => ({ - name: img.name, - path: img.path, - url: img.url, - publicUrl: img.publicUrl ?? img.public_url, - })), - } - : undefined, - }; - - // Use stable handlers instead of direct messageHandlersRef to prevent reassignment issues - if (stableMessageHandlers.current) { - stableMessageHandlers.current.add(optimisticUserMessage); - } else if (messageHandlersRef.current) { - // Fallback to direct handlers if stable handlers aren't ready yet - messageHandlersRef.current.add(optimisticUserMessage); - } - } - - // Add timeout to prevent indefinite waiting - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), 60000); - - let r: Response; - try { - r = await fetch(`${API_BASE}/api/chat/${projectId}/act`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(requestBody), - signal: controller.signal - }); - - clearTimeout(timeoutId); - - if (!r.ok) { - const errorText = await r.text(); - console.error('API Error:', errorText); - - if (tempUserMessageId) { - if (stableMessageHandlers.current) { - stableMessageHandlers.current.remove(tempUserMessageId); - } else if (messageHandlersRef.current) { - messageHandlersRef.current.remove(tempUserMessageId); - } - } - - alert(`Failed to send message: ${r.status} ${r.statusText}\n${errorText}`); - return; - } - } catch (fetchError: any) { - clearTimeout(timeoutId); - if (fetchError.name === 'AbortError') { - if (tempUserMessageId) { - if (stableMessageHandlers.current) { - stableMessageHandlers.current.remove(tempUserMessageId); - } else if (messageHandlersRef.current) { - messageHandlersRef.current.remove(tempUserMessageId); - } - } - - alert('Request timed out after 60 seconds. Please check your connection and try again.'); - return; - } - throw fetchError; - } - - const result = await r.json(); - - const returnedConversationId = - typeof result?.conversationId === 'string' - ? result.conversationId - : typeof result?.conversation_id === 'string' - ? result.conversation_id - : undefined; - if (returnedConversationId) { - setConversationId(returnedConversationId); - } - - const resolvedRequestId = - typeof result?.requestId === 'string' - ? result.requestId - : typeof result?.request_id === 'string' - ? result.request_id - : requestId; - const userMessageId = - typeof result?.userMessageId === 'string' - ? result.userMessageId - : typeof result?.user_message_id === 'string' - ? result.user_message_id - : ''; - - createRequest(resolvedRequestId, userMessageId, finalMessage); - setSelectedElement(null); - setPrompt(''); - // Clean up old format images if any - if (uploadedImages && uploadedImages.length > 0) { - uploadedImages.forEach(img => { - if (img.url) URL.revokeObjectURL(img.url); - }); - setUploadedImages([]); - } - - } catch (error: any) { - console.error('Act execution error:', error); - - if (tempUserMessageId) { - if (stableMessageHandlers.current) { - stableMessageHandlers.current.remove(tempUserMessageId); - } else if (messageHandlersRef.current) { - messageHandlersRef.current.remove(tempUserMessageId); - } - } - - const errorMessage = error?.message || String(error); - alert(`Failed to send message: ${errorMessage}\n\nPlease try again. If the problem persists, check the console for details.`); - } finally { - setIsRunning(false); - // Remove from pending requests - pendingRequestsRef.current.delete(requestFingerprint); - } - } - - - // Handle project status updates via callback from ChatLog - const handleProjectStatusUpdate = (status: string, message?: string) => { - const previousStatus = projectStatus; - - // Ignore if status is the same (prevent duplicates) - if (previousStatus === status) { - return; - } - - setProjectStatus(status as ProjectStatus); - if (message) { - setInitializationMessage(message); - } - - // If project becomes active, stop showing loading UI - if (status === 'active') { - setIsInitializing(false); - - // Handle only when transitioning from initializing → active - if (previousStatus === 'initializing') { - - // Start dependency installation - startDependencyInstallation(); - loadTreeRef.current?.('.'); - } - - // Initial prompt: trigger once with shared guard (handles active-via-WS case) - triggerInitialPromptIfNeeded(); - } else if (status === 'failed') { - setIsInitializing(false); - } - }; - - // Function to start dependency installation in background - const handleRetryInitialization = async () => { - setProjectStatus('initializing'); - setIsInitializing(true); - setInitializationMessage('Retrying project initialization...'); - - try { - const response = await fetch(`${API_BASE}/api/projects/${projectId}/retry-initialization`, { - method: 'POST' - }); - - if (!response.ok) { - throw new Error('Failed to retry initialization'); - } - } catch (error) { - console.error('Failed to retry initialization:', error); - setProjectStatus('failed'); - setInitializationMessage('Failed to retry initialization. Please try again.'); - } - }; - - // Load states from localStorage when projectId changes - useEffect(() => { - if (typeof window !== 'undefined' && projectId) { - const storedHasInitialPrompt = localStorage.getItem(`project_${projectId}_hasInitialPrompt`); - const storedTaskComplete = localStorage.getItem(`project_${projectId}_taskComplete`); - - if (storedHasInitialPrompt !== null) { - setHasInitialPrompt(storedHasInitialPrompt === 'true'); - } - if (storedTaskComplete !== null) { - setAgentWorkComplete(storedTaskComplete === 'true'); - } - } - }, [projectId]); - - // Stop active AI generation - const handleStopGeneration = useCallback(async () => { - try { - await fetch(`${API_BASE}/api/chat/${projectId}/stop`, { method: 'POST' }); - } catch (error) { - console.error('Failed to stop generation:', error); - } finally { - setIsRunning(false); - clearActiveRequests(); - } - }, [projectId, clearActiveRequests]); - - // Load version history checkpoints - const loadHistory = useCallback(async () => { - if (!projectId) return; - setIsLoadingHistory(true); - try { - const response = await fetch(`${API_BASE}/api/projects/${projectId}/history?limit=30`, { - cache: 'no-store', - }); - if (response.ok) { - const data = await response.json(); - setCheckpoints(Array.isArray(data?.checkpoints) ? data.checkpoints : []); - setHistoryHeadSha(typeof data?.headSha === 'string' ? data.headSha : null); - } - } catch (error) { - console.warn('Failed to load project history:', error); - } finally { - setIsLoadingHistory(false); - } - }, [projectId]); - - const handleCreateCheckpoint = useCallback(async () => { - const label = typeof window !== 'undefined' ? window.prompt('Checkpoint description:', 'Manual checkpoint') : null; - if (label === null) return; - try { - const response = await fetch(`${API_BASE}/api/projects/${projectId}/history`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ message: label.trim() || 'Manual checkpoint' }), - }); - if (response.ok) { - await loadHistory(); - } - } catch (error) { - console.error('Failed to create checkpoint:', error); - } - }, [projectId, loadHistory]); - - const handleRestoreCheckpoint = useCallback(async (sha: string, shortSha: string) => { - if (restoringSha) return; - const confirmed = - typeof window !== 'undefined' - ? window.confirm(`Restore project files to checkpoint ${shortSha}? Current changes will be saved as a backup commit first.`) - : true; - if (!confirmed) return; - - setRestoringSha(sha); - try { - const response = await fetch(`${API_BASE}/api/projects/${projectId}/history/restore`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ sha }), - }); - if (!response.ok) { - const err = await response.json().catch(() => ({})); - throw new Error(err?.error || 'Restore failed'); - } - tabDraftsRef.current.clear(); - setDirtyTabs(new Set()); - setCheckpointDiffs({}); - setExpandedDiffSha(null); - await Promise.all([loadTree('.'), loadHistory()]); - if (selectedFile) { - await reloadCurrentFile(); - } - refreshPreview(); - setPreviewError(null); - } catch (error) { - console.error('Failed to restore checkpoint:', error); - alert(error instanceof Error ? error.message : 'Failed to restore checkpoint'); - } finally { - setRestoringSha(null); - } - }, [projectId, restoringSha, loadTree, loadHistory, selectedFile, reloadCurrentFile, refreshPreview]); - - // Toggle inline unified diff for a checkpoint commit - const handleToggleCheckpointDiff = useCallback(async (sha: string) => { - if (expandedDiffSha === sha) { - setExpandedDiffSha(null); - return; - } - setExpandedDiffSha(sha); - if (checkpointDiffs[sha] && !checkpointDiffs[sha].error) { - return; - } - setCheckpointDiffs((prev) => ({ - ...prev, - [sha]: { diff: '', truncated: false, loading: true }, - })); - try { - const response = await fetch(`${API_BASE}/api/projects/${projectId}/history/${encodeURIComponent(sha)}/diff`, { - cache: 'no-store', - }); - const data = await response.json().catch(() => ({})); - if (!response.ok) { - throw new Error(data?.error || 'Failed to load diff'); - } - setCheckpointDiffs((prev) => ({ - ...prev, - [sha]: { - diff: typeof data?.diff === 'string' ? data.diff : '', - truncated: Boolean(data?.truncated), - loading: false, - }, - })); - } catch (error) { - setCheckpointDiffs((prev) => ({ - ...prev, - [sha]: { - diff: '', - truncated: false, - loading: false, - error: error instanceof Error ? error.message : 'Failed to load diff', - }, - })); - } - }, [expandedDiffSha, checkpointDiffs, projectId]); - - // One-click TypeScript check across project files - const handleRunTypeCheck = useCallback(async () => { - if (!projectId || isCheckingTypes) return; - setIsCheckingTypes(true); - setShowTypeCheckDrawer(true); - try { - const response = await fetch(`${API_BASE}/api/projects/${projectId}/check`, { - method: 'POST', - }); - const data = await response.json().catch(() => ({})); - if (!response.ok) { - throw new Error(data?.error || 'Type check failed'); - } - setTypeCheckResult({ - ok: Boolean(data?.ok), - timedOut: Boolean(data?.timedOut), - errorCount: typeof data?.errorCount === 'number' ? data.errorCount : 0, - errors: Array.isArray(data?.errors) ? data.errors : [], - rawOutput: typeof data?.rawOutput === 'string' ? data.rawOutput : '', - durationMs: typeof data?.durationMs === 'number' ? data.durationMs : 0, - }); - } catch (error) { - setTypeCheckResult({ - ok: false, - errorCount: 1, - errors: [ - { - file: '', - line: 0, - column: 0, - code: 'CHECK_ERROR', - message: error instanceof Error ? error.message : 'Type check failed', - }, - ], - durationMs: 0, - }); - } finally { - setIsCheckingTypes(false); - } - }, [projectId, isCheckingTypes]); - - // Load preview dev-server logs - const loadPreviewLogs = useCallback(async () => { - if (!projectId) return; - setIsLoadingPreviewLogs(true); - try { - const response = await fetch(`${API_BASE}/api/projects/${projectId}/preview/logs`, { - cache: 'no-store', - }); - if (response.ok) { - const data = await response.json(); - setPreviewLogs(Array.isArray(data?.logs) ? data.logs : []); - if (typeof data?.lastError === 'string' && data.lastError) { - setPreviewError(data.lastError); - } - } - } catch (error) { - console.warn('Failed to fetch preview logs:', error); - } finally { - setIsLoadingPreviewLogs(false); - } - }, [projectId]); - - const handleClearPreviewLogs = useCallback(async () => { - try { - await fetch(`${API_BASE}/api/projects/${projectId}/preview/logs`, { method: 'DELETE' }); - setPreviewLogs([]); - setPreviewError(null); - } catch (error) { - console.warn('Failed to clear preview logs:', error); - } - }, [projectId]); - - const runActRef = useRef(runAct); - runActRef.current = runAct; - - const handleFixPreviewErrorWithAI = useCallback(async () => { - if (!previewError || isRunning || hasActiveRequests) return; - const recentLogs = previewLogs.slice(-25).join('\n'); - const fixPrompt = [ - 'Please fix the following preview error in this project:', - '', - '```', - previewError, - '```', - ...(recentLogs ? ['', 'Recent dev server logs:', '```', recentLogs, '```'] : []), - '', - 'Diagnose the root cause and fix the code directly.', - ].join('\n'); - setPreviewError(null); - await runActRef.current(fixPrompt); - }, [previewError, previewLogs, isRunning, hasActiveRequests]); - - const handleFixTypeErrorsWithAI = useCallback(async () => { - if (!typeCheckResult || typeCheckResult.ok || isRunning || hasActiveRequests) return; - const lines = typeCheckResult.errors.slice(0, 20).map((err) => - err.file ? `${err.file}:${err.line}:${err.column} - error ${err.code}: ${err.message}` : err.message - ); - const fixPrompt = [ - `Please fix the following ${typeCheckResult.errorCount} TypeScript error(s) in this project:`, - '', - '```', - lines.join('\n') || typeCheckResult.rawOutput || 'TypeScript check failed', - '```', - '', - 'Fix all type errors cleanly so `tsc --noEmit` passes with zero errors.', - ].join('\n'); - await runActRef.current(fixPrompt); - }, [typeCheckResult, isRunning, hasActiveRequests]); - - // Opt-in Auto-Fix loop for preview runtime/compile errors (strictly capped at 2 attempts per error signature) - useEffect(() => { - if (!autoFixPreviewErrors || !previewError || isRunning || hasActiveRequests) { - return; - } - const signature = previewError.split('\n')[0].trim().slice(0, 180); - if (!signature) return; - const prev = autoFixAttemptsRef.current; - if (prev.signature === signature && prev.count >= 2) { - return; - } - const timer = setTimeout(() => { - autoFixAttemptsRef.current = { - signature, - count: prev.signature === signature ? prev.count + 1 : 1, - }; - void handleFixPreviewErrorWithAI(); - }, 1500); - return () => clearTimeout(timer); - }, [autoFixPreviewErrors, previewError, isRunning, hasActiveRequests, handleFixPreviewErrorWithAI]); - - // Global Cmd+P / Ctrl+P quick file search shortcut - useEffect(() => { - const handleGlobalKeyDown = (event: globalThis.KeyboardEvent) => { - if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'p') { - event.preventDefault(); - setShowPreview(false); - requestAnimationFrame(() => { - fileSearchInputRef.current?.focus(); - fileSearchInputRef.current?.select(); - }); - } - }; - window.addEventListener('keydown', handleGlobalKeyDown); - return () => window.removeEventListener('keydown', handleGlobalKeyDown); - }, []); - - // Toggle Lovable-style visual element picker inside preview iframe - const toggleInspectorMode = useCallback(() => { - setIsInspectorActive(prev => { - const next = !prev; - try { - iframeRef.current?.contentWindow?.postMessage( - { type: 'claudable:inspector:toggle', enabled: next }, - '*', - ); - } catch { - // ignore cross-origin postMessage errors - } - return next; - }); - }, []); - - // Listen to preview iframe messages (visual element selection, client runtime errors, route sync) - useEffect(() => { - const handleWindowMessage = (event: MessageEvent) => { - const data = event.data; - if (!data || typeof data !== 'object') return; - if (data.type === 'claudable:inspector:select' && data.element) { - setSelectedElement(data.element as SelectedPreviewElement); - setIsInspectorActive(false); - } else if (data.type === 'claudable:inspector:cancelled') { - setIsInspectorActive(false); - } else if (data.type === 'claudable:preview:error' && typeof data.message === 'string') { - setPreviewError(data.message); - } else if (data.type === 'claudable:preview:route' && typeof data.path === 'string') { - setCurrentRoute(data.path || '/'); - } - }; - window.addEventListener('message', handleWindowMessage); - return () => window.removeEventListener('message', handleWindowMessage); - }, []); - - // Fetch logs while logs drawer is open - useEffect(() => { - if (!showPreviewLogs || !projectId) return; - void loadPreviewLogs(); - const timer = setInterval(() => { - if (!document.hidden) { - void loadPreviewLogs(); - } - }, 3000); - return () => clearInterval(timer); - }, [showPreviewLogs, projectId, loadPreviewLogs]); - - // Load history whenever History panel opens - useEffect(() => { - if (showHistoryPanel) { - void loadHistory(); - } - }, [showHistoryPanel, loadHistory]); - - // Code Explorer: create file/folder, delete entry, and debounced search - const handleCreateNewEntry = useCallback(async (type: 'file' | 'dir') => { - const promptLabel = type === 'dir' ? 'New folder path (e.g. components/ui):' : 'New file path (e.g. components/Card.tsx):'; - const input = typeof window !== 'undefined' ? window.prompt(promptLabel) : null; - if (!input || !input.trim()) return; - const entryPath = input.trim(); - try { - const response = await fetch(`${API_BASE}/api/repo/${projectId}/file`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ path: entryPath, type, content: '' }), - }); - if (!response.ok) { - const err = await response.json().catch(() => ({})); - throw new Error(err?.error || `Failed to create ${type}`); - } - await loadTree('.'); - if (type === 'file') { - await openFile(entryPath); - } - } catch (error) { - alert(error instanceof Error ? error.message : `Failed to create ${type}`); - } - }, [projectId, loadTree, openFile]); - - const handleDeleteEntry = useCallback(async (entryPath: string, type: 'file' | 'dir') => { - const confirmed = - typeof window !== 'undefined' - ? window.confirm(`Delete ${type === 'dir' ? 'folder' : 'file'} "${entryPath}"?`) - : true; - if (!confirmed) return; - try { - const response = await fetch( - `${API_BASE}/api/repo/${projectId}/file?path=${encodeURIComponent(entryPath)}`, - { method: 'DELETE' }, - ); - if (!response.ok) { - const err = await response.json().catch(() => ({})); - throw new Error(err?.error || 'Failed to delete entry'); - } - // Remove deleted files/folders from open tabs & draft cache - Array.from(tabDraftsRef.current.keys()).forEach((tabKey) => { - if (tabKey === entryPath || tabKey.startsWith(`${entryPath}/`)) { - tabDraftsRef.current.delete(tabKey); - } - }); - setDirtyTabs((prev) => { - const next = new Set(prev); - prev.forEach((tabKey) => { - if (tabKey === entryPath || tabKey.startsWith(`${entryPath}/`)) { - next.delete(tabKey); - } - }); - return next; - }); - setOpenTabs((prev) => - prev.filter((tabKey) => tabKey !== entryPath && !tabKey.startsWith(`${entryPath}/`)) - ); - if (selectedFile === entryPath || selectedFile.startsWith(`${entryPath}/`)) { - setSelectedFile(''); - setContent(''); - setEditedContent(''); - editedContentRef.current = ''; - setHasUnsavedChanges(false); - } - await loadTree('.'); - } catch (error) { - alert(error instanceof Error ? error.message : 'Failed to delete entry'); - } - }, [projectId, selectedFile, loadTree]); - - useEffect(() => { - const q = fileSearchQuery.trim(); - if (!q || !projectId) { - setFileSearchMatches([]); - setIsSearchingFiles(false); - return; - } - setIsSearchingFiles(true); - const controller = new AbortController(); - const timer = setTimeout(async () => { - try { - const response = await fetch( - `${API_BASE}/api/repo/${projectId}/search?q=${encodeURIComponent(q)}&limit=40`, - { signal: controller.signal }, - ); - if (response.ok) { - const data = await response.json(); - setFileSearchMatches(Array.isArray(data?.matches) ? data.matches : []); - } - } catch { - // aborted or network error - } finally { - setIsSearchingFiles(false); - } - }, 200); - return () => { - clearTimeout(timer); - controller.abort(); - }; - }, [fileSearchQuery, projectId]); - - // Start the preview on load and after each AI turn, so a failed start or a manual stop does not restart in a loop - const previousActiveState = useRef(false); - const hasRunPreviewEffectRef = useRef(false); - - useEffect(() => { - const isFirstRun = !hasRunPreviewEffectRef.current; - hasRunPreviewEffectRef.current = true; - if (!hasActiveRequests) { - const turnJustFinished = previousActiveState.current; - if (!previewUrl && !isStartingPreview) { - if (isFirstRun || turnJustFinished) { - start(); - } - } else if (turnJustFinished) { - // AI just finished a turn: invalidate clean tab cache and refresh tree, open file, preview, and history - Array.from(tabDraftsRef.current.entries()).forEach(([tabPath, draft]) => { - if (draft.saved === draft.edited) { - tabDraftsRef.current.delete(tabPath); - } - }); - void loadTree('.'); - if (selectedFile && !hasUnsavedChanges) { - void reloadCurrentFile(); - } - if (previewUrl) { - refreshPreview(); - } - if (showHistoryPanel) { - void loadHistory(); - } - } - } - - previousActiveState.current = hasActiveRequests; - }, [hasActiveRequests, previewUrl, isStartingPreview, start, loadTree, selectedFile, hasUnsavedChanges, reloadCurrentFile, refreshPreview, showHistoryPanel, loadHistory]); - - // Poll for file changes in code view (low frequency & visibility-aware) - useEffect(() => { - if (!showPreview && selectedFile && !hasUnsavedChanges) { - const interval = setInterval(() => { - if (!document.hidden) { - reloadCurrentFile(); - } - }, 5000); - - return () => clearInterval(interval); - } - }, [showPreview, selectedFile, hasUnsavedChanges, reloadCurrentFile]); - - - useEffect(() => { - if (!projectId) { - return; - } - - let canceled = false; - - const initializeChat = async () => { - try { - const [projectSettings] = await Promise.all([ - loadProjectInfoRef.current?.(), - loadTreeRef.current?.('.'), - loadDeployStatusRef.current?.(), - checkCurrentDeploymentRef.current?.(), - ]); - if (canceled) return; - - await loadSettingsRef.current?.(projectSettings); - } catch (error) { - console.error('Failed to initialize chat view:', error); - } - }; - - initializeChat(); - - const handleServicesUpdate = () => { - loadDeployStatusRef.current?.(); - }; - - const handleBeforeUnload = () => { - navigator.sendBeacon(`${API_BASE}/api/projects/${projectId}/preview/stop`); - }; - - window.addEventListener('beforeunload', handleBeforeUnload); - window.addEventListener('services-updated', handleServicesUpdate); - - return () => { - canceled = true; - window.removeEventListener('beforeunload', handleBeforeUnload); - window.removeEventListener('services-updated', handleServicesUpdate); - - const currentPreview = previewUrlRef.current; - if (currentPreview) { - fetch(`${API_BASE}/api/projects/${projectId}/preview/stop`, { method: 'POST' }).catch(() => {}); - } - }; - }, [projectId]); - - // Cleanup pending requests on unmount - useEffect(() => { - const pendingRequests = pendingRequestsRef.current; - return () => { - pendingRequests.clear(); - }; - }, []); - - // React to global settings changes when using global defaults - const { settings: globalSettings } = useGlobalSettings(); - useEffect(() => { - if (!usingGlobalDefaults) return; - if (!globalSettings) return; - - const cli = sanitizeCli(globalSettings.default_cli); - updatePreferredCli(cli); - - const modelFromGlobal = globalSettings.cli_settings?.[cli]?.model; - if (modelFromGlobal) { - updateSelectedModel(modelFromGlobal, cli); - } else { - updateSelectedModel(getDefaultModelForCli(cli), cli); - } - }, [globalSettings, usingGlobalDefaults, updatePreferredCli, updateSelectedModel]); - - if (projectMissing) { - notFound(); - } - - return ( - <> - - -
- {/* Top bar */} -
-
- -

- {projectName || ( -

-
- -
- {/* Preview / Code switch */} -
- - -
- - {/* Code View Quick TypeScript Check */} - {!showPreview && ( - - )} - - {/* Preview controls */} - {showPreview && previewUrl && ( -
- {/* Route Navigation */} -
- - / - { - const value = e.target.value; - setCurrentRoute(value ? `/${value}` : '/'); - }} - onKeyDown={(e) => { - if (e.key === 'Enter') { - navigateToRoute(currentRoute); - } - }} - className="min-w-0 flex-1 bg-transparent px-1 text-sm text-gray-700 outline-none placeholder:text-gray-400" - placeholder="route" - aria-label="Preview route" - /> - {/* Open Preview in New Tab */} - - - -
- - {/* Device Mode Toggle */} -
- - - -
- - {/* Visual Element Picker (Select to Edit) */} - - - {/* Preview Logs Drawer Toggle */} - - - {/* Stop preview server */} - -
- )} - -
- {/* Version History / Checkpoints Button */} -
- - - {showHistoryPanel && ( -
-
-
-

Version History

-

Auto-saved git checkpoints

-
- -
-
- {isLoadingHistory ? ( -
Loading history…
- ) : checkpoints.length === 0 ? ( -
- No checkpoints yet. Changes are saved automatically after each AI turn. -
- ) : ( - checkpoints.map((cp) => { - const isCurrent = cp.sha === historyHeadSha; - const isDiffOpen = expandedDiffSha === cp.sha; - const diffEntry = checkpointDiffs[cp.sha]; - return ( -
-
-
-
- {cp.shortSha} - {isCurrent && ( - - Current - - )} -
-

- {cp.message} -

-

- {new Date(cp.committedAt).toLocaleString()} - {cp.filesChanged.length > 0 ? ` • ${cp.filesChanged.length} file${cp.filesChanged.length > 1 ? 's' : ''}` : ''} -

-
-
- - {!isCurrent && ( - - )} -
-
- {isDiffOpen && ( -
- {diffEntry?.loading ? ( -
Loading diff…
- ) : diffEntry?.error ? ( -
{diffEntry.error}
- ) : !diffEntry?.diff ? ( -
No text diff for this commit.
- ) : ( -
- {diffEntry.diff.split('\n').map((line, lineIdx) => { - const lineClass = - line.startsWith('+') && !line.startsWith('+++') - ? 'bg-green-50 text-green-800' - : line.startsWith('-') && !line.startsWith('---') - ? 'bg-red-50 text-red-800' - : line.startsWith('@@') - ? 'text-blue-600 font-medium' - : 'text-gray-700'; - return ( -
- {line || ' '} -
- ); - })} - {diffEntry.truncated && ( -
- Diff output truncated for performance. -
- )} -
- )} -
- )} -
- ); - }) - )} -
-
- )} -
- - {/* Export Project ZIP Button */} - - - - - {/* Settings Button */} - - - {/* Publish/Update */} - {showPreview && previewUrl && ( - - )} -
-
-
- -
- {/* Left: Chat window */} -
- {/* Chat log area */} -
- - { - messageHandlersRef.current = handlers; - - // Also update stable handlers if they exist - if (stableMessageHandlers.current) { - // Note: stableMessageHandlers.current already has its own add/remove logic - // We don't replace it completely, just keep the reference to handlers - } - }} - onSessionStatusChange={(isRunningValue) => { - setIsRunning(isRunningValue); - // Track agent task completion and auto-start preview - if (!isRunningValue && hasInitialPrompt && !agentWorkComplete && !previewUrl) { - setAgentWorkComplete(true); - // Save to localStorage - localStorage.setItem(`project_${projectId}_taskComplete`, 'true'); - // Auto-start preview server after initial prompt task completion - start(); - } - }} - onSseFallbackActive={(active) => { - setIsSseFallbackActive(active); - }} - onPreviewError={(errMessage) => { - setPreviewError(errMessage); - }} - onPreviewSuccess={() => { - setPreviewError(null); - autoFixAttemptsRef.current = { signature: '', count: 0 }; - }} - onCheckpointEvent={() => { - if (showHistoryPanel) { - void loadHistory(); - } - }} - onProjectStatusUpdate={handleProjectStatusUpdate} - startRequest={startRequest} - completeRequest={completeRequest} - /> - -
- - {/* Simple input area */} -
- { - // Pass images to runAct - runAct(message, images); - }} - onStop={handleStopGeneration} - disabled={isRunning || hasActiveRequests} - isRunning={isRunning || hasActiveRequests} - projectId={projectId} - preferredCli={preferredCli} - selectedModel={selectedModel} - reasoningEffort={reasoningEffort} - reasoningEffortLevels={reasoningEffortLevels} - onReasoningEffortChange={setReasoningEffort} - modelOptions={modelOptions} - onModelChange={handleModelChange} - modelChangeDisabled={isUpdatingModel} - cliOptions={cliOptions} - onCliChange={handleCliChange} - cliChangeDisabled={isUpdatingModel} - selectedElement={selectedElement} - onClearSelectedElement={() => setSelectedElement(null)} - /> -
-
- - {/* Right: Preview/Code area */} -
- {/* Content Area */} -
- - {showPreview ? ( - - {previewUrl ? ( -
-
-
-