agent-command-tab 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. agent_command_tab/__init__.py +4 -0
  2. agent_command_tab/agent_adapters/__init__.py +48 -0
  3. agent_command_tab/agent_adapters/base.py +162 -0
  4. agent_command_tab/agent_adapters/claude_code.py +120 -0
  5. agent_command_tab/agent_adapters/codex.py +102 -0
  6. agent_command_tab/agent_adapters/generic.py +22 -0
  7. agent_command_tab/agent_process_tree.py +557 -0
  8. agent_command_tab/agent_session_pausing.py +254 -0
  9. agent_command_tab/app_controller.py +947 -0
  10. agent_command_tab/claude_code_transcript_records.py +75 -0
  11. agent_command_tab/command_line.py +187 -0
  12. agent_command_tab/context_window_usage.py +230 -0
  13. agent_command_tab/dashboard_core_api.py +57 -0
  14. agent_command_tab/docked_window_frames_store.py +60 -0
  15. agent_command_tab/global_shortcut_key_filter.py +167 -0
  16. agent_command_tab/hook_event_forwarder.py +116 -0
  17. agent_command_tab/hook_event_tracking.py +129 -0
  18. agent_command_tab/hook_states_store.py +60 -0
  19. agent_command_tab/hooks_installer.py +300 -0
  20. agent_command_tab/installed_copy_paths.py +41 -0
  21. agent_command_tab/iterm2_actions.py +325 -0
  22. agent_command_tab/iterm2_connection_thread.py +2299 -0
  23. agent_command_tab/iterm2_snapshot_builder.py +403 -0
  24. agent_command_tab/list_sorting.py +117 -0
  25. agent_command_tab/messages_between_agent_sessions.py +78 -0
  26. agent_command_tab/monitor_assignment.py +109 -0
  27. agent_command_tab/pause_records_store.py +61 -0
  28. agent_command_tab/screen_readings.py +108 -0
  29. agent_command_tab/session_preview_computation.py +228 -0
  30. agent_command_tab/session_status_computation.py +235 -0
  31. agent_command_tab/settings_store.py +292 -0
  32. agent_command_tab/snapshot_data_classes.py +145 -0
  33. agent_command_tab/start_with_iterm2.py +138 -0
  34. agent_command_tab/tab_order_computation.py +26 -0
  35. agent_command_tab/user_interface/__init__.py +1 -0
  36. agent_command_tab/user_interface/agent_session_outline_view.py +2120 -0
  37. agent_command_tab/user_interface/agent_tool_icons.py +124 -0
  38. agent_command_tab/user_interface/app_icon.py +75 -0
  39. agent_command_tab/user_interface/control_helpers.py +38 -0
  40. agent_command_tab/user_interface/list_window.py +116 -0
  41. agent_command_tab/user_interface/menu_bar_status_item.py +193 -0
  42. agent_command_tab/user_interface/named_colors.py +58 -0
  43. agent_command_tab/user_interface/pointing_hand_button.py +42 -0
  44. agent_command_tab/user_interface/popover_container.py +461 -0
  45. agent_command_tab/user_interface/row_text_rendering.py +342 -0
  46. agent_command_tab/user_interface/screen_layout.py +91 -0
  47. agent_command_tab/user_interface/settings_window.py +530 -0
  48. agent_command_tab/user_interface/sidebar_panel.py +486 -0
  49. agent_command_tab/user_interface/sidebar_placement.py +105 -0
  50. agent_command_tab/user_interface/talk_to_each_other_alert.py +130 -0
  51. agent_command_tab/window_list_ordering.py +44 -0
  52. agent_command_tab-0.1.0.dist-info/METADATA +85 -0
  53. agent_command_tab-0.1.0.dist-info/RECORD +57 -0
  54. agent_command_tab-0.1.0.dist-info/WHEEL +5 -0
  55. agent_command_tab-0.1.0.dist-info/entry_points.txt +2 -0
  56. agent_command_tab-0.1.0.dist-info/licenses/LICENSE +21 -0
  57. agent_command_tab-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,167 @@
1
+ """The global shortcut that shows the list from any app (user request, 2026-10-19).
2
+
3
+ The shortcut is Shift-Command-Tab (the default) or Command-Fn-Tab. macOS's app switcher takes
4
+ both before macOS's usual way of making a global shortcut (RegisterEventHotKey) sees them, also
5
+ with Fn held, so they are caught by a key filter instead: an active event tap (CGEventTapCreate)
6
+ that sees every key press before the app switcher does and holds back only the chosen shortcut.
7
+ While the app switcher is open (Command still held after a Command-Tab press), the shortcut goes
8
+ to the app switcher, where Shift-Command-Tab moves backward (user request). Both were checked with
9
+ real key presses on 2026-10-19.
10
+
11
+ The filter needs the Accessibility permission (macOS checks it for the app that started this one,
12
+ such as iTerm2). It runs on its own thread, so key presses never wait for the main thread's run
13
+ loop, but each key event takes Python's global lock once, so while another thread runs Python
14
+ a key press waits a moment for it. It calls CoreGraphics through ctypes, so it needs no extra
15
+ package.
16
+ """
17
+
18
+ import collections
19
+ import ctypes
20
+ import threading
21
+
22
+ CORE_GRAPHICS_PATH = "/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics"
23
+ CORE_GRAPHICS = ctypes.CDLL(CORE_GRAPHICS_PATH)
24
+ # The reads made for every key event keep Python's global lock (PyDLL): ctypes.CDLL would let go
25
+ # of it around each call, and each time the key event could wait for another thread to give it back.
26
+ CORE_GRAPHICS_KEEPING_THE_PYTHON_LOCK = ctypes.PyDLL(CORE_GRAPHICS_PATH)
27
+ CORE_FOUNDATION = ctypes.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
28
+
29
+ # CGEventType values (CGEventTypes.h): the events the filter asks for, and the two that say macOS
30
+ # turned the filter off (it answered too slowly, or secure typing such as a password field began).
31
+ KEY_DOWN_EVENT, KEY_UP_EVENT, MODIFIER_KEYS_CHANGED_EVENT = 10, 11, 12
32
+ FILTER_TURNED_OFF_EVENTS = (0xFFFFFFFE, 0xFFFFFFFF)
33
+ KEY_EVENT_MASK = (1 << KEY_DOWN_EVENT) | (1 << KEY_UP_EVENT) | (1 << MODIFIER_KEYS_CHANGED_EVENT)
34
+ # CGEventField values: whether a key press is the key repeating, and which key it is.
35
+ KEY_REPEAT_FIELD, KEY_CODE_FIELD = 8, 9
36
+ TAB_KEY_CODE = 48
37
+ # CGEventFlags masks.
38
+ SHIFT_FLAG, CONTROL_FLAG, OPTION_FLAG, COMMAND_FLAG, FN_FLAG = 0x20000, 0x40000, 0x80000, 0x100000, 0x800000
39
+ # The modifier key that each shortcut choice (settings_store.GLOBAL_SHORTCUT_CHOICES other than
40
+ # "off") adds to Command-Tab.
41
+ EXTRA_MODIFIER_FLAG_BY_GLOBAL_SHORTCUT = {"shift_command_tab": SHIFT_FLAG, "command_fn_tab": FN_FLAG}
42
+ # CGEventTapCreate's location (before the window server routes the event), placement (ahead of
43
+ # other filters) and option (may hold events back, which is what needs the Accessibility permission).
44
+ HID_EVENT_TAP_LOCATION, HEAD_INSERT_PLACEMENT, ACTIVE_FILTER_OPTION = 0, 0, 0
45
+
46
+ EventTapCallback = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_void_p)
47
+ CORE_GRAPHICS.CGEventTapCreate.argtypes = [ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint64,
48
+ EventTapCallback, ctypes.c_void_p]
49
+ CORE_GRAPHICS.CGEventTapCreate.restype = ctypes.c_void_p
50
+ CORE_GRAPHICS.CGEventTapEnable.argtypes = [ctypes.c_void_p, ctypes.c_bool]
51
+ CORE_GRAPHICS.CGEventTapEnable.restype = None
52
+ CORE_GRAPHICS_KEEPING_THE_PYTHON_LOCK.CGEventGetFlags.argtypes = [ctypes.c_void_p]
53
+ CORE_GRAPHICS_KEEPING_THE_PYTHON_LOCK.CGEventGetFlags.restype = ctypes.c_uint64
54
+ CORE_GRAPHICS_KEEPING_THE_PYTHON_LOCK.CGEventGetIntegerValueField.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
55
+ CORE_GRAPHICS_KEEPING_THE_PYTHON_LOCK.CGEventGetIntegerValueField.restype = ctypes.c_int64
56
+ CORE_FOUNDATION.CFMachPortCreateRunLoopSource.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_long]
57
+ CORE_FOUNDATION.CFMachPortCreateRunLoopSource.restype = ctypes.c_void_p
58
+ CORE_FOUNDATION.CFRunLoopGetCurrent.argtypes = []
59
+ CORE_FOUNDATION.CFRunLoopGetCurrent.restype = ctypes.c_void_p
60
+ CORE_FOUNDATION.CFRunLoopAddSource.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
61
+ CORE_FOUNDATION.CFRunLoopAddSource.restype = None
62
+ CORE_FOUNDATION.CFRunLoopRun.argtypes = []
63
+ CORE_FOUNDATION.CFRunLoopRun.restype = None
64
+ RUN_LOOP_COMMON_MODES = ctypes.c_void_p.in_dll(CORE_FOUNDATION, "kCFRunLoopCommonModes")
65
+
66
+ # What the filter remembers between key events: whether the app switcher is open, and whether the
67
+ # next Tab key release belongs to a press that was held back (and so is held back too).
68
+ KeyFilterState = collections.namedtuple("KeyFilterState", ["app_switcher_is_open", "tab_release_is_held_back"])
69
+ START_KEY_FILTER_STATE = KeyFilterState(app_switcher_is_open=False, tab_release_is_held_back=False)
70
+
71
+
72
+ def decide_what_to_do_with_key_event(event_type, key_code, flags, is_key_repeat, global_shortcut, state):
73
+ """Returns (what_to_do, new_state) for one key event. what_to_do is "let_through", "hold_back",
74
+ or "hold_back_and_show_the_list" for a first press of the chosen shortcut while the app
75
+ switcher is closed. A held-back press is held back until its release, key repeats included.
76
+
77
+ The app switcher opens on Command-Tab, also with Shift or Fn held, and stays open until
78
+ Command is let go; meanwhile the shortcut is let through to it. Tab with Control or Option
79
+ held is always let through.
80
+ """
81
+ if event_type == MODIFIER_KEYS_CHANGED_EVENT:
82
+ if state.app_switcher_is_open and not flags & COMMAND_FLAG:
83
+ return "let_through", state._replace(app_switcher_is_open=False)
84
+ return "let_through", state
85
+ if key_code != TAB_KEY_CODE:
86
+ return "let_through", state
87
+ if event_type == KEY_UP_EVENT:
88
+ if state.tab_release_is_held_back:
89
+ return "hold_back", state._replace(tab_release_is_held_back=False)
90
+ return "let_through", state
91
+ if is_key_repeat and state.tab_release_is_held_back:
92
+ return "hold_back", state # a held-back press repeating, even after a modifier key was let go
93
+ if event_type != KEY_DOWN_EVENT or not flags & COMMAND_FLAG or flags & (CONTROL_FLAG | OPTION_FLAG):
94
+ return "let_through", state
95
+ shortcut_flag = EXTRA_MODIFIER_FLAG_BY_GLOBAL_SHORTCUT.get(global_shortcut)
96
+ if shortcut_flag is not None and flags & (SHIFT_FLAG | FN_FLAG) == shortcut_flag and not state.app_switcher_is_open:
97
+ return ("hold_back" if is_key_repeat else "hold_back_and_show_the_list"), state._replace(tab_release_is_held_back=True)
98
+ return "let_through", state._replace(app_switcher_is_open=True) # Command-Tab, with or without Shift or Fn
99
+
100
+
101
+ class GlobalShortcutKeyFilter:
102
+ """Holds back the chosen global shortcut from every app and calls shortcut_pressed() for
103
+ each first press, on the filter's own thread. Made at the first use_global_shortcut that
104
+ macOS allows, it then stays for the app's lifetime, turned on and off with the setting."""
105
+
106
+ def __init__(self, shortcut_pressed):
107
+ self.shortcut_pressed = shortcut_pressed
108
+ self.global_shortcut = "off"
109
+ # Written on the filter's thread; also reset by use_global_shortcut while the filter is off.
110
+ self.state = START_KEY_FILTER_STATE
111
+ self.tap = None
112
+ self.callback = EventTapCallback(self.filter_key_event) # kept here: ctypes frees a callback nothing holds
113
+
114
+ def use_global_shortcut(self, global_shortcut):
115
+ """Switches to a settings_store.GLOBAL_SHORTCUT_CHOICES choice ("off" turns the filter
116
+ off). Without the Accessibility permission macOS refuses the filter (lacks_permission());
117
+ calling again, once the permission may have been given, tries again."""
118
+ filter_was_off = self.global_shortcut == "off"
119
+ self.global_shortcut = global_shortcut
120
+ if global_shortcut == "off":
121
+ if self.tap is not None:
122
+ CORE_GRAPHICS.CGEventTapEnable(self.tap, False)
123
+ return
124
+ if self.tap is not None:
125
+ if filter_was_off:
126
+ # Key events missed while it was off (a Tab release, Command let go) may have left
127
+ # the state stale; while it is off, no key event changes the state meanwhile.
128
+ self.state = START_KEY_FILTER_STATE
129
+ CORE_GRAPHICS.CGEventTapEnable(self.tap, True)
130
+ return
131
+ self.tap = CORE_GRAPHICS.CGEventTapCreate(HID_EVENT_TAP_LOCATION, HEAD_INSERT_PLACEMENT, ACTIVE_FILTER_OPTION,
132
+ KEY_EVENT_MASK, self.callback, None) or None
133
+ if self.tap is not None:
134
+ threading.Thread(target=self.run_filter_thread, name="global-shortcut-key-filter", daemon=True).start()
135
+
136
+ def lacks_permission(self):
137
+ """Returns whether a shortcut is chosen but macOS refused the filter (no Accessibility permission)."""
138
+ return self.global_shortcut != "off" and self.tap is None
139
+
140
+ def run_filter_thread(self):
141
+ source = CORE_FOUNDATION.CFMachPortCreateRunLoopSource(None, self.tap, 0)
142
+ CORE_FOUNDATION.CFRunLoopAddSource(CORE_FOUNDATION.CFRunLoopGetCurrent(), source, RUN_LOOP_COMMON_MODES)
143
+ CORE_FOUNDATION.CFRunLoopRun()
144
+
145
+ def filter_key_event(self, proxy, event_type, event, user_data):
146
+ """Called by macOS for every key event on the Mac: returns the event to let it through,
147
+ or None to hold it back. An error lets the event through, since a filter that held back
148
+ everything would leave the Mac without a keyboard."""
149
+ try:
150
+ if event_type in FILTER_TURNED_OFF_EVENTS:
151
+ # Key events were missed while macOS had it off, so start over rather than hold
152
+ # back a later Tab release or send the shortcut to an app switcher already closed.
153
+ self.state = START_KEY_FILTER_STATE
154
+ if self.global_shortcut != "off":
155
+ CORE_GRAPHICS.CGEventTapEnable(self.tap, True)
156
+ return event
157
+ what_to_do, self.state = decide_what_to_do_with_key_event(
158
+ event_type, CORE_GRAPHICS_KEEPING_THE_PYTHON_LOCK.CGEventGetIntegerValueField(event, KEY_CODE_FIELD),
159
+ CORE_GRAPHICS_KEEPING_THE_PYTHON_LOCK.CGEventGetFlags(event),
160
+ bool(CORE_GRAPHICS_KEEPING_THE_PYTHON_LOCK.CGEventGetIntegerValueField(event, KEY_REPEAT_FIELD)),
161
+ self.global_shortcut, self.state)
162
+ if what_to_do == "hold_back_and_show_the_list":
163
+ self.shortcut_pressed()
164
+ return event if what_to_do == "let_through" else None
165
+ except Exception as error:
166
+ print(f"global shortcut key filter: {error!r}; letting the key through", flush=True)
167
+ return event
@@ -0,0 +1,116 @@
1
+ """The command that Claude Code's and Codex's hooks run: it reads the event from standard input,
2
+ keeps the few fields the app uses, adds the processes above it (whose nearest agent sent the
3
+ event), and sends one line to the app's socket.
4
+
5
+ The installer (hooks_installer) registers it as `<python> -I -S <this file> <agent tool name>`
6
+ (build_forwarder_command): it imports only the standard library, so Python starts without its
7
+ site packages (30 to 40 ms in all, measured on 2026-10-27), and it runs in the background (the hooks are registered as
8
+ async), so agents never wait for it. It never prints, since Claude Code can feed a hook's output into the conversation,
9
+ and it never fails: an event that can't be sent (the app isn't running) is dropped.
10
+ """
11
+
12
+ import ctypes
13
+ import json
14
+ import os
15
+ import socket
16
+ import sys
17
+ import time
18
+
19
+ HOOK_EVENTS_SOCKET_PATH = os.path.expanduser("~/Library/Application Support/agent-command-tab/hook_events.sock")
20
+ SECONDS_TO_REACH_THE_APP = 0.2
21
+ ANCESTOR_LEVELS_SENT = 6 # the shell the hook runs in, the agent, and the agent's own launcher and shell above it
22
+ LONGEST_TEXT_KEPT = 300 # characters of a text field (a reason, an ID)
23
+ MOST_BACKGROUND_TASKS_KEPT = 50
24
+ PROC_PIDT_SHORTBSDINFO = 13 # proc_pidinfo flavor of struct proc_bsdshortinfo, as in agent_process_tree
25
+
26
+
27
+ class ProcessShortBsdInfo(ctypes.Structure):
28
+ """struct proc_bsdshortinfo from <sys/proc_info.h>."""
29
+
30
+ _fields_ = [
31
+ ("pbsi_pid", ctypes.c_uint32), ("pbsi_ppid", ctypes.c_uint32), ("pbsi_pgid", ctypes.c_uint32),
32
+ ("pbsi_status", ctypes.c_uint32), ("pbsi_comm", ctypes.c_char * 16), ("pbsi_flags", ctypes.c_uint32),
33
+ ("pbsi_uid", ctypes.c_uint32), ("pbsi_gid", ctypes.c_uint32), ("pbsi_ruid", ctypes.c_uint32),
34
+ ("pbsi_rgid", ctypes.c_uint32), ("pbsi_svuid", ctypes.c_uint32), ("pbsi_svgid", ctypes.c_uint32),
35
+ ("pbsi_rfu", ctypes.c_uint32),
36
+ ]
37
+
38
+
39
+ def list_ancestor_processes(process_id, levels):
40
+ """Returns [process ID, executable name] of process_id and the processes above it, nearest
41
+ first, up to levels of them (fewer once one can't be read)."""
42
+ libproc = ctypes.CDLL("/usr/lib/libproc.dylib")
43
+ ancestors = []
44
+ while process_id > 1 and len(ancestors) < levels:
45
+ info = ProcessShortBsdInfo()
46
+ if libproc.proc_pidinfo(process_id, PROC_PIDT_SHORTBSDINFO, ctypes.c_uint64(0), ctypes.byref(info),
47
+ ctypes.sizeof(info)) != ctypes.sizeof(info):
48
+ break
49
+ ancestors.append([process_id, info.pbsi_comm.decode(errors="replace")])
50
+ process_id = info.pbsi_ppid
51
+ return ancestors
52
+
53
+
54
+ def shorten(value):
55
+ """Returns a string field cut to LONGEST_TEXT_KEPT characters, or None for anything else."""
56
+ return value[:LONGEST_TEXT_KEPT] if isinstance(value, str) else None
57
+
58
+
59
+ def find_background_task_launched(payload):
60
+ """Returns the ID of the background task a PostToolUse event's tool call started in Claude
61
+ Code (a Bash command run in the background returns a backgroundTaskId, a background agent
62
+ isAsync and its agentId), or None."""
63
+ tool_response = payload.get("tool_response")
64
+ if not isinstance(tool_response, dict):
65
+ return None
66
+ if tool_response.get("backgroundTaskId"):
67
+ return shorten(tool_response["backgroundTaskId"])
68
+ if tool_response.get("isAsync") and tool_response.get("agentId"):
69
+ return shorten(tool_response["agentId"])
70
+ return None
71
+
72
+
73
+ def reduce_hook_payload(payload, agent_tool_name, ancestors, now):
74
+ """Returns the event the app receives: the payload's fields it uses, and where it came from.
75
+
76
+ Args:
77
+ payload: The hook's input, as the agent tool sent it.
78
+ agent_tool_name: The name the installer passed ("Claude Code", "Codex").
79
+ ancestors: list_ancestor_processes's list, from the hook's own parent up.
80
+ now: When the hook started.
81
+ """
82
+ background_tasks = payload.get("background_tasks")
83
+ return {
84
+ "agent_tool_name": agent_tool_name,
85
+ "hook_event_name": shorten(payload.get("hook_event_name")),
86
+ "reason": shorten(payload.get("reason")),
87
+ "source": shorten(payload.get("source")),
88
+ "agent_id": shorten(payload.get("agent_id")),
89
+ "background_task_launched_id": find_background_task_launched(payload),
90
+ # Claude Code lists the session's background tasks (shells and agents) when a turn or an agent ends.
91
+ "background_tasks": [{"id": shorten(task.get("id")), "status": shorten(task.get("status"))}
92
+ for task in background_tasks[:MOST_BACKGROUND_TASKS_KEPT] if isinstance(task, dict)]
93
+ if isinstance(background_tasks, list) else None,
94
+ "ancestor_processes": ancestors,
95
+ "sent_at": now,
96
+ }
97
+
98
+
99
+ def main():
100
+ try:
101
+ now = time.time()
102
+ payload = json.loads(sys.stdin.read() or "{}")
103
+ if not isinstance(payload, dict):
104
+ return
105
+ event = reduce_hook_payload(payload, sys.argv[1] if len(sys.argv) > 1 else "",
106
+ list_ancestor_processes(os.getppid(), ANCESTOR_LEVELS_SENT), now)
107
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
108
+ connection.settimeout(SECONDS_TO_REACH_THE_APP)
109
+ connection.connect(HOOK_EVENTS_SOCKET_PATH)
110
+ connection.sendall(json.dumps(event).encode() + b"\n")
111
+ except BaseException: # never fail, never print: the agent goes on either way
112
+ pass
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
@@ -0,0 +1,129 @@
1
+ """What the app's hooks (hooks_installer, hook_event_forwarder) report about each agent process.
2
+ Pure functions.
3
+
4
+ An agent process whose hooks reported anything is known to report: when it is gone without a
5
+ normal session end, it crashed or was killed. Claude Code's events also list its
6
+ background shells and agents.
7
+ """
8
+
9
+ from agent_command_tab.agent_process_tree import NAMES_OF_AGENT_PROGRAMS, SHELL_AND_WRAPPER_PROCESS_NAMES
10
+
11
+ # A session end that leaves the process running: Claude Code's /clear ends one conversation and
12
+ # starts the next in the same process, and so does /resume (its "resume", one
13
+ # of the reasons Claude Code 2.1.311's program lists). A SessionStart after any session end also
14
+ # means the process goes on.
15
+ SESSION_END_REASONS_OF_A_PROCESS_THAT_GOES_ON = frozenset({"clear", "resume"})
16
+ # The SessionStart sources that follow those ends: the process goes on in another conversation
17
+ # ("compact" keeps the same one, "startup" is a new process).
18
+ SESSION_START_SOURCES_OF_ANOTHER_CONVERSATION_IN_THE_SAME_PROCESS = frozenset({"clear", "resume"})
19
+ # The tools whose hook events carry their list of background tasks and their prompts (hooks_installer
20
+ # registers UserPromptSubmit for them). Codex's carry neither, so its rows count the background
21
+ # shells below it and go by the status it sets itself.
22
+ AGENT_TOOL_NAMES_WHOSE_HOOKS_REPORT_TURNS_AND_BACKGROUND_TASKS = frozenset({"Claude Code"})
23
+ # A background task Claude Code lists counts while it runs (its list also holds finished ones until it reports them).
24
+ STATUSES_OF_A_RUNNING_BACKGROUND_TASK = frozenset({"running", "pending", None})
25
+ # The hook events of a tool call starting and finishing (hooks_installer registers both for Claude Code's
26
+ # Bash, Agent and Task); the main agent's, after a Stop, show its turn going on (code review, 2026-10-28).
27
+ TOOL_EVENT_NAMES = frozenset({"PreToolUse", "PostToolUse"})
28
+
29
+
30
+ def find_agent_process_id_of_hook_event(ancestor_processes):
31
+ """Returns the ID of the agent process whose hook sent an event: the nearest process above the
32
+ forwarder that isn't a shell (the agent runs its hooks in one), or, for Codex's program below
33
+ its node launcher, the launcher, which is the process its tab runs. None if there is none.
34
+
35
+ An agent started inside a tab's agent (a `claude -p` its shell tool runs) has its own process
36
+ ID, so its events never count as the tab agent's.
37
+
38
+ Args:
39
+ ancestor_processes: [[process ID, executable name]], from the forwarder's parent up.
40
+ """
41
+ for index, (process_id, name) in enumerate(ancestor_processes):
42
+ if name in SHELL_AND_WRAPPER_PROCESS_NAMES:
43
+ continue
44
+ if name in NAMES_OF_AGENT_PROGRAMS and index + 1 < len(ancestor_processes) and ancestor_processes[index + 1][1] == "node":
45
+ return ancestor_processes[index + 1][0]
46
+ return process_id
47
+ return None
48
+
49
+
50
+ def list_running_background_task_ids(background_tasks):
51
+ """Returns the IDs of the tasks in a Claude Code list that still run."""
52
+ return {task["id"] for task in background_tasks if task.get("id") and task.get("status") in STATUSES_OF_A_RUNNING_BACKGROUND_TASK}
53
+
54
+
55
+ def apply_hook_event(hook_state, event):
56
+ """Returns an agent process's hook state after one more event from it.
57
+
58
+ The state is {"agent_tool_name", "session_ended_at": when a normal session end arrived (and
59
+ no session started since), or None, "background_task_ids": the IDs of its background shells
60
+ and agents, or None while not known (no new start, no list since the app started; always for
61
+ Codex, whose events list none), "last_prompt_at" and "last_turn_end_at": when the last prompt
62
+ was submitted and the last turn ended, or None, "last_main_agent_tool_event_at": when the
63
+ main agent last started or finished a tool call the hooks report (PreToolUse, PostToolUse;
64
+ a subagent's carry its agent_id), or None}.
65
+
66
+ Args:
67
+ hook_state: The state before, or None for the process's first event.
68
+ event: An event from hook_event_forwarder.reduce_hook_payload.
69
+ """
70
+ hook_state = dict(hook_state or {"agent_tool_name": event.get("agent_tool_name"), "session_ended_at": None,
71
+ "background_task_ids": None, "last_prompt_at": None, "last_turn_end_at": None,
72
+ "last_main_agent_tool_event_at": None})
73
+ event_name = event.get("hook_event_name")
74
+ if event_name == "UserPromptSubmit":
75
+ hook_state["last_prompt_at"] = event.get("sent_at")
76
+ if event_name == "Stop":
77
+ hook_state["last_turn_end_at"] = event.get("sent_at")
78
+ if event_name in TOOL_EVENT_NAMES and not event.get("agent_id"):
79
+ hook_state["last_main_agent_tool_event_at"] = event.get("sent_at")
80
+ background_task_ids = set(hook_state["background_task_ids"]) if hook_state["background_task_ids"] is not None else None
81
+ if (event_name == "SessionStart" and event.get("source") == "startup"
82
+ and hook_state["agent_tool_name"] in AGENT_TOOL_NAMES_WHOSE_HOOKS_REPORT_TURNS_AND_BACKGROUND_TASKS):
83
+ background_task_ids = set() # a new process runs none yet (Codex's stays unknown: none of its events would list them)
84
+ if event_name == "SessionStart":
85
+ hook_state["session_ended_at"] = None # a new session in the same process
86
+ if event.get("background_tasks") is not None: # Claude Code's Stop and SubagentStop
87
+ background_task_ids = list_running_background_task_ids(event["background_tasks"])
88
+ if event.get("background_task_launched_id") and background_task_ids is not None: # (unknown stays unknown: others may run)
89
+ background_task_ids.add(event["background_task_launched_id"])
90
+ if event_name == "SubagentStop" and background_task_ids is not None:
91
+ background_task_ids.discard(event.get("agent_id")) # its own list still has it running
92
+ hook_state["background_task_ids"] = background_task_ids
93
+ if event_name == "SessionEnd" and event.get("reason") not in SESSION_END_REASONS_OF_A_PROCESS_THAT_GOES_ON:
94
+ hook_state["session_ended_at"] = event.get("sent_at")
95
+ return hook_state
96
+
97
+
98
+ def find_when_the_hooks_ended_the_turn(hook_state, iterm2_status_change_time):
99
+ """Returns when the agent's last turn ended (its Stop event), if that came after its last prompt
100
+ and after iTerm2's status value last changed, else None: the row then goes by the hooks rather
101
+ than an older "working". iTerm2's Claude Code integration keeps the status at working, with
102
+ "1 background task running" in its tab bar, while a background task runs after the turn ended,
103
+ and Claude Code's own report says "shell" then too (checked with Claude Code 2.1.311 on
104
+ 2026-10-27); a value set after the Stop, or a later prompt, counts again.
105
+
106
+ A Stop that another Stop hook blocks (Claude Code's goal feature) doesn't end the turn; when
107
+ iTerm2's value doesn't change as the turn goes on (it already said working), a tool call of
108
+ the main agent after it tells (a background shell fires no hook, and a background agent's
109
+ events carry its agent_id; code review, 2026-10-28), and so does Claude Code's own report
110
+ (DashboardCore.claude_code_reports_the_turn_going_on, which the core checks before going by
111
+ this). Only for the tools whose hooks report prompts
112
+ (AGENT_TOOL_NAMES_WHOSE_HOOKS_REPORT_TURNS_AND_BACKGROUND_TASKS): without them a turn that
113
+ follows right after (Codex running a message `codex queue` held) would look ended, and Codex
114
+ sets its own status accurately anyway.
115
+
116
+ Args:
117
+ hook_state: The agent process's apply_hook_event state, or None.
118
+ iterm2_status_change_time: When iTerm2's status value for the tab last changed.
119
+ """
120
+ if (hook_state is None or hook_state.get("last_turn_end_at") is None
121
+ or hook_state.get("agent_tool_name") not in AGENT_TOOL_NAMES_WHOSE_HOOKS_REPORT_TURNS_AND_BACKGROUND_TASKS):
122
+ return None
123
+ turn_ended_at = hook_state["last_turn_end_at"]
124
+ if (hook_state.get("last_prompt_at") is not None and hook_state["last_prompt_at"] >= turn_ended_at) \
125
+ or iterm2_status_change_time > turn_ended_at:
126
+ return None
127
+ if hook_state.get("last_main_agent_tool_event_at") is not None and hook_state["last_main_agent_tool_event_at"] > turn_ended_at:
128
+ return None
129
+ return turn_ended_at
@@ -0,0 +1,60 @@
1
+ """What each agent process's hooks reported (hook_event_tracking.apply_hook_event), kept in a file next to the settings.
2
+
3
+ So a turn end the hooks reported still counts after the dashboard restarts while iTerm2 says
4
+ working (find_when_the_hooks_ended_the_turn): a background task that runs after the turn keeps
5
+ iTerm2 at working and Claude Code's own report at "shell", so nothing else tells the turn is
6
+ over, and the row turned "stuck" (user report, 2026-10-28). Each state is stored with its
7
+ process's start time, so a later process that gets the same ID doesn't take it over. Pure
8
+ functions apart from the file reading and writing.
9
+ """
10
+
11
+ import json
12
+ import os
13
+
14
+ from agent_command_tab.hook_event_tracking import apply_hook_event
15
+ from agent_command_tab.settings_store import SETTINGS_FOLDER, write_json_file_atomically
16
+
17
+ HOOK_STATES_FILE_PATH = os.path.join(SETTINGS_FOLDER, "agent_hook_states.json")
18
+
19
+
20
+ def is_stored_hook_state(value):
21
+ """Whether value has a hook state's keys, each holding None, a number, a string or (the background task IDs) a list of strings."""
22
+ if not isinstance(value, dict) or not set(apply_hook_event(None, {})) <= set(value): # the keys a first event gives
23
+ return False
24
+ return all(item is None or (isinstance(item, (int, float, str)) and not isinstance(item, bool))
25
+ or (key == "background_task_ids" and isinstance(item, list) and all(isinstance(task_id, str) for task_id in item))
26
+ for key, item in value.items())
27
+
28
+
29
+ def load_hook_states(file_path):
30
+ """Returns {agent process ID: (its start time, its hook state)} from the file; {} when it is
31
+ missing or unreadable, and without records that don't have that shape."""
32
+ try:
33
+ with open(file_path) as file:
34
+ stored_records = json.load(file)
35
+ except (OSError, ValueError):
36
+ return {}
37
+ if not isinstance(stored_records, list):
38
+ return {}
39
+ started_at_and_hook_state_by_process_id = {}
40
+ for value in stored_records:
41
+ if not isinstance(value, dict) or not is_stored_hook_state(value.get("hook_state")):
42
+ continue
43
+ process_id, started_at = value.get("process_id"), value.get("started_at")
44
+ if (not isinstance(process_id, int) or isinstance(process_id, bool) or not isinstance(started_at, (int, float))
45
+ or isinstance(started_at, bool)):
46
+ continue
47
+ hook_state = dict(value["hook_state"])
48
+ if hook_state["background_task_ids"] is not None:
49
+ hook_state["background_task_ids"] = set(hook_state["background_task_ids"])
50
+ started_at_and_hook_state_by_process_id[process_id] = (started_at, hook_state)
51
+ return started_at_and_hook_state_by_process_id
52
+
53
+
54
+ def save_hook_states(file_path, started_at_and_hook_state_by_process_id):
55
+ """Writes the states as a list, each with its process ID and start time."""
56
+ write_json_file_atomically([
57
+ {"process_id": process_id, "started_at": started_at,
58
+ "hook_state": dict(hook_state, background_task_ids=sorted(hook_state["background_task_ids"])
59
+ if hook_state["background_task_ids"] is not None else None)}
60
+ for process_id, (started_at, hook_state) in sorted(started_at_and_hook_state_by_process_id.items())], file_path)