# GridPilot Companion App - POC Guide

## Overview

The Electron companion app demonstrates the complete hosted session automation workflow with a visual interface, validating the Clean Architecture implementation through a functional proof-of-concept.

## Quick Start

### Prerequisites

```bash
npm install
```

### Running the POC

```bash
npm run companion:start
```

This command:
1. Compiles TypeScript main process → `dist/main/`
2. Builds React renderer with Vite → `dist/renderer/`
3. Launches the Electron application

## What You'll See

### Left Panel: Session Configuration Form

Pre-configured form with fields representing all 18 automation steps:
- **Session Name** - Race session identifier
- **Server Name** - Server configuration name
- **Passwords** - Session and admin access credentials
- **Max Drivers** - Capacity (1-60)
- **Track** - Track selection (e.g., "watkins-glen")
- **Cars** - Vehicle selection (e.g., "porsche-911-gt3-r")
- **Weather Type** - Static or dynamic weather
- **Time of Day** - Morning, afternoon, evening, or night
- **Session Lengths** - Practice, qualifying, warmup, race durations
- **Race Options** - Start type, restarts, damage model
- **Track State** - Surface condition

**Action**: Click "Start Automation" to begin the workflow

### Right Panel: Live Progress Monitor

Real-time visualization showing:
- **Session ID** - Generated UUID
- **Current Status** - Running/Completed/Failed/Stopped
- **Step-by-Step Progress** - Visual indicators for all 18 steps:
  - ✓ Green checkmark = Completed
  - Blue number = Current step (in progress)
  - Gray number = Pending
- **Safety Notice** - Yellow warning at step 18 stop point
- **Progress Counter** - "X / 18 steps" tracker

## Expected Behavior

### 1. Initial State
- Form enabled with pre-filled POC defaults
- Progress panel shows "Configure and start..." message

### 2. Automation Started
- Form becomes disabled
- Button changes to "Automation Running..."
- Progress panel shows "Running" status
- Steps begin progressing: 1 → 2 → 3 → ... → 18

### 3. Step Progression (Simulated)
Each step takes ~500ms to complete:
- **Step 1**: Navigate to Hosted Racing
- **Step 2**: Click Create a Race  
- **Step 3**: Fill Race Information
- **Step 4**: Configure Server Details
- **Step 5**: Set Admins
- **Step 6**: Add Admin (modal step)
- **Step 7**: Set Time Limits
- **Step 8**: Set Cars
- **Step 9**: Add Car (modal step)
- **Step 10**: Set Car Classes
- **Step 11**: Set Track
- **Step 12**: Add Track (modal step)
- **Step 13**: Configure Track Options
- **Step 14**: Set Time of Day
- **Step 15**: Configure Weather
- **Step 16**: Set Race Options
- **Step 17**: Configure Team Driving
- **Step 18**: Set Track Conditions → **STOPS HERE**

### 4. Step 18 Reached
- Status changes to "Stopped at Step 18"
- Yellow safety notice appears:
  ```
  ⚠️ Safety Stop
  Automation stopped at step 18 (Track Conditions) as configured.
  This prevents accidental session creation during POC demonstration.
  ```
- Form remains disabled
- All 18 steps visible with completion status

## Technical Architecture

### Clean Architecture Validation

**Presentation Layer** (newly created):
```
src/apps/companion/
├── main/
│   ├── index.ts              # Electron app initialization
│   ├── di-container.ts       # Dependency injection
│   ├── ipc-handlers.ts       # IPC request/response handlers
│   └── preload.ts            # Secure IPC bridge
└── renderer/
    ├── App.tsx               # Main UI component
    ├── main.tsx              # React entry point
    ├── index.html            # HTML entry
    └── components/
        ├── SessionCreationForm.tsx
        └── SessionProgressMonitor.tsx
```

**Reused Layers** (100% unchanged):
- **Domain**: [`AutomationSession`](../src/core/domain/entities/AutomationSession.ts:1), [`SessionState`](../src/core/domain/value-objects/SessionState.ts:1), [`StepId`](../src/core/domain/value-objects/StepId.ts:1)
- **Application**: [`StartAutomationSessionUseCase`](../src/core/application/use-cases/StartAutomationSessionUseCase.ts:1)
- **Infrastructure**: [`MockBrowserAutomationAdapter`](../src/infrastructure/adapters/automation/MockBrowserAutomationAdapter.ts:1), [`MockAutomationEngineAdapter`](../src/infrastructure/adapters/automation/MockAutomationEngineAdapter.ts:1), [`InMemorySessionRepository`](../src/infrastructure/repositories/InMemorySessionRepository.ts:1)

### IPC Communication Flow

```
Renderer Process              Main Process
     |                             |
     |-- start-automation -------->|
     |                             |-- Create session
     |                             |-- Start automation engine
     |                             |-- Begin step execution loop
     |                             |
     |<-- session-progress --------|  (emitted every 100ms)
     |<-- session-progress --------|
     |<-- session-progress --------|
     |                             |
```

### Dependency Chain

```
UI Component (React)
    ↓
IPC Handler (Electron main)
    ↓
DI Container
    ↓
StartAutomationSessionUseCase
    ↓
MockAutomationEngineAdapter
    ↓
MockBrowserAutomationAdapter
InMemorySessionRepository
```

## POC Success Criteria

✅ **Clean Architecture Preserved**
- Zero business logic in UI components
- Complete separation of concerns
- All 158 existing tests still passing
- Domain/application/infrastructure layers unchanged

✅ **18-Step Workflow Visualized**
- All steps from [`ROADMAP.md`](./ROADMAP.md:1) represented
- Real-time progress updates every 100ms
- State transitions validated by domain layer
- Step execution tracked via domain entities

✅ **Mock Adapters Functional**
- Browser automation simulated with realistic delays
- Session state persisted in-memory
- Dependency injection wiring complete
- Automation engine orchestrates workflow

✅ **Electron Best Practices**
- Context isolation enabled
- Preload script for secure IPC
- Main/renderer process separation
- No node integration in renderer

✅ **Safety Stop Demonstrated**
- Automation stops at step 18 as designed
- `STOPPED_AT_STEP_18` state properly displayed
- Clear user communication about safety measure
- No accidental session creation possible

## Architecture Compliance

### Boundaries Respected

**Presentation Layer** (UI only):
- React components render data
- Electron IPC handles communication
- No domain knowledge or business logic

**Application Layer** (orchestration):
- Use cases coordinate workflow
- Port interfaces define contracts
- No UI or infrastructure concerns

**Domain Layer** (business rules):
- Entities enforce invariants
- Value objects validate states
- Services implement domain logic
- No dependencies on outer layers

**Infrastructure Layer** (adapters):
- Mock implementations for POC
- Repository handles persistence
- Automation adapters simulate browser
- Ready to swap with real implementations

### SOLID Principles Demonstrated

- **Single Responsibility**: Each component has one clear purpose
- **Open/Closed**: New adapters can be added without changing domain
- **Liskov Substitution**: Mock adapters fully implement port interfaces
- **Interface Segregation**: Clean port definitions, no fat interfaces
- **Dependency Inversion**: All dependencies point inward via abstractions

## Next Steps (Beyond POC)

This POC validates the technical approach. For production:

1. **Replace Mock Adapters**:
   - Swap [`MockBrowserAutomationAdapter`](../src/infrastructure/adapters/automation/MockBrowserAutomationAdapter.ts:1) with `PuppeteerAdapter` or `PlaywrightAdapter`
   - Replace [`InMemorySessionRepository`](../src/infrastructure/repositories/InMemorySessionRepository.ts:1) with `PostgreSQLSessionRepository`

2. **Implement Real Automation**:
   - Add actual browser control (Puppeteer/Playwright)
   - Implement iRacing website interaction
   - Handle real modals, forms, and navigation

3. **Add Pause/Resume**:
   - IPC handlers currently stubbed
   - Implement session state management
   - Add UI controls for pause/resume

4. **Polish UI/UX**:
   - Professional styling and branding
   - Error recovery flows
   - Better loading states

5. **Production Features**:
   - Auto-updater mechanism
   - Crash reporting
   - Logging and diagnostics
   - User preferences storage

## Troubleshooting

### Build Fails

```bash
# Clean and rebuild
rm -rf dist node_modules
npm install
npm run companion:build
```

### Electron Doesn't Start

```bash
# Verify build output exists
ls dist/main/index.js        # Main process
ls dist/renderer/index.html  # Renderer

# Run directly
electron dist/main/index.js
```

### Progress Not Updating

- Open DevTools in Electron (View → Toggle Developer Tools)
- Check browser console for errors
- Verify IPC handlers registered
- Check main process terminal output

### TypeScript Errors

```bash
# Check configuration
cat tsconfig.electron.json

# Verify include paths match your structure
npm run typecheck
```

## File Reference

| File | Purpose | Lines |
|------|---------|-------|
| [`main/index.ts`](../src/apps/companion/main/index.ts:1) | Electron app initialization | 39 |
| [`main/di-container.ts`](../src/apps/companion/main/di-container.ts:1) | Dependency injection setup | 47 |
| [`main/ipc-handlers.ts`](../src/apps/companion/main/ipc-handlers.ts:1) | Request/response handlers | 79 |
| [`main/preload.ts`](../src/apps/companion/main/preload.ts:1) | Secure IPC bridge | 21 |
| [`renderer/App.tsx`](../src/apps/companion/renderer/App.tsx:1) | Main UI component | 80 |
| [`renderer/components/SessionCreationForm.tsx`](../src/apps/companion/renderer/components/SessionCreationForm.tsx:1) | Config form | 173 |
| [`renderer/components/SessionProgressMonitor.tsx`](../src/apps/companion/renderer/components/SessionProgressMonitor.tsx:1) | Progress visualization | 213 |
| [`MockAutomationEngineAdapter.ts`](../src/infrastructure/adapters/automation/MockAutomationEngineAdapter.ts:1) | Automation orchestrator | 85 |

## Conclusion

This POC successfully demonstrates:
- Clean Architecture principles in practice
- Separation of concerns across all layers
- Real-time automation workflow visualization
- Safety controls preventing accidental actions
- Foundation for production implementation

All domain logic remains testable, maintainable, and independent of UI or infrastructure concerns. The 158 passing tests validate the core business rules remain intact.