about summary refs log tree commit diff
path: root/aisearch/src/web
diff options
context:
space:
mode:
Diffstat (limited to 'aisearch/src/web')
-rw-r--r--aisearch/src/web/app.py348
-rw-r--r--aisearch/src/web/auth.py167
-rw-r--r--aisearch/src/web/static/css/style.css962
-rw-r--r--aisearch/src/web/templates/index.html233
-rw-r--r--aisearch/src/web/templates/login.html187
-rw-r--r--aisearch/src/web/templates/partials/response.html12
-rw-r--r--aisearch/src/web/templates/partials/response_body.html55
-rw-r--r--aisearch/src/web/templates/partials/stream_shell.html95
8 files changed, 2059 insertions, 0 deletions
diff --git a/aisearch/src/web/app.py b/aisearch/src/web/app.py
new file mode 100644
index 0000000..68d4a3d
--- /dev/null
+++ b/aisearch/src/web/app.py
@@ -0,0 +1,348 @@
+import asyncio
+import concurrent.futures
+import os
+import uuid
+
+import dspy
+import quart
+import quart_flask_patch  # noqa: F401
+import torch
+from flask_caching import Cache
+from flask_limiter import Limiter
+from flask_limiter.util import get_remote_address
+from gnais.config import Config
+from gnais.search.prompts import GN_FACT_EXTRACTION_PROMPT, GN_UPDATE_MEMORY_PROMPT
+from gnais.search.ragent import hybrid_search
+from markupsafe import escape
+from mem0 import Memory
+from mem0.configs.base import MemoryConfig
+from quart import (
+    Quart,
+    Response,
+    flash,
+    jsonify,
+    redirect,
+    render_template,
+    request,
+    session,
+    url_for,
+)
+from quart.typing import ResponseReturnValue
+from quart_auth import (
+    AuthUser,
+    QuartAuth,
+    Unauthorized,
+    current_user,
+    login_required,
+    login_user,
+    logout_user,
+)
+
+app = Quart(__name__)
+app.config.from_object(Config)
+
+# Basic Login
+app.secret_key = Config.SECRET_KEY
+QuartAuth(app)
+
+# Set up template and static directories
+template_dir = os.path.join(os.path.dirname(__file__), "templates")
+app.template_folder = template_dir
+static_dir = os.path.join(os.path.dirname(__file__), "static")
+app.static_folder = static_dir
+
+
+limiter = Limiter(
+    get_remote_address,
+    app=app,
+    default_limits=["100 per minute"],
+    storage_uri="redis://localhost:6379",
+    strategy="fixed-window",
+)
+
+cache = Cache(config={"CACHE_TYPE": "RedisCache"})
+cache.init_app(app)
+
+#  Bootstrapping our model
+#  NOTE: The backend serving localhost:7501 should also run on the GPU
+#  (e.g. vLLM with --device cuda) for maximum inference throughput.
+torch.manual_seed(app.config["SEED"])
+if torch.cuda.is_available():
+    torch.cuda.manual_seed_all(app.config["SEED"])
+
+
+dspy.configure(lm=app.config["DEFAULT_LLM"])
+
+
+@app.before_serving
+async def _set_default_executor():
+    loop = asyncio.get_running_loop()
+    loop.set_default_executor(concurrent.futures.ThreadPoolExecutor(max_workers=64))
+
+
+#  Shared mem0 memory instance (loaded once at server startup)
+_MEMORY = Memory(
+    config=MemoryConfig(
+        custom_fact_extraction_prompt=GN_FACT_EXTRACTION_PROMPT,
+        custom_update_extraction_prompt=GN_UPDATE_MEMORY_PROMPT,
+        llm={
+            "provider": "litellm",
+            "config": {
+                "model": Config.MEMORY_MODEL,
+                "temperature": 0.5,
+                "max_tokens": 100_000,
+                "api_key": Config.API_KEY,
+            },
+        },
+        embedder={
+            "provider": "huggingface",
+            "config": {
+                "model": "Qwen/Qwen3-Embedding-0.6B",
+                "embedding_dims": 1024,
+                "model_kwargs": {
+                    "trust_remote_code": True,
+                    "device": "cuda" if torch.cuda.is_available() else "cpu",
+                },
+            },
+        },
+        vector_store={
+            "provider": "chroma",
+            "config": {
+                "collection_name": "mem0",
+                "host": "localhost",
+                "port": 8001,
+            },
+        },
+    )
+)
+
+
+def _format_sse(event: str, data: str) -> str:
+    lines = data.splitlines() or [""]
+    payload = [f"event: {event}"]
+    payload.extend(f"data: {line}" for line in lines)
+    payload.append("")
+    return "\n".join(payload) + "\n"
+
+
+def _stream_chunk_markup(content: str, error: bool = False) -> str:
+    css_class = "stream-fragment stream-fragment-error" if error else "stream-fragment"
+    return f"<span class='{css_class}'>{escape(content)}</span>"
+
+
+def _stream_status_markup(label: str, tone: str = "working") -> str:
+    return f"<span class='stream-stage-badge is-{tone}'>{escape(label)}</span>"
+
+
+def _stream_final_status_markup(message: str, tone: str = "waiting") -> str:
+    icon = "🔍" if tone == "waiting" else "✨"
+    return (
+        f"<div class='stream-final-status is-{tone}'>"
+        f"<div class='stream-final-status-icon'>{icon}</div>"
+        f"<div class='stream-final-status-text'>{escape(message)}</div>"
+        "</div>"
+    )
+
+
+@app.route("/login", methods=["GET", "POST"])
+async def login():
+    # KLUDGE: Set a static password for now to prevent token abuse
+    # from non-GN testers.
+    users = {"test@balg-qa.genenetwork.org": os.environ.get("USER_PASS")}
+    if quart.request.method == "GET":
+        return await render_template("login.html")
+    form = await request.form
+    email, password = form.get("email"), form.get("password")
+
+    if email in users and users[email] == password:
+        login_user(AuthUser(email))
+        return redirect(url_for("index"))
+
+    flash("Set the correct user/password")
+    return redirect(url_for("login"))
+
+
+@app.route("/logout")
+async def logout():
+    logout_user()
+    return "Logged out"
+
+
+@app.errorhandler(Unauthorized)
+async def redirect_to_login(*_: Exception) -> ResponseReturnValue:
+    return redirect(url_for("login"))
+
+
+@app.route("/")
+@login_required
+async def index():
+    """Serve the AI search web interface."""
+    return await render_template("index.html")
+
+
+@app.route("/search/stream-shell", methods=["GET"])
+@limiter.limit("300 per day")
+@login_required
+async def search_stream_shell():
+    """Shell endpoint that returns the streaming message container."""
+    query = request.args.get("q", "").strip()
+    if not query:
+        return "<div class='error-message'>Missing query parameter 'q'</div>", 400
+    if len(query) > 1000:
+        return "<div class='error-message'>Query too long</div>", 400
+    if "user_id" not in session:
+        session["user_id"] = str(uuid.uuid4())
+    return await render_template("partials/stream_shell.html", query=query)
+
+
+@app.route("/search/stream", methods=["GET"])
+@limiter.limit("300 per day")
+@login_required
+async def search_stream():
+    """SSE endpoint for live hybrid search updates."""
+    query = request.args.get("q", "").strip()
+    if not query:
+        return Response(
+            _format_sse(
+                "final_html",
+                "<div class='error-message'>Missing query parameter 'q'</div>",
+            ),
+            mimetype="text/event-stream",
+        )
+    if len(query) > 1000:
+        return Response(
+            _format_sse(
+                "final_html", "<div class='error-message'>Query too long</div>"
+            ),
+            mimetype="text/event-stream",
+        )
+
+    user_id = session.get("user_id")
+    if not user_id:
+        session["user_id"] = str(uuid.uuid4())
+        user_id = session["user_id"]
+
+    async def event_stream():
+        completed = set()
+        final_sent = False
+
+        yield _format_sse("search_state", _stream_status_markup("Streaming", "working"))
+        yield _format_sse(
+            "final_html",
+            _stream_final_status_markup("Waiting for searches to complete…", "waiting"),
+        )
+        try:
+            async for event in hybrid_search(query, user_id=user_id, memory=_MEMORY):
+                if final_sent:
+                    break
+
+                source = event["source"]
+                kind = event["kind"]
+                content = event["content"]
+
+                if source in {"rag", "grag", "agent"} and kind == "status":
+                    yield _format_sse(
+                        f"{source}_chunk",
+                        f"<div class='stream-status-msg'>{escape(content)}</div>",
+                    )
+                    continue
+
+                if source in {"rag", "grag", "agent"} and kind == "chunk":
+                    yield _format_sse(
+                        f"{source}_chunk",
+                        _stream_chunk_markup(content),
+                    )
+                    continue
+
+                if source in {"rag", "grag", "agent"} and kind == "final":
+                    yield _format_sse(
+                        f"{source}_final_html",
+                        str(content),
+                    )
+                    continue
+
+                if source in {"rag", "grag", "agent"} and kind == "timing":
+                    yield _format_sse(
+                        f"{source}_timing",
+                        escape(content),
+                    )
+                    continue
+
+                if source in {"rag", "grag", "agent"} and kind == "error":
+                    yield _format_sse(
+                        f"{source}_chunk",
+                        _stream_chunk_markup(content, error=True),
+                    )
+                    yield _format_sse(
+                        f"{source}_done",
+                        _stream_status_markup("Error", "error"),
+                    )
+                    completed.add(source)
+                    if len(completed) == 3 and not final_sent:
+                        yield _format_sse(
+                            "search_state",
+                            _stream_status_markup("Synthesizing", "working"),
+                        )
+                        yield _format_sse(
+                            "final_html",
+                            "<div class='synthesis-stream' sse-swap='synthesis_chunk' hx-swap='beforeend'></div>",
+                        )
+                    continue
+
+                if source in {"rag", "grag", "agent"} and kind == "done":
+                    yield _format_sse(
+                        f"{source}_done",
+                        _stream_status_markup("Complete", "complete"),
+                    )
+                    completed.add(source)
+                    if len(completed) == 3 and not final_sent:
+                        yield _format_sse(
+                            "search_state",
+                            _stream_status_markup("Synthesizing", "working"),
+                        )
+                        yield _format_sse(
+                            "final_html",
+                            "<div class='synthesis-stream' sse-swap='synthesis_chunk' hx-swap='beforeend'></div>",
+                        )
+                    continue
+
+                if source == "synthesis" and kind == "chunk":
+                    yield _format_sse("synthesis_chunk", content)
+                    continue
+
+                if source == "hybrid" and kind == "timing":
+                    yield _format_sse(
+                        "total_timing",
+                        f"Total: {escape(content)}",
+                    )
+                    continue
+
+                if source == "hybrid" and kind == "final":
+                    final_sent = True
+                    # await asyncio.to_thread(cache.set, cache_key, content, timeout=3600)
+                    yield _format_sse("final_html", content)
+                    yield _format_sse(
+                        "search_state", _stream_status_markup("Complete", "complete")
+                    )
+                    yield _format_sse("stream_end", "<div></div>")
+                    return
+        except Exception as exc:
+            error_html = f"<div class='error-display'>{escape(str(exc))}</div>"
+            yield _format_sse("final_html", error_html)
+            yield _format_sse("stream_end", "<div></div>")
+
+    response = Response(
+        event_stream(),
+        mimetype="text/event-stream",
+        headers={
+            "Cache-Control": "no-cache",
+            "Connection": "keep-alive",
+            "X-Accel-Buffering": "no",
+        },
+    )
+    response.timeout = None
+    return response
+
+
+if __name__ == "__main__":
+    app.run(host="0.0.0.0", port=5001, debug=True)
diff --git a/aisearch/src/web/auth.py b/aisearch/src/web/auth.py
new file mode 100644
index 0000000..af15505
--- /dev/null
+++ b/aisearch/src/web/auth.py
@@ -0,0 +1,167 @@
+"""Authentication and authorization utilities for ai-search.
+
+This module provides JWT token validation using JWKS from the auth server.
+"""
+
+import logging
+from datetime import datetime
+from functools import wraps
+from typing import Optional
+from urllib.parse import urljoin
+
+import requests
+from authlib.jose import JsonWebKey, JsonWebToken, KeySet
+from authlib.jose.errors import BadSignatureError
+from quart import request, jsonify, current_app
+
+logger = logging.getLogger(__name__)
+
+
+class TokenValidationError(Exception):
+    """Raised when token validation fails."""
+
+    pass
+
+
+def fetch_jwks(auth_server_url: str, timeout: int = 30) -> KeySet:
+    """Fetch JSON Web Keys from the auth server."""
+    jwks_uri = urljoin(auth_server_url, "auth/public-jwks")
+    response = requests.get(jwks_uri, timeout=timeout)
+    response.raise_for_status()
+    jwks_data = response.json()
+    keys = [
+        JsonWebKey.import_key(key) for key in jwks_data.get("jwks", {}).get("keys", [])
+    ]
+    if not keys:
+        raise TokenValidationError("No keys found in JWKS response")
+    return KeySet(keys)
+
+
+def get_cached_jwks(auth_server_url: str) -> KeySet:
+    """Get cached JWKS from Redis, fetching if necessary."""
+    cache = current_app.extensions["cache"]
+    cached = cache.get("auth_server_jwks")
+
+    if cached is not None:
+        return KeySet([JsonWebKey.import_key(key) for key in cached])
+
+    # Fetch and cache for 2 hours
+    jwks = fetch_jwks(auth_server_url)
+    key_data = [key.export() for key in jwks.keys]
+    cache.set("auth_server_jwks", key_data, timeout=7200)
+    return jwks
+
+
+def validate_token(token: str, keys: KeySet) -> dict:
+    """Validate a JWT token against the provided keys.
+
+    Args:
+        token: The JWT token string
+        keys: KeySet containing valid public keys
+
+    Returns:
+        Decoded JWT payload
+
+    Raises:
+        TokenValidationError: If token is invalid or cannot be verified
+    """
+    for key in keys.keys:
+        try:
+            jwt = JsonWebToken(["RS256"])
+            payload = jwt.decode(token, key)
+
+            # Check expiration
+            if payload.get("exp") and datetime.now().timestamp() > payload["exp"]:
+                raise TokenValidationError("Token has expired")
+
+            logger.debug("Token validated successfully")
+            return payload
+        except BadSignatureError:
+            continue
+
+    raise TokenValidationError("Token signature could not be verified")
+
+
+def require_token(func):
+    """Decorator that requires a valid bearer token for the endpoint.
+
+    Expects the Authorization header with a Bearer token.
+    Adds `auth_token` kwarg to the decorated function with the decoded JWT payload.
+
+    Example:
+        @app.route("/api/v1/search")
+        @require_token
+        async def search(auth_token=None):
+            # auth_token contains the decoded JWT payload
+            user_id = auth_token.get("sub")
+            ...
+    """
+
+    @wraps(func)
+    async def wrapper(*args, **kwargs):
+        auth_server_url = current_app.config.get("AUTH_SERVER_URL")
+
+        if not auth_server_url:
+            logger.error("AUTH_SERVER_URL not configured")
+            return jsonify(
+                {
+                    "error": "ConfigurationError",
+                    "description": "Authentication not properly configured",
+                }
+            ), 500
+
+        # Extract bearer token from Authorization header
+        bearer = request.headers.get("Authorization", "")
+
+        if not bearer.startswith("Bearer "):
+            logger.debug("No bearer token provided")
+            return jsonify(
+                {
+                    "error": "AuthenticationError",
+                    "description": "Expected 'Authorization: Bearer <token>' header",
+                }
+            ), 401
+
+        try:
+            _, token = bearer.split(" ", 1)
+            token = token.strip()
+
+            # Get cached JWKS and validate token
+            jwks = get_cached_jwks(auth_server_url)
+            jwt_payload = validate_token(token, jwks)
+
+            # Add auth token info to kwargs
+            kwargs["auth_token"] = {"access_token": token, "jwt": jwt_payload}
+
+            return await func(*args, **kwargs)
+
+        except TokenValidationError as exc:
+            logger.debug("Token validation failed: %s", exc)
+            return jsonify(
+                {"error": "TokenValidationError", "description": str(exc)}
+            ), 401
+        except Exception:
+            logger.error("Unexpected error during token validation", exc_info=True)
+            return jsonify(
+                {
+                    "error": "InternalError",
+                    "description": "Failed to validate authentication token",
+                }
+            ), 500
+
+    return wrapper
+
+
+def get_user_id(auth_token: Optional[dict] = None) -> Optional[str]:
+    """Extract user ID from auth token.
+
+    Args:
+        auth_token: The auth token dict with 'jwt' key containing the payload
+
+    Returns:
+        User ID (subject claim) or None if not available
+    """
+    if auth_token is None:
+        return None
+    jwt_payload = auth_token.get("jwt", {})
+    return jwt_payload.get("sub")
diff --git a/aisearch/src/web/static/css/style.css b/aisearch/src/web/static/css/style.css
new file mode 100644
index 0000000..38fc5a5
--- /dev/null
+++ b/aisearch/src/web/static/css/style.css
@@ -0,0 +1,962 @@
+:root {
+    --bg: #fff;
+    --bg-accent: #f5f5f5;
+    --surface: #fff;
+    --surface-strong: #fff;
+    --surface-muted: #f9f9f9;
+    --line: #ddd;
+    --line-strong: #ccc;
+    --text: #000;
+    --muted: #777;
+    --accent: #3071a9;
+    --accent-strong: #245269;
+    --blue: #3071a9;
+    --success: #3c763d;
+    --warning: #8a6d3b;
+    --error: #a94442;
+    --shadow: none;
+    --shadow-soft: none;
+    --radius-xl: 24px;
+    --radius-lg: 18px;
+    --radius-md: 14px;
+}
+
+* {
+    margin: 0;
+    padding: 0;
+    box-sizing: border-box;
+}
+
+html,
+body {
+    min-height: 100%;
+}
+
+body {
+    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+    background: #fff;
+    color: var(--text);
+    height: 100vh;
+    display: flex;
+    flex-direction: column;
+}
+
+.header {
+    padding: 1rem 1.4rem;
+    display: flex;
+    align-items: center;
+    gap: 1rem;
+    background: #222;
+    border-bottom: 1px solid #080808;
+    position: sticky;
+    top: 0;
+    z-index: 20;
+}
+
+.header-logo {
+    width: 38px;
+    height: 38px;
+    border-radius: 14px;
+    background: #3071a9;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    color: white;
+    font-weight: 700;
+    letter-spacing: 0.04em;
+}
+
+.header-title {
+    font-size: 1.05rem;
+    font-weight: 700;
+    letter-spacing: 0.02em;
+    color: #fff;
+}
+
+.chat-container {
+    flex: 1;
+    min-height: 0;
+    overflow-y: auto;
+    padding: 1.5rem 1rem 2rem;
+    max-width: 1100px;
+    margin: 0 auto;
+    width: 100%;
+    scrollbar-width: none;
+}
+
+.chat-container::-webkit-scrollbar {
+    display: none;
+}
+
+#messages {
+    display: flex;
+    flex-direction: column;
+    gap: 1.4rem;
+}
+
+.empty-state {
+    text-align: center;
+    padding: 4rem 1rem 2rem;
+    color: var(--muted);
+    max-width: 820px;
+    margin: 0 auto;
+}
+
+.empty-state h1 {
+    font-family: Georgia, "Times New Roman", serif;
+    font-size: clamp(2.6rem, 5vw, 4.5rem);
+    line-height: 0.96;
+    letter-spacing: -0.03em;
+    margin-bottom: 1rem;
+    color: var(--text);
+}
+
+.empty-state p {
+    font-size: 1.02rem;
+    margin-bottom: 0.5rem;
+}
+
+.examples {
+    margin-top: 2rem;
+    display: grid;
+    gap: 0.85rem;
+    text-align: left;
+}
+
+.example-btn {
+    background: #f9f9f9;
+    border: 1px solid #ddd;
+    border-radius: 16px;
+    padding: 1rem 1.1rem;
+    cursor: pointer;
+    color: #333;
+    font-size: 0.96rem;
+    text-align: left;
+    transition: transform 0.2s ease, border-color 0.2s ease, background 0.2s ease;
+}
+
+.example-btn:hover {
+    transform: translateY(-1px);
+    border-color: #3071a9;
+    background: #fff;
+}
+
+.message {
+    animation: fadeIn 0.28s ease;
+}
+
+@keyframes fadeIn {
+    from {
+        opacity: 0;
+        transform: translateY(8px);
+    }
+    to {
+        opacity: 1;
+        transform: translateY(0);
+    }
+}
+
+.message-user {
+    display: flex;
+    justify-content: flex-end;
+}
+
+.message-user .message-content {
+    max-width: min(78%, 760px);
+    background: #3071a9;
+    color: white;
+    border-radius: 22px 22px 8px 22px;
+    padding: 1rem 1.3rem;
+    line-height: 1.65;
+}
+
+.message-ai {
+    display: flex;
+    gap: 1rem;
+    position: relative;
+}
+
+.avatar {
+    width: 40px;
+    height: 40px;
+    border-radius: 14px;
+    background: #222;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    color: white;
+    font-weight: 700;
+    flex-shrink: 0;
+}
+
+.message-ai .message-content {
+    flex: 1;
+    background: var(--surface);
+    border: 1px solid #ddd;
+    border-radius: var(--radius-xl);
+    padding: 1.25rem;
+    line-height: 1.75;
+}
+
+.message-ai-stream .message-content {
+    padding: 1.35rem;
+}
+
+.stream-shell {
+    display: grid;
+    gap: 1rem;
+}
+
+.stream-shell-header {
+    display: flex;
+    justify-content: space-between;
+    gap: 1rem;
+    align-items: start;
+}
+
+.stream-shell-kicker,
+.stream-final-kicker {
+    text-transform: uppercase;
+    letter-spacing: 0.12em;
+    font-size: 0.72rem;
+    font-weight: 700;
+    color: var(--accent);
+}
+
+.stream-shell-header h2 {
+    margin-top: 0.25rem;
+    font-size: 1.15rem;
+    line-height: 1.2;
+}
+
+.stream-shell-intro {
+    color: var(--muted);
+    font-size: 0.96rem;
+}
+
+.stream-stage-grid {
+    display: grid;
+    grid-template-columns: repeat(3, minmax(0, 1fr));
+    gap: 0.9rem;
+}
+
+.stream-stage-card {
+    background: #fafafa;
+    border: 1px solid var(--line);
+    border-radius: var(--radius-lg);
+    padding: 1rem;
+    min-height: 220px;
+    display: flex;
+    flex-direction: column;
+    gap: 0.8rem;
+}
+
+.stream-stage-card.is-muted {
+    opacity: 0.75;
+}
+
+.stream-stage-head,
+.stream-final-head {
+    display: flex;
+    justify-content: space-between;
+    gap: 0.8rem;
+    align-items: center;
+}
+
+.stream-stage-meta,
+.stream-final-meta {
+    display: flex;
+    align-items: center;
+    gap: 0.6rem;
+}
+
+.stream-stage-timing,
+.stream-final-timing {
+    font-family: "SFMono-Regular", "Menlo", "Consolas", monospace;
+    font-size: 0.75rem;
+    color: var(--muted);
+    white-space: nowrap;
+}
+
+.stream-final-timing {
+    font-weight: 600;
+    color: var(--accent);
+}
+
+.stream-stage-name {
+    font-size: 0.95rem;
+    font-weight: 700;
+}
+
+.stream-stage-badge {
+    display: inline-flex;
+    align-items: center;
+    gap: 0.35rem;
+    font-size: 0.74rem;
+    border-radius: 999px;
+    padding: 0.28rem 0.58rem;
+    border: 1px solid transparent;
+    white-space: nowrap;
+}
+
+.stream-stage-badge.is-working {
+    color: #31708f;
+    background: #d9edf7;
+    border-color: #bce8f1;
+}
+
+.stream-stage-badge.is-working::before {
+    content: "";
+    display: inline-block;
+    width: 0.75em;
+    height: 0.75em;
+    border: 2px solid currentColor;
+    border-right-color: transparent;
+    border-radius: 50%;
+    animation: spin 1s linear infinite;
+}
+
+.stream-stage-badge.is-complete {
+    color: var(--success);
+    background: #dff0d8;
+    border-color: #d6e9c6;
+}
+
+.stream-stage-badge.is-complete::before {
+    content: "âś“";
+    display: inline-flex;
+    align-items: center;
+    justify-content: center;
+    width: 1em;
+    height: 1em;
+    font-size: 0.7em;
+    font-weight: 700;
+    background: var(--success);
+    color: white;
+    border-radius: 50%;
+}
+
+.stream-stage-badge.is-error {
+    color: var(--error);
+    background: #f2dede;
+    border-color: #ebccd1;
+}
+
+.stream-stage-body-scroll {
+    flex: 1;
+    min-height: 0;
+    max-height: 220px;
+    overflow-y: auto;
+    padding-right: 0.4rem;
+    overscroll-behavior: contain;
+}
+
+.stream-stage-body-scroll::-webkit-scrollbar {
+    width: 6px;
+}
+
+.stream-stage-body-scroll::-webkit-scrollbar-thumb {
+    background: #ccc;
+    border-radius: 999px;
+}
+
+.stream-stage-body {
+    font-family: "SFMono-Regular", "Menlo", "Consolas", monospace;
+    font-size: 0.84rem;
+    line-height: 1.65;
+    color: #555;
+    white-space: pre-wrap;
+    word-break: break-word;
+}
+
+.stream-init-msg {
+    font-family: "SFMono-Regular", "Menlo", "Consolas", monospace;
+    font-size: 0.84rem;
+    color: var(--muted);
+    font-style: italic;
+    padding: 0.25rem 0;
+    animation: blink 1.4s infinite ease-in-out;
+}
+
+.stream-stage-body-scroll:has(.stream-stage-body:not(:empty)) .stream-init-msg {
+    display: none;
+}
+
+@keyframes blink {
+    0%, 100% {
+        opacity: 1;
+    }
+    50% {
+        opacity: 0.35;
+    }
+}
+
+.stream-fragment {
+    display: inline;
+}
+
+.stream-fragment-error {
+    color: var(--error);
+}
+
+.stream-status-msg {
+    font-family: "SFMono-Regular", "Menlo", "Consolas", monospace;
+    font-size: 0.84rem;
+    color: var(--muted);
+    font-style: italic;
+    padding: 0.15rem 0;
+    border-left: 2px solid var(--accent);
+    padding-left: 0.5rem;
+    margin: 0.2rem 0;
+    animation: fadeIn 0.3s ease;
+}
+
+.stream-final-card {
+    background: #fff;
+    border: 1px solid var(--line);
+    border-radius: calc(var(--radius-xl) + 2px);
+    padding: 1.2rem 1.25rem;
+}
+
+.stream-final-note {
+    font-size: 0.82rem;
+    color: var(--muted);
+}
+
+.stream-final-body {
+    margin-top: 1rem;
+}
+
+.stream-final-status {
+    border: 1px dashed #ccc;
+    border-radius: var(--radius-md);
+    padding: 1.25rem;
+    color: var(--muted);
+    background: #f9f9f9;
+    text-align: center;
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    gap: 0.5rem;
+}
+
+.stream-final-status.is-waiting {
+    animation: pulse-soft 2s infinite ease-in-out;
+}
+
+.stream-final-status.is-synthesizing {
+    animation: pulse-soft 1.5s infinite ease-in-out;
+}
+
+.stream-final-status-icon {
+    font-size: 1.5rem;
+    line-height: 1;
+    opacity: 0.85;
+}
+
+.stream-final-status-text {
+    font-size: 0.95rem;
+    font-weight: 500;
+}
+
+@keyframes pulse-soft {
+    0%, 100% {
+        opacity: 1;
+    }
+    50% {
+        opacity: 0.55;
+    }
+}
+
+.ai-response h3 {
+    color: var(--text);
+    margin: 1.5rem 0 0.8rem;
+    font-size: 1.08rem;
+    border-bottom: 1px solid var(--line);
+    padding-bottom: 0.45rem;
+}
+
+.ai-response h3:first-child {
+    margin-top: 0;
+}
+
+.summary {
+    background: #d9edf7;
+    border-left: 4px solid var(--accent);
+    padding: 1rem 1.1rem;
+    margin: 0.85rem 0 1.2rem;
+    border-radius: 0 12px 12px 0;
+    color: #245269;
+}
+
+.status-success,
+.status-partial,
+.status-error {
+    display: inline-flex;
+    align-items: center;
+    gap: 0.45rem;
+    font-size: 0.88rem;
+    margin-bottom: 0.8rem;
+    font-weight: 600;
+}
+
+.status-success {
+    color: var(--success);
+}
+
+.status-partial {
+    color: var(--warning);
+}
+
+.status-error {
+    color: var(--error);
+}
+
+.status-success::before,
+.status-partial::before,
+.status-error::before {
+    width: 18px;
+    height: 18px;
+    border-radius: 999px;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    color: white;
+    font-size: 11px;
+}
+
+.status-success::before {
+    content: "âś“";
+    background: var(--success);
+}
+
+.status-partial::before {
+    content: "!";
+    background: var(--warning);
+}
+
+.status-error::before {
+    content: "âś•";
+    background: var(--error);
+}
+
+.card-list {
+    list-style: none;
+    display: grid;
+    gap: 0.9rem;
+    margin-top: 0.9rem;
+}
+
+.card-item {
+    background: #fff;
+    border: 1px solid var(--line);
+    border-radius: var(--radius-md);
+    padding: 1rem;
+    transition: transform 0.2s ease, border-color 0.2s ease;
+}
+
+.card-item:hover {
+    transform: translateY(-1px);
+    border-color: #3071a9;
+}
+
+.card-title {
+    font-weight: 700;
+    color: var(--blue);
+    font-size: 1.03rem;
+    margin-bottom: 0.45rem;
+}
+
+.card-title a {
+    color: inherit;
+    text-decoration: none;
+}
+
+.card-title a:hover {
+    text-decoration: underline;
+}
+
+.card-description {
+    color: #333;
+    font-size: 0.95rem;
+    line-height: 1.6;
+    margin-bottom: 0.45rem;
+}
+
+.card-meta {
+    color: var(--muted);
+    font-size: 0.88rem;
+    font-style: italic;
+}
+
+.note-box,
+.access-note,
+.error-display,
+.raw-response {
+    border-radius: var(--radius-md);
+    padding: 1rem;
+    margin-top: 1rem;
+}
+
+.note-box {
+    background: #fcf8e3;
+    border: 1px solid #faebcc;
+    color: #8a6d3b;
+}
+
+.access-note {
+    background: #dff0d8;
+    border: 1px solid #d6e9c6;
+    color: #3c763d;
+}
+
+.error-display {
+    background: #f2dede;
+    border: 1px solid #ebccd1;
+    color: #a94442;
+}
+
+.raw-response {
+    background: #f5f5f5;
+    border: 1px solid var(--line);
+    font-family: "SFMono-Regular", "Menlo", "Consolas", monospace;
+    font-size: 0.85rem;
+    white-space: pre-wrap;
+    word-wrap: break-word;
+    max-height: 200px;
+    overflow-y: auto;
+}
+
+.loading-message {
+    display: flex;
+    align-items: center;
+    gap: 1rem;
+    color: var(--muted);
+    padding: 0.8rem 0.2rem;
+}
+
+.loading-dots {
+    display: flex;
+    gap: 4px;
+}
+
+.loading-dots span {
+    width: 8px;
+    height: 8px;
+    background: var(--accent);
+    border-radius: 50%;
+    animation: bounce 1.4s infinite ease-in-out;
+}
+
+.loading-dots span:nth-child(2) {
+    animation-delay: 0.2s;
+}
+
+.loading-dots span:nth-child(3) {
+    animation-delay: 0.4s;
+}
+
+@keyframes spin {
+    to {
+        transform: rotate(360deg);
+    }
+}
+
+@keyframes bounce {
+    0%, 80%, 100% {
+        transform: scale(0.2);
+        opacity: 0.5;
+    }
+    40% {
+        transform: scale(1);
+        opacity: 1;
+    }
+}
+
+.htmx-indicator {
+    display: none !important;
+}
+
+.htmx-request.htmx-indicator {
+    display: flex !important;
+}
+
+.input-container {
+    padding: 1rem 1rem 1.5rem;
+    background: #fff;
+    border-top: 1px solid #f0f0f0;
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    gap: 0.25rem;
+}
+
+.input-wrapper {
+    max-width: 768px;
+    width: 100%;
+    margin: 0 auto;
+    display: flex;
+    align-items: flex-end;
+    gap: 0.5rem;
+    background: #fff;
+    border: 1px solid #e5e5e5;
+    border-radius: 24px;
+    padding: 0.5rem 0.6rem 0.5rem 1.25rem;
+    box-shadow:
+        0 2px 12px rgba(0, 0, 0, 0.06),
+        0 0 0 1px rgba(0, 0, 0, 0.02);
+    transition: box-shadow 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
+}
+
+.input-wrapper:focus-within {
+    box-shadow:
+        0 2px 16px rgba(48, 113, 169, 0.10),
+        0 0 0 1px rgba(48, 113, 169, 0.15);
+    border-color: rgba(48, 113, 169, 0.25);
+}
+
+.textarea-box {
+    flex: 1;
+    position: relative;
+    min-width: 0;
+    display: flex;
+    align-items: flex-start;
+}
+
+.search-input {
+    width: 100%;
+    min-height: 44px;
+    max-height: 200px;
+    padding: 10px 28px 10px 0;
+    font-size: 16px;
+    line-height: 1.5;
+    border: none;
+    background: transparent;
+    outline: none;
+    color: #222;
+    resize: none;
+    overflow-y: hidden;
+    font-family: inherit;
+}
+
+.search-input::placeholder {
+    color: #999;
+}
+
+.search-input:disabled {
+    opacity: 0.5;
+    cursor: not-allowed;
+}
+
+.clear-btn {
+    position: absolute;
+    right: 0;
+    top: 8px;
+    background: none;
+    border: none;
+    color: #999;
+    font-size: 1.2rem;
+    line-height: 1;
+    cursor: pointer;
+    width: 24px;
+    height: 24px;
+    display: none;
+    align-items: center;
+    justify-content: center;
+    border-radius: 50%;
+    transition: color 0.15s ease, background 0.15s ease;
+}
+
+.clear-btn:hover {
+    color: #666;
+    background: #f0f0f0;
+}
+
+.search-button,
+.stop-button {
+    width: 36px;
+    height: 36px;
+    border-radius: 50%;
+    border: none;
+    color: white;
+    cursor: pointer;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    flex-shrink: 0;
+    transition: transform 0.15s ease, background 0.15s ease, opacity 0.15s ease;
+    margin-bottom: 4px;
+}
+
+.search-button {
+    background: #3071a9;
+    font-size: 1.1rem;
+}
+
+.search-button:hover {
+    transform: scale(1.06);
+    background: #245269;
+}
+
+.search-button:disabled {
+    opacity: 0.4;
+    cursor: not-allowed;
+}
+
+.stop-button {
+    background: #e53935;
+    display: none;
+}
+
+.stop-button:hover {
+    transform: scale(1.06);
+    background: #c62828;
+}
+
+.stop-button:active {
+    transform: scale(0.95);
+    background: #b71c1c;
+}
+
+.char-counter {
+    max-width: 768px;
+    width: 100%;
+    margin: 0 auto;
+    text-align: right;
+    font-size: 0.75rem;
+    color: #999;
+    padding-right: 0.75rem;
+    min-height: 1.2em;
+}
+
+.char-counter.caution {
+    color: #f5a623;
+}
+
+.char-counter.warning {
+    color: #e53935;
+}
+
+.copy-btn {
+    position: absolute;
+    top: 0.75rem;
+    right: 0.75rem;
+    background: #fff;
+    border: 1px solid var(--line);
+    border-radius: 999px;
+    padding: 0.36rem 0.7rem;
+    font-size: 0.78rem;
+    color: var(--muted);
+    cursor: pointer;
+    opacity: 0;
+    transition: opacity 0.2s ease, background 0.2s ease;
+}
+
+.message-ai:hover .copy-btn {
+    opacity: 1;
+}
+
+.copy-btn:hover {
+    background: white;
+}
+
+.scroll-to-bottom-btn {
+    position: fixed;
+    bottom: 100px;
+    right: 24px;
+    z-index: 100;
+    background: var(--accent);
+    color: white;
+    border: none;
+    border-radius: 50%;
+    width: 44px;
+    height: 44px;
+    font-size: 1.2rem;
+    line-height: 1;
+    cursor: pointer;
+    opacity: 0;
+    pointer-events: none;
+    transition: opacity 0.2s ease, transform 0.2s ease, background 0.2s ease;
+    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.18);
+    display: flex;
+    align-items: center;
+    justify-content: center;
+}
+
+.scroll-to-bottom-btn.visible {
+    opacity: 1;
+    pointer-events: auto;
+}
+
+.scroll-to-bottom-btn:hover {
+    transform: scale(1.06);
+    background: var(--accent-strong);
+}
+
+.error-message {
+    background: #f2dede;
+    border: 1px solid #ebccd1;
+    border-radius: var(--radius-md);
+    padding: 1rem;
+    color: #a94442;
+}
+
+@media (max-width: 920px) {
+    .stream-stage-grid {
+        grid-template-columns: 1fr;
+    }
+
+    .stream-stage-body-scroll {
+        max-height: 180px;
+    }
+
+    .message-user .message-content {
+        max-width: 92%;
+    }
+}
+
+@media (max-width: 640px) {
+    .header {
+        padding: 0.85rem 1rem;
+    }
+
+    .chat-container {
+        padding: 1rem 0.75rem 1.5rem;
+    }
+
+    .message-ai {
+        gap: 0.75rem;
+    }
+
+    .avatar {
+        width: 34px;
+        height: 34px;
+        border-radius: 12px;
+    }
+
+    .message-ai .message-content,
+    .message-user .message-content {
+        padding: 1rem;
+    }
+
+    .stream-shell-header,
+    .stream-final-head {
+        flex-direction: column;
+        align-items: flex-start;
+    }
+
+    .copy-btn {
+        position: static;
+        opacity: 1;
+        margin-top: 0.75rem;
+    }
+
+    .input-container {
+        padding: 0.75rem;
+    }
+
+    .input-wrapper {
+        border-radius: 20px;
+        padding: 0.4rem 0.5rem 0.4rem 1rem;
+    }
+}
diff --git a/aisearch/src/web/templates/index.html b/aisearch/src/web/templates/index.html
new file mode 100644
index 0000000..02d61f1
--- /dev/null
+++ b/aisearch/src/web/templates/index.html
@@ -0,0 +1,233 @@
+<!DOCTYPE html>
+<html lang="en">
+    <head>
+        <meta charset="utf-8">
+        <meta name="viewport" content="width=device-width, initial-scale=1.0">
+        <title>GeneNetwork AI Search</title>
+        <script src="https://unpkg.com/htmx.org@2.0.8"></script>
+        <script src="https://unpkg.com/htmx-ext-sse@2.2.4/sse.js"></script>
+        <script src="https://unpkg.com/hyperscript.org@0.9.12"></script>
+        <link rel="stylesheet"
+              href="{{ url_for('static', filename='css/style.css') }}">
+    </head>
+    <body>
+        <div class="header">
+            <div class="header-logo">GN</div>
+            <div class="header-title">GeneNetwork AI Search</div>
+        </div>
+        <div class="chat-container" id="chat-container">
+            <div class="empty-state" id="empty-state">
+                <h1>GeneNetwork AI Search</h1>
+                <p>Ask natural language questions about genes, traits, and datasets</p>
+                <p style="font-size: 0.9em; color: #999;">Powered by Hybrid RAG + Agent</p>
+                <div class="examples">
+                    <button type="button"
+                            class="example-btn"
+                            _="on click set #search-input.value to 'What genes are associated with diabetes?' then call #search-input.focus()">
+                        What genes are associated with diabetes?
+                    </button>
+                    <button type="button"
+                            class="example-btn"
+                            _="on click set #search-input.value to 'Find datasets related to obesity' then call #search-input.focus()">
+                        Find datasets related to obesity
+                    </button>
+                    <button type="button"
+                            class="example-btn"
+                            _="on click set #search-input.value to 'How does the mosaic structure of BXD recombinant inbred mice genomes affect mapping resolution across generations?' then call #search-input.focus()">
+                        How does the mosaic structure of BXD recombinant inbred mice genomes affect mapping resolution across generations?
+                    </button>
+                </div>
+            </div>
+            <!-- messages wrapper -->
+            <div id="messages"></div>
+            <!-- indicator sits after messages so it appears at the bottom -->
+            <div id="loading-indicator" class="message message-ai htmx-indicator">
+                <div class="avatar">AI</div>
+                <div class="message-content">
+                    <div class="loading-message">
+                        <div class="loading-dots">
+                            <span></span><span></span><span></span>
+                        </div>
+                        <span>Searching GeneNetwork data...</span>
+                    </div>
+                </div>
+            </div>
+        </div>
+        <div class="input-container">
+            <form class="input-wrapper"
+                  id="search-form"
+                  hx-get="/search/stream-shell"
+                  hx-target="#messages"
+                  hx-swap="beforeend"
+                  hx-indicator="#loading-indicator"
+                  _="on htmx:beforeRequest
+                         if no #search-input.value.trim() halt end
+                         put 'none' into #empty-state's style.display
+                         on htmx:afterRequest
+                         put '' into #search-input.value
+                         call #search-input.focus()">
+                <div class="textarea-box">
+                    <textarea name="q"
+                              id="search-input"
+                              class="search-input"
+                              placeholder="Ask a question about genes, traits, or datasets... (Shift+Enter for new line)"
+                              rows="1"
+                              autocomplete="off"
+                              autofocus></textarea>
+                    <button type="button"
+                            class="clear-btn"
+                            id="clear-btn"
+                            title="Clear message"
+                            aria-label="Clear message">Ă—</button>
+                </div>
+                <button type="submit"
+                        class="search-button"
+                        id="search-btn"
+                        aria-label="Send"
+                        title="Send">↑</button>
+                <button type="button"
+                        class="stop-button"
+                        id="stop-btn"
+                        aria-label="Stop generating"
+                        title="Stop generating">
+                    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true">
+                        <rect x="6" y="6" width="12" height="12" rx="2" />
+                    </svg>
+                </button>
+            </form>
+            <div class="char-counter" id="char-counter">0 / 1000</div>
+        </div>
+        <button id="scroll-to-bottom" class="scroll-to-bottom-btn" title="Scroll to bottom">↓</button>
+
+        <script type="text/hyperscript">
+         def focusInput()
+         call #search-input.focus()
+         end
+        </script>
+        <script>
+        (function(){
+            const chat = document.getElementById('chat-container');
+            const btn = document.getElementById('scroll-to-bottom');
+            const messages = document.getElementById('messages');
+            if (!chat || !btn || !messages) return;
+            const THRESHOLD = 80;
+            let atBottom = true;
+
+            function check() {
+                atBottom = chat.scrollHeight - chat.scrollTop <= chat.clientHeight + THRESHOLD;
+                btn.classList.toggle('visible', !atBottom);
+            }
+
+            chat.addEventListener('scroll', check);
+            window.addEventListener('resize', check);
+
+            new MutationObserver(function(muts) {
+                var hit = muts.some(function(m) {
+                    return m.target.closest && m.target.closest('.stream-final-body');
+                });
+                if (!hit) return;
+                if (atBottom) chat.scrollTop = chat.scrollHeight;
+                else btn.classList.add('visible');
+            }).observe(messages, { childList: true, subtree: true });
+
+            btn.addEventListener('click', function(){
+                chat.scrollTop = chat.scrollHeight;
+                atBottom = true;
+                btn.classList.remove('visible');
+            });
+        })();
+        </script>
+        <script>
+        (function(){
+            const input = document.getElementById('search-input');
+            const sendBtn = document.getElementById('search-btn');
+            const stopBtn = document.getElementById('stop-btn');
+            const clearBtn = document.getElementById('clear-btn');
+            const charCounter = document.getElementById('char-counter');
+            const messages = document.getElementById('messages');
+            const form = document.getElementById('search-form');
+            if (!input || !sendBtn || !stopBtn || !messages || !form) return;
+            const MAX_HEIGHT = 200;
+            const MAX_CHARS = 1000;
+
+            function autoGrow() {
+                input.style.height = 'auto';
+                var h = Math.min(input.scrollHeight, MAX_HEIGHT);
+                input.style.height = h + 'px';
+                input.style.overflowY = input.scrollHeight > MAX_HEIGHT ? 'auto' : 'hidden';
+            }
+
+            function updateUI() {
+                var len = input.value.length;
+                if (charCounter) {
+                    charCounter.textContent = len + ' / ' + MAX_CHARS;
+                    charCounter.classList.remove('warning', 'caution');
+                    if (len > 900) charCounter.classList.add('warning');
+                    else if (len > 700) charCounter.classList.add('caution');
+                }
+                if (clearBtn) clearBtn.style.display = len > 0 ? 'flex' : 'none';
+            }
+
+            function setStreaming(v) {
+                input.disabled = v;
+                sendBtn.style.display = v ? 'none' : 'flex';
+                stopBtn.style.display = v ? 'flex' : 'none';
+                if (!v) {
+                    input.focus();
+                    autoGrow();
+                    updateUI();
+                }
+            }
+
+            window.onStreamEnd = function() { setStreaming(false); };
+
+            form.addEventListener('htmx:afterRequest', function(evt) {
+                if (evt.detail.successful) setStreaming(true);
+                setTimeout(function() {
+                    autoGrow();
+                    updateUI();
+                }, 0);
+            });
+
+            stopBtn.addEventListener('click', function() {
+                var lastMsg = messages.lastElementChild;
+                if (lastMsg) lastMsg.remove();
+                setStreaming(false);
+            });
+
+            if (clearBtn) {
+                clearBtn.addEventListener('click', function() {
+                    input.value = '';
+                    input.focus();
+                    autoGrow();
+                    updateUI();
+                });
+            }
+
+            input.addEventListener('input', function() {
+                autoGrow();
+                updateUI();
+            });
+
+            input.addEventListener('keydown', function(e) {
+                if (e.key !== 'Enter') return;
+                if (e.shiftKey) return;
+                e.preventDefault();
+                if (!input.disabled && input.value.trim()) {
+                    form.requestSubmit();
+                }
+            });
+
+            input.addEventListener('paste', function() {
+                setTimeout(function() {
+                    autoGrow();
+                    updateUI();
+                }, 0);
+            });
+
+            autoGrow();
+            updateUI();
+        })();
+        </script>
+    </body>
+</html>
diff --git a/aisearch/src/web/templates/login.html b/aisearch/src/web/templates/login.html
new file mode 100644
index 0000000..1b87523
--- /dev/null
+++ b/aisearch/src/web/templates/login.html
@@ -0,0 +1,187 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>GeneNetwork AI Search – Sign In</title>
+    <script src="https://unpkg.com/htmx.org@2.0.8"></script>
+    <script src="https://unpkg.com/htmx-ext-sse@2.2.4/sse.js"></script>
+    <script src="https://unpkg.com/hyperscript.org@0.9.12"></script>
+    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
+    <style>
+        /* === Login Page Specific Styles === */
+        * {
+            margin: 0;
+            padding: 0;
+            box-sizing: border-box;
+        }
+
+        body {
+            font-family: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
+            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
+            min-height: 100vh;
+            display: flex;
+            align-items: center;
+            justify-content: center;
+            padding: 1.5rem;
+        }
+
+        .login-container {
+            width: 100%;
+            max-width: 440px;
+        }
+
+        .login-card {
+            background: rgba(255, 255, 255, 0.05);
+            backdrop-filter: blur(10px);
+            border-radius: 2rem;
+            padding: 2rem 1.8rem 2.2rem 1.8rem;
+            box-shadow: 0 25px 45px -12px rgba(0, 0, 0, 0.4), 0 0 0 1px rgba(255, 255, 255, 0.08);
+            transition: transform 0.2s ease;
+        }
+
+        .login-card:hover {
+            transform: translateY(-3px);
+        }
+
+        .brand {
+            text-align: center;
+            margin-bottom: 2rem;
+        }
+
+        .brand h1 {
+            font-size: 1.9rem;
+            font-weight: 600;
+            background: linear-gradient(120deg, #c084fc, #60a5fa);
+            background-clip: text;
+            -webkit-background-clip: text;
+            color: transparent;
+            letter-spacing: -0.3px;
+        }
+
+        .brand p {
+            color: #94a3b8;
+            font-size: 0.9rem;
+            margin-top: 0.5rem;
+        }
+
+        .input-group {
+            margin-bottom: 1.5rem;
+        }
+
+        .input-group label {
+            display: block;
+            color: #e2e8f0;
+            font-size: 0.85rem;
+            font-weight: 500;
+            margin-bottom: 0.4rem;
+            letter-spacing: 0.3px;
+        }
+
+        .input-group input {
+            width: 100%;
+            padding: 0.85rem 1rem;
+            background: rgba(15, 23, 42, 0.6);
+            border: 1px solid #334155;
+            border-radius: 1rem;
+            font-size: 1rem;
+            color: #f1f5f9;
+            transition: all 0.2s ease;
+            outline: none;
+        }
+
+        .input-group input:focus {
+            border-color: #818cf8;
+            box-shadow: 0 0 0 3px rgba(129, 140, 248, 0.3);
+            background: rgba(30, 41, 59, 0.8);
+        }
+
+        .input-group input::placeholder {
+            color: #64748b;
+            font-size: 0.9rem;
+        }
+
+        button {
+            width: 100%;
+            background: linear-gradient(95deg, #4f46e5, #7c3aed);
+            border: none;
+            padding: 0.85rem;
+            border-radius: 1.5rem;
+            font-weight: 600;
+            font-size: 1rem;
+            color: white;
+            cursor: pointer;
+            transition: all 0.2s ease;
+            margin-top: 0.5rem;
+            box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
+        }
+
+        button:hover {
+            background: linear-gradient(95deg, #6366f1, #8b5cf6);
+            transform: scale(0.98);
+            box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
+        }
+
+        .footer-note {
+            text-align: center;
+            margin-top: 1.8rem;
+            font-size: 0.75rem;
+            color: #64748b;
+        }
+
+        .footer-note a {
+            color: #a78bfa;
+            text-decoration: none;
+        }
+
+        .footer-note a:hover {
+            text-decoration: underline;
+        }
+
+        /* Simple error styling (if any flash messages appear) */
+        .error-message {
+            background: rgba(239, 68, 68, 0.15);
+            border-left: 4px solid #ef4444;
+            padding: 0.75rem;
+            border-radius: 0.75rem;
+            margin-bottom: 1.5rem;
+            color: #fecaca;
+            font-size: 0.85rem;
+        }
+    </style>
+</head>
+<body>
+    <div class="login-container">
+        <div class="login-card">
+            <div class="brand">
+                <h1> GeneNetwork</h1>
+                <p>AI-powered genomics search</p>
+            </div>
+
+            <!-- Show error if provided via query param or flash (optional) -->
+            {% with messages = get_flashed_messages(with_categories=true) %}
+                {% if messages %}
+                    {% for category, message in messages %}
+                        <div class="error-message">{{ message }}</div>
+                    {% endfor %}
+                {% endif %}
+            {% endwith %}
+
+            <form method="post" action="/login">
+                <div class="input-group">
+                    <label>đź“§ Email address</label>
+                    <input type="email" name="email" placeholder="you@example.org" required autofocus>
+                </div>
+                <div class="input-group">
+                    <label>đź”’ Password</label>
+                    <input type="password" name="password" placeholder="••••••••" required>
+                </div>
+                <button type="submit">Sign in →</button>
+            </form>
+            <div class="footer-note">
+                Secure access · <a href="#">Request access</a>
+            </div>
+        </div>
+    </div>
+</body>
+</html>
diff --git a/aisearch/src/web/templates/partials/response.html b/aisearch/src/web/templates/partials/response.html
new file mode 100644
index 0000000..cc8a0fd
--- /dev/null
+++ b/aisearch/src/web/templates/partials/response.html
@@ -0,0 +1,12 @@
+<div class="message message-ai">
+    <div class="avatar">AI</div>
+    <div class="message-content">
+        {% include "partials/response_body.html" %}
+    </div>
+    <button type="button" class="copy-btn"
+            _="on click
+                writeText(my previousElementSibling's innerText) on navigator.clipboard
+                put 'Copied!' into me
+                wait 1.5s
+                put 'Copy' into me">Copy</button>
+</div>
diff --git a/aisearch/src/web/templates/partials/response_body.html b/aisearch/src/web/templates/partials/response_body.html
new file mode 100644
index 0000000..4b305b5
--- /dev/null
+++ b/aisearch/src/web/templates/partials/response_body.html
@@ -0,0 +1,55 @@
+<div class="ai-response">
+    {% if data.error or data.status == 'error' %}
+        <div class="status-error">Search encountered an error</div>
+        <div class="error-display">{{ data.error or data.message or 'Unknown error' }}</div>
+        {% if data.raw_response %}
+            <div class="raw-response">
+                <strong>Raw Response:</strong><br>
+                {{ data.raw_response }}
+            </div>
+        {% endif %}
+    {% else %}
+        {% if data.status == 'success' %}
+            <div class="status-success">Search completed successfully</div>
+        {% elif data.status == 'partial_success' %}
+            <div class="status-partial">Partial success - some data sources unavailable</div>
+        {% endif %}
+
+        {% if data.summary %}
+            <div class="summary">{{ data.summary }}</div>
+        {% endif %}
+
+        {% if grouped and grouped|length > 0 %}
+            {% for type, items in grouped.items() %}
+                {% set display_type = type[0]|upper + type[1:] + 's' %}
+                <h3>{{ display_type }} ({{ items|length }})</h3>
+                <ul class="card-list">
+                    {% for item in items %}
+                        {% set url = item.url or item.link or '#' %}
+                        {% set name = item.name or item.symbol or item.trait_name or 'Unnamed' %}
+                        <li class="card-item">
+                            <div class="card-title">
+                                <a href="{{ url }}" target="_blank">{{ name }}</a>
+                            </div>
+                            {% if item.description %}
+                                <div class="card-description">{{ item.description }}</div>
+                            {% endif %}
+                            {% if item.extra %}
+                                <div class="card-meta">{{ item.extra }}</div>
+                            {% endif %}
+                        </li>
+                    {% endfor %}
+                </ul>
+            {% endfor %}
+        {% else %}
+            <div class="note-box">No specific results were found for this query.</div>
+        {% endif %}
+
+        {% if data.note %}
+            <div class="note-box">{{ data.note }}</div>
+        {% endif %}
+        {% if data.access_note %}
+            <div class="access-note">{{ data.access_note }}</div>
+        {% endif %}
+    {% endif %}
+</div>
diff --git a/aisearch/src/web/templates/partials/stream_shell.html b/aisearch/src/web/templates/partials/stream_shell.html
new file mode 100644
index 0000000..24d4ffe
--- /dev/null
+++ b/aisearch/src/web/templates/partials/stream_shell.html
@@ -0,0 +1,95 @@
+<div class="message message-user">
+    <div class="message-content">
+        {{ query }}
+    </div>
+</div>
+
+<div class="message message-ai message-ai-stream">
+    <div class="avatar">AI</div>
+    <div class="message-content stream-shell"
+         hx-ext="sse"
+         sse-connect="{{ url_for('search_stream') }}?q={{ query|urlencode }}"
+         sse-close="stream_end">
+        <div class="stream-shell-header">
+            <div>
+                <div class="stream-shell-kicker">Live Research Trace</div>
+                <h2>Cross-checking RAG, GraphRAG, and AgentSearch</h2>
+            </div>
+            <div class="stream-shell-state" sse-swap="search_state" hx-swap="innerHTML">
+                <span class="stream-stage-badge is-working">Starting</span>
+            </div>
+        </div>
+
+        <div class="stream-shell-intro">
+            Intermediate system output stays muted while the final answer is assembled.
+        </div>
+
+        <div class="stream-stage-grid">
+            <section class="stream-stage-card is-muted">
+                <div class="stream-stage-head">
+                    <span class="stream-stage-name">RAGSearch</span>
+                    <div class="stream-stage-meta">
+                        <span class="stream-stage-timing" sse-swap="rag_timing" hx-swap="innerHTML"></span>
+                        <span class="stream-stage-state" sse-swap="rag_done" hx-swap="innerHTML" hx-on:htmx:after-swap="this.closest('.stream-stage-card').querySelector('.stream-init-msg').style.display='none'">
+                            <span class="stream-stage-badge is-working">Running</span>
+                        </span>
+                    </div>
+                </div>
+                <div class="stream-stage-body-scroll" sse-swap="rag_final_html" hx-target="find .stream-stage-body" hx-swap="innerHTML" hx-on:htmx:after-swap="this.scrollTop = this.scrollHeight">
+                    <div class="stream-init-msg">Initializing search…</div>
+                    <div class="stream-stage-body" sse-swap="rag_chunk" hx-target="this" hx-swap="beforeend" hx-on:htmx:after-swap="this.parentElement.scrollTop = this.parentElement.scrollHeight"></div>
+                </div>
+            </section>
+
+            <section class="stream-stage-card is-muted">
+                <div class="stream-stage-head">
+                    <span class="stream-stage-name">GraphRAGSearch</span>
+                    <div class="stream-stage-meta">
+                        <span class="stream-stage-timing" sse-swap="grag_timing" hx-swap="innerHTML"></span>
+                        <span class="stream-stage-state" sse-swap="grag_done" hx-swap="innerHTML" hx-on:htmx:after-swap="this.closest('.stream-stage-card').querySelector('.stream-init-msg').style.display='none'">
+                            <span class="stream-stage-badge is-working">Running</span>
+                        </span>
+                    </div>
+                </div>
+                <div class="stream-stage-body-scroll" sse-swap="grag_final_html" hx-target="find .stream-stage-body" hx-swap="innerHTML" hx-on:htmx:after-swap="this.scrollTop = this.scrollHeight">
+                    <div class="stream-init-msg">Initializing search…</div>
+                    <div class="stream-stage-body" sse-swap="grag_chunk" hx-target="this" hx-swap="beforeend" hx-on:htmx:after-swap="this.parentElement.scrollTop = this.parentElement.scrollHeight"></div>
+                </div>
+            </section>
+
+            <section class="stream-stage-card is-muted">
+                <div class="stream-stage-head">
+                    <span class="stream-stage-name">AgentSearch</span>
+                    <div class="stream-stage-meta">
+                        <span class="stream-stage-timing" sse-swap="agent_timing" hx-swap="innerHTML"></span>
+                        <span class="stream-stage-state" sse-swap="agent_done" hx-swap="innerHTML" hx-on:htmx:after-swap="this.closest('.stream-stage-card').querySelector('.stream-init-msg').style.display='none'">
+                            <span class="stream-stage-badge is-working">Running</span>
+                        </span>
+                    </div>
+                </div>
+                <div class="stream-stage-body-scroll" sse-swap="agent_final_html" hx-target="find .stream-stage-body" hx-swap="innerHTML" hx-on:htmx:after-swap="this.scrollTop = this.scrollHeight">
+                    <div class="stream-init-msg">Initializing search…</div>
+                    <div class="stream-stage-body" sse-swap="agent_chunk" hx-target="this" hx-swap="beforeend" hx-on:htmx:after-swap="this.parentElement.scrollTop = this.parentElement.scrollHeight"></div>
+                </div>
+            </section>
+        </div>
+
+        <section class="stream-final-card">
+            <div class="stream-final-head">
+                <span class="stream-final-kicker">Final Answer</span>
+                <div class="stream-final-meta">
+                    <span class="stream-final-timing" sse-swap="total_timing" hx-swap="innerHTML"></span>
+                    <span class="stream-final-note">Rendered after the three systems complete</span>
+                </div>
+            </div>
+            <div class="stream-final-body" sse-swap="final_html" hx-swap="innerHTML">
+                <div class="stream-final-status is-waiting">
+                    <div class="stream-final-status-icon">🔍</div>
+                    <div class="stream-final-status-text">Waiting for searches to complete…</div>
+                </div>
+            </div>
+        </section>
+
+        <div hidden sse-swap="stream_end" hx-on:htmx:after-swap="window.onStreamEnd()"></div>
+    </div>
+</div>