terminal_tool_macos_open.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. """macOS ``open`` frontmost raise-ladder for the terminal tool.
  2. Split out of ``tools/terminal_tool.py`` (PR #95286, Jackal991): a pure,
  3. deterministic string rewrite — no subprocess calls at transform time — that
  4. appends a verified raise-ladder to file-opening ``open`` invocations so the
  5. opened document lands in front of the Hermes window instead of behind it.
  6. """
  7. import platform
  8. import shlex
  9. # ---------------------------------------------------------------------------
  10. # macOS `open` frontmost raise-ladder
  11. #
  12. # On macOS, when the agent opens a file via a tool call (e.g. `open -a Preview
  13. # file.pdf` or `open file.pdf`), the command returns exit 0 and genuinely
  14. # succeeds — the document loads and a window is created — but the window opens
  15. # BEHIND the Hermes desktop window (Hermes is typically maximised, so the file
  16. # is completely hidden). Because the exit code is 0, the agent reports success
  17. # while the user sees nothing happen.
  18. #
  19. # Root cause: the tool shell runs as a child process of the Electron app; macOS
  20. # does not let a non-frontmost process hand activation to another app, so the
  21. # implicit activation that normally accompanies `open` is silently ignored.
  22. # `osascript -e 'tell application "X" to activate'` alone is NOT reliable (it
  23. # also returns 0 while focus lands elsewhere, e.g. a racing Chrome).
  24. #
  25. # Fix: VERIFY, don't trust the exit code. After an `open`, check `frontmost`
  26. # and escalate via a raise-ladder, then settle ~0.8s, re-check, and re-assert
  27. # once. Each rung is verified before moving on; the report comes from the final
  28. # observed state, never from "a rung returned 0".
  29. # ---------------------------------------------------------------------------
  30. # `open` flags that do NOT open a file in a new frontmost window and must never
  31. # be transformed (conservative: only transform when it clearly opens a file).
  32. _MACOS_OPEN_NO_TRANSFORM_FLAGS = frozenset(
  33. {"-R", "-e", "-t", "-f", "-W", "-n", "-g", "-h", "-b", "-D"}
  34. )
  35. # Shell splice that breaks out of a single-quoted osascript argument so the
  36. # shell expands $_H_APP (handles app names containing spaces, e.g. "Google
  37. # Chrome"). Renders as: " ' " $_H_APP " ' "
  38. _APP_SPLICE = '"\'"$_H_APP"\'"'
  39. def _osascript_app(script: str) -> str:
  40. """Wrap an AppleScript snippet in an `osascript -e` invocation.
  41. ``script`` may reference the target app via the ``_APP_SPLICE`` shell
  42. splice (``$_H_APP``). Errors are suppressed so a swallowed AppleEvent
  43. simply falls through to the next rung of the ladder.
  44. """
  45. return f"osascript -e '{script}' 2>/dev/null"
  46. def _build_macos_open_raise_ladder(app: str | None, file: str) -> str:
  47. """Build the shell raise-ladder appended after a macOS ``open`` command.
  48. The ladder verifies the target app is frontmost and escalates through
  49. progressively more forceful activation mechanisms, then settles ~0.8s,
  50. re-checks ``frontmost``, and re-asserts once to absorb a queued activation
  51. from another app. Each rung is verified before moving on.
  52. Args:
  53. app: The target application name (from ``open -a <App>``), or None for
  54. a bare ``open <file>`` where the app is resolved at runtime from
  55. the frontmost process.
  56. file: The file path that was opened.
  57. """
  58. if app is not None:
  59. app_assign = f"_H_APP={shlex.quote(app)}"
  60. else:
  61. # Bare `open <file>`: the target app is unknown at transform time, so
  62. # resolve it at runtime from whichever process is frontmost after the
  63. # open (the app that actually received the document).
  64. app_assign = (
  65. '_H_APP="$(osascript -e \'tell application "System Events" to get '
  66. 'name of first application process whose frontmost is true\' '
  67. '2>/dev/null)"'
  68. )
  69. file_q = shlex.quote(file)
  70. activate = _osascript_app("tell application " + _APP_SPLICE + " to activate")
  71. frontmost = _osascript_app(
  72. 'tell application "System Events" to get frontmost of application process '
  73. + _APP_SPLICE
  74. )
  75. unminimise = _osascript_app(
  76. 'tell application "System Events" to set visible of every process to true'
  77. )
  78. # lsappinfo is a different subsystem and works even when AppleEvents are
  79. # swallowed. `find` returns the app's ASN; `setfront` raises it.
  80. asn = 'lsappinfo find "$_H_APP" 2>/dev/null | awk \'{print $1}\''
  81. setfront = '[ -n "$_H_ASN" ] && lsappinfo setfront "$_H_ASN" 2>/dev/null'
  82. # Re-issuing `open -a <App> <file>` on the already-open document is treated
  83. # by macOS as pure activation.
  84. reopen = f"open -a \"$_H_APP\" {file_q} 2>/dev/null"
  85. # Outcome reporting from the FINAL observed frontmost state. The two
  86. # branches are deliberately distinct so a focus race can never read as
  87. # success: the tool output tells the agent (and the user) whether the
  88. # opened document actually ended up in front, and if not, which
  89. # application holds focus. ``file_q`` is a self-contained quoted token, so
  90. # the messages survive paths with spaces or shell metacharacters.
  91. frontmost_name = (
  92. "osascript -e 'tell application \"System Events\" to get name of "
  93. "first application process whose frontmost is true' 2>/dev/null"
  94. )
  95. report = (
  96. f'if {frontmost}; then echo open: {file_q} is now frontmost; '
  97. f'else _H_FOCUS=$({frontmost_name}); '
  98. f'echo open: {file_q} opened but another application holds focus; '
  99. f'echo "frontmost: $_H_FOCUS"; fi'
  100. )
  101. return (
  102. f"{app_assign}; "
  103. f"if ! {frontmost}; then "
  104. f"{activate}; sleep 0.2; "
  105. f"if ! {frontmost}; then "
  106. f"_H_ASN=$({asn}); {setfront}; sleep 0.2; "
  107. f"if ! {frontmost}; then "
  108. f"{reopen}; sleep 0.2; {unminimise}; {activate}; "
  109. f"fi; "
  110. f"fi; "
  111. f"fi; "
  112. f"sleep 0.8; "
  113. f"if ! {frontmost}; then {activate}; sleep 0.4; fi; "
  114. f"{report}"
  115. )
  116. def _transform_macos_open_command(command: str | None, system: str | None = None) -> str | None:
  117. """Append a frontmost raise-ladder to a macOS ``open`` command.
  118. On macOS, ``open <file>`` / ``open -a <App> <file>`` returns exit 0 and
  119. genuinely opens the document, but the window can land BEHIND the Hermes
  120. desktop window (Hermes is typically maximised), so the user sees nothing
  121. happen while the agent reports success. This transform appends a verified
  122. raise-ladder that brings the opened app to the front.
  123. The transform is a pure, deterministic string rewrite (no subprocess calls
  124. at transform time) so it is unit-testable on any OS by passing ``system``
  125. as data (``"Darwin"`` to exercise the ladder, ``"Linux"`` to prove the
  126. no-op). The actual osascript/lsappinfo calls happen at runtime inside the
  127. rewritten shell command.
  128. Conservative: only transforms a bare ``open <file>`` or
  129. ``open -a <App> <file>``. Never transforms ``open`` with no args, the
  130. non-file-opening flags (``-R``/``-e``/``-t``/``-f``/``-W``/``-n``/``-g``/
  131. ``-h``/``-b``/``-D``), ``open -a <App>`` with no file, compound commands,
  132. or any non-``open`` command. The original ``open`` runs exactly as written.
  133. """
  134. if (system if system is not None else platform.system()) != "Darwin":
  135. return command
  136. if command is None:
  137. return command
  138. try:
  139. tokens = shlex.split(command)
  140. except ValueError:
  141. return command
  142. if not tokens or tokens[0] != "open":
  143. return command
  144. args = tokens[1:]
  145. if not args:
  146. return command
  147. first = args[0]
  148. if first.startswith("-"):
  149. if first in _MACOS_OPEN_NO_TRANSFORM_FLAGS:
  150. return command
  151. if first == "-a":
  152. # open -a <App> <file>
  153. if len(args) < 3:
  154. return command
  155. app, file = args[1], args[2]
  156. if file.startswith("-"):
  157. return command
  158. if len(tokens) != 4:
  159. return command
  160. else:
  161. return command
  162. else:
  163. # bare open <file>
  164. file = first
  165. app = None
  166. if len(tokens) != 2:
  167. return command
  168. ladder = _build_macos_open_raise_ladder(app, file)
  169. return f"{command}; {ladder}"