Files
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

449 lines
20 KiB
Python

"""The application state: every store, hub, watcher and mirror, built once
by :func:`build_state` and attached to ``app.state.ai``.
Routes take it as a FastAPI dependency (``deps: State``) and the helpers they
call take it explicitly (``deps: AppState``) — nothing reads a module-level
singleton, so a test can build a throwaway state and the import order of the
domain packages never matters. The domain functions this wiring needs
(creating a notification) are imported *inside*
``build_state`` on purpose: those modules import ``AppState`` from here.
"""
from __future__ import annotations
import dataclasses
import os
import pathlib
import threading
import typing
from fastapi import Depends, Request
from core.config import (
ASKFORM_PATH,
ACCOUNT_SOURCE_DIRS,
ARCHIVE_DIR,
FRESH_CONTEXT_PATH,
DB_PATH,
FORM_SECRETS_PATH, FORMS_PATH,
META_PATH,
NOTIFY_PATH,
PROFILES_PATH,
SOURCE_DIRS,
UI_STATE_PATH,
DRAFTS_PATH,
TAG_META_PATH,
WORKERS_PATH,
WORKERS_SOURCE_DIR,
WORKSPACE,
)
from db import Store
from events import Hub, Watcher
from indexer import Indexer
from meta import MetaStore
from notifications.read_ledger import NotifReadStore
from notifications.store import NotifyStore
from profiles.store import ProfileStore
from runs.fresh import FreshContextStore
from settings.ui_state import UiStateStore
from drafts.store import DraftStore
from tags.store import TagStore
from security.store import SecurityLog, SecurityState
from users.store import AuthStore, UsersStore
from remoteaccess.passkeys import PasskeyStore
from remoteaccess.sessions import OwnerSessions
from users.webpush import WEBPUSH_PATH, PushStore
from workers.outbox_mirror import OutboxMirror
from workers.remotefeed import FeedMirror
from workers.store import WorkerMonitor, WorkerStore
from mcpserver.store import McpStore
# Server-side "read" ledger for the notification feed — lets the phone fetch
# *unread* notifications (listening ≠ reading; only the UI marks them read).
NOTIF_READ_PATH = os.environ.get("NOTIF_READ_PATH", "/data/notif-read.json")
# Guests (users.json) and their login state (auth.json) — see users/store.py.
USERS_PATH = os.environ.get("USERS_PATH", "/data/users.json")
AUTH_PATH = os.environ.get("AUTH_PATH", "/data/auth.json")
# Beside auth.json unless set (a test's throwaway AUTH_PATH takes it along).
OWNER_SESSIONS_PATH = os.environ.get("OWNER_SESSIONS_PATH") or os.path.join(
os.path.dirname(AUTH_PATH) or ".", "owner-sessions.json")
OWNER_PASSKEYS_PATH = os.environ.get("OWNER_PASSKEYS_PATH") or os.path.join(
os.path.dirname(AUTH_PATH) or ".", "owner-passkeys.json")
# The security log and its switches — see security/.
SECURITY_LOG_PATH = os.environ.get("SECURITY_LOG_PATH", "/data/security-log.jsonl")
SECURITY_STATE_PATH = os.environ.get("SECURITY_STATE_PATH", "/data/security.json")
# The MCP server's apps, approvals, connections and tokens — see mcpserver/.
MCP_PATH = os.environ.get("MCP_PATH", "/data/mcp.json")
PERF_SETTINGS_PATH = os.environ.get("PERF_SETTINGS_PATH", "/data/perf-settings.json")
# The account picks of repo plugins (workers/repoplugins.py).
REPO_PLUGINS_PATH = os.environ.get("REPO_PLUGINS_PATH", "/data/repo-plugins.json")
from usage.poller import UsagePoller
from usage.plans import PlanTracker
from usage.store import UsageStore
from perf.poller import PerfPoller
from perf.settings import PerfSettings
from perf.store import PerfStore
from telemetry.store import TelemetryStore
from accounts.health import HealthMonitor
from askform.mirror import AskFormMirror
from askform.store import AskFormStore
from plugins.scheduler import PluginScheduler
from plugins.store import PluginStore
@dataclasses.dataclass
class AppState:
store: Store
meta_store: MetaStore
ui_state: UiStateStore
draft_store: DraftStore
tag_store: TagStore
notify_store: NotifyStore
askform_store: AskFormStore
askform_mirror: AskFormMirror
fresh_store: FreshContextStore
notif_read_store: NotifReadStore
hub: Hub
worker_store: WorkerStore
profile_store: ProfileStore
worker_monitor: WorkerMonitor
indexer: Indexer
watcher: Watcher
feed_mirror: FeedMirror | None
outbox_mirror: OutboxMirror
users: UsersStore
auth: AuthStore
# The owner's sessions on the internet address (remoteaccess/).
owner_sessions: OwnerSessions
owner_passkeys: PasskeyStore
# The guests' Web Push devices (users/webpush.py).
push: PushStore
security_log: SecurityLog
security_state: SecurityState
usage_store: "UsageStore"
usage_poller: "UsagePoller"
# Which plan (tier + limit windows) each account is on (usage/plans.py).
usage_plans: "PlanTracker"
account_health: "HealthMonitor"
# One card colour per hue + shade resource — an issue + its PRs
# (conversations/look.py).
look_colors: "LookColors" = None
# The Performance dashboard: CPU + memory of agent runs (perf/).
perf_store: "PerfStore" = None
perf_settings: "PerfSettings" = None
perf_poller: "PerfPoller" = None
# The hub's own latency history + feature usage (telemetry/).
telemetry: "TelemetryStore" = None
# Live user plugins (v1 + v2 + v3 — backend/plugins/).
plugin_store: "PluginStore" = None
plugin_scheduler: "PluginScheduler" = None
# The MCP server's OAuth state and connections (mcpserver/store.py).
mcp: "McpStore" = None
def _record_source_account(deps: "AppState", rel: str, account: str) -> None:
"""Stamp ``meta.accountSource`` on the session a transcript imported from
``account``'s source dir belongs to (``<proj>/<sid>.jsonl``, or a subagent
under ``<proj>/<sid>/subagents/``). Once per session: a no-op after."""
parts = pathlib.PurePosixPath(rel).parts
if len(parts) < 2:
return
sid = parts[1][:-6] if parts[1].endswith(".jsonl") else parts[1]
if deps.meta_store.peek(sid).get("accountSource") == account:
return
deps.meta_store.update(sid, {"accountSource": account})
def _closing_push(deps: "AppState", summary: dict, block: dict) -> None:
"""A run's final message ended on a ```notify block: push it, once
(notifications/closing.py)."""
from notifications import closing
closing.maybe_push(deps, summary, block)
def _record_worker_files(deps: "AppState", w: dict, rels: list[str]) -> None:
"""The mirror landed these transcripts from worker ``w``: stamp which
worker each session lives on (resume/fork/interrupt route on it) and the
worker's account (``accountSource`` — the import-source rule in
accounts.resolve). One meta save per pass, however many sessions."""
from accounts.profiles import guest_account
from claudeproxy import opencode as oc_proxy, service as proxy
from workers import guests
from workers.remotefeed import agy_account, local_rel, opencode_account
patches: dict[str, dict] = {}
extra = guests.stamp(w)
# A terminal session the guest synced off their own login keeps billing
# it (workers/terminal.py), not the computer's proxied account.
own = guest_account(guests.owner_of(w)) if guests.is_guest(w) else None
for rel in rels:
parts = local_rel(pathlib.PurePosixPath(rel)).parts
if len(parts) < 2:
continue
sid = parts[1][:-6] if parts[1].endswith(".jsonl") else parts[1]
# An opencode session bills the worker's opencode account, not its
# Claude login — one the worker declares, never any id it names.
oc = opencode_account(rel)
if oc and oc not in (w.get("opencodeAccounts") or []) \
and oc not in oc_proxy.proxied_accounts(w):
continue
# An agy session bills the worker's own Google login of that account.
ag = agy_account(rel)
if ag:
if ag not in (w.get("agyAccounts") or []) or guests.is_guest(w):
continue
oc = ag
local = own and deps.meta_store.peek(sid).get("terminal") == "local"
patches[sid] = {"workerSource": w["id"],
"accountSource": oc or (own if local else
proxy.terminal_account(deps.worker_store, w)),
**extra}
if patches and deps.meta_store.stamp_many(patches):
deps.hub.publish({"type": "meta"})
_reload_timer: list = [None]
_reload_lock = threading.Lock()
def _reload_harnesses_later(deps) -> None:
"""``POST /harnesses/reload`` on the host sidecar, off the request thread
and best effort: a sidecar that predates it (404) or is down keeps the
drivers it has; the next change asks again. Changes within 2 s (the
first boot's seeding installs nine plugins) make one call."""
def run() -> None:
try:
from runs.sidecar_client import _sidecar_call
_sidecar_call(deps, "/harnesses/reload", {}, timeout=30)
except Exception as e: # noqa: BLE001
import logging
logging.getLogger(__name__).info("harness reload not taken: %s", e)
with _reload_lock:
if _reload_timer[0] is not None:
_reload_timer[0].cancel()
t = threading.Timer(2.0, run)
t.daemon = True
t.name = "harnesses-reload"
_reload_timer[0] = t
t.start()
def build_state() -> AppState:
"""Construct every store and background worker (nothing is started here —
see ``main._startup``)."""
from files.discovery import WorkspaceWatch, _iter_files, _read_text
store = Store(DB_PATH)
# Public conversation ids (conversations/ids.py): load the registry, and
# — once — move every JSON store off the old path ids. Before any store
# below loads its file, so none keeps the old spelling in memory.
from conversations import id_migration, ids
ids.bind(store, ARCHIVE_DIR)
try:
id_migration.migrate(store, ARCHIVE_DIR, pathlib.Path(DB_PATH).parent)
except Exception: # never keep the hub from starting
import logging
logging.getLogger(__name__).exception("conv-uids migration failed")
usage_store = UsageStore(DB_PATH)
meta_store = MetaStore(META_PATH)
hub = Hub()
worker_store = WorkerStore(WORKERS_PATH)
from workers.repoplugins import RepoPluginSettings
worker_store.repo_plugins = RepoPluginSettings(REPO_PLUGINS_PATH)
notify_store = NotifyStore(NOTIFY_PATH)
ui_state = UiStateStore(UI_STATE_PATH)
deps = AppState(
store=store,
meta_store=meta_store,
ui_state=ui_state,
draft_store=DraftStore(DRAFTS_PATH),
# Seeded once from the settings blob, where these used to live.
tag_store=TagStore(TAG_META_PATH, seed=lambda: ui_state.get("ai-agent-settings")),
notify_store=notify_store,
askform_store=AskFormStore(ASKFORM_PATH),
askform_mirror=typing.cast(AskFormMirror, None),
fresh_store=FreshContextStore(FRESH_CONTEXT_PATH),
notif_read_store=NotifReadStore(NOTIF_READ_PATH),
hub=hub,
worker_store=worker_store,
# A guest's own computer is in no profile (workers/guests.py).
profile_store=ProfileStore(PROFILES_PATH, workers_fn=lambda: [
w for w in worker_store.list() if not w.get("owner")]),
worker_monitor=WorkerMonitor(worker_store, hub.publish),
indexer=typing.cast(Indexer, None),
watcher=typing.cast(Watcher, None),
feed_mirror=None,
outbox_mirror=typing.cast(OutboxMirror, None),
users=UsersStore(USERS_PATH),
auth=AuthStore(AUTH_PATH),
owner_sessions=OwnerSessions(OWNER_SESSIONS_PATH),
owner_passkeys=PasskeyStore(OWNER_PASSKEYS_PATH),
push=PushStore(WEBPUSH_PATH),
security_log=SecurityLog(SECURITY_LOG_PATH),
security_state=SecurityState(SECURITY_STATE_PATH),
mcp=McpStore(MCP_PATH),
usage_store=usage_store,
usage_poller=UsagePoller(usage_store, hub.publish),
usage_plans=PlanTracker(usage_store),
account_health=typing.cast(HealthMonitor, None),
perf_store=PerfStore.beside(DB_PATH),
perf_settings=PerfSettings(PERF_SETTINGS_PATH),
telemetry=TelemetryStore.beside(DB_PATH),
plugin_store=PluginStore(),
)
deps.plugin_scheduler = PluginScheduler(deps, deps.plugin_store)
# The active plugins' conversation resource kinds, for the transcript
# miner (it has no deps of its own — plugins/resources.py).
from plugins import resources as plugin_resources
plugin_resources.bind(deps)
# The providers & harnesses registry (pricing, catalogue, accounts) — read
# by helpers that have no deps (plugins/providers.py); a change to the live
# bundles asks the host sidecar to reload its drivers.
from plugins import providers as plugin_providers
plugin_providers.bind(deps)
# The installed translations (translation-<lang>): core/i18n.tr, the
# language prefs and /api/i18n read them (plugins/translations.py).
from plugins import translations as plugin_translations
plugin_translations.bind(deps.plugin_store)
deps.plugin_store.on_typed_change = lambda: _reload_harnesses_later(deps)
# harnessHooks: a runner's profile places them (plugins/harness_hooks.py);
# the lab's copy is rewritten at each start (a profile may have moved).
from plugins import harness_hooks
harness_hooks.profile_of = lambda rid: (deps.profile_store._runner_ref(rid) or {}).get("id")
deps.plugin_store.sync_hooks()
from plugins.scheduler import dispatch_event as _plugin_dispatch
def _on_hub_event(ev: dict) -> None:
kind = ev.get("type")
if kind == "notification":
_plugin_dispatch(deps, "notify", ev)
elif kind == "deploy":
_plugin_dispatch(deps, "deploy", ev)
hub.listeners.append(_on_hub_event)
deps.perf_poller = PerfPoller(deps)
deps.account_health = HealthMonitor(deps)
# The opencode seats' usage: from the worker hosting the account when it
# isn't mounted here, the push past an account's `limitAlerts` and the
# one when its week falls behind its `weekTarget`.
from usage.service import (behind_alert, limit_alert, plan_changed, remote_snapshots,
track_plans)
deps.usage_poller.remote = lambda: remote_snapshots(deps)
deps.usage_poller.alert = lambda *a: limit_alert(deps, *a)
deps.usage_poller.behind = lambda *a: behind_alert(deps, *a)
deps.usage_poller.after_poll = lambda: track_plans(deps)
deps.usage_plans.notify = lambda *a: plan_changed(deps, *a)
deps.indexer = Indexer(store, WORKSPACE, SOURCE_DIRS, ARCHIVE_DIR,
_iter_files, _read_text,
source_accounts={d: a for a, d in ACCOUNT_SOURCE_DIRS.items()},
on_account=lambda rel, a: _record_source_account(deps, rel, a),
files_watch=WorkspaceWatch(),
on_closing_notify=lambda s, b: _closing_push(deps, s, b))
# A guest's computer gets the guests' shared lab skills, nothing else.
from workers import labsync
labsync.guest_skills = lambda: [r for r in deps.users.defaults()["sharedSkills"]
if "/" not in r]
# …plus their live plugins' skills, and every worker's ``hub.json``
# (toolproxy/): its own proxy token, for the plugin skills with a proxy.
labsync.user_plugins = lambda uid: deps.plugin_store.live_skill_dirs(uid)
labsync.plugin_store = lambda: getattr(deps, "plugin_store", None)
labsync.tool_hub = lambda w: _tool_hub(worker_store, w)
# How often a guest computer's tokens rotate (workers/guests.maybe_rotate).
worker_store.rotate_days = lambda: deps.users.defaults()["computerLimits"]["rotateDays"]
# The Claude proxy's machine default for a worker: its ★ Claude login.
worker_store.star_of = lambda wid, held: deps.profile_store.default_login(wid, "claude", held)
# A guest computer's terminal: the figures its picker and mod show.
from workers import terminal as worker_terminal
worker_store.terminal_push = lambda w, held: worker_terminal.maybe_push_status(deps, w, held)
from conversations.card import cards_for # noqa: E402 — late: it imports the catalog
deps.watcher = Watcher(SOURCE_DIRS, meta_store, deps.indexer, hub,
cards_for=lambda ids: cards_for(deps, ids), deps=deps)
if WORKERS_SOURCE_DIR:
from workers import guests, terminal
deps.feed_mirror = FeedMirror(
worker_store, WORKERS_SOURCE_DIR,
on_files=lambda w, rels: _record_worker_files(deps, w, rels),
allow=lambda w, rel: guests.may_mirror(deps, w, rel) and guests.mirror_ok(deps, w),
on_bytes=lambda w, n: guests.MIRROR.add(w["id"], n) if guests.is_guest(w) else None,
on_synced=lambda w, sids: terminal.claim_synced(deps, w, sids))
# The two workers below call back into domain code with the finished state.
from notifications.service import _create_ask, _create_notify
from conversations.resource_view import apply_recorded
from askform import links as askform_links
from askform import service as askform_service
from conversations import past
from workers import guests
# Workers' outboxes: the notifications / asks a session on a remote
# worker queued in *its* sidecar (it never calls the hub). Pulled here, created
# through the same functions the routes use, answers pushed back.
deps.outbox_mirror = OutboxMirror(
worker_store,
create={"notify": lambda d: _create_notify(deps, d),
"ask": lambda d: _create_ask(deps, d),
"meta": lambda d: apply_recorded(deps, d),
# A worker's `ask-form serve` event (its sidecar's webhook).
"askform": lambda d: askform_service.ingest_outbox(deps, d),
# A worker's `ai-agent past`: answered in the ack.
"lookup": lambda d: past.outbox_lookup(deps, d),
# A plugin path shim's report (plugins/hubreports.py).
"report": lambda d: _report_ingest(deps, d)},
status={"ntf": lambda i: notify_store.get(i),
"ask": lambda i: notify_store.ask_status(i)},
cancel={},
publish=hub.publish,
allow=lambda w, kind, payload: guests.outbox_allowed(deps, w, kind, payload))
# The standalone ask-form tool's forms on every machine, mirrored for the
# thread cards, the push and Waiting for feedback (askform/mirror.py).
deps.askform_mirror = AskFormMirror(
deps.askform_store, machines=lambda: askform_service.machines(deps),
on_new=lambda rec: askform_service.on_mirror_new(deps, rec),
on_closed=lambda rec: askform_service.on_mirror_closed(deps, rec),
publish=hub.publish,
recover=lambda: askform_links.recover(deps),
origins=askform_service.hub_origins)
from conversations.look import LookColors
deps.look_colors = LookColors()
return deps
def _report_ingest(deps, d: dict) -> dict:
from plugins import hubreports
return hubreports.outbox_ingest(deps, d)
def get_state(request: Request) -> AppState:
return request.app.state.ai
# The dependency every route declares: ``def route(deps: State, ...)``.
State = typing.Annotated[AppState, Depends(get_state)]
def tool_hub_url(w: dict) -> str:
"""The ``AIA_TOOLS_URL`` a worker's runs get ("" when there is none): a
guest's computer the public guest host, an owner's worker the hub over
the tailnet."""
from claudeproxy import service as proxy
from users.deliver import GUEST_PUBLIC_URL
if w.get("owner"):
return f"{GUEST_PUBLIC_URL}/proxy/tools" if GUEST_PUBLIC_URL else ""
base = proxy.PROXY_URL
return base[: -len("/proxy/claude")] + "/proxy/tools" if base.endswith("/proxy/claude") \
else ""
def _tool_hub(store, w: dict) -> dict | None:
"""Where a worker's plugin skills call the tool proxy
(:func:`tool_hub_url`) — with the worker's proxy token (minted on first
need)."""
from claudeproxy import service as proxy
url = tool_hub_url(w)
if not url:
return None
w = proxy.ensure_token(store, w)
return {"url": url, "token": w.get("proxyToken") or ""} if w.get("proxyToken") else None