foreign_sessions_browser.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """Backend-local discovery and previews for the desktop session importer."""
  2. import hashlib
  3. import re
  4. import socket
  5. from pathlib import Path
  6. from hermes_cli.foreign_sessions import _SOURCE_DB_NAMES, _SOURCE_LABELS, _SOURCES, _parser, _walk
  7. MAX_LOG_BYTES = 32 * 1024 * 1024
  8. def _display_title(parsed, source):
  9. # Codex attachment envelopes put the actual request after a file listing.
  10. # Keep the history intact; only the browser's display title skips that header.
  11. first_user = next((turn["content"] for turn in parsed["turns"] if turn["role"] == "user"), "")
  12. request = re.split(r"(?im)^#{1,6}\s*My request:\s*$", first_user, maxsplit=1)
  13. title = request[-1].strip().splitlines()[0] if len(request) > 1 and request[-1].strip() else parsed["title_guess"]
  14. return (title or _SOURCE_LABELS[source]).lstrip("# ")[:180]
  15. def _candidates(source=None):
  16. """``(mtime, handle, source, path, size)`` rows across sources, newest first. The handle is
  17. the only identifier handed to the client; a request can never name a path."""
  18. if source is not None and source not in _SOURCES:
  19. raise ValueError("Unknown session source")
  20. rows = [(st.st_mtime, hashlib.sha256(f"{name}:{path}".encode()).hexdigest(), name, path, st.st_size)
  21. for name in _SOURCES if source in (None, name) for path, st in _walk(name)]
  22. return sorted(rows, key=lambda row: (row[0], row[1]), reverse=True)
  23. def _parse(candidate):
  24. _, _, source, path, size = candidate
  25. if size > MAX_LOG_BYTES:
  26. raise ValueError("This log exceeds the 32 MB preview and import limit")
  27. parsed = _parser(source)(path)
  28. if not parsed["turns"]:
  29. raise ValueError("This session has no readable conversation messages")
  30. return parsed
  31. def resolve_foreign_session(handle):
  32. if not isinstance(handle, str) or len(handle) != 64:
  33. raise ValueError("Unknown session. Refresh the list and try again")
  34. for candidate in _candidates():
  35. if candidate[1] == handle:
  36. return candidate, _parse(candidate)
  37. raise ValueError("Session no longer available. Refresh the list and try again")
  38. def list_foreign_sessions(source=None, offset=0, limit=25):
  39. if not isinstance(offset, int) or offset < 0 or not isinstance(limit, int) or not 1 <= limit <= 50:
  40. raise ValueError("Invalid session page")
  41. candidates = _candidates(source)
  42. rows, unreadable = [], 0
  43. # Page candidates before parsing. Empty or oversized logs cannot turn a
  44. # request for 25 rows into an unbounded transcript scan.
  45. for candidate in candidates[offset:offset + limit]:
  46. mtime, handle, name, _, _ = candidate
  47. try:
  48. parsed = _parse(candidate)
  49. except (ValueError, OSError):
  50. unreadable += 1
  51. continue
  52. rows.append({"id": handle, "source": name, "label": _SOURCE_LABELS[name],
  53. "title": _display_title(parsed, name),
  54. "cwd": parsed["cwd"], "mtime": mtime, "turn_count": len(parsed["turns"]),
  55. "excerpt": parsed["turns"][0]["content"][:200]})
  56. next_offset = offset + limit
  57. return {"sessions": rows, "next_offset": next_offset if next_offset < len(candidates) else None,
  58. "host": socket.gethostname(), "unreadable": unreadable}
  59. def foreign_origin(candidate, parsed):
  60. return {"tool": _SOURCE_DB_NAMES[candidate[2]], "path": str(candidate[3]),
  61. "foreign_session_id": parsed["session_id"]}
  62. def preview_foreign_session(handle, db):
  63. candidate, parsed = resolve_foreign_session(handle)
  64. origin = foreign_origin(candidate, parsed)
  65. existing = db.find_foreign_import(origin)
  66. # A bounded preview avoids mounting thousands of messages in the renderer.
  67. messages = [{**turn, "content": turn["content"][:8000]} for turn in parsed["turns"][-40:]]
  68. return {"messages": messages, "total": len(parsed["turns"]),
  69. "truncated": len(parsed["turns"]) > 40 or any(len(turn["content"]) > 8000 for turn in parsed["turns"][-40:]),
  70. "already_imported": existing, "cwd": parsed["cwd"]}
  71. def import_browser_session(handle, db, profile):
  72. candidate, parsed = resolve_foreign_session(handle)
  73. origin = foreign_origin(candidate, parsed)
  74. cwd = parsed["cwd"]
  75. return db.import_foreign_history(origin, parsed["turns"],
  76. title=_display_title(parsed, candidate[2]),
  77. cwd=cwd if cwd and Path(cwd).is_dir() else None, profile=profile)