Files
gabrielvidalandClaude Opus 5.5 6e85fcece0 refactor(projects): the .env editor moves to the project-env plugin
The project page's .env editor is now the owner-only `project-env` live
plugin (ai-agent-plugins, `project.detail` slot, `projects.env` capability).
Removed from the core: `projects/envfile.py`, `GET|PUT /api/project-env`
(+ `EnvSetItem` / `EnvSaveBody`, the `ProjectEnvVar` / `ProjectEnvResponse`
schemas and their authz matrix rows), `EnvEditor.tsx`, `fetchProjectEnv` /
`saveProjectEnv` / `useProjectEnv`. `<PluginSlots where="project.detail">`
stays. test_guests' default-deny check now probes `/api/project-merges`.
openapi.json / generated client are left for the post-Batch-1 dump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:44:34 +01:00

217 lines
9.6 KiB
Python

"""Projects gallery routes, with per-project cost rollups."""
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import accounts as accounts_mod
import projects as projects_mod
import schemas
from conversations.cards import _summaries_with_account
from core.http import _json_in_worker, _r
from core.memo import _Memo
from core.state import AppState, State
from profiles import store as profiles_mod
from projects import costs as project_costs_mod
from projects import merges as merges_mod
from projects import worker_projects as worker_projects_mod
from users.caller import CallerDep, OwnerDep
router = APIRouter()
# ── projects gallery (the repo's projects/ dir) ──────────────────────────────
# Cost rollups walk every summary once (single-flight memoized on store versions).
# A project's $ may lag a transcript write by up to this much: the rollup is
# ~10 s of GIL on the live box and ``summaries_version`` moves every couple of
# seconds while anything runs, so keying on it rebuilt it on nearly every
# request (151 builds in 40 min on prod).
COSTS_MAX_STALE_S = 60.0
def _build_project_costs(deps: AppState, account: str | None) -> dict:
rows = _summaries_with_account(deps)
merges = merges_mod.load()
lab_slugs = worker_projects_mod._lab_slugs()
reg = worker_projects_mod.registry(deps)
list_fn = getattr(deps.worker_store, "list", None)
workers_by_id = {w["id"]: w for w in list_fn()} if list_fn is not None else None
sel = deps.profile_store.selector(account)
by_profile = bool(getattr(sel, "by_profile", False))
acct_ids = set(accounts_mod.ids())
per_acct_buckets: dict[str, dict[str, list[dict]]] = {a: {} for a in acct_ids}
view_buckets: dict[str, list[dict]] = {}
prof_cache: dict[tuple, str] = {}
for _p, s, a in rows:
if not s.get("messages"):
continue
sid = s.get("sessionId") or ""
m = deps.meta_store.peek(sid)
owner_g = profiles_mod.guest_owner(m, a)
pkey = (m.get("worker") or m.get("workerSource"), a, m.get("profile"), owner_g)
prof = prof_cache.get(pkey)
if prof is None:
prof = prof_cache[pkey] = deps.profile_store.of_meta(m, a)
slugs = worker_projects_mod.conversation_projects(
deps, s, m, prof, merges=merges, lab_slugs=lab_slugs,
reg=reg, workers_by_id=workers_by_id)
if a in acct_ids:
ab = per_acct_buckets[a]
for slug in slugs:
ab.setdefault(slug, []).append(s)
in_view = sel(a, prof, owner_g) if by_profile else sel(a)
if in_view:
for slug in slugs:
view_buckets.setdefault(slug, []).append(s)
per_acct = {
a: {slug: project_costs_mod._aggregate(convs) for slug, convs in buckets.items()}
for a, buckets in per_acct_buckets.items()
}
view = {slug: project_costs_mod._aggregate(convs) for slug, convs in view_buckets.items()}
default_view = (account or "").strip().lower() in ("", "totals")
costs: dict[str, dict] = {}
for slug in set(view) | {sl for c in per_acct.values() for sl in c}:
owner = _account_of_project(deps, slug)
excluded = not accounts_mod.counts_in_totals(owner)
agg = (per_acct.get(owner, {}).get(slug) if excluded and default_view
else view.get(slug))
costs[slug] = {
**(agg or project_costs_mod._aggregate([])),
"account": owner,
"excludeFromTotals": excluded,
"byAccount": {a: {"cost": (c.get(slug) or {}).get("cost", 0.0),
"tokens": (c.get(slug) or {}).get("tokens", 0),
"conversations":
(c.get(slug) or {}).get("conversations", 0)}
for a, c in per_acct.items()},
}
return costs
# Stale-while-revalidate on the summaries (soft); a few slots so the
# composer's totals and the gallery's ?account= view don't evict each other.
_costs_memo = _Memo(_build_project_costs, max_stale=COSTS_MAX_STALE_S, slots=4)
def _project_costs(deps: AppState, account: str | None = None) -> dict:
"""``{slug: spend aggregate}`` for one ``?account=`` view, plus each
project's ``byAccount`` split and owning ``account``.
The default (totals) view drops the excluded accounts' conversations —
except on a project an excluded account *owns* (its profile lists it):
that card reports its own account's spend, flagged ``excludeFromTotals``,
so it neither reads $0 nor leaks into the gallery's totals.
Up to ``COSTS_MAX_STALE_S`` behind the transcripts (``summaries_version``
is the memo's soft key); a meta, profile, worker or merge change — who a
conversation belongs to — rebuilds at once."""
key = (id(deps.store), deps.meta_store.version,
deps.profile_store.version, getattr(deps.worker_store, "version", 0),
merges_mod.version(), account or "")
return _costs_memo.get(key, deps, account, soft=deps.store.summaries_version)
def _account_of_project(deps: AppState, slug: str) -> str:
"""Whose spend a project is (worker projects: their worker's ★ seat)."""
if worker_projects_mod.is_worker_slug(slug):
return worker_projects_mod.account_for(deps, slug)
return deps.profile_store.account_for_project(slug) or accounts_mod.DEFAULT
def _costs_card(agg: dict | None, owner: str) -> dict:
return {
"cost": agg["cost"] if agg else 0.0,
"tokens": agg["tokens"] if agg else 0,
"conversations": agg["conversations"] if agg else 0,
"account": owner,
"excludeFromTotals": not accounts_mod.counts_in_totals(owner),
"byAccount": agg["byAccount"] if agg else None,
}
@router.get("/api/projects", responses=_r(schemas.ProjectsResponse))
@_json_in_worker
def projects_list(deps: State, caller: CallerDep, account: str | None = None):
"""Card metadata for every directory under projects/ (newest commit first).
Each card carries a compact ``costs`` rollup (total $/tokens + conversation
count) aggregated from every conversation attributed to the project —
within the ``account`` view (unset = the totals; see ``_project_costs``)."""
costs = _project_costs(deps, account)
merged = merges_mod.load()
# A lab project folded into a worker project is that project now.
items = [it for it in projects_mod.list_projects() if it["dir"] not in merged]
if not caller.is_owner:
items = [it for it in items if caller.can(it["dir"], "view")]
# Projects deduced on the workers (projects/worker_projects.py) — a guest
# sees their own computers' ones.
items += worker_projects_mod.list_for(deps, caller)
for it in items:
owner = _account_of_project(deps, it["dir"])
it["account"] = owner
it["costs"] = _costs_card(costs.get(it["dir"]), owner)
return {"projects": items}
@router.get("/api/project", responses=_r(schemas.ProjectDetail))
def project_detail(deps: State, caller: CallerDep, slug: str,
account: str | None = None):
"""Full metadata + key-file contents (README/CLAUDE.md/index meta/og) for one project.
Also attaches a ``costs`` block: total/mean/median spend across the project's
conversations, a per-token-type breakdown, and mean cost per line of code."""
# A lab project folded into a worker project opens as that project.
slug = merges_mod.load().get(slug, slug)
if worker_projects_mod.is_worker_slug(slug):
detail = (worker_projects_mod.detail(deps, slug)
if worker_projects_mod.visible_to(deps, caller, slug) else None)
if detail is None:
raise HTTPException(404, "project not found")
agg = _project_costs(deps, account).get(slug) or project_costs_mod._aggregate([])
detail["account"] = _account_of_project(deps, slug)
detail["costs"] = {**agg, "loc": 0, "meanCostPerLoc": 0.0}
return detail
if not caller.can(slug, "view"):
raise HTTPException(404, "project not found")
detail = projects_mod.project_detail(slug)
if detail is None:
raise HTTPException(404, "project not found")
agg = _project_costs(deps, account).get(slug) or project_costs_mod._aggregate([])
detail["account"] = _account_of_project(deps, slug)
loc = projects_mod.count_loc(slug)
agg = {**agg, "loc": loc,
"meanCostPerLoc": (agg["cost"] / loc) if loc else 0.0}
detail["costs"] = agg
return detail
# ── lab projects folded into a worker project (projects/merges.py) ───────────
class MergeBody(BaseModel):
# The lab project (``~/projects/<slug>``) and the worker project it is
# folded into; ``into`` empty/None un-merges it.
slug: str
into: str | None = None
@router.get("/api/project-merges")
def project_merges(_: OwnerDep):
"""``{merges: {lab slug: worker project slug}}``."""
return {"merges": merges_mod.load()}
@router.put("/api/project-merges")
def project_merges_set(body: MergeBody, _: OwnerDep):
"""Fold a lab project into a worker project (or undo it with no ``into``)."""
slug = body.slug.strip()
into = (body.into or "").strip()
if not slug or worker_projects_mod.is_worker_slug(slug):
raise HTTPException(400, "slug must be a lab project")
if into and not worker_projects_mod.is_worker_slug(into):
raise HTTPException(400, "into must be a worker project (<name>@<worker id>)")
data = dict(merges_mod.load())
if into:
data[slug] = into
else:
data.pop(slug, None)
return {"merges": merges_mod.save(data)}