Skip to content

Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.

feat(frontend): finished login/logout, connected chat to the api

karloks20059993ef84a6ad
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..c95bf94
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,10 @@
+.env
+.git
+.gitignore
+.pytest_cache
+dev.db
+frontend/node_modules
+src/frontend/node_modules
+venv
+__pycache__
+*.pyc
\ No newline at end of file
diff --git a/README.md b/README.md
index a88b30b..baa91c7 100644
--- a/README.md
+++ b/README.md
@@ -44,7 +44,48 @@ cd /media/karlo/data/Documents/programming/homelab-agent
docker compose up -d
```
-Use the values already defined in the project `.env` file for the real stack:
+### Run the complete stack with Compose
+
+Build and start the database, Redis, backend API, and frontend together:
+
+```bash
+docker compose up -d --build
+```
+
+Open the frontend at http://localhost:5173. The backend API is available at
+http://localhost:8000 and its health endpoint is http://localhost:8000/health.
+
+For local testing, every backend startup ensures this account exists (including
+after `docker compose up -d --build`):
+
+```text
+Password: admin123
+```
+
+Authentication rate limits are enforced through Redis: login allows 5 attempts
+per minute per IP and email, while registration allows 3 attempts per hour per
+IP. Override these defaults with `LOGIN_RATE_LIMIT`,
+`LOGIN_RATE_WINDOW_SECONDS`, `REGISTER_RATE_LIMIT`, and
+`REGISTER_RATE_WINDOW_SECONDS`.
+
+The initialization SQL only runs when the Postgres volume is created. If the
+database was already initialized with the old schema, recreate the local data
+volumes before starting the stack:
+
+```bash
+sudo docker compose down -v
+sudo docker compose up -d --build
+```
+
+To inspect the application logs or stop the stack:
+
+```bash
+docker compose logs -f backend frontend
+docker compose down
+```
+
+When running the backend outside Compose, use the values already defined in the project `.env` file for the real stack:
```env
DATABASE_URL=postgresql+psycopg://homelab:homelab_dev@localhost:5432/homelab
diff --git a/docker-compose.yml b/docker-compose.yml
index f947ebf..2f22259 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -33,6 +33,44 @@ services:
timeout: 5s
retries: 5
+ backend:
+ build:
+ context: .
+ dockerfile: docker/backend.Dockerfile
+ container_name: homelab-backend
+ restart: unless-stopped
+ environment:
+ DATABASE_URL: postgresql+psycopg://homelab:homelab_dev@postgres:5432/homelab
+ REDIS_URL: redis://redis:6379/0
+ GEMINI_API_KEY: ${GEMINI_API_KEY}
+ AGENT_MODEL: ${AGENT_MODEL:-models/gemini-3.5-flash}
+ ports:
+ - "8000:8000"
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+ healthcheck:
+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
+ interval: 10s
+ timeout: 5s
+ retries: 5
+
+ frontend:
+ build:
+ context: .
+ dockerfile: docker/frontend.Dockerfile
+ args:
+ VITE_API_BASE_URL: http://localhost:8000
+ container_name: homelab-frontend
+ restart: unless-stopped
+ ports:
+ - "5173:80"
+ depends_on:
+ backend:
+ condition: service_healthy
+
volumes:
postgres_data:
redis_data:
diff --git a/docker/backend.Dockerfile b/docker/backend.Dockerfile
new file mode 100644
index 0000000..b0401b9
--- /dev/null
+++ b/docker/backend.Dockerfile
@@ -0,0 +1,12 @@
+FROM python:3.12-slim
+
+WORKDIR /app
+
+COPY requirements.txt .
+RUN pip install --no-cache-dir -r requirements.txt
+
+COPY src ./src
+
+EXPOSE 8000
+
+CMD ["uvicorn", "src.backend.main:app", "--host", "0.0.0.0", "--port", "8000"]
\ No newline at end of file
diff --git a/docker/frontend.Dockerfile b/docker/frontend.Dockerfile
new file mode 100644
index 0000000..5f31ad1
--- /dev/null
+++ b/docker/frontend.Dockerfile
@@ -0,0 +1,18 @@
+FROM node:20-alpine AS build
+
+WORKDIR /app
+
+COPY src/frontend/package*.json ./
+RUN npm ci
+
+COPY src/frontend/ ./
+ARG VITE_API_BASE_URL=http://localhost:8000
+ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
+RUN npm run build
+
+FROM nginx:alpine
+
+COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
+COPY --from=build /app/dist /usr/share/nginx/html
+
+EXPOSE 80
\ No newline at end of file
diff --git a/docker/nginx.conf b/docker/nginx.conf
new file mode 100644
index 0000000..6270228
--- /dev/null
+++ b/docker/nginx.conf
@@ -0,0 +1,11 @@
+server {
+ listen 80;
+ server_name _;
+
+ root /usr/share/nginx/html;
+ index index.html;
+
+ location / {
+ try_files $uri $uri/ /index.html;
+ }
+}
\ No newline at end of file
diff --git a/docker/postgres/init/01_create_users.sql b/docker/postgres/init/01_create_users.sql
index 1972bb5..d9a8eb8 100644
--- a/docker/postgres/init/01_create_users.sql
+++ b/docker/postgres/init/01_create_users.sql
@@ -2,8 +2,7 @@ CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
- first_name VARCHAR(100),
- last_name VARCHAR(100),
+ name VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL DEFAULT 'user',
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
@@ -14,12 +13,11 @@ CREATE INDEX IF NOT EXISTS idx_users_email ON users (email);
CREATE INDEX IF NOT EXISTS idx_users_role ON users (role);
-- Example seed user for quick testing.
-INSERT INTO users (email, password_hash, first_name, last_name, role)
+INSERT INTO users (email, password_hash, name, role)
VALUES (
- '$2b$12$8Cj5XkVJ8GNr9XELmD7.uO0mIUSrM2iKzQx8D8BJP4h3w8mYhN8rC',
- 'Admin',
- 'User',
+ '$2b$12$pb1MBMmCHsJOwpZ4k7aVoOpOJfGDS/TBmR8KwvibUv15z4tgYAm3O',
+ 'Admin User',
'admin'
)
ON CONFLICT (email) DO NOTHING;
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 9fb6b71..ee70dbc 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -219,7 +219,7 @@ function LoginPage() {
<span className="mb-2 block text-sm text-[#bcbcbc]">Email</span>
<input
type="email"
- defaultValue="[email protected]"
+ defaultValue="[email protected]"
className="w-full rounded-2xl border border-neutral-700 bg-neutral-900/70 px-4 py-3 text-white outline-none ring-0 transition focus:border-emerald-400"
/>
</label>
diff --git a/poem.txt b/poem.txt
new file mode 100644
index 0000000..e69de29
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..1786bb6
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,9 @@
+bcrypt
+email-validator
+fastapi
+google-genai
+psycopg[binary]
+python-dotenv
+redis
+sqlalchemy
+uvicorn[standard]
\ No newline at end of file
diff --git a/src/agent/service.py b/src/agent/service.py
new file mode 100644
index 0000000..7fd85cb
--- /dev/null
+++ b/src/agent/service.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+import os
+import threading
+
+from dotenv import load_dotenv
+from google import genai
+from google.genai import types
+
+from .prompts import SYSTEM_PROMPT
+
+load_dotenv()
+
+
+class AgentService:
+ def __init__(self):
+ api_key = os.getenv("GEMINI_API_KEY")
+ if not api_key:
+ raise RuntimeError("GEMINI_API_KEY is not configured.")
+ self.client = genai.Client(api_key=api_key)
+ self.chats = {}
+ self.lock = threading.Lock()
+
+ def _get_chat(self, user_id: int, conversation_id: str):
+ chat_key = (user_id, conversation_id)
+ with self.lock:
+ if chat_key not in self.chats:
+ self.chats[chat_key] = self.client.chats.create(
+ model=os.getenv("AGENT_MODEL", "models/gemini-3.5-flash"),
+ config=types.GenerateContentConfig(
+ system_instruction=SYSTEM_PROMPT,
+ temperature=0.2,
+ ),
+ )
+ return self.chats[chat_key]
+
+ def send(self, user_id: int, conversation_id: str, message: str) -> str:
+ response = self._get_chat(user_id, conversation_id).send_message(message)
+ return getattr(response, "text", "") or "The agent returned an empty response."
+
+
+_agent_service = None
+
+
+def send_agent_message(user_id: int, conversation_id: str, message: str) -> str:
+ global _agent_service
+ if _agent_service is None:
+ _agent_service = AgentService()
+ return _agent_service.send(user_id, conversation_id, message)
\ No newline at end of file
diff --git a/src/backend/auth.py b/src/backend/auth.py
index eb9fc7e..18b9e24 100644
--- a/src/backend/auth.py
+++ b/src/backend/auth.py
@@ -6,9 +6,6 @@ import bcrypt
from .config import SESSION_TTL_SECONDS
from .models import AuditLog, User
-SESSION_FALLBACK = {}
-
-
def _serialize_user(user: User):
return {
"id": user.id,
@@ -26,39 +23,36 @@ def _session_key(session_id: str) -> str:
def _store_session(redis_client, session_id: str, payload: dict):
key = _session_key(session_id)
value = json.dumps(payload)
- try:
- redis_client.set(key, value, ex=SESSION_TTL_SECONDS)
- except Exception:
- SESSION_FALLBACK[key] = value
+ redis_client.set(key, value, ex=SESSION_TTL_SECONDS)
def _read_session(redis_client, session_id: str):
key = _session_key(session_id)
- try:
- value = redis_client.get(key)
- if value is not None:
- return value
- except Exception:
- pass
-
- return SESSION_FALLBACK.get(key)
+ return redis_client.get(key)
def _delete_session(redis_client, session_id: str):
key = _session_key(session_id)
- try:
- redis_client.delete(key)
- except Exception:
- pass
- SESSION_FALLBACK.pop(key, None)
-
-
-def record_audit_log(db, *, user_id: int | None, level: str, message: str, source: str = "system"):
+ redis_client.delete(key)
+
+
+def record_audit_log(
+ db,
+ *,
+ user_id: int | None,
+ level: str,
+ message: str,
+ source: str = "system",
+ task_title: str | None = None,
+ steps: list[str] | None = None,
+):
log_entry = AuditLog(
user_id=user_id,
level=level.upper(),
message=message,
source=source,
+ task_title=task_title,
+ steps=json.dumps(steps or []),
)
db.add(log_entry)
db.commit()
@@ -69,23 +63,58 @@ def record_audit_log(db, *, user_id: int | None, level: str, message: str, sourc
"level": log_entry.level,
"message": log_entry.message,
"source": log_entry.source,
+ "task_title": log_entry.task_title,
+ "steps": steps or [],
"created_at": log_entry.created_at.isoformat(),
}
def get_recent_logs(db, *, limit: int = 20):
- logs = db.query(AuditLog).order_by(AuditLog.created_at.desc()).limit(limit).all()
- return [
- {
- "id": log.id,
- "user_id": log.user_id,
- "level": log.level,
- "message": log.message,
- "source": log.source,
- "created_at": log.created_at.isoformat(),
- }
- for log in logs
- ]
+ logs = (
+ db.query(AuditLog)
+ .filter(AuditLog.source != "auth")
+ .order_by(AuditLog.created_at.desc())
+ .limit(limit)
+ .all()
+ )
+ result = []
+ for log in logs:
+ try:
+ steps = json.loads(log.steps or "[]")
+ except (TypeError, ValueError):
+ steps = []
+ result.append(
+ {
+ "id": log.id,
+ "user_id": log.user_id,
+ "level": log.level,
+ "message": log.message,
+ "source": log.source,
+ "task_title": log.task_title or log.message,
+ "steps": steps if isinstance(steps, list) else [],
+ "created_at": log.created_at.isoformat(),
+ }
+ )
+ return result
+
+
+def ensure_default_user(db):
+ email = "[email protected]"
+ user = db.query(User).filter(User.email == email).first()
+ if user:
+ return user
+
+ user = User(
+ name="Admin User",
+ email=email,
+ password_hash=bcrypt.hashpw(b"admin123", bcrypt.gensalt()).decode("utf-8"),
+ role="admin",
+ is_active=True,
+ )
+ db.add(user)
+ db.commit()
+ db.refresh(user)
+ return user
def register_user(db, redis_client, *, name: str, email: str, password: str):
@@ -131,7 +160,7 @@ def authenticate_user(db, redis_client, *, email: str, password: str):
normalized_email = email.strip().lower()
user = db.query(User).filter(User.email == normalized_email).first()
- if not user:
+ if not user or not user.is_active:
raise ValueError("Invalid email or password.")
if not bcrypt.checkpw(password.encode("utf-8"), user.password_hash.encode("utf-8")):
diff --git a/src/backend/config.py b/src/backend/config.py
index 3587243..b0398bd 100644
--- a/src/backend/config.py
+++ b/src/backend/config.py
@@ -12,3 +12,10 @@ DATABASE_URL = os.getenv(
)
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "86400"))
+AGENT_MODEL = os.getenv("AGENT_MODEL", "models/gemini-3.5-flash")
+SESSION_COOKIE_NAME = os.getenv("SESSION_COOKIE_NAME", "homie_session")
+SESSION_COOKIE_SECURE = os.getenv("SESSION_COOKIE_SECURE", "false").lower() == "true"
+LOGIN_RATE_LIMIT = int(os.getenv("LOGIN_RATE_LIMIT", "5"))
+LOGIN_RATE_WINDOW_SECONDS = int(os.getenv("LOGIN_RATE_WINDOW_SECONDS", "60"))
+REGISTER_RATE_LIMIT = int(os.getenv("REGISTER_RATE_LIMIT", "3"))
+REGISTER_RATE_WINDOW_SECONDS = int(os.getenv("REGISTER_RATE_WINDOW_SECONDS", "3600"))
diff --git a/src/backend/main.py b/src/backend/main.py
index 270375b..36effb0 100644
--- a/src/backend/main.py
+++ b/src/backend/main.py
@@ -3,17 +3,28 @@ from __future__ import annotations
from typing import Annotated
import redis
-from fastapi import Depends, FastAPI, Header, HTTPException, status
+from fastapi import Cookie, Depends, FastAPI, HTTPException, Request, Response, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, EmailStr
from sqlalchemy import text
-from .auth import authenticate_user, get_recent_logs, get_user_from_session, logout_user, record_audit_log, register_user
+from .auth import authenticate_user, ensure_default_user, get_recent_logs, get_user_from_session, logout_user, record_audit_log, register_user
from .db import SessionLocal, check_database, get_db
from .models import AuditLog, Base, User
from .db import engine
-from .config import REDIS_URL
+from .config import (
+ LOGIN_RATE_LIMIT,
+ LOGIN_RATE_WINDOW_SECONDS,
+ REDIS_URL,
+ REGISTER_RATE_LIMIT,
+ REGISTER_RATE_WINDOW_SECONDS,
+ SESSION_COOKIE_NAME,
+ SESSION_COOKIE_SECURE,
+ SESSION_TTL_SECONDS,
+)
+from .rate_limit import enforce_login_limit, enforce_register_limit, reset_limits
+from ..agent.service import send_agent_message
class RegisterRequest(BaseModel):
@@ -27,6 +38,11 @@ class LoginRequest(BaseModel):
password: str
+class AgentChatRequest(BaseModel):
+ conversation_id: str
+ message: str
+
+
redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
app = FastAPI(title="Homelab Agent API")
@@ -42,6 +58,15 @@ app.add_middleware(
@app.on_event("startup")
def startup_event():
Base.metadata.create_all(bind=engine)
+ with engine.begin() as connection:
+ if engine.dialect.name == "postgresql":
+ connection.execute(text("ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS task_title VARCHAR(255)"))
+ connection.execute(text("ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS steps TEXT"))
+ db = SessionLocal()
+ try:
+ ensure_default_user(db)
+ finally:
+ db.close()
try:
redis_client.ping()
except Exception:
@@ -64,7 +89,13 @@ def health():
@app.post("/auth/register")
-def auth_register(payload: RegisterRequest, db=Depends(get_db)):
+def auth_register(payload: RegisterRequest, request: Request, response: Response, db=Depends(get_db)):
+ enforce_register_limit(
+ redis_client,
+ ip_address=request.client.host if request.client else "unknown",
+ limit=REGISTER_RATE_LIMIT,
+ window_seconds=REGISTER_RATE_WINDOW_SECONDS,
+ )
try:
result = register_user(
db,
@@ -76,11 +107,28 @@ def auth_register(payload: RegisterRequest, db=Depends(get_db)):
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ response.set_cookie(
+ key=SESSION_COOKIE_NAME,
+ value=result["session_id"],
+ max_age=SESSION_TTL_SECONDS,
+ httponly=True,
+ secure=SESSION_COOKIE_SECURE,
+ samesite="lax",
+ path="/",
+ )
+ result.pop("session_id", None)
return result
@app.post("/auth/login")
-def auth_login(payload: LoginRequest, db=Depends(get_db)):
+def auth_login(payload: LoginRequest, request: Request, response: Response, db=Depends(get_db)):
+ limit_keys = enforce_login_limit(
+ redis_client,
+ ip_address=request.client.host if request.client else "unknown",
+ email=str(payload.email),
+ limit=LOGIN_RATE_LIMIT,
+ window_seconds=LOGIN_RATE_WINDOW_SECONDS,
+ )
try:
result = authenticate_user(
db,
@@ -91,12 +139,24 @@ def auth_login(payload: LoginRequest, db=Depends(get_db)):
except ValueError as exc:
raise HTTPException(status_code=401, detail=str(exc)) from exc
+ reset_limits(redis_client, *limit_keys)
+
+ response.set_cookie(
+ key=SESSION_COOKIE_NAME,
+ value=result["session_id"],
+ max_age=SESSION_TTL_SECONDS,
+ httponly=True,
+ secure=SESSION_COOKIE_SECURE,
+ samesite="lax",
+ path="/",
+ )
+ result.pop("session_id", None)
return result
@app.get("/auth/me")
def auth_me(
- session_id: Annotated[str | None, Header(alias="x-session-id")] = None,
+ session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None,
db=Depends(get_db),
):
user = get_user_from_session(redis_client, session_id)
@@ -107,16 +167,18 @@ def auth_me(
@app.post("/auth/logout")
def auth_logout(
- session_id: Annotated[str | None, Header(alias="x-session-id")] = None,
+ response: Response,
+ session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None,
):
if logout_user(redis_client, session_id):
+ response.delete_cookie(key=SESSION_COOKIE_NAME, path="/")
return {"status": "ok"}
raise HTTPException(status_code=400, detail="No session id supplied.")
@app.get("/dashboard/summary")
def dashboard_summary(
- session_id: Annotated[str | None, Header(alias="x-session-id")] = None,
+ session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None,
db=Depends(get_db),
):
user = get_user_from_session(redis_client, session_id)
@@ -138,7 +200,7 @@ def dashboard_summary(
@app.get("/logs")
def list_logs(
- session_id: Annotated[str | None, Header(alias="x-session-id")] = None,
+ session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None,
db=Depends(get_db),
):
user = get_user_from_session(redis_client, session_id)
@@ -151,7 +213,7 @@ def list_logs(
@app.post("/logs")
def create_log(
payload: dict,
- session_id: Annotated[str | None, Header(alias="x-session-id")] = None,
+ session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None,
db=Depends(get_db),
):
user = get_user_from_session(redis_client, session_id)
@@ -164,7 +226,41 @@ def create_log(
level=str(payload.get("level", "INFO")).upper(),
message=str(payload.get("message", "New event")),
source=str(payload.get("source", "dashboard")),
+ task_title=str(payload.get("task_title") or payload.get("message", "New task")),
+ steps=[str(step) for step in payload.get("steps", []) if str(step).strip()],
+ )
+
+
[email protected]("/agent/chat")
+def agent_chat(payload: AgentChatRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ user = get_user_from_session(redis_client, session_id)
+ if not user:
+ raise HTTPException(status_code=401, detail="Session is invalid or expired.")
+
+ message = payload.message.strip()
+ if not message:
+ raise HTTPException(status_code=400, detail="Message is required.")
+
+ try:
+ response_text = send_agent_message(user["id"], payload.conversation_id, message)
+ except Exception as exc:
+ raise HTTPException(status_code=503, detail="Agent is unavailable.") from exc
+
+ command_lines = [line.removeprefix("[COMMAND]:").strip() for line in response_text.splitlines() if line.startswith("[COMMAND]:")]
+ steps = ["Received the task and evaluated the request.", "Generated a structured response for the requested task."]
+ if command_lines:
+ steps.append(f"Prepared {len(command_lines)} command(s) for review.")
+
+ record_audit_log(
+ db,
+ user_id=user["id"],
+ level="INFO",
+ message=response_text.splitlines()[0][:255] if response_text.splitlines() else "Agent task completed",
+ source="homie",
+ task_title=message[:255],
+ steps=steps,
)
+ return {"message": response_text}
@app.get("/")
diff --git a/src/backend/models.py b/src/backend/models.py
index e956b07..90ed1ee 100644
--- a/src/backend/models.py
+++ b/src/backend/models.py
@@ -39,6 +39,8 @@ class AuditLog(Base):
level: Mapped[str] = mapped_column(String(50), default="INFO", nullable=False)
message: Mapped[str] = mapped_column(Text, nullable=False)
source: Mapped[str] = mapped_column(String(100), default="system", nullable=False)
+ task_title: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
+ steps: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
diff --git a/src/backend/rate_limit.py b/src/backend/rate_limit.py
new file mode 100644
index 0000000..a929698
--- /dev/null
+++ b/src/backend/rate_limit.py
@@ -0,0 +1,50 @@
+from __future__ import annotations
+
+import hashlib
+
+from fastapi import HTTPException
+
+
+def _key(scope: str, value: str) -> str:
+ digest = hashlib.sha256(value.encode("utf-8")).hexdigest()
+ return f"homelab:rate-limit:{scope}:{digest}"
+
+
+def _record_attempt(redis_client, key: str, limit: int, window_seconds: int) -> None:
+ try:
+ pipe = redis_client.pipeline()
+ pipe.incr(key)
+ pipe.expire(key, window_seconds)
+ count, _ = pipe.execute()
+ except Exception as exc:
+ raise HTTPException(status_code=503, detail="Rate limiting service unavailable.") from exc
+
+ if count > limit:
+ raise HTTPException(
+ status_code=429,
+ detail="Too many attempts. Try again later.",
+ headers={"Retry-After": str(window_seconds)},
+ )
+
+
+def enforce_login_limit(redis_client, *, ip_address: str, email: str, limit: int, window_seconds: int) -> tuple[str, str]:
+ keys = (
+ _key("login-ip", ip_address),
+ _key("login-email", email.lower()),
+ )
+ for key in keys:
+ _record_attempt(redis_client, key, limit, window_seconds)
+ return keys
+
+
+def enforce_register_limit(redis_client, *, ip_address: str, limit: int, window_seconds: int) -> str:
+ key = _key("register-ip", ip_address)
+ _record_attempt(redis_client, key, limit, window_seconds)
+ return key
+
+
+def reset_limits(redis_client, *keys: str) -> None:
+ try:
+ redis_client.delete(*keys)
+ except Exception:
+ pass
\ No newline at end of file
diff --git a/src/frontend/src/App.jsx b/src/frontend/src/App.jsx
index 06de1a8..1cf342a 100644
--- a/src/frontend/src/App.jsx
+++ b/src/frontend/src/App.jsx
@@ -1,14 +1,25 @@
import { BrowserRouter, Link, NavLink, Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom'
-import { useEffect, useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
const AUTH_KEY = 'homie-auth-user'
-const SESSION_KEY = 'homie-session-id'
const USERS_KEY = 'homie-auth-users'
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
+function createChatThread() {
+ return {
+ id: typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : `chat-${Date.now()}`,
+ title: 'New chat',
+ preview: 'Start a task with Homie',
+ time: 'now',
+ unread: 0,
+ messages: [],
+ }
+}
+
async function apiRequest(path, options = {}) {
const response = await fetch(`${API_BASE}${path}`, {
...options,
+ credentials: 'include',
headers: {
'Content-Type': 'application/json',
...(options.headers || {}),
@@ -23,6 +34,18 @@ async function apiRequest(path, options = {}) {
return response.json()
}
+function parseAgentMessage(text) {
+ const commandMatch = text.match(/\[COMMAND\]:\s*(.+)/)
+ const riskMatch = text.match(/\[RISK\]:\s*(VERY LOW|LOW|MEDIUM|HIGH|VERY HIGH)/)
+ const explanation = text.split('[RUN]')[0].trim() || text
+
+ return {
+ text: explanation,
+ command: commandMatch ? commandMatch[1].trim() : undefined,
+ risk: riskMatch ? riskMatch[1].toLowerCase().replace(' ', '-') : 'low',
+ }
+}
+
const navigation = [
{ label: 'Landing', to: '/', icon: '◈' },
{ label: 'Dashboard', to: '/dashboard', icon: '▣' },
@@ -107,10 +130,9 @@ const stats = [
]
const logEntries = [
- { id: 'nginx-502', type: 'ERROR', message: 'Nginx 502 after stale upstream config', time: '08:42:02', actor: 'homie', conversationId: 1 },
- { id: 'ssl-expiry', type: 'WARN', message: 'Certificate renewal threshold near expiration', time: '07:51:16', actor: 'scheduler', conversationId: 2 },
- { id: 'backup-fail', type: 'ERROR', message: 'Backup job failed on /srv/data', time: '06:20:44', actor: 'homie', conversationId: 3 },
- { id: 'nginx-success', type: 'SUCCESS', message: 'Nginx reload completed without error', time: '05:48:12', actor: 'homie', conversationId: 1 },
+ { id: 'nginx-502', type: 'COMPLETED', taskTitle: 'Resolve nginx 502 after upstream drift', message: 'Recovered the nginx upstream and confirmed the service was healthy.', time: '08:42:02', actor: 'homie', steps: ['Inspected nginx logs and the active upstream configuration.', 'Validated the target socket and tested the nginx configuration.', 'Reloaded nginx and confirmed the service was listening.'] },
+ { id: 'ssl-renewal', type: 'COMPLETED', taskTitle: 'Validate staging certificate renewal', message: 'Validated the renewal path without changing the live certificate.', time: '07:51:16', actor: 'homie', steps: ['Checked the certificate expiry and renewal configuration.', 'Ran certbot in dry-run mode.', 'Confirmed the deployment hook would reload nginx safely.'] },
+ { id: 'backup-check', type: 'ATTENTION', taskTitle: 'Investigate failed RAID backup', message: 'Checked the backup volume and identified the next recovery checks.', time: '06:20:44', actor: 'homie', steps: ['Checked available space on the backup mount.', 'Inspected block devices and RAID status.', 'Recorded the failed volume check for follow-up.'] },
]
const adminSettings = {
@@ -140,7 +162,7 @@ function getStoredUsers() {
try {
const raw = window.localStorage.getItem(USERS_KEY)
if (!raw) {
- const demoUser = [{ id: 'demo-user', name: 'Demo User', email: '[email protected]', password: 'password' }]
+ const demoUser = [{ id: 'demo-user', name: 'Demo User', email: '[email protected]', password: 'admin123' }]
window.localStorage.setItem(USERS_KEY, JSON.stringify(demoUser))
return demoUser
}
@@ -195,10 +217,10 @@ function getRiskStyles(risk, role) {
return map[risk] || map.neutral
}
-function AppShell({ children, user, onLogout }) {
+function AppShell({ children, user, onLogout, fitViewport = false }) {
return (
- <div className="min-h-screen bg-[#0d1013] text-[#e6e7ea]">
- <div className="mx-auto flex max-w-[1700px] gap-6 px-4 py-5 lg:px-6">
+ <div className={`${fitViewport ? 'h-screen overflow-hidden' : 'min-h-screen'} bg-[#0d1013] text-[#e6e7ea]`}>
+ <div className={`${fitViewport ? 'h-full min-h-0' : ''} mx-auto flex max-w-[1700px] gap-6 px-4 py-5 lg:px-6`}>
<aside className="glass-panel hidden w-72 shrink-0 rounded-3xl p-4 lg:block">
<div className="mb-6 flex items-center gap-3 px-2">
<div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-linear-to-br from-white to-[#cfcfcf] text-sm font-bold text-slate-950">H</div>
@@ -254,7 +276,7 @@ function AppShell({ children, user, onLogout }) {
</div>
</aside>
- <main className="flex-1">{children}</main>
+ <main className={`${fitViewport ? 'min-h-0' : ''} flex-1`}>{children}</main>
</div>
</div>
)
@@ -292,8 +314,8 @@ function AuthCard({ title, subtitle, children, footerText, footerLink, footerLin
function LoginPage({ onLogin }) {
const navigate = useNavigate()
- const [email, setEmail] = useState('[email protected]')
- const [password, setPassword] = useState('password')
+ const [email, setEmail] = useState('[email protected]')
+ const [password, setPassword] = useState('admin123')
const [error, setError] = useState('')
const handleSubmit = async (event) => {
@@ -311,7 +333,6 @@ function LoginPage({ onLogin }) {
name: data.user.name,
email: data.user.email,
role: data.user.role,
- sessionId: data.session_id,
})
navigate('/')
} catch (requestError) {
@@ -402,7 +423,6 @@ function RegisterPage({ onRegister }) {
name: data.user.name,
email: data.user.email,
role: data.user.role,
- sessionId: data.session_id,
})
navigate('/')
} catch (requestError) {
@@ -466,22 +486,114 @@ function RegisterPage({ onRegister }) {
}
function LandingPage({ chatThreads, activeThreadId, onSelectChat, user, onLogout }) {
- const activeThread = chatThreads.find((thread) => thread.id === activeThreadId) || chatThreads[0]
+ const [threads, setThreads] = useState(() => (chatThreads.length ? chatThreads : [createChatThread()]))
+ const [messageInput, setMessageInput] = useState('')
+ const [isSending, setIsSending] = useState(false)
+ const [sendError, setSendError] = useState('')
+ const messageScrollerRef = useRef(null)
+ const scrollAnimationRef = useRef(null)
+ const activeThread = threads.find((thread) => thread.id === activeThreadId) || threads[0]
+
+ useEffect(() => {
+ const element = messageScrollerRef.current
+ if (!element) return undefined
+
+ if (scrollAnimationRef.current) {
+ cancelAnimationFrame(scrollAnimationRef.current)
+ }
+
+ const startTop = element.scrollTop
+ const targetTop = element.scrollHeight - element.clientHeight
+ const distance = targetTop - startTop
+ if (distance <= 1) return undefined
+
+ const duration = Math.min(520, Math.max(260, distance * 0.7))
+ const startTime = performance.now()
+ const easeInOutCubic = (progress) => (
+ progress < 0.5
+ ? 4 * progress * progress * progress
+ : 1 - Math.pow(-2 * progress + 2, 3) / 2
+ )
+
+ const animate = (currentTime) => {
+ const progress = Math.min((currentTime - startTime) / duration, 1)
+ element.scrollTop = startTop + distance * easeInOutCubic(progress)
+ if (progress < 1) {
+ scrollAnimationRef.current = requestAnimationFrame(animate)
+ } else {
+ scrollAnimationRef.current = null
+ }
+ }
+
+ scrollAnimationRef.current = requestAnimationFrame(animate)
+ return () => {
+ if (scrollAnimationRef.current) cancelAnimationFrame(scrollAnimationRef.current)
+ }
+ }, [activeThread?.id, activeThread?.messages.length])
+
+ const handleSend = async (event) => {
+ event.preventDefault()
+ const message = messageInput.trim()
+ if (!message || isSending || !activeThread) return
+
+ setMessageInput('')
+ setSendError('')
+ setIsSending(true)
+ setThreads((currentThreads) => currentThreads.map((thread) => (
+ thread.id === activeThread.id
+ ? {
+ ...thread,
+ title: thread.title === 'New chat' ? message.slice(0, 42) : thread.title,
+ preview: message,
+ messages: [...thread.messages, { role: 'user', text: message, risk: 'neutral' }],
+ }
+ : thread
+ )))
+
+ try {
+ const data = await apiRequest('/agent/chat', {
+ method: 'POST',
+ body: JSON.stringify({ conversation_id: activeThread.id, message }),
+ })
+ const agentMessage = parseAgentMessage(data.message)
+ setThreads((currentThreads) => currentThreads.map((thread) => (
+ thread.id === activeThread.id
+ ? { ...thread, messages: [...thread.messages, { role: 'agent', ...agentMessage }] }
+ : thread
+ )))
+ } catch (requestError) {
+ setSendError(requestError.message || 'Agent is unavailable.')
+ } finally {
+ setIsSending(false)
+ }
+ }
return (
- <AppShell user={user} onLogout={onLogout}>
- <div className="flex min-h-[calc(100vh-2rem)] flex-col gap-5 lg:flex-row">
- <aside className="glass-panel rounded-[28px] p-4 lg:w-[330px]">
+ <AppShell user={user} onLogout={onLogout} fitViewport>
+ <div className="flex h-full min-h-0 flex-col gap-5 lg:flex-row">
+ <aside className="glass-panel flex h-[250px] min-h-0 shrink-0 flex-col rounded-[28px] p-4 lg:h-auto lg:w-[330px]">
<div className="mb-4 flex items-center justify-between px-2">
<div>
<div className="text-xs uppercase tracking-[0.2em] text-[#9aa0a6]">Chats</div>
<h2 className="mt-1 text-xl font-semibold text-white">Sessions</h2>
</div>
- <button className="rounded-xl border border-neutral-700 bg-neutral-800/80 px-2.5 py-1.5 text-sm text-[#cfcfcf]">+ New</button>
+ <button
+ type="button"
+ onClick={() => {
+ const newThread = createChatThread()
+ setThreads((currentThreads) => [newThread, ...currentThreads])
+ onSelectChat(newThread.id)
+ setMessageInput('')
+ setSendError('')
+ }}
+ className="rounded-xl border border-neutral-700 bg-neutral-800/80 px-2.5 py-1.5 text-sm text-[#cfcfcf]"
+ >
+ + New
+ </button>
</div>
- <div className="custom-scroll max-h-[calc(100vh-11rem)] space-y-2 overflow-y-auto pr-1">
- {chatThreads.map((chat) => (
+ <div className="custom-scroll min-h-0 flex-1 space-y-2 overflow-y-auto pr-1">
+ {threads.map((chat) => (
<button
key={chat.id}
onClick={() => onSelectChat(chat.id)}
@@ -508,11 +620,11 @@ function LandingPage({ chatThreads, activeThreadId, onSelectChat, user, onLogout
</div>
</aside>
- <section className="glass-panel flex min-h-[760px] flex-1 flex-col rounded-[28px] p-4 md:p-5">
+ <section className="glass-panel flex min-h-0 flex-1 flex-col rounded-[28px] p-4 md:p-5">
<div className="flex flex-col gap-4 border-b border-neutral-800 pb-4 md:flex-row md:items-center md:justify-between">
<div>
<div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Active chat</div>
- <h1 className="mt-1 text-2xl font-semibold text-white md:text-3xl">{activeThread.title}</h1>
+ <h1 className="mt-1 text-2xl font-semibold text-white md:text-3xl">{activeThread?.title || 'New chat'}</h1>
</div>
<div className="flex items-center gap-2">
<div className="inline-flex items-center rounded-full border border-emerald-400/30 bg-emerald-500/10 px-2.5 py-1 text-xs text-emerald-300">
@@ -523,8 +635,8 @@ function LandingPage({ chatThreads, activeThreadId, onSelectChat, user, onLogout
</div>
</div>
- <div className="custom-scroll flex-1 space-y-4 overflow-y-auto py-4 pr-1">
- {activeThread.messages.map((message, index) => {
+ <div ref={messageScrollerRef} className="custom-scroll min-h-0 flex-1 space-y-4 overflow-y-auto py-4 pr-1">
+ {activeThread?.messages.map((message, index) => {
const riskStyles = getRiskStyles(message.risk, message.role)
return (
@@ -560,17 +672,20 @@ function LandingPage({ chatThreads, activeThreadId, onSelectChat, user, onLogout
})}
</div>
- <div className="mt-4 rounded-[24px] border border-[#171b1f] bg-[#0d1013]/80 p-3">
+ <form onSubmit={handleSend} className="mt-4 rounded-[24px] border border-[#171b1f] bg-[#0d1013]/80 p-3">
<div className="flex flex-col gap-3 md:flex-row md:items-center">
- <button className="rounded-xl border border-[#171b1f] bg-[#111417] px-3 py-2 text-sm text-[#cfcfcf]">Attach</button>
+ <button type="button" className="rounded-xl border border-[#171b1f] bg-[#111417] px-3 py-2 text-sm text-[#cfcfcf]">Attach</button>
<input
type="text"
- defaultValue="Check the failed upstream and confirm if the service is healthy."
+ value={messageInput}
+ onChange={(event) => setMessageInput(event.target.value)}
+ placeholder="Ask Homie to inspect a service or solve a task..."
className="flex-1 rounded-xl border border-[#171b1f] bg-[#070809] px-4 py-3 text-sm text-[#cfcfcf] outline-none focus:border-emerald-400"
/>
- <button className="rounded-xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-3 text-sm font-medium text-[#0b0b0b]">Send</button>
+ <button type="submit" disabled={isSending || !messageInput.trim()} className="rounded-xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-3 text-sm font-medium text-[#0b0b0b] disabled:cursor-not-allowed disabled:opacity-50">{isSending ? 'Working...' : 'Send'}</button>
</div>
- </div>
+ {sendError && <div className="mt-2 text-sm text-red-300">{sendError}</div>}
+ </form>
</section>
</div>
</AppShell>
@@ -581,13 +696,7 @@ function DashboardPage({ user, onLogout }) {
const [summary, setSummary] = useState(null)
useEffect(() => {
- const sessionId = window.localStorage.getItem(SESSION_KEY)
- if (!sessionId) return
-
- apiRequest('/dashboard/summary', {
- method: 'GET',
- headers: { 'x-session-id': sessionId },
- })
+ apiRequest('/dashboard/summary', { method: 'GET' })
.then((data) => setSummary(data))
.catch(() => setSummary(null))
}, [user])
@@ -602,9 +711,9 @@ function DashboardPage({ user, onLogout }) {
: stats
return (
- <AppShell user={user} onLogout={onLogout}>
- <div className="space-y-5">
- <div className="glass-panel rounded-[28px] p-5 md:p-6">
+ <AppShell user={user} onLogout={onLogout} fitViewport>
+ <div className="custom-scroll flex h-full min-h-0 flex-col gap-5 overflow-y-auto pr-1">
+ <div className="glass-panel shrink-0 rounded-[28px] p-5 md:p-6">
<div className="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
<div>
<div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Overview</div>
@@ -614,7 +723,7 @@ function DashboardPage({ user, onLogout }) {
</div>
</div>
- <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
+ <div className="grid shrink-0 gap-4 md:grid-cols-2 xl:grid-cols-4">
{dashboardStats.map((stat) => (
<div key={stat.label} className="glass-panel rounded-[24px] p-5">
<div className={`inline-flex rounded-2xl bg-linear-to-r p-2 ring-1 ${getAccentClasses(stat.accent)}`}>
@@ -629,8 +738,8 @@ function DashboardPage({ user, onLogout }) {
))}
</div>
- <div className="grid gap-5 xl:grid-cols-[1.4fr_0.8fr]">
- <div className="glass-panel rounded-[28px] p-5">
+ <div className="grid min-h-0 flex-1 grid-rows-2 gap-5 xl:grid-cols-[1.4fr_0.8fr] xl:grid-rows-1">
+ <div className="glass-panel flex h-full min-h-0 flex-col rounded-[28px] p-5">
<div className="mb-4 flex items-center justify-between">
<div>
<div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Execution trend</div>
@@ -638,7 +747,7 @@ function DashboardPage({ user, onLogout }) {
</div>
<div className="text-sm text-emerald-300">+28.4%</div>
</div>
- <div className="flex h-52 items-end gap-3">
+ <div className="flex min-h-0 flex-1 items-end gap-3">
{[30, 48, 62, 55, 76, 84, 96].map((bar, index) => (
<div key={index} className="flex flex-1 flex-col items-center gap-2">
<div className="w-full rounded-t-2xl bg-linear-to-t from-[#f5f5f6] to-[#cfcfcf]" style={{ height: `${bar}%` }} />
@@ -648,7 +757,7 @@ function DashboardPage({ user, onLogout }) {
</div>
</div>
- <div className="glass-panel rounded-[28px] p-5">
+ <div className="glass-panel h-full min-h-0 rounded-[28px] p-5">
<div className="mb-4 text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Tasks</div>
<div className="space-y-3">
{[
@@ -675,25 +784,20 @@ function DashboardPage({ user, onLogout }) {
}
function LogsPage({ onOpenThread, user, onLogout }) {
- const navigate = useNavigate()
const [entries, setEntries] = useState(logEntries)
+ const [expandedId, setExpandedId] = useState(null)
useEffect(() => {
- const sessionId = window.localStorage.getItem(SESSION_KEY)
- if (!sessionId) return
-
- apiRequest('/logs', {
- method: 'GET',
- headers: { 'x-session-id': sessionId },
- })
+ apiRequest('/logs', { method: 'GET' })
.then((data) => {
const mapped = (data.logs || []).map((entry) => ({
id: entry.id,
- type: entry.level,
+ type: entry.level === 'ERROR' || entry.level === 'WARN' ? 'ATTENTION' : 'COMPLETED',
+ taskTitle: entry.task_title || entry.message,
message: entry.message,
time: new Date(entry.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }),
actor: entry.source || 'system',
- conversationId: 1,
+ steps: entry.steps || [],
}))
setEntries(mapped)
})
@@ -701,9 +805,9 @@ function LogsPage({ onOpenThread, user, onLogout }) {
}, [user])
return (
- <AppShell user={user} onLogout={onLogout}>
- <div className="glass-panel rounded-[28px] p-5 md:p-6">
- <div className="mb-5 flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
+ <AppShell user={user} onLogout={onLogout} fitViewport>
+ <div className="glass-panel flex h-full min-h-0 flex-col rounded-[28px] p-5 md:p-6">
+ <div className="mb-5 flex shrink-0 flex-col gap-3 md:flex-row md:items-end md:justify-between">
<div>
<div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Event stream</div>
<h1 className="mt-1 text-3xl font-semibold text-white">Logs</h1>
@@ -715,28 +819,43 @@ function LogsPage({ onOpenThread, user, onLogout }) {
</div>
</div>
- <div className="space-y-3">
+ <div className="custom-scroll min-h-0 flex-1 space-y-3 overflow-y-auto pr-1">
{entries.map((entry) => (
- <button
+ <article
key={`${entry.time}-${entry.message}`}
- onClick={() => {
- onOpenThread(entry.conversationId)
- navigate('/')
- }}
- className="flex w-full items-start gap-3 rounded-2xl border border-[#111417] bg-[#0d1013]/70 p-3 text-left transition hover:border-[#1f2326] hover:bg-[#0d1013]"
+ className="rounded-2xl border border-[#111417] bg-[#0d1013]/70 transition hover:border-[#1f2326] hover:bg-[#0d1013]"
>
- <div className={`mt-1 h-2.5 w-2.5 rounded-full ${entry.type === 'ERROR' ? 'bg-red-400' : entry.type === 'WARN' ? 'bg-amber-400' : entry.type === 'SUCCESS' || entry.type === 'INFO' ? 'bg-emerald-400' : 'bg-[#cfcfcf]'}`} />
- <div className="flex-1">
- <div className="flex flex-col gap-1 md:flex-row md:items-center md:justify-between">
- <div className="flex items-center gap-2">
- <span className="text-xs uppercase tracking-[0.2em] text-[#9aa0a6]">{entry.type}</span>
- <span className="text-sm text-white">{entry.message}</span>
+ <button
+ type="button"
+ aria-expanded={expandedId === entry.id}
+ onClick={() => setExpandedId((currentId) => (currentId === entry.id ? null : entry.id))}
+ className="flex w-full items-start gap-3 p-4 text-left"
+ >
+ <div className={`mt-1 h-2.5 w-2.5 shrink-0 rounded-full ${entry.type === 'ATTENTION' ? 'bg-amber-400' : 'bg-emerald-400'}`} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
+ <div className="min-w-0">
+ <div className="text-base font-medium text-white">{entry.taskTitle}</div>
+ <div className="mt-1 line-clamp-1 text-sm text-[#9aa0a6]">{entry.message}</div>
+ </div>
+ <div className="flex shrink-0 items-center gap-3">
+ <span className={`text-xs uppercase tracking-[0.18em] ${entry.type === 'ATTENTION' ? 'text-amber-300' : 'text-emerald-300'}`}>{entry.type}</span>
+ <span className="text-xs text-[#7f8589]">{entry.time}</span>
+ <span className="text-xs text-[#7f8589]">{expandedId === entry.id ? 'Hide' : 'Details'}</span>
+ </div>
</div>
- <span className="text-xs text-[#7f8589]">{entry.time}</span>
+ <div className="mt-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Completed by {entry.actor}</div>
</div>
- <div className="mt-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Actor: {entry.actor}</div>
- </div>
- </button>
+ </button>
+ {expandedId === entry.id && (
+ <div className="border-t border-[#111417] px-4 pb-4 pt-3 pl-11">
+ <div className="mb-2 text-xs uppercase tracking-[0.2em] text-[#9aa0a6]">What Homie did</div>
+ <ul className="space-y-2 text-sm leading-6 text-[#cfcfcf]">
+ {entry.steps.length > 0 ? entry.steps.map((step) => <li key={step} className="flex gap-2"><span className="text-emerald-300">•</span><span>{step}</span></li>) : <li className="text-[#9aa0a6]">No step details were recorded for this task.</li>}
+ </ul>
+ </div>
+ )}
+ </article>
))}
</div>
</div>
@@ -812,35 +931,25 @@ function RequireAuth({ user, children }) {
}
function App() {
- const [activeThreadId, setActiveThreadId] = useState(1)
+ const [activeThreadId, setActiveThreadId] = useState(null)
const [user, setUser] = useState(() => getStoredUser())
const [users, setUsers] = useState(() => getStoredUsers())
useEffect(() => {
if (user) {
window.localStorage.setItem(AUTH_KEY, JSON.stringify(user))
- if (user.sessionId) {
- window.localStorage.setItem(SESSION_KEY, user.sessionId)
- }
} else {
window.localStorage.removeItem(AUTH_KEY)
- window.localStorage.removeItem(SESSION_KEY)
}
}, [user])
useEffect(() => {
- const storedSessionId = window.localStorage.getItem(SESSION_KEY)
- if (!storedSessionId || !user) return
+ if (!user) return
apiRequest('/auth/me', {
method: 'GET',
- headers: { 'x-session-id': storedSessionId },
}).then((data) => {
- setUser((currentUser) => ({
- ...(currentUser || {}),
- ...data.user,
- sessionId: storedSessionId,
- }))
+ setUser((currentUser) => ({ ...(currentUser || {}), ...data.user }))
}).catch(() => {
setUser(null)
})
@@ -859,19 +968,12 @@ function App() {
}
const handleLogout = async () => {
- const sessionId = window.localStorage.getItem(SESSION_KEY)
- if (sessionId) {
- try {
- await apiRequest('/auth/logout', {
- method: 'POST',
- headers: { 'x-session-id': sessionId },
- })
- } catch {
- // Ignore backend logout failures and clear local state.
- }
+ try {
+ await apiRequest('/auth/logout', { method: 'POST' })
+ } catch {
+ // Clear local state even if the session has already expired.
}
setUser(null)
- window.localStorage.removeItem(SESSION_KEY)
}
return (
@@ -885,7 +987,7 @@ function App() {
element={
<RequireAuth user={user}>
<LandingPage
- chatThreads={conversationThreads}
+ chatThreads={[]}
activeThreadId={activeThreadId}
onSelectChat={setActiveThreadId}
user={user}
diff --git a/tests/test_auth_backend.py b/tests/test_auth_backend.py
index 1f1bd1e..6f9f77a 100644
--- a/tests/test_auth_backend.py
+++ b/tests/test_auth_backend.py
@@ -3,10 +3,11 @@ import os
os.environ.setdefault("DATABASE_URL", "sqlite://")
os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")
+import bcrypt
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
-from src.backend.auth import authenticate_user, record_audit_log, register_user
+from src.backend.auth import authenticate_user, ensure_default_user, record_audit_log, register_user
from src.backend.models import AuditLog, Base, User
@@ -26,6 +27,20 @@ class FakeRedis:
return True
+def test_ensure_default_user_is_idempotent():
+ engine = create_engine("sqlite://")
+ Base.metadata.create_all(engine)
+ Session = sessionmaker(bind=engine)
+ session = Session()
+
+ first_user = ensure_default_user(session)
+ second_user = ensure_default_user(session)
+
+ assert first_user.id == second_user.id
+ assert second_user.email == "[email protected]"
+ assert bcrypt.checkpw(b"admin123", second_user.password_hash.encode("utf-8"))
+
+
def test_register_user_creates_record_and_hashes_password():
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)