desktop_console.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Keep Windows console backpressure off the packaged desktop startup path."""
  2. import logging
  3. import os
  4. import sys
  5. import threading
  6. import time
  7. from contextlib import contextmanager
  8. logger = logging.getLogger("hermes_cli.desktop")
  9. def desktop_launch_notice(message: str, *, source_mode: bool = False) -> None:
  10. if sys.platform == "win32" and not source_mode:
  11. # setup_logging() uses an async queue and rotating, redacted files.
  12. logger.info(message)
  13. else:
  14. print(message)
  15. @contextmanager
  16. def desktop_console_output(*, source_mode: bool):
  17. """Drain packaged Windows stdout/stderr into the existing rotating logs.
  18. Inheriting the console lets an unresponsive console host/profiler block
  19. Electron's synchronous startup messages before it can create a window.
  20. Keep source launches interactive and preserve subprocess.run's lifecycle
  21. and exit-code handling. Read bounded lines so output cannot grow a buffer
  22. without limit, and never wait indefinitely on a descendant's open pipe.
  23. """
  24. if sys.platform != "win32" or source_mode:
  25. yield {}
  26. return
  27. def drain(read_fd, level):
  28. with os.fdopen(read_fd, "rb") as stream:
  29. # Decode/redact complete records, not arbitrary pipe-read fragments.
  30. # Discard an oversized line in full: even its prefix may be a secret.
  31. limit = 128 * 1024
  32. while data := stream.readline(limit + 1):
  33. if len(data) > limit:
  34. while data and not data.endswith(b"\n"):
  35. data = stream.readline(8192)
  36. logger.log(level, "[desktop] [oversized line omitted]")
  37. else:
  38. logger.log(level, "[desktop] %s", data.decode("utf-8", errors="replace").rstrip())
  39. streams = {}
  40. readers = []
  41. try:
  42. # Keep diagnostics visible even when ordinary INFO output is disabled.
  43. for name, level in (("stdout", logging.INFO), ("stderr", logging.ERROR)):
  44. read_fd, write_fd = os.pipe()
  45. streams[name] = write_fd
  46. reader = threading.Thread(
  47. target=drain, args=(read_fd, level), name=f"desktop-console-{name}", daemon=True,
  48. )
  49. try:
  50. reader.start()
  51. except BaseException:
  52. os.close(read_fd)
  53. raise
  54. readers.append(reader)
  55. yield streams
  56. finally:
  57. for write_fd in streams.values():
  58. os.close(write_fd)
  59. deadline = time.monotonic() + 1
  60. for reader in readers:
  61. reader.join(timeout=max(0, deadline - time.monotonic()))