chat_workspaces.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """Chat workspace picker: which host directories a NEW dashboard chat can start in.
  2. The dashboard's ``/chat`` tab used to spawn every fresh TUI in the dashboard process's own
  3. launch directory, so from a phone or browser there was no way to say "work in ~/code/foo".
  4. This lists the same projects and discovered repositories the Desktop sidebar shows (the
  5. per-profile ``projects.db`` plus session-derived and scanned git roots) so the SPA can offer
  6. a picker, and ``/api/pty?cwd=`` (``chat_ws``) honours the choice.
  7. """
  8. from __future__ import annotations
  9. import os
  10. from pathlib import Path
  11. from typing import Optional
  12. from fastapi import APIRouter, HTTPException
  13. from hermes_cli.web_deps import late
  14. from hermes_cli.web_routers._common import http_failure, scoped_to_thread
  15. router = APIRouter()
  16. _open_session_db_for_profile = late("_open_session_db_for_profile", "hermes_cli.web_server_sessions")
  17. def resolve_chat_cwd(raw: Optional[str]) -> Optional[str]:
  18. """Validate a ``?cwd=`` for a fresh chat: an existing host directory, or None when unset.
  19. A dead or relative path fails closed (400) instead of silently falling back to the launch
  20. dir — the user picked a workspace and would otherwise get a session in the wrong place.
  21. """
  22. text = (raw or "").strip()
  23. if not text:
  24. return None
  25. resolved = os.path.abspath(os.path.expanduser(text))
  26. if not os.path.isdir(resolved):
  27. raise HTTPException(status_code=400, detail=f"Working directory does not exist: {text}")
  28. return resolved
  29. def _collect_workspaces(profile: Optional[str], scan: bool) -> dict:
  30. # The dashboard hosts the in-process gateway (``web_server`` imports ``tui_gateway.server``
  31. # at startup), so the sidebar's repo-discovery helpers are already bound there.
  32. import tui_gateway.server as gateway
  33. from hermes_cli import projects_db as pdb
  34. # Browsing never bootstraps the owner's session store: a profile whose gateway has not
  35. # yet initialized state.db simply contributes no session-derived roots (``db=None``).
  36. try:
  37. db = _open_session_db_for_profile(profile, read_only=True)
  38. except HTTPException as exc:
  39. if exc.status_code != 503:
  40. raise
  41. db = None
  42. try:
  43. with pdb.connect_closing() as conn:
  44. policy = gateway._repo_discovery_policy()
  45. if scan and policy["enabled"]:
  46. gateway._scan_discovered_repos_remote(conn, policy)
  47. projects = [p.to_dict() for p in pdb.list_projects(conn)]
  48. repos = gateway._discover_repos_payload(
  49. db, conn=conn, backfill=False, include_cached=policy["enabled"])
  50. finally:
  51. if db is not None:
  52. db.close()
  53. default_cwd = gateway._completion_cwd({"profile": profile} if profile else {})
  54. return {
  55. "projects": projects, "repos": repos, "default_cwd": default_cwd,
  56. "home": str(Path.home()), "scan_enabled": bool(policy["enabled"])}
  57. @router.get("/api/chat/workspaces")
  58. async def get_chat_workspaces(profile: Optional[str] = None, scan: bool = False):
  59. """Projects + discovered repos a fresh chat may start in; ``scan=1`` rescans the
  60. configured discovery roots on the host first (headless installs have no Desktop to do it)."""
  61. with http_failure("GET /api/chat/workspaces failed", 500, "Failed to list workspaces"):
  62. return await scoped_to_thread(profile, lambda: _collect_workspaces(profile, scan))