← back to Terminal Status

pin_codex_headers.py

61 lines

#!/usr/bin/env python3
"""One-time native bindings for currently live Codex windows; no timer installed."""
import json
from pathlib import Path
import subprocess
import terminal_status as ts

live = ts.owners(ts.processes())
codex = {tty for tty, owner in live.items() if owner.runtime == 'codex'}
script = '''
tell application "iTerm2"
 set resultRows to ""
 repeat with w in windows
  repeat with ti from 1 to count of tabs of w
   repeat with s in sessions of tab ti of w
    set resultRows to resultRows & (id of w as text) & " " & ti & " " & (tty of s) & linefeed
   end repeat
  end repeat
 end repeat
 return resultRows
end tell
'''
output = subprocess.run(['osascript', '-e', script], capture_output=True, text=True, check=True).stdout
targets = set()
for line in output.splitlines():
    parts = line.split()
    if len(parts) == 3 and parts[2].removeprefix('/dev/') in codex:
        targets.add((int(parts[0]), int(parts[1])))
evidence = []
for window, tab in sorted(targets):
    script = f'''
tell application "iTerm2"
 select window id {window}
 select tab {tab} of window id {window}
 activate
end tell
tell application "System Events" to tell process "iTerm2"
 click menu item "Edit Tab Title" of menu 1 of menu item "Tab" of menu "Window" of menu bar 1
 delay 0.2
 if not (exists static text "Set Tab Title" of sheet 1 of window 1) then error "Unexpected tab dialog"
 set oldTab to value of text field 1 of sheet 1 of window 1
 set value of text field 1 of sheet 1 of window 1 to "\\\\(currentSession.user.abramsTitle)"
 click button "OK" of sheet 1 of window 1
 click menu item "Edit Window Title" of menu "Window" of menu bar 1
 delay 0.2
 if not (exists static text "Set Window Title" of window 1) then error "Unexpected window dialog"
 set oldWindow to value of text field 1 of window 1
 set value of text field 1 of window 1 to "\\\\(currentTab.currentSession.user.abramsTitle)"
 click button "OK" of window 1
end tell
delay 0.2
tell application "iTerm2"
 return oldTab & linefeed & oldWindow & linefeed & (name of window id {window})
end tell
'''
    result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True, check=True)
    evidence.append({'window': window, 'tab': tab, 'result': result.stdout.strip()})
path = Path.home() / '.local/state/abrams-terminal-status/native-title-bindings.json'
ts.atomic_write(path, json.dumps(evidence, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(evidence, ensure_ascii=False, indent=2))