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,403 @@
1
+ """Builds the published snapshot from plain data gathered from iTerm2.
2
+
3
+ Everything here is pure: the connection thread gathers iTerm2's windows, tabs and session
4
+ variables into plain dicts (the same shape the test fixtures use), and this module turns them
5
+ into a ComputerSnapshot.
6
+
7
+ Shape of a gathered window (see DashboardCore.gather_iterm2_windows and DashboardCore.gather_iterm2_tab):
8
+ {"window_id": str, "frame": (x, y, width, height), "title": str, "title_override_format": str or None,
9
+ "tabs": [{"tab_id": str, "title": str, "title_override_format": str or None,
10
+ "first_session": {"session_id": str, "command_line": str, "job_pid": int or None,
11
+ "job_folder": str (the job process's current folder, or ""),
12
+ "job_started_at": float or None (when the job process started),
13
+ "status_set_in_iterm2": str or None,
14
+ "status_set_in_iterm2_at": float or None (when iTerm2 last reported
15
+ changing it, since the dashboard connected),
16
+ "status": str or None (the one the row goes by), "path": str}}]}
17
+ """
18
+
19
+ import collections
20
+ import os
21
+
22
+ from agent_command_tab.agent_adapters import find_agent_tool_adapter_for_tab
23
+ from agent_command_tab.monitor_assignment import assign_windows_to_monitors_by_largest_overlap
24
+ from agent_command_tab.session_preview_computation import choose_preview_text
25
+ from agent_command_tab.session_status_computation import (CLAUDE_AGENTS_STATUSES_TO_STATES,
26
+ compute_session_status_from_sources,
27
+ map_iterm2_status_value_to_state)
28
+ from agent_command_tab.snapshot_data_classes import (AgentSessionEntry, ComputerSnapshot, MonitorEntry,
29
+ WindowEntry)
30
+
31
+ PLACEHOLDER_MONITOR = {"monitor_id": "unknown", "name": "", "frame": (0, 0, 0, 0), "visible_frame": (0, 0, 0, 0)}
32
+ # A tool call open this long in the conversation file makes a working agent "running" (user
33
+ # request, 2026-10-28). The file is read every 5 seconds, so quick calls (reading or editing a
34
+ # file) would otherwise make the state flicker between thinking and running.
35
+ SECONDS_BEFORE_AN_OPEN_TOOL_CALL_SHOWS_AS_RUNNING = 5
36
+
37
+ DisplayedState = collections.namedtuple("DisplayedState", ["state", "since", "status_change_time"])
38
+ DisplayedState.__doc__ = ("What a session's row showed in a snapshot: its state, since when, and when iTerm2's status "
39
+ "value had last changed then (compute_displayed_state_since).")
40
+
41
+
42
+ def session_has_background_work(screen_reading):
43
+ """Returns whether processes an agent started keep running in the background, which makes an
44
+ idle session "background" (user request, 2026-10-28): a background task the lights count, or
45
+ a process row in the background (a background shell or a detached job). Helpers such as a
46
+ language server or caffeinate don't count."""
47
+ return (screen_reading.get("background_task_count", 0) > 0
48
+ or any(child_process.is_background_shell for child_process in screen_reading.get("child_processes", ())))
49
+
50
+
51
+ def choose_tool_the_agent_is_waiting_on(state, screen_reading, now):
52
+ """Returns (name, started at) of the tool a working agent waits on, or None: the command it
53
+ started, found from its processes at once ("running_command"), else the newest tool call of
54
+ any kind (a subagent, a web fetch, an MCP tool) that its conversation file has shown open for
55
+ SECONDS_BEFORE_AN_OPEN_TOOL_CALL_SHOWS_AS_RUNNING or more ("conversation_preview")."""
56
+ if state != "working":
57
+ return None
58
+ if screen_reading.get("running_command"):
59
+ return screen_reading["running_command"]
60
+ preview_fields = screen_reading.get("conversation_preview") or {}
61
+ open_tool_started_at = preview_fields.get("open_tool_started_at")
62
+ if open_tool_started_at is not None and now - open_tool_started_at >= SECONDS_BEFORE_AN_OPEN_TOOL_CALL_SHOWS_AS_RUNNING:
63
+ return preview_fields["open_tool_name"], open_tool_started_at
64
+ return None
65
+
66
+
67
+ def build_folder_display_name(folder_path):
68
+ """Returns the last part of a folder path ("~" for the home folder), or "" for no path."""
69
+ if not folder_path:
70
+ return ""
71
+ normalized_path = os.path.normpath(folder_path)
72
+ if normalized_path == os.path.expanduser("~"):
73
+ return "~"
74
+ return os.path.basename(normalized_path) or normalized_path
75
+
76
+
77
+ def find_status_set_in_iterm2_since_the_job_started(first_session):
78
+ """Returns the status value iTerm2 was seen to set after the tab's foreground job started, or None.
79
+
80
+ Only such a value tells that an unknown program in front reports a status (the generic
81
+ adapter). An older value is left over from the program before: Claude Code's last status can
82
+ stay after it exits, and a `gh` command run at that prompt was listed as an agent (user report,
83
+ 2026-10-28). A value iTerm2 already held when the dashboard connected has no time, so it
84
+ doesn't count either, and neither does the status iTerm2's tab bar shows.
85
+ """
86
+ status_set_at, job_started_at = first_session.get("status_set_in_iterm2_at"), first_session.get("job_started_at")
87
+ if status_set_at is None or job_started_at is None or status_set_at < job_started_at:
88
+ return None
89
+ return first_session.get("status_set_in_iterm2")
90
+
91
+
92
+ def resolve_agent_sessions(gathered_windows, previous_agent_sessions, specific_adapters, generic_adapter,
93
+ process_is_alive, process_is_stopped):
94
+ """Returns which tabs run an agent, keeping an agent whose tab's foreground job changed while it lives.
95
+
96
+ A `commandLine` change alone does not mean the agent exited (Claude Code's
97
+ Ctrl+G opens an editor in the same terminal, and Ctrl+Z suspends the agent). Such a tab keeps
98
+ its agent, marked as in the background, while the process recorded at detection still exists,
99
+ also when the program in front would count as an unknown agent tool (the generic adapter):
100
+ the agent's own hooks can set the status while Ctrl+G's editor is open.
101
+
102
+ Args:
103
+ gathered_windows: Gathered window dicts (module docstring).
104
+ previous_agent_sessions: The result of the previous call, or {}.
105
+ specific_adapters: Adapters tried in order.
106
+ generic_adapter: The generic adapter.
107
+ process_is_alive: function(process ID) -> bool.
108
+ process_is_stopped: function(process ID) -> bool (paused, or suspended with Ctrl+Z).
109
+
110
+ Returns:
111
+ {session_id: {"adapter": AgentToolAdapter, "process_id": int or None, "is_in_background": bool,
112
+ "is_stopped": bool, "agent_tool_name": str, "working_folder": the agent
113
+ process's current folder or "", "started_at": when the agent process started, or None}}.
114
+ """
115
+ agent_sessions = {}
116
+ for gathered_window in gathered_windows:
117
+ for gathered_tab in gathered_window["tabs"]:
118
+ first_session = gathered_tab.get("first_session")
119
+ if not first_session:
120
+ continue
121
+ session_id = first_session["session_id"]
122
+ adapter = find_agent_tool_adapter_for_tab(first_session.get("command_line"),
123
+ find_status_set_in_iterm2_since_the_job_started(first_session),
124
+ specific_adapters, generic_adapter)
125
+ previous_agent_session = previous_agent_sessions.get(session_id)
126
+ previous_agent_lives = (previous_agent_session is not None and previous_agent_session["process_id"]
127
+ and process_is_alive(previous_agent_session["process_id"]))
128
+ if (adapter is generic_adapter and previous_agent_lives
129
+ and previous_agent_session["process_id"] != first_session.get("job_pid")):
130
+ adapter = None # an unknown program in front of a live agent doesn't replace it, whatever status it has
131
+ if adapter is not None:
132
+ process_id = first_session.get("job_pid")
133
+ agent_sessions[session_id] = {
134
+ "adapter": adapter, "process_id": process_id, "is_in_background": False,
135
+ "is_stopped": bool(process_id) and process_is_stopped(process_id), # until iTerm2 sees the shell in front
136
+ "agent_tool_name": adapter.name_agent_tool_for_command_line(first_session.get("command_line")),
137
+ "working_folder": first_session.get("job_folder") or "",
138
+ "started_at": first_session.get("job_started_at")}
139
+ elif previous_agent_lives:
140
+ agent_sessions[session_id] = dict(previous_agent_session, is_in_background=True,
141
+ is_stopped=process_is_stopped(previous_agent_session["process_id"]))
142
+ return agent_sessions
143
+
144
+
145
+ def compute_context_fill_percent(context_tokens, context_window_tokens):
146
+ """Returns the share of the context window in use as a whole percent (in parentheses in the
147
+ Tokens column), or None while either number is unknown."""
148
+ if not context_tokens or not context_window_tokens:
149
+ return None
150
+ return round(100 * context_tokens / context_window_tokens)
151
+
152
+
153
+ def compute_displayed_state_since(state, raw_status_change_time, previous_displayed_state, now):
154
+ """Returns since when the shown state holds, for the elapsed time in the row.
155
+
156
+ Args:
157
+ state: The state shown now.
158
+ raw_status_change_time: When iTerm2's status value last changed.
159
+ previous_displayed_state: The DisplayedState from the previous snapshot, or None.
160
+ now: The current time.
161
+
162
+ Returns:
163
+ The previous time while the state is unchanged; the status change time when a status
164
+ report newer than the previous snapshot's caused the change; otherwise now (for example
165
+ "done" became "idle" when the tab was seen, also when the status had said idle since
166
+ before then).
167
+ """
168
+ if previous_displayed_state is None:
169
+ return raw_status_change_time
170
+ if previous_displayed_state.state == state:
171
+ return previous_displayed_state.since
172
+ if raw_status_change_time > previous_displayed_state.status_change_time:
173
+ return raw_status_change_time
174
+ return now
175
+
176
+
177
+ def build_agent_session_entry(gathered_tab, agent_session, claude_agent_record, session_tracking,
178
+ previous_displayed_state, screen_reading, stuck_threshold_seconds, seen_session_id,
179
+ highlighted_session_id, now):
180
+ """Returns the AgentSessionEntry for one agent tab.
181
+
182
+ Args:
183
+ gathered_tab: A gathered tab dict (module docstring).
184
+ agent_session: The tab's entry from resolve_agent_sessions.
185
+ claude_agent_record: The tab's entry from `claude agents --json` (matched by the agent's
186
+ process ID), or None.
187
+ session_tracking: {"status_change_time": float, "last_time_tab_was_seen": float or None,
188
+ "last_turn_ended_at": float (once a turn ended), "finished_turn_cleared_at": float
189
+ (after a /clear from the list)} for the tab's first session, or None.
190
+ previous_displayed_state: The DisplayedState shown for this session in the previous
191
+ snapshot, or None.
192
+ screen_reading: The core's latest screen reading for the session, or None (see
193
+ session_status_computation.compute_session_status_from_sources).
194
+ stuck_threshold_seconds: The stuck time limit (iterm2_connection_thread.STUCK_THRESHOLD_SECONDS).
195
+ seen_session_id: The session being seen right now (selected in the key iTerm2 window
196
+ while iTerm2 is active), or None.
197
+ highlighted_session_id: The session shown as in front, or None.
198
+ now: The current time.
199
+ """
200
+ first_session = gathered_tab["first_session"]
201
+ session_id = first_session["session_id"]
202
+ session_tracking = session_tracking or {}
203
+ claude_agent_record = claude_agent_record or {}
204
+ # The agent process's folder first; iTerm2's `path` can be empty or stale.
205
+ working_folder = claude_agent_record.get("cwd") or agent_session["working_folder"] or first_session.get("path") or ""
206
+ agent_session_name = claude_agent_record.get("name") or ""
207
+ tab_title_set_by_user = bool(gathered_tab.get("title_override_format"))
208
+ if tab_title_set_by_user:
209
+ tab_title = gathered_tab.get("title") or gathered_tab["title_override_format"]
210
+ else:
211
+ tab_title = agent_session_name or build_folder_display_name(working_folder) or gathered_tab.get("title") or ""
212
+ is_paused_with_the_processes_below_it = agent_session.get("is_paused_with_the_processes_below_it", False)
213
+ if agent_session["is_stopped"]:
214
+ # Paused from the list, or suspended with Ctrl+Z by hand, which leaves the processes the
215
+ # agent started in their own process groups running: stopped until it is resumed.
216
+ state = "paused"
217
+ reason = ("paused: the agent and the processes below it are stopped until it is resumed"
218
+ if is_paused_with_the_processes_below_it
219
+ else "suspended with Ctrl+Z: the agent is stopped, but commands it started may still run")
220
+ status_since = (previous_displayed_state.since if previous_displayed_state and previous_displayed_state.state == "paused"
221
+ else now)
222
+ elif agent_session["is_in_background"]:
223
+ # Another program (an editor opened with Ctrl+G) is in front, or a resumed agent is coming
224
+ # back to the front; iTerm2 cleared the status, so the row keeps what it showed before,
225
+ # except "paused", which ended when the agent was resumed.
226
+ state, status_since = (
227
+ (previous_displayed_state.state, previous_displayed_state.since)
228
+ if previous_displayed_state and previous_displayed_state.state != "paused" else ("unknown", now))
229
+ reason = "another program in front of the agent"
230
+ elif (map_iterm2_status_value_to_state(first_session.get("status")) is None
231
+ and claude_agent_record.get("status") in CLAUDE_AGENTS_STATUSES_TO_STATES):
232
+ # iTerm2 has no status for the tab, neither its variable nor its tab bar's (the core reads
233
+ # that when the variable is empty): Claude Code's own report, up to a minute old. It can't
234
+ # tell "done" from "idle", and the screen checks behind "stuck" and an answered "asking" don't run.
235
+ state = CLAUDE_AGENTS_STATUSES_TO_STATES[claude_agent_record["status"]]
236
+ reason = "from claude agents --json: iTerm2 reports no status for this tab"
237
+ status_since = compute_displayed_state_since(state, now, previous_displayed_state, now)
238
+ else:
239
+ # A finished turn stops waiting to be seen when the tab is seen, or when /clear cleared it.
240
+ times_the_finished_turn_was_dealt_with = [time_ for time_ in (session_tracking.get("last_time_tab_was_seen"),
241
+ session_tracking.get("finished_turn_cleared_at"))
242
+ if time_ is not None]
243
+ state, reason = compute_session_status_from_sources(
244
+ first_session.get("status"),
245
+ session_tracking.get("status_change_time", now),
246
+ session_tracking.get("last_turn_ended_at"),
247
+ max(times_the_finished_turn_was_dealt_with, default=None),
248
+ session_id == seen_session_id,
249
+ screen_reading,
250
+ stuck_threshold_seconds,
251
+ now,
252
+ )
253
+ status_since = compute_displayed_state_since(state, session_tracking.get("status_change_time", now),
254
+ previous_displayed_state, now)
255
+ if state == "idle" and session_has_background_work(screen_reading or {}):
256
+ state, reason = "background", "at its prompt, with background processes running"
257
+ status_since = compute_displayed_state_since(state, session_tracking.get("status_change_time", now),
258
+ previous_displayed_state, now)
259
+ running_tool = choose_tool_the_agent_is_waiting_on(state, screen_reading or {}, now)
260
+ return AgentSessionEntry(
261
+ tab_id=gathered_tab["tab_id"],
262
+ session_id=session_id,
263
+ tab_title=tab_title,
264
+ tab_title_set_by_user=tab_title_set_by_user,
265
+ agent_session_name=agent_session_name,
266
+ agent_tool_name=agent_session["agent_tool_name"],
267
+ working_folder=working_folder,
268
+ status=state,
269
+ status_reason=reason,
270
+ status_since=status_since,
271
+ is_paused_with_the_processes_below_it=state == "paused" and is_paused_with_the_processes_below_it,
272
+ is_in_front=session_id == highlighted_session_id,
273
+ last_time_tab_was_seen=session_tracking.get("last_time_tab_was_seen"),
274
+ running_tool_name=running_tool[0] if running_tool else "",
275
+ running_tool_started_at=running_tool[1] if running_tool else None,
276
+ preview_line=choose_preview_text(state, (screen_reading or {}).get("conversation_preview")),
277
+ context_tokens=(screen_reading or {}).get("context_tokens"),
278
+ context_fill_percent=compute_context_fill_percent((screen_reading or {}).get("context_tokens"),
279
+ (screen_reading or {}).get("context_window_tokens")),
280
+ memory_bytes=(screen_reading or {}).get("memory_bytes"),
281
+ cpu_percent=(screen_reading or {}).get("cpu_percent"),
282
+ started_at=agent_session.get("started_at"),
283
+ slash_commands=agent_session["adapter"].slash_commands,
284
+ background_task_count=(screen_reading or {}).get("background_task_count", 0),
285
+ child_processes=(screen_reading or {}).get("child_processes", ()),
286
+ )
287
+
288
+
289
+ def build_exited_agent_session_entry(last_agent_session_entry, ended_at, highlighted_session_id, gathered_tab):
290
+ """Returns the row of an agent that ended without a normal session end (a crash, or
291
+ killed), kept for EXITED_ROW_SECONDS: what its row last showed (name, tool, folder, preview),
292
+ gray and "exited" since it ended, without the readings of a running agent. A title the user
293
+ gives the tab meanwhile (Rename stays in its menu) is its name.
294
+
295
+ Args:
296
+ last_agent_session_entry: The AgentSessionEntry from the last snapshot before it ended.
297
+ ended_at: When the dashboard noticed its process was gone.
298
+ highlighted_session_id: See build_agent_session_entry.
299
+ gathered_tab: The tab's gathered dict now (module docstring).
300
+ """
301
+ if gathered_tab.get("title_override_format"):
302
+ last_agent_session_entry = last_agent_session_entry._replace(
303
+ tab_title=gathered_tab.get("title") or gathered_tab["title_override_format"], tab_title_set_by_user=True)
304
+ return last_agent_session_entry._replace(
305
+ status="exited", status_reason="the agent ended without a normal session end (a crash, or killed)",
306
+ status_since=ended_at, ended_abnormally_at=ended_at,
307
+ is_in_front=last_agent_session_entry.session_id == highlighted_session_id, running_tool_name="",
308
+ running_tool_started_at=None, context_tokens=None, context_fill_percent=None, memory_bytes=None,
309
+ cpu_percent=None, slash_commands=(), is_paused_with_the_processes_below_it=False, background_task_count=0,
310
+ child_processes=())
311
+
312
+
313
+ def build_window_entry(gathered_window, agent_session_entries):
314
+ """Returns the WindowEntry for a window that has at least one agent session.
315
+
316
+ A window without a title of its own is named after its first agent session's folder.
317
+ """
318
+ window_title_set_by_user = bool(gathered_window.get("title_override_format"))
319
+ if window_title_set_by_user:
320
+ title = gathered_window.get("title") or gathered_window["title_override_format"]
321
+ else:
322
+ title = build_folder_display_name(agent_session_entries[0].working_folder) or gathered_window.get("title") or ""
323
+ return WindowEntry(
324
+ window_id=gathered_window["window_id"],
325
+ title=title,
326
+ window_title_set_by_user=window_title_set_by_user,
327
+ frame=tuple(gathered_window.get("frame") or (0, 0, 0, 0)),
328
+ total_tab_count=len(gathered_window["tabs"]),
329
+ agent_sessions=tuple(agent_session_entries),
330
+ selected_tab_id=gathered_window.get("selected_tab_id"),
331
+ )
332
+
333
+
334
+ def build_computer_snapshot(gathered_windows, agent_sessions, monitors, window_order, session_tracking_by_session_id,
335
+ displayed_state_by_session_id, screen_readings_by_session_id, stuck_threshold_seconds,
336
+ claude_agents_by_process_id, seen_session_id, highlighted_session_id, computer_id,
337
+ computer_name, now, exited_agent_sessions_by_session_id=None, hooks_status_per_agent_tool=()):
338
+ """Returns the ComputerSnapshot for the gathered iTerm2 state.
339
+
340
+ Args:
341
+ gathered_windows: Gathered window dicts in iTerm2's order (module docstring).
342
+ agent_sessions: The tabs that run an agent, from resolve_agent_sessions.
343
+ monitors: Monitor dicts {"monitor_id", "name", "frame", "visible_frame"} from the main
344
+ thread, in NSScreen's order (menu-bar monitor first); empty before the first screen
345
+ layout message. The snapshot lists the monitor groups left to right.
346
+ window_order: Window IDs in the list's order (window_list_ordering).
347
+ session_tracking_by_session_id: Per-session tracking dicts (see build_agent_session_entry).
348
+ displayed_state_by_session_id: {session_id: DisplayedState} from the previous snapshot.
349
+ screen_readings_by_session_id: The core's latest screen readings (see build_agent_session_entry).
350
+ stuck_threshold_seconds: See build_agent_session_entry.
351
+ claude_agents_by_process_id: {process ID: record from `claude agents --json`}.
352
+ seen_session_id: See build_agent_session_entry.
353
+ highlighted_session_id: See build_agent_session_entry.
354
+ computer_id: A stable ID for this computer.
355
+ computer_name: The computer's name.
356
+ now: The current time.
357
+ exited_agent_sessions_by_session_id: {session ID: (the AgentSessionEntry its row last
358
+ showed, when its agent ended)} for the tabs whose agent ended without a normal
359
+ session end, still shown as "exited" (build_exited_agent_session_entry).
360
+ hooks_status_per_agent_tool: ComputerSnapshot.hooks_status_per_agent_tool.
361
+
362
+ Returns:
363
+ A ComputerSnapshot. Windows without agent sessions are left out.
364
+ """
365
+ exited_agent_sessions_by_session_id = exited_agent_sessions_by_session_id or {}
366
+ window_entries_by_window_id = {}
367
+ for gathered_window in gathered_windows:
368
+ agent_session_entries = []
369
+ for gathered_tab in gathered_window["tabs"]:
370
+ first_session = gathered_tab.get("first_session")
371
+ agent_session = agent_sessions.get(first_session["session_id"]) if first_session else None
372
+ if agent_session is None:
373
+ if first_session and first_session["session_id"] in exited_agent_sessions_by_session_id:
374
+ agent_session_entries.append(build_exited_agent_session_entry(
375
+ *exited_agent_sessions_by_session_id[first_session["session_id"]], highlighted_session_id, gathered_tab))
376
+ continue
377
+ agent_session_entries.append(build_agent_session_entry(
378
+ gathered_tab, agent_session, claude_agents_by_process_id.get(agent_session["process_id"]),
379
+ session_tracking_by_session_id.get(first_session["session_id"]),
380
+ displayed_state_by_session_id.get(first_session["session_id"]),
381
+ screen_readings_by_session_id.get(first_session["session_id"]), stuck_threshold_seconds,
382
+ seen_session_id, highlighted_session_id, now))
383
+ if agent_session_entries:
384
+ window_entries_by_window_id[gathered_window["window_id"]] = build_window_entry(gathered_window, agent_session_entries)
385
+
386
+ monitors = sorted(monitors, key=lambda monitor: (monitor["frame"][0], monitor["frame"][1])) or [PLACEHOLDER_MONITOR]
387
+ monitor_index_by_window_id = assign_windows_to_monitors_by_largest_overlap(
388
+ {window_id: window_entry.frame for window_id, window_entry in window_entries_by_window_id.items()},
389
+ [monitor["frame"] for monitor in monitors])
390
+ ordered_window_ids = [window_id for window_id in window_order if window_id in window_entries_by_window_id]
391
+ ordered_window_ids += [window_id for window_id in window_entries_by_window_id if window_id not in set(window_order)]
392
+ monitor_entries = []
393
+ for monitor_index, monitor in enumerate(monitors):
394
+ monitor_entries.append(MonitorEntry(
395
+ monitor_id=monitor["monitor_id"],
396
+ name=monitor["name"],
397
+ frame=tuple(monitor["frame"]),
398
+ visible_frame=tuple(monitor["visible_frame"]),
399
+ windows=tuple(window_entries_by_window_id[window_id] for window_id in ordered_window_ids
400
+ if monitor_index_by_window_id.get(window_id, 0) == monitor_index),
401
+ ))
402
+ return ComputerSnapshot(computer_id=computer_id, computer_name=computer_name, taken_at=now,
403
+ monitors=tuple(monitor_entries), hooks_status_per_agent_tool=tuple(hooks_status_per_agent_tool))
@@ -0,0 +1,117 @@
1
+ """The list's sort orders, chosen with the Sort pop-up at the top of the list (user request, 2026-10-19)
2
+ or by clicking a column's title, which also reverses them (user requests, 2026-10-26).
3
+
4
+ Sorting changes only the order the list shows. iTerm2's tab order and the window order set by
5
+ dragging rows stay as they are, so "manual" shows them again unchanged. Python's sort keeps
6
+ equal rows in their manual order.
7
+
8
+ Each rank function returns an agent session's sort key in its order's first direction (the Sort
9
+ pop-up's, and a column title's first click), or None while the value isn't known: those agent
10
+ sessions go last in either direction.
11
+ """
12
+
13
+ from agent_command_tab.session_status_computation import STATES_IN_URGENCY_ORDER
14
+
15
+
16
+ def find_when_the_shown_state_started(agent_session_entry):
17
+ """Returns when the state an agent session's row shows started, which its time counts from:
18
+ while it waits on a tool ("running"), when the tool started; otherwise its last state change."""
19
+ if agent_session_entry.running_tool_name:
20
+ return agent_session_entry.running_tool_started_at
21
+ return agent_session_entry.status_since
22
+
23
+
24
+ def rank_agent_session_by_activity(agent_session_entry):
25
+ """Sort key: the most urgent state first (asking, error, stuck, working, done, idle), then the
26
+ most recent state change, as the row shows it (find_when_the_shown_state_started)."""
27
+ state = agent_session_entry.status
28
+ if state not in STATES_IN_URGENCY_ORDER:
29
+ return None
30
+ return STATES_IN_URGENCY_ORDER.index(state), -find_when_the_shown_state_started(agent_session_entry)
31
+
32
+
33
+ def rank_agent_session_by_created_time(agent_session_entry):
34
+ """Sort key: the agent session that started last first."""
35
+ started_at = agent_session_entry.started_at
36
+ return None if started_at is None else -started_at
37
+
38
+
39
+ def rank_agent_session_by_title(agent_session_entry):
40
+ """Sort key: the tab's title, ignoring case."""
41
+ return agent_session_entry.tab_title.casefold()
42
+
43
+
44
+ def rank_agent_session_by_memory_usage(agent_session_entry):
45
+ """Sort key: the agent session using the most memory first (with the processes below it; user
46
+ request, 2026-10-21)."""
47
+ memory_bytes = agent_session_entry.memory_bytes
48
+ return None if memory_bytes is None else -memory_bytes
49
+
50
+
51
+ def rank_agent_session_by_cpu_usage(agent_session_entry):
52
+ """Sort key: the agent session using the most CPU first (with the processes below it; user
53
+ request, 2026-10-21)."""
54
+ cpu_percent = agent_session_entry.cpu_percent
55
+ return None if cpu_percent is None else -cpu_percent
56
+
57
+
58
+ def rank_agent_session_by_context_percent(agent_session_entry):
59
+ """Sort key: the agent session whose context fills the most of its window first, rather than
60
+ the largest context, since windows differ in size (the Tokens column; user request, 2026-10-26)."""
61
+ context_fill_percent = agent_session_entry.context_fill_percent
62
+ return None if context_fill_percent is None else -context_fill_percent
63
+
64
+
65
+ def rank_agent_session_by_last_state_change(agent_session_entry):
66
+ """Sort key: the agent session whose state changed last first (user request, 2026-10-26), by
67
+ the time its row shows (find_when_the_shown_state_started)."""
68
+ return -find_when_the_shown_state_started(agent_session_entry)
69
+
70
+
71
+ # How each sort order but "manual" (iTerm2's tab order, and the window order set by dragging)
72
+ # ranks agent sessions; settings_store takes its choices from here.
73
+ AGENT_SESSION_RANK_BY_LIST_SORT_ORDER = {
74
+ "activity": rank_agent_session_by_activity,
75
+ "alphabet": rank_agent_session_by_title,
76
+ "context_percent": rank_agent_session_by_context_percent,
77
+ "created_time": rank_agent_session_by_created_time,
78
+ "memory_usage": rank_agent_session_by_memory_usage,
79
+ "cpu_usage": rank_agent_session_by_cpu_usage,
80
+ "state_duration": rank_agent_session_by_last_state_change,
81
+ }
82
+ LIST_SORT_ORDERS = ["manual"] + list(AGENT_SESSION_RANK_BY_LIST_SORT_ORDER)
83
+
84
+
85
+ def sort_by_rank(entries, rank_entry, is_reversed):
86
+ """Returns the entries by rank_entry's key, in the other direction when is_reversed, those it
87
+ ranks None (not known) last either way; entries with equal keys keep their order."""
88
+ keys_and_entries = [(rank_entry(entry), entry) for entry in entries]
89
+ ranked_keys_and_entries = sorted(((key, entry) for key, entry in keys_and_entries if key is not None),
90
+ key=lambda key_and_entry: key_and_entry[0], reverse=is_reversed)
91
+ return [entry for _, entry in ranked_keys_and_entries] + [entry for key, entry in keys_and_entries if key is None]
92
+
93
+
94
+ def sort_agent_session_entries(agent_session_entries, list_sort_order, is_reversed=False):
95
+ """Returns one window's agent sessions in the list's order (one of LIST_SORT_ORDERS), reversed when is_reversed."""
96
+ if list_sort_order == "manual":
97
+ return list(agent_session_entries)
98
+ return sort_by_rank(agent_session_entries, AGENT_SESSION_RANK_BY_LIST_SORT_ORDER[list_sort_order], is_reversed)
99
+
100
+
101
+ def sort_window_entries(window_entries, list_sort_order, list_ranked_agent_sessions=lambda window_entry: window_entry.agent_sessions,
102
+ is_reversed=False):
103
+ """Returns one monitor's windows in the list's order (one of LIST_SORT_ORDERS), reversed when
104
+ is_reversed: alphabetically by their own titles, otherwise by each window's first agent
105
+ session in that order, among those list_ranked_agent_sessions(window_entry) returns (all of
106
+ them, or the ones whose rows Hide Idle doesn't hide, so a hidden tab doesn't decide where its
107
+ window goes). A window without one, or whose first one's value isn't known, goes last."""
108
+ if list_sort_order == "manual":
109
+ return list(window_entries)
110
+ if list_sort_order == "alphabet":
111
+ return sort_by_rank(window_entries, lambda window_entry: window_entry.title.casefold(), is_reversed)
112
+ rank_agent_session = AGENT_SESSION_RANK_BY_LIST_SORT_ORDER[list_sort_order]
113
+
114
+ def rank_window_by_its_first_agent_session(window_entry):
115
+ first_agent_sessions = sort_agent_session_entries(list_ranked_agent_sessions(window_entry), list_sort_order, is_reversed)[:1]
116
+ return rank_agent_session(first_agent_sessions[0]) if first_agent_sessions else None
117
+ return sort_by_rank(window_entries, rank_window_by_its_first_agent_session, is_reversed)
@@ -0,0 +1,78 @@
1
+ """The message "Talk to Each Other" sends each selected agent session (user request, 2026-10-21).
2
+
3
+ Every session gets the user's note, then its own name, then, for each of the other sessions,
4
+ what it needs to send that session a message: a Claude Code session's name, which Claude Code's
5
+ SendMessage tool takes as the address; or a Codex session's conversation ID, for
6
+ `codex queue --thread <ID>`, which any agent with a shell can run. Claude Code has no supported
7
+ way in from outside a Claude Code session, so a Codex session can't message a Claude Code
8
+ session; its copy says so.
9
+ """
10
+
11
+ import collections
12
+ import shlex
13
+
14
+ from agent_command_tab.agent_adapters.base import MESSAGES_THROUGH_CODEX_QUEUE, MESSAGES_THROUGH_THE_SEND_MESSAGE_TOOL
15
+
16
+ # A Claude Code session's message is held until it waits at its prompt, for up to this long.
17
+ SECONDS_A_MESSAGE_WAITS_FOR_AN_AGENT_AT_ITS_PROMPT = 30 * 60
18
+ DEFAULT_NOTE_ASKING_AGENT_SESSIONS_TO_TALK_TO_EACH_OTHER = (
19
+ "You and these other agents might be working on similar things right now. Please message them with a summary "
20
+ "of what you're doing and figure out how you can all work together effectively.")
21
+
22
+ AgentSessionForMessages = collections.namedtuple(
23
+ "AgentSessionForMessages",
24
+ ["agent_tool_name", "how_other_agent_sessions_send_it_messages", "address", "process_id", "working_folder", "tab_title"])
25
+ AgentSessionForMessages.__doc__ = (
26
+ "What the messages say about one agent session: its tool (\"Codex\"), how other sessions send it messages "
27
+ "(agent_adapters.base: MESSAGES_THROUGH_THE_SEND_MESSAGE_TOOL or MESSAGES_THROUGH_CODEX_QUEUE), its address "
28
+ "for that (a Claude Code session's name, a Codex session's conversation ID), its agent's process ID, its "
29
+ "working folder and its iTerm2 tab's title.")
30
+
31
+
32
+ def describe_agent_session_for_messages(agent_session):
33
+ """Returns how the messages name a session, with its process ID, folder and tab, for example
34
+ 'the Claude Code session "analysis-1d" (process ID 4242, folder /x, iTerm2 tab "analysis")'."""
35
+ name = (f'"{agent_session.address}"' if agent_session.how_other_agent_sessions_send_it_messages == MESSAGES_THROUGH_THE_SEND_MESSAGE_TOOL
36
+ else agent_session.address)
37
+ return (f"the {agent_session.agent_tool_name} session {name} (process ID {agent_session.process_id}, "
38
+ f'folder {agent_session.working_folder or "unknown"}, iTerm2 tab "{agent_session.tab_title}")')
39
+
40
+
41
+ def explain_how_to_send_a_message(sender, recipient, recipient_gets_the_message_too):
42
+ """Returns the sentence telling the sender how to send the recipient a message, or why it can't.
43
+
44
+ Args:
45
+ sender: The AgentSessionForMessages that gets this explanation.
46
+ recipient: The AgentSessionForMessages it would send a message to.
47
+ recipient_gets_the_message_too: Whether the recipient gets a Talk to Each Other message
48
+ too, so it learns how to message the sender (only the one chosen in the Talk to Each
49
+ Other window may get it; code review, 2026-10-28).
50
+ """
51
+ if recipient.how_other_agent_sessions_send_it_messages == MESSAGES_THROUGH_CODEX_QUEUE:
52
+ # The message attached to its option, so one starting with "-" isn't read as an option.
53
+ return (f"To message it, run: codex queue --thread {shlex.quote(recipient.address)} "
54
+ f'--message="<your message>"')
55
+ if sender.how_other_agent_sessions_send_it_messages == MESSAGES_THROUGH_THE_SEND_MESSAGE_TOOL:
56
+ return f'To message it, use your SendMessage tool with to: "{recipient.address}".'
57
+ if recipient_gets_the_message_too:
58
+ return ("A Codex session has no way to send a Claude Code session a message, so it can't hear from you directly, "
59
+ "but it can message you.")
60
+ return ("A Codex session has no way to send a Claude Code session a message, so it can't hear from you, "
61
+ "and it wasn't told how to message you.")
62
+
63
+
64
+ def build_message_asking_agent_session_to_talk_to_the_others(note, recipient, other_agent_sessions, agent_sessions_that_get_the_message):
65
+ """Returns the message one agent session gets from "Talk to Each Other".
66
+
67
+ Args:
68
+ note: The user's note, from the Talk to Each Other window.
69
+ recipient: The AgentSessionForMessages that gets this message.
70
+ other_agent_sessions: The AgentSessionForMessages of the other sessions, in list order.
71
+ agent_sessions_that_get_the_message: The AgentSessionForMessages of every session that
72
+ gets a Talk to Each Other message this time.
73
+ """
74
+ lines = [note.strip(), "", f"You are {describe_agent_session_for_messages(recipient)}.", "", "The other sessions:"]
75
+ lines += [f"- {describe_agent_session_for_messages(other)}. "
76
+ f"{explain_how_to_send_a_message(recipient, other, other in agent_sessions_that_get_the_message)}"
77
+ for other in other_agent_sessions]
78
+ return "\n".join(lines)