mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 18:42:34 +01:00
* chore(coherence): adopt Coherence with specs, invariants and a PR report Install @posthog/coherence as a frontend dev dependency and wire its Claude Code hooks into the committed .claude/settings.json, so every agent session in the repo gets the vocabulary, specs, journal and checks. The hooks call the binary under frontend/ through $CLAUDE_PROJECT_DIR. Declare 23 components and the entrances that carry outside trust, and six invariants, each refuted with a deliberate break before it counted: - every /api route requires auth and its scopes, except a named public list (new route sweep in tests/endpoints/test_route_guards.py) - a hidden rom, platform or firmware answers every id route exactly as a missing id would (new sweep over every method of every id route) - the unscoped save, state and screenshot fetches by id are reached only from their own routers (chokepoints) - validate_path never resolves outside its base folder The PR workflow runs in comment mode: one report comment, failing only when Coherence itself breaks. Trunk skips Prettier and markdownlint on *.spec.md and *.practice.md, since Prettier escapes their globs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(routes): satisfy mypy in the route guard sweep Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(coherence): record the worktree test database enactment Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(roms): answer a hidden rom like a missing one on file routes; tighten route sweeps Addresses Greptile's review on #5584. The rom file delete and reading-progress routes answered "File not found" for a hidden rom but "Rom with id N not found" for a missing one, so a caller could tell them apart. They now raise the same not-found. The route sweeps now reach the checks they claim to test: a protected route with no scopes counts as public (its guard admits anyone), write requests carry a body and upload name so validation can't answer first, RomFile-keyed routes get a real file id, error bodies are compared with the id normalized, and the rom routes are swept with the rom hidden directly, through its platform, and by the unrated filter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(coherence): tighten route guard sweeps and isolate oracle test databases (code-review) - Count a route as protected only when its endpoint is the scope-checking wrapper with non-empty scopes, not just when it declares the bearer scopes. - Treat 401 and 403 like 422 as never reaching the visibility check, and sweep /api/streaming/states/{rom_id}. - Run pytest oracles with a per-run ROMM_TEST_DB_TAG unless one is set. - Use the shared setup-frontend action and ubuntu-24.04 in the workflow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(tests): simplify route guard sweeps and path tests (simplify) - Mark scope-guard wrappers with required_scopes so the auth sweep reads a public attribute instead of the private closure. - Derive the entity regex from one segment list, ask each missing id once, and run the three hide scenarios through one sweep helper. - Fold the new validate_path inputs into the existing valid, traversal and absolute path tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(coherence): trim workflow comments (review-polish) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(filesystem): restore the validate_path property test the paths invariant cites Filesystem.spec.md names test_validate_path_never_escapes_its_base as the invariant's evidence, and Coherence selects it by name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(coherence): run hooks from the local binary instead of npx Each hook calls frontend/node_modules/.bin/coherence directly and exits 0 when it isn't installed, so sessions without frontend deps (fresh worktrees, backend-only setups, cloud setup still installing) don't report a hook error on every tool call, and no hook pays npx's startup. Also commits the journal and run records left by earlier sessions, which .coherence/.gitignore keeps as durable records. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(tests): share the bearer, user token and hide helpers Tests built the same Authorization headers and HiddenEntity rows in about 40 local copies, and two modules imported private helpers from other test files. They now use bearer, user_headers and hide from tests/auth_helpers.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(endpoints): one 404 for a missing or hidden rom, platform or firmware Each route wrote the missing-row 404 and the hidden-row 404 separately and had to keep them identical by hand. visible_rom_or_404, visible_platform_or_404 and visible_firmware_or_404 take the lookup result and raise one answer for both, either the standard not-found or a bespoke detail. Re-reads after a write keep a plain not-found check, so an edit that hides the row doesn't turn into a 404 after it succeeded. The RomFile-keyed routes (/roms/{file_id}/files, .../files/content/{name}, /roms/{file_id}/patch) name their path parameter file_id instead of id, so the route sweep reads which id a route takes from its path and drops its hand-kept list. URLs are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(setup): develop inside WSL on Windows @posthog/coherence installs only on Linux and macOS, so npm install in frontend/ fails on native Windows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(coherence): record the whole-repo chokepoint run Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(types): regenerate API types for the file_id patch route Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
338 lines
11 KiB
Python
338 lines
11 KiB
Python
"""Install requests: the web UI queues and cancels them, the device claims and reports them."""
|
|
|
|
import asyncio
|
|
from collections.abc import Iterator
|
|
from contextlib import contextmanager
|
|
from typing import Annotated, Final
|
|
|
|
from fastapi import HTTPException
|
|
from fastapi import Path as PathVar
|
|
from fastapi import Request, Response, status
|
|
from pydantic import BaseModel, Field, field_validator
|
|
|
|
from config import DEVICE_INSTALL_ENABLED
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.device.install import (
|
|
InstallReason,
|
|
InstallRequestSchema,
|
|
InstallStatus,
|
|
)
|
|
from endpoints.sockets.devices import (
|
|
emit_install_cancelled,
|
|
emit_install_queued,
|
|
emit_install_updated,
|
|
mark_claimed,
|
|
online_device_ids,
|
|
)
|
|
from exceptions.endpoint_exceptions import (
|
|
DeviceInstallDisabledException,
|
|
)
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import (
|
|
get_rom_visibility_filter,
|
|
visible_rom_or_404,
|
|
)
|
|
from handler.database import db_device_handler, db_rom_handler
|
|
from handler.device_install import (
|
|
InstallRequestNotFoundError,
|
|
InstallTransitionError,
|
|
device_install_handler,
|
|
)
|
|
from handler.device_install.policy import (
|
|
InstallNotAllowedError,
|
|
accepts_remote_install,
|
|
is_installable_platform,
|
|
select_install_files,
|
|
)
|
|
from handler.notification_handler import notify
|
|
from logger.logger import log
|
|
from models.device import Device
|
|
from models.notification import NotificationKind, NotificationLevel
|
|
from utils.auth import require_device, token_reaches_device
|
|
from utils.router import APIRouter
|
|
|
|
router = APIRouter()
|
|
|
|
DEVICE_REPORTS: Final = frozenset(
|
|
{InstallStatus.DONE, InstallStatus.ALREADY_INSTALLED, InstallStatus.FAILED}
|
|
)
|
|
|
|
|
|
class InstallRequestCreatePayload(BaseModel):
|
|
rom_id: int = Field(ge=1)
|
|
|
|
|
|
class InstallRequestUpdatePayload(BaseModel):
|
|
status: InstallStatus
|
|
reason: InstallReason | None = None
|
|
|
|
@field_validator("status")
|
|
@classmethod
|
|
def _reportable(cls, value: InstallStatus) -> InstallStatus:
|
|
if value not in DEVICE_REPORTS:
|
|
raise ValueError(
|
|
f"A device reports one of {', '.join(sorted(DEVICE_REPORTS))}"
|
|
)
|
|
return value
|
|
|
|
|
|
async def _require_request(request: Request, device_id: str, request_id: str) -> None:
|
|
install = await device_install_handler.get(request_id)
|
|
if (
|
|
install is None
|
|
or install.device_id != device_id
|
|
or install.user_id != request.user.id
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Install request {request_id} not found",
|
|
)
|
|
|
|
|
|
@contextmanager
|
|
def _install_errors() -> Iterator[None]:
|
|
"""A gone request as a 404, a request in the wrong status as a 409."""
|
|
try:
|
|
yield
|
|
except InstallRequestNotFoundError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Install request {exc.args[0]} not found",
|
|
) from exc
|
|
except InstallTransitionError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
|
|
) from exc
|
|
|
|
|
|
def _hidden_rom_ids(request: Request, installs: list[InstallRequestSchema]) -> set[int]:
|
|
return db_rom_handler.get_hidden_rom_ids_among(
|
|
[install.rom_id for install in installs], get_rom_visibility_filter(request)
|
|
)
|
|
|
|
|
|
async def _notify_outcome(
|
|
request: Request, install: InstallRequestSchema, device: Device
|
|
) -> None:
|
|
rom = db_rom_handler.get_rom_visibility_label(install.rom_id)
|
|
# The reporting device acts as `install.user_id`, so the visibility is theirs.
|
|
hidden = rom is not None and not get_rom_visibility_filter(request).allows(rom)
|
|
failed = install.status == InstallStatus.FAILED
|
|
await notify(
|
|
install.user_id,
|
|
(
|
|
NotificationKind.DEVICE_INSTALL_FAILED
|
|
if failed
|
|
else NotificationKind.DEVICE_INSTALL_COMPLETED
|
|
),
|
|
NotificationLevel.ERROR if failed else NotificationLevel.SUCCESS,
|
|
{
|
|
"rom_id": None if hidden else install.rom_id,
|
|
"rom_name": (rom.name or rom.fs_name) if rom and not hidden else None,
|
|
"device_name": device.name or device.hostname,
|
|
"status": install.status,
|
|
"reason": install.reason,
|
|
},
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/online",
|
|
[Scope.DEVICES_READ],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
async def get_online_devices(request: Request) -> list[str]:
|
|
"""Ids of the caller's devices holding an open device socket or that claimed lately."""
|
|
if not DEVICE_INSTALL_ENABLED:
|
|
raise DeviceInstallDisabledException()
|
|
device_ids = [
|
|
device.id
|
|
for device in db_device_handler.get_devices(user_id=request.user.id)
|
|
if token_reaches_device(request, device.id)
|
|
]
|
|
return await online_device_ids(device_ids)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/{device_id}/installs",
|
|
[Scope.DEVICES_WRITE, Scope.ROMS_READ],
|
|
status_code=status.HTTP_201_CREATED,
|
|
responses={
|
|
status.HTTP_200_OK: {"model": InstallRequestSchema},
|
|
status.HTTP_400_BAD_REQUEST: {},
|
|
status.HTTP_404_NOT_FOUND: {},
|
|
status.HTTP_409_CONFLICT: {},
|
|
},
|
|
)
|
|
async def create_install_request(
|
|
request: Request,
|
|
response: Response,
|
|
device_id: Annotated[str, PathVar(description="Target device id.")],
|
|
payload: InstallRequestCreatePayload,
|
|
) -> InstallRequestSchema:
|
|
"""Queue a rom for install on a device, returning a live request for the same pair with 200."""
|
|
if not DEVICE_INSTALL_ENABLED:
|
|
raise DeviceInstallDisabledException()
|
|
device = require_device(request, device_id)
|
|
if not accepts_remote_install(device.capabilities):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Device {device_id} does not accept remote installs",
|
|
)
|
|
|
|
rom = visible_rom_or_404(
|
|
request, db_rom_handler.get_rom_install_target(payload.rom_id), payload.rom_id
|
|
)
|
|
|
|
if not is_installable_platform(rom.platform_slug):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Roms for {rom.platform_slug} cannot be installed on a device",
|
|
)
|
|
# A rescan flags only the rom when its path is gone, never its file rows.
|
|
files = [] if rom.missing_from_fs else db_rom_handler.rom_files_for_rom_id(rom.id)
|
|
try:
|
|
file_ids = select_install_files(files)
|
|
except InstallNotAllowedError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
|
|
) from exc
|
|
|
|
with _install_errors():
|
|
install, created = await device_install_handler.create(
|
|
user_id=request.user.id,
|
|
device_id=device_id,
|
|
rom_id=rom.id,
|
|
file_ids=file_ids,
|
|
)
|
|
|
|
if not created:
|
|
response.status_code = status.HTTP_200_OK
|
|
return install
|
|
|
|
# A delete that ran between the device check and the write missed this request.
|
|
if (
|
|
db_device_handler.get_device(device_id=device_id, user_id=request.user.id)
|
|
is None
|
|
):
|
|
await device_install_handler.discard_for_device(device_id)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Device with ID {device_id} not found",
|
|
)
|
|
|
|
log.info(f"Queued rom {rom.id} for install on device {device_id}")
|
|
await asyncio.gather(emit_install_queued(install), emit_install_updated(install))
|
|
return install
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/{device_id}/installs",
|
|
[Scope.DEVICES_READ],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
async def list_install_requests(
|
|
request: Request,
|
|
device_id: Annotated[str, PathVar(description="Target device id.")],
|
|
) -> list[InstallRequestSchema]:
|
|
"""The device's pending and taken requests, oldest first."""
|
|
if not DEVICE_INSTALL_ENABLED:
|
|
raise DeviceInstallDisabledException()
|
|
require_device(request, device_id)
|
|
|
|
installs = await device_install_handler.list_for_device(device_id)
|
|
hidden = _hidden_rom_ids(request, installs)
|
|
return [install for install in installs if install.rom_id not in hidden]
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/{device_id}/installs/claim",
|
|
[Scope.DEVICES_WRITE, Scope.ROMS_READ],
|
|
responses={
|
|
status.HTTP_403_FORBIDDEN: {},
|
|
status.HTTP_404_NOT_FOUND: {},
|
|
status.HTTP_409_CONFLICT: {},
|
|
},
|
|
)
|
|
async def claim_install_requests(
|
|
request: Request,
|
|
device_id: Annotated[str, PathVar(description="Target device id.")],
|
|
) -> list[InstallRequestSchema]:
|
|
"""Take every pending request and return all the device holds taken, oldest first."""
|
|
if not DEVICE_INSTALL_ENABLED:
|
|
raise DeviceInstallDisabledException()
|
|
require_device(request, device_id, device_only=True)
|
|
|
|
# A request is only queued for a visible ROM, so one hidden later stays pending.
|
|
hidden: set[int] = set()
|
|
if not get_rom_visibility_filter(request).is_unrestricted:
|
|
hidden = _hidden_rom_ids(
|
|
request, await device_install_handler.list_for_device(device_id)
|
|
)
|
|
with _install_errors():
|
|
claim = await device_install_handler.claim(device_id, skip_rom_ids=hidden)
|
|
|
|
await mark_claimed(device_id)
|
|
await asyncio.gather(*(emit_install_updated(i) for i in claim.newly_taken))
|
|
return claim.taken
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{device_id}/installs/{request_id}",
|
|
[Scope.DEVICES_WRITE],
|
|
responses={
|
|
status.HTTP_403_FORBIDDEN: {},
|
|
status.HTTP_404_NOT_FOUND: {},
|
|
status.HTTP_409_CONFLICT: {},
|
|
},
|
|
)
|
|
async def update_install_request(
|
|
request: Request,
|
|
device_id: Annotated[str, PathVar(description="Target device id.")],
|
|
request_id: Annotated[str, PathVar(description="Install request id.")],
|
|
payload: InstallRequestUpdatePayload,
|
|
) -> InstallRequestSchema:
|
|
"""The device reports the outcome of a request it has taken, which ends the request."""
|
|
if not DEVICE_INSTALL_ENABLED:
|
|
raise DeviceInstallDisabledException()
|
|
device = require_device(request, device_id, device_only=True)
|
|
await _require_request(request, device_id, request_id)
|
|
|
|
with _install_errors():
|
|
ended = await device_install_handler.report(
|
|
request_id, payload.status, payload.reason
|
|
)
|
|
|
|
await emit_install_updated(ended)
|
|
await _notify_outcome(request, ended, device)
|
|
return ended
|
|
|
|
|
|
@protected_route(
|
|
router.delete,
|
|
"/{device_id}/installs/{request_id}",
|
|
[Scope.DEVICES_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}, status.HTTP_409_CONFLICT: {}},
|
|
)
|
|
async def cancel_install_request(
|
|
request: Request,
|
|
device_id: Annotated[str, PathVar(description="Target device id.")],
|
|
request_id: Annotated[str, PathVar(description="Install request id.")],
|
|
) -> InstallRequestSchema:
|
|
"""Cancel a request still pending or taken; one already ended is a 404."""
|
|
if not DEVICE_INSTALL_ENABLED:
|
|
raise DeviceInstallDisabledException()
|
|
require_device(request, device_id)
|
|
await _require_request(request, device_id, request_id)
|
|
|
|
with _install_errors():
|
|
ended = await device_install_handler.cancel(request_id)
|
|
|
|
await asyncio.gather(emit_install_cancelled(ended), emit_install_updated(ended))
|
|
return ended
|