diff --git a/backend/app/controller/chat_controller.py b/backend/app/controller/chat_controller.py index d9afc4acd..8fb4bcf1a 100644 --- a/backend/app/controller/chat_controller.py +++ b/backend/app/controller/chat_controller.py @@ -27,7 +27,7 @@ from app.utils.workforce import Workforce from camel.tasks.task import Task -router = APIRouter(tags=["chat"]) +router = APIRouter() # Create traceroot logger for chat controller chat_logger = traceroot.get_logger('chat_controller') diff --git a/backend/app/controller/health_controller.py b/backend/app/controller/health_controller.py new file mode 100644 index 000000000..296655bf1 --- /dev/null +++ b/backend/app/controller/health_controller.py @@ -0,0 +1,16 @@ +from fastapi import APIRouter +from pydantic import BaseModel + +router = APIRouter(tags=["Health"]) + + +class HealthResponse(BaseModel): + status: str + service: str + + +@router.get("/health", name="health check", response_model=HealthResponse) +async def health_check(): + """Health check endpoint for verifying backend is ready to accept requests.""" + return HealthResponse(status="ok", service="eigent") + diff --git a/backend/app/controller/model_controller.py b/backend/app/controller/model_controller.py index 1ce4f02e2..692a7fb2a 100644 --- a/backend/app/controller/model_controller.py +++ b/backend/app/controller/model_controller.py @@ -8,7 +8,7 @@ from utils import traceroot_wrapper as traceroot logger = traceroot.get_logger("model_controller") -router = APIRouter(tags=["model"]) +router = APIRouter() class ValidateModelRequest(BaseModel): diff --git a/backend/app/controller/task_controller.py b/backend/app/controller/task_controller.py index 3a7bb2d4f..2bf3fc7f6 100644 --- a/backend/app/controller/task_controller.py +++ b/backend/app/controller/task_controller.py @@ -20,7 +20,7 @@ from utils import traceroot_wrapper as traceroot logger = traceroot.get_logger("task_controller") -router = APIRouter(tags=["task"]) +router = APIRouter() @router.post("/task/{id}/start", name="start task") diff --git a/backend/app/controller/tool_controller.py b/backend/app/controller/tool_controller.py index 485f3b31e..3e97407c8 100644 --- a/backend/app/controller/tool_controller.py +++ b/backend/app/controller/tool_controller.py @@ -5,7 +5,7 @@ from app.utils.oauth_state_manager import oauth_state_manager from utils import traceroot_wrapper as traceroot logger = traceroot.get_logger("tool_controller") -router = APIRouter(tags=["task"]) +router = APIRouter() @router.post("/install/tool/{tool}", name="install tool") diff --git a/backend/app/router.py b/backend/app/router.py new file mode 100644 index 000000000..3fc6cb257 --- /dev/null +++ b/backend/app/router.py @@ -0,0 +1,64 @@ +""" +Centralized router registration for the Eigent API. +All routers are explicitly registered here for better visibility and maintainability. +""" +from fastapi import FastAPI +from app.controller import chat_controller, model_controller, task_controller, tool_controller, health_controller +from utils import traceroot_wrapper as traceroot + +logger = traceroot.get_logger("router") + + +def register_routers(app: FastAPI, prefix: str = "") -> None: + """ + Register all API routers with their respective prefixes and tags. + + This replaces the auto-discovery mechanism for better: + - Visibility: See all routes in one place + - Maintainability: Easy to add/remove routes + - Debugging: Clear registration order and configuration + + Args: + app: FastAPI application instance + prefix: Optional global prefix for all routes (e.g., "/api") + """ + routers_config = [ + { + "router": health_controller.router, + "tags": ["Health"], + "description": "Health check endpoint for service readiness" + }, + { + "router": chat_controller.router, + "tags": ["chat"], + "description": "Chat session management, improvements, and human interactions" + }, + { + "router": model_controller.router, + "tags": ["model"], + "description": "Model validation and configuration" + }, + { + "router": task_controller.router, + "tags": ["task"], + "description": "Task lifecycle management (start, stop, update, control)" + }, + { + "router": tool_controller.router, + "tags": ["tool"], + "description": "Tool installation and management" + }, + ] + + for config in routers_config: + app.include_router( + config["router"], + prefix=prefix, + tags=config["tags"] + ) + route_count = len(config["router"].routes) + logger.info( + f"Registered {config['tags'][0]} router: {route_count} routes - {config['description']}" + ) + + logger.info(f"Total routers registered: {len(routers_config)}") \ No newline at end of file diff --git a/backend/main.py b/backend/main.py index 4664ed66a..23421fda9 100644 --- a/backend/main.py +++ b/backend/main.py @@ -20,7 +20,9 @@ if traceroot.is_enabled(): connect_fastapi(api) # 2) Now safe to import modules that use traceroot.get_logger() at import-time -from app.component.environment import auto_include_routers, env +from app.component.environment import env +from app.router import register_routers + os.environ["PYTHONIOENCODING"] = "utf-8" @@ -33,7 +35,7 @@ app_logger.info(f"Environment: {os.environ.get('ENVIRONMENT', 'development')}") prefix = env("url_prefix", "") app_logger.info(f"Loading routers with prefix: '{prefix}'") -auto_include_routers(api, prefix, "app/controller") +register_routers(api, prefix) app_logger.info("All routers loaded successfully") diff --git a/electron/main/init.ts b/electron/main/init.ts index 11ed6ef38..b09db6595 100644 --- a/electron/main/init.ts +++ b/electron/main/init.ts @@ -4,6 +4,7 @@ import log from 'electron-log' import fs from 'fs' import path from 'path' import * as net from "net"; +import * as http from "http"; import { ipcMain, BrowserWindow, app } from 'electron' import { promisify } from 'util' import { detectInstallationLogs, PromiseReturnType } from "./install-deps"; @@ -195,21 +196,77 @@ export async function startBackend(setPort?: (port: number) => void): Promise { if (!started) { + if (healthCheckInterval) clearInterval(healthCheckInterval); node_process.kill(); reject(new Error('Backend failed to start within timeout')); } }, 30000); // 30 second timeout + // Helper function to poll health endpoint + const pollHealthEndpoint = (): void => { + let attempts = 0; + const maxAttempts = 20; // 5 seconds total (20 * 250ms) + const intervalMs = 250; + + healthCheckInterval = setInterval(() => { + attempts++; + const healthUrl = `http://127.0.0.1:${port}/health`; + + const req = http.get(healthUrl, { timeout: 1000 }, (res) => { + if (res.statusCode === 200) { + log.info(`Backend health check passed after ${attempts} attempts`); + started = true; + clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); + resolve(node_process); + } else { + // Non-200 status (e.g., 404), continue polling unless max attempts reached + if (attempts >= maxAttempts) { + log.error(`Backend health check failed after ${attempts} attempts with status ${res.statusCode}`); + started = true; + clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); + node_process.kill(); + reject(new Error(`Backend health check failed: HTTP ${res.statusCode}`)); + } + } + }); + + req.on('error', () => { + // Connection error - backend might not be ready yet, continue polling + if (attempts >= maxAttempts) { + log.error(`Backend health check failed after ${attempts} attempts: unable to connect`); + started = true; + clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); + node_process.kill(); + reject(new Error('Backend health check failed: unable to connect')); + } + }); + + req.on('timeout', () => { + req.destroy(); + if (attempts >= maxAttempts) { + log.error(`Backend health check timed out after ${attempts} attempts`); + started = true; + clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); + node_process.kill(); + reject(new Error('Backend health check timed out')); + } + }); + }, intervalMs); + }; node_process.stdout.on('data', (data) => { displayFilteredLogs(data); // check output content, judge if start success if (!started && data.toString().includes("Uvicorn running on")) { - started = true; - clearTimeout(startTimeout); - resolve(node_process); + log.info('Uvicorn startup detected, starting health check polling...'); + pollHealthEndpoint(); } }); @@ -217,9 +274,8 @@ export async function startBackend(setPort?: (port: number) => void): Promise void): Promise void): Promise { clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); if (!started) { reject(new Error(`fastapi exited with code ${code}`)); } diff --git a/server/app/controller/chat/history_controller.py b/server/app/controller/chat/history_controller.py index f58b29995..9dd6f2a30 100644 --- a/server/app/controller/chat/history_controller.py +++ b/server/app/controller/chat/history_controller.py @@ -3,7 +3,7 @@ from fastapi_pagination import Page from fastapi_pagination.ext.sqlmodel import paginate from app.model.chat.chat_history import ChatHistoryOut, ChatHistoryIn, ChatHistory, ChatHistoryUpdate from fastapi_babel import _ -from sqlmodel import Session, select, desc +from sqlmodel import Session, select, desc, case from app.component.auth import Auth, auth_must from app.component.database import session from utils import traceroot_wrapper as traceroot @@ -38,7 +38,19 @@ def create_chat_history(data: ChatHistoryIn, session: Session = Depends(session) def list_chat_history(session: Session = Depends(session), auth: Auth = Depends(auth_must)) -> Page[ChatHistoryOut]: """List chat histories for current user.""" user_id = auth.user.id - stmt = select(ChatHistory).where(ChatHistory.user_id == user_id).order_by(desc(ChatHistory.created_at)) + + # Order by created_at descending, but fallback to id descending for old records without timestamps + # This ensures newer records with timestamps come first, followed by old records ordered by id + stmt = ( + select(ChatHistory) + .where(ChatHistory.user_id == user_id) + .order_by( + desc(case((ChatHistory.created_at.is_(None), 0), else_=1)), # Non-null created_at first + desc(ChatHistory.created_at), # Then by created_at descending + desc(ChatHistory.id) # Finally by id descending for records with same/null created_at + ) + ) + result = paginate(session, stmt) total = result.total if hasattr(result, 'total') else 0 logger.debug("Chat histories listed", extra={"user_id": user_id, "total": total}) diff --git a/server/app/model/chat/chat_history.py b/server/app/model/chat/chat_history.py index 6dd7775a1..79720d87e 100644 --- a/server/app/model/chat/chat_history.py +++ b/server/app/model/chat/chat_history.py @@ -2,6 +2,7 @@ from sqlalchemy import Float, Integer from sqlmodel import Field, SmallInteger, Column, JSON, String from typing import Optional from enum import IntEnum +from datetime import datetime from sqlalchemy_utils import ChoiceType from app.model.abstract.model import AbstractModel, DefaultTimes from pydantic import BaseModel, model_validator @@ -13,6 +14,16 @@ class ChatStatus(IntEnum): class ChatHistory(AbstractModel, DefaultTimes, table=True): + """ + Chat history model with timestamp tracking. + + Inherits from DefaultTimes which provides: + - created_at: timestamp when record is created (auto-populated) + - updated_at: timestamp when record is last modified (auto-updated) + - deleted_at: timestamp for soft deletion (nullable) + + For legacy records without timestamps, sorting falls back to id ordering. + """ id: int = Field(default=None, primary_key=True) user_id: int = Field(index=True) task_id: str = Field(index=True, unique=True) @@ -70,13 +81,22 @@ class ChatHistoryOut(BaseModel): summary: str | None = None tokens: int status: int + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None @model_validator(mode="after") def fill_project_id_from_task_id(self): - """fill by task_id when project_id is None""" + """Fill project_id from task_id when project_id is None""" if self.project_id is None: self.project_id = self.task_id return self + + @model_validator(mode="after") + def handle_legacy_timestamps(self): + """Handle legacy records that might not have timestamp fields""" + # For old records without timestamps, we rely on database-level defaults + # The sorting in the controller will handle ordering appropriately + return self class ChatHistoryUpdate(BaseModel): diff --git a/server/app/model/config/config.py b/server/app/model/config/config.py index 022a520d5..4677b4e82 100644 --- a/server/app/model/config/config.py +++ b/server/app/model/config/config.py @@ -124,10 +124,10 @@ class ConfigInfo: "env_vars": [], "toolkit": "google_drive_mcp_toolkit", }, - # ConfigGroup.GOOGLE_GMAIL_MCP.value: { - # "env_vars": [], - # "toolkit": "google_gmail_mcp_toolkit", - # }, + ConfigGroup.GOOGLE_GMAIL_MCP.value: { + "env_vars": ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET", "GOOGLE_REFRESH_TOKEN"], + "toolkit": "google_gmail_native_toolkit", + }, ConfigGroup.IMAGE_ANALYSIS.value: { "env_vars": [], "toolkit": "image_analysis_toolkit", diff --git a/server/app/type/config_group.py b/server/app/type/config_group.py index ba7b66050..df5103e64 100644 --- a/server/app/type/config_group.py +++ b/server/app/type/config_group.py @@ -21,7 +21,7 @@ class ConfigGroup(str, Enum): GITHUB = "Github" GOOGLE_CALENDAR = "Google Calendar" GOOGLE_DRIVE_MCP = "Google Drive MCP" - GOOGLE_GMAIL_MCP = "Google Gmail MCP" + GOOGLE_GMAIL_MCP = "Google Gmail" IMAGE_ANALYSIS = "Image Analysis" MCP_SEARCH = "MCP Search" PPTX = "PPTX" diff --git a/src/assets/wechat_qr_1.jpg b/src/assets/wechat_qr_1.jpg index 857ac9d9d..3fe17cb39 100644 Binary files a/src/assets/wechat_qr_1.jpg and b/src/assets/wechat_qr_1.jpg differ diff --git a/src/assets/wechat_qr_2.jpg b/src/assets/wechat_qr_2.jpg index a3d5ee49c..c6596c507 100644 Binary files a/src/assets/wechat_qr_2.jpg and b/src/assets/wechat_qr_2.jpg differ diff --git a/src/assets/wechat_qr_3.jpg b/src/assets/wechat_qr_3.jpg index 5663db8e0..8a373214c 100644 Binary files a/src/assets/wechat_qr_3.jpg and b/src/assets/wechat_qr_3.jpg differ diff --git a/src/assets/wechat_qr_4.jpg b/src/assets/wechat_qr_4.jpg index f1e72d6bd..e38ff30bf 100644 Binary files a/src/assets/wechat_qr_4.jpg and b/src/assets/wechat_qr_4.jpg differ diff --git a/src/components/AddWorker/index.tsx b/src/components/AddWorker/index.tsx index e99d7b199..c2374af3d 100644 --- a/src/components/AddWorker/index.tsx +++ b/src/components/AddWorker/index.tsx @@ -1,7 +1,6 @@ import { Button } from "@/components/ui/button"; import { Dialog, - DialogClose, DialogContent, DialogContentSection, DialogFooter, @@ -11,12 +10,10 @@ import { import { Input } from "@/components/ui/input"; import { Bot, - CircleAlert, Plus, - RefreshCw, - ChevronLeft, - ArrowRight, Edit, + Eye, + EyeOff, } from "lucide-react"; import ToolSelect from "./ToolSelect"; import { Textarea } from "@/components/ui/textarea"; @@ -25,7 +22,6 @@ import githubIcon from "@/assets/github.svg"; import { fetchPost } from "@/api/http"; import { useAuthStore, useWorkerList } from "@/store/authStore"; import { useTranslation } from "react-i18next"; -import { TooltipSimple } from "../ui/tooltip"; import useChatStoreAdapter from "@/hooks/useChatStoreAdapter"; interface EnvValue { @@ -70,6 +66,7 @@ export function AddWorker({ const [activeMcp, setActiveMcp] = useState(null); const [envValues, setEnvValues] = useState<{ [key: string]: EnvValue }>({}); const [isValidating, setIsValidating] = useState(false); + const [secretVisible, setSecretVisible] = useState<{ [key: string]: boolean }>({}); const toolSelectRef = useRef<{ installMcp: (id: number, env?: any, activeMcp?: any) => Promise; } | null>(null); @@ -88,7 +85,8 @@ export function AddWorker({ console.log(mcp); if (mcp?.install_command?.env) { const initialValues: { [key: string]: EnvValue } = {}; - for(const key of Object.keys(mcp.install_command.env)) { + const initialVisibility: { [key: string]: boolean } = {}; + for (const key of Object.keys(mcp.install_command.env)) { initialValues[key] = { value: "", required: true, @@ -97,12 +95,14 @@ export function AddWorker({ ?.replace(/{{/g, "") ?.replace(/}}/g, "") || "", }; - // GOOGLE_REFRESH_TOKEN is not required (will be obtained via OAuth) - if (key === 'GOOGLE_REFRESH_TOKEN') { + // GOOGLE_REFRESH_TOKEN is obtained via OAuth and does not require manual input + if (key === "GOOGLE_REFRESH_TOKEN") { initialValues[key].required = false; } + initialVisibility[key] = false; } setEnvValues(initialValues); + setSecretVisible(initialVisibility); } }; @@ -186,12 +186,14 @@ export function AddWorker({ // clean status setActiveMcp(null); setEnvValues({}); + setSecretVisible({}); }; const handleCloseMcpEnvSetting = () => { setShowEnvConfig(false); setActiveMcp(null); setEnvValues({}); + setSecretVisible({}); }; const handleShowEnvConfig = (mcp: McpItem) => { @@ -200,6 +202,11 @@ export function AddWorker({ setShowEnvConfig(true); }; + const isSensitiveKey = (key: string) => /token|key|secret|password|id/i.test(key); + const toggleSecretVisibility = (key: string) => { + setSecretVisible((prev) => ({ ...prev, [key]: !prev[key] })); + }; + const handleSelectedToolsChange = (tools: McpItem[]) => { setSelectedTools(tools); }; @@ -211,6 +218,7 @@ export function AddWorker({ setShowEnvConfig(false); setActiveMcp(null); setEnvValues({}); + setSecretVisible({}); setNameError(""); }; @@ -254,9 +262,11 @@ export function AddWorker({ } }); console.log("mcpLocal.mcpServers", mcpLocal.mcpServers); - for(const key of Object.keys(mcpLocal.mcpServers)) { - if (!mcpList.includes(key)) { - delete mcpLocal.mcpServers[key]; + if (mcpLocal.mcpServers && typeof mcpLocal.mcpServers === 'object') { + for(const key of Object.keys(mcpLocal.mcpServers)) { + if (!mcpList.includes(key)) { + delete mcpLocal.mcpServers[key]; + } } } if (edit) { @@ -369,10 +379,9 @@ export function AddWorker({ )} - { if (isValidating) e.preventDefault(); }} @@ -424,25 +433,31 @@ export function AddWorker({
- {Object.keys(activeMcp?.install_command?.env || {}).map( - (key) => ( -
-
- {key}{envValues[key]?.required ? '*' : ''} -
- updateEnvValue(key, e.target.value)} - state={envValues[key]?.error ? "error" : "default"} - /> -
- {envValues[key]?.error || envValues[key]?.tip} -
-
- ) - )} + {Object.keys(activeMcp?.install_command?.env || {}).map((key) => ( +
+
+ {key} + {envValues[key]?.required ? "*" : ""} +
+ updateEnvValue(key, e.target.value)} + state={envValues[key]?.error ? "error" : "default"} + note={envValues[key]?.error || envValues[key]?.tip} + backIcon={isSensitiveKey(key) + ? secretVisible[key] + ? + : + : undefined} + onBackIconClick={isSensitiveKey(key) ? () => toggleSecretVisibility(key) : undefined} + /> +
+ ))}
- {/* hidden but keep rendering ToolSelect component */}
@@ -489,11 +503,6 @@ export function AddWorker({ }} state={nameError ? "error" : "default"} note={nameError || ""} - backIcon={} - onBackIconClick={() => { - // Handle refresh/regenerate logic here - console.log("Refresh agent name"); - }} required />
diff --git a/src/components/TopBar/index.tsx b/src/components/TopBar/index.tsx index 0e6c4c89f..03e65ce4a 100644 --- a/src/components/TopBar/index.tsx +++ b/src/components/TopBar/index.tsx @@ -145,9 +145,12 @@ function HeaderWin() { return; } + const projectId = projectStore.activeProjectId; + const historyId = projectId ? projectStore.getHistoryId(projectId) : null; + try { const task = chatStore.tasks[taskId]; - + // Stop the task if it's running if (task && task.status === 'running') { await fetchPut(`/task/${taskId}/take-control`, { @@ -162,11 +165,15 @@ function HeaderWin() { console.log("Task may not exist on backend:", error); } - // Delete from history - try { - await proxyFetchDelete(`/api/chat/history/${taskId}`); - } catch (error) { - console.log("Task may not exist in history:", error); + // Delete from history using historyId + if (historyId) { + try { + await proxyFetchDelete(`/api/chat/history/${historyId}`); + } catch (error) { + console.log("History may not exist:", error); + } + } else { + console.warn("No historyId found for project, skipping history deletion"); } // Remove from local store @@ -176,8 +183,8 @@ function HeaderWin() { const newTaskId = chatStore.create(); chatStore.setActiveTaskId(newTaskId); - // Navigate to home - navigate("/"); + // Navigate to home with replace to force refresh + navigate("/", { replace: true }); toast.success(t("layout.project-ended-successfully"), { closeButton: true,