import asyncio import json import os import uuid from datetime import datetime from json import dumps from fastapi import Body, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import (FileResponse, HTMLResponse, JSONResponse, StreamingResponse) from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from loguru import logger import uvicorn import aiohttp app = FastAPI() OPENMANUS_ENDPOINT_URL = os.getenv("OPENMANUS_ENDPOINT_URL") if not OPENMANUS_ENDPOINT_URL: raise EnvironmentError("OPENMANUS_ENDPOINT_URL environment variable must be set") app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class Task(BaseModel): id: str prompt: str created_at: datetime status: str steps: list = [] def model_dump(self, *args, **kwargs): data = super().model_dump(*args, **kwargs) data["created_at"] = self.created_at.isoformat() return data class TaskManager: def __init__(self): self.tasks = {} self.queues = {} def create_task(self, prompt: str) -> Task: task_id = str(uuid.uuid4()) task = Task( id=task_id, prompt=prompt, created_at=datetime.now(), status="pending" ) self.tasks[task_id] = task self.queues[task_id] = asyncio.Queue() return task async def update_task_step(self, task_id: str, step: int, result: str, step_type: str = "step"): if task_id in self.tasks: task = self.tasks[task_id] task.steps.append({"step": step, "result": result, "type": step_type}) await self.queues[task_id].put({"type": step_type, "step": step, "result": result}) await self.queues[task_id].put({"type": "status", "status": task.status, "steps": task.steps}) async def complete_task(self, task_id: str): if task_id in self.tasks: task = self.tasks[task_id] task.status = "completed" await self.queues[task_id].put({"type": "status", "status": task.status, "steps": task.steps}) await self.queues[task_id].put({"type": "complete"}) async def fail_task(self, task_id: str, error: str): if task_id in self.tasks: self.tasks[task_id].status = f"failed: {error}" await self.queues[task_id].put({"type": "error", "message": error}) task_manager = TaskManager() def make_sse_handler(task_id): handler = SSELogHandler(task_id) def sink(message): asyncio.create_task(handler(str(message))) return sink def get_available_themes(): themes_dir = "static/themes" if not os.path.exists(themes_dir): return [{"id": "openmanus", "name": "Manus", "description": "默认主题"}] themes = [] for item in os.listdir(themes_dir): theme_path = os.path.join(themes_dir, item) if os.path.isdir(theme_path): templates_dir = os.path.join(theme_path, "templates") static_dir = os.path.join(theme_path, "static") config_file = os.path.join(theme_path, "theme.json") if os.path.exists(templates_dir) and os.path.exists(static_dir): if os.path.exists(os.path.join(templates_dir, "chat.html")): theme_info = {"id": item, "name": item, "description": ""} if os.path.exists(config_file): try: with open(config_file, "r", encoding="utf-8") as f: config = json.load(f) theme_info["name"] = config.get("name", item) theme_info["description"] = config.get("description", "") except Exception as e: print(f"读取主题配置文件出错: {str(e)}") themes.append(theme_info) if not any(theme["id"] == "openmanus" for theme in themes): themes.append({"id": "openmanus", "name": "Manus", "description": "默认主题"}) return themes @app.get("/", response_class=HTMLResponse) async def index(request: Request): themes = get_available_themes() sorted_themes = [] normal_theme = None cyberpunk_theme = None other_themes = [] for theme in themes: if theme["id"] == "openmanus": normal_theme = theme elif theme["id"] == "cyberpunk": cyberpunk_theme = theme else: other_themes.append(theme) if normal_theme: sorted_themes.append(normal_theme) if cyberpunk_theme: sorted_themes.append(cyberpunk_theme) sorted_themes.extend(other_themes) return templates.TemplateResponse("index.html", {"request": request, "themes": sorted_themes}) @app.get("/chat", response_class=HTMLResponse) async def chat(request: Request): theme = request.query_params.get("theme", "openmanus") theme_chat_path = f"static/themes/{theme}/templates/chat.html" if os.path.exists(theme_chat_path): with open(theme_chat_path, "r", encoding="utf-8") as f: content = f.read() theme_config_path = f"static/themes/{theme}/theme.json" theme_name = theme if os.path.exists(theme_config_path): try: with open(theme_config_path, "r", encoding="utf-8") as f: config = json.load(f) theme_name = config.get("name", theme) except Exception: pass content = content.replace("