refactor: complete migration from Next.js to Vite and update documentation

- Finalized core migration to Vite, ensuring feature parity and functionality.
- Updated migration plan to reflect completed tasks and deferred items.
- Renamed `apps/app` to `apps/ui` and adjusted related configurations.
- Verified Zustand stores and HTTP API client functionality remain unchanged.
- Added additional tasks completed during migration, including environment variable updates and memory history configuration for Electron.

This commit marks the transition to the new build infrastructure, setting the stage for further component refactoring.
This commit is contained in:
Kacper
2025-12-17 20:42:24 +01:00
parent ad4da23743
commit 96b941b008
3 changed files with 44 additions and 607 deletions

View File

@@ -1,310 +0,0 @@
# Large Files - Refactoring Candidates
This document tracks files in the AutoMaker codebase that exceed 3000 lines or are significantly large (1000+ lines) and should be considered for refactoring into smaller, more maintainable components.
**Last Updated:** 2025-12-15
**Total Large Files:** 8
**Combined Size:** 15,027 lines
---
## 🔴 CRITICAL - Over 3000 Lines
### 1. board-view.tsx - 3,325 lines
**Path:** `apps/app/src/components/views/board-view.tsx`
**Type:** React Component (TSX)
**Priority:** VERY HIGH
**Description:**
Main Kanban board view component that serves as the centerpiece of the application.
**Current Responsibilities:**
- Feature/task card management and drag-and-drop operations using @dnd-kit
- Adding, editing, and deleting features
- Running autonomous agents to implement features
- Displaying feature status across multiple columns (Backlog, In Progress, Waiting Approval, Verified)
- Model/AI profile selection for feature implementation
- Advanced options configuration (thinking level, model selection, skip tests)
- Search/filtering functionality for cards
- Output modal for viewing agent results
- Feature suggestions dialog
- Board background customization
- Integration with Electron APIs for IPC communication
- Keyboard shortcuts support
- 40+ state variables for managing UI state
**Refactoring Recommendations:**
Extract into smaller components:
- `AddFeatureDialog.tsx` - Feature creation dialog with image upload
- `EditFeatureDialog.tsx` - Feature editing dialog
- `AgentOutputModal.tsx` - Already exists, verify separation
- `FeatureSuggestionsDialog.tsx` - Already exists, verify separation
- `BoardHeader.tsx` - Header with controls and search
- `BoardSearchBar.tsx` - Search and filter functionality
- `ConcurrencyControl.tsx` - Concurrency slider component
- `BoardActions.tsx` - Action buttons (add feature, auto mode, etc.)
- `DragDropContext.tsx` - Wrap drag-and-drop logic
- Custom hooks:
- `useBoardFeatures.ts` - Feature loading and management
- `useBoardDragDrop.ts` - Drag and drop handlers
- `useBoardActions.ts` - Feature action handlers (run, verify, delete, etc.)
- `useBoardKeyboardShortcuts.ts` - Keyboard shortcut logic
---
## 🟡 HIGH PRIORITY - 2000+ Lines
### 2. sidebar.tsx - 2,396 lines
**Path:** `apps/app/src/components/layout/sidebar.tsx`
**Type:** React Component (TSX)
**Priority:** HIGH
**Description:**
Main navigation sidebar with comprehensive project management.
**Current Responsibilities:**
- Project folder navigation and selection
- View mode switching (Board, Agent, Settings, etc.)
- Project operations (create, delete, rename)
- Theme and appearance controls
- Terminal, Wiki, and other view launchers
- Drag-and-drop project reordering
- Settings and configuration access
**Refactoring Recommendations:**
Split into focused components:
- `ProjectSelector.tsx` - Project list and selection
- `NavigationTabs.tsx` - View mode tabs
- `ProjectActions.tsx` - Create, delete, rename operations
- `SettingsMenu.tsx` - Settings dropdown
- `ThemeSelector.tsx` - Theme controls
- `ViewLaunchers.tsx` - Terminal, Wiki launchers
- Custom hooks:
- `useProjectManagement.ts` - Project CRUD operations
- `useSidebarState.ts` - Sidebar state management
---
### 3. electron.ts - 2,356 lines
**Path:** `apps/app/src/lib/electron.ts`
**Type:** TypeScript Utility/API Bridge
**Priority:** HIGH
**Description:**
Electron IPC bridge and type definitions for frontend-backend communication.
**Current Responsibilities:**
- File system operations (read, write, directory listing)
- Project management APIs
- Feature management APIs
- Terminal/shell execution
- Auto mode and agent execution APIs
- Worktree management
- Provider status APIs
- Event handling and subscriptions
**Refactoring Recommendations:**
Modularize into domain-specific API modules:
- `api/file-system-api.ts` - File operations
- `api/project-api.ts` - Project CRUD
- `api/feature-api.ts` - Feature management
- `api/execution-api.ts` - Auto mode and agent execution
- `api/provider-api.ts` - Provider status and management
- `api/worktree-api.ts` - Git worktree operations
- `api/terminal-api.ts` - Terminal/shell APIs
- `types/electron-types.ts` - Shared type definitions
- `electron.ts` - Main export aggregator
---
### 4. app-store.ts - 2,174 lines
**Path:** `apps/app/src/store/app-store.ts`
**Type:** TypeScript State Management (Zustand Store)
**Priority:** HIGH
**Description:**
Centralized application state store using Zustand.
**Current Responsibilities:**
- Global app state types and interfaces
- Project and feature management state
- Theme and appearance settings
- API keys configuration
- Keyboard shortcuts configuration
- Terminal themes configuration
- Auto mode settings
- All store mutations and selectors
**Refactoring Recommendations:**
Split into domain-specific stores:
- `stores/projects-store.ts` - Project state and actions
- `stores/features-store.ts` - Feature state and actions
- `stores/ui-store.ts` - UI state (theme, sidebar, modals)
- `stores/settings-store.ts` - User settings and preferences
- `stores/execution-store.ts` - Auto mode and running tasks
- `stores/provider-store.ts` - Provider configuration
- `types/store-types.ts` - Shared type definitions
- `app-store.ts` - Main store aggregator with combined selectors
---
## 🟢 MEDIUM PRIORITY - 1000-2000 Lines
### 5. auto-mode-service.ts - 1,232 lines
**Path:** `apps/server/src/services/auto-mode-service.ts`
**Type:** TypeScript Service (Backend)
**Priority:** MEDIUM-HIGH
**Description:**
Core autonomous feature implementation service.
**Current Responsibilities:**
- Worktree creation and management
- Feature execution with Claude Agent SDK
- Concurrent execution with concurrency limits
- Progress streaming via events
- Verification and merge workflows
- Provider management
- Error handling and classification
**Refactoring Recommendations:**
Extract into service modules:
- `services/worktree-manager.ts` - Worktree operations
- `services/feature-executor.ts` - Feature execution logic
- `services/concurrency-manager.ts` - Concurrency control
- `services/verification-service.ts` - Verification workflows
- `utils/error-classifier.ts` - Error handling utilities
---
### 6. spec-view.tsx - 1,230 lines
**Path:** `apps/app/src/components/views/spec-view.tsx`
**Type:** React Component (TSX)
**Priority:** MEDIUM
**Description:**
Specification editor view component for feature specification management.
**Refactoring Recommendations:**
Extract editor components and hooks:
- `SpecEditor.tsx` - Main editor component
- `SpecToolbar.tsx` - Editor toolbar
- `SpecSidebar.tsx` - Spec navigation sidebar
- `useSpecEditor.ts` - Editor state management
---
### 7. kanban-card.tsx - 1,180 lines
**Path:** `apps/app/src/components/views/kanban-card.tsx`
**Type:** React Component (TSX)
**Priority:** MEDIUM
**Description:**
Individual Kanban card component with rich feature display and interaction.
**Refactoring Recommendations:**
Split into smaller card components:
- `KanbanCardHeader.tsx` - Card title and metadata
- `KanbanCardBody.tsx` - Card content
- `KanbanCardActions.tsx` - Action buttons
- `KanbanCardStatus.tsx` - Status indicators
- `useKanbanCard.ts` - Card interaction logic
---
### 8. analysis-view.tsx - 1,134 lines
**Path:** `apps/app/src/components/views/analysis-view.tsx`
**Type:** React Component (TSX)
**Priority:** MEDIUM
**Description:**
Analysis view component for displaying and managing feature analysis data.
**Refactoring Recommendations:**
Extract visualization and data components:
- `AnalysisChart.tsx` - Chart/graph components
- `AnalysisTable.tsx` - Data table
- `AnalysisFilters.tsx` - Filter controls
- `useAnalysisData.ts` - Data fetching and processing
---
## Refactoring Strategy
### Phase 1: Critical (Immediate)
1. **board-view.tsx** - Break into dialogs, header, and custom hooks
- Extract all dialogs first (AddFeature, EditFeature)
- Move to custom hooks for business logic
- Split remaining UI into smaller components
### Phase 2: High Priority (Next Sprint)
2. **sidebar.tsx** - Componentize navigation and project management
3. **electron.ts** - Modularize into API domains
4. **app-store.ts** - Split into domain stores
### Phase 3: Medium Priority (Future)
5. **auto-mode-service.ts** - Extract service modules
6. **spec-view.tsx** - Break into editor components
7. **kanban-card.tsx** - Split card into sub-components
8. **analysis-view.tsx** - Extract visualization components
---
## General Refactoring Guidelines
### When Refactoring Large Components:
1. **Extract Dialogs/Modals First**
- Move dialog components to separate files
- Keep dialog state management in parent initially
- Later extract to custom hooks if complex
2. **Create Custom Hooks for Business Logic**
- Move data fetching to `useFetch*` hooks
- Move complex state logic to `use*State` hooks
- Move side effects to `use*Effect` hooks
3. **Split UI into Presentational Components**
- Header/toolbar components
- Content area components
- Footer/action components
4. **Move Utils and Helpers**
- Extract pure functions to utility files
- Move constants to separate constant files
- Create type files for shared interfaces
### When Refactoring Large Files:
1. **Identify Domains/Concerns**
- Group related functionality
- Find natural boundaries
2. **Extract Gradually**
- Start with least coupled code
- Work towards core functionality
- Test after each extraction
3. **Maintain Type Safety**
- Export types from extracted modules
- Use shared type files for common interfaces
- Ensure no type errors after refactoring
---
## Progress Tracking
- [ ] board-view.tsx (3,325 lines)
- [ ] sidebar.tsx (2,396 lines)
- [ ] electron.ts (2,356 lines)
- [ ] app-store.ts (2,174 lines)
- [ ] auto-mode-service.ts (1,232 lines)
- [ ] spec-view.tsx (1,230 lines)
- [ ] kanban-card.tsx (1,180 lines)
- [ ] analysis-view.tsx (1,134 lines)
**Target:** All files under 500 lines, most under 300 lines
---
*Generated: 2025-12-15*

View File

@@ -1,9 +1,9 @@
# Migration Plan: Next.js to Vite + Electron + TanStack
> **Document Version**: 1.0
> **Document Version**: 1.1
> **Date**: December 2025
> **Status**: Planning Phase
> **Branch**: feature/worktrees (awaiting merge before implementation)
> **Status**: Phase 2 Complete - Core Migration Done
> **Branch**: refactor/frontend
---
@@ -1526,37 +1526,48 @@ export async function pickFile(options?: {
**Goal**: Set up new build infrastructure without breaking existing functionality.
- [ ] Create `vite.config.mts` with electron plugins
- [ ] Create `electron/tsconfig.json` for Electron TypeScript
- [ ] Convert `electron/main.js``electron/main.ts`
- [ ] Convert `electron/preload.js``electron/preload.ts`
- [ ] Implement IPC schema and type-safe handlers
- [ ] Set up TanStack Router configuration
- [ ] Port debug console from starter template
- [ ] Create `index.html` for Vite entry
- [x] Create `vite.config.mts` with electron plugins
- [x] Create `electron/tsconfig.json` for Electron TypeScript
- [x] Convert `electron/main.js``electron/main.ts`
- [x] Convert `electron/preload.js``electron/preload.ts`
- [ ] Implement IPC schema and type-safe handlers (deferred - using existing HTTP API)
- [x] Set up TanStack Router configuration
- [ ] Port debug console from starter template (deferred)
- [x] Create `index.html` for Vite entry
**Deliverables**:
- Working Vite dev server
- Type-safe Electron main process
- Debug console functional
- [x] Working Vite dev server
- [x] TypeScript Electron main process
- [ ] Debug console functional (deferred)
### Phase 2: Core Migration (Week 3-4)
**Goal**: Replace Next.js with Vite while maintaining feature parity.
- [ ] Create `src/renderer.ts` entry point
- [ ] Create `src/App.tsx` root component
- [ ] Set up TanStack Router with file-based routes
- [ ] Port all views to route files
- [ ] Update environment variables (`NEXT_PUBLIC_*``VITE_*`)
- [ ] Verify Zustand stores work unchanged
- [ ] Verify HTTP API client works unchanged
- [ ] Test both Electron and Web builds
- [x] Create `src/renderer.tsx` entry point
- [x] Create `src/App.tsx` root component
- [x] Set up TanStack Router with file-based routes
- [x] Port all views to route files
- [x] Update environment variables (`NEXT_PUBLIC_*``VITE_*`)
- [x] Verify Zustand stores work unchanged
- [x] Verify HTTP API client works unchanged
- [x] Test Electron build
- [ ] Test Web build (needs verification)
**Additional completed tasks**:
- [x] Remove all "use client" directives (not needed in Vite)
- [x] Replace all `setCurrentView()` calls with TanStack Router `navigate()`
- [x] Rename `apps/app` to `apps/ui`
- [x] Update package.json scripts
- [x] Configure memory history for Electron (no URL bar)
- [x] Fix ES module imports (replace `require()` with `import`)
- [x] Remove PostCSS config (using `@tailwindcss/vite` plugin)
**Deliverables**:
- All views accessible via TanStack Router
- Both Electron and web builds functional
- No regression in existing functionality
- [x] All views accessible via TanStack Router
- [x] Electron build functional
- [ ] Web build functional (needs testing)
- [x] No regression in existing functionality
### Phase 3: Component Refactoring (Week 5-7)
@@ -1740,11 +1751,15 @@ export default defineConfig({
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | Dec 2025 | Team | Initial migration plan |
| 1.1 | Dec 2025 | Team | Phase 1 & 2 complete. Updated checkboxes, added completed tasks, noted deferred items |
---
**Next Steps**:
1. Review and approve this plan
2. Wait for `feature/worktrees` branch merge
3. Create `feature/vite-migration` branch
4. Begin Phase 1 implementation
1. ~~Review and approve this plan~~
2. ~~Wait for `feature/worktrees` branch merge~~
3. ~~Create migration branch~~ ✅ (refactor/frontend)
4. ~~Complete Phase 1 implementation~~
5. ~~Complete Phase 2 implementation~~
6. **Current**: Verify web build works, then begin Phase 3 (Component Refactoring)
7. Consider implementing deferred items: Debug console, IPC schema

268
plan.md
View File

@@ -1,268 +0,0 @@
# Plan: Full Web Support for Automaker
## Goal
Make the app work fully in web browsers while keeping Electron support. Web mode connects to a backend server (self-hosted or cloud). Electron embeds the same server locally.
## Architecture
```
┌─────────────────────────────────────┐
│ Next.js Frontend │
│ (same code both modes) │
└───────────────┬─────────────────────┘
┌───────────┴───────────┐
│ │
[Web Mode] [Electron Mode]
│ │
HTTP/WebSocket HTTP/WebSocket
to remote server to localhost:3008
│ │
└───────────┬───────────┘
┌───────────────▼─────────────────────┐
│ Backend Server │
│ (apps/server) │
│ - Express + WebSocket │
│ - All services from electron/ │
│ - Claude Agent SDK │
│ - File ops, Git, PTY │
└─────────────────────────────────────┘
```
**Key insight**: Electron uses the same HTTP API - just connects to localhost instead of remote.
---
## New Package: `apps/server`
```
apps/server/
├── package.json
├── src/
│ ├── index.ts # Express server entry
│ ├── routes/
│ │ ├── fs.ts # File system routes
│ │ ├── agent.ts # Agent routes
│ │ ├── sessions.ts # Session routes
│ │ ├── auto-mode.ts # Auto mode routes
│ │ ├── features.ts # Features routes
│ │ ├── worktree.ts # Git worktree routes
│ │ ├── setup.ts # Setup/config routes
│ │ └── suggestions.ts # Feature suggestions routes
│ ├── services/ # Moved from electron/services/
│ │ ├── agent-service.ts
│ │ ├── auto-mode-service.ts
│ │ ├── worktree-manager.ts
│ │ ├── feature-loader.ts
│ │ ├── feature-executor.ts
│ │ └── ...
│ └── lib/
│ ├── events.ts # Event emitter for streaming
│ └── security.ts # Path validation
```
---
## Critical Files to Modify
| File | Change |
|------|--------|
| `apps/app/src/lib/electron.ts` | Add `HttpApiClient` class that implements `ElectronAPI` using fetch/WebSocket |
| `apps/app/electron/main.js` | Simplify to: spawn server + create window (remove 1500+ lines of IPC handlers) |
| `apps/app/electron/preload.js` | Simplify to just expose `isElectron` flag |
| `apps/app/package.json` | Remove server-side deps (Claude SDK, pty) |
| Root `package.json` | Add `apps/server` workspace |
---
## Implementation Phases
### Phase 1: Create Server Package (Foundation)
1. Create `apps/server` with Express + TypeScript setup
2. Add health check endpoint: `GET /api/health`
3. Copy one simple service (feature-loader) and create route
4. Test with curl/Postman
### Phase 2: File System API
1. Create `POST /api/fs/read`, `POST /api/fs/write`, etc.
2. Add path security (allowlist validation)
3. Update `electron.ts` with `HttpApiClient` for fs operations
4. Test: file operations work in web mode
### Phase 3: Agent API with Streaming
1. Add WebSocket server for events (`/api/events`)
2. Migrate `agent-service.js` to TypeScript
3. Create routes: `POST /api/agent/send`, etc.
4. Events stream via WebSocket instead of IPC
5. Test: chat works in web mode
### Phase 4: Sessions & Features API
1. Migrate session management routes
2. Migrate features CRUD routes
3. Test: project/feature management works
### Phase 5: Auto Mode & Worktree
1. Migrate `auto-mode-service.js` (complex - has streaming)
2. Migrate `worktree-manager.js`
3. Test: auto mode runs features in web
### Phase 6: Remaining Services
1. Spec regeneration
2. Feature suggestions
3. Setup/CLI detection
4. Model provider checks
### Phase 7: Simplify Electron
1. Update `main.js` to spawn server process + create window
2. Remove all IPC handlers
3. Electron app uses HTTP like web
4. Test: Electron still works
### Phase 8: Production Ready
1. Add authentication (API key header)
2. Configure CORS for production
3. Add `ALLOWED_PROJECT_DIRS` env for security
4. Docker setup for deployment
5. Update build scripts
---
## API Design Pattern
Convert IPC handlers to REST:
```
IPC: dialog:openDirectory → Web: User types path, POST /api/fs/validate
IPC: fs:readFile → POST /api/fs/read { filePath }
IPC: agent:send → POST /api/agent/send { sessionId, message, ... }
IPC: auto-mode:start → POST /api/auto-mode/start { projectPath }
IPC: features:getAll → GET /api/projects/:path/features
```
Streaming via WebSocket:
```
ws://server/api/events
Events: agent:stream, auto-mode:event, suggestions:event
```
---
## Web-Specific Handling
| Feature | Electron | Web |
|---------|----------|-----|
| File picker | Native dialog | Text input + server validation |
| Open link | shell.openExternal | window.open() |
| Data directory | app.getPath('userData') | Server's DATA_DIR env |
---
## Configuration
**Server `.env`:**
```
PORT=3008
DATA_DIR=/path/to/data
ANTHROPIC_API_KEY=xxx
ALLOWED_PROJECT_DIRS=/home/user/projects
```
**Frontend `.env.local`:**
```
NEXT_PUBLIC_SERVER_URL=http://localhost:3008
```
---
## Estimated Scope
- New files: ~15-20 (server package)
- Modified files: ~5 (electron.ts, main.js, preload.js, package.jsons)
- Deleted lines: ~1500 (IPC handlers from main.js)
- Services to migrate: ~10
---
## Implementation Status
### ✅ ALL PHASES COMPLETE
- [x] **Phase 1**: Server package foundation (`apps/server`)
- Express server with WebSocket support
- Event emitter for streaming
- Security module for path validation
- Health check endpoint
- [x] **Phase 2**: HttpApiClient in frontend
- `apps/app/src/lib/http-api-client.ts` - full implementation
- Modified `electron.ts` to use HTTP client when not in Electron
- No mocks - all calls go through HTTP
- [x] **Phase 3**: Agent API with streaming
- `apps/server/src/services/agent-service.ts`
- `apps/server/src/routes/agent.ts`
- WebSocket streaming for responses
- [x] **Phase 4**: Sessions & Features API
- `apps/server/src/routes/sessions.ts`
- `apps/server/src/services/feature-loader.ts`
- `apps/server/src/routes/features.ts`
- [x] **Phase 5**: Auto Mode & Worktree
- `apps/server/src/services/auto-mode-service.ts` - full implementation with Claude SDK
- `apps/server/src/routes/auto-mode.ts`
- `apps/server/src/routes/worktree.ts`
- `apps/server/src/routes/git.ts`
- [x] **Phase 6**: Remaining services
- `apps/server/src/routes/setup.ts` - CLI detection, API keys, platform info
- `apps/server/src/routes/suggestions.ts` - AI-powered feature suggestions
- `apps/server/src/routes/spec-regeneration.ts` - spec generation from overview
- `apps/server/src/routes/models.ts` - model providers and availability
- `apps/server/src/routes/running-agents.ts` - active agent tracking
- [x] **Phase 7**: Simplify Electron
- `apps/app/electron/main.js` - spawns server, minimal IPC (10 handlers for native features only)
- `apps/app/electron/preload.js` - only native features exposed
- Updated `electron.ts` to detect simplified mode
- Updated `http-api-client.ts` to use native dialogs when available
- Removed ~13,000 lines of dead code (obsolete services, agent-service.js, auto-mode-service.js)
- [x] **Phase 8**: Production ready
- `apps/server/src/lib/auth.ts` - API key authentication middleware
- `apps/server/Dockerfile` - multi-stage Docker build
- `docker-compose.yml` - easy deployment configuration
- `apps/server/.env.example` - documented configuration
---
## Additional Fixes Applied
### State Persistence
- Features now cached in localStorage via Zustand persist middleware
- Board view properly handles API failures by keeping cached data
- Theme and UI state properly persisted across refreshes
### Authentication Display
- Server now returns proper auth method names: `oauth_token_env`, `oauth_token`, `api_key_env`, `api_key`
- Settings view displays correct auth source (OAuth token, API key, subscription, etc.)
- Added support for Codex subscription detection
- Fixed "Unknown method" display issue
### Bug Fixes
- Fixed board-view.tsx crash when feature status is unknown (defaults to backlog)
- Removed "Mock IPC" label from web mode indicator
- Fixed unused imports and dependency warnings
- Updated API key authentication header support in HTTP client
---
## Summary
The architecture is simple: **one backend server, two ways to access it** (web browser or Electron shell).
- **Web users**: Connect browser to your cloud-hosted server
- **Electron users**: App spawns server locally, connects to localhost
- **Same codebase**: Frontend code unchanged, backend services extracted to standalone server