uploads.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """Authenticated browser-to-host attachment staging for Hermes Webapp."""
  2. from __future__ import annotations
  3. import asyncio
  4. import os
  5. from fastapi import APIRouter, File, HTTPException, UploadFile
  6. from hermes_constants import WEBAPP_ATTACHMENT_MAX_BYTES
  7. from hermes_cli.staged_uploads import (
  8. publish_staged_upload,
  9. resolve_upload_home,
  10. staged_upload_descriptor,
  11. )
  12. router = APIRouter()
  13. _MAX_UPLOAD_BYTES = WEBAPP_ATTACHMENT_MAX_BYTES
  14. @router.post("/api/chat/file-upload")
  15. async def upload_chat_file(
  16. file: UploadFile = File(...),
  17. profile: str | None = None,
  18. ):
  19. """Stage one user-selected browser file under the active Hermes profile.
  20. The client never chooses a server path. A unique 0600 file under
  21. ``$HERMES_HOME/uploads`` is returned for the existing ``file.attach`` flow.
  22. """
  23. profile_home = await asyncio.to_thread(resolve_upload_home, profile)
  24. try:
  25. # FastAPI has already spooled the complete upload outside the profile.
  26. # Check the actual bytes, then publish that spool into the resolved home.
  27. total = await asyncio.to_thread(file.file.seek, 0, os.SEEK_END)
  28. if total > _MAX_UPLOAD_BYTES:
  29. cap_mib = _MAX_UPLOAD_BYTES // (1024 * 1024)
  30. raise HTTPException(
  31. status_code=413,
  32. detail=f"File is too large; cap is {cap_mib} MiB",
  33. )
  34. target = await asyncio.to_thread(
  35. publish_staged_upload,
  36. file.file,
  37. profile_home,
  38. file.filename or "attachment",
  39. )
  40. finally:
  41. await file.close()
  42. result = {"ok": True, "path": str(target), "size": total}
  43. if descriptor := await asyncio.to_thread(staged_upload_descriptor, target, profile_home):
  44. result["staged_upload"] = descriptor
  45. return result