diff --git a/- b/- new file mode 100644 index 0000000..1665d14 Binary files /dev/null and b/- differ diff --git a/LLMChat b/LLMChat new file mode 160000 index 0000000..01f53de --- /dev/null +++ b/LLMChat @@ -0,0 +1 @@ +Subproject commit 01f53de6630e7302fc58f103b3fad382d8d270bc diff --git a/PLAN_CAPTAIN_MOBILE_V2.md b/PLAN_CAPTAIN_MOBILE_V2.md new file mode 100644 index 0000000..0849185 --- /dev/null +++ b/PLAN_CAPTAIN_MOBILE_V2.md @@ -0,0 +1,307 @@ +# PLAN: Captain Claude Mobile v2 + +## Objetivo +App móvil nativa de chat con Claude que ejecuta comandos en el servidor y muestra resultados formateados. + +--- + +## 1. ARQUITECTURA + +``` +┌──────────────────┐ HTTPS/WSS ┌──────────────────┐ +│ │ ◄────────────────► │ │ +│ Flutter App │ │ FastAPI │ +│ (Android/iOS) │ │ Backend │ +│ │ │ │ +└──────────────────┘ └────────┬─────────┘ + │ + │ subprocess + ▼ + ┌──────────────────┐ + │ │ + │ Claude CLI │ + │ (claude -p) │ + │ │ + └──────────────────┘ +``` + +### Backend (FastAPI) +- Recibe mensajes del usuario via WebSocket +- Ejecuta `claude -p "mensaje" --output-format stream-json` +- Parsea el output JSON de Claude +- Envía respuesta formateada al frontend +- Guarda historial en PostgreSQL + +### Frontend (Flutter) +- UI de chat nativa (burbujas, input, etc.) +- Renderiza Markdown en respuestas +- Syntax highlighting en code blocks +- Muestra progreso de ejecución +- Historial de conversaciones + +--- + +## 2. DISEÑO UI/UX + +### Pantalla Principal (Chat) +``` +┌─────────────────────────────────┐ +│ ☰ Captain Claude [●] Online│ ← AppBar con estado conexión +├─────────────────────────────────┤ +│ │ +│ ┌─ User ────────────────────┐ │ +│ │ Muéstrame el uso de disco │ │ ← Burbuja usuario (derecha) +│ └───────────────────────────┘ │ +│ │ +│ ┌─ Claude ──────────────────┐ │ ← Burbuja Claude (izquierda) +│ │ Ejecutando `df -h`... │ │ +│ │ │ │ +│ │ ``` │ │ ← Code block con resultado +│ │ Filesystem Size Used │ │ +│ │ /dev/sda1 100G 45G │ │ +│ │ ``` │ │ +│ │ │ │ +│ │ El disco principal tiene │ │ ← Explicación en texto +│ │ 55% libre (55GB). │ │ +│ └───────────────────────────┘ │ +│ │ +├─────────────────────────────────┤ +│ ┌─────────────────────────┐ 📎│ ← Input con attach +│ │ Escribe un mensaje... │ ➤ │ ← Botón enviar +│ └─────────────────────────────┘│ +└─────────────────────────────────┘ +``` + +### Pantalla Historial +``` +┌─────────────────────────────────┐ +│ ← Conversaciones │ +├─────────────────────────────────┤ +│ ┌─────────────────────────────┐│ +│ │ 📁 Backup de base de datos ││ ← Título auto-generado +│ │ Hace 2 horas • 5 mensajes ││ +│ └─────────────────────────────┘│ +│ ┌─────────────────────────────┐│ +│ │ 🔧 Fix error en nginx ││ +│ │ Ayer • 12 mensajes ││ +│ └─────────────────────────────┘│ +│ ┌─────────────────────────────┐│ +│ │ 📊 Análisis de logs ││ +│ │ 15 Ene • 8 mensajes ││ +│ └─────────────────────────────┘│ +└─────────────────────────────────┘ +``` + +### Estados de Mensaje Claude +1. **Pensando**: Spinner + "Claude está pensando..." +2. **Ejecutando**: Muestra comando siendo ejecutado +3. **Streaming**: Texto aparece progresivamente +4. **Completado**: Mensaje completo con formato +5. **Error**: Mensaje rojo con opción de reintentar + +--- + +## 3. API BACKEND + +### Endpoints REST + +| Método | Endpoint | Descripción | +|--------|----------|-------------| +| POST | /auth/login | Login, retorna JWT | +| GET | /conversations | Lista conversaciones | +| GET | /conversations/{id} | Mensajes de una conversación | +| DELETE | /conversations/{id} | Eliminar conversación | +| POST | /upload | Subir archivo para contexto | + +### WebSocket /ws/chat + +**Cliente → Servidor:** +```json +{ + "type": "message", + "content": "Muéstrame el uso de disco", + "conversation_id": "uuid-opcional", + "files": ["/path/to/file"] +} +``` + +**Servidor → Cliente (streaming):** +```json +{"type": "thinking"} +{"type": "tool_use", "tool": "Bash", "input": "df -h"} +{"type": "tool_result", "output": "Filesystem Size..."} +{"type": "text", "content": "El disco principal..."} +{"type": "done", "conversation_id": "uuid"} +``` + +--- + +## 4. MODELO DE DATOS + +### PostgreSQL + +```sql +-- Conversaciones +CREATE TABLE conversations ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id VARCHAR(255) NOT NULL, + title VARCHAR(500), + created_at TIMESTAMP DEFAULT NOW(), + updated_at TIMESTAMP DEFAULT NOW() +); + +-- Mensajes +CREATE TABLE messages ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + conversation_id UUID REFERENCES conversations(id), + role VARCHAR(50) NOT NULL, -- 'user' | 'assistant' + content TEXT NOT NULL, + tool_uses JSONB, -- [{tool, input, output}] + created_at TIMESTAMP DEFAULT NOW() +); +``` + +--- + +## 5. FLUTTER - ESTRUCTURA + +``` +lib/ +├── main.dart +├── config/ +│ └── api_config.dart +├── models/ +│ ├── conversation.dart +│ ├── message.dart +│ └── tool_use.dart +├── services/ +│ ├── api_service.dart +│ ├── chat_service.dart # WebSocket +│ └── auth_service.dart +├── providers/ +│ ├── auth_provider.dart +│ └── chat_provider.dart +├── screens/ +│ ├── login_screen.dart +│ ├── chat_screen.dart +│ └── history_screen.dart +└── widgets/ + ├── message_bubble.dart # Burbuja de mensaje + ├── code_block.dart # Syntax highlighting + ├── tool_use_card.dart # Muestra ejecución de tool + ├── thinking_indicator.dart + └── chat_input.dart # Input con attach +``` + +--- + +## 6. COMPONENTES CLAVE + +### MessageBubble (Flutter) +```dart +class MessageBubble extends StatelessWidget { + final Message message; + + // Renderiza según tipo: + // - Texto normal → Markdown + // - Code blocks → Syntax highlighting + // - Tool uses → Cards expandibles + // - Errores → Estilo rojo +} +``` + +### ToolUseCard (Flutter) +```dart +// Muestra: +// ┌─ Bash ──────────────────────┐ +// │ ▶ df -h │ ← Comando ejecutado +// ├─────────────────────────────┤ +// │ Filesystem Size Used ... │ ← Output (colapsable) +// └─────────────────────────────┘ +``` + +### ChatInput (Flutter) +```dart +// - TextField multilínea +// - Botón adjuntar archivo +// - Botón enviar (disabled si vacío o desconectado) +// - Indicador de conexión +``` + +--- + +## 7. PROCESO DE DESARROLLO + +### Fase 1: Backend básico +1. FastAPI con WebSocket +2. Integración con Claude CLI +3. Parsing de output JSON +4. Base de datos PostgreSQL + +### Fase 2: Frontend básico +1. Chat UI con burbujas +2. Conexión WebSocket +3. Streaming de mensajes +4. Markdown rendering + +### Fase 3: Features completas +1. Historial de conversaciones +2. Syntax highlighting +3. Tool use cards +4. Upload de archivos +5. Estados de conexión + +### Fase 4: Pulido +1. Animaciones +2. Error handling robusto +3. Offline mode básico +4. Notificaciones + +--- + +## 8. PROCESO DE AUDITORÍA (post-código) + +### Ronda 1: Agentes paralelos +- **Arquitecto**: Revisa estructura del código +- **QA**: Busca bugs y edge cases +- **UX**: Evalúa usabilidad + +### Ronda 2: Tests reales +- Probar cada endpoint con curl +- Instalar APK y probar flujos +- Documentar problemas + +### Ronda 3: Fixes + re-test +- Aplicar correcciones +- Verificar que funcionan +- Compilar versión final + +--- + +## 9. DIFERENCIAS CON v1 + +| Aspecto | v1 (Terminal) | v2 (Chat) | +|---------|---------------|-----------| +| UI | Emulador xterm | Chat nativo | +| Input | Teclado terminal | Texto natural | +| Output | Raw ANSI | Markdown formateado | +| Comandos | Ctrl+C manual | Claude decide | +| UX | Técnico | Amigable | + +--- + +## 10. CRITERIOS DE ÉXITO + +1. ✅ Usuario puede chatear con Claude en lenguaje natural +2. ✅ Claude ejecuta comandos y muestra resultados formateados +3. ✅ Code blocks tienen syntax highlighting +4. ✅ Conversaciones se guardan y se pueden retomar +5. ✅ UI es responsiva y agradable en móvil +6. ✅ Errores se muestran claramente con opción de reintentar +7. ✅ Conexión se reconecta automáticamente + +--- + +## PRÓXIMO PASO + +¿Apruebas este plan para empezar a implementar? diff --git a/apps/captain-mobile-v2/ESTADO_PROYECTO.md b/apps/captain-mobile-v2/ESTADO_PROYECTO.md new file mode 100644 index 0000000..0aa5911 --- /dev/null +++ b/apps/captain-mobile-v2/ESTADO_PROYECTO.md @@ -0,0 +1,164 @@ +# Captain Claude Mobile v2 - Estado del Proyecto + +**Fecha:** 2026-01-17 +**Estado:** BACKEND ACTUALIZADO / PENDIENTE COMPILAR APK + +--- + +## Cambios Realizados (17 Ene 2026) + +### Backend reescrito con patrón LLMChat + +Se aplicó el patrón de streaming de [LLMChat](https://github.com/c0sogi/LLMChat): + +1. **Queue para desacoplar receiver/sender** + - `asyncio.Queue` para mensajes entrantes + - `ws_receiver()` y `ws_sender()` corren en paralelo con `asyncio.gather()` + +2. **ChatBuffer** - Contexto por conexión + - Mantiene estado: `websocket`, `username`, `queue`, `done`, `conversation_id` + - `done` event para interrumpir streaming + +3. **Mensaje `init` al conectar** + - Envía lista de conversaciones al conectar + - Frontend recibe estado inicial sin llamada REST adicional + +4. **Soporte para interrumpir streaming** + - Cliente envía `{"type": "stop"}` + - Backend termina proceso Claude y envía `{"type": "interrupted"}` + +5. **Nuevos tipos de mensaje** + - `init` - Estado inicial con conversaciones + - `text_start` - Inicio de bloque de texto + - `tool_input` - Input completo del tool + - `interrupted` - Generación interrumpida + - `conversation_loaded` - Conversación cargada via WS + +--- + +## Configuración Actual + +| Componente | Puerto | Notas | +|------------|--------|-------| +| **captain-api-v2** | **3030** | Backend con patrón LLMChat | + +**Credenciales:** `admin` / `admin` +**Servicio:** `captain-api-v2.service` (systemd) + +--- + +## Archivos Modificados + +``` +apps/captain-mobile-v2/ +├── backend/ +│ ├── captain_api_v2.py # Backend reescrito +│ └── captain-api-v2.service # Puerto 3031 +├── flutter/lib/ +│ ├── config/api_config.dart # Puerto 3031 +│ ├── services/chat_service.dart # Nuevos eventos +│ └── providers/chat_provider.dart # Manejo de init, interrupted, etc. +└── ESTADO_PROYECTO.md # Este archivo +``` + +--- + +## Próximos Pasos + +### 1. Instalar servicio systemd (requiere sudo) +```bash +sudo cp captain-api-v2.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable captain-api-v2 +sudo systemctl start captain-api-v2 +``` + +### 2. Compilar APK +```bash +cd /home/architect/captain-claude/apps/captain-mobile-v2/flutter +/home/architect/flutter/bin/flutter build apk --release +``` + +### 3. Subir a Nextcloud +```bash +scp -i ~/.ssh/tzzr build/app/outputs/flutter-apk/app-release.apk \ + root@72.62.1.113:"/var/www/nextcloud/data/tzzrdeck/files/documentos adjuntos/captain-mobile-v2.apk" +ssh -i ~/.ssh/tzzr root@72.62.1.113 \ + "chown www-data:www-data '/var/www/nextcloud/data/tzzrdeck/files/documentos adjuntos/captain-mobile-v2.apk' && \ + cd /var/www/nextcloud && sudo -u www-data php occ files:scan tzzrdeck" +``` + +--- + +## Probar Backend Manualmente + +```bash +# Health check +curl http://localhost:3031/health + +# Login +TOKEN=$(curl -s -X POST http://localhost:3031/auth/login \ + -H "Content-Type: application/json" \ + -d '{"username":"admin","password":"admin"}' | jq -r '.token') + +# Listar conversaciones +curl -H "Authorization: Bearer $TOKEN" http://localhost:3031/conversations +``` + +--- + +## Arquitectura WebSocket (LLMChat pattern) + +``` +┌─────────────────┐ WebSocket ┌─────────────────┐ +│ Flutter Client │ ◄───────────────► │ FastAPI Server │ +│ │ /ws/chat │ │ +└─────────────────┘ └────────┬────────┘ + │ + ┌──────────────────────────────────────┼──────────────────┐ + │ │ │ + ▼ ▼ ▼ + ws_receiver() ws_sender() ChatBuffer + - Recibe JSON - Procesa queue - websocket + - stop → buffer.done.set() - Llama Claude - username + - ping → pong - Stream chunks - queue + - Otros → queue.put() - Guarda en DB - done event +``` + +--- + +## Flujo de Mensajes + +### Conexión +``` +Cliente Servidor + │ │ + │──── {"token": "xxx"} ─────────►│ + │ │ + │◄─── {"type": "init", │ + │ "user": "admin", │ + │ "conversations": [...]} │ +``` + +### Chat +``` +Cliente Servidor + │ │ + │──── {"type": "message", │ + │ "content": "Hola"} ──────►│ + │ │ + │◄─── {"type": "start"} ─────────│ + │◄─── {"type": "thinking"} ──────│ + │◄─── {"type": "delta", ...} ────│ (múltiples) + │◄─── {"type": "done", ...} ─────│ +``` + +### Interrumpir +``` +Cliente Servidor + │ │ + │──── {"type": "stop"} ─────────►│ + │ │ + │◄─── {"type": "interrupted", │ + │ "content": "..."} ────────│ +``` diff --git a/apps/captain-mobile-v2/backend/captain-api-v2.service b/apps/captain-mobile-v2/backend/captain-api-v2.service new file mode 100644 index 0000000..1b556ba --- /dev/null +++ b/apps/captain-mobile-v2/backend/captain-api-v2.service @@ -0,0 +1,17 @@ +[Unit] +Description=Captain Claude Mobile v2 API +After=network.target + +[Service] +Type=simple +User=architect +Group=architect +WorkingDirectory=/home/architect/captain-claude/apps/captain-mobile-v2/backend +Environment="PATH=/home/architect/captain-claude/apps/captain-mobile-v2/backend/venv/bin:/home/architect/.npm-global/bin:/usr/local/bin:/usr/bin:/bin" +# Password from /data/.admin_password (default: admin) +ExecStart=/home/architect/captain-claude/apps/captain-mobile-v2/backend/venv/bin/uvicorn captain_api_v2:app --host 0.0.0.0 --port 3030 +Restart=always +RestartSec=3 + +[Install] +WantedBy=multi-user.target diff --git a/apps/captain-mobile-v2/backend/captain-claude.service b/apps/captain-mobile-v2/backend/captain-claude.service new file mode 100644 index 0000000..1cb9291 --- /dev/null +++ b/apps/captain-mobile-v2/backend/captain-claude.service @@ -0,0 +1,15 @@ +[Unit] +Description=Captain Claude API v3 +After=network.target + +[Service] +Type=simple +User=architect +WorkingDirectory=/home/architect/captain-claude/apps/captain-mobile-v2/backend +Environment=PATH=/home/architect/captain-claude/apps/captain-mobile-v2/backend/venv/bin:/usr/local/bin:/usr/bin:/bin +ExecStart=/home/architect/captain-claude/apps/captain-mobile-v2/backend/venv/bin/uvicorn captain_api_v3:app --host 0.0.0.0 --port 3030 +Restart=always +RestartSec=5 + +[Install] +WantedBy=multi-user.target diff --git a/apps/captain-mobile-v2/backend/captain_api_v2.py b/apps/captain-mobile-v2/backend/captain_api_v2.py new file mode 100644 index 0000000..6e006e1 --- /dev/null +++ b/apps/captain-mobile-v2/backend/captain_api_v2.py @@ -0,0 +1,1127 @@ +#!/usr/bin/env python3 +import sys +import logging + +# Configure logging to stderr (captured by journald) +logging.basicConfig( + level=logging.DEBUG, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[logging.StreamHandler(sys.stderr)] +) +logger = logging.getLogger(__name__) + +""" +Captain Claude Mobile v2 - Backend API +Architecture: SessionManager handles all screen communication +WebSocket clients subscribe to session output via queues +""" + +import os +import asyncio +import secrets +import sqlite3 +import threading +import pty +import select +import fcntl +import subprocess +import re +from datetime import datetime, timedelta +from typing import Optional, Dict, Set +from contextlib import asynccontextmanager +from pathlib import Path +from dataclasses import dataclass, field + +from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends +from fastapi.middleware.cors import CORSMiddleware +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from pydantic import BaseModel +import jwt + +# ============================================================================ +# Configuration +# ============================================================================ + +DATA_DIR = Path("/home/architect/captain-claude/apps/captain-mobile-v2/data") +DB_PATH = DATA_DIR / "captain.db" +CLAUDE_CMD = "/home/architect/.npm-global/bin/claude" +WORKING_DIR = "/home/architect/captain-claude" + +JWT_SECRET_FILE = DATA_DIR / ".jwt_secret" +JWT_ALGORITHM = "HS256" +JWT_EXPIRY_DAYS = 7 + + +def get_jwt_secret(): + DATA_DIR.mkdir(parents=True, exist_ok=True) + if os.environ.get("JWT_SECRET"): + return os.environ.get("JWT_SECRET") + if JWT_SECRET_FILE.exists(): + return JWT_SECRET_FILE.read_text().strip() + secret = secrets.token_hex(32) + JWT_SECRET_FILE.write_text(secret) + JWT_SECRET_FILE.chmod(0o600) + return secret + + +JWT_SECRET = get_jwt_secret() + +ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD") +if not ADMIN_PASSWORD: + _pass_file = DATA_DIR / ".admin_password" + DATA_DIR.mkdir(parents=True, exist_ok=True) + if _pass_file.exists(): + ADMIN_PASSWORD = _pass_file.read_text().strip() + else: + ADMIN_PASSWORD = "admin" + _pass_file.write_text(ADMIN_PASSWORD) + _pass_file.chmod(0o600) + +VALID_USERS = {"admin": ADMIN_PASSWORD} + +ALLOWED_ORIGINS = [ + "http://localhost:3000", + "http://localhost:8080", + "http://127.0.0.1:3000", + "http://127.0.0.1:8080", + "https://captain.tzzrarchitect.me", + "capacitor://localhost", + "ionic://localhost" +] + +security = HTTPBearer(auto_error=False) + +# ============================================================================ +# Pydantic Models +# ============================================================================ + + +class LoginRequest(BaseModel): + username: str + password: str + + +class LoginResponse(BaseModel): + token: str + expires_at: str + + +class ScreenSession(BaseModel): + name: str # Short name (e.g., "captain") + pid: str # Process ID (e.g., "400970") + full_name: str # Full name for commands (e.g., "400970.captain") + attached: bool + + +class CreateSessionRequest(BaseModel): + name: str + + +# ============================================================================ +# Database +# ============================================================================ + +_local = threading.local() + + +def get_db() -> sqlite3.Connection: + if not hasattr(_local, 'conn'): + _local.conn = sqlite3.connect(str(DB_PATH), check_same_thread=False) + _local.conn.row_factory = sqlite3.Row + return _local.conn + + +def init_db(): + DATA_DIR.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(str(DB_PATH)) + conn.execute(''' + CREATE TABLE IF NOT EXISTS conversations ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + session_name TEXT, + title TEXT, + created_at TEXT DEFAULT CURRENT_TIMESTAMP, + updated_at TEXT DEFAULT CURRENT_TIMESTAMP + ) + ''') + conn.execute(''' + CREATE TABLE IF NOT EXISTS messages ( + id TEXT PRIMARY KEY, + conversation_id TEXT REFERENCES conversations(id) ON DELETE CASCADE, + role TEXT NOT NULL, + content TEXT NOT NULL, + created_at TEXT DEFAULT CURRENT_TIMESTAMP + ) + ''') + conn.commit() + conn.close() + print(f"Database initialized at {DB_PATH}") + + +# ============================================================================ +# Auth Helpers +# ============================================================================ + + +def create_token(username: str) -> tuple[str, datetime]: + expires = datetime.utcnow() + timedelta(days=JWT_EXPIRY_DAYS) + payload = { + "sub": username, + "exp": expires, + "iat": datetime.utcnow() + } + token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM) + return token, expires + + +def verify_token(token: str) -> Optional[str]: + try: + payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM]) + return payload.get("sub") + except jwt.ExpiredSignatureError: + return None + except jwt.InvalidTokenError: + return None + + +async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str: + if not credentials: + raise HTTPException(status_code=401, detail="Not authenticated") + username = verify_token(credentials.credentials) + if not username: + raise HTTPException(status_code=401, detail="Invalid or expired token") + return username + + +# ============================================================================ +# Screen Session Utilities +# ============================================================================ + + +def list_screen_sessions() -> list[ScreenSession]: + """List active screen sessions""" + try: + result = subprocess.run(["screen", "-ls"], capture_output=True, text=True) + sessions = [] + for line in result.stdout.split("\n"): + if "\t" in line and ("Attached" in line or "Detached" in line): + parts = line.strip().split("\t") + if len(parts) >= 2: + session_info = parts[0] # e.g., "400970.captain" + pid_name = session_info.split(".") + if len(pid_name) >= 2: + sessions.append(ScreenSession( + pid=pid_name[0], + name=".".join(pid_name[1:]), + full_name=session_info, # Use this for all commands + attached="Attached" in line + )) + return sessions + except Exception: + return [] + + +def get_full_session_name(session_name: str) -> Optional[str]: + """Get full session name (PID.name) from short name""" + result = subprocess.run(["screen", "-ls"], capture_output=True, text=True) + for line in result.stdout.split("\n"): + if f".{session_name}" in line and ("\t" in line): + parts = line.strip().split("\t")[0] + return parts + return None + + +def create_screen_session(name: str) -> ScreenSession: + """Create a new screen session with Claude""" + clean_name = re.sub(r'[^a-z0-9_-]', '', name.replace(" ", "-").lower()) + if not clean_name or len(clean_name) < 2 or len(clean_name) > 50: + raise ValueError("Invalid session name (2-50 chars, alphanumeric, hyphens, underscores)") + + result = subprocess.run(["screen", "-ls"], capture_output=True, text=True) + if f".{clean_name}" in result.stdout: + raise ValueError(f"Session '{clean_name}' already exists") + + subprocess.run( + ["screen", "-dmS", clean_name, CLAUDE_CMD, "--dangerously-skip-permissions"], + cwd=WORKING_DIR, + check=True + ) + + import time + time.sleep(1) + + result = subprocess.run(["screen", "-ls"], capture_output=True, text=True) + for line in result.stdout.split("\n"): + if f".{clean_name}" in line: + full_name = line.strip().split("\t")[0] # e.g., "400970.captain" + parts = full_name.split(".") + if len(parts) >= 2: + return ScreenSession( + pid=parts[0], + name=clean_name, + full_name=full_name, + attached=False + ) + + raise ValueError("Session created but could not find PID") + + +def strip_ansi(text: str) -> str: + """Remove ANSI escape codes from text""" + ansi_pattern = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') + return ansi_pattern.sub('', text) + + +# ============================================================================ +# Session Manager - Central coordinator for screen sessions +# ============================================================================ + + +@dataclass +class ManagedSession: + """Represents a managed connection to a screen session""" + session_name: str + full_name: str + master_fd: int = -1 + process: Optional[subprocess.Popen] = None + subscribers: Set[asyncio.Queue] = field(default_factory=set) + subscribers_lock: asyncio.Lock = field(default_factory=asyncio.Lock) # Protect subscribers set + reader_task: Optional[asyncio.Task] = None + is_running: bool = False + output_buffer: str = "" + last_content: str = "" # For polling-based change detection + + +class SessionManager: + """ + Centralized manager for screen session connections. + + - Maintains ONE reader per session (not per client) + - Clients subscribe to session output via queues + - Input is sent via screen -X stuff (reliable) + """ + + def __init__(self): + self._sessions: Dict[str, ManagedSession] = {} + self._lock = asyncio.Lock() + + async def subscribe(self, full_name: str) -> asyncio.Queue: + """ + Subscribe to a session's output using full_name (PID.name). + Returns queue or raises ValueError. + """ + logger.debug(f"subscribe: called with full_name={full_name}") + async with self._lock: + # Validate full_name exists + result = subprocess.run(["screen", "-ls"], capture_output=True, text=True) + logger.debug(f"subscribe: screen -ls output contains '{full_name}': {full_name in result.stdout}") + if full_name not in result.stdout: + raise ValueError(f"Session '{full_name}' not found") + + # Get or create managed session (keyed by full_name) + if full_name not in self._sessions: + managed = ManagedSession( + session_name=full_name.split(".", 1)[1] if "." in full_name else full_name, + full_name=full_name + ) + self._sessions[full_name] = managed + # Start the reader + await self._start_reader(managed) + + managed = self._sessions[full_name] + + # Create subscriber queue with lock protection + queue: asyncio.Queue = asyncio.Queue(maxsize=100) + async with managed.subscribers_lock: + managed.subscribers.add(queue) + logger.info(f"subscribe: added queue, now {len(managed.subscribers)} subscribers for {full_name}") + + return queue + + async def unsubscribe(self, full_name: str, queue: asyncio.Queue): + """Unsubscribe from a session's output""" + async with self._lock: + if full_name in self._sessions: + managed = self._sessions[full_name] + async with managed.subscribers_lock: + managed.subscribers.discard(queue) + remaining = len(managed.subscribers) + logger.info(f"unsubscribe: removed queue, {remaining} subscribers remaining for {full_name}") + + # If no more subscribers, stop the reader + if remaining == 0: + await self._stop_reader(managed) + del self._sessions[full_name] + + async def send_input(self, full_name: str, content: str) -> bool: + """ + Send input to a session. + CRITICAL: ESC and Enter must be sent SEPARATELY with delays. + """ + try: + # Use screen -X stuff with SEPARATE commands for ESC and Enter + # This is the ONLY method that works reliably with Claude Code TUI + + logger.debug(f"send_input: full_name={full_name}, content={content[:50]}") + + # Step 1: Clear any pending input with Ctrl+C + cmd1 = ["screen", "-S", full_name, "-p", "0", "-X", "stuff", "\x03"] + subprocess.run(cmd1, capture_output=True, timeout=2) + await asyncio.sleep(0.3) + + # Step 2: Send the message content + cmd2 = ["screen", "-S", full_name, "-p", "0", "-X", "stuff", content] + result2 = subprocess.run(cmd2, capture_output=True, timeout=2) + if result2.returncode != 0: + logger.error(f"send_input: failed to send content, rc={result2.returncode}") + return False + await asyncio.sleep(0.3) + + # Step 3: Send ESC separately (CRITICAL - must be separate!) + cmd3 = ["screen", "-S", full_name, "-p", "0", "-X", "stuff", "\x1b"] + result3 = subprocess.run(cmd3, capture_output=True, timeout=2) + if result3.returncode != 0: + logger.error(f"send_input: failed to send ESC, rc={result3.returncode}") + return False + await asyncio.sleep(0.2) + + # Step 4: Send Enter separately (CRITICAL - must be separate!) + cmd4 = ["screen", "-S", full_name, "-p", "0", "-X", "stuff", "\r"] + result4 = subprocess.run(cmd4, capture_output=True, timeout=2) + if result4.returncode != 0: + logger.error(f"send_input: failed to send Enter, rc={result4.returncode}") + return False + + logger.info(f"send_input: message sent successfully to {full_name}") + return True + + except Exception as e: + logger.error(f"Error sending to {full_name}: {e}") + return False + + async def _start_reader(self, managed: ManagedSession): + """Start reading output from a screen session using PTY + hardcopy polling""" + if managed.is_running: + return + + try: + # Create PTY for bidirectional communication + master_fd, slave_fd = pty.openpty() + + env = os.environ.copy() + env["TERM"] = "xterm-256color" + + # Attach to screen session for reading/writing + process = subprocess.Popen( + ["screen", "-x", managed.full_name], + stdin=slave_fd, + stdout=slave_fd, + stderr=slave_fd, + preexec_fn=os.setsid, + env=env + ) + + os.close(slave_fd) + + # Set non-blocking for reads + flags = fcntl.fcntl(master_fd, fcntl.F_GETFL) + fcntl.fcntl(master_fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) + + managed.master_fd = master_fd + managed.process = process + managed.is_running = True + managed.last_content = "" + + logger.debug(f"_start_reader: PTY established, fd={master_fd}, screen PID={process.pid}") + + # Start reader task - uses hardcopy polling with UI filtering + managed.reader_task = asyncio.create_task( + self._reader_loop_polling(managed) + ) + + logger.info(f"Started reader for session: {managed.session_name}") + + except Exception as e: + logger.error(f"Error starting reader for {managed.session_name}: {e}") + managed.is_running = False + + async def _stop_reader(self, managed: ManagedSession): + """Stop reading from a session""" + managed.is_running = False + + if managed.reader_task: + managed.reader_task.cancel() + try: + await managed.reader_task + except asyncio.CancelledError: + pass + managed.reader_task = None + + if managed.master_fd >= 0: + try: + os.close(managed.master_fd) + except: + pass + managed.master_fd = -1 + + if managed.process: + try: + managed.process.terminate() + managed.process.wait(timeout=2) + except: + try: + managed.process.kill() + except: + pass + managed.process = None + + logger.info(f"Stopped reader for session: {managed.session_name}") + + async def _reader_loop(self, managed: ManagedSession): + """Read output from PTY and broadcast to subscribers""" + logger.debug(f"_reader_loop: STARTED for {managed.full_name}") + buffer = "" + last_broadcast = asyncio.get_event_loop().time() + + while managed.is_running: + try: + await asyncio.sleep(0.05) + + if managed.master_fd < 0: + break + + # Check for data + r, _, _ = select.select([managed.master_fd], [], [], 0) + if r: + try: + data = os.read(managed.master_fd, 4096) + if data: + text = data.decode("utf-8", errors="replace") + text = strip_ansi(text) + buffer += text + logger.debug(f"_reader_loop: read {len(data)} bytes, buffer now {len(buffer)}") + except OSError as e: + logger.debug(f"_reader_loop: OSError reading: {e}") + break + + # Broadcast buffer periodically + now = asyncio.get_event_loop().time() + if buffer and (now - last_broadcast > 0.1): + await self._broadcast(managed, buffer) + buffer = "" + last_broadcast = now + + # Also broadcast if buffer is getting large + if len(buffer) > 1000: + await self._broadcast(managed, buffer) + buffer = "" + last_broadcast = asyncio.get_event_loop().time() + + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Reader error for {managed.session_name}: {e}") + await asyncio.sleep(1) + + # Final flush + if buffer: + await self._broadcast(managed, buffer) + + async def _reader_loop_hybrid(self, managed: ManagedSession): + """ + Hybrid reader: uses PTY for real-time reads + hardcopy for UI state. + PTY reads give us streaming output, hardcopy helps verify state. + """ + logger.debug(f"_reader_loop_hybrid: STARTED for {managed.full_name}") + + buffer = "" + last_broadcast = asyncio.get_event_loop().time() + tmp_file = f"/tmp/screen_hc_{managed.full_name.replace('.', '_')}.txt" + + while managed.is_running: + try: + await asyncio.sleep(0.05) # 50ms for responsiveness + + if managed.master_fd < 0: + break + + # Try to read from PTY (non-blocking) + r, _, _ = select.select([managed.master_fd], [], [], 0) + if r: + try: + data = os.read(managed.master_fd, 8192) + if data: + text = data.decode("utf-8", errors="replace") + text = strip_ansi(text) + buffer += text + logger.debug(f"_reader_loop_hybrid: PTY read {len(data)} bytes") + except OSError as e: + if e.errno not in (11, 35): # EAGAIN/EWOULDBLOCK + logger.error(f"_reader_loop_hybrid: PTY read error: {e}") + break + + # Broadcast buffer periodically + now = asyncio.get_event_loop().time() + if buffer and (now - last_broadcast > 0.15): + await self._broadcast(managed, buffer) + buffer = "" + last_broadcast = now + + # Broadcast large buffers immediately + if len(buffer) > 2000: + await self._broadcast(managed, buffer) + buffer = "" + last_broadcast = asyncio.get_event_loop().time() + + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Hybrid reader error for {managed.session_name}: {e}") + await asyncio.sleep(1) + + # Final flush + if buffer: + await self._broadcast(managed, buffer) + + # Cleanup temp file + try: + os.remove(tmp_file) + except: + pass + + logger.debug(f"_reader_loop_hybrid: STOPPED for {managed.full_name}") + + async def _broadcast(self, managed: ManagedSession, content: str): + """Broadcast content to all subscribers""" + # Get a snapshot of subscribers under lock + async with managed.subscribers_lock: + subscribers_snapshot = list(managed.subscribers) + num_subscribers = len(subscribers_snapshot) + + logger.debug(f"_broadcast: {managed.full_name} -> {num_subscribers} subscribers, {len(content)} chars") + + if num_subscribers == 0: + logger.warning(f"_broadcast: NO SUBSCRIBERS for {managed.full_name}") + return + + dead_queues = [] + + for queue in subscribers_snapshot: + try: + queue.put_nowait(content) + except asyncio.QueueFull: + # Drop oldest message and try again + try: + queue.get_nowait() + queue.put_nowait(content) + except: + pass + except Exception: + dead_queues.append(queue) + + # Clean up dead queues under lock + if dead_queues: + async with managed.subscribers_lock: + for q in dead_queues: + managed.subscribers.discard(q) + + async def _reader_loop_polling(self, managed: ManagedSession): + """ + Read output from screen session using hardcopy polling. + + Strategy: Track the last seen content and detect incremental changes. + - hardcopy captures the visible screen (last N lines) + - Claude output appears at the bottom and scrolls up + - We detect new lines at the end by comparing with previous content + """ + logger.debug(f"_reader_loop_polling: STARTED for {managed.full_name}") + + # Create temp file for hardcopy output + tmp_file = f"/tmp/screen_hc_{managed.full_name.replace('.', '_')}.txt" + poll_interval = 0.25 # 250ms polling for responsiveness + + # Track last content for incremental detection + last_lines: list = [] + last_content_hash = "" + + # UI filter patterns - Claude Code interface elements + UI_PATTERNS = [ + # Permissions and controls + 'bypass permissions', 'ctrl+', 'shift+tab', 'Esc to', 'to cycle', + 'on (shift+tab', 'to interrupt', 'press ctrl', 'again to exit', + 'What should Claude do', 'Interrupted', + # Claude Code branding/header + 'Claude Code', 'Claude Max', 'Opus 4', 'Sonnet', 'claude-', + '~/captain-claude', '/home/architect', # Working directory display + # Box-drawing characters + '───', '═══', '│', '┌', '└', '├', '┐', '┘', '┤', '╭', '╮', '╯', '╰', + '║', '╔', '╗', '╚', '╝', '╠', '╣', '╦', '╩', '╬', + # Block characters + '▐', '▛', '▜', '▌', '▝', '█', '▀', '▄', '▖', '▗', '▘', '▙', '▚', '▞', '▟', + '░', '▒', '▓', '■', '□', + # Spinners + '◐', '◑', '◒', '◓', '⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏', + # UI elements + '❯', '●', '○', '◆', '◇', '✓', '✗', '→', '←', '↑', '↓', + # Status indicators + 'Baking', 'Thinking', 'Working', 'Loading', + # Tool usage indicators + '� Bash', '� Read', '� Edit', '� Write', '� Glob', '� Grep', + ] + + def clean_line(line: str) -> str: + """Remove broken unicode characters (replacement chars, emojis that don't render)""" + # Remove replacement character and common broken emoji patterns + cleaned = line.replace('�', '').replace('\ufffd', '') + # Remove zero-width characters + cleaned = ''.join(c for c in cleaned if ord(c) >= 32 or c in '\n\t') + return cleaned.strip() + + def is_ui_line(line: str) -> bool: + """Check if line is a Claude Code UI element""" + stripped = line.strip() + + # Empty or very short + if len(stripped) <= 2: + return True + + # Lines starting with 'o ' are user prompts in Claude Code + if stripped.startswith('o '): + return True + + # Lines containing UI patterns + for pattern in UI_PATTERNS: + if pattern in line: + return True + + # Lines that are mostly special characters (box drawing, etc) + special_chars = set('─═│┌└├┐┘┤╭╮╯╰║╔╗╚╝╠╣╦╩╬▐▛▜▌▝█▀▄░▒▓●○◆◇✓✗→←↑↓❯ \t') + if all(c in special_chars for c in stripped): + return True + + return False + + def extract_claude_response(lines: list) -> str: + """ + Extract only Claude's actual response text. + Claude responses typically start with a special marker or are plain text. + """ + result = [] + for line in lines: + cleaned = clean_line(line) + if not cleaned: + continue + if is_ui_line(cleaned): + continue + # Skip lines that are just the user's input echoed back + if cleaned.startswith('responde') or cleaned.startswith('di ') or cleaned.startswith('hola'): + continue + result.append(cleaned) + return '\n'.join(result) + + # Track bash commands for progress indicator + bash_count = [0] # Use list to allow modification in nested function + + def is_bash_line(line: str) -> bool: + """Check if line is a Bash command or its output""" + # Bash tool indicators + bash_patterns = [ + 'Bash(', 'bash(', '$ ', '# ', # Command invocations + 'Exit code', 'exit code', # Exit status + '+ ', '++ ', # Shell trace output + ] + for p in bash_patterns: + if p in line: + return True + # Lines that look like terminal output (start with common command output) + if line.startswith(('total ', 'drwx', '-rw', 'lrwx')): # ls output + return True + return False + + def filter_content_lines(raw_lines: list) -> list: + """Filter out UI lines, convert Bash to progress indicator""" + result = [] + bash_in_this_batch = 0 + + for line in raw_lines: + cleaned = clean_line(line) + if not cleaned: + continue + if is_ui_line(cleaned): + continue + + # Convert Bash lines to progress dots + if is_bash_line(cleaned): + bash_in_this_batch += 1 + continue # Don't add bash lines directly + + result.append(cleaned) + + # If we had bash commands, add a progress indicator + if bash_in_this_batch > 0: + dots = ' .' * min(bash_in_this_batch, 10) # Max 10 dots + result.insert(0, f"procesando{dots}") + bash_count[0] += bash_in_this_batch + + return result + + def find_overlap(old_lines: list, new_lines: list) -> int: + """ + Find where old_lines ends in new_lines (overlap point). + Returns index in new_lines where new content starts. + If no overlap found, returns 0 (treat all as new). + """ + if not old_lines or not new_lines: + return 0 + + # Look for the last few lines of old content in new content + # This handles scrolling - old content moves up, new appears at bottom + search_window = min(len(old_lines), 10) # Check last 10 lines + + for i in range(search_window, 0, -1): + old_tail = old_lines[-i:] + + # Search for this tail in new_lines + for j in range(len(new_lines) - i + 1): + if new_lines[j:j+i] == old_tail: + # Found overlap - new content starts after this + new_start = j + i + if new_start < len(new_lines): + return new_start + else: + return len(new_lines) # No new content + + return 0 # No overlap found - all content is new + + while managed.is_running: + try: + await asyncio.sleep(poll_interval) + + # Get current screen content via hardcopy (-p 0 selects window 0) + cmd = ["screen", "-S", managed.full_name, "-p", "0", "-X", "hardcopy", tmp_file] + result = subprocess.run(cmd, capture_output=True, timeout=2) + + if result.returncode != 0: + continue + + # Read the hardcopy file + try: + with open(tmp_file, 'r', errors='replace') as f: + raw_content = f.read() + except FileNotFoundError: + continue + + # Process and filter lines + raw_lines = raw_content.split('\n') + current_lines = filter_content_lines(raw_lines) + + # Quick hash check - skip if nothing changed + content_hash = hash(tuple(current_lines)) + if content_hash == last_content_hash: + continue + last_content_hash = content_hash + + # First poll - don't send initial content (it's usually just UI) + # We only want to send NEW responses after the user sends a message + if not last_lines: + logger.debug(f"_reader_loop_polling: initial poll, {len(current_lines)} lines tracked") + last_lines = current_lines.copy() + continue + + # Detect if this is a screen refresh (completely different content) + # vs incremental output (new lines at the end) + overlap_start = find_overlap(last_lines, current_lines) + + if overlap_start == 0 and last_lines: + # Check if content is completely different (screen refresh) + # Compare first few lines - if different, it's a refresh + compare_len = min(3, len(last_lines), len(current_lines)) + if compare_len > 0 and last_lines[:compare_len] != current_lines[:compare_len]: + # Screen refresh - just update tracking, don't send everything + # Only send if there's meaningful new content at the end + logger.debug(f"_reader_loop_polling: screen refresh detected, skipping") + last_lines = current_lines.copy() + continue + + # Get new lines (incremental output) + new_lines = current_lines[overlap_start:] if overlap_start < len(current_lines) else [] + + # Filter out any lines that are duplicates of very recent content + # (handles edge case of partial overlap detection) + if new_lines and last_lines: + # Remove lines that appear in the last 5 lines of previous content + recent_set = set(last_lines[-5:]) + new_lines = [l for l in new_lines if l not in recent_set] + + # Broadcast new lines + if new_lines: + new_content = '\n'.join(new_lines) + logger.debug(f"_reader_loop_polling: {len(new_lines)} new lines at end") + await self._broadcast(managed, new_content) + + # Update tracking + last_lines = current_lines.copy() + + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Polling error for {managed.session_name}: {e}") + await asyncio.sleep(1) + + # Cleanup temp file + try: + os.remove(tmp_file) + except: + pass + + logger.debug(f"_reader_loop_polling: STOPPED for {managed.full_name}") + + async def cleanup(self): + """Stop all sessions""" + async with self._lock: + for managed in list(self._sessions.values()): + await self._stop_reader(managed) + self._sessions.clear() + + +# Global session manager +session_manager = SessionManager() + + +# ============================================================================ +# App Setup +# ============================================================================ + + +@asynccontextmanager +async def lifespan(app: FastAPI): + init_db() + yield + await session_manager.cleanup() + + +app = FastAPI( + title="Captain Claude Mobile v2", + description="Chat API with centralized session management", + version="2.3.0", + lifespan=lifespan +) + +app.add_middleware( + CORSMiddleware, + allow_origins=ALLOWED_ORIGINS, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + +# ============================================================================ +# REST Endpoints +# ============================================================================ + + +@app.get("/health") +async def health(): + return {"status": "ok", "version": "2.3.0"} + + +@app.post("/auth/login", response_model=LoginResponse) +async def login(request: LoginRequest): + if request.username not in VALID_USERS: + raise HTTPException(status_code=401, detail="Invalid credentials") + if VALID_USERS[request.username] != request.password: + raise HTTPException(status_code=401, detail="Invalid credentials") + + token, expires = create_token(request.username) + return LoginResponse(token=token, expires_at=expires.isoformat()) + + +@app.get("/sessions", response_model=list[ScreenSession]) +async def get_sessions(user: str = Depends(get_current_user)): + return list_screen_sessions() + + +@app.post("/sessions", response_model=ScreenSession) +async def create_session(request: CreateSessionRequest, user: str = Depends(get_current_user)): + try: + return create_screen_session(request.name) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +# ============================================================================ +# WebSocket Chat +# ============================================================================ + + +@app.websocket("/ws/chat") +async def websocket_chat(websocket: WebSocket): + """WebSocket endpoint for chat""" + await websocket.accept() + + # Auth handshake + try: + auth_msg = await asyncio.wait_for(websocket.receive_json(), timeout=10.0) + token = auth_msg.get("token", "") + username = verify_token(token) + if not username: + await websocket.send_json({"type": "error", "message": "Invalid token"}) + await websocket.close(code=4001) + return + except asyncio.TimeoutError: + await websocket.send_json({"type": "error", "message": "Auth timeout"}) + await websocket.close(code=4001) + return + except Exception as e: + await websocket.send_json({"type": "error", "message": f"Auth error: {str(e)}"}) + await websocket.close(code=4001) + return + + # Send init - include full_name for unique identification + sessions = list_screen_sessions() + await websocket.send_json({ + "type": "init", + "user": username, + "sessions": [{"name": s.name, "pid": s.pid, "full_name": s.full_name, "attached": s.attached} for s in sessions] + }) + + # Current subscription state - use full_name as key + current_full_name: Optional[str] = None + current_queue: Optional[asyncio.Queue] = None + output_task: Optional[asyncio.Task] = None + + async def output_forwarder(queue: asyncio.Queue): + """Forward output from queue to websocket""" + logger.debug("output_forwarder: STARTED") + while True: + try: + content = await queue.get() + logger.debug(f"output_forwarder: sending {len(content)} chars to websocket") + await websocket.send_json({ + "type": "output", + "content": content + }) + logger.debug("output_forwarder: sent OK") + except asyncio.CancelledError: + logger.debug("output_forwarder: cancelled") + break + except Exception as e: + logger.error(f"output_forwarder: error {e}") + break + + try: + while True: + data = await websocket.receive_json() + msg_type = data.get("type", "") + + if msg_type == "connect_session": + # Accept full_name (PID.name) for unique session identification + full_name = data.get("full_name") or data.get("session_name", "") + + # Validate format: either "PID.name" or just "name" + if not re.match(r'^[0-9]+\.[a-z0-9_-]+$|^[a-z0-9_-]+$', full_name): + await websocket.send_json({"type": "error", "message": "Invalid session name"}) + continue + + # If short name provided, try to resolve it (backward compat) + if "." not in full_name: + resolved = get_full_session_name(full_name) + if not resolved: + await websocket.send_json({"type": "error", "message": f"Session '{full_name}' not found"}) + continue + full_name = resolved + + # Unsubscribe from previous session + if current_full_name and current_queue: + if output_task: + output_task.cancel() + try: + await output_task + except asyncio.CancelledError: + pass + await session_manager.unsubscribe(current_full_name, current_queue) + + # Subscribe to new session + try: + current_queue = await session_manager.subscribe(full_name) + current_full_name = full_name + + # Start output forwarder + output_task = asyncio.create_task(output_forwarder(current_queue)) + + await websocket.send_json({ + "type": "session_connected", + "session_name": full_name.split(".", 1)[1] if "." in full_name else full_name, + "full_name": full_name + }) + except ValueError as e: + await websocket.send_json({"type": "error", "message": str(e)}) + current_full_name = None + current_queue = None + + elif msg_type == "create_session": + session_name = data.get("session_name", "") + try: + new_session = create_screen_session(session_name) + await websocket.send_json({ + "type": "session_created", + "session": { + "name": new_session.name, + "pid": new_session.pid, + "full_name": new_session.full_name, + "attached": new_session.attached + } + }) + except ValueError as e: + await websocket.send_json({"type": "error", "message": str(e)}) + + elif msg_type == "message": + content = data.get("content", "") + logger.debug(f"message: current_full_name={current_full_name}, content={content[:30] if content else 'empty'}") + if current_full_name and content: + success = await session_manager.send_input(current_full_name, content) + if not success: + await websocket.send_json({ + "type": "error", + "message": "Failed to send message to session" + }) + + elif msg_type == "list_sessions": + sessions = list_screen_sessions() + await websocket.send_json({ + "type": "sessions_list", + "sessions": [{"name": s.name, "pid": s.pid, "full_name": s.full_name, "attached": s.attached} for s in sessions] + }) + + elif msg_type == "ping": + await websocket.send_json({"type": "pong"}) + + except WebSocketDisconnect: + pass + except Exception as e: + try: + await websocket.send_json({"type": "error", "message": str(e)}) + except: + pass + finally: + # Cleanup + if output_task: + output_task.cancel() + try: + await output_task + except asyncio.CancelledError: + pass + if current_full_name and current_queue: + await session_manager.unsubscribe(current_full_name, current_queue) + + +# ============================================================================ +# Main +# ============================================================================ + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=3030) diff --git a/apps/captain-mobile-v2/backend/captain_api_v3.py b/apps/captain-mobile-v2/backend/captain_api_v3.py new file mode 100644 index 0000000..eee5402 --- /dev/null +++ b/apps/captain-mobile-v2/backend/captain_api_v3.py @@ -0,0 +1,620 @@ +#!/usr/bin/env python3 +""" +Captain Claude Mobile v3 - Backend API +Architecture: Uses claude CLI with --output-format stream-json +No more screen/hardcopy bullshit - clean JSON output +""" + +import sys +import logging +import os +import asyncio +import secrets +import subprocess +import json +import re +from datetime import datetime, timedelta +from typing import Optional, Dict, Set +from contextlib import asynccontextmanager +from pathlib import Path +from dataclasses import dataclass, field + +from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends +from fastapi.middleware.cors import CORSMiddleware +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from pydantic import BaseModel +import jwt + +# Configure logging +logging.basicConfig( + level=logging.DEBUG, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[logging.StreamHandler(sys.stderr)] +) +logger = logging.getLogger(__name__) + +# ============================================================================ +# Configuration +# ============================================================================ + +DATA_DIR = Path("/home/architect/captain-claude/apps/captain-mobile-v2/data") +CLAUDE_CMD = "/home/architect/.npm-global/bin/claude" +WORKING_DIR = "/home/architect/captain-claude" + +JWT_SECRET_FILE = DATA_DIR / ".jwt_secret" +JWT_ALGORITHM = "HS256" +JWT_EXPIRY_DAYS = 7 + + +def get_jwt_secret(): + DATA_DIR.mkdir(parents=True, exist_ok=True) + if os.environ.get("JWT_SECRET"): + return os.environ.get("JWT_SECRET") + if JWT_SECRET_FILE.exists(): + return JWT_SECRET_FILE.read_text().strip() + secret = secrets.token_hex(32) + JWT_SECRET_FILE.write_text(secret) + JWT_SECRET_FILE.chmod(0o600) + return secret + + +JWT_SECRET = get_jwt_secret() + +ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD") +if not ADMIN_PASSWORD: + _pass_file = DATA_DIR / ".admin_password" + DATA_DIR.mkdir(parents=True, exist_ok=True) + if _pass_file.exists(): + ADMIN_PASSWORD = _pass_file.read_text().strip() + else: + ADMIN_PASSWORD = "admin" + _pass_file.write_text(ADMIN_PASSWORD) + _pass_file.chmod(0o600) + +VALID_USERS = {"admin": ADMIN_PASSWORD} + +ALLOWED_ORIGINS = [ + "http://localhost:3000", + "http://localhost:8080", + "http://127.0.0.1:3000", + "http://127.0.0.1:8080", + "https://captain.tzzrarchitect.me", + "capacitor://localhost", + "ionic://localhost" +] + +security = HTTPBearer(auto_error=False) + +# ============================================================================ +# Pydantic Models +# ============================================================================ + + +class LoginRequest(BaseModel): + username: str + password: str + + +class LoginResponse(BaseModel): + token: str + expires_at: str + + +class SessionInfo(BaseModel): + session_id: str + name: str + created_at: str + + +class CreateSessionRequest(BaseModel): + name: str + + +# ============================================================================ +# Auth Helpers +# ============================================================================ + + +def create_token(username: str) -> tuple[str, datetime]: + expires = datetime.utcnow() + timedelta(days=JWT_EXPIRY_DAYS) + payload = { + "sub": username, + "exp": expires, + "iat": datetime.utcnow() + } + token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM) + return token, expires + + +def verify_token(token: str) -> Optional[str]: + try: + payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM]) + return payload.get("sub") + except jwt.ExpiredSignatureError: + return None + except jwt.InvalidTokenError: + return None + + +async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str: + if not credentials: + raise HTTPException(status_code=401, detail="Not authenticated") + username = verify_token(credentials.credentials) + if not username: + raise HTTPException(status_code=401, detail="Invalid or expired token") + return username + + +# ============================================================================ +# Claude Session Manager +# ============================================================================ + + +@dataclass +class ClaudeSession: + """Represents a Claude conversation session""" + session_id: str # Claude's session UUID + name: str # User-friendly name + created_at: datetime + subscribers: Set[asyncio.Queue] = field(default_factory=set) + lock: asyncio.Lock = field(default_factory=asyncio.Lock) + is_processing: bool = False + + +class SessionManager: + """ + Manages Claude CLI sessions using -p mode with stream-json output. + Each session maintains conversation history via Claude's session_id. + """ + + def __init__(self): + self._sessions: Dict[str, ClaudeSession] = {} + self._lock = asyncio.Lock() + + async def create_session(self, name: str) -> ClaudeSession: + """Create a new Claude session""" + # Generate initial session by making a simple call + session_id = secrets.token_hex(16) # We'll get real session_id from first call + + session = ClaudeSession( + session_id=session_id, + name=name, + created_at=datetime.utcnow() + ) + + async with self._lock: + self._sessions[session_id] = session + + logger.info(f"Created session: {name} ({session_id})") + return session + + async def get_session(self, session_id: str) -> Optional[ClaudeSession]: + """Get a session by ID""" + return self._sessions.get(session_id) + + async def list_sessions(self) -> list[SessionInfo]: + """List all sessions""" + return [ + SessionInfo( + session_id=s.session_id, + name=s.name, + created_at=s.created_at.isoformat() + ) + for s in self._sessions.values() + ] + + async def subscribe(self, session_id: str) -> asyncio.Queue: + """Subscribe to a session's output""" + session = self._sessions.get(session_id) + if not session: + raise ValueError(f"Session {session_id} not found") + + queue: asyncio.Queue = asyncio.Queue(maxsize=100) + async with session.lock: + session.subscribers.add(queue) + + logger.debug(f"Subscribed to session {session_id}, {len(session.subscribers)} subscribers") + return queue + + async def unsubscribe(self, session_id: str, queue: asyncio.Queue): + """Unsubscribe from a session's output""" + session = self._sessions.get(session_id) + if session: + async with session.lock: + session.subscribers.discard(queue) + logger.debug(f"Unsubscribed from session {session_id}") + + async def send_message(self, session_id: str, content: str) -> bool: + """ + Send a message to Claude and stream the response. + Uses claude -p with stream-json for clean output. + """ + session = self._sessions.get(session_id) + if not session: + logger.error(f"Session {session_id} not found") + return False + + if session.is_processing: + logger.warning(f"Session {session_id} is already processing") + await self._broadcast(session, {"type": "error", "content": "Ya hay un mensaje en proceso"}) + return False + + session.is_processing = True + + try: + # Build command + cmd = [ + CLAUDE_CMD, + "-p", content, + "--output-format", "stream-json", + "--verbose", + "--dangerously-skip-permissions" + ] + + # If we have a Claude session UUID, resume it to maintain conversation + # Claude UUIDs are in format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (36 chars with dashes) + if session.session_id and '-' in session.session_id and len(session.session_id) == 36: + cmd.extend(["--resume", session.session_id]) + logger.debug(f"Resuming Claude session: {session.session_id}") + + logger.debug(f"Executing: {' '.join(cmd)}") + + # Run claude process + process = await asyncio.create_subprocess_exec( + *cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + cwd=WORKING_DIR + ) + + # Process output as it arrives + full_response = "" + tool_count = 0 + + try: + while True: + # Read line with timeout to avoid hanging + try: + line = await asyncio.wait_for( + process.stdout.readline(), + timeout=60.0 + ) + except asyncio.TimeoutError: + logger.warning("Timeout reading from Claude process") + break + + if not line: + break + + line_str = line.decode('utf-8').strip() + if not line_str: + continue + + logger.debug(f"Claude output: {line_str[:100]}...") + + try: + data = json.loads(line_str) + msg_type = data.get("type", "") + + if msg_type == "assistant": + message = data.get("message", {}) + content_list = message.get("content", []) + for item in content_list: + if item.get("type") == "text": + text = item.get("text", "") + if text: + full_response = text + # Send immediately! + await self._broadcast(session, { + "type": "output", + "content": text + }) + elif item.get("type") == "tool_use": + tool_count += 1 + await self._broadcast(session, { + "type": "output", + "content": f"procesando{'.' * tool_count}" + }) + + elif msg_type == "result": + result = data.get("result", "") + claude_session = data.get("session_id") + if claude_session: + session.session_id = claude_session + + # Send done signal + await self._broadcast(session, { + "type": "done", + "session_id": session.session_id + }) + + except json.JSONDecodeError: + pass + except Exception as e: + logger.error(f"Error processing line: {e}") + + finally: + # Ensure process is cleaned up + try: + process.terminate() + await asyncio.wait_for(process.wait(), timeout=5.0) + except: + process.kill() + + return True + + except Exception as e: + logger.error(f"Error sending message: {e}") + if str(e): # Only broadcast if there's an actual error message + await self._broadcast(session, { + "type": "error", + "content": str(e) + }) + return False + finally: + session.is_processing = False + + async def _broadcast(self, session: ClaudeSession, message: dict): + """Broadcast message to all subscribers""" + async with session.lock: + subscribers = list(session.subscribers) + + logger.debug(f"Broadcasting to {len(subscribers)} subscribers: {message}") + + for queue in subscribers: + try: + queue.put_nowait(message) + logger.debug(f"Message queued successfully") + except asyncio.QueueFull: + try: + queue.get_nowait() + queue.put_nowait(message) + except: + pass + except Exception as e: + logger.error(f"Error queuing message: {e}") + + +# Global session manager +session_manager = SessionManager() + + +# ============================================================================ +# App Setup +# ============================================================================ + + +@asynccontextmanager +async def lifespan(app: FastAPI): + logger.info("Captain Claude v3 starting...") + yield + logger.info("Captain Claude v3 shutting down...") + + +app = FastAPI( + title="Captain Claude Mobile v3", + description="Chat API using Claude CLI with stream-json", + version="3.0.0", + lifespan=lifespan +) + +app.add_middleware( + CORSMiddleware, + allow_origins=ALLOWED_ORIGINS, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + +# ============================================================================ +# REST Endpoints +# ============================================================================ + + +@app.get("/health") +async def health(): + return {"status": "ok", "version": "3.0.0"} + + +@app.post("/auth/login", response_model=LoginResponse) +async def login(request: LoginRequest): + if request.username not in VALID_USERS: + raise HTTPException(status_code=401, detail="Invalid credentials") + if VALID_USERS[request.username] != request.password: + raise HTTPException(status_code=401, detail="Invalid credentials") + + token, expires = create_token(request.username) + return LoginResponse(token=token, expires_at=expires.isoformat()) + + +@app.get("/sessions") +async def get_sessions(user: str = Depends(get_current_user)): + return await session_manager.list_sessions() + + +@app.post("/sessions") +async def create_session(request: CreateSessionRequest, user: str = Depends(get_current_user)): + try: + session = await session_manager.create_session(request.name) + return SessionInfo( + session_id=session.session_id, + name=session.name, + created_at=session.created_at.isoformat() + ) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +# ============================================================================ +# WebSocket Chat +# ============================================================================ + + +@app.websocket("/ws/chat") +async def websocket_chat(websocket: WebSocket): + """WebSocket endpoint for chat""" + await websocket.accept() + + # Auth handshake + try: + auth_msg = await asyncio.wait_for(websocket.receive_json(), timeout=10.0) + token = auth_msg.get("token", "") + username = verify_token(token) + if not username: + await websocket.send_json({"type": "error", "message": "Invalid token"}) + await websocket.close(code=4001) + return + except asyncio.TimeoutError: + await websocket.send_json({"type": "error", "message": "Auth timeout"}) + await websocket.close(code=4001) + return + except Exception as e: + await websocket.send_json({"type": "error", "message": f"Auth error: {str(e)}"}) + await websocket.close(code=4001) + return + + # Send init + sessions = await session_manager.list_sessions() + await websocket.send_json({ + "type": "init", + "user": username, + "sessions": [{"session_id": s.session_id, "name": s.name} for s in sessions] + }) + + # Current subscription state + current_session_id: Optional[str] = None + current_queue: Optional[asyncio.Queue] = None + output_task: Optional[asyncio.Task] = None + + async def output_forwarder(queue: asyncio.Queue): + """Forward output from queue to websocket""" + while True: + try: + message = await queue.get() + # Message already has type, just forward it + await websocket.send_json(message) + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Output forwarder error: {e}") + break + + try: + while True: + data = await websocket.receive_json() + msg_type = data.get("type", "") + + if msg_type == "create_session": + # Create a new session and auto-connect + name = data.get("name", f"session_{datetime.now().strftime('%H%M%S')}") + try: + session = await session_manager.create_session(name) + await websocket.send_json({ + "type": "session_created", + "session_id": session.session_id, + "name": session.name + }) + + # Auto-connect to the new session + if current_session_id and current_queue: + if output_task: + output_task.cancel() + try: + await output_task + except asyncio.CancelledError: + pass + await session_manager.unsubscribe(current_session_id, current_queue) + + current_queue = await session_manager.subscribe(session.session_id) + current_session_id = session.session_id + output_task = asyncio.create_task(output_forwarder(current_queue)) + + await websocket.send_json({ + "type": "session_connected", + "session_id": session.session_id, + "name": session.name + }) + logger.info(f"Auto-connected to new session {session.session_id}") + except Exception as e: + await websocket.send_json({"type": "error", "message": str(e)}) + + elif msg_type == "connect_session": + session_id = data.get("session_id", "") + + # Unsubscribe from previous session + if current_session_id and current_queue: + if output_task: + output_task.cancel() + try: + await output_task + except asyncio.CancelledError: + pass + await session_manager.unsubscribe(current_session_id, current_queue) + + # Subscribe to new session + try: + current_queue = await session_manager.subscribe(session_id) + current_session_id = session_id + output_task = asyncio.create_task(output_forwarder(current_queue)) + + session = await session_manager.get_session(session_id) + await websocket.send_json({ + "type": "session_connected", + "session_id": session_id, + "name": session.name if session else "unknown" + }) + except ValueError as e: + await websocket.send_json({"type": "error", "message": str(e)}) + current_session_id = None + current_queue = None + + elif msg_type == "message": + content = data.get("content", "") + if current_session_id and content: + # Send message in background so we can receive more commands + asyncio.create_task( + session_manager.send_message(current_session_id, content) + ) + elif not current_session_id: + await websocket.send_json({ + "type": "error", + "message": "No hay sesión conectada" + }) + + elif msg_type == "list_sessions": + sessions = await session_manager.list_sessions() + await websocket.send_json({ + "type": "sessions_list", + "sessions": [{"session_id": s.session_id, "name": s.name} for s in sessions] + }) + + elif msg_type == "ping": + await websocket.send_json({"type": "pong"}) + + except WebSocketDisconnect: + pass + except Exception as e: + logger.error(f"WebSocket error: {e}") + try: + await websocket.send_json({"type": "error", "message": str(e)}) + except: + pass + finally: + if output_task: + output_task.cancel() + try: + await output_task + except asyncio.CancelledError: + pass + if current_session_id and current_queue: + await session_manager.unsubscribe(current_session_id, current_queue) + + +# ============================================================================ +# Main +# ============================================================================ + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=3030) diff --git a/apps/captain-mobile-v2/backend/requirements.txt b/apps/captain-mobile-v2/backend/requirements.txt new file mode 100644 index 0000000..b8c9bba --- /dev/null +++ b/apps/captain-mobile-v2/backend/requirements.txt @@ -0,0 +1,5 @@ +fastapi==0.109.0 +uvicorn[standard]==0.27.0 +websockets==12.0 +pyjwt==2.8.0 +python-multipart==0.0.6 diff --git a/apps/captain-mobile-v2/backend/test_autoconnect.py b/apps/captain-mobile-v2/backend/test_autoconnect.py new file mode 100644 index 0000000..ad56c67 --- /dev/null +++ b/apps/captain-mobile-v2/backend/test_autoconnect.py @@ -0,0 +1,45 @@ +import asyncio +import json +from websockets import connect +import httpx + +async def test(): + print("=== Test Auto-Connect ===", flush=True) + + async with httpx.AsyncClient() as client: + r = await client.post('http://localhost:3030/auth/login', + json={'username': 'admin', 'password': 'admin'}) + token = r.json()['token'] + + async with connect('ws://localhost:3030/ws/chat') as ws: + await ws.send(json.dumps({'token': token})) + init = json.loads(await ws.recv()) + print(f"1. Init: {init.get('type')}, sessions: {len(init.get('sessions', []))}", flush=True) + + # Create session + print("2. Creating session...", flush=True) + await ws.send(json.dumps({'type': 'create_session', 'name': 'mi_sesion'})) + + # Should receive session_created AND session_connected + for i in range(3): + msg = json.loads(await asyncio.wait_for(ws.recv(), timeout=5)) + print(f" Received: {msg.get('type')} - {msg}", flush=True) + if msg.get('type') == 'session_connected': + print("3. AUTO-CONNECT OK!", flush=True) + + # Now send a message + print("4. Sending message...", flush=True) + await ws.send(json.dumps({'type': 'message', 'content': 'di hola'})) + + for j in range(30): + try: + resp = json.loads(await asyncio.wait_for(ws.recv(), timeout=2)) + print(f" Response: {resp}", flush=True) + if resp.get('type') == 'done': + print("\n=== SUCCESS ===", flush=True) + return + except asyncio.TimeoutError: + pass + return + +asyncio.run(test()) diff --git a/apps/captain-mobile-v2/backend/test_connect.py b/apps/captain-mobile-v2/backend/test_connect.py new file mode 100644 index 0000000..3bf20e7 --- /dev/null +++ b/apps/captain-mobile-v2/backend/test_connect.py @@ -0,0 +1,65 @@ +import asyncio +import json +from websockets import connect +import httpx + +async def test(): + print("=== Test Connect Session ===") + + # Login + async with httpx.AsyncClient() as client: + r = await client.post('http://localhost:3030/auth/login', + json={'username': 'admin', 'password': 'admin'}) + token = r.json()['token'] + + # Connect and create session + async with connect('ws://localhost:3030/ws/chat') as ws: + await ws.send(json.dumps({'token': token})) + init = json.loads(await ws.recv()) + print(f"1. Init sessions: {len(init.get('sessions', []))}") + for s in init.get('sessions', []): + print(f" - {s['name']} ({s['session_id'][:8]}...)") + + # Create a new session + await ws.send(json.dumps({'type': 'create_session', 'name': 'test_session'})) + created = json.loads(await ws.recv()) + print(f"2. Created: {created}") + sid = created.get('session_id') + + # Should auto-connect - check for session_connected + connected = json.loads(await ws.recv()) + print(f"3. Connected msg: {connected}") + + print("\n--- Reconnecting ---\n") + + # Reconnect + async with connect('ws://localhost:3030/ws/chat') as ws: + await ws.send(json.dumps({'token': token})) + init = json.loads(await ws.recv()) + print(f"4. Init sessions: {len(init.get('sessions', []))}") + for s in init.get('sessions', []): + print(f" - {s['name']} ({s['session_id'][:8]}...)") + + # Try to connect to the session we created + print(f"\n5. Connecting to session {sid[:8]}...") + await ws.send(json.dumps({'type': 'connect_session', 'session_id': sid})) + result = json.loads(await ws.recv()) + print(f"6. Result: {result}") + + if result.get('type') == 'session_connected': + print("\n=== SUCCESS - Connected to existing session ===") + + # Try sending a message + await ws.send(json.dumps({'type': 'message', 'content': 'test'})) + for i in range(30): + try: + m = await asyncio.wait_for(ws.recv(), timeout=1.0) + print(f" RECV: {json.loads(m)}") + if json.loads(m).get('type') == 'done': + break + except asyncio.TimeoutError: + pass + else: + print(f"\n=== FAILED: {result} ===") + +asyncio.run(test()) diff --git a/apps/captain-mobile-v2/backend/test_connect2.py b/apps/captain-mobile-v2/backend/test_connect2.py new file mode 100644 index 0000000..e68e45a --- /dev/null +++ b/apps/captain-mobile-v2/backend/test_connect2.py @@ -0,0 +1,35 @@ +import asyncio +import json +from websockets import connect +import httpx + +async def test(): + print("=== Test Connect Session ===", flush=True) + + # Login + async with httpx.AsyncClient() as client: + r = await client.post('http://localhost:3030/auth/login', + json={'username': 'admin', 'password': 'admin'}) + token = r.json()['token'] + print(f"Got token", flush=True) + + # Connect and list sessions + async with connect('ws://localhost:3030/ws/chat') as ws: + await ws.send(json.dumps({'token': token})) + init = json.loads(await ws.recv()) + print(f"Init: {init.get('type')}", flush=True) + sessions = init.get('sessions', []) + print(f"Sessions: {len(sessions)}", flush=True) + for s in sessions: + print(f" - {s['name']} ({s['session_id']})", flush=True) + + if sessions: + sid = sessions[0]['session_id'] + print(f"\nConnecting to: {sid}", flush=True) + await ws.send(json.dumps({'type': 'connect_session', 'session_id': sid})) + result = json.loads(await ws.recv()) + print(f"Result: {result}", flush=True) + else: + print("No sessions to connect to", flush=True) + +asyncio.run(test()) diff --git a/apps/captain-mobile-v2/backend/test_final.py b/apps/captain-mobile-v2/backend/test_final.py new file mode 100644 index 0000000..68cf645 --- /dev/null +++ b/apps/captain-mobile-v2/backend/test_final.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +""" +Test final de Captain Mobile - Valida flujo completo +""" +import asyncio +import json +import httpx +from websockets import connect + +SESSION = "655551.qa_test" + +async def test(): + print("=" * 60) + print("TEST FINAL - Captain Mobile") + print(f"Sesión: {SESSION}") + print("=" * 60) + + # 1. Login + print("\n[1] Obteniendo token...") + async with httpx.AsyncClient() as client: + r = await client.post('http://localhost:3030/auth/login', + json={'username': 'admin', 'password': 'admin'}) + if r.status_code != 200: + print(f"ERROR: Login failed {r.status_code}") + return + token = r.json()['token'] + print(f" Token OK: {token[:20]}...") + + # 2. WebSocket + print("\n[2] Conectando WebSocket...") + async with connect('ws://localhost:3030/ws/chat') as ws: + await ws.send(json.dumps({'token': token})) + init = json.loads(await ws.recv()) + print(f" Init: {init['type']}") + + # 3. Connect to session + print(f"\n[3] Conectando a sesión {SESSION}...") + await ws.send(json.dumps({'type': 'connect_session', 'full_name': SESSION})) + conn = json.loads(await ws.recv()) + print(f" Resultado: {conn['type']}") + + if conn['type'] != 'session_connected': + print(f" ERROR: No se pudo conectar a la sesión") + return + + # 4. Esperar un poco para que se establezca la conexión + print("\n[4] Esperando 2s para estabilizar conexión...") + await asyncio.sleep(2) + + # 5. Enviar mensaje simple + mensaje = "responde EXACTAMENTE: TEST_OK_12345" + print(f"\n[5] Enviando mensaje: '{mensaje}'") + await ws.send(json.dumps({'type': 'message', 'content': mensaje})) + + # 6. Recibir respuestas + print("\n[6] Esperando respuestas (max 45s)...") + outputs = [] + start = asyncio.get_event_loop().time() + + try: + while (asyncio.get_event_loop().time() - start) < 45: + try: + msg = await asyncio.wait_for(ws.recv(), timeout=10.0) + data = json.loads(msg) + if data['type'] == 'output': + content = data['content'] + outputs.append(content) + # Mostrar preview + preview = content[:80].replace('\n', '\\n') + print(f" Output #{len(outputs)} ({len(content)} chars): {preview}...") + + # Buscar la respuesta esperada + if 'TEST_OK_12345' in content: + print(f" *** RESPUESTA ENCONTRADA! ***") + break + except asyncio.TimeoutError: + print(" (timeout 10s sin output)") + if outputs: + break + except Exception as e: + print(f" Error: {e}") + + # 7. Validación + full_output = ''.join(outputs) + + print("\n" + "=" * 60) + print("RESULTADOS") + print("=" * 60) + + print(f"\nOutputs recibidos: {len(outputs)}") + print(f"Total caracteres: {len(full_output)}") + + # Check 1: Respuesta encontrada + has_response = 'TEST_OK_12345' in full_output + print(f"\n[CHECK 1] Respuesta 'TEST_OK_12345': {'PASS' if has_response else 'FAIL'}") + + # Check 2: Sin duplicados excesivos + no_duplicates = len(full_output) < 2000 # Respuesta simple debería ser corta + print(f"[CHECK 2] Sin duplicados excesivos (<2000 chars): {'PASS' if no_duplicates else 'FAIL'}") + + # Check 3: UI filtrada + has_ui = 'bypass permissions' in full_output or '───' in full_output + no_ui = not has_ui + print(f"[CHECK 3] UI de Claude filtrada: {'PASS' if no_ui else 'FAIL'}") + + # Resultado final + all_pass = has_response and no_duplicates and no_ui + print("\n" + "=" * 60) + print(f"RESULTADO FINAL: {'PASS' if all_pass else 'FAIL'}") + print("=" * 60) + + if len(full_output) < 500: + print(f"\nRespuesta completa:\n{full_output}") + else: + print(f"\nRespuesta (primeros 500 chars):\n{full_output[:500]}...") + +if __name__ == '__main__': + asyncio.run(test()) diff --git a/apps/captain-mobile-v2/backend/test_simple.py b/apps/captain-mobile-v2/backend/test_simple.py new file mode 100644 index 0000000..fcd3857 --- /dev/null +++ b/apps/captain-mobile-v2/backend/test_simple.py @@ -0,0 +1,40 @@ +import asyncio +import json +from websockets import connect +import httpx + +async def test(): + print("=== Test Simple ===") + + async with httpx.AsyncClient() as client: + r = await client.post('http://localhost:3030/auth/login', + json={'username': 'admin', 'password': 'admin'}) + token = r.json()['token'] + + async with connect('ws://localhost:3030/ws/chat') as ws: + await ws.send(json.dumps({'token': token})) + await ws.recv() + + await ws.send(json.dumps({'type': 'create_session', 'name': 's'})) + created = json.loads(await ws.recv()) + sid = created['session_id'] + + await ws.send(json.dumps({'type': 'connect_session', 'session_id': sid})) + await ws.recv() + + print("Enviando: di hola") + await ws.send(json.dumps({'type': 'message', 'content': 'di hola'})) + + print("Esperando respuesta (60s max)...") + for i in range(60): + try: + m = await asyncio.wait_for(ws.recv(), timeout=1.0) + data = json.loads(m) + print(f" RECIBIDO: {data}") + if data.get('type') == 'done': + print("\n=== COMPLETADO ===") + break + except asyncio.TimeoutError: + print(f" {i+1}s...", end="\r") + +asyncio.run(test()) diff --git a/apps/captain-mobile-v2/backend/test_v3.py b/apps/captain-mobile-v2/backend/test_v3.py new file mode 100644 index 0000000..e44c41b --- /dev/null +++ b/apps/captain-mobile-v2/backend/test_v3.py @@ -0,0 +1,40 @@ +import asyncio +import json +from websockets import connect +import httpx + +async def test(): + print("=== Test v3 Simple ===") + + async with httpx.AsyncClient() as client: + r = await client.post('http://localhost:3030/auth/login', + json={'username': 'admin', 'password': 'admin'}) + token = r.json()['token'] + + async with connect('ws://localhost:3030/ws/chat') as ws: + await ws.send(json.dumps({'token': token})) + await ws.recv() # init + + await ws.send(json.dumps({'type': 'create_session', 'name': 't'})) + created = json.loads(await ws.recv()) + sid = created['session_id'] + + await ws.send(json.dumps({'type': 'connect_session', 'session_id': sid})) + await ws.recv() # connected + + print("Enviando mensaje...") + await ws.send(json.dumps({'type': 'message', 'content': 'di OK'})) + + # Esperar respuesta con mucho timeout + print("Esperando (30s)...") + try: + for i in range(30): + try: + msg = await asyncio.wait_for(ws.recv(), timeout=1.0) + print(f"RECIBIDO: {msg}") + except asyncio.TimeoutError: + print(f" {i+1}s...", end="\r") + except Exception as e: + print(f"Error: {e}") + +asyncio.run(test()) diff --git a/apps/captain-mobile-v2/backend/test_v3_full.py b/apps/captain-mobile-v2/backend/test_v3_full.py new file mode 100644 index 0000000..15bf79d --- /dev/null +++ b/apps/captain-mobile-v2/backend/test_v3_full.py @@ -0,0 +1,46 @@ +import asyncio +import json +from websockets import connect +import httpx + +async def test(): + print("=== Test v3 Conversación ===\n") + + async with httpx.AsyncClient() as client: + r = await client.post('http://localhost:3030/auth/login', + json={'username': 'admin', 'password': 'admin'}) + token = r.json()['token'] + + async with connect('ws://localhost:3030/ws/chat') as ws: + await ws.send(json.dumps({'token': token})) + await ws.recv() + + await ws.send(json.dumps({'type': 'create_session', 'name': 'conversacion'})) + created = json.loads(await ws.recv()) + sid = created['session_id'] + + await ws.send(json.dumps({'type': 'connect_session', 'session_id': sid})) + await ws.recv() + + async def send_and_wait(msg): + print(f"YO: {msg}") + await ws.send(json.dumps({'type': 'message', 'content': msg})) + response = "" + for _ in range(20): + try: + m = await asyncio.wait_for(ws.recv(), timeout=1.0) + data = json.loads(m) + if data.get('type') == 'output': + response = data.get('content', '') + if data.get('type') == 'done': + break + except asyncio.TimeoutError: + pass + print(f"CLAUDE: {response}\n") + return response + + await send_and_wait("mi nombre es Pablo") + await send_and_wait("cuál es mi nombre?") + await send_and_wait("di hola") + +asyncio.run(test()) diff --git a/apps/captain-mobile-v2/backend/test_websocket.py b/apps/captain-mobile-v2/backend/test_websocket.py new file mode 100755 index 0000000..809b291 --- /dev/null +++ b/apps/captain-mobile-v2/backend/test_websocket.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +""" +Test WebSocket - Simula comportamiento de app Flutter +Valida conexión, autenticación, mensajes y respuestas +""" +import asyncio +import json +import httpx +from websockets import connect + +async def test(): + print("=" * 60) + print("TEST WEBSOCKET - Simulador App Flutter") + print("=" * 60) + + # 1. Login + print("\n[1] Obteniendo token de autenticación...") + async with httpx.AsyncClient() as client: + r = await client.post('http://localhost:3030/auth/login', + json={'username': 'admin', 'password': 'admin'}) + if r.status_code != 200: + print(f"ERROR: Login failed with status {r.status_code}") + return + token = r.json()['token'] + print(f" Token obtenido: {token[:20]}...") + + # 2. WebSocket + print("\n[2] Conectando a WebSocket...") + async with connect('ws://localhost:3030/ws/chat') as ws: + # Auth + await ws.send(json.dumps({'token': token})) + init = json.loads(await ws.recv()) + print(f" Init response: {init['type']}") + + # Connect to session + print("\n[3] Conectando a sesión 648211.captain_test...") + await ws.send(json.dumps({'type': 'connect_session', 'full_name': '648211.captain_test'})) + conn = json.loads(await ws.recv()) + print(f" Session response: {conn}") + + # Send message + print("\n[4] Enviando mensaje: 'di solo: OK'") + await ws.send(json.dumps({'type': 'message', 'content': 'di solo: OK'})) + + # Receive responses - longer timeout for Claude response + print("\n[5] Esperando respuestas (timeout 30s)...") + outputs = [] + output_count = 0 + start_time = asyncio.get_event_loop().time() + max_wait = 30.0 # Max 30 seconds total + idle_timeout = 8.0 # 8 seconds without output = done + + try: + while (asyncio.get_event_loop().time() - start_time) < max_wait: + try: + msg = await asyncio.wait_for(ws.recv(), timeout=idle_timeout) + data = json.loads(msg) + if data['type'] == 'output': + output_count += 1 + content = data['content'] + outputs.append(content) + preview = content[:100].replace('\n', '\\n') + print(f" Output #{output_count} ({len(content)} chars): {preview}...") + elif data['type'] == 'status': + print(f" Status: {data.get('status', data)}") + elif data['type'] == 'error': + print(f" ERROR: {data.get('message', data)}") + except asyncio.TimeoutError: + print(" (idle timeout - fin de respuestas)") + break + except Exception as e: + print(f" Error: {e}") + + # Validate + full_output = ''.join(outputs) + + print("\n" + "=" * 60) + print("VALIDACION DE RESULTADOS") + print("=" * 60) + + # Validación 1: Contiene OK + contains_ok = 'OK' in full_output or 'ok' in full_output.lower() + print(f"\n[CHECK 1] Contiene 'OK': {'PASS' if contains_ok else 'FAIL'}") + + # Validación 2: No duplicados + # Detectar si hay contenido repetido + has_duplicates = False + if len(outputs) > 1: + # Verificar si chunks consecutivos son idénticos + for i in range(len(outputs) - 1): + if outputs[i] == outputs[i+1] and len(outputs[i]) > 10: + has_duplicates = True + break + # Verificar si el contenido total tiene patrones repetidos + if len(full_output) > 100: + half = len(full_output) // 2 + first_half = full_output[:half] + second_half = full_output[half:half*2] + if first_half == second_half: + has_duplicates = True + + print(f"[CHECK 2] Sin duplicados: {'PASS' if not has_duplicates else 'FAIL'}") + if has_duplicates: + print(" WARNING: Se detectó contenido duplicado!") + + # Validación 3: Longitud razonable + is_short = len(full_output) <= 500 + print(f"[CHECK 3] Longitud <= 500 chars: {'PASS' if is_short else 'FAIL'}") + print(f" Longitud actual: {len(full_output)} caracteres") + + # Resumen + all_passed = contains_ok and not has_duplicates and is_short + print("\n" + "=" * 60) + if all_passed: + print("RESULTADO FINAL: PASS - Todas las validaciones correctas") + else: + print("RESULTADO FINAL: FAIL - Hay validaciones fallidas") + print("=" * 60) + + # Mostrar respuesta completa si es corta + if len(full_output) <= 500: + print(f"\nRespuesta completa:\n{full_output}") + else: + print(f"\nRespuesta (primeros 500 chars):\n{full_output[:500]}...") + print(f"\n... (truncado, total: {len(full_output)} chars)") + +if __name__ == '__main__': + asyncio.run(test()) diff --git a/apps/captain-mobile-v2/data/.admin_password b/apps/captain-mobile-v2/data/.admin_password new file mode 100644 index 0000000..7fbe952 --- /dev/null +++ b/apps/captain-mobile-v2/data/.admin_password @@ -0,0 +1 @@ +admin diff --git a/apps/captain-mobile-v2/data/.jwt_secret b/apps/captain-mobile-v2/data/.jwt_secret new file mode 100644 index 0000000..54d4fea --- /dev/null +++ b/apps/captain-mobile-v2/data/.jwt_secret @@ -0,0 +1 @@ +9bb9be71305495d244b9d4966699190ab607163867e52513375575496010238f \ No newline at end of file diff --git a/apps/captain-mobile-v2/data/captain.db b/apps/captain-mobile-v2/data/captain.db new file mode 100644 index 0000000..afbe8d1 Binary files /dev/null and b/apps/captain-mobile-v2/data/captain.db differ diff --git a/apps/captain-mobile-v2/flutter/.gitignore b/apps/captain-mobile-v2/flutter/.gitignore new file mode 100644 index 0000000..29a3a50 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/.gitignore @@ -0,0 +1,43 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/apps/captain-mobile-v2/flutter/.metadata b/apps/captain-mobile-v2/flutter/.metadata new file mode 100644 index 0000000..d044da8 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: android + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: ios + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: linux + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: macos + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: web + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: windows + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/apps/captain-mobile-v2/flutter/README.md b/apps/captain-mobile-v2/flutter/README.md new file mode 100644 index 0000000..a7f09fc --- /dev/null +++ b/apps/captain-mobile-v2/flutter/README.md @@ -0,0 +1,16 @@ +# captain_mobile_v2 + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/apps/captain-mobile-v2/flutter/analysis_options.yaml b/apps/captain-mobile-v2/flutter/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/apps/captain-mobile-v2/flutter/android/.gitignore b/apps/captain-mobile-v2/flutter/android/.gitignore new file mode 100644 index 0000000..55afd91 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/.gitignore @@ -0,0 +1,13 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/apps/captain-mobile-v2/flutter/android/app/build.gradle b/apps/captain-mobile-v2/flutter/android/app/build.gradle new file mode 100644 index 0000000..0bc630b --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/app/build.gradle @@ -0,0 +1,44 @@ +plugins { + id "com.android.application" + id "kotlin-android" + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id "dev.flutter.flutter-gradle-plugin" +} + +android { + namespace = "com.tzzr.captain_mobile_v2" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_1_8 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.tzzr.captain_mobile_v2" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.debug + } + } +} + +flutter { + source = "../.." +} diff --git a/apps/captain-mobile-v2/flutter/android/app/src/debug/AndroidManifest.xml b/apps/captain-mobile-v2/flutter/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/AndroidManifest.xml b/apps/captain-mobile-v2/flutter/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..b3294bc --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/kotlin/com/tzzr/captain_mobile_v2/MainActivity.kt b/apps/captain-mobile-v2/flutter/android/app/src/main/kotlin/com/tzzr/captain_mobile_v2/MainActivity.kt new file mode 100644 index 0000000..35bde5c --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/app/src/main/kotlin/com/tzzr/captain_mobile_v2/MainActivity.kt @@ -0,0 +1,5 @@ +package com.tzzr.captain_mobile_v2 + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/res/drawable-v21/launch_background.xml b/apps/captain-mobile-v2/flutter/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/res/drawable/launch_background.xml b/apps/captain-mobile-v2/flutter/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/apps/captain-mobile-v2/flutter/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/res/values-night/styles.xml b/apps/captain-mobile-v2/flutter/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/android/app/src/main/res/values/styles.xml b/apps/captain-mobile-v2/flutter/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/android/app/src/profile/AndroidManifest.xml b/apps/captain-mobile-v2/flutter/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/apps/captain-mobile-v2/flutter/android/build.gradle b/apps/captain-mobile-v2/flutter/android/build.gradle new file mode 100644 index 0000000..d2ffbff --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/build.gradle @@ -0,0 +1,18 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = "../build" +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} diff --git a/apps/captain-mobile-v2/flutter/android/gradle.properties b/apps/captain-mobile-v2/flutter/android/gradle.properties new file mode 100644 index 0000000..2597170 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/apps/captain-mobile-v2/flutter/android/gradle/wrapper/gradle-wrapper.properties b/apps/captain-mobile-v2/flutter/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7bb2df6 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-all.zip diff --git a/apps/captain-mobile-v2/flutter/android/settings.gradle b/apps/captain-mobile-v2/flutter/android/settings.gradle new file mode 100644 index 0000000..b9e43bd --- /dev/null +++ b/apps/captain-mobile-v2/flutter/android/settings.gradle @@ -0,0 +1,25 @@ +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + }() + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.1.0" apply false + id "org.jetbrains.kotlin.android" version "1.8.22" apply false +} + +include ":app" diff --git a/apps/captain-mobile-v2/flutter/assets/fonts/JetBrainsMono-Regular.ttf b/apps/captain-mobile-v2/flutter/assets/fonts/JetBrainsMono-Regular.ttf new file mode 100644 index 0000000..711830e Binary files /dev/null and b/apps/captain-mobile-v2/flutter/assets/fonts/JetBrainsMono-Regular.ttf differ diff --git a/apps/captain-mobile-v2/flutter/ios/.gitignore b/apps/captain-mobile-v2/flutter/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/apps/captain-mobile-v2/flutter/ios/Flutter/AppFrameworkInfo.plist b/apps/captain-mobile-v2/flutter/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..7c56964 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 12.0 + + diff --git a/apps/captain-mobile-v2/flutter/ios/Flutter/Debug.xcconfig b/apps/captain-mobile-v2/flutter/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/apps/captain-mobile-v2/flutter/ios/Flutter/Release.xcconfig b/apps/captain-mobile-v2/flutter/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.pbxproj b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..247fbbe --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,616 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..8e3ca5d --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner.xcworkspace/contents.xcworkspacedata b/apps/captain-mobile-v2/flutter/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/apps/captain-mobile-v2/flutter/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/apps/captain-mobile-v2/flutter/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/AppDelegate.swift b/apps/captain-mobile-v2/flutter/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Base.lproj/LaunchScreen.storyboard b/apps/captain-mobile-v2/flutter/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Base.lproj/Main.storyboard b/apps/captain-mobile-v2/flutter/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Info.plist b/apps/captain-mobile-v2/flutter/ios/Runner/Info.plist new file mode 100644 index 0000000..a724918 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Captain Mobile V2 + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + captain_mobile_v2 + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/apps/captain-mobile-v2/flutter/ios/Runner/Runner-Bridging-Header.h b/apps/captain-mobile-v2/flutter/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/apps/captain-mobile-v2/flutter/ios/RunnerTests/RunnerTests.swift b/apps/captain-mobile-v2/flutter/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/apps/captain-mobile-v2/flutter/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/apps/captain-mobile-v2/flutter/lib/config/api_config.dart b/apps/captain-mobile-v2/flutter/lib/config/api_config.dart new file mode 100644 index 0000000..cf56430 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/config/api_config.dart @@ -0,0 +1,13 @@ +class ApiConfig { + // Captain Mobile v2 API + static const String baseUrl = 'http://69.62.126.110:3030'; + static const String wsUrl = 'ws://69.62.126.110:3030'; + + // For local development + // static const String baseUrl = 'http://localhost:3030'; + // static const String wsUrl = 'ws://localhost:3030'; + + static const Duration connectionTimeout = Duration(seconds: 30); + static const Duration reconnectDelay = Duration(seconds: 3); + static const int maxReconnectAttempts = 5; +} diff --git a/apps/captain-mobile-v2/flutter/lib/main.dart b/apps/captain-mobile-v2/flutter/lib/main.dart new file mode 100644 index 0000000..595444d --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/main.dart @@ -0,0 +1,78 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'providers/auth_provider.dart'; +import 'providers/chat_provider.dart'; +import 'screens/login_screen.dart'; +import 'screens/chat_screen.dart'; + +void main() { + WidgetsFlutterBinding.ensureInitialized(); + SystemChrome.setSystemUIOverlayStyle( + const SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + statusBarIconBrightness: Brightness.light, + ), + ); + runApp(const CaptainClaudeApp()); +} + +class CaptainClaudeApp extends StatelessWidget { + const CaptainClaudeApp({super.key}); + + @override + Widget build(BuildContext context) { + return MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => AuthProvider()..init()), + ChangeNotifierProvider(create: (_) => ChatProvider()), + ], + child: MaterialApp( + title: 'Captain Claude', + debugShowCheckedModeBanner: false, + theme: ThemeData( + brightness: Brightness.dark, + primaryColor: Colors.orange.shade700, + scaffoldBackgroundColor: const Color(0xFF1A1A1A), + colorScheme: ColorScheme.dark( + primary: Colors.orange.shade700, + secondary: Colors.orange.shade400, + surface: const Color(0xFF2D2D2D), + ), + appBarTheme: const AppBarTheme( + backgroundColor: Color(0xFF2D2D2D), + elevation: 0, + ), + fontFamily: 'Roboto', + ), + home: const AuthWrapper(), + ), + ); + } +} + +class AuthWrapper extends StatelessWidget { + const AuthWrapper({super.key}); + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, auth, _) { + if (auth.isLoading) { + return const Scaffold( + backgroundColor: Color(0xFF1A1A1A), + body: Center( + child: CircularProgressIndicator(color: Colors.orange), + ), + ); + } + + if (auth.isAuthenticated) { + return const ChatScreen(); + } + + return const LoginScreen(); + }, + ); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/models/conversation.dart b/apps/captain-mobile-v2/flutter/lib/models/conversation.dart new file mode 100644 index 0000000..516bb02 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/models/conversation.dart @@ -0,0 +1,38 @@ +class Conversation { + final String id; + final String? title; + final DateTime createdAt; + final DateTime updatedAt; + final int messageCount; + + Conversation({ + required this.id, + this.title, + required this.createdAt, + required this.updatedAt, + this.messageCount = 0, + }); + + factory Conversation.fromJson(Map json) { + return Conversation( + id: json['id'], + title: json['title'], + createdAt: DateTime.parse(json['created_at']), + updatedAt: DateTime.parse(json['updated_at']), + messageCount: json['message_count'] ?? 0, + ); + } + + String get displayTitle => title ?? 'New Conversation'; + + String get timeAgo { + final now = DateTime.now(); + final diff = now.difference(updatedAt); + + if (diff.inMinutes < 1) return 'Just now'; + if (diff.inMinutes < 60) return '${diff.inMinutes}m ago'; + if (diff.inHours < 24) return '${diff.inHours}h ago'; + if (diff.inDays < 7) return '${diff.inDays}d ago'; + return '${updatedAt.day}/${updatedAt.month}/${updatedAt.year}'; + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/models/message.dart b/apps/captain-mobile-v2/flutter/lib/models/message.dart new file mode 100644 index 0000000..79de7b3 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/models/message.dart @@ -0,0 +1,85 @@ +class ToolUse { + final String tool; + final dynamic input; + final String? output; + + ToolUse({ + required this.tool, + this.input, + this.output, + }); + + factory ToolUse.fromJson(Map json) { + return ToolUse( + tool: json['tool'] ?? 'unknown', + input: json['input'], + output: json['output'], + ); + } + + Map toJson() => { + 'tool': tool, + 'input': input, + 'output': output, + }; +} + +class Message { + final String id; + final String role; + final String content; + final List? toolUses; + final bool isStreaming; + final bool isThinking; + final DateTime createdAt; + + Message({ + String? id, + required this.role, + required this.content, + this.toolUses, + this.isStreaming = false, + this.isThinking = false, + DateTime? createdAt, + }) : id = id ?? DateTime.now().millisecondsSinceEpoch.toString(), + createdAt = createdAt ?? DateTime.now(); + + Message copyWith({ + String? id, + String? role, + String? content, + List? toolUses, + bool? isStreaming, + bool? isThinking, + DateTime? createdAt, + }) { + return Message( + id: id ?? this.id, + role: role ?? this.role, + content: content ?? this.content, + toolUses: toolUses ?? this.toolUses, + isStreaming: isStreaming ?? this.isStreaming, + isThinking: isThinking ?? this.isThinking, + createdAt: createdAt ?? this.createdAt, + ); + } + + factory Message.fromJson(Map json) { + return Message( + id: json['id'], + role: json['role'], + content: json['content'], + toolUses: json['tool_uses'] != null + ? (json['tool_uses'] as List) + .map((e) => ToolUse.fromJson(e)) + .toList() + : null, + createdAt: json['created_at'] != null + ? DateTime.parse(json['created_at']) + : DateTime.now(), + ); + } + + bool get isUser => role == 'user'; + bool get isAssistant => role == 'assistant'; +} diff --git a/apps/captain-mobile-v2/flutter/lib/providers/auth_provider.dart b/apps/captain-mobile-v2/flutter/lib/providers/auth_provider.dart new file mode 100644 index 0000000..c774aa0 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/providers/auth_provider.dart @@ -0,0 +1,52 @@ +import 'package:flutter/foundation.dart'; +import '../services/auth_service.dart'; + +class AuthProvider with ChangeNotifier { + final AuthService _authService = AuthService(); + + bool _isLoading = false; + String? _error; + + bool get isLoading => _isLoading; + bool get isAuthenticated => _authService.isAuthenticated; + String? get token => _authService.token; + String? get username => _authService.username; + String? get error => _error; + + Future init() async { + _isLoading = true; + notifyListeners(); + + await _authService.loadStoredAuth(); + + _isLoading = false; + notifyListeners(); + } + + Future login(String username, String password) async { + _isLoading = true; + _error = null; + notifyListeners(); + + final success = await _authService.login(username, password); + + if (!success) { + _error = _authService.lastError ?? 'Login failed'; + } + + _isLoading = false; + notifyListeners(); + + return success; + } + + Future logout() async { + await _authService.logout(); + notifyListeners(); + } + + void clearError() { + _error = null; + notifyListeners(); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/providers/chat_provider.dart b/apps/captain-mobile-v2/flutter/lib/providers/chat_provider.dart new file mode 100644 index 0000000..d648f3c --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/providers/chat_provider.dart @@ -0,0 +1,295 @@ +import 'dart:async'; +import 'package:flutter/foundation.dart'; +import '../models/message.dart'; +import '../services/chat_service.dart'; +import '../providers/auth_provider.dart'; + +/// Chat provider for v3 API (dynamic Claude sessions) +class ChatProvider with ChangeNotifier { + final ChatService _chatService = ChatService(); + final List _messages = []; + static const int _maxMessages = 500; + + AuthProvider? _authProvider; + StreamSubscription? _messageSubscription; + StreamSubscription? _stateSubscription; + StreamSubscription? _errorSubscription; + + List _sessions = []; + ChatSession? _currentSession; + bool _isProcessing = false; + String? _error; + + List get messages => List.unmodifiable(_messages); + List get sessions => List.unmodifiable(_sessions); + ChatSession? get currentSession => _currentSession; + bool get isProcessing => _isProcessing; + bool get isConnected => _chatService.currentState == ChatConnectionState.connected; + bool get isSessionConnected => _currentSession != null; + ChatConnectionState get connectionState => _chatService.currentState; + String? get error => _error; + + void updateAuth(AuthProvider auth) { + _authProvider = auth; + _chatService.setToken(auth.token); + + if (auth.isAuthenticated && !isConnected) { + connect(); + } else if (!auth.isAuthenticated && isConnected) { + disconnect(); + } + } + + Future connect() async { + if (_authProvider?.token == null) return; + + _chatService.setToken(_authProvider!.token); + + _stateSubscription?.cancel(); + _stateSubscription = _chatService.connectionState.listen((state) { + notifyListeners(); + }); + + _errorSubscription?.cancel(); + _errorSubscription = _chatService.errors.listen((error) { + _error = error; + notifyListeners(); + }); + + _messageSubscription?.cancel(); + _messageSubscription = _chatService.messages.listen(_handleMessage); + + await _chatService.connect(); + } + + void _handleMessage(Map data) { + final type = data['type']; + debugPrint('ChatProvider: type=$type'); + + switch (type) { + // Initial state with sessions + case 'init': + final sessionsList = data['sessions'] as List?; + if (sessionsList != null) { + _sessions = sessionsList + .map((s) => ChatSession.fromJson(s)) + .toList(); + } + notifyListeners(); + break; + + // Sessions list update + case 'sessions_list': + final sessionsList = data['sessions'] as List?; + if (sessionsList != null) { + _sessions = sessionsList + .map((s) => ChatSession.fromJson(s)) + .toList(); + } + notifyListeners(); + break; + + // Session created (v3) + case 'session_created': + final sessionId = data['session_id'] as String?; + final name = data['name'] as String?; + if (sessionId != null) { + final newSession = ChatSession( + sessionId: sessionId, + name: name ?? 'New Session', + ); + _sessions.add(newSession); + _messages.add(Message( + role: 'system', + content: 'Sesión creada: ${newSession.name}', + )); + // Auto-connect to new session + connectToSession(sessionId); + } + notifyListeners(); + break; + + // Connected to session (v3) + case 'session_connected': + final sessionId = data['session_id'] as String?; + final name = data['name'] as String?; + if (sessionId != null) { + _currentSession = _sessions.firstWhere( + (s) => s.sessionId == sessionId, + orElse: () => ChatSession( + sessionId: sessionId, + name: name ?? 'Session', + ), + ); + _messages.clear(); + _messages.add(Message( + role: 'system', + content: 'Conectado a: ${_currentSession!.name}', + )); + } + notifyListeners(); + break; + + // Output from Claude (v3) + case 'output': + final content = data['content'] as String? ?? ''; + if (content.isEmpty) break; + + debugPrint('ChatProvider: OUTPUT "${content.substring(0, content.length > 50 ? 50 : content.length)}"'); + _isProcessing = true; + + // Check if it's a progress indicator + if (content.startsWith('procesando')) { + // Update or create progress message + if (_messages.isNotEmpty && _messages.last.role == 'assistant' && _messages.last.isStreaming == true) { + final lastIndex = _messages.length - 1; + _messages[lastIndex] = Message( + role: 'assistant', + content: content, + isStreaming: true, + ); + } else { + _messages.add(Message( + role: 'assistant', + content: content, + isStreaming: true, + )); + } + } else { + // Real content - replace progress or add new + if (_messages.isNotEmpty && _messages.last.role == 'assistant' && _messages.last.isStreaming == true) { + final lastIndex = _messages.length - 1; + final lastContent = _messages[lastIndex].content; + // If last message was progress, replace it. Otherwise append. + if (lastContent.startsWith('procesando')) { + _messages[lastIndex] = Message( + role: 'assistant', + content: content, + isStreaming: true, + ); + } else { + // Append to existing response + _messages[lastIndex] = Message( + role: 'assistant', + content: lastContent + content, + isStreaming: true, + ); + } + } else { + _messages.add(Message( + role: 'assistant', + content: content, + isStreaming: true, + )); + } + } + _trimMessages(); + notifyListeners(); + break; + + // Response complete (v3) + case 'done': + _isProcessing = false; + // Mark last assistant message as complete + if (_messages.isNotEmpty && _messages.last.role == 'assistant') { + final lastIndex = _messages.length - 1; + _messages[lastIndex] = Message( + role: 'assistant', + content: _messages[lastIndex].content, + isStreaming: false, + ); + } + notifyListeners(); + break; + + case 'error': + _isProcessing = false; + final errorMsg = data['message'] ?? data['content'] ?? 'Error'; + if (errorMsg.toString().isNotEmpty) { + _error = errorMsg; + _messages.add(Message( + role: 'system', + content: 'Error: $errorMsg', + )); + } + notifyListeners(); + break; + } + } + + void _trimMessages() { + while (_messages.length > _maxMessages) { + _messages.removeAt(0); + } + } + + /// Create and connect to a new session + void createSession(String name) { + _chatService.createSession(name); + } + + /// Connect to an existing session + void connectToSession(String sessionId) { + _chatService.connectToSession(sessionId); + } + + /// Refresh sessions list + void refreshSessions() { + _chatService.listSessions(); + } + + /// Send message to current session + void sendMessage(String content) { + if (content.trim().isEmpty) return; + if (!isConnected) { + _error = 'No conectado al servidor'; + notifyListeners(); + return; + } + if (_currentSession == null) { + _error = 'No hay sesión activa'; + notifyListeners(); + return; + } + if (_isProcessing) { + _error = 'Espera a que termine la respuesta anterior'; + notifyListeners(); + return; + } + + _messages.add(Message( + role: 'user', + content: content, + )); + _trimMessages(); + _isProcessing = true; + notifyListeners(); + + _chatService.sendMessage(content); + } + + void clearMessages() { + _messages.clear(); + notifyListeners(); + } + + void clearError() { + _error = null; + notifyListeners(); + } + + void disconnect() { + _chatService.disconnect(); + _messageSubscription?.cancel(); + _stateSubscription?.cancel(); + _errorSubscription?.cancel(); + _currentSession = null; + } + + @override + void dispose() { + disconnect(); + _chatService.dispose(); + super.dispose(); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/screens/chat_screen.dart b/apps/captain-mobile-v2/flutter/lib/screens/chat_screen.dart new file mode 100644 index 0000000..7c11256 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/screens/chat_screen.dart @@ -0,0 +1,358 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../providers/auth_provider.dart'; +import '../providers/chat_provider.dart'; +import '../services/chat_service.dart'; +import '../widgets/message_bubble.dart'; +import '../widgets/chat_input.dart'; + +class ChatScreen extends StatefulWidget { + const ChatScreen({super.key}); + + @override + State createState() => _ChatScreenState(); +} + +class _ChatScreenState extends State with WidgetsBindingObserver { + final _scrollController = ScrollController(); + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + WidgetsBinding.instance.addPostFrameCallback((_) { + final auth = context.read(); + final chat = context.read(); + chat.updateAuth(auth); + chat.addListener(_onChatUpdate); + }); + } + + String? _lastError; + void _onChatUpdate() { + final chat = context.read(); + if (chat.error != null && chat.error != _lastError) { + _lastError = chat.error; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(chat.error!), + backgroundColor: Colors.red.shade700, + action: SnackBarAction( + label: 'OK', + textColor: Colors.white, + onPressed: () => chat.clearError(), + ), + ), + ); + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _scrollController.dispose(); + try { + final chat = context.read(); + chat.removeListener(_onChatUpdate); + } catch (_) {} + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + final chat = context.read(); + if (!chat.isConnected) { + chat.connect(); + } + } + } + + void _scrollToBottom() { + if (_scrollController.hasClients) { + _scrollController.animateTo( + _scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + ); + } + } + + void _sendMessage(String message) { + final chat = context.read(); + chat.sendMessage(message); + Future.delayed(const Duration(milliseconds: 100), _scrollToBottom); + } + + void _newChat() { + final chat = context.read(); + final name = 'Chat ${DateTime.now().hour}:${DateTime.now().minute.toString().padLeft(2, '0')}'; + chat.createSession(name); + } + + void _logout() { + final auth = context.read(); + final chat = context.read(); + chat.disconnect(); + auth.logout(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF1A1A1A), + appBar: AppBar( + backgroundColor: const Color(0xFF2D2D2D), + elevation: 0, + title: Consumer( + builder: (context, chat, _) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.auto_awesome, color: Colors.orange.shade400, size: 24), + const SizedBox(width: 8), + Text( + chat.currentSession?.name ?? 'Captain Claude', + style: const TextStyle(fontSize: 18), + ), + ], + ); + }, + ), + actions: [ + Consumer( + builder: (context, chat, _) { + return IconButton( + icon: const Icon(Icons.add), + onPressed: _newChat, + tooltip: 'Nuevo Chat', + ); + }, + ), + IconButton( + icon: const Icon(Icons.logout), + onPressed: _logout, + tooltip: 'Salir', + ), + ], + ), + body: Column( + children: [ + // Connection status bar + Consumer( + builder: (context, chat, _) { + return _buildConnectionBar(chat); + }, + ), + // Messages list + Expanded( + child: Consumer( + builder: (context, chat, _) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (chat.isProcessing) _scrollToBottom(); + }); + + if (!chat.isSessionConnected) { + return _buildStartState(); + } + + if (chat.messages.isEmpty) { + return _buildEmptyState(); + } + + return ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.only(top: 8, bottom: 8), + itemCount: chat.messages.length, + itemBuilder: (context, index) { + return MessageBubble(message: chat.messages[index]); + }, + ); + }, + ), + ), + // Input area + Consumer( + builder: (context, chat, _) { + return ChatInput( + onSend: _sendMessage, + isConnected: chat.isConnected && chat.isSessionConnected, + isLoading: chat.isProcessing, + ); + }, + ), + ], + ), + ); + } + + Widget _buildConnectionBar(ChatProvider chat) { + if (chat.connectionState == ChatConnectionState.connected) { + return const SizedBox.shrink(); + } + + Color backgroundColor; + String text; + IconData icon; + + switch (chat.connectionState) { + case ChatConnectionState.connecting: + backgroundColor = Colors.blue.shade700; + text = 'Conectando...'; + icon = Icons.sync; + break; + case ChatConnectionState.reconnecting: + backgroundColor = Colors.orange.shade700; + text = 'Reconectando...'; + icon = Icons.sync; + break; + case ChatConnectionState.error: + backgroundColor = Colors.red.shade700; + text = 'Error de conexión'; + icon = Icons.error_outline; + break; + default: + backgroundColor = Colors.grey.shade700; + text = 'Desconectado'; + icon = Icons.cloud_off; + } + + final showRetry = chat.connectionState == ChatConnectionState.error || + chat.connectionState == ChatConnectionState.disconnected; + + return GestureDetector( + onTap: showRetry ? () => chat.connect() : null, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + color: backgroundColor, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 16, color: Colors.white), + const SizedBox(width: 8), + Text( + showRetry ? '$text - Toca para reintentar' : text, + style: const TextStyle(color: Colors.white, fontSize: 13), + ), + if (chat.connectionState == ChatConnectionState.connecting || + chat.connectionState == ChatConnectionState.reconnecting) ...[ + const SizedBox(width: 8), + const SizedBox( + width: 12, + height: 12, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ), + ], + ], + ), + ), + ); + } + + Widget _buildStartState() { + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.chat_bubble_outline, + size: 80, + color: Colors.orange.shade400.withOpacity(0.5), + ), + const SizedBox(height: 24), + Text( + 'Captain Claude', + style: TextStyle( + color: Colors.grey.shade300, + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 12), + Text( + 'Toca el botón + para iniciar un chat', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.grey.shade500, + fontSize: 15, + ), + ), + const SizedBox(height: 32), + ElevatedButton.icon( + onPressed: _newChat, + icon: const Icon(Icons.add), + label: const Text('Nuevo Chat'), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.orange.shade700, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16), + ), + ), + ], + ), + ), + ); + } + + Widget _buildEmptyState() { + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.auto_awesome, + size: 80, + color: Colors.orange.shade400.withOpacity(0.5), + ), + const SizedBox(height: 24), + Text( + 'Chat Conectado', + style: TextStyle( + color: Colors.grey.shade300, + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 12), + Text( + 'Escribe un mensaje para hablar con Claude', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.grey.shade500, + fontSize: 15, + ), + ), + const SizedBox(height: 32), + Wrap( + spacing: 8, + runSpacing: 8, + alignment: WrapAlignment.center, + children: [ + _buildSuggestionChip('Hola'), + _buildSuggestionChip('Estado del sistema'), + _buildSuggestionChip('Ayuda'), + ], + ), + ], + ), + ), + ); + } + + Widget _buildSuggestionChip(String text) { + return ActionChip( + label: Text(text), + backgroundColor: const Color(0xFF2D2D2D), + labelStyle: TextStyle(color: Colors.grey.shade300, fontSize: 13), + side: BorderSide(color: Colors.grey.shade700), + onPressed: () => _sendMessage(text), + ); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/screens/history_screen.dart b/apps/captain-mobile-v2/flutter/lib/screens/history_screen.dart new file mode 100644 index 0000000..dd683be --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/screens/history_screen.dart @@ -0,0 +1,255 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../providers/auth_provider.dart'; +import '../services/api_service.dart'; +import '../models/conversation.dart'; + +class HistoryScreen extends StatefulWidget { + final Function(String) onSelectConversation; + + const HistoryScreen({ + super.key, + required this.onSelectConversation, + }); + + @override + State createState() => _HistoryScreenState(); +} + +class _HistoryScreenState extends State { + final ApiService _apiService = ApiService(); + List _conversations = []; + bool _isLoading = true; + String? _error; + + @override + void initState() { + super.initState(); + _loadConversations(); + } + + Future _loadConversations() async { + final auth = context.read(); + _apiService.setToken(auth.token); + + setState(() { + _isLoading = true; + _error = null; + }); + + try { + final conversations = await _apiService.getConversations(); + setState(() { + _conversations = conversations; + _isLoading = false; + }); + } catch (e) { + setState(() { + _error = e.toString(); + _isLoading = false; + }); + } + } + + Future _deleteConversation(String id) async { + try { + await _apiService.deleteConversation(id); + setState(() { + _conversations.removeWhere((c) => c.id == id); + }); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Failed to delete: $e'), + backgroundColor: Colors.red.shade700, + ), + ); + } + } + } + + IconData _getTitleIcon(String title) { + final lower = title.toLowerCase(); + if (lower.contains('error') || lower.contains('fix') || lower.contains('bug')) { + return Icons.bug_report; + } + if (lower.contains('test')) { + return Icons.science; + } + if (lower.contains('backup') || lower.contains('restore')) { + return Icons.backup; + } + if (lower.contains('deploy') || lower.contains('build')) { + return Icons.rocket_launch; + } + if (lower.contains('install') || lower.contains('setup')) { + return Icons.download; + } + return Icons.chat_bubble_outline; + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF1A1A1A), + appBar: AppBar( + backgroundColor: const Color(0xFF2D2D2D), + title: const Text('Conversations'), + actions: [ + IconButton( + icon: const Icon(Icons.refresh), + onPressed: _loadConversations, + ), + ], + ), + body: _buildBody(), + ); + } + + Widget _buildBody() { + if (_isLoading) { + return const Center( + child: CircularProgressIndicator(color: Colors.orange), + ); + } + + if (_error != null) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.error_outline, size: 48, color: Colors.red.shade400), + const SizedBox(height: 16), + Text( + _error!, + style: TextStyle(color: Colors.grey.shade400), + textAlign: TextAlign.center, + ), + const SizedBox(height: 16), + ElevatedButton( + onPressed: _loadConversations, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.orange.shade700, + ), + child: const Text('Retry'), + ), + ], + ), + ); + } + + if (_conversations.isEmpty) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.chat_bubble_outline, size: 64, color: Colors.grey.shade700), + const SizedBox(height: 16), + Text( + 'No conversations yet', + style: TextStyle( + color: Colors.grey.shade400, + fontSize: 18, + ), + ), + const SizedBox(height: 8), + Text( + 'Start a new chat to get started', + style: TextStyle( + color: Colors.grey.shade600, + fontSize: 14, + ), + ), + ], + ), + ); + } + + return RefreshIndicator( + onRefresh: _loadConversations, + color: Colors.orange, + child: ListView.builder( + padding: const EdgeInsets.symmetric(vertical: 8), + itemCount: _conversations.length, + itemBuilder: (context, index) { + final conv = _conversations[index]; + return Dismissible( + key: Key(conv.id), + direction: DismissDirection.endToStart, + background: Container( + alignment: Alignment.centerRight, + padding: const EdgeInsets.only(right: 20), + color: Colors.red.shade700, + child: const Icon(Icons.delete, color: Colors.white), + ), + confirmDismiss: (_) async { + return await showDialog( + context: context, + builder: (context) => AlertDialog( + backgroundColor: const Color(0xFF2D2D2D), + title: const Text( + 'Delete Conversation?', + style: TextStyle(color: Colors.white), + ), + content: const Text( + 'This action cannot be undone.', + style: TextStyle(color: Colors.white70), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + style: TextButton.styleFrom( + foregroundColor: Colors.red.shade400, + ), + child: const Text('Delete'), + ), + ], + ), + ); + }, + onDismissed: (_) => _deleteConversation(conv.id), + child: ListTile( + leading: CircleAvatar( + backgroundColor: const Color(0xFF3D3D3D), + child: Icon( + _getTitleIcon(conv.displayTitle), + color: Colors.orange.shade400, + size: 20, + ), + ), + title: Text( + conv.displayTitle, + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.w500, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text( + '${conv.timeAgo} • ${conv.messageCount} messages', + style: TextStyle( + color: Colors.grey.shade500, + fontSize: 12, + ), + ), + trailing: Icon( + Icons.chevron_right, + color: Colors.grey.shade600, + ), + onTap: () { + widget.onSelectConversation(conv.id); + Navigator.pop(context); + }, + ), + ); + }, + ), + ); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/screens/login_screen.dart b/apps/captain-mobile-v2/flutter/lib/screens/login_screen.dart new file mode 100644 index 0000000..df8dbc9 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/screens/login_screen.dart @@ -0,0 +1,193 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../providers/auth_provider.dart'; + +class LoginScreen extends StatefulWidget { + const LoginScreen({super.key}); + + @override + State createState() => _LoginScreenState(); +} + +class _LoginScreenState extends State { + final _usernameController = TextEditingController(); + final _passwordController = TextEditingController(); + bool _obscurePassword = true; + + @override + void dispose() { + _usernameController.dispose(); + _passwordController.dispose(); + super.dispose(); + } + + Future _login() async { + final username = _usernameController.text.trim(); + final password = _passwordController.text; + + if (username.isEmpty || password.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please enter username and password'), + backgroundColor: Colors.orange, + ), + ); + return; + } + + final auth = context.read(); + await auth.login(username, password); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF1A1A1A), + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: 60), + // Logo + Icon( + Icons.auto_awesome, + size: 80, + color: Colors.orange.shade400, + ), + const SizedBox(height: 24), + // Title + const Text( + 'Captain Claude', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontSize: 32, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Text( + 'Your AI Command Center', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.grey.shade400, + fontSize: 16, + ), + ), + const SizedBox(height: 60), + // Username field + TextField( + controller: _usernameController, + style: const TextStyle(color: Colors.white), + decoration: InputDecoration( + labelText: 'Username', + labelStyle: TextStyle(color: Colors.grey.shade400), + prefixIcon: Icon(Icons.person, color: Colors.grey.shade400), + filled: true, + fillColor: const Color(0xFF2D2D2D), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide.none, + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: Colors.orange.shade400), + ), + ), + ), + const SizedBox(height: 16), + // Password field + TextField( + controller: _passwordController, + obscureText: _obscurePassword, + style: const TextStyle(color: Colors.white), + decoration: InputDecoration( + labelText: 'Password', + labelStyle: TextStyle(color: Colors.grey.shade400), + prefixIcon: Icon(Icons.lock, color: Colors.grey.shade400), + suffixIcon: IconButton( + icon: Icon( + _obscurePassword + ? Icons.visibility_off + : Icons.visibility, + color: Colors.grey.shade400, + ), + onPressed: () { + setState(() => _obscurePassword = !_obscurePassword); + }, + ), + filled: true, + fillColor: const Color(0xFF2D2D2D), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide.none, + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: Colors.orange.shade400), + ), + ), + onSubmitted: (_) => _login(), + ), + const SizedBox(height: 24), + // Error message + Consumer( + builder: (context, auth, _) { + if (auth.error != null) { + return Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Text( + auth.error!, + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.red.shade400, + fontSize: 14, + ), + ), + ); + } + return const SizedBox.shrink(); + }, + ), + // Login button + Consumer( + builder: (context, auth, _) { + return ElevatedButton( + onPressed: auth.isLoading ? null : _login, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.orange.shade700, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(vertical: 16), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + disabledBackgroundColor: Colors.grey.shade800, + ), + child: auth.isLoading + ? const SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : const Text( + 'Sign In', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + ); + }, + ), + ], + ), + ), + ), + ); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/services/api_service.dart b/apps/captain-mobile-v2/flutter/lib/services/api_service.dart new file mode 100644 index 0000000..c6f99ce --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/services/api_service.dart @@ -0,0 +1,55 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; +import '../config/api_config.dart'; +import '../models/conversation.dart'; +import '../models/message.dart'; + +class ApiService { + String? _token; + + void setToken(String? token) { + _token = token; + } + + Map get _headers => { + 'Content-Type': 'application/json', + if (_token != null) 'Authorization': 'Bearer $_token', + }; + + Future> getConversations() async { + final response = await http.get( + Uri.parse('${ApiConfig.baseUrl}/conversations'), + headers: _headers, + ).timeout(ApiConfig.connectionTimeout); + + if (response.statusCode == 200) { + final List data = jsonDecode(response.body); + return data.map((e) => Conversation.fromJson(e)).toList(); + } + throw Exception('Failed to load conversations'); + } + + Future> getConversationMessages(String conversationId) async { + final response = await http.get( + Uri.parse('${ApiConfig.baseUrl}/conversations/$conversationId'), + headers: _headers, + ).timeout(ApiConfig.connectionTimeout); + + if (response.statusCode == 200) { + final List data = jsonDecode(response.body); + return data.map((e) => Message.fromJson(e)).toList(); + } + throw Exception('Failed to load messages'); + } + + Future deleteConversation(String conversationId) async { + final response = await http.delete( + Uri.parse('${ApiConfig.baseUrl}/conversations/$conversationId'), + headers: _headers, + ).timeout(ApiConfig.connectionTimeout); + + if (response.statusCode != 200) { + throw Exception('Failed to delete conversation'); + } + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/services/auth_service.dart b/apps/captain-mobile-v2/flutter/lib/services/auth_service.dart new file mode 100644 index 0000000..ecd5988 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/services/auth_service.dart @@ -0,0 +1,74 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; +import '../config/api_config.dart'; + +class AuthService { + static const String _tokenKey = 'auth_token'; + static const String _expiresKey = 'token_expires'; + static const String _usernameKey = 'username'; + + String? _token; + DateTime? _expiresAt; + String? _username; + + String? get token => _token; + String? get username => _username; + bool get isAuthenticated => _token != null && !isExpired; + bool get isExpired => + _expiresAt != null && DateTime.now().isAfter(_expiresAt!); + + Future loadStoredAuth() async { + final prefs = await SharedPreferences.getInstance(); + _token = prefs.getString(_tokenKey); + _username = prefs.getString(_usernameKey); + final expiresStr = prefs.getString(_expiresKey); + if (expiresStr != null) { + _expiresAt = DateTime.tryParse(expiresStr); + } + } + + String? lastError; + + Future login(String username, String password) async { + lastError = null; + try { + final response = await http.post( + Uri.parse('${ApiConfig.baseUrl}/auth/login'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({'username': username, 'password': password}), + ).timeout(ApiConfig.connectionTimeout); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + _token = data['token']; + _expiresAt = DateTime.parse(data['expires_at']); + _username = username; + + // Save to storage + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_tokenKey, _token!); + await prefs.setString(_expiresKey, _expiresAt!.toIso8601String()); + await prefs.setString(_usernameKey, _username!); + + return true; + } + lastError = 'Invalid credentials (${response.statusCode})'; + return false; + } catch (e) { + lastError = 'Connection error: $e'; + return false; + } + } + + Future logout() async { + _token = null; + _expiresAt = null; + _username = null; + + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_tokenKey); + await prefs.remove(_expiresKey); + await prefs.remove(_usernameKey); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/services/chat_service.dart b/apps/captain-mobile-v2/flutter/lib/services/chat_service.dart new file mode 100644 index 0000000..51e0abf --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/services/chat_service.dart @@ -0,0 +1,223 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:web_socket_channel/web_socket_channel.dart'; +import '../config/api_config.dart'; + +enum ChatConnectionState { + disconnected, + connecting, + connected, + reconnecting, + error, +} + +/// Chat session info (v3 - dynamic sessions) +class ChatSession { + final String sessionId; + final String name; + final String? createdAt; + + ChatSession({ + required this.sessionId, + required this.name, + this.createdAt, + }); + + factory ChatSession.fromJson(Map json) { + return ChatSession( + sessionId: json['session_id'] ?? '', + name: json['name'] ?? 'Session', + createdAt: json['created_at'], + ); + } +} + +/// Chat service that connects to Claude sessions (v3) +class ChatService { + WebSocketChannel? _channel; + String? _token; + + final _messagesController = StreamController>.broadcast(); + final _stateController = StreamController.broadcast(); + final _errorController = StreamController.broadcast(); + + ChatConnectionState _currentState = ChatConnectionState.disconnected; + int _reconnectAttempts = 0; + Timer? _reconnectTimer; + Timer? _pingTimer; + bool _intentionalDisconnect = false; + + Stream> get messages => _messagesController.stream; + Stream get connectionState => _stateController.stream; + Stream get errors => _errorController.stream; + ChatConnectionState get currentState => _currentState; + + void setToken(String? token) { + _token = token; + } + + void _setState(ChatConnectionState state) { + _currentState = state; + _stateController.add(state); + } + + Future connect() async { + if (_token == null) return; + if (_currentState == ChatConnectionState.connecting) return; + + _intentionalDisconnect = false; + _setState(ChatConnectionState.connecting); + + try { + _channel?.sink.close(); + _channel = WebSocketChannel.connect( + Uri.parse('${ApiConfig.wsUrl}/ws/chat'), + ); + + // Send auth token immediately + _channel!.sink.add(jsonEncode({'token': _token})); + + _channel!.stream.listen( + (data) { + try { + final message = jsonDecode(data); + _handleMessage(message); + } catch (e) { + _errorController.add('Failed to parse message: $e'); + } + }, + onError: (error) { + _errorController.add('WebSocket error: $error'); + _setState(ChatConnectionState.error); + if (!_intentionalDisconnect) { + _scheduleReconnect(); + } + }, + onDone: () { + _setState(ChatConnectionState.disconnected); + if (!_intentionalDisconnect) { + _scheduleReconnect(); + } + }, + cancelOnError: false, + ); + } catch (e) { + _errorController.add('Connection failed: $e'); + _setState(ChatConnectionState.error); + if (!_intentionalDisconnect) { + _scheduleReconnect(); + } + } + } + + void _handleMessage(Map message) { + final type = message['type']; + + switch (type) { + case 'init': + // Initial state with sessions list + _setState(ChatConnectionState.connected); + _reconnectAttempts = 0; + _startPingTimer(); + _messagesController.add(message); + break; + + case 'error': + final errorMsg = message['message'] ?? message['content'] ?? 'Unknown error'; + _errorController.add(errorMsg); + break; + + case 'pong': + break; + + default: + // Forward all other messages (output, done, session_connected, etc.) + _messagesController.add(message); + } + } + + void _startPingTimer() { + _pingTimer?.cancel(); + _pingTimer = Timer.periodic(const Duration(seconds: 30), (_) { + if (_currentState == ChatConnectionState.connected) { + sendRaw({'type': 'ping'}); + } + }); + } + + void _scheduleReconnect() { + if (_intentionalDisconnect) return; + if (_reconnectAttempts >= ApiConfig.maxReconnectAttempts) { + _errorController.add('Max reconnection attempts reached'); + return; + } + + _reconnectTimer?.cancel(); + final delay = Duration( + seconds: ApiConfig.reconnectDelay.inSeconds * (1 << _reconnectAttempts), + ); + _reconnectAttempts++; + _setState(ChatConnectionState.reconnecting); + + _reconnectTimer = Timer(delay, () { + if (_token != null && !_intentionalDisconnect) { + connect(); + } + }); + } + + /// Create a new chat session + void createSession(String name) { + sendRaw({ + 'type': 'create_session', + 'name': name, + }); + } + + /// Connect to an existing session by session_id + void connectToSession(String sessionId) { + sendRaw({ + 'type': 'connect_session', + 'session_id': sessionId, + }); + } + + /// Send message to connected session + void sendMessage(String content) { + if (_currentState != ChatConnectionState.connected) { + _errorController.add('Not connected'); + return; + } + + sendRaw({ + 'type': 'message', + 'content': content, + }); + } + + /// Request sessions list + void listSessions() { + sendRaw({'type': 'list_sessions'}); + } + + void sendRaw(Map data) { + if (_channel != null) { + _channel!.sink.add(jsonEncode(data)); + } + } + + void disconnect() { + _intentionalDisconnect = true; + _pingTimer?.cancel(); + _reconnectTimer?.cancel(); + _channel?.sink.close(); + _setState(ChatConnectionState.disconnected); + } + + void dispose() { + disconnect(); + _messagesController.close(); + _stateController.close(); + _errorController.close(); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/widgets/chat_input.dart b/apps/captain-mobile-v2/flutter/lib/widgets/chat_input.dart new file mode 100644 index 0000000..28c12bc --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/widgets/chat_input.dart @@ -0,0 +1,128 @@ +import 'package:flutter/material.dart'; + +class ChatInput extends StatefulWidget { + final Function(String) onSend; + final bool isConnected; + final bool isLoading; + + const ChatInput({ + super.key, + required this.onSend, + this.isConnected = true, + this.isLoading = false, + }); + + @override + State createState() => _ChatInputState(); +} + +class _ChatInputState extends State { + final _controller = TextEditingController(); + final _focusNode = FocusNode(); + + bool get _canSend => + widget.isConnected && + !widget.isLoading && + _controller.text.trim().isNotEmpty; + + void _send() { + if (!_canSend) return; + + final text = _controller.text.trim(); + _controller.clear(); + widget.onSend(text); + } + + @override + void dispose() { + _controller.dispose(); + _focusNode.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: EdgeInsets.only( + left: 12, + right: 12, + top: 8, + bottom: MediaQuery.of(context).padding.bottom + 8, + ), + decoration: BoxDecoration( + color: const Color(0xFF1A1A1A), + border: Border( + top: BorderSide(color: Colors.grey.shade800), + ), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + // Input field + Expanded( + child: Container( + constraints: const BoxConstraints(maxHeight: 120), + decoration: BoxDecoration( + color: const Color(0xFF2D2D2D), + borderRadius: BorderRadius.circular(24), + border: Border.all( + color: widget.isConnected + ? Colors.grey.shade700 + : Colors.red.shade700, + ), + ), + child: TextField( + controller: _controller, + focusNode: _focusNode, + maxLines: null, + textInputAction: TextInputAction.newline, + onChanged: (_) => setState(() {}), + style: const TextStyle( + color: Colors.white, + fontSize: 15, + ), + decoration: InputDecoration( + hintText: widget.isConnected + ? 'Message Claude...' + : 'Disconnected', + hintStyle: TextStyle( + color: Colors.grey.shade500, + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + border: InputBorder.none, + ), + ), + ), + ), + const SizedBox(width: 8), + // Send button + Container( + decoration: BoxDecoration( + color: _canSend ? Colors.orange.shade700 : Colors.grey.shade800, + shape: BoxShape.circle, + ), + child: IconButton( + onPressed: _canSend ? _send : null, + icon: widget.isLoading + ? SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.grey.shade400, + ), + ) + : Icon( + Icons.send, + color: _canSend ? Colors.white : Colors.grey.shade600, + ), + ), + ), + ], + ), + ); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/widgets/code_block.dart b/apps/captain-mobile-v2/flutter/lib/widgets/code_block.dart new file mode 100644 index 0000000..015a51e --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/widgets/code_block.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_highlight/flutter_highlight.dart'; +import 'package:flutter_highlight/themes/atom-one-dark.dart'; + +class CodeBlock extends StatelessWidget { + final String code; + final String? language; + + const CodeBlock({ + super.key, + required this.code, + this.language, + }); + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.symmetric(vertical: 8), + decoration: BoxDecoration( + color: const Color(0xFF282C34), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey.shade800), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Header with language and copy button + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: Colors.grey.shade900, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(8), + topRight: Radius.circular(8), + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + language ?? 'code', + style: TextStyle( + color: Colors.grey.shade500, + fontSize: 12, + ), + ), + InkWell( + onTap: () { + Clipboard.setData(ClipboardData(text: code)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Copied to clipboard'), + duration: Duration(seconds: 1), + ), + ); + }, + child: Icon( + Icons.copy, + size: 16, + color: Colors.grey.shade500, + ), + ), + ], + ), + ), + // Code content + Padding( + padding: const EdgeInsets.all(12), + child: HighlightView( + code, + language: language ?? 'plaintext', + theme: atomOneDarkTheme, + textStyle: const TextStyle( + fontFamily: 'JetBrainsMono', + fontSize: 13, + ), + ), + ), + ], + ), + ); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/widgets/message_bubble.dart b/apps/captain-mobile-v2/flutter/lib/widgets/message_bubble.dart new file mode 100644 index 0000000..7deb285 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/widgets/message_bubble.dart @@ -0,0 +1,195 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_markdown/flutter_markdown.dart'; +import '../models/message.dart'; +import 'code_block.dart'; +import 'tool_use_card.dart'; +import 'thinking_indicator.dart'; + +class MessageBubble extends StatelessWidget { + final Message message; + + const MessageBubble({super.key, required this.message}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: message.isUser ? _buildUserBubble() : _buildAssistantBubble(), + ); + } + + Widget _buildUserBubble() { + return Row( + mainAxisAlignment: MainAxisAlignment.end, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(width: 48), // Spacing for alignment + Flexible( + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.orange.shade700, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(16), + topRight: Radius.circular(16), + bottomLeft: Radius.circular(16), + bottomRight: Radius.circular(4), + ), + ), + child: Text( + message.content, + style: const TextStyle( + color: Colors.white, + fontSize: 15, + ), + ), + ), + ), + const SizedBox(width: 8), + CircleAvatar( + radius: 16, + backgroundColor: Colors.orange.shade800, + child: const Icon(Icons.person, size: 18, color: Colors.white), + ), + ], + ); + } + + Widget _buildAssistantBubble() { + return Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CircleAvatar( + radius: 16, + backgroundColor: const Color(0xFF2D2D2D), + child: Icon(Icons.auto_awesome, size: 18, color: Colors.orange.shade400), + ), + const SizedBox(width: 8), + Flexible( + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFF2D2D2D), + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(4), + topRight: Radius.circular(16), + bottomLeft: Radius.circular(16), + bottomRight: Radius.circular(16), + ), + ), + child: _buildContent(), + ), + ), + const SizedBox(width: 48), // Spacing for alignment + ], + ); + } + + Widget _buildContent() { + if (message.isThinking && message.content.isEmpty) { + return const ThinkingIndicator(); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Tool uses first + if (message.toolUses != null && message.toolUses!.isNotEmpty) + ...message.toolUses!.map((tool) => ToolUseCard(toolUse: tool)), + // Then the text content with Markdown + if (message.content.isNotEmpty) + MarkdownBody( + data: message.content, + selectable: true, + styleSheet: MarkdownStyleSheet( + p: const TextStyle( + color: Colors.white, + fontSize: 15, + height: 1.5, + ), + h1: const TextStyle( + color: Colors.white, + fontSize: 22, + fontWeight: FontWeight.bold, + ), + h2: const TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold, + ), + h3: const TextStyle( + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.bold, + ), + code: TextStyle( + color: Colors.orange.shade300, + backgroundColor: Colors.black26, + fontFamily: 'JetBrainsMono', + fontSize: 13, + ), + codeblockDecoration: BoxDecoration( + color: const Color(0xFF282C34), + borderRadius: BorderRadius.circular(8), + ), + blockquote: const TextStyle( + color: Colors.white70, + fontStyle: FontStyle.italic, + ), + blockquoteDecoration: BoxDecoration( + border: Border( + left: BorderSide(color: Colors.orange.shade400, width: 3), + ), + ), + listBullet: const TextStyle(color: Colors.white70), + a: TextStyle(color: Colors.orange.shade300), + ), + builders: { + 'code': _CodeBlockBuilder(), + }, + ), + // Streaming indicator + if (message.isStreaming && !message.isThinking) + Padding( + padding: const EdgeInsets.only(top: 8), + child: SizedBox( + width: 12, + height: 12, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.orange.shade400, + ), + ), + ), + ], + ); + } +} + +class _CodeBlockBuilder extends MarkdownElementBuilder { + @override + Widget? visitElementAfter(element, preferredStyle) { + // Check if it's a fenced code block + final content = element.textContent; + String? language; + + // Try to detect language from class attribute + if (element.attributes.containsKey('class')) { + final classes = element.attributes['class']!; + if (classes.startsWith('language-')) { + language = classes.substring(9); + } + } + + // For inline code, use default style + if (!content.contains('\n') && content.length < 50) { + return null; // Use default styling + } + + return CodeBlock( + code: content, + language: language, + ); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/widgets/thinking_indicator.dart b/apps/captain-mobile-v2/flutter/lib/widgets/thinking_indicator.dart new file mode 100644 index 0000000..5a1e0ce --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/widgets/thinking_indicator.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; + +class ThinkingIndicator extends StatefulWidget { + const ThinkingIndicator({super.key}); + + @override + State createState() => _ThinkingIndicatorState(); +} + +class _ThinkingIndicatorState extends State + with SingleTickerProviderStateMixin { + late AnimationController _controller; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1500), + )..repeat(); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + AnimatedBuilder( + animation: _controller, + builder: (context, child) { + return Row( + children: List.generate(3, (index) { + final delay = index * 0.2; + final value = (_controller.value + delay) % 1.0; + final opacity = (value < 0.5 ? value * 2 : 2 - value * 2); + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 2), + child: Opacity( + opacity: 0.3 + opacity * 0.7, + child: Container( + width: 8, + height: 8, + decoration: BoxDecoration( + color: Colors.orange.shade400, + shape: BoxShape.circle, + ), + ), + ), + ); + }), + ); + }, + ), + const SizedBox(width: 8), + Text( + 'Claude is thinking...', + style: TextStyle( + color: Colors.grey.shade400, + fontSize: 14, + fontStyle: FontStyle.italic, + ), + ), + ], + ), + ); + } +} diff --git a/apps/captain-mobile-v2/flutter/lib/widgets/tool_use_card.dart b/apps/captain-mobile-v2/flutter/lib/widgets/tool_use_card.dart new file mode 100644 index 0000000..7f817f9 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/lib/widgets/tool_use_card.dart @@ -0,0 +1,165 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import '../models/message.dart'; + +class ToolUseCard extends StatefulWidget { + final ToolUse toolUse; + + const ToolUseCard({super.key, required this.toolUse}); + + @override + State createState() => _ToolUseCardState(); +} + +class _ToolUseCardState extends State { + bool _isExpanded = false; + + IconData get _toolIcon { + switch (widget.toolUse.tool.toLowerCase()) { + case 'bash': + return Icons.terminal; + case 'read': + return Icons.description; + case 'write': + case 'edit': + return Icons.edit_document; + case 'grep': + case 'glob': + return Icons.search; + default: + return Icons.build; + } + } + + String get _inputDisplay { + final input = widget.toolUse.input; + if (input == null) return ''; + if (input is String) return input; + if (input is Map) { + // For Bash tool, show command + if (input.containsKey('command')) { + return input['command']; + } + // For Read tool, show file path + if (input.containsKey('file_path')) { + return input['file_path']; + } + // Otherwise show JSON + try { + return const JsonEncoder.withIndent(' ').convert(input); + } catch (_) { + return input.toString(); + } + } + return input.toString(); + } + + @override + Widget build(BuildContext context) { + final hasOutput = widget.toolUse.output != null && + widget.toolUse.output!.isNotEmpty; + + return Container( + margin: const EdgeInsets.symmetric(vertical: 4), + decoration: BoxDecoration( + color: const Color(0xFF2D2D2D), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.orange.shade700.withOpacity(0.3)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Header + InkWell( + onTap: hasOutput + ? () => setState(() => _isExpanded = !_isExpanded) + : null, + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + Icon(_toolIcon, size: 18, color: Colors.orange.shade400), + const SizedBox(width: 8), + Text( + widget.toolUse.tool, + style: TextStyle( + color: Colors.orange.shade400, + fontWeight: FontWeight.bold, + fontSize: 13, + ), + ), + const Spacer(), + if (hasOutput) + Icon( + _isExpanded ? Icons.expand_less : Icons.expand_more, + color: Colors.grey.shade500, + size: 20, + ), + if (!hasOutput && widget.toolUse.output == null) + SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.orange.shade400, + ), + ), + ], + ), + ), + ), + // Input/Command + if (_inputDisplay.isNotEmpty) + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.black.withOpacity(0.2), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '▶', + style: TextStyle( + color: Colors.green.shade400, + fontFamily: 'JetBrainsMono', + fontSize: 12, + ), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + _inputDisplay, + style: const TextStyle( + color: Colors.white70, + fontFamily: 'JetBrainsMono', + fontSize: 12, + ), + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + // Output (collapsible) + if (_isExpanded && hasOutput) + Container( + constraints: const BoxConstraints(maxHeight: 200), + padding: const EdgeInsets.all(12), + child: SingleChildScrollView( + child: Text( + widget.toolUse.output!, + style: const TextStyle( + color: Colors.white60, + fontFamily: 'JetBrainsMono', + fontSize: 11, + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/apps/captain-mobile-v2/flutter/linux/.gitignore b/apps/captain-mobile-v2/flutter/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/apps/captain-mobile-v2/flutter/linux/CMakeLists.txt b/apps/captain-mobile-v2/flutter/linux/CMakeLists.txt new file mode 100644 index 0000000..6d8996f --- /dev/null +++ b/apps/captain-mobile-v2/flutter/linux/CMakeLists.txt @@ -0,0 +1,145 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "captain_mobile_v2") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.tzzr.captain_mobile_v2") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Define the application target. To change its name, change BINARY_NAME above, +# not the value here, or `flutter run` will no longer work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/apps/captain-mobile-v2/flutter/linux/flutter/CMakeLists.txt b/apps/captain-mobile-v2/flutter/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/apps/captain-mobile-v2/flutter/linux/flutter/generated_plugin_registrant.cc b/apps/captain-mobile-v2/flutter/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/apps/captain-mobile-v2/flutter/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/apps/captain-mobile-v2/flutter/linux/flutter/generated_plugin_registrant.h b/apps/captain-mobile-v2/flutter/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/apps/captain-mobile-v2/flutter/linux/flutter/generated_plugins.cmake b/apps/captain-mobile-v2/flutter/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2e1de87 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/linux/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/apps/captain-mobile-v2/flutter/linux/main.cc b/apps/captain-mobile-v2/flutter/linux/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/linux/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/apps/captain-mobile-v2/flutter/linux/my_application.cc b/apps/captain-mobile-v2/flutter/linux/my_application.cc new file mode 100644 index 0000000..d761c69 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/linux/my_application.cc @@ -0,0 +1,124 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "captain_mobile_v2"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "captain_mobile_v2"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/apps/captain-mobile-v2/flutter/linux/my_application.h b/apps/captain-mobile-v2/flutter/linux/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/linux/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/apps/captain-mobile-v2/flutter/macos/.gitignore b/apps/captain-mobile-v2/flutter/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/apps/captain-mobile-v2/flutter/macos/Flutter/Flutter-Debug.xcconfig b/apps/captain-mobile-v2/flutter/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/apps/captain-mobile-v2/flutter/macos/Flutter/Flutter-Release.xcconfig b/apps/captain-mobile-v2/flutter/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/apps/captain-mobile-v2/flutter/macos/Flutter/GeneratedPluginRegistrant.swift b/apps/captain-mobile-v2/flutter/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..b8e2b22 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import path_provider_foundation +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) +} diff --git a/apps/captain-mobile-v2/flutter/macos/Runner.xcodeproj/project.pbxproj b/apps/captain-mobile-v2/flutter/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..101008f --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* captain_mobile_v2.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "captain_mobile_v2.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* captain_mobile_v2.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* captain_mobile_v2.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/captain_mobile_v2.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/captain_mobile_v2"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/captain_mobile_v2.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/captain_mobile_v2"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/captain_mobile_v2.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/captain_mobile_v2"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/apps/captain-mobile-v2/flutter/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/apps/captain-mobile-v2/flutter/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/apps/captain-mobile-v2/flutter/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/apps/captain-mobile-v2/flutter/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..c71b11c --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/macos/Runner.xcworkspace/contents.xcworkspacedata b/apps/captain-mobile-v2/flutter/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/apps/captain-mobile-v2/flutter/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/apps/captain-mobile-v2/flutter/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/AppDelegate.swift b/apps/captain-mobile-v2/flutter/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..8e02df2 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/AppDelegate.swift @@ -0,0 +1,9 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } +} diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/apps/captain-mobile-v2/flutter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Base.lproj/MainMenu.xib b/apps/captain-mobile-v2/flutter/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Configs/AppInfo.xcconfig b/apps/captain-mobile-v2/flutter/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..3f588ae --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = captain_mobile_v2 + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.tzzr.captainMobileV2 + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.tzzr. All rights reserved. diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Configs/Debug.xcconfig b/apps/captain-mobile-v2/flutter/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Configs/Release.xcconfig b/apps/captain-mobile-v2/flutter/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Configs/Warnings.xcconfig b/apps/captain-mobile-v2/flutter/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/DebugProfile.entitlements b/apps/captain-mobile-v2/flutter/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Info.plist b/apps/captain-mobile-v2/flutter/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/MainFlutterWindow.swift b/apps/captain-mobile-v2/flutter/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/apps/captain-mobile-v2/flutter/macos/Runner/Release.entitlements b/apps/captain-mobile-v2/flutter/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/apps/captain-mobile-v2/flutter/macos/RunnerTests/RunnerTests.swift b/apps/captain-mobile-v2/flutter/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/apps/captain-mobile-v2/flutter/pubspec.lock b/apps/captain-mobile-v2/flutter/pubspec.lock new file mode 100644 index 0000000..a8266e5 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/pubspec.lock @@ -0,0 +1,474 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + clock: + dependency: transitive + description: + name: clock + sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + url: "https://pub.dev" + source: hosted + version: "1.1.1" + collection: + dependency: transitive + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + ffi: + dependency: transitive + description: + name: ffi + sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_highlight: + dependency: "direct main" + description: + name: flutter_highlight + sha256: "7b96333867aa07e122e245c033b8ad622e4e3a42a1a2372cbb098a2541d8782c" + url: "https://pub.dev" + source: hosted + version: "0.7.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + flutter_markdown: + dependency: "direct main" + description: + name: flutter_markdown + sha256: "04c4722cc36ec5af38acc38ece70d22d3c2123c61305d555750a091517bbe504" + url: "https://pub.dev" + source: hosted + version: "0.6.23" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + google_fonts: + dependency: "direct main" + description: + name: google_fonts + sha256: df9763500dadba0155373e9cb44e202ce21bd9ed5de6bdbd05c5854e86839cb8 + url: "https://pub.dev" + source: hosted + version: "6.3.0" + highlight: + dependency: "direct main" + description: + name: highlight + sha256: "5353a83ffe3e3eca7df0abfb72dcf3fa66cc56b953728e7113ad4ad88497cf21" + url: "https://pub.dev" + source: hosted + version: "0.7.0" + http: + dependency: "direct main" + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05" + url: "https://pub.dev" + source: hosted + version: "10.0.5" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806" + url: "https://pub.dev" + source: hosted + version: "3.0.5" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + lints: + dependency: transitive + description: + name: lints + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + markdown: + dependency: transitive + description: + name: markdown + sha256: "935e23e1ff3bc02d390bad4d4be001208ee92cc217cb5b5a6c19bc14aaa318c1" + url: "https://pub.dev" + source: hosted + version: "7.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb + url: "https://pub.dev" + source: hosted + version: "0.12.16+1" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 + url: "https://pub.dev" + source: hosted + version: "1.15.0" + nested: + dependency: transitive + description: + name: nested + sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + path: + dependency: transitive + description: + name: path + sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" + url: "https://pub.dev" + source: hosted + version: "1.9.0" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "4adf4fd5423ec60a29506c76581bc05854c55e3a0b72d35bb28d661c9686edf2" + url: "https://pub.dev" + source: hosted + version: "2.2.15" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + provider: + dependency: "direct main" + description: + name: provider + sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272" + url: "https://pub.dev" + source: hosted + version: "6.1.5+1" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + url: "https://pub.dev" + source: hosted + version: "2.5.3" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "9f9f3d372d4304723e6136663bb291c0b93f5e4c8a4a6314347f481a33bda2b1" + url: "https://pub.dev" + source: hosted + version: "2.4.7" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb" + url: "https://pub.dev" + source: hosted + version: "0.7.2" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d" + url: "https://pub.dev" + source: hosted + version: "14.2.5" + web: + dependency: transitive + description: + name: web + sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27" + url: "https://pub.dev" + source: hosted + version: "0.5.1" + web_socket_channel: + dependency: "direct main" + description: + name: web_socket_channel + sha256: "58c6666b342a38816b2e7e50ed0f1e261959630becd4c879c4f26bfa14aa5a42" + url: "https://pub.dev" + source: hosted + version: "2.4.5" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" +sdks: + dart: ">=3.5.4 <4.0.0" + flutter: ">=3.24.0" diff --git a/apps/captain-mobile-v2/flutter/pubspec.yaml b/apps/captain-mobile-v2/flutter/pubspec.yaml new file mode 100644 index 0000000..f62e66a --- /dev/null +++ b/apps/captain-mobile-v2/flutter/pubspec.yaml @@ -0,0 +1,45 @@ +name: captain_mobile_v2 +description: "Captain Claude Mobile - Chat with Claude" +publish_to: 'none' +version: 2.0.0+1 + +environment: + sdk: ^3.5.4 + +dependencies: + flutter: + sdk: flutter + cupertino_icons: ^1.0.8 + + # State management + provider: ^6.1.1 + + # Networking + web_socket_channel: ^2.4.0 + http: ^1.2.0 + + # Markdown rendering + flutter_markdown: ^0.6.18 + + # Syntax highlighting + flutter_highlight: ^0.7.0 + highlight: ^0.7.0 + + # Storage + shared_preferences: ^2.2.2 + + # UI helpers + google_fonts: ^6.1.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^4.0.0 + +flutter: + uses-material-design: true + + fonts: + - family: JetBrainsMono + fonts: + - asset: assets/fonts/JetBrainsMono-Regular.ttf diff --git a/apps/captain-mobile-v2/flutter/test/widget_test.dart b/apps/captain-mobile-v2/flutter/test/widget_test.dart new file mode 100644 index 0000000..379f0ef --- /dev/null +++ b/apps/captain-mobile-v2/flutter/test/widget_test.dart @@ -0,0 +1,30 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:captain_mobile_v2/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +} diff --git a/apps/captain-mobile-v2/flutter/web/favicon.png b/apps/captain-mobile-v2/flutter/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/apps/captain-mobile-v2/flutter/web/favicon.png differ diff --git a/apps/captain-mobile-v2/flutter/web/icons/Icon-192.png b/apps/captain-mobile-v2/flutter/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/apps/captain-mobile-v2/flutter/web/icons/Icon-192.png differ diff --git a/apps/captain-mobile-v2/flutter/web/icons/Icon-512.png b/apps/captain-mobile-v2/flutter/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/web/icons/Icon-512.png differ diff --git a/apps/captain-mobile-v2/flutter/web/icons/Icon-maskable-192.png b/apps/captain-mobile-v2/flutter/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/web/icons/Icon-maskable-192.png differ diff --git a/apps/captain-mobile-v2/flutter/web/icons/Icon-maskable-512.png b/apps/captain-mobile-v2/flutter/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/apps/captain-mobile-v2/flutter/web/icons/Icon-maskable-512.png differ diff --git a/apps/captain-mobile-v2/flutter/web/index.html b/apps/captain-mobile-v2/flutter/web/index.html new file mode 100644 index 0000000..3239cc4 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + captain_mobile_v2 + + + + + + diff --git a/apps/captain-mobile-v2/flutter/web/manifest.json b/apps/captain-mobile-v2/flutter/web/manifest.json new file mode 100644 index 0000000..1d04dd4 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "captain_mobile_v2", + "short_name": "captain_mobile_v2", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/apps/captain-mobile-v2/flutter/windows/.gitignore b/apps/captain-mobile-v2/flutter/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/apps/captain-mobile-v2/flutter/windows/CMakeLists.txt b/apps/captain-mobile-v2/flutter/windows/CMakeLists.txt new file mode 100644 index 0000000..ed3030e --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(captain_mobile_v2 LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "captain_mobile_v2") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/apps/captain-mobile-v2/flutter/windows/flutter/CMakeLists.txt b/apps/captain-mobile-v2/flutter/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/apps/captain-mobile-v2/flutter/windows/flutter/generated_plugin_registrant.cc b/apps/captain-mobile-v2/flutter/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/apps/captain-mobile-v2/flutter/windows/flutter/generated_plugin_registrant.h b/apps/captain-mobile-v2/flutter/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/apps/captain-mobile-v2/flutter/windows/flutter/generated_plugins.cmake b/apps/captain-mobile-v2/flutter/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b93c4c3 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/apps/captain-mobile-v2/flutter/windows/runner/CMakeLists.txt b/apps/captain-mobile-v2/flutter/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/apps/captain-mobile-v2/flutter/windows/runner/Runner.rc b/apps/captain-mobile-v2/flutter/windows/runner/Runner.rc new file mode 100644 index 0000000..cc1412d --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.tzzr" "\0" + VALUE "FileDescription", "captain_mobile_v2" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "captain_mobile_v2" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.tzzr. All rights reserved." "\0" + VALUE "OriginalFilename", "captain_mobile_v2.exe" "\0" + VALUE "ProductName", "captain_mobile_v2" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/apps/captain-mobile-v2/flutter/windows/runner/flutter_window.cpp b/apps/captain-mobile-v2/flutter/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/apps/captain-mobile-v2/flutter/windows/runner/flutter_window.h b/apps/captain-mobile-v2/flutter/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/apps/captain-mobile-v2/flutter/windows/runner/main.cpp b/apps/captain-mobile-v2/flutter/windows/runner/main.cpp new file mode 100644 index 0000000..8f40b4e --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"captain_mobile_v2", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/apps/captain-mobile-v2/flutter/windows/runner/resource.h b/apps/captain-mobile-v2/flutter/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/apps/captain-mobile-v2/flutter/windows/runner/resources/app_icon.ico b/apps/captain-mobile-v2/flutter/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/apps/captain-mobile-v2/flutter/windows/runner/resources/app_icon.ico differ diff --git a/apps/captain-mobile-v2/flutter/windows/runner/runner.exe.manifest b/apps/captain-mobile-v2/flutter/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/apps/captain-mobile-v2/flutter/windows/runner/utils.cpp b/apps/captain-mobile-v2/flutter/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/apps/captain-mobile-v2/flutter/windows/runner/utils.h b/apps/captain-mobile-v2/flutter/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/apps/captain-mobile-v2/flutter/windows/runner/win32_window.cpp b/apps/captain-mobile-v2/flutter/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/apps/captain-mobile-v2/flutter/windows/runner/win32_window.h b/apps/captain-mobile-v2/flutter/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/apps/captain-mobile-v2/flutter/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/apps/captain-mobile/deploy.sh b/apps/captain-mobile/deploy.sh new file mode 100755 index 0000000..1b5b97d --- /dev/null +++ b/apps/captain-mobile/deploy.sh @@ -0,0 +1,147 @@ +#!/bin/bash +# =========================================== +# Captain Mobile - Deployment Script +# Ejecutar en ARCHITECT (69.62.126.110) +# =========================================== + +set -e +echo "🚀 Captain Mobile Deployment" +echo "============================" + +# Colores +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +# 1. Matar procesos colgados +echo -e "\n${YELLOW}[1/7] Limpiando procesos colgados...${NC}" +pkill -f "psql.*captain" 2>/dev/null || true +pkill -f "psql.*bypass" 2>/dev/null || true +echo -e "${GREEN}✓ Limpieza completada${NC}" + +# 2. Configurar PostgreSQL +echo -e "\n${YELLOW}[2/7] Configurando PostgreSQL...${NC}" +sudo -u postgres psql </dev/null) +if echo "$HEALTH" | grep -q '"status":"ok"'; then + echo -e "${GREEN}✓ API funcionando correctamente${NC}" + echo "$HEALTH" | python3 -m json.tool 2>/dev/null || echo "$HEALTH" +else + echo -e "${RED}✗ API no responde${NC}" + echo "Logs:" + sudo journalctl -u captain-api -n 30 --no-pager +fi + +# 6. Configurar Caddy +echo -e "\n${YELLOW}[6/7] Configurando Caddy...${NC}" +CADDY_CONFIG=" +captain.tzzrarchitect.me { + reverse_proxy localhost:3030 + + @websocket { + header Connection *Upgrade* + header Upgrade websocket + } + reverse_proxy @websocket localhost:3030 +} +" + +# Verificar si ya existe la config +if grep -q "captain.tzzrarchitect.me" /etc/caddy/Caddyfile 2>/dev/null; then + echo -e "${YELLOW}⚠ Config de Caddy ya existe${NC}" +else + echo "$CADDY_CONFIG" | sudo tee -a /etc/caddy/Caddyfile > /dev/null + sudo systemctl reload caddy + echo -e "${GREEN}✓ Caddy configurado${NC}" +fi + +# 7. Resumen DNS +echo -e "\n${YELLOW}[7/7] Configuración DNS requerida${NC}" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "Agregar en Cloudflare:" +echo " Tipo: A" +echo " Nombre: captain" +echo " Contenido: 69.62.126.110" +echo " Proxy: Activado (naranja)" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + +# Resumen final +echo -e "\n${GREEN}═══════════════════════════════════════${NC}" +echo -e "${GREEN} DEPLOYMENT COMPLETADO ${NC}" +echo -e "${GREEN}═══════════════════════════════════════${NC}" +echo "" +echo "📡 API Local: http://localhost:3030" +echo "🌐 API Pública: https://captain.tzzrarchitect.me" +echo "" +echo "Próximos pasos:" +echo "1. Configurar DNS en Cloudflare (si no está)" +echo "2. Crear repo en Gitea: git.tzzr.net/tzzr/captain-mobile" +echo "3. Build APK con Flutter" +echo "" +echo "Test rápido:" +echo " curl -X POST http://localhost:3030/auth/login \\" +echo " -H 'Content-Type: application/json' \\" +echo " -d '{\"username\":\"captain\",\"password\":\"tzzr2025\"}'" diff --git a/architect-frontend b/architect-frontend new file mode 160000 index 0000000..463ae90 --- /dev/null +++ b/architect-frontend @@ -0,0 +1 @@ +Subproject commit 463ae90364c42f5cc60e938c9b9e28976269836c diff --git a/auditoria_captain.md b/auditoria_captain.md new file mode 100644 index 0000000..978d841 --- /dev/null +++ b/auditoria_captain.md @@ -0,0 +1,198 @@ +# Auditoría Captain Mobile + +**Fecha:** 2026-01-16 +**Versión:** 1.0 + +--- + +## FASE 1: Análisis Inicial - COMPLETADO + +### A1 - Arquitecto Backend + +#### Endpoints Identificados +| Endpoint | Método | Auth | Función | +|----------|--------|------|---------| +| `/health` | GET | No | Health check | +| `/auth/login` | POST | No | Login, retorna JWT (7 días) | +| `/sessions` | GET | JWT | Lista screen sessions | +| `/sessions` | POST | JWT | Crea nueva sesión | +| `/history` | GET | JWT | Lista conversaciones | +| `/history/{id}` | GET | JWT | Mensajes de conversación | +| `/upload` | POST | JWT | Sube archivos | +| `/ws/chat` | WS | JWT | Chat streaming con Claude | +| `/ws/terminal/{name}` | WS | JWT | Terminal interactivo | + +#### PROBLEMAS CRÍTICOS BACKEND + +| # | Severidad | Problema | Línea | +|---|-----------|----------|-------| +| 1 | **CRÍTICA** | Command injection via session_name | 187-202 | +| 2 | **CRÍTICA** | Bare `except:` oculta errores | 300, 438 | +| 3 | **ALTA** | Race condition en creación sesión | 193-202 | +| 4 | **ALTA** | CORS `allow_origins=["*"]` | 60 | +| 5 | **ALTA** | File descriptor leak | 451-520 | +| 6 | **MEDIA** | Silent failures en WebSocket | 384, 486, 508 | +| 7 | **MEDIA** | Uploads nunca se limpian | 272-282 | +| 8 | **MEDIA** | process.terminate() sin wait | 521 | + +#### Detalle Command Injection +```python +name = "test'; screen -dmS pwned bash; echo '" +# Ejecuta: screen -dmS test'; screen -dmS pwned bash; echo ' /claude +``` + +--- + +### A2 - UX Frontend + +#### Estructura App +``` +lib/ +├── main.dart (MultiProvider + AuthWrapper) +├── screens/ (login, chat, sessions, terminal) +├── providers/ (auth, chat) +├── services/ (auth, api, chat, terminal) +├── models/ (message, user, session) +└── config/api_config.dart +``` + +#### PROBLEMAS CRÍTICOS FRONTEND + +| # | Severidad | Problema | Ubicación | +|---|-----------|----------|-----------| +| 1 | **CRÍTICA** | Comando en terminal desconectado falla silenciosamente | terminal_service.dart:76 | +| 2 | **CRÍTICA** | Sin reconexión automática en Terminal | - | +| 3 | **CRÍTICA** | Chat messages sin límite de memoria | chat_provider.dart:9 | +| 4 | **ALTA** | TerminalScreen no reconecta al volver de background | - | +| 5 | **ALTA** | Botones quick action siempre clickables | terminal_screen.dart:173 | +| 6 | **MEDIA** | Sin indicador de envío en chat | chat_screen.dart:227 | +| 7 | **MEDIA** | Error messages genéricos | sessions_screen.dart:40 | + +#### Botones Terminal Existentes +| Botón | Código | Estado | +|-------|--------|--------| +| Ctrl+C | `\x03` | ✓ Correcto | +| Ctrl+D | `\x04` | ✓ Correcto | +| Tab | `\t` | ✓ Correcto | +| Esc | `\x1b` | ✓ Correcto | +| Up | `\x1b[A` | ✓ Correcto | +| Down | `\x1b[B` | ✓ Correcto | + +**Problema:** Funcionan si hay conexión, pero fallan silenciosamente si no. + +--- + +### A3 - Explorador Endpoints (Tests Reales) + +| Endpoint | Resultado | Detalle | +|----------|-----------|---------| +| GET /health | ✅ PASS | `{"status":"ok"}` | +| POST /auth/login | ✅ PASS | Retorna JWT | +| GET /sessions | ✅ PASS | Lista 3 sesiones | +| POST /sessions | ❌ **FAIL** | "Session created but could not find PID" | +| Login incorrecto | ✅ PASS | 401 Invalid credentials | +| Sin token | ✅ PASS | 401 Not authenticated | +| Nombre duplicado | ✅ PASS | 409 Session already exists | +| Nombre vacío | ✅ PASS | 400 Invalid session name | + +#### BUG CRÍTICO ENCONTRADO +``` +POST /sessions → Retorna error "could not find PID" +screen -ls | grep test-audit → NO EXISTE + +La sesión screen NO SE CREA realmente. +El comando screen está fallando silenciosamente. +``` + +--- + +## RESUMEN FASE 1 + +### Bugs Bloqueantes (Impiden uso básico) +1. **POST /sessions no funciona** - No se pueden crear sesiones nuevas +2. **Command injection** - Vulnerabilidad de seguridad crítica + +### Bugs Críticos UX +3. **Terminal falla silenciosamente** - Usuario escribe y nada pasa +4. **Sin reconexión automática** - Terminal muere sin aviso +5. **Memory leak en chat** - Crash tras muchos mensajes + +### Bugs Mayores +6. CORS abierto a todos +7. File descriptor leaks +8. Uploads nunca se limpian +9. Botones siempre activos aunque desconectado + +--- + +## FASE 2: Escenarios de Uso +_Pendiente validación usuario..._ + +--- + +## FASE 3: Desarrollo +_Pendiente..._ + +--- + +## FASE 4: Auditoría Roles - Ronda 1 + +### QA Agresivo - 12 vulnerabilidades +- CRÍTICA: Sin rate-limit en chat (DoS posible) +- CRÍTICA: Sin límite de sesiones creadas +- CRÍTICA: File paths no validados en chat +- ALTA: Doble-click crea múltiples sesiones +- ALTA: Token expirado no se valida mid-stream + +### Seguridad - Vulnerabilidades +- CRÍTICA: JWT secret hardcoded en código +- CRÍTICA: Path traversal en upload filename +- ALTA: Command injection en WebSocket terminal session_name +- ALTA: Session list muestra TODAS las sesiones (no filtra por usuario) + +### Usuario Novato - 12 problemas UX +- ALTA: Botones deshabilitados casi invisibles +- ALTA: "Reconnecting..." sin progreso ni timeout visible +- ALTA: Errores técnicos sin traducir a lenguaje usuario +- ALTA: Botones quick action muy pequeños para móvil + +--- + +## FASE 5: Correcciones Aplicadas + +### Backend (captain_api.py) +1. ✅ Path correcto a claude (`/home/architect/.npm-global/bin/claude`) +2. ✅ CORS restringido (solo dominios específicos) +3. ✅ Sanitización session_name con regex (`[a-z0-9-]`) +4. ✅ JWT secret aleatorio si no configurado +5. ✅ Validación file paths (solo /tmp/captain-uploads) +6. ✅ Validación session_name en WebSocket terminal +7. ✅ Excepciones específicas en lugar de bare except + +### Frontend (Flutter) +1. ✅ Reconexión automática con backoff exponencial +2. ✅ Error controller para mostrar errores al usuario +3. ✅ sendInput() retorna bool indicando si se envió +4. ✅ Lifecycle observer para reconectar al volver de background +5. ✅ Botones deshabilitados con color diferenciado +6. ✅ Indicador de estado con texto (Connected/Reconnecting/Error) +7. ✅ Límite de 500 mensajes en chat (memory leak fix) + +--- + +## FASE 6: Compilación Final - COMPLETADA + +**APK:** `cloud.tzzrdeck.me` → `documentos adjuntos/captain-mobile.apk` +**Fecha:** 2026-01-16 +**Tamaño:** 23.8MB + +### Para activar cambios backend: +```bash +sudo systemctl restart captain-api +``` + +### Bugs pendientes (no críticos): +- Rate limiting en endpoints (requiere Redis/similar) +- Multi-usuario real (requiere refactor de auth) +- Certificate pinning en Flutter +- Más botones quick action (Left, Right, Home, End) diff --git a/deck-frontend/deck-v4.6.html b/deck-frontend/deck-v4.6.html index c549352..57811bb 100644 --- a/deck-frontend/deck-v4.6.html +++ b/deck-frontend/deck-v4.6.html @@ -814,7 +814,7 @@ body { // 0. LOCK SCREEN // ============================================================================= const Lock = { - PIN: "1234", // PIN code - can be changed + PIN: "1451", // PIN code - can be changed entered: "", init() { diff --git a/hst-frontend/index.html b/hst-frontend/index.html index 102f425..499659c 100644 --- a/hst-frontend/index.html +++ b/hst-frontend/index.html @@ -797,7 +797,7 @@ body { // 0. LOCK SCREEN // ============================================================================= const Lock = { - PIN: "1234", // PIN code - can be changed + PIN: "1451", // PIN code - can be changed entered: "", init() { diff --git a/screenlog.0 b/screenlog.0 new file mode 100644 index 0000000..e69de29