Files
ai-agent/backend/main.py
gabrielvidalandClaude Opus 5.5 af80c5bf27 feat(i18n): French leaves the core — a translation kind of plugin
The core speaks English only; every other language is a kind: "translation" plugin
(translation-<lang>; the French one is translation-fr in ai-agent-plugins, seeded once at start).

- plugins: kind translation (typed_manifest.parse_translation: lang, name, englishName, flag,
  locale, promptLine, ui/backend JSON dictionaries — strict, operator-only, in the fingerprint);
  a top-level "languages" field on any plugin (default ["en"]) shown on its page; seeding takes
  translation-*; plugins/translations.py reads the enabled ones (first by id wins a code).
- core/i18n: tr / langs / localized / clean_pref / effective_lang read the installed
  translations; a pick whose translation is gone reads English and is kept; browserLang records
  any base code. core/i18n_fr.py and FRENCH_LINE are gone (language_line = the plugin's promptLine).
- The owner picks a language too (users.json ownerLang, PUT /api/me {lang}; English by default).
- Public GET /api/i18n/languages and /api/i18n/{lang} (ETag/304), guest host and sign-in included.
- Coverage: backend/core/i18n_keys/{ui,backend}.json (kept by the two i18n tests,
  UPDATE_I18N_KEYS=1); a translation's page shows translated / missing / stale / placeholder
  mismatches.
- Frontend: frontend/src/i18n/fr removed; the dictionary comes from the hub, cached in
  localStorage and revalidated in the background (first boot in a language waits <= 4 s, any
  failure is English); Lang is a string; number/currency style from the translation's locale;
  LanguageSelect lists English + installed translations (hidden when none); Settings → Plugins
  has a Translations kind (tab, catalog filter, group) and a Translation section with the
  missing-strings count; mock is English only.
- Tests: test_i18n.py rewritten on a made-up translation; i18n_testkit.speaking() for the
  tests that need a second language. authz golden, openapi.json + src/generated regenerated;
  docs/plugins.md (Translations), CLAUDE.md, i18n README, docs/settings.md.

Changelog
- Added: languages are plugins — Settings → Plugins → Translations; the owner can pick a language.
- Changed: French moved to the translation-fr plugin (seeded at start: nothing changes for guests).
- Removed: the core's built-in French dictionaries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:07:22 +01:00

375 lines
15 KiB
Python

"""
ai-agent backend — a viewer/editor + analytics dashboard for the homelab's
Claude context.
Exposes the repo's CLAUDE.md files and the `.claude/` tree (skills, hooks,
settings) as a flat list of files with **real** Claude token counts and dollar
costs, lets them be edited, and surfaces skill-usage analytics mined from the
Claude Code transcripts.
Token counts and skill stats are maintained in a small SQLite store by a
background indexer (see indexer.py): token counts come from the count_tokens
endpoint and are only refreshed for files whose content changed, after a debounce.
The built React PWA is served from STATIC_DIR at the web root.
This module is the assembly only: the routes live in one package per domain
(``conversations/``, ``runs/``, ``notifications/``, …), each exposing an
``APIRouter``; the shared stores are built once by ``core.state.build_state``
and attached to ``app.state.ai``, which every route reads through the
``State`` dependency. See ``CLAUDE.md`` → "Backend modules".
"""
import contextlib
import pathlib
import threading
from urllib.parse import urlencode
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, Response
import accounts.guest
import claudeproxy.routes
import toolproxy.routes
import plugins.routes
import plugins.translation_routes
import plugins.proxyroutes
import plugins.hubruns
import plugins.hubcomplete
import plugins.hubbridge
import plugins.hubmachines
import plugins.hubwake
import plugins.hubperf
import plugins.hubconvdata
import plugins.hubchecks
import plugins.hubtasks
import plugins.hubdiff
import plugins.hubfiles
import plugins.hubreports
import plugins.hubcatalog
import plugins.hubcontextcost
import plugins.relay
import plugins.sockets
import accounts.routes
import agents.routes
import askform.routes
import authz.api
import conversations.routes
import core.auth
from core import csp
import core.routes
import tags.routes
import dashboards.routes
import diff.routes
import drafts.routes
import files.assets
import files.browse
import models.routes
import notifications.routes
import perf.routes
import perf.storage_routes
import profiles.routes
import projects.routes
import runs.routes
import runs.guestjob_routes
import security.routes
import remoteaccess.routes
import settings.routes
import usage.routes
import usage.service
import users.computers
import users.oidc
import users.routes
from users import branding
from users.caller import on_guest_surface, request_lang
import telemetry.middleware
import telemetry.routes
import mcpserver.routes
import workers.link
import workers.routes
import workers.tools
from core.config import STATIC_DIR
from core.state import AppState, build_state
from runs.sidecar_client import _watch_sidecar_runs
# Declaration order matters only for the SPA fallback (last) — every API path
# is distinct. Kept in the order the old monolith declared them.
ROUTERS = (
settings.routes.router,
dashboards.routes.router,
conversations.routes.router,
notifications.routes.router,
diff.routes.router,
accounts.routes.router,
accounts.guest.router,
workers.routes.router,
profiles.routes.router,
models.routes.router,
runs.routes.router,
# « Discuter » on a guest's scheduled-job run (the jobs: the cron-jobs plugin)
runs.guestjob_routes.router,
agents.routes.router,
askform.routes.router,
projects.routes.router,
files.assets.router,
files.browse.router,
usage.routes.router,
users.routes.router,
authz.api.router,
users.oidc.router,
users.computers.router,
security.routes.router,
remoteaccess.routes.router,
perf.routes.router,
perf.storage_routes.router,
telemetry.routes.router,
claudeproxy.routes.router,
toolproxy.routes.router,
plugins.routes.router,
plugins.translation_routes.router,
plugins.proxyroutes.router,
plugins.hubruns.router,
plugins.hubcomplete.router,
plugins.hubbridge.router,
plugins.hubmachines.router,
plugins.hubwake.router,
plugins.hubperf.router,
plugins.hubconvdata.router,
plugins.hubchecks.router,
plugins.hubtasks.router,
# diff.read and conversations.reports (+ POST /api/plugin-reports, a lab
# run's path-shim reports) — the diff-viewer and commits plugins
plugins.hubdiff.router,
plugins.hubfiles.router,
plugins.hubreports.router,
plugins.hubcatalog.router,
# contextcost.read — the context-skills plugin's Context & skills dashboard
plugins.hubcontextcost.router,
plugins.relay.router,
# websockets plugin frames open through the host (the lab-chrome plugin's VNC)
plugins.sockets.router,
mcpserver.routes.router,
workers.link.router,
workers.tools.router,
tags.routes.router,
drafts.routes.router,
core.routes.router,
)
def create_app() -> FastAPI:
# No served schema: /openapi.json sat outside the gate, the whole API's
# shape for anyone on the public host. `app.openapi()` still builds it for
# the orval dump (CLAUDE.md → "API types are generated").
# `strict_content_type=False`: host callers (hooks, scripts, Home
# Assistant) that post JSON without a Content-Type keep working as they
# did on FastAPI 0.115; a *browser's* body without one is refused by the
# gate (core/auth.py), which is where that matters.
app = FastAPI(title="ai-agent", docs_url=None, redoc_url=None, openapi_url=None,
lifespan=_lifespan, strict_content_type=False)
core.auth.install(app)
# Outermost: it times the gate too, and reads the caller it leaves.
telemetry.middleware.install(app)
app.state.ai = build_state()
for r in ROUTERS:
app.include_router(r)
_mount_static(app)
return app
@contextlib.asynccontextmanager
async def _lifespan(app: FastAPI):
"""The server's start (Starlette 1.x has no startup event any more). A
TestClient used without `with` never enters it — no threads in tests."""
_startup(app.state.ai)
# Event-loop lag needs the server's own loop (telemetry/loop.py).
from telemetry import loop as tl
lag = tl.start(app.state.ai.hub)
yield
lag.cancel()
def _startup(deps: AppState) -> None:
# seed file metadata so the first request has data, then index in background
try:
deps.indexer.scan_files()
except Exception:
pass
deps.indexer.start()
deps.watcher.start()
# Run-exit detection: flip "running" conversations to "finished" the
# moment their sidecar-launched process dies (see _watch_sidecar_runs).
threading.Thread(target=_watch_sidecar_runs, args=(deps,),
daemon=True).start()
# Remote workers: health poller + the transcript mirror (workers.py,
# remotefeed.py). Both idle when nothing is paired.
deps.worker_monitor.start()
deps.outbox_mirror.start()
deps.askform_mirror.start()
# Asks past their expiry: flipped and taken off the phone / devices.
from notifications.service import start_ask_sweeper
start_ask_sweeper(deps)
# Worker projects' cards — description, stack, site, README — read off
# their transcripts (projects/worker_meta.py).
from projects import worker_meta
worker_meta.ScanThread(deps).start()
# Successful cron runs and finished test runs fold into the archive
# (conversations/autoarchive.py).
from conversations import autoarchive
autoarchive.start(deps)
if deps.feed_mirror:
deps.feed_mirror.start()
# A guest job's result goes out (push, mail) once its run ends — the
# jobs and their schedules are the cron-jobs plugin's (runs/guestjob.py).
from runs import guestjob
guestjob.start(deps)
# Live plugins: a replaced core feature's data, carried over once
# (plugins/carryover.py), then their scheduled non-LLM jobs.
from plugins import carryover
carryover.run_all(
getattr(deps, "plugin_store", None),
getattr(deps, "notify_store", None),
getattr(deps, "ui_state", None),
getattr(deps, "users", None),
getattr(deps, "worker_store", None),
getattr(deps, "meta_store", None),
)
# The default providers & harnesses (provider-*, harness-*) and the app
# plugins that ask for it ("seed": true — prompt-shortcuts), installed
# once from PLUGINS_SEED_DIR — never again once the owner uninstalls one.
try:
carryover.seed_typed_plugins(getattr(deps, "plugin_store", None))
except Exception: # noqa: BLE001 — a failed seed must not stop the boot
import logging
logging.getLogger(__name__).exception("typed plugin seeding failed")
deps.plugin_scheduler.start()
# Performance dashboard: poll every runner's /procs, roll up, auto-kill
# leftovers past their hours (perf/).
deps.perf_poller.start()
# Telemetry: the minute's request rollup + loop lag → telemetry.db.
from telemetry.store import Flusher
Flusher(deps.telemetry).start()
# Plan usage: record the official /usage % and recalibrate daily (usage/).
usage.service.start(deps)
# Login health: the signed-out call-out, locked composers and the push
# when an account's OAuth session dies (accounts/health.py).
deps.account_health.start()
# Provider discovery (the OpenRouter catalogue from APPE, Anthropic's
# models): pulled off the request path so the first model-browser open and
# the first priced transcript already have it (plugins/providers.py).
from plugins import providers as _providers
_providers.warm_discovery(_providers.registry(deps))
# ── static PWA + SPA fallback (declared last so /api/* wins) ─────────────────
# Everything under /assets/ carries a content hash in its name, so it can never
# go stale and is cached forever. The rest of the shell — index.html, the
# service worker, the manifest — keeps its name across deploys, so it must be
# revalidated on every request or a client can pin itself to an old bundle.
_IMMUTABLE = "public, max-age=31536000, immutable"
_REVALIDATE = "no-cache"
def _static_response(path: pathlib.Path, v: str | None = None) -> FileResponse:
hashed = path.parent.name == "assets" and path.parent.parent == STATIC_DIR
cache = _IMMUTABLE if hashed else _REVALIDATE
headers = {"Cache-Control": cache}
# Two documents carry a Content-Security-Policy (core/csp.py): the app
# shell, and the page a form's scripted HTML is written into — an opaque
# origin whoever opens it.
if path == STATIC_DIR / "index.html":
headers["Content-Security-Policy"] = csp.shell_csp(path)
elif path == STATIC_DIR / csp.SANDBOX_FRAME:
headers["Content-Security-Policy"] = csp.SANDBOX_FRAME_CSP
# ``?v=<its content hash>`` names this exact file: cached for good
# (the app asks for it that way; a bare request still revalidates).
if v and v == csp.sandbox_frame_hash(path):
headers["Cache-Control"] = _IMMUTABLE
return FileResponse(path, headers=headers)
# What a share-sheet text may carry into a `?q=` URL — well under what Traefik
# and uvicorn take in a request line.
_SHARE_TEXT_MAX = 4000
# …and the whole POST the fallback will parse (text fields + small files).
_SHARE_BODY_MAX = 1024 * 1024
def _share_text(title: str, text: str, url: str) -> str:
"""The composer text for a share: each field once, in reading order, a
title or link the text already carries left out — ``shareText()`` in
``frontend/src/business/composer/useShareTarget.ts``."""
title, text, url = title.strip(), text.strip(), url.strip()
parts = []
if title and title != url and title not in text:
parts.append(title)
if text:
parts.append(text)
if url and url not in text:
parts.append(url)
return "\n".join(parts)[:_SHARE_TEXT_MAX]
def _mount_static(app: FastAPI) -> None:
# The installed PWA's share target (the manifest's `share_target`). The
# service worker answers this POST itself (frontend/public/share-sw.js), so
# one that gets here came from a client with no worker yet. Rather than a
# 405, keep what fits in a URL: the text, as a `?q=` deep link into the
# composer. The files have nowhere to wait and are dropped.
@app.post("/share")
async def share(request: Request):
# Outside the gate and unauthenticated: only a declared, small body is
# parsed — a share's text. (It used to spool up to 20 files of any
# size to disk before dropping them.)
try:
size = int(request.headers.get("content-length") or "")
except ValueError:
size = -1
if not 0 <= size <= _SHARE_BODY_MAX:
return RedirectResponse("/", status_code=303)
try:
form = await request.form(max_files=20)
except Exception:
return RedirectResponse("/", status_code=303)
try:
field = lambda k: v if isinstance(v := form.get(k), str) else "" # noqa: E731
text = _share_text(field("title"), field("text"), field("url"))
finally:
await form.close()
return RedirectResponse(f"/?{urlencode({'q': text})}" if text else "/", status_code=303)
# Serve built assets when they exist, otherwise hand back index.html so the
# client-side router can resolve deep links like /_/.claude/skills/...
@app.get("/{full_path:path}")
def spa(full_path: str, request: Request):
index = STATIC_DIR / "index.html"
if not index.is_file():
return JSONResponse({"detail": "frontend not built"}, status_code=200)
guest = on_guest_surface(request)
if guest and full_path == "manifest.webmanifest":
path = STATIC_DIR / full_path
if path.is_file():
return Response(branding.guest_manifest(path.read_text(), request_lang(request)),
media_type="application/manifest+json",
headers={"Cache-Control": _REVALIDATE, "Vary": "Accept-Language"})
if full_path:
candidate = (STATIC_DIR / full_path).resolve()
try:
candidate.relative_to(STATIC_DIR)
except ValueError:
candidate = index # path traversal attempt → fall back
if candidate.is_dir() and (candidate / "index.html").is_file():
# Static sub-sites shipped in public/ (a dir with its own index.html)
# get their own index instead of the SPA shell.
candidate = candidate / "index.html"
if candidate.is_file() and candidate != index:
return _static_response(candidate, request.query_params.get("v"))
if guest:
return Response(branding.guest_index(index.read_text(), request_lang(request)),
media_type="text/html",
headers={"Cache-Control": _REVALIDATE, "Vary": "Accept-Language",
"Content-Security-Policy": csp.shell_csp(index)})
return _static_response(index)
app = create_app()