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.
- agent_command_tab/__init__.py +4 -0
- agent_command_tab/agent_adapters/__init__.py +48 -0
- agent_command_tab/agent_adapters/base.py +162 -0
- agent_command_tab/agent_adapters/claude_code.py +120 -0
- agent_command_tab/agent_adapters/codex.py +102 -0
- agent_command_tab/agent_adapters/generic.py +22 -0
- agent_command_tab/agent_process_tree.py +557 -0
- agent_command_tab/agent_session_pausing.py +254 -0
- agent_command_tab/app_controller.py +947 -0
- agent_command_tab/claude_code_transcript_records.py +75 -0
- agent_command_tab/command_line.py +187 -0
- agent_command_tab/context_window_usage.py +230 -0
- agent_command_tab/dashboard_core_api.py +57 -0
- agent_command_tab/docked_window_frames_store.py +60 -0
- agent_command_tab/global_shortcut_key_filter.py +167 -0
- agent_command_tab/hook_event_forwarder.py +116 -0
- agent_command_tab/hook_event_tracking.py +129 -0
- agent_command_tab/hook_states_store.py +60 -0
- agent_command_tab/hooks_installer.py +300 -0
- agent_command_tab/installed_copy_paths.py +41 -0
- agent_command_tab/iterm2_actions.py +325 -0
- agent_command_tab/iterm2_connection_thread.py +2299 -0
- agent_command_tab/iterm2_snapshot_builder.py +403 -0
- agent_command_tab/list_sorting.py +117 -0
- agent_command_tab/messages_between_agent_sessions.py +78 -0
- agent_command_tab/monitor_assignment.py +109 -0
- agent_command_tab/pause_records_store.py +61 -0
- agent_command_tab/screen_readings.py +108 -0
- agent_command_tab/session_preview_computation.py +228 -0
- agent_command_tab/session_status_computation.py +235 -0
- agent_command_tab/settings_store.py +292 -0
- agent_command_tab/snapshot_data_classes.py +145 -0
- agent_command_tab/start_with_iterm2.py +138 -0
- agent_command_tab/tab_order_computation.py +26 -0
- agent_command_tab/user_interface/__init__.py +1 -0
- agent_command_tab/user_interface/agent_session_outline_view.py +2120 -0
- agent_command_tab/user_interface/agent_tool_icons.py +124 -0
- agent_command_tab/user_interface/app_icon.py +75 -0
- agent_command_tab/user_interface/control_helpers.py +38 -0
- agent_command_tab/user_interface/list_window.py +116 -0
- agent_command_tab/user_interface/menu_bar_status_item.py +193 -0
- agent_command_tab/user_interface/named_colors.py +58 -0
- agent_command_tab/user_interface/pointing_hand_button.py +42 -0
- agent_command_tab/user_interface/popover_container.py +461 -0
- agent_command_tab/user_interface/row_text_rendering.py +342 -0
- agent_command_tab/user_interface/screen_layout.py +91 -0
- agent_command_tab/user_interface/settings_window.py +530 -0
- agent_command_tab/user_interface/sidebar_panel.py +486 -0
- agent_command_tab/user_interface/sidebar_placement.py +105 -0
- agent_command_tab/user_interface/talk_to_each_other_alert.py +130 -0
- agent_command_tab/window_list_ordering.py +44 -0
- agent_command_tab-0.1.0.dist-info/METADATA +85 -0
- agent_command_tab-0.1.0.dist-info/RECORD +57 -0
- agent_command_tab-0.1.0.dist-info/WHEEL +5 -0
- agent_command_tab-0.1.0.dist-info/entry_points.txt +2 -0
- agent_command_tab-0.1.0.dist-info/licenses/LICENSE +21 -0
- agent_command_tab-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,2299 @@
|
|
|
1
|
+
"""The core's background thread: the iTerm2 connection, its subscriptions, and snapshot publishing.
|
|
2
|
+
|
|
3
|
+
Everything here runs on one asyncio event loop in a background thread; the
|
|
4
|
+
AppKit main thread only receives snapshots (through publish_snapshot) and sends messages and
|
|
5
|
+
action requests (through the thread-safe methods of Iterm2ConnectionThread).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import glob
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import signal
|
|
13
|
+
import socket
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
import iterm2
|
|
18
|
+
import iterm2.auth
|
|
19
|
+
import iterm2.rpc
|
|
20
|
+
from iterm2 import api_pb2
|
|
21
|
+
from iterm2.notifications import async_subscribe_to_variable_change_notification
|
|
22
|
+
|
|
23
|
+
from agent_command_tab import iterm2_actions
|
|
24
|
+
from agent_command_tab.agent_process_tree import (an_agent_program_runs_through_a_shell_below,
|
|
25
|
+
choose_command_the_agent_is_waiting_on,
|
|
26
|
+
choose_detached_processes_of_the_conversation, choose_helper_process_ids,
|
|
27
|
+
compute_cpu_percent, list_descendant_processes, list_detached_processes,
|
|
28
|
+
process_has_its_terminal, process_is_alive,
|
|
29
|
+
process_is_stopped, read_child_processes,
|
|
30
|
+
read_name_the_process_was_started_as, read_process_arguments_and_environment,
|
|
31
|
+
read_process_current_folder, read_process_info,
|
|
32
|
+
read_process_tree_resource_usage)
|
|
33
|
+
from agent_command_tab.hook_event_tracking import (SESSION_START_SOURCES_OF_ANOTHER_CONVERSATION_IN_THE_SAME_PROCESS,
|
|
34
|
+
apply_hook_event, find_agent_process_id_of_hook_event,
|
|
35
|
+
find_when_the_hooks_ended_the_turn)
|
|
36
|
+
from agent_command_tab.hooks_installer import HOOK_EVENTS_BY_AGENT_TOOL_NAME, check_hooks
|
|
37
|
+
from agent_command_tab.hook_states_store import load_hook_states, save_hook_states
|
|
38
|
+
from agent_command_tab.agent_session_pausing import (continue_processes_stopped_at_pause, pause_agent_session,
|
|
39
|
+
pause_has_ended, resume_agent_session, send_signal_to_processes)
|
|
40
|
+
from agent_command_tab.pause_records_store import load_pause_records, save_pause_records
|
|
41
|
+
from agent_command_tab.settings_store import find_program_on_path_or_in_the_usual_folders
|
|
42
|
+
from agent_command_tab.agent_adapters import build_built_in_agent_tool_adapters
|
|
43
|
+
from agent_command_tab.agent_adapters.base import (COMMAND_THAT_STARTS_A_NEW_CONVERSATION, MESSAGES_THROUGH_CODEX_QUEUE,
|
|
44
|
+
MESSAGES_THROUGH_THE_SEND_MESSAGE_TOOL, command_line_runs_a_shell)
|
|
45
|
+
from agent_command_tab.agent_adapters.claude_code import ClaudeCodeAdapter, list_claude_config_folders
|
|
46
|
+
from agent_command_tab.agent_adapters.codex import CodexAdapter
|
|
47
|
+
from agent_command_tab.dashboard_core_api import ActionRegistry, ActionResult
|
|
48
|
+
from agent_command_tab.messages_between_agent_sessions import (SECONDS_A_MESSAGE_WAITS_FOR_AN_AGENT_AT_ITS_PROMPT,
|
|
49
|
+
AgentSessionForMessages,
|
|
50
|
+
build_message_asking_agent_session_to_talk_to_the_others)
|
|
51
|
+
from agent_command_tab.iterm2_snapshot_builder import DisplayedState, build_computer_snapshot, resolve_agent_sessions
|
|
52
|
+
from agent_command_tab.docked_window_frames_store import (adopt_records_of_restored_windows,
|
|
53
|
+
load_docked_window_frames, save_docked_window_frames)
|
|
54
|
+
from agent_command_tab.monitor_assignment import compute_frame_clear_of_area, frames_are_within_tolerance
|
|
55
|
+
from agent_command_tab.screen_readings import (compute_screen_fingerprint, count_lines_matching,
|
|
56
|
+
screen_shows_permission_dialog)
|
|
57
|
+
from agent_command_tab.session_status_computation import (STATES_OF_A_TURN_UNDER_WAY, STATES_OF_AN_AGENT_WAITING_AT_ITS_PROMPT,
|
|
58
|
+
map_iterm2_status_value_to_state,
|
|
59
|
+
permission_dialog_was_answered,
|
|
60
|
+
status_values_put_the_agent_in_the_same_state,
|
|
61
|
+
track_status_value,
|
|
62
|
+
update_permission_dialog_reading)
|
|
63
|
+
from agent_command_tab.snapshot_data_classes import ChildProcessEntry, iterate_agent_session_entries
|
|
64
|
+
from agent_command_tab.window_list_ordering import move_window_in_window_list_order, update_window_list_order
|
|
65
|
+
|
|
66
|
+
FRAME_POLL_INTERVAL_SECONDS = 2
|
|
67
|
+
SCREEN_CHECK_INTERVAL_SECONDS = 2
|
|
68
|
+
FINGERPRINT_INTERVAL_SECONDS = 30
|
|
69
|
+
# When the dashboard first sees a session mid-turn, processes started this long after the agent
|
|
70
|
+
# itself count as commands; MCP servers and other helpers start before that.
|
|
71
|
+
SECONDS_AN_AGENT_TAKES_TO_START_ITS_HELPERS = 30
|
|
72
|
+
SECONDS_BETWEEN_HELPER_PROCESS_RECORDINGS = 30 # while a session is idle
|
|
73
|
+
CONTEXT_USAGE_CHECK_INTERVAL_SECONDS = 5
|
|
74
|
+
RESOURCE_USAGE_CHECK_INTERVAL_SECONDS = 3 # the Memory and CPU columns
|
|
75
|
+
CPU_PERCENT_SHOWN_AS_IDLE = 3 # an idle agent's CPU use wavers between 0 and 2 percent
|
|
76
|
+
SECONDS_AN_AGENT_GETS_TO_END_BEFORE_IT_IS_KILLED = 5 # "Kill Session": SIGTERM, then SIGKILL
|
|
77
|
+
CONVERSATION_FILE_RETRY_SECONDS = 15 # a conversation file not found yet (Codex writes it at the first prompt)
|
|
78
|
+
CONVERSATION_FILE_RECHECK_SECONDS = 60 # a conversation file found: looked up again in case the conversation changed
|
|
79
|
+
CONVERSATION_FILE_READING_NAMES = ("context_tokens", "context_window_tokens", "conversation_preview") # screen reading values read from it
|
|
80
|
+
# How long a working agent may think with nothing new on screen before its row shows "stuck"; no
|
|
81
|
+
# longer a setting (user request, 2026-10-26).
|
|
82
|
+
STUCK_THRESHOLD_SECONDS = 600
|
|
83
|
+
# How long iTerm2 must have said working before Claude Code's own "idle" counts over it without a
|
|
84
|
+
# turn end from the hooks: at a turn's start Claude Code's own report may lag iTerm2's for a moment
|
|
85
|
+
# (DashboardCore.claude_code_reports_the_turn_over).
|
|
86
|
+
SECONDS_BEFORE_CLAUDE_CODES_OWN_IDLE_COUNTS_OVER_WORKING = 10
|
|
87
|
+
SMALLEST_WINDOW_WIDTH = 400 # a docked sidebar never makes an iTerm2 window narrower than this
|
|
88
|
+
FRAME_TOLERANCE_POINTS = 20 # iTerm2 rounds window sizes to whole character cells
|
|
89
|
+
RETRY_DELAY_SECONDS = 1
|
|
90
|
+
CLAUDE_AGENTS_REFRESH_INTERVAL_SECONDS = 60
|
|
91
|
+
CLAUDE_AGENTS_TIMEOUT_SECONDS = 5
|
|
92
|
+
CLAUDE_AGENTS_RETRIES_FOR_A_NEW_PROCESS = 3
|
|
93
|
+
CLAUDE_AGENTS_RETRY_DELAY_SECONDS = 3
|
|
94
|
+
SNAPSHOT_COALESCING_DELAY_SECONDS = 0.1
|
|
95
|
+
SESSION_VARIABLES_TO_WATCH = ("commandLine", "status")
|
|
96
|
+
# Claude Code's own report of a session (read_claude_code_session_status) as the iTerm2 status
|
|
97
|
+
# value it stands for; "shell" is a command running.
|
|
98
|
+
CLAUDE_CODE_SESSION_STATUSES_TO_ITERM2_STATUS_VALUES = {"idle": "idle", "busy": "working", "shell": "working",
|
|
99
|
+
"waiting": "waiting"}
|
|
100
|
+
SECONDS_TO_WAIT_FOR_THE_STATUS_IN_ITERM2S_TAB_BAR = 2
|
|
101
|
+
CODEX_QUEUE_TIMEOUT_SECONDS = 30
|
|
102
|
+
# How often "Talk to Each Other" checks whether a held message can be pasted (user request, 2026-10-21).
|
|
103
|
+
SECONDS_BETWEEN_CHECKS_FOR_AN_AGENT_AT_ITS_PROMPT = 3
|
|
104
|
+
# How long the row of an agent that ended without a normal session end stays, gray and "exited"
|
|
105
|
+
# (a fixed time rather than a setting, as for "stuck").
|
|
106
|
+
EXITED_ROW_SECONDS = 300
|
|
107
|
+
CHILD_PROCESS_CHECK_INTERVAL_SECONDS = 3 # an open tab row's sub rows and the background shells
|
|
108
|
+
LONGEST_COMMAND_TEXT = 500 # characters of a sub row's command kept in the snapshot
|
|
109
|
+
HOOKS_CHECK_INTERVAL_SECONDS = 10 # whether the agent tools' settings hold the app's hooks
|
|
110
|
+
LONGEST_HOOK_EVENT_LINE = 1024 ** 2
|
|
111
|
+
SECONDS_TO_REACH_ANOTHER_HOOK_EVENTS_LISTENER = 0.5
|
|
112
|
+
# How often a copy that left the hook events socket to another copy checks whether that one has ended.
|
|
113
|
+
SECONDS_BETWEEN_CHECKS_FOR_ANOTHER_HOOK_EVENTS_LISTENER = 5
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def find_claude_command_path():
|
|
117
|
+
"""Returns the path of the `claude` command (the stable link on PATH or in the usual folders,
|
|
118
|
+
not a versioned file), or None."""
|
|
119
|
+
return find_program_on_path_or_in_the_usual_folders("claude")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def list_folders_that_may_hold_claude_code_transcripts():
|
|
123
|
+
"""Returns CLAUDE_CONFIG_DIR, ~/.claude, and other ~/.claude* folders with a projects folder
|
|
124
|
+
(a Claude Code started with its own CLAUDE_CONFIG_DIR, for example ~/.claude_work)."""
|
|
125
|
+
home_folder = os.path.expanduser("~")
|
|
126
|
+
candidate_folders = ([os.environ["CLAUDE_CONFIG_DIR"]] if os.environ.get("CLAUDE_CONFIG_DIR") else []) + \
|
|
127
|
+
[os.path.join(home_folder, ".claude")] + sorted(glob.glob(os.path.join(home_folder, ".claude*")))
|
|
128
|
+
return [folder for folder in dict.fromkeys(candidate_folders) if os.path.isdir(os.path.join(folder, "projects"))]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def read_claude_agents_by_process_id(claude_command_path, config_folders):
|
|
132
|
+
"""Runs `claude agents --json` once per config folder; returns {process ID: record}, each
|
|
133
|
+
record with "config_folder" added (None for the default folder).
|
|
134
|
+
|
|
135
|
+
Failures (no command, a timeout, unreadable output) give an empty result for that folder.
|
|
136
|
+
"""
|
|
137
|
+
claude_agents_by_process_id = {}
|
|
138
|
+
for config_folder in config_folders:
|
|
139
|
+
environment = dict(os.environ)
|
|
140
|
+
environment.pop("CLAUDE_CONFIG_DIR", None)
|
|
141
|
+
if config_folder:
|
|
142
|
+
environment["CLAUDE_CONFIG_DIR"] = config_folder
|
|
143
|
+
process = None
|
|
144
|
+
try:
|
|
145
|
+
process = await asyncio.create_subprocess_exec(
|
|
146
|
+
claude_command_path, "agents", "--json", env=environment,
|
|
147
|
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL)
|
|
148
|
+
standard_output, _ = await asyncio.wait_for(process.communicate(), timeout=CLAUDE_AGENTS_TIMEOUT_SECONDS)
|
|
149
|
+
for record in json.loads(standard_output or b"[]"):
|
|
150
|
+
if isinstance(record, dict) and record.get("pid"):
|
|
151
|
+
claude_agents_by_process_id[int(record["pid"])] = dict(record, config_folder=config_folder)
|
|
152
|
+
except (OSError, ValueError, asyncio.TimeoutError) as error:
|
|
153
|
+
print(f"claude agents --json failed for config folder {config_folder or '(default)'}: {error!r}")
|
|
154
|
+
if process is not None and process.returncode is None:
|
|
155
|
+
process.kill()
|
|
156
|
+
await process.wait()
|
|
157
|
+
return claude_agents_by_process_id
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def read_claude_code_session_status(config_folder, process_id):
|
|
161
|
+
"""Returns the status Claude Code keeps for a running session ("idle", "busy", "waiting", or
|
|
162
|
+
"shell" while it runs a command; seen on 2026-10-21), read now from
|
|
163
|
+
<config folder>/sessions/<process ID>.json (the file `claude agents --json` reads), or None
|
|
164
|
+
when it can't be read. Cheap enough to read just before typing into a session,
|
|
165
|
+
while the record from `claude agents --json` may be a minute old.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
config_folder: The record's "config_folder", or None for the default ~/.claude.
|
|
169
|
+
process_id: The Claude Code process ID.
|
|
170
|
+
"""
|
|
171
|
+
path = os.path.join(config_folder or os.path.expanduser("~/.claude"), "sessions", f"{process_id}.json")
|
|
172
|
+
try:
|
|
173
|
+
with open(path) as session_file:
|
|
174
|
+
return json.load(session_file).get("status")
|
|
175
|
+
except (OSError, ValueError, AttributeError):
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
async def queue_message_for_codex_session(codex_command_path, conversation_id, message):
|
|
180
|
+
"""Runs `codex queue --thread <conversation ID> --message <text>`, which hands the message to
|
|
181
|
+
the running Codex session; it runs it as its next turn, after any turn under way (checked live
|
|
182
|
+
with Codex 0.155.1 on 2026-10-21). Returns an ActionResult."""
|
|
183
|
+
if not codex_command_path:
|
|
184
|
+
return ActionResult(False, "the codex command wasn't found")
|
|
185
|
+
process = None
|
|
186
|
+
try:
|
|
187
|
+
# The message is attached to its option: on its own, a message starting with "-" (a note
|
|
188
|
+
# that begins with a bullet) would be read as an unknown option.
|
|
189
|
+
process = await asyncio.create_subprocess_exec(
|
|
190
|
+
codex_command_path, "queue", "--thread", conversation_id, f"--message={message}",
|
|
191
|
+
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE)
|
|
192
|
+
_, standard_error = await asyncio.wait_for(process.communicate(), timeout=CODEX_QUEUE_TIMEOUT_SECONDS)
|
|
193
|
+
except (OSError, asyncio.TimeoutError) as error:
|
|
194
|
+
if process is not None and process.returncode is None:
|
|
195
|
+
process.kill()
|
|
196
|
+
await process.wait()
|
|
197
|
+
return ActionResult(False, f"codex queue failed: {error!r}")
|
|
198
|
+
if process.returncode != 0:
|
|
199
|
+
return ActionResult(False, f"codex queue failed: {standard_error.decode(errors='replace').strip()[-300:]}")
|
|
200
|
+
return ActionResult(True)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def another_process_listens_at(socket_path):
|
|
204
|
+
"""Returns whether a process accepts connections on this Unix socket (not just a file left by
|
|
205
|
+
a process that ended)."""
|
|
206
|
+
try:
|
|
207
|
+
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
|
|
208
|
+
connection.settimeout(SECONDS_TO_REACH_ANOTHER_HOOK_EVENTS_LISTENER)
|
|
209
|
+
connection.connect(socket_path)
|
|
210
|
+
return True
|
|
211
|
+
except OSError: # no file, or no one listening (ConnectionRefusedError)
|
|
212
|
+
return False
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def round_memory_and_cpu_use(memory_bytes, cpu_percent):
|
|
216
|
+
"""Returns the memory to the megabyte and the CPU use to a whole percent, 0 below
|
|
217
|
+
CPU_PERCENT_SHOWN_AS_IDLE (None stays None), so an idle session's rows and the snapshot don't
|
|
218
|
+
change at every reading."""
|
|
219
|
+
if cpu_percent is not None:
|
|
220
|
+
cpu_percent = round(cpu_percent) if cpu_percent >= CPU_PERCENT_SHOWN_AS_IDLE else 0
|
|
221
|
+
return round(memory_bytes / 1024 ** 2) * 1024 ** 2, cpu_percent
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def convert_exception_to_action_result(result_or_exception):
|
|
225
|
+
"""Returns an ActionResult from asyncio.gather(..., return_exceptions=True): a failed one for an exception."""
|
|
226
|
+
if isinstance(result_or_exception, Exception):
|
|
227
|
+
return ActionResult(False, f"it failed: {result_or_exception!r}")
|
|
228
|
+
return result_or_exception
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def build_conversation_file_record(conversation_key, path, looked_up_at, cleared_path):
|
|
232
|
+
"""Returns what the core keeps about a session's conversation file: the conversation it is for
|
|
233
|
+
(DashboardCore.find_conversation_key), its path or None while not found, when it was looked
|
|
234
|
+
up, the modification time of its last reading (None until read), and the file of a
|
|
235
|
+
conversation /clear ended, which lookups skip (or None)."""
|
|
236
|
+
return {"key": conversation_key, "path": path, "looked_up_at": looked_up_at, "modified_at": None,
|
|
237
|
+
"cleared_path": cleared_path}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def parse_job_process_id(job_pid_value):
|
|
241
|
+
"""Returns iTerm2's `jobPid` variable as an int, or None."""
|
|
242
|
+
try:
|
|
243
|
+
return int(job_pid_value)
|
|
244
|
+
except (TypeError, ValueError):
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
async def read_iterm2_variables(connection, names, session_id=None, tab_id=None, window_id=None):
|
|
249
|
+
"""Returns the values of several variables of one session, tab or window, read in a single
|
|
250
|
+
request (the iterm2 package's async_get_variable sends one request per variable).
|
|
251
|
+
|
|
252
|
+
Raises:
|
|
253
|
+
iterm2.RPCException: The session, tab or window is gone.
|
|
254
|
+
"""
|
|
255
|
+
response = await iterm2.rpc.async_variable(connection, session_id, [], names, tab_id=tab_id, window_id=window_id)
|
|
256
|
+
status = response.variable_response.status
|
|
257
|
+
if status != api_pb2.VariableResponse.Status.Value("OK"):
|
|
258
|
+
raise iterm2.RPCException(api_pb2.VariableResponse.Status.Name(status))
|
|
259
|
+
return [json.loads(value) for value in response.variable_response.values]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
async def read_status_shown_in_iterm2s_tab_bar(session):
|
|
263
|
+
"""Returns the status iTerm2 shows for a session in its tab bar ("idle", "working", ...), from
|
|
264
|
+
its built-in function iterm2.get_session_status (not in iTerm2's documentation), or None.
|
|
265
|
+
|
|
266
|
+
After iTerm2 restarts, its tab bar still shows each tab's status, and this function returns
|
|
267
|
+
it, but the session's `status` variable stays empty until the agent's next hook event (seen
|
|
268
|
+
with iTerm2 3.7.6; user request, 2026-10-21).
|
|
269
|
+
"""
|
|
270
|
+
try:
|
|
271
|
+
result = await session.async_invoke_function(f'iterm2.get_session_status(session_id: "{session.session_id}")',
|
|
272
|
+
timeout=SECONDS_TO_WAIT_FOR_THE_STATUS_IN_ITERM2S_TAB_BAR)
|
|
273
|
+
except iterm2.RPCException:
|
|
274
|
+
return None
|
|
275
|
+
return result.get("status") if isinstance(result, dict) else None
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
async def read_window_frame(window):
|
|
279
|
+
"""Returns an iTerm2 window's frame as (x, y, width, height)."""
|
|
280
|
+
frame = await window.async_get_frame()
|
|
281
|
+
return (frame.origin.x, frame.origin.y, frame.size.width, frame.size.height)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
class DashboardCore:
|
|
285
|
+
"""The core: owns all shared state and runs on the background thread's event loop.
|
|
286
|
+
|
|
287
|
+
Args:
|
|
288
|
+
publish_snapshot: Called on the background thread with each new ComputerSnapshot.
|
|
289
|
+
report_connection_lost: Called on the background thread with a message when the
|
|
290
|
+
iTerm2 connection fails or closes; the app then exits so its supervisor restarts it.
|
|
291
|
+
verbose: Print diagnostics.
|
|
292
|
+
docked_window_frames_file_path: Where the frames windows had before a docked sidebar
|
|
293
|
+
narrowed them are kept across restarts; None keeps them in memory only.
|
|
294
|
+
pause_records_file_path: Where the records of paused agent sessions are kept across
|
|
295
|
+
restarts (pause_records_store); None keeps them in memory only.
|
|
296
|
+
pause_record_by_tab_and_agent_to_start_with: The records to start with when
|
|
297
|
+
pause_records_file_path is None (dump-snapshot reads the app's file but never writes it).
|
|
298
|
+
hook_events_socket_path: The socket the app's hooks send their events to
|
|
299
|
+
(hook_event_forwarder.HOOK_EVENTS_SOCKET_PATH), or None to listen to none
|
|
300
|
+
(dump-snapshot, which must not take the app's socket away).
|
|
301
|
+
hook_states_file_path: Where what the agent processes' hooks reported is kept across
|
|
302
|
+
restarts (hook_states_store); None keeps it in memory only.
|
|
303
|
+
"""
|
|
304
|
+
|
|
305
|
+
def __init__(self, publish_snapshot, report_connection_lost, verbose=False, docked_window_frames_file_path=None,
|
|
306
|
+
pause_records_file_path=None, pause_record_by_tab_and_agent_to_start_with=None, hook_events_socket_path=None,
|
|
307
|
+
hook_states_file_path=None):
|
|
308
|
+
self.publish_snapshot = publish_snapshot
|
|
309
|
+
self.report_connection_lost = report_connection_lost
|
|
310
|
+
self.verbose = verbose
|
|
311
|
+
self.docked_window_frames_file_path = docked_window_frames_file_path
|
|
312
|
+
self.pause_records_file_path = pause_records_file_path
|
|
313
|
+
self.hook_events_socket_path = hook_events_socket_path
|
|
314
|
+
self.hook_states_file_path = hook_states_file_path
|
|
315
|
+
# What each agent process's hooks reported (hook_event_tracking.apply_hook_event), by its
|
|
316
|
+
# process ID, kept while it runs or is a tab's agent, and while its row shows "exited";
|
|
317
|
+
# those of the processes still running come back after a restart.
|
|
318
|
+
self.hook_state_by_agent_process_id = (self.load_hook_states_of_the_processes_still_running()
|
|
319
|
+
if hook_states_file_path else {})
|
|
320
|
+
# {session ID: (the AgentSessionEntry its row last showed, when its agent ended)} for the
|
|
321
|
+
# tabs whose agent ended without a normal session end, shown as "exited" for EXITED_ROW_SECONDS.
|
|
322
|
+
self.exited_agent_sessions_by_session_id = {}
|
|
323
|
+
self.last_agent_session_entry_by_session_id = {} # from the last snapshot, for an "exited" row
|
|
324
|
+
self.process_ids_ended_from_the_list = set() # "Kill Session": their end is no crash
|
|
325
|
+
self.hooks_status_per_agent_tool = () # ComputerSnapshot.hooks_status_per_agent_tool
|
|
326
|
+
self.hooks_check_needed = asyncio.Event()
|
|
327
|
+
self.connection = None
|
|
328
|
+
self.app = None
|
|
329
|
+
self.specific_adapters, self.generic_adapter = build_built_in_agent_tool_adapters()
|
|
330
|
+
self.process_ids_asked_about_in_claude_agents = set()
|
|
331
|
+
self.claude_agents_retry_count_by_process_id = {}
|
|
332
|
+
self.agent_sessions = {}
|
|
333
|
+
self.claude_agents_refresh_is_running = False
|
|
334
|
+
self.computer_id = socket.gethostname()
|
|
335
|
+
self.computer_name = socket.gethostname().split(".")[0]
|
|
336
|
+
self.claude_command_path = find_claude_command_path()
|
|
337
|
+
# For `codex queue`; the app's settings then name it (set_core_settings).
|
|
338
|
+
self.codex_command_path = find_program_on_path_or_in_the_usual_folders("codex")
|
|
339
|
+
self.message_typing_lock_by_session_id = {} # two held messages are never pasted into one tab at once
|
|
340
|
+
self.gathered_windows = []
|
|
341
|
+
self.windows_were_gathered = False # till the first gather, saved frames can't be matched to windows
|
|
342
|
+
self.gather_is_in_progress = False
|
|
343
|
+
self.monitors = []
|
|
344
|
+
self.window_order = []
|
|
345
|
+
self.session_tracking_by_session_id = {}
|
|
346
|
+
# Codex agent processes that shared their folder with another Codex session while they ran
|
|
347
|
+
# (remember_codex_sessions_that_share_a_folder).
|
|
348
|
+
self.codex_process_ids_that_shared_their_folder = set()
|
|
349
|
+
# For each tab whose row goes by its own agent (choose_status_value_of_the_tabs_own_agent):
|
|
350
|
+
# the status iTerm2 held at the last check while an agent program ran inside the tab's agent.
|
|
351
|
+
self.iterm2_status_seen_while_an_inner_agent_ran_by_session_id = {}
|
|
352
|
+
# {session ID: (the status value set in iTerm2, when the dashboard first saw it)}, so a turn
|
|
353
|
+
# end its hooks report counts until iTerm2 sets another value (find_when_the_hooks_ended_the_turn).
|
|
354
|
+
self.status_set_in_iterm2_and_since_by_session_id = {}
|
|
355
|
+
# {session ID: when iTerm2 last reported a change of the session's status variable}; a value
|
|
356
|
+
# already set when the dashboard connected has none (find_status_set_in_iterm2_since_the_job_started).
|
|
357
|
+
self.status_set_in_iterm2_at_by_session_id = {}
|
|
358
|
+
self.displayed_state_by_session_id = {}
|
|
359
|
+
self.screen_readings_by_session_id = {}
|
|
360
|
+
# {(session ID, agent process ID): agent_session_pausing.PauseRecord}, until the agent runs
|
|
361
|
+
# again or is gone; an agent still paused from before a restart is listed again from its
|
|
362
|
+
# record. By agent too: a tab can hold a paused agent and, at the shell, a newer one.
|
|
363
|
+
self.pause_record_by_tab_and_agent = (load_pause_records(pause_records_file_path) if pause_records_file_path
|
|
364
|
+
else dict(pause_record_by_tab_and_agent_to_start_with or {}))
|
|
365
|
+
self.session_ids_being_paused_or_resumed = set()
|
|
366
|
+
self.reserved_screen_area = None
|
|
367
|
+
self.frames_before_making_room_by_window_id = (load_docked_window_frames(docked_window_frames_file_path)
|
|
368
|
+
if docked_window_frames_file_path else {})
|
|
369
|
+
self.saved_docked_window_frames = dict(self.frames_before_making_room_by_window_id)
|
|
370
|
+
self.records_loaded_from_file_await_adoption = bool(self.frames_before_making_room_by_window_id)
|
|
371
|
+
self.reserved_area_was_received = False # until the main thread says whether the sidebar is docked
|
|
372
|
+
self.window_room_lock = asyncio.Lock()
|
|
373
|
+
self.left_out_agent_tool_names = frozenset() # the settings' Harnesses section
|
|
374
|
+
self.resource_usage_is_read = False # while the Memory or CPU column is shown, or the list is sorted by one
|
|
375
|
+
self.claude_agents_by_process_id = {}
|
|
376
|
+
self.key_terminal_window_id = None # None while no terminal window (for example iTerm2's Settings) has keyboard focus
|
|
377
|
+
self.last_seen_session_id = None
|
|
378
|
+
self.dashboard_is_active = False
|
|
379
|
+
self.last_published_snapshot_without_time = None
|
|
380
|
+
self.snapshot_needed = asyncio.Event()
|
|
381
|
+
self.regather_needed = asyncio.Event()
|
|
382
|
+
self.screen_check_needed = asyncio.Event()
|
|
383
|
+
self.conversation_files_by_session_id = {} # build_conversation_file_record's records
|
|
384
|
+
self.folders_that_may_hold_claude_code_transcripts = list_folders_that_may_hold_claude_code_transcripts()
|
|
385
|
+
self.peek_lock = asyncio.Lock() # a quick release must not undo a peek that hasn't happened yet
|
|
386
|
+
self.iterm2_state_before_peek = None
|
|
387
|
+
self.action_registry = ActionRegistry()
|
|
388
|
+
self.register_actions()
|
|
389
|
+
|
|
390
|
+
# ----- actions -----
|
|
391
|
+
|
|
392
|
+
def register_actions(self):
|
|
393
|
+
"""Registers every action with its flags."""
|
|
394
|
+
register = self.action_registry.register_action
|
|
395
|
+
register("focus_agent_session", self.handle_focus_agent_session, True, False)
|
|
396
|
+
register("focus_window", self.handle_focus_window, True, False)
|
|
397
|
+
register("rename_tab", self.handle_rename_tab, True, False)
|
|
398
|
+
register("rename_window", self.handle_rename_window, True, False)
|
|
399
|
+
register("move_tab", self.handle_move_tab, False, False)
|
|
400
|
+
register("move_tab_to_new_window", self.handle_move_tab_to_new_window, False, False)
|
|
401
|
+
register("reorder_window_list", self.handle_reorder_window_list, False, False)
|
|
402
|
+
register("start_agent_session", self.handle_start_agent_session, True, False)
|
|
403
|
+
register("move_window_to_monitor", self.handle_move_window_to_monitor, False, False)
|
|
404
|
+
register("close_window", self.handle_close_window, False, False)
|
|
405
|
+
register("duplicate_agent_session", self.handle_duplicate_agent_session, True, False)
|
|
406
|
+
register("peek_agent_session", self.handle_peek_agent_session, False, False)
|
|
407
|
+
register("end_peek", self.handle_end_peek, False, False)
|
|
408
|
+
register("send_slash_command", self.handle_send_slash_command, True, True)
|
|
409
|
+
register("send_slash_command_to_agent_sessions", self.handle_send_slash_command_to_agent_sessions, True, True)
|
|
410
|
+
register("end_agent_process", self.handle_end_agent_process, False, False)
|
|
411
|
+
register("end_agent_processes", self.handle_end_agent_processes, False, False)
|
|
412
|
+
register("pause_agent_sessions", self.handle_pause_agent_sessions, True, True)
|
|
413
|
+
register("resume_agent_sessions", self.handle_resume_agent_sessions, True, True)
|
|
414
|
+
register("ask_agent_sessions_to_talk_to_each_other", self.handle_ask_agent_sessions_to_talk_to_each_other, True, True)
|
|
415
|
+
|
|
416
|
+
async def perform_action(self, action_request):
|
|
417
|
+
"""Runs an action request, then asks for a fresh gather and snapshot.
|
|
418
|
+
|
|
419
|
+
The gather itself runs in publish_when_needed, so gathers never overlap and their
|
|
420
|
+
errors are handled in one place.
|
|
421
|
+
"""
|
|
422
|
+
if self.app is None:
|
|
423
|
+
return ActionResult(False, "not connected to iTerm2")
|
|
424
|
+
action_result = await self.action_registry.perform_action(action_request)
|
|
425
|
+
if self.verbose or not action_result.succeeded:
|
|
426
|
+
print(f"action {action_request.action}: {action_result}")
|
|
427
|
+
self.regather_needed.set()
|
|
428
|
+
return action_result
|
|
429
|
+
|
|
430
|
+
async def handle_focus_agent_session(self, action_request):
|
|
431
|
+
return await iterm2_actions.focus_agent_session(self.app, action_request.target["session_id"])
|
|
432
|
+
|
|
433
|
+
async def handle_focus_window(self, action_request):
|
|
434
|
+
return await iterm2_actions.focus_window(self.app, action_request.target["window_id"])
|
|
435
|
+
|
|
436
|
+
async def handle_rename_tab(self, action_request):
|
|
437
|
+
return await iterm2_actions.rename_tab(self.app, action_request.target["tab_id"], action_request.arguments["new_title"])
|
|
438
|
+
|
|
439
|
+
async def handle_rename_window(self, action_request):
|
|
440
|
+
return await iterm2_actions.rename_window(self.app, action_request.target["window_id"],
|
|
441
|
+
action_request.arguments["new_title"])
|
|
442
|
+
|
|
443
|
+
async def handle_move_tab(self, action_request):
|
|
444
|
+
return await iterm2_actions.move_tab_to_window_position(
|
|
445
|
+
self.app, action_request.target["tab_id"], action_request.arguments["target_window_id"],
|
|
446
|
+
action_request.arguments.get("drop_before_tab_id"))
|
|
447
|
+
|
|
448
|
+
async def handle_move_tab_to_new_window(self, action_request):
|
|
449
|
+
return await iterm2_actions.move_tab_to_new_window(self.app, action_request.target["tab_id"])
|
|
450
|
+
|
|
451
|
+
async def handle_start_agent_session(self, action_request):
|
|
452
|
+
"""Target {"window_id": ...} opens a tab there; an empty target opens a new window."""
|
|
453
|
+
return await iterm2_actions.start_agent_session(
|
|
454
|
+
self.connection, self.app, action_request.target.get("window_id"), action_request.arguments["folder"],
|
|
455
|
+
action_request.arguments["launch_command"])
|
|
456
|
+
|
|
457
|
+
async def handle_send_slash_command(self, action_request):
|
|
458
|
+
"""Types /compact or /clear into an agent session that waits at its prompt, idle or done
|
|
459
|
+
as its row shows it (iterm2_actions.type_slash_command checks its input box)."""
|
|
460
|
+
session_id = action_request.target["session_id"]
|
|
461
|
+
# Checked and typed holding the tab's lock, as every typing into a tab is: a held message may be being pasted.
|
|
462
|
+
async with self.message_typing_lock_by_session_id.setdefault(session_id, asyncio.Lock()):
|
|
463
|
+
agent_session = self.agent_sessions.get(session_id)
|
|
464
|
+
if agent_session is None:
|
|
465
|
+
return ActionResult(False, "that tab no longer runs an agent")
|
|
466
|
+
if agent_session["is_in_background"]:
|
|
467
|
+
# Its row keeps the state from before, but keys would go to the shell or editor in front.
|
|
468
|
+
return ActionResult(False, "the agent is suspended or another program is in front of it")
|
|
469
|
+
displayed_state = self.displayed_state_by_session_id.get(session_id)
|
|
470
|
+
state = displayed_state.state if displayed_state is not None else "unknown"
|
|
471
|
+
if state not in STATES_OF_AN_AGENT_WAITING_AT_ITS_PROMPT:
|
|
472
|
+
return ActionResult(False, f"the agent is {state}; commands are typed only while it waits at its prompt")
|
|
473
|
+
if self.claude_code_reports_the_session_busy(session_id, agent_session):
|
|
474
|
+
return ActionResult(False, "Claude Code reports the session busy; commands are typed only while it waits at its prompt")
|
|
475
|
+
return await self.type_slash_command_into_agent_session(
|
|
476
|
+
session_id, agent_session, action_request.arguments["command"], waits_at_its_prompt=True) or ActionResult(
|
|
477
|
+
False, "the tab has unsent text in its input box, the input box isn't on screen, or the agent refused it during a turn")
|
|
478
|
+
|
|
479
|
+
async def type_slash_command_into_agent_session(self, session_id, agent_session, command, waits_at_its_prompt):
|
|
480
|
+
"""Types the command (iterm2_actions.type_slash_command: None when nothing was typed, the
|
|
481
|
+
input box holding unsent text or being off screen). A /clear typed at the prompt forgets
|
|
482
|
+
the cleared conversation at once; one the agent queues during its turn runs only when the
|
|
483
|
+
turn ends, so its new conversation is found as after a /clear typed by hand (the
|
|
484
|
+
`claude agents` refresh)."""
|
|
485
|
+
clears_at_once = command == COMMAND_THAT_STARTS_A_NEW_CONVERSATION and waits_at_its_prompt
|
|
486
|
+
# Known before the conversation ends, since a lookup after /clear can't tell old from new.
|
|
487
|
+
path_of_conversation_to_clear = await self.find_current_conversation_file(session_id, agent_session) \
|
|
488
|
+
if clears_at_once else None
|
|
489
|
+
action_result = await iterm2_actions.type_slash_command(
|
|
490
|
+
self.app, session_id, command, agent_session["adapter"], agent_is_in_the_middle_of_a_turn=not waits_at_its_prompt)
|
|
491
|
+
if action_result is not None and action_result.succeeded and clears_at_once:
|
|
492
|
+
self.forget_the_cleared_conversation(session_id, agent_session, path_of_conversation_to_clear)
|
|
493
|
+
return action_result
|
|
494
|
+
|
|
495
|
+
async def handle_send_slash_command_to_agent_sessions(self, action_request):
|
|
496
|
+
"""Types /compact or /clear (arguments {"command": ...}) into every session of target
|
|
497
|
+
{"session_ids": [...]}, those in the middle of a turn too (the menu of several selected
|
|
498
|
+
rows; user requests, 2026-10-21): type_slash_command_once_the_agent_can_take_it for each."""
|
|
499
|
+
return await self.run_for_each_agent_session(action_request, self.type_slash_command_once_the_agent_can_take_it)
|
|
500
|
+
|
|
501
|
+
async def type_slash_command_once_the_agent_can_take_it(self, action_request):
|
|
502
|
+
"""Types /compact or /clear into one agent session (target {"session_id": ...}) at once when
|
|
503
|
+
it waits at its prompt (for a row without a state, when its screen shows no turn under
|
|
504
|
+
way), or when its tool queues commands typed during a turn (Claude Code runs them when the
|
|
505
|
+
turn ends). Otherwise (Codex refuses them during a task), and while the
|
|
506
|
+
input box holds unsent text or is off screen (a permission prompt), checks again every
|
|
507
|
+
SECONDS_BETWEEN_CHECKS_FOR_AN_AGENT_AT_ITS_PROMPT, as a held Talk to Each Other message
|
|
508
|
+
does. Gives up after SECONDS_A_MESSAGE_WAITS_FOR_AN_AGENT_AT_ITS_PROMPT, or once the tab's
|
|
509
|
+
agent process changes; at once for an agent that is suspended or has another program in
|
|
510
|
+
front of it."""
|
|
511
|
+
session_id = action_request.target["session_id"]
|
|
512
|
+
command = action_request.arguments["command"]
|
|
513
|
+
agent_session = self.agent_sessions.get(session_id)
|
|
514
|
+
if agent_session is None or not agent_session["process_id"]:
|
|
515
|
+
return ActionResult(False, "that tab no longer runs an agent")
|
|
516
|
+
if agent_session["is_in_background"]:
|
|
517
|
+
return ActionResult(False, "the agent is suspended or another program is in front of it")
|
|
518
|
+
agent_process_id = agent_session["process_id"]
|
|
519
|
+
deadline = time.time() + SECONDS_A_MESSAGE_WAITS_FOR_AN_AGENT_AT_ITS_PROMPT
|
|
520
|
+
typing_lock = self.message_typing_lock_by_session_id.setdefault(session_id, asyncio.Lock())
|
|
521
|
+
while True:
|
|
522
|
+
# Checked holding the lock: a held message or command may have just been typed, starting a turn.
|
|
523
|
+
async with typing_lock:
|
|
524
|
+
agent_session = self.agent_sessions.get(session_id)
|
|
525
|
+
if agent_session is None or agent_session["process_id"] != agent_process_id:
|
|
526
|
+
return ActionResult(False, f"its agent ended before {command} could be typed")
|
|
527
|
+
try:
|
|
528
|
+
waits_at_its_prompt = (self.agent_waits_at_its_prompt(session_id, agent_session)
|
|
529
|
+
or await self.agent_whose_state_is_unknown_shows_no_turn_on_screen(session_id, agent_session))
|
|
530
|
+
if not agent_session["is_in_background"] and (
|
|
531
|
+
waits_at_its_prompt or agent_session["adapter"].queues_slash_commands_typed_during_a_turn):
|
|
532
|
+
action_result = await self.type_slash_command_into_agent_session(
|
|
533
|
+
session_id, agent_session, command, waits_at_its_prompt)
|
|
534
|
+
if action_result is not None:
|
|
535
|
+
return action_result
|
|
536
|
+
except iterm2.RPCException:
|
|
537
|
+
return ActionResult(False, "the tab closed meanwhile")
|
|
538
|
+
if time.time() >= deadline:
|
|
539
|
+
return ActionResult(False, "it didn't wait at its prompt with an empty input box within "
|
|
540
|
+
f"{SECONDS_A_MESSAGE_WAITS_FOR_AN_AGENT_AT_ITS_PROMPT // 60} minutes, "
|
|
541
|
+
f"so {command} wasn't typed")
|
|
542
|
+
await asyncio.sleep(SECONDS_BETWEEN_CHECKS_FOR_AN_AGENT_AT_ITS_PROMPT)
|
|
543
|
+
|
|
544
|
+
async def run_for_each_agent_session(self, action_request, handle_one):
|
|
545
|
+
"""Runs a one-session action (handle_one, taking target {"session_id": ...}) for every
|
|
546
|
+
session of target {"session_ids": [...]} at once; returns one ActionResult whose message
|
|
547
|
+
names each tab that failed and why."""
|
|
548
|
+
session_ids = action_request.target["session_ids"]
|
|
549
|
+
action_results = await asyncio.gather(*(handle_one(action_request._replace(target={"session_id": session_id}))
|
|
550
|
+
for session_id in session_ids), return_exceptions=True)
|
|
551
|
+
return self.combine_results_naming_the_tabs_that_failed(
|
|
552
|
+
session_ids, [convert_exception_to_action_result(action_result) for action_result in action_results])
|
|
553
|
+
|
|
554
|
+
def combine_results_naming_the_tabs_that_failed(self, session_ids, action_results):
|
|
555
|
+
"""Returns one ActionResult for an action on several agent sessions, whose message names
|
|
556
|
+
each tab that failed and why."""
|
|
557
|
+
failures = [f'"{self.find_tab_title_of_agent_session(session_id) or "a tab"}": {action_result.message}'
|
|
558
|
+
for session_id, action_result in zip(session_ids, action_results) if not action_result.succeeded]
|
|
559
|
+
return ActionResult(not failures, "; ".join(failures))
|
|
560
|
+
|
|
561
|
+
def find_tab_title_of_agent_session(self, session_id):
|
|
562
|
+
"""Returns the title the last snapshot shows for the agent session's tab, or ""."""
|
|
563
|
+
if self.last_published_snapshot_without_time is None:
|
|
564
|
+
return ""
|
|
565
|
+
return next((agent_session_entry.tab_title
|
|
566
|
+
for _, _, agent_session_entry in iterate_agent_session_entries(self.last_published_snapshot_without_time)
|
|
567
|
+
if agent_session_entry.session_id == session_id), "")
|
|
568
|
+
|
|
569
|
+
def agent_waits_at_its_prompt(self, session_id, agent_session):
|
|
570
|
+
"""Whether the agent session waits at its prompt: its row shows idle or done, and Claude
|
|
571
|
+
Code doesn't report it busy."""
|
|
572
|
+
displayed_state = self.displayed_state_by_session_id.get(session_id)
|
|
573
|
+
return (displayed_state is not None and displayed_state.state in STATES_OF_AN_AGENT_WAITING_AT_ITS_PROMPT
|
|
574
|
+
and not self.claude_code_reports_the_session_busy(session_id, agent_session))
|
|
575
|
+
|
|
576
|
+
async def agent_whose_state_is_unknown_shows_no_turn_on_screen(self, session_id, agent_session):
|
|
577
|
+
"""Whether an agent session whose row has no state (Codex 0.155.1 reports none to iTerm2)
|
|
578
|
+
shows no turn under way on screen (its adapter's working_screen_pattern, such as Codex's
|
|
579
|
+
"(5s • esc to interrupt)"), so it waits at its prompt. False when the row has a state, or
|
|
580
|
+
the adapter no such pattern."""
|
|
581
|
+
displayed_state = self.displayed_state_by_session_id.get(session_id)
|
|
582
|
+
working_screen_pattern = agent_session["adapter"].working_screen_pattern
|
|
583
|
+
session = self.app.get_session_by_id(session_id)
|
|
584
|
+
if working_screen_pattern is None or session is None or (displayed_state is not None and displayed_state.state != "unknown"):
|
|
585
|
+
return False
|
|
586
|
+
return count_lines_matching([text for text, _ in await iterm2_actions.read_screen_lines_with_faint_flags(session)],
|
|
587
|
+
working_screen_pattern) == 0
|
|
588
|
+
|
|
589
|
+
def claude_code_reports_the_session_busy(self, session_id, agent_session):
|
|
590
|
+
"""Whether Claude Code itself reports the agent session as anything but idle right now
|
|
591
|
+
(read_claude_code_session_status). Checked just before typing into it: a row may take its
|
|
592
|
+
idle state from a `claude agents --json` record up to a minute old, and Claude Code's input
|
|
593
|
+
box is empty during a turn too. False when Claude Code reports nothing (another tool). Its
|
|
594
|
+
"shell" while a background task runs after the turn ended, as its hooks report
|
|
595
|
+
(find_when_the_hooks_ended_the_turn), counts as at the prompt: its input box takes text
|
|
596
|
+
then (code review, 2026-10-27). With no background task running, that "shell" is a
|
|
597
|
+
command of a turn that another Stop hook kept going (claude_code_reports_the_turn_going_on;
|
|
598
|
+
code review, 2026-10-28)."""
|
|
599
|
+
claude_agent_record = self.claude_agents_by_process_id.get(agent_session["process_id"])
|
|
600
|
+
if claude_agent_record is None:
|
|
601
|
+
return False
|
|
602
|
+
status = read_claude_code_session_status(claude_agent_record.get("config_folder"), agent_session["process_id"])
|
|
603
|
+
hook_state = self.hook_state_by_agent_process_id.get(agent_session["process_id"])
|
|
604
|
+
if status == "shell" and (hook_state or {}).get("background_task_ids") != set() and find_when_the_hooks_ended_the_turn(
|
|
605
|
+
hook_state, self.status_set_in_iterm2_and_since_by_session_id.get(session_id, (None, float("inf")))[1]) is not None:
|
|
606
|
+
return False
|
|
607
|
+
return status is not None and status != "idle"
|
|
608
|
+
|
|
609
|
+
def claude_code_reports_the_turn_over(self, agent_session, seconds_working_has_held):
|
|
610
|
+
"""Whether Claude Code's own report of the session (read_claude_code_session_status) says
|
|
611
|
+
idle, for a tab iTerm2 says is working, at a moment that can't be a turn's start: the
|
|
612
|
+
hooks reported the turn's end and no prompt since, or working has held for
|
|
613
|
+
SECONDS_BEFORE_CLAUDE_CODES_OWN_IDLE_COUNTS_OVER_WORKING since iTerm2's value changed and
|
|
614
|
+
since the last prompt the hooks reported (Claude Code's own report may lag a new turn's
|
|
615
|
+
start; code review, 2026-10-28). iTerm2's Claude Code integration set working again after
|
|
616
|
+
turns that had ended with nothing running, which left their rows "stuck" (user report,
|
|
617
|
+
2026-10-28; what set it isn't known). Claude Code says "shell" while a command runs and
|
|
618
|
+
"busy" while a Stop hook keeps the turn going, so neither ends here. False when Claude
|
|
619
|
+
Code reports nothing (another tool)."""
|
|
620
|
+
process_id = agent_session["process_id"]
|
|
621
|
+
claude_agent_record = self.claude_agents_by_process_id.get(process_id)
|
|
622
|
+
if claude_agent_record is None:
|
|
623
|
+
return False
|
|
624
|
+
# No time is passed for iTerm2's value: it may have been set after the turn's end.
|
|
625
|
+
hooks_report_the_turn_over = find_when_the_hooks_ended_the_turn(
|
|
626
|
+
self.hook_state_by_agent_process_id.get(process_id), float("-inf")) is not None
|
|
627
|
+
if not hooks_report_the_turn_over and seconds_working_has_held < SECONDS_BEFORE_CLAUDE_CODES_OWN_IDLE_COUNTS_OVER_WORKING:
|
|
628
|
+
return False
|
|
629
|
+
return read_claude_code_session_status(claude_agent_record.get("config_folder"), process_id) == "idle"
|
|
630
|
+
|
|
631
|
+
def claude_code_reports_the_turn_going_on(self, agent_session):
|
|
632
|
+
"""Whether Claude Code's own report of the session (read_claude_code_session_status) says
|
|
633
|
+
its turn goes on after the Stop its hooks reported: another Stop hook (Claude Code's goal
|
|
634
|
+
feature) can block a Stop, and iTerm2's value then says working all along (code review,
|
|
635
|
+
2026-10-28). That is "busy" or "waiting", or "shell" while none of its background tasks
|
|
636
|
+
runs, so the command is the turn's own: while one runs after the turn ended, Claude Code
|
|
637
|
+
says "shell" too. False when Claude Code reports nothing (another tool)."""
|
|
638
|
+
process_id = agent_session["process_id"]
|
|
639
|
+
claude_agent_record = self.claude_agents_by_process_id.get(process_id)
|
|
640
|
+
if claude_agent_record is None:
|
|
641
|
+
return False
|
|
642
|
+
status = read_claude_code_session_status(claude_agent_record.get("config_folder"), process_id)
|
|
643
|
+
background_task_ids = (self.hook_state_by_agent_process_id.get(process_id) or {}).get("background_task_ids")
|
|
644
|
+
return status in ("busy", "waiting") or (status == "shell" and background_task_ids == set())
|
|
645
|
+
|
|
646
|
+
def codex_conversation_may_be_another_sessions(self, session_id, agent_session):
|
|
647
|
+
"""Whether this Codex agent session shares its folder with another Codex agent session, or
|
|
648
|
+
did while its process has run (remember_codex_sessions_that_share_a_folder). Codex's
|
|
649
|
+
conversation files are matched to a process by folder and start time only
|
|
650
|
+
(find_codex_conversation_files), so the earlier of two such sessions would take the later
|
|
651
|
+
one's file for its own, also after the later one ended, since its file stays."""
|
|
652
|
+
return isinstance(agent_session["adapter"], CodexAdapter) and (
|
|
653
|
+
agent_session["process_id"] in self.codex_process_ids_that_shared_their_folder
|
|
654
|
+
or any(other_session_id != session_id and isinstance(other_agent_session["adapter"], CodexAdapter)
|
|
655
|
+
and other_agent_session["working_folder"] == agent_session["working_folder"]
|
|
656
|
+
for other_session_id, other_agent_session in self.agent_sessions.items()))
|
|
657
|
+
|
|
658
|
+
def remember_codex_sessions_that_share_a_folder(self):
|
|
659
|
+
"""Notes the process of each Codex agent session that shares its folder with another, for
|
|
660
|
+
codex_conversation_may_be_another_sessions, and forgets the processes no longer listed."""
|
|
661
|
+
codex_process_ids_by_folder = {}
|
|
662
|
+
for agent_session in self.agent_sessions.values():
|
|
663
|
+
if isinstance(agent_session["adapter"], CodexAdapter) and agent_session["process_id"]:
|
|
664
|
+
codex_process_ids_by_folder.setdefault(agent_session["working_folder"], set()).add(agent_session["process_id"])
|
|
665
|
+
self.codex_process_ids_that_shared_their_folder &= set().union(*codex_process_ids_by_folder.values())
|
|
666
|
+
for process_ids in codex_process_ids_by_folder.values():
|
|
667
|
+
if len(process_ids) >= 2:
|
|
668
|
+
self.codex_process_ids_that_shared_their_folder |= process_ids
|
|
669
|
+
|
|
670
|
+
def conversation_was_cleared_and_the_next_has_no_file_yet(self, session_id):
|
|
671
|
+
"""Whether /clear ended the agent session's conversation and the agent hasn't written its
|
|
672
|
+
next one yet: a lookup by folder and start time would still find the ended one."""
|
|
673
|
+
conversation_file = self.conversation_files_by_session_id.get(session_id) or {}
|
|
674
|
+
return bool(conversation_file.get("cleared_path")) and conversation_file["path"] is None
|
|
675
|
+
|
|
676
|
+
async def find_current_conversation_file(self, session_id, agent_session):
|
|
677
|
+
"""Returns the path of the agent session's conversation file: the one last found for its
|
|
678
|
+
current conversation, else looked up now; or None."""
|
|
679
|
+
conversation_file = self.conversation_files_by_session_id.get(session_id)
|
|
680
|
+
if (conversation_file is not None and conversation_file["path"] is not None
|
|
681
|
+
and conversation_file["key"] == self.find_conversation_key(agent_session)):
|
|
682
|
+
return conversation_file["path"]
|
|
683
|
+
return await self.look_up_conversation_file(session_id, agent_session)
|
|
684
|
+
|
|
685
|
+
def forget_the_cleared_conversation(self, session_id, agent_session, cleared_path):
|
|
686
|
+
"""After /clear: the old conversation's size and preview no longer apply, and its finished
|
|
687
|
+
turn no longer waits to be seen. Its file (cleared_path) is ignored until the agent writes
|
|
688
|
+
a new one: Codex keeps its process and starts the new chat's file only with its first
|
|
689
|
+
prompt, so looking the file up again finds the old one. Claude Code's new session ID is
|
|
690
|
+
asked for at the gather that follows this action."""
|
|
691
|
+
conversation_file = self.conversation_files_by_session_id.setdefault(session_id, build_conversation_file_record(
|
|
692
|
+
self.find_conversation_key(agent_session), None, time.time(), None))
|
|
693
|
+
conversation_file.update(path=None, modified_at=None, cleared_path=cleared_path or conversation_file["cleared_path"])
|
|
694
|
+
self.forget_conversation_file_readings(session_id)
|
|
695
|
+
if session_id in self.session_tracking_by_session_id:
|
|
696
|
+
# The finished turn no longer waits to be seen; the tab itself wasn't seen, so its seen time stays.
|
|
697
|
+
self.session_tracking_by_session_id[session_id]["finished_turn_cleared_at"] = time.time()
|
|
698
|
+
self.process_ids_asked_about_in_claude_agents.discard(agent_session["process_id"])
|
|
699
|
+
|
|
700
|
+
async def handle_end_agent_process(self, action_request):
|
|
701
|
+
"""Ends a tab's agent process ("Kill Session"; the tab and its shell stay): SIGTERM, then
|
|
702
|
+
SIGCONT so an agent suspended with Ctrl+Z wakes up to handle it (as a shell's kill does
|
|
703
|
+
for a stopped job), also for the stopped processes below a paused agent, and SIGKILL if it
|
|
704
|
+
is still running SECONDS_AN_AGENT_GETS_TO_END_BEFORE_IT_IS_KILLED later."""
|
|
705
|
+
agent_session = self.agent_sessions.get(action_request.target["session_id"])
|
|
706
|
+
if agent_session is None or not agent_session["process_id"]:
|
|
707
|
+
return ActionResult(False, "that tab no longer runs an agent")
|
|
708
|
+
process_id = agent_session["process_id"]
|
|
709
|
+
self.process_ids_ended_from_the_list.add(process_id) # its row goes, rather than show "exited"
|
|
710
|
+
# Listed first: once the agent ends, the processes below it are no longer its descendants.
|
|
711
|
+
stopped_process_ids_below = [process.process_id for process in list_descendant_processes(process_id, maximum_depth=None)
|
|
712
|
+
if process_is_stopped(process.process_id)]
|
|
713
|
+
try:
|
|
714
|
+
os.kill(process_id, signal.SIGTERM)
|
|
715
|
+
os.kill(process_id, signal.SIGCONT)
|
|
716
|
+
except ProcessLookupError:
|
|
717
|
+
return ActionResult(True) # it had ended already
|
|
718
|
+
send_signal_to_processes(stopped_process_ids_below, signal.SIGCONT) # a paused session's: none stays stopped
|
|
719
|
+
deadline = time.time() + SECONDS_AN_AGENT_GETS_TO_END_BEFORE_IT_IS_KILLED
|
|
720
|
+
while time.time() < deadline:
|
|
721
|
+
await asyncio.sleep(0.2)
|
|
722
|
+
if not process_is_alive(process_id):
|
|
723
|
+
return ActionResult(True)
|
|
724
|
+
try:
|
|
725
|
+
os.kill(process_id, signal.SIGKILL)
|
|
726
|
+
except ProcessLookupError:
|
|
727
|
+
pass
|
|
728
|
+
return ActionResult(True)
|
|
729
|
+
|
|
730
|
+
async def handle_end_agent_processes(self, action_request):
|
|
731
|
+
"""end_agent_process for every session of target {"session_ids": [...]} (the menu of
|
|
732
|
+
several selected rows; user request, 2026-10-21)."""
|
|
733
|
+
return await self.run_for_each_agent_session(action_request, self.handle_end_agent_process)
|
|
734
|
+
|
|
735
|
+
async def handle_pause_agent_sessions(self, action_request):
|
|
736
|
+
"""Pauses the agent sessions of target {"session_ids": [...]}: each agent as Ctrl+Z does,
|
|
737
|
+
and every process below it (agent_session_pausing; user request, 2026-10-20)."""
|
|
738
|
+
|
|
739
|
+
async def pause_one(session_id, agent_session, session):
|
|
740
|
+
agent_process_id = agent_session["process_id"]
|
|
741
|
+
# Ctrl+Z goes to the agent only while its group has the terminal (asked of the kernel)
|
|
742
|
+
# and no other program, such as the editor Claude Code's Ctrl+G opens in the agent's
|
|
743
|
+
# own group, is in front. iTerm2 still names the shell in front for a while after fg,
|
|
744
|
+
# so a shell there doesn't count.
|
|
745
|
+
if not process_is_stopped(agent_process_id) and (
|
|
746
|
+
not process_has_its_terminal(agent_process_id)
|
|
747
|
+
or (agent_session["is_in_background"]
|
|
748
|
+
and not command_line_runs_a_shell(self.find_command_line_of_the_session(session_id)))):
|
|
749
|
+
return ActionResult(False, "another program is in front of the agent")
|
|
750
|
+
if (session_id, agent_process_id) in self.pause_record_by_tab_and_agent:
|
|
751
|
+
return ActionResult(True) # paused already (a new record would lose the prompt seen then)
|
|
752
|
+
action_result, pause_record = await pause_agent_session(session, agent_process_id, agent_session["agent_tool_name"])
|
|
753
|
+
if pause_record is not None:
|
|
754
|
+
self.pause_record_by_tab_and_agent[(session_id, agent_process_id)] = pause_record
|
|
755
|
+
self.save_pause_records()
|
|
756
|
+
return action_result
|
|
757
|
+
return await self.pause_or_resume_each_agent_session(action_request.target["session_ids"], pause_one)
|
|
758
|
+
|
|
759
|
+
async def handle_resume_agent_sessions(self, action_request):
|
|
760
|
+
"""Resumes the paused agent sessions of target {"session_ids": [...]}; one suspended with
|
|
761
|
+
Ctrl+Z by hand gets an explanation instead, since no pause recorded its prompt."""
|
|
762
|
+
|
|
763
|
+
async def resume_one(session_id, agent_session, session):
|
|
764
|
+
tab_and_agent = (session_id, agent_session["process_id"])
|
|
765
|
+
action_result = await resume_agent_session(session, agent_session["process_id"],
|
|
766
|
+
self.pause_record_by_tab_and_agent.get(tab_and_agent))
|
|
767
|
+
if action_result.succeeded and self.pause_record_by_tab_and_agent.pop(tab_and_agent, None) is not None:
|
|
768
|
+
self.save_pause_records()
|
|
769
|
+
return action_result
|
|
770
|
+
return await self.pause_or_resume_each_agent_session(action_request.target["session_ids"], resume_one)
|
|
771
|
+
|
|
772
|
+
async def pause_or_resume_each_agent_session(self, session_ids, pause_or_resume_one):
|
|
773
|
+
"""Runs pause_or_resume_one(session_id, agent_session, session) for every session at once,
|
|
774
|
+
each holding its tab's typing lock, as every typing into a tab does: its Ctrl+Z or fg can't
|
|
775
|
+
come between a held message's paste and its Enter (code review, 2026-10-28). Returns one
|
|
776
|
+
ActionResult whose message names each tab that failed and why."""
|
|
777
|
+
|
|
778
|
+
async def run_for(session_id):
|
|
779
|
+
agent_session = self.agent_sessions.get(session_id)
|
|
780
|
+
session = self.app.get_session_by_id(session_id)
|
|
781
|
+
if agent_session is None or not agent_session["process_id"] or session is None:
|
|
782
|
+
return ActionResult(False, "that tab no longer runs an agent")
|
|
783
|
+
if session_id in self.session_ids_being_paused_or_resumed:
|
|
784
|
+
# A second click while the first is under way (both could see the same empty prompt and type fg twice).
|
|
785
|
+
return ActionResult(True)
|
|
786
|
+
self.session_ids_being_paused_or_resumed.add(session_id)
|
|
787
|
+
try:
|
|
788
|
+
async with self.message_typing_lock_by_session_id.setdefault(session_id, asyncio.Lock()):
|
|
789
|
+
return await pause_or_resume_one(session_id, agent_session, session)
|
|
790
|
+
except iterm2.RPCException:
|
|
791
|
+
return ActionResult(False, "the tab closed meanwhile")
|
|
792
|
+
finally:
|
|
793
|
+
self.session_ids_being_paused_or_resumed.discard(session_id)
|
|
794
|
+
action_results = await asyncio.gather(*(run_for(session_id) for session_id in session_ids))
|
|
795
|
+
return self.combine_results_naming_the_tabs_that_failed(session_ids, action_results)
|
|
796
|
+
|
|
797
|
+
# ----- Talk to Each Other (user request, 2026-10-21) -----
|
|
798
|
+
|
|
799
|
+
async def handle_ask_agent_sessions_to_talk_to_each_other(self, action_request):
|
|
800
|
+
"""Sends the agent sessions of target {"session_ids": [...]} that arguments
|
|
801
|
+
{"recipient_session_ids": [...]} name (all of them when it is left out; one chosen in the
|
|
802
|
+
Talk to Each Other window, user request, 2026-10-28) the note of arguments {"note": ...},
|
|
803
|
+
followed by what each needs to send every other one of the sessions a message
|
|
804
|
+
(messages_between_agent_sessions). A Codex session gets it through `codex queue`, which it
|
|
805
|
+
runs after any turn under way. A Claude Code session has no supported way in from outside,
|
|
806
|
+
so its message is held until the session waits at its prompt with an empty input box, then
|
|
807
|
+
pasted there, giving up after SECONDS_A_MESSAGE_WAITS_FOR_AN_AGENT_AT_ITS_PROMPT. Returns
|
|
808
|
+
once every message was delivered or given up on, naming each tab that didn't get one, and
|
|
809
|
+
each session that couldn't take part."""
|
|
810
|
+
session_ids = action_request.target["session_ids"]
|
|
811
|
+
recipient_session_ids = action_request.arguments.get("recipient_session_ids") or session_ids
|
|
812
|
+
agent_session_for_messages_by_session_id = {}
|
|
813
|
+
action_result_by_session_id = {}
|
|
814
|
+
for session_id in session_ids:
|
|
815
|
+
agent_session_for_messages, reason = await self.describe_agent_session_for_messages(session_id)
|
|
816
|
+
if agent_session_for_messages is None:
|
|
817
|
+
action_result_by_session_id[session_id] = ActionResult(False, reason)
|
|
818
|
+
else:
|
|
819
|
+
agent_session_for_messages_by_session_id[session_id] = agent_session_for_messages
|
|
820
|
+
if len(agent_session_for_messages_by_session_id) < 2:
|
|
821
|
+
for session_id in agent_session_for_messages_by_session_id:
|
|
822
|
+
action_result_by_session_id[session_id] = ActionResult(False, "no other selected session can take part")
|
|
823
|
+
else:
|
|
824
|
+
delivered_session_ids = [session_id for session_id in agent_session_for_messages_by_session_id
|
|
825
|
+
if session_id in recipient_session_ids]
|
|
826
|
+
agent_sessions_that_get_the_message = [agent_session_for_messages_by_session_id[session_id]
|
|
827
|
+
for session_id in delivered_session_ids]
|
|
828
|
+
delivery_results = await asyncio.gather(*(
|
|
829
|
+
self.deliver_message_to_agent_session(
|
|
830
|
+
session_id, agent_session_for_messages_by_session_id[session_id],
|
|
831
|
+
build_message_asking_agent_session_to_talk_to_the_others(
|
|
832
|
+
action_request.arguments["note"], agent_session_for_messages_by_session_id[session_id],
|
|
833
|
+
[other for other_session_id, other in agent_session_for_messages_by_session_id.items()
|
|
834
|
+
if other_session_id != session_id], agent_sessions_that_get_the_message))
|
|
835
|
+
for session_id in delivered_session_ids), return_exceptions=True)
|
|
836
|
+
for session_id, delivery_result in zip(delivered_session_ids, delivery_results):
|
|
837
|
+
action_result_by_session_id[session_id] = convert_exception_to_action_result(delivery_result)
|
|
838
|
+
# A session that only appears in the others' messages has a result only when it couldn't take part.
|
|
839
|
+
reported_session_ids = [session_id for session_id in session_ids if session_id in action_result_by_session_id]
|
|
840
|
+
return self.combine_results_naming_the_tabs_that_failed(
|
|
841
|
+
reported_session_ids, [action_result_by_session_id[session_id] for session_id in reported_session_ids])
|
|
842
|
+
|
|
843
|
+
async def describe_agent_session_for_messages(self, session_id):
|
|
844
|
+
"""Returns (AgentSessionForMessages, None) for an agent session that other sessions can
|
|
845
|
+
send messages to, else (None, the reason it can't take part)."""
|
|
846
|
+
agent_session = self.agent_sessions.get(session_id)
|
|
847
|
+
if agent_session is None or not agent_session["process_id"]:
|
|
848
|
+
return None, "that tab no longer runs an agent"
|
|
849
|
+
process_id = agent_session["process_id"]
|
|
850
|
+
how_other_agent_sessions_send_it_messages = agent_session["adapter"].how_other_agent_sessions_send_it_messages
|
|
851
|
+
if how_other_agent_sessions_send_it_messages == MESSAGES_THROUGH_THE_SEND_MESSAGE_TOOL:
|
|
852
|
+
address = (self.claude_agents_by_process_id.get(process_id) or {}).get("name")
|
|
853
|
+
reason_without_address = "its Claude Code session name isn't known yet"
|
|
854
|
+
elif how_other_agent_sessions_send_it_messages == MESSAGES_THROUGH_CODEX_QUEUE:
|
|
855
|
+
if self.conversation_was_cleared_and_the_next_has_no_file_yet(session_id):
|
|
856
|
+
return None, "its conversation was just cleared, and its next one starts at its next prompt"
|
|
857
|
+
if self.codex_conversation_may_be_another_sessions(session_id, agent_session):
|
|
858
|
+
return None, "another Codex session runs or ran in the same folder, so its conversation can't be told apart"
|
|
859
|
+
address = await agent_session["adapter"].find_conversation_id(process_id, None)
|
|
860
|
+
reason_without_address = ("its Codex conversation can't be identified: Codex starts it at the first prompt, "
|
|
861
|
+
"and after /new more than one fits")
|
|
862
|
+
else:
|
|
863
|
+
return None, f"{agent_session['agent_tool_name']} sessions can't take messages from other sessions"
|
|
864
|
+
if not address:
|
|
865
|
+
return None, reason_without_address
|
|
866
|
+
return AgentSessionForMessages(agent_session["agent_tool_name"], how_other_agent_sessions_send_it_messages, address,
|
|
867
|
+
process_id, agent_session["working_folder"],
|
|
868
|
+
self.find_tab_title_of_agent_session(session_id)), None
|
|
869
|
+
|
|
870
|
+
async def deliver_message_to_agent_session(self, session_id, agent_session_for_messages, message):
|
|
871
|
+
"""Queues the message for a Codex session, or pastes it into a Claude Code session once it waits at its prompt."""
|
|
872
|
+
if agent_session_for_messages.how_other_agent_sessions_send_it_messages == MESSAGES_THROUGH_CODEX_QUEUE:
|
|
873
|
+
return await queue_message_for_codex_session(self.codex_command_path, agent_session_for_messages.address, message)
|
|
874
|
+
return await self.paste_message_once_the_agent_waits_at_its_prompt(session_id, agent_session_for_messages.process_id, message)
|
|
875
|
+
|
|
876
|
+
async def paste_message_once_the_agent_waits_at_its_prompt(self, session_id, agent_process_id, message):
|
|
877
|
+
"""Checks every SECONDS_BETWEEN_CHECKS_FOR_AN_AGENT_AT_ITS_PROMPT until the agent session
|
|
878
|
+
waits at its prompt (its row shows idle or done) with an empty input box, then pastes the
|
|
879
|
+
message there and presses Enter. Gives up after
|
|
880
|
+
SECONDS_A_MESSAGE_WAITS_FOR_AN_AGENT_AT_ITS_PROMPT, or once the tab's agent process is no
|
|
881
|
+
longer agent_process_id."""
|
|
882
|
+
deadline = time.time() + SECONDS_A_MESSAGE_WAITS_FOR_AN_AGENT_AT_ITS_PROMPT
|
|
883
|
+
typing_lock = self.message_typing_lock_by_session_id.setdefault(session_id, asyncio.Lock())
|
|
884
|
+
while True:
|
|
885
|
+
# Checked holding the lock: another message held for this session may have just
|
|
886
|
+
# been pasted, starting a turn.
|
|
887
|
+
async with typing_lock:
|
|
888
|
+
agent_session = self.agent_sessions.get(session_id)
|
|
889
|
+
if agent_session is None or agent_session["process_id"] != agent_process_id:
|
|
890
|
+
return ActionResult(False, "its agent ended before the message could be pasted")
|
|
891
|
+
if not agent_session["is_in_background"] and self.agent_waits_at_its_prompt(session_id, agent_session):
|
|
892
|
+
try:
|
|
893
|
+
action_result = await iterm2_actions.paste_message_into_empty_input_box(
|
|
894
|
+
self.app, session_id, message, agent_session["adapter"])
|
|
895
|
+
except iterm2.RPCException:
|
|
896
|
+
return ActionResult(False, "the tab closed meanwhile")
|
|
897
|
+
if action_result is not None:
|
|
898
|
+
return action_result
|
|
899
|
+
if time.time() >= deadline:
|
|
900
|
+
return ActionResult(False, "it didn't wait at its prompt with an empty input box within "
|
|
901
|
+
f"{SECONDS_A_MESSAGE_WAITS_FOR_AN_AGENT_AT_ITS_PROMPT // 60} minutes, "
|
|
902
|
+
"so the message wasn't pasted")
|
|
903
|
+
await asyncio.sleep(SECONDS_BETWEEN_CHECKS_FOR_AN_AGENT_AT_ITS_PROMPT)
|
|
904
|
+
|
|
905
|
+
def set_reserved_screen_area(self, reserved_area):
|
|
906
|
+
"""Receives the docked sidebar's area, {"frame": (x, y, width, height), "edge": "right" or
|
|
907
|
+
"left", "monitor_visible_frame": (...)}, or None when docking ends; kept until iTerm2 is
|
|
908
|
+
connected if it arrives earlier."""
|
|
909
|
+
asyncio.ensure_future(self.change_reserved_screen_area(reserved_area))
|
|
910
|
+
|
|
911
|
+
async def change_reserved_screen_area(self, new_reserved_area):
|
|
912
|
+
"""Gives the room back for the old area, then makes room for the new one, holding the
|
|
913
|
+
lock so a regather can't resize windows in between. Before the first gather it only
|
|
914
|
+
keeps the area, which make_room_for_reserved_area then applies: the saved frames of
|
|
915
|
+
windows iTerm2 restored after a restart can be matched to them only once they are
|
|
916
|
+
gathered, and giving room back earlier would drop those records (code review, 2026-10-28)."""
|
|
917
|
+
async with self.window_room_lock:
|
|
918
|
+
self.reserved_area_was_received = True
|
|
919
|
+
if new_reserved_area == self.reserved_screen_area:
|
|
920
|
+
if new_reserved_area is None and self.windows_were_gathered and self.frames_before_making_room_by_window_id:
|
|
921
|
+
await self.give_room_back_while_holding_the_lock() # restores still pending from before
|
|
922
|
+
return
|
|
923
|
+
if self.windows_were_gathered:
|
|
924
|
+
await self.give_room_back_while_holding_the_lock() # both handle each window's errors themselves
|
|
925
|
+
self.reserved_screen_area = new_reserved_area
|
|
926
|
+
if self.windows_were_gathered:
|
|
927
|
+
await self.make_room_while_holding_the_lock()
|
|
928
|
+
|
|
929
|
+
async def make_room_for_reserved_area(self):
|
|
930
|
+
"""After each gather: while docked, narrows (or moves) iTerm2 windows that reach into the
|
|
931
|
+
reserved area; while not, retries restores still pending (after a restart with docking
|
|
932
|
+
off, or a window that was full screen when docking ended). Pending restores wait until
|
|
933
|
+
the main thread has said whether the sidebar is docked, so a docked start doesn't widen
|
|
934
|
+
windows only to narrow them again."""
|
|
935
|
+
async with self.window_room_lock:
|
|
936
|
+
if self.reserved_screen_area is not None:
|
|
937
|
+
await self.make_room_while_holding_the_lock()
|
|
938
|
+
elif self.reserved_area_was_received and self.frames_before_making_room_by_window_id:
|
|
939
|
+
await self.give_room_back_while_holding_the_lock()
|
|
940
|
+
|
|
941
|
+
async def make_room_while_holding_the_lock(self):
|
|
942
|
+
"""Narrows or moves each window that reaches into the reserved area, remembering its frame
|
|
943
|
+
so it can get the room back. Full-screen windows are left alone (they have their own desktop).
|
|
944
|
+
|
|
945
|
+
Frames are read fresh, since with one monitor nothing polls them before docking starts.
|
|
946
|
+
A window that was moved or resized by hand since it was last made room for gets that
|
|
947
|
+
frame as the one to restore. A window that closes meanwhile is skipped.
|
|
948
|
+
"""
|
|
949
|
+
if self.reserved_screen_area is None:
|
|
950
|
+
return
|
|
951
|
+
self.adopt_records_of_restored_windows()
|
|
952
|
+
for gathered_window in self.gathered_windows:
|
|
953
|
+
window = self.app.get_window_by_id(gathered_window["window_id"])
|
|
954
|
+
if window is None:
|
|
955
|
+
continue
|
|
956
|
+
try:
|
|
957
|
+
current_frame = await read_window_frame(window)
|
|
958
|
+
gathered_window["frame"] = current_frame
|
|
959
|
+
new_frame = compute_frame_clear_of_area(
|
|
960
|
+
current_frame, self.reserved_screen_area["frame"], self.reserved_screen_area["edge"],
|
|
961
|
+
self.reserved_screen_area["monitor_visible_frame"], SMALLEST_WINDOW_WIDTH)
|
|
962
|
+
if new_frame is None or await window.async_get_fullscreen():
|
|
963
|
+
continue
|
|
964
|
+
original_frame, frame_that_was_set = self.frames_before_making_room_by_window_id.get(
|
|
965
|
+
window.window_id, (current_frame, None))
|
|
966
|
+
if frame_that_was_set is not None and not frames_are_within_tolerance(
|
|
967
|
+
current_frame, frame_that_was_set, FRAME_TOLERANCE_POINTS):
|
|
968
|
+
original_frame = current_frame # moved or resized by hand since
|
|
969
|
+
await window.async_set_frame(iterm2.Frame(iterm2.Point(new_frame[0], new_frame[1]),
|
|
970
|
+
iterm2.Size(new_frame[2], new_frame[3])))
|
|
971
|
+
self.frames_before_making_room_by_window_id[window.window_id] = (original_frame, new_frame)
|
|
972
|
+
gathered_window["frame"] = new_frame
|
|
973
|
+
except (iterm2.RPCException, iterm2.GetPropertyException, iterm2.SetPropertyException) as error:
|
|
974
|
+
print(f"could not make room for the docked sidebar in window {gathered_window['window_id']}: {error!r}")
|
|
975
|
+
self.save_docked_window_frames()
|
|
976
|
+
|
|
977
|
+
async def give_room_back_while_holding_the_lock(self):
|
|
978
|
+
"""Restores the windows narrowed for a docked sidebar, unless the user moved or resized
|
|
979
|
+
them since, and updates the cached frames so the next layout starts from the real ones.
|
|
980
|
+
|
|
981
|
+
A window that is full screen, or whose restore fails, stays remembered, so it can still
|
|
982
|
+
be restored when a later docking ends. Records of windows that are gone are dropped.
|
|
983
|
+
"""
|
|
984
|
+
self.adopt_records_of_restored_windows()
|
|
985
|
+
gathered_windows_by_window_id = {gathered_window["window_id"]: gathered_window for gathered_window in self.gathered_windows}
|
|
986
|
+
for window_id, (original_frame, frame_that_was_set) in list(self.frames_before_making_room_by_window_id.items()):
|
|
987
|
+
window = self.app.get_window_by_id(window_id)
|
|
988
|
+
if window is None:
|
|
989
|
+
del self.frames_before_making_room_by_window_id[window_id]
|
|
990
|
+
continue
|
|
991
|
+
try:
|
|
992
|
+
if await window.async_get_fullscreen():
|
|
993
|
+
continue # its own desktop shows a full-screen frame; it returns to the narrowed one later
|
|
994
|
+
current_frame = await read_window_frame(window)
|
|
995
|
+
if frames_are_within_tolerance(current_frame, frame_that_was_set, FRAME_TOLERANCE_POINTS):
|
|
996
|
+
await window.async_set_frame(iterm2.Frame(iterm2.Point(original_frame[0], original_frame[1]),
|
|
997
|
+
iterm2.Size(original_frame[2], original_frame[3])))
|
|
998
|
+
current_frame = original_frame
|
|
999
|
+
except (iterm2.RPCException, iterm2.GetPropertyException, iterm2.SetPropertyException) as error:
|
|
1000
|
+
print(f"could not give window {window_id} its room back: {error!r}")
|
|
1001
|
+
continue
|
|
1002
|
+
del self.frames_before_making_room_by_window_id[window_id]
|
|
1003
|
+
if window_id in gathered_windows_by_window_id:
|
|
1004
|
+
gathered_windows_by_window_id[window_id]["frame"] = current_frame
|
|
1005
|
+
self.save_docked_window_frames()
|
|
1006
|
+
|
|
1007
|
+
def adopt_records_of_restored_windows(self):
|
|
1008
|
+
"""On the first pass after start-up, moves frames remembered from the file for windows
|
|
1009
|
+
that are gone to windows iTerm2 restored after a restart, which get new IDs but keep the
|
|
1010
|
+
narrowed frame. Later, the records of windows that closed are dropped instead, so a new
|
|
1011
|
+
window of the same size never takes over a closed window's record."""
|
|
1012
|
+
if not self.gathered_windows:
|
|
1013
|
+
return
|
|
1014
|
+
if self.records_loaded_from_file_await_adoption:
|
|
1015
|
+
self.records_loaded_from_file_await_adoption = False
|
|
1016
|
+
self.frames_before_making_room_by_window_id = adopt_records_of_restored_windows(
|
|
1017
|
+
self.frames_before_making_room_by_window_id,
|
|
1018
|
+
{gathered_window["window_id"]: gathered_window["frame"] for gathered_window in self.gathered_windows},
|
|
1019
|
+
FRAME_TOLERANCE_POINTS)
|
|
1020
|
+
else:
|
|
1021
|
+
self.frames_before_making_room_by_window_id = {
|
|
1022
|
+
window_id: frames for window_id, frames in self.frames_before_making_room_by_window_id.items()
|
|
1023
|
+
if self.app.get_window_by_id(window_id) is not None}
|
|
1024
|
+
|
|
1025
|
+
def save_docked_window_frames(self):
|
|
1026
|
+
"""Writes the remembered frames to their file when they changed since the last write."""
|
|
1027
|
+
if not self.docked_window_frames_file_path or self.frames_before_making_room_by_window_id == self.saved_docked_window_frames:
|
|
1028
|
+
return
|
|
1029
|
+
try:
|
|
1030
|
+
save_docked_window_frames(self.docked_window_frames_file_path, self.frames_before_making_room_by_window_id)
|
|
1031
|
+
self.saved_docked_window_frames = dict(self.frames_before_making_room_by_window_id)
|
|
1032
|
+
except OSError as error:
|
|
1033
|
+
print(f"could not save the docked windows' frames: {error!r}")
|
|
1034
|
+
|
|
1035
|
+
async def handle_peek_agent_session(self, action_request):
|
|
1036
|
+
"""Press and hold on a tab row: shows the tab, first remembering what to put back."""
|
|
1037
|
+
async with self.peek_lock:
|
|
1038
|
+
current_window = self.app.current_terminal_window
|
|
1039
|
+
self.iterm2_state_before_peek = {
|
|
1040
|
+
# The App's current window, not the key window: while the dropdown is open the
|
|
1041
|
+
# dashboard is active and no iTerm2 window is key.
|
|
1042
|
+
"key_window_id": current_window.window_id if current_window is not None else None,
|
|
1043
|
+
"selected_tab_id_by_window_id": {window.window_id: window.current_tab.tab_id
|
|
1044
|
+
for window in self.app.terminal_windows if window.current_tab is not None},
|
|
1045
|
+
}
|
|
1046
|
+
return await iterm2_actions.focus_agent_session(self.app, action_request.target["session_id"])
|
|
1047
|
+
|
|
1048
|
+
async def handle_end_peek(self, action_request):
|
|
1049
|
+
"""The button was released: arguments {"bring_back_iterm2_window": bool}, true when iTerm2
|
|
1050
|
+
was in front before the peek (otherwise the main thread brings back the app that was)."""
|
|
1051
|
+
async with self.peek_lock:
|
|
1052
|
+
state, self.iterm2_state_before_peek = self.iterm2_state_before_peek, None
|
|
1053
|
+
if state is None:
|
|
1054
|
+
return ActionResult(False, "no peek to end")
|
|
1055
|
+
return await iterm2_actions.put_back_tabs_and_window_after_peek(
|
|
1056
|
+
self.app, state["selected_tab_id_by_window_id"],
|
|
1057
|
+
state["key_window_id"] if action_request.arguments["bring_back_iterm2_window"] else None)
|
|
1058
|
+
|
|
1059
|
+
async def handle_duplicate_agent_session(self, action_request):
|
|
1060
|
+
"""Target {"tab_id": ...}; arguments {"folder": ..., "launch_command": ...}. The copy continues
|
|
1061
|
+
a copy of the conversation when the agent tool can fork it, else it starts fresh."""
|
|
1062
|
+
session_id = self.find_first_session_id_of_tab(action_request.target["tab_id"])
|
|
1063
|
+
agent_session = self.agent_sessions.get(session_id)
|
|
1064
|
+
if agent_session is None:
|
|
1065
|
+
return ActionResult(False, "that tab no longer runs an agent session")
|
|
1066
|
+
process_id = agent_session["process_id"]
|
|
1067
|
+
claude_agent_record = self.claude_agents_by_process_id.get(process_id)
|
|
1068
|
+
conversation_is_shared_with_another_codex_session = self.codex_conversation_may_be_another_sessions(
|
|
1069
|
+
session_id, agent_session)
|
|
1070
|
+
if self.conversation_was_cleared_and_the_next_has_no_file_yet(session_id) or conversation_is_shared_with_another_codex_session:
|
|
1071
|
+
conversation_id = None # start fresh rather than fork a conversation that may not be this session's
|
|
1072
|
+
else:
|
|
1073
|
+
conversation_id = await agent_session["adapter"].find_conversation_id(process_id, claude_agent_record)
|
|
1074
|
+
launch_command_for_the_copy = agent_session["adapter"].build_launch_command_for_a_copy(
|
|
1075
|
+
action_request.arguments["launch_command"], conversation_id, claude_agent_record)
|
|
1076
|
+
action_result = await iterm2_actions.duplicate_agent_session(
|
|
1077
|
+
self.connection, self.app, action_request.target["tab_id"], action_request.arguments["folder"],
|
|
1078
|
+
launch_command_for_the_copy)
|
|
1079
|
+
if action_result.succeeded and conversation_is_shared_with_another_codex_session:
|
|
1080
|
+
return ActionResult(True, "another Codex session runs or ran in the same folder, so its conversation can't be told apart, "
|
|
1081
|
+
"and the copy starts a new conversation")
|
|
1082
|
+
if action_result.succeeded and not conversation_id:
|
|
1083
|
+
return ActionResult(True, "the conversation's ID wasn't found, so the copy starts a new conversation")
|
|
1084
|
+
return action_result
|
|
1085
|
+
|
|
1086
|
+
async def handle_close_window(self, action_request):
|
|
1087
|
+
return await iterm2_actions.close_window(self.app, action_request.target["window_id"])
|
|
1088
|
+
|
|
1089
|
+
async def handle_move_window_to_monitor(self, action_request):
|
|
1090
|
+
return await iterm2_actions.move_window_to_monitor(
|
|
1091
|
+
self.app, action_request.target["window_id"], self.monitors, action_request.arguments["monitor_id"])
|
|
1092
|
+
|
|
1093
|
+
async def handle_reorder_window_list(self, action_request):
|
|
1094
|
+
self.window_order = move_window_in_window_list_order(
|
|
1095
|
+
self.window_order, action_request.target["window_id"], action_request.arguments.get("drop_before_window_id"))
|
|
1096
|
+
return ActionResult(True)
|
|
1097
|
+
|
|
1098
|
+
# ----- messages from the main thread -----
|
|
1099
|
+
|
|
1100
|
+
def set_monitors(self, monitors):
|
|
1101
|
+
"""Receives the monitor rectangles from the main thread (menu-bar monitor first)."""
|
|
1102
|
+
self.monitors = list(monitors)
|
|
1103
|
+
self.snapshot_needed.set()
|
|
1104
|
+
|
|
1105
|
+
def set_core_settings(self, core_settings):
|
|
1106
|
+
"""Receives the settings the core uses (settings_store.build_core_settings): the agent
|
|
1107
|
+
tools the Harnesses section leaves out of the list, whether memory and CPU use are read,
|
|
1108
|
+
and the codex program for `codex queue`."""
|
|
1109
|
+
self.left_out_agent_tool_names = frozenset(core_settings["left_out_agent_tool_names"])
|
|
1110
|
+
self.resource_usage_is_read = core_settings["resource_usage_is_read"]
|
|
1111
|
+
self.codex_command_path = core_settings["codex_command_path"]
|
|
1112
|
+
self.snapshot_needed.set()
|
|
1113
|
+
|
|
1114
|
+
def set_dashboard_is_active(self, dashboard_is_active):
|
|
1115
|
+
"""Receives whether the dashboard itself is the active app (then nothing counts as seen)."""
|
|
1116
|
+
self.dashboard_is_active = dashboard_is_active
|
|
1117
|
+
self.record_seen_time_for_the_seen_session()
|
|
1118
|
+
self.snapshot_needed.set()
|
|
1119
|
+
|
|
1120
|
+
# ----- gathering -----
|
|
1121
|
+
|
|
1122
|
+
async def gather_iterm2_tab(self, tab):
|
|
1123
|
+
"""Reads one tab and its first-pane session into a plain dict, one request for each."""
|
|
1124
|
+
first_session = tab.sessions[0] if tab.sessions else None
|
|
1125
|
+
tab_variables_reading = read_iterm2_variables(self.connection, ["title", "titleOverrideFormat"], tab_id=tab.tab_id)
|
|
1126
|
+
gathered_session = None
|
|
1127
|
+
if first_session is None:
|
|
1128
|
+
title, title_override_format = await tab_variables_reading
|
|
1129
|
+
else:
|
|
1130
|
+
(title, title_override_format), (job_pid, command_line, status, path) = await asyncio.gather(
|
|
1131
|
+
tab_variables_reading, read_iterm2_variables(self.connection, ["jobPid", "commandLine", "status", "path"],
|
|
1132
|
+
session_id=first_session.session_id))
|
|
1133
|
+
if not status and command_line and not command_line_runs_a_shell(command_line):
|
|
1134
|
+
# As after iTerm2 restarts: the status its tab bar shows (the variable then takes over).
|
|
1135
|
+
status = await read_status_shown_in_iterm2s_tab_bar(first_session)
|
|
1136
|
+
job_process_id = parse_job_process_id(job_pid)
|
|
1137
|
+
job_process = read_process_info(job_process_id) if job_process_id else None
|
|
1138
|
+
gathered_session = {
|
|
1139
|
+
"session_id": first_session.session_id,
|
|
1140
|
+
"command_line": command_line,
|
|
1141
|
+
"job_pid": job_process_id,
|
|
1142
|
+
"job_folder": read_process_current_folder(job_process_id),
|
|
1143
|
+
"job_started_at": job_process.started_at if job_process is not None else None,
|
|
1144
|
+
"status_set_in_iterm2": status,
|
|
1145
|
+
"status_set_in_iterm2_at": self.status_set_in_iterm2_at_by_session_id.get(first_session.session_id),
|
|
1146
|
+
"status": status, # the one the row goes by (update_session_tracking)
|
|
1147
|
+
"path": path or "",
|
|
1148
|
+
}
|
|
1149
|
+
return {
|
|
1150
|
+
"tab_id": tab.tab_id,
|
|
1151
|
+
"title": title or "",
|
|
1152
|
+
"title_override_format": title_override_format,
|
|
1153
|
+
"first_session": gathered_session,
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
async def gather_iterm2_window(self, window):
|
|
1157
|
+
"""Reads one window and its tabs into a plain dict; a tab that closes meanwhile is left
|
|
1158
|
+
out (and another gather is requested). Raises if the window itself is gone."""
|
|
1159
|
+
|
|
1160
|
+
async def gather_tab_unless_it_closed(tab):
|
|
1161
|
+
try:
|
|
1162
|
+
return await self.gather_iterm2_tab(tab)
|
|
1163
|
+
except iterm2.RPCException:
|
|
1164
|
+
self.regather_needed.set()
|
|
1165
|
+
return None
|
|
1166
|
+
|
|
1167
|
+
frame, (title, title_override_format), *gathered_tabs = await asyncio.gather(
|
|
1168
|
+
read_window_frame(window),
|
|
1169
|
+
read_iterm2_variables(self.connection, ["title", "titleOverrideFormat"], window_id=window.window_id),
|
|
1170
|
+
*(gather_tab_unless_it_closed(tab) for tab in window.tabs))
|
|
1171
|
+
return {
|
|
1172
|
+
"window_id": window.window_id,
|
|
1173
|
+
"frame": frame,
|
|
1174
|
+
"title": title or "",
|
|
1175
|
+
"title_override_format": title_override_format,
|
|
1176
|
+
"tabs": [gathered_tab for gathered_tab in gathered_tabs if gathered_tab is not None],
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
async def gather_iterm2_windows(self):
|
|
1180
|
+
"""Reads every window, tab and first-pane session that the snapshot needs into plain dicts.
|
|
1181
|
+
|
|
1182
|
+
All windows and tabs are read at the same time, so a gather takes about as long as one
|
|
1183
|
+
round trip to iTerm2 rather than one per tab (20 windows with 100 tabs stay quick). A
|
|
1184
|
+
window or tab that closes while it is being read makes iTerm2 answer with an error; it
|
|
1185
|
+
is skipped, and another gather is requested so the list catches up.
|
|
1186
|
+
"""
|
|
1187
|
+
|
|
1188
|
+
async def gather_window_unless_it_closed(window):
|
|
1189
|
+
try:
|
|
1190
|
+
return await self.gather_iterm2_window(window)
|
|
1191
|
+
except (iterm2.RPCException, iterm2.GetPropertyException):
|
|
1192
|
+
self.regather_needed.set()
|
|
1193
|
+
return None
|
|
1194
|
+
|
|
1195
|
+
gathered_windows = await asyncio.gather(*(gather_window_unless_it_closed(window) for window in self.app.terminal_windows))
|
|
1196
|
+
return [gathered_window for gathered_window in gathered_windows if gathered_window is not None]
|
|
1197
|
+
|
|
1198
|
+
def update_session_tracking(self, now):
|
|
1199
|
+
"""Records when each session's status value changed and when its turns start and end, and
|
|
1200
|
+
forgets sessions that are gone. A turn end the tab agent's hooks report counts while
|
|
1201
|
+
iTerm2's value still says working (find_when_the_hooks_ended_the_turn), unless Claude
|
|
1202
|
+
Code's own report says the turn goes on (claude_code_reports_the_turn_going_on), and so
|
|
1203
|
+
does Claude Code's own idle (claude_code_reports_the_turn_over), which ends no turn
|
|
1204
|
+
unless the hooks reported one."""
|
|
1205
|
+
live_session_ids = set()
|
|
1206
|
+
for gathered_window in self.gathered_windows:
|
|
1207
|
+
for gathered_tab in gathered_window["tabs"]:
|
|
1208
|
+
first_session = gathered_tab["first_session"]
|
|
1209
|
+
if first_session is None:
|
|
1210
|
+
continue
|
|
1211
|
+
session_id = first_session["session_id"]
|
|
1212
|
+
live_session_ids.add(session_id)
|
|
1213
|
+
previous_tracking = self.session_tracking_by_session_id.get(session_id)
|
|
1214
|
+
agent_session = self.agent_sessions.get(session_id)
|
|
1215
|
+
if (previous_tracking is not None and not first_session["status_set_in_iterm2"] and agent_session is not None
|
|
1216
|
+
and agent_session["process_id"] and (process_is_stopped(agent_session["process_id"])
|
|
1217
|
+
or first_session.get("job_pid") != agent_session["process_id"])):
|
|
1218
|
+
# Paused (or suspended with Ctrl+Z), or resumed while iTerm2 still sees the shell in
|
|
1219
|
+
# front: the shell has no status, and the agent's turn goes on where it was once it is
|
|
1220
|
+
# back in front, with the commands it started counted.
|
|
1221
|
+
continue
|
|
1222
|
+
status_set_in_iterm2_and_since = self.status_set_in_iterm2_and_since_by_session_id.get(session_id)
|
|
1223
|
+
status_set_in_iterm2_changed = (status_set_in_iterm2_and_since is None
|
|
1224
|
+
or status_set_in_iterm2_and_since[0] != first_session["status_set_in_iterm2"])
|
|
1225
|
+
if status_set_in_iterm2_changed:
|
|
1226
|
+
status_set_in_iterm2_and_since = (first_session["status_set_in_iterm2"], now)
|
|
1227
|
+
self.status_set_in_iterm2_and_since_by_session_id[session_id] = status_set_in_iterm2_and_since
|
|
1228
|
+
first_session["status"] = self.choose_status_value_of_the_tabs_own_agent(
|
|
1229
|
+
session_id, first_session, previous_tracking, status_set_in_iterm2_changed)
|
|
1230
|
+
ends_no_turn = False
|
|
1231
|
+
if agent_session is not None and map_iterm2_status_value_to_state(first_session["status"]) == "working":
|
|
1232
|
+
hook_state = self.hook_state_by_agent_process_id.get(agent_session["process_id"])
|
|
1233
|
+
if (find_when_the_hooks_ended_the_turn(hook_state, status_set_in_iterm2_and_since[1]) is not None
|
|
1234
|
+
and not self.claude_code_reports_the_turn_going_on(agent_session)):
|
|
1235
|
+
first_session["status"] = "idle" # its turn ended, though iTerm2 still says working while a background task runs
|
|
1236
|
+
elif self.claude_code_reports_the_turn_over(agent_session, now - max(
|
|
1237
|
+
status_set_in_iterm2_and_since[1], (hook_state or {}).get("last_prompt_at") or float("-inf"))):
|
|
1238
|
+
first_session["status"] = "idle"
|
|
1239
|
+
# Without a turn end from the hooks, the working it replaces may be one iTerm2 set with
|
|
1240
|
+
# no turn at all (as the app restarted, say), so it ends no turn (code review, 2026-10-28).
|
|
1241
|
+
ends_no_turn = find_when_the_hooks_ended_the_turn(hook_state, float("-inf")) is None
|
|
1242
|
+
tracking = track_status_value(previous_tracking, first_session["status"], now,
|
|
1243
|
+
self.screen_readings_by_session_id.get(session_id), ends_no_turn)
|
|
1244
|
+
self.session_tracking_by_session_id[session_id] = tracking
|
|
1245
|
+
if (previous_tracking is not None and tracking is not previous_tracking
|
|
1246
|
+
and map_iterm2_status_value_to_state(first_session["status"]) == "asking"):
|
|
1247
|
+
self.screen_check_needed.set()
|
|
1248
|
+
for session_id in set(self.session_tracking_by_session_id) - live_session_ids:
|
|
1249
|
+
del self.session_tracking_by_session_id[session_id]
|
|
1250
|
+
for session_id in set(self.iterm2_status_seen_while_an_inner_agent_ran_by_session_id) - live_session_ids:
|
|
1251
|
+
del self.iterm2_status_seen_while_an_inner_agent_ran_by_session_id[session_id]
|
|
1252
|
+
for session_id in set(self.status_set_in_iterm2_and_since_by_session_id) - live_session_ids:
|
|
1253
|
+
del self.status_set_in_iterm2_and_since_by_session_id[session_id]
|
|
1254
|
+
for session_id in set(self.status_set_in_iterm2_at_by_session_id) - live_session_ids:
|
|
1255
|
+
del self.status_set_in_iterm2_at_by_session_id[session_id]
|
|
1256
|
+
|
|
1257
|
+
def choose_status_value_of_the_tabs_own_agent(self, session_id, first_session, previous_tracking, status_set_in_iterm2_changed):
|
|
1258
|
+
"""Returns the status value a tab's row goes by: the one set in iTerm2, except while an agent
|
|
1259
|
+
program runs inside the tab's agent (a `claude -p` its shell tool started, waited on or left
|
|
1260
|
+
running in the background), and after it ends until iTerm2's value fits the tab's agent
|
|
1261
|
+
again. That agent fires the same user-level hooks, so it sets the tab's status too, and its
|
|
1262
|
+
last value stays until the tab's agent sets another (Phase 0).
|
|
1263
|
+
Meanwhile the row goes by the tab's own agent (read_status_value_of_the_tabs_own_agent)
|
|
1264
|
+
and turns back to iTerm2's value once the two agree; for a tool without such a report, it
|
|
1265
|
+
keeps its value until iTerm2's changes after the inner agent ended. The agent's processes
|
|
1266
|
+
are listed only when the value set in iTerm2 changed since the last check
|
|
1267
|
+
(status_set_in_iterm2_changed: not the value the row went by, which a turn end its hooks
|
|
1268
|
+
report can make idle), and while the row goes by its own agent."""
|
|
1269
|
+
status_set_in_iterm2 = first_session["status_set_in_iterm2"]
|
|
1270
|
+
agent_session = self.agent_sessions.get(session_id)
|
|
1271
|
+
status_seen_while_an_inner_agent_ran = self.iterm2_status_seen_while_an_inner_agent_ran_by_session_id
|
|
1272
|
+
if previous_tracking is None or agent_session is None or not agent_session["process_id"]:
|
|
1273
|
+
status_seen_while_an_inner_agent_ran.pop(session_id, None)
|
|
1274
|
+
return status_set_in_iterm2
|
|
1275
|
+
goes_by_its_own_agent = session_id in status_seen_while_an_inner_agent_ran
|
|
1276
|
+
if not goes_by_its_own_agent and not status_set_in_iterm2_changed:
|
|
1277
|
+
return status_set_in_iterm2
|
|
1278
|
+
an_inner_agent_runs = an_agent_program_runs_through_a_shell_below(
|
|
1279
|
+
list_descendant_processes(agent_session["process_id"]), read_name_the_process_was_started_as)
|
|
1280
|
+
if not goes_by_its_own_agent:
|
|
1281
|
+
if not an_inner_agent_runs:
|
|
1282
|
+
return status_set_in_iterm2
|
|
1283
|
+
self.screen_readings_by_session_id.setdefault(session_id, {}).pop("turn_shows_on_screen", None) # an earlier one's
|
|
1284
|
+
self.screen_check_needed.set()
|
|
1285
|
+
own_status_value = self.read_status_value_of_the_tabs_own_agent(session_id, agent_session)
|
|
1286
|
+
if an_inner_agent_runs:
|
|
1287
|
+
status_seen_while_an_inner_agent_ran[session_id] = status_set_in_iterm2
|
|
1288
|
+
elif (status_values_put_the_agent_in_the_same_state(own_status_value, status_set_in_iterm2) if own_status_value
|
|
1289
|
+
else status_set_in_iterm2 != status_seen_while_an_inner_agent_ran[session_id]):
|
|
1290
|
+
del status_seen_while_an_inner_agent_ran[session_id]
|
|
1291
|
+
return status_set_in_iterm2
|
|
1292
|
+
return own_status_value or previous_tracking["status_value"]
|
|
1293
|
+
|
|
1294
|
+
def read_status_value_of_the_tabs_own_agent(self, session_id, agent_session):
|
|
1295
|
+
"""Returns the state of the tab's own agent as an iTerm2 status value, from what no agent
|
|
1296
|
+
inside it writes, or None when its tool reports nothing of the kind: for Claude Code its own
|
|
1297
|
+
report of its session (read_claude_code_session_status); for a tool whose screen shows a
|
|
1298
|
+
turn under way (Codex's "(5s • esc to interrupt)"), the screen check made while the row
|
|
1299
|
+
goes by its own agent ("turn_shows_on_screen")."""
|
|
1300
|
+
process_id = agent_session["process_id"]
|
|
1301
|
+
if isinstance(agent_session["adapter"], ClaudeCodeAdapter):
|
|
1302
|
+
return CLAUDE_CODE_SESSION_STATUSES_TO_ITERM2_STATUS_VALUES.get(read_claude_code_session_status(
|
|
1303
|
+
(self.claude_agents_by_process_id.get(process_id) or {}).get("config_folder"), process_id))
|
|
1304
|
+
turn_shows_on_screen = self.screen_readings_by_session_id.get(session_id, {}).get("turn_shows_on_screen")
|
|
1305
|
+
if turn_shows_on_screen is None:
|
|
1306
|
+
return None
|
|
1307
|
+
return "working" if turn_shows_on_screen else "idle"
|
|
1308
|
+
|
|
1309
|
+
def find_command_line_of_the_session(self, session_id):
|
|
1310
|
+
"""Returns the gathered commandLine of a tab's first-pane session (its foreground job), or ""."""
|
|
1311
|
+
for gathered_window in self.gathered_windows:
|
|
1312
|
+
for gathered_tab in gathered_window["tabs"]:
|
|
1313
|
+
first_session = gathered_tab["first_session"]
|
|
1314
|
+
if first_session and first_session["session_id"] == session_id:
|
|
1315
|
+
return first_session.get("command_line") or ""
|
|
1316
|
+
return ""
|
|
1317
|
+
|
|
1318
|
+
def find_first_session_id_of_tab(self, tab_id):
|
|
1319
|
+
"""Returns the first-pane session ID of a gathered tab, or None."""
|
|
1320
|
+
for gathered_window in self.gathered_windows:
|
|
1321
|
+
for gathered_tab in gathered_window["tabs"]:
|
|
1322
|
+
if gathered_tab["tab_id"] == tab_id and gathered_tab["first_session"]:
|
|
1323
|
+
return gathered_tab["first_session"]["session_id"]
|
|
1324
|
+
return None
|
|
1325
|
+
|
|
1326
|
+
def find_front_tab_id(self):
|
|
1327
|
+
"""Returns the selected tab of iTerm2's current terminal window, as the iterm2 App object
|
|
1328
|
+
tracks it from focus notifications (it ignores windows resigning focus), or None."""
|
|
1329
|
+
current_window = self.app.current_terminal_window
|
|
1330
|
+
if current_window is None or current_window.current_tab is None:
|
|
1331
|
+
return None
|
|
1332
|
+
return current_window.current_tab.tab_id
|
|
1333
|
+
|
|
1334
|
+
def find_seen_session_id(self):
|
|
1335
|
+
"""Returns the session being seen: the front tab's, while iTerm2 (not the dashboard) is active
|
|
1336
|
+
and a terminal window (not, for example, iTerm2's Settings) has keyboard focus."""
|
|
1337
|
+
if self.app is None or not self.app.app_active or self.key_terminal_window_id is None or self.dashboard_is_active:
|
|
1338
|
+
return None # (the main thread can report the dashboard's activity before iTerm2 is connected)
|
|
1339
|
+
return self.find_first_session_id_of_tab(self.find_front_tab_id())
|
|
1340
|
+
|
|
1341
|
+
def find_highlighted_session_id(self):
|
|
1342
|
+
"""Returns the session shown as in front: the front tab's while it is seen, and also
|
|
1343
|
+
while the dashboard itself is active (so the highlight doesn't vanish while you use the
|
|
1344
|
+
list); None while another app is active."""
|
|
1345
|
+
if self.dashboard_is_active or self.find_seen_session_id() is not None:
|
|
1346
|
+
return self.find_first_session_id_of_tab(self.find_front_tab_id())
|
|
1347
|
+
return None
|
|
1348
|
+
|
|
1349
|
+
def record_seen_time_for_the_seen_session(self):
|
|
1350
|
+
"""Stamps "seen until now" on the session that was seen at the last check and on the one
|
|
1351
|
+
seen now. Called with each snapshot and when the dashboard's activity changes, so a tab
|
|
1352
|
+
that stops being seen keeps the time it was last seen, whenever the change is noticed."""
|
|
1353
|
+
now = time.time()
|
|
1354
|
+
seen_session_id = self.find_seen_session_id()
|
|
1355
|
+
for session_id in (self.last_seen_session_id, seen_session_id):
|
|
1356
|
+
if session_id in self.session_tracking_by_session_id:
|
|
1357
|
+
self.session_tracking_by_session_id[session_id]["last_time_tab_was_seen"] = now
|
|
1358
|
+
self.last_seen_session_id = seen_session_id
|
|
1359
|
+
|
|
1360
|
+
async def regather_and_publish(self):
|
|
1361
|
+
"""Re-reads iTerm2 and publishes a snapshot if anything changed."""
|
|
1362
|
+
await self.app.async_refresh()
|
|
1363
|
+
self.gather_is_in_progress = True
|
|
1364
|
+
try:
|
|
1365
|
+
self.gathered_windows = await self.gather_iterm2_windows()
|
|
1366
|
+
self.windows_were_gathered = True
|
|
1367
|
+
finally:
|
|
1368
|
+
self.gather_is_in_progress = False
|
|
1369
|
+
await self.make_room_for_reserved_area() # a new or moved window may reach under a docked sidebar
|
|
1370
|
+
self.publish_snapshot_if_changed()
|
|
1371
|
+
process_ids_not_asked_about = self.list_claude_code_process_ids() - self.process_ids_asked_about_in_claude_agents
|
|
1372
|
+
if self.claude_command_path and process_ids_not_asked_about and not self.claude_agents_refresh_is_running:
|
|
1373
|
+
self.process_ids_asked_about_in_claude_agents |= process_ids_not_asked_about
|
|
1374
|
+
# A separate task, so snapshots keep flowing while the command runs (it can take seconds).
|
|
1375
|
+
asyncio.ensure_future(self.refresh_claude_agents())
|
|
1376
|
+
|
|
1377
|
+
def list_claude_code_process_ids(self):
|
|
1378
|
+
"""Returns the agent process IDs of the tabs that run Claude Code (also those in the background)."""
|
|
1379
|
+
return {agent_session["process_id"] for agent_session in self.agent_sessions.values()
|
|
1380
|
+
if isinstance(agent_session["adapter"], ClaudeCodeAdapter) and agent_session["process_id"]}
|
|
1381
|
+
|
|
1382
|
+
async def refresh_claude_agents(self):
|
|
1383
|
+
"""Re-reads `claude agents --json` (names and folders), then asks for a snapshot.
|
|
1384
|
+
|
|
1385
|
+
A Claude Code process registers its session a second or so after it starts, so a process
|
|
1386
|
+
missing from the output is asked about again by a gather CLAUDE_AGENTS_RETRY_DELAY_SECONDS
|
|
1387
|
+
later, up to CLAUDE_AGENTS_RETRIES_FOR_A_NEW_PROCESS times.
|
|
1388
|
+
"""
|
|
1389
|
+
self.claude_agents_refresh_is_running = True
|
|
1390
|
+
try:
|
|
1391
|
+
claude_agents_read_now = await read_claude_agents_by_process_id(self.claude_command_path, list_claude_config_folders())
|
|
1392
|
+
finally:
|
|
1393
|
+
self.claude_agents_refresh_is_running = False
|
|
1394
|
+
# A run that failed or timed out for a config folder leaves its agents out; their last
|
|
1395
|
+
# records stay while their processes run, or their conversation would look new.
|
|
1396
|
+
claude_code_process_ids = self.list_claude_code_process_ids()
|
|
1397
|
+
self.claude_agents_by_process_id = {
|
|
1398
|
+
**{process_id: record for process_id, record in self.claude_agents_by_process_id.items()
|
|
1399
|
+
if process_id in claude_code_process_ids},
|
|
1400
|
+
**claude_agents_read_now}
|
|
1401
|
+
if claude_code_process_ids - self.process_ids_asked_about_in_claude_agents:
|
|
1402
|
+
# Asked about again while this run was under way (a /clear typed then, note_hook_event),
|
|
1403
|
+
# so this run may have read the record from before it: the next gather runs again at
|
|
1404
|
+
# once (code review, 2026-10-28).
|
|
1405
|
+
self.regather_needed.set()
|
|
1406
|
+
retry_is_due = False
|
|
1407
|
+
for process_id in claude_code_process_ids - set(self.claude_agents_by_process_id):
|
|
1408
|
+
self.claude_agents_retry_count_by_process_id[process_id] = self.claude_agents_retry_count_by_process_id.get(process_id, 0) + 1
|
|
1409
|
+
if self.claude_agents_retry_count_by_process_id[process_id] <= CLAUDE_AGENTS_RETRIES_FOR_A_NEW_PROCESS:
|
|
1410
|
+
self.process_ids_asked_about_in_claude_agents.discard(process_id)
|
|
1411
|
+
retry_is_due = True
|
|
1412
|
+
if retry_is_due: # the next gather asks again
|
|
1413
|
+
asyncio.get_running_loop().call_later(CLAUDE_AGENTS_RETRY_DELAY_SECONDS, self.regather_needed.set)
|
|
1414
|
+
self.snapshot_needed.set()
|
|
1415
|
+
|
|
1416
|
+
def continue_the_processes_of_agents_no_longer_paused(self):
|
|
1417
|
+
"""Continues the processes a pause stopped below an agent that runs again without Resume
|
|
1418
|
+
(fg typed by hand) or is gone (its tab closed, also from iTerm2), so none stays stopped,
|
|
1419
|
+
and marks the agent sessions whose pause stopped the processes below them."""
|
|
1420
|
+
ended_tabs_and_agents = [tab_and_agent for tab_and_agent, pause_record in self.pause_record_by_tab_and_agent.items()
|
|
1421
|
+
if pause_has_ended(pause_record)]
|
|
1422
|
+
for tab_and_agent in ended_tabs_and_agents:
|
|
1423
|
+
continue_processes_stopped_at_pause(self.pause_record_by_tab_and_agent.pop(tab_and_agent).stopped_processes)
|
|
1424
|
+
if ended_tabs_and_agents:
|
|
1425
|
+
self.save_pause_records()
|
|
1426
|
+
for session_id, agent_session in self.agent_sessions.items():
|
|
1427
|
+
agent_session["is_paused_with_the_processes_below_it"] = (
|
|
1428
|
+
(session_id, agent_session["process_id"]) in self.pause_record_by_tab_and_agent)
|
|
1429
|
+
|
|
1430
|
+
def save_pause_records(self):
|
|
1431
|
+
"""Writes the pause records to their file. A write that fails (a full disk) is reported,
|
|
1432
|
+
not raised: it would end the core, which then restarts and fails the same way (code review, 2026-10-28)."""
|
|
1433
|
+
if not self.pause_records_file_path:
|
|
1434
|
+
return
|
|
1435
|
+
try:
|
|
1436
|
+
save_pause_records(self.pause_records_file_path, self.pause_record_by_tab_and_agent)
|
|
1437
|
+
except OSError as error:
|
|
1438
|
+
print(f"could not save the pause records: {error!r}")
|
|
1439
|
+
|
|
1440
|
+
def load_hook_states_of_the_processes_still_running(self):
|
|
1441
|
+
"""Returns {agent process ID: hook state} from the hook states file, for the processes
|
|
1442
|
+
that still run with the start time stored with their state."""
|
|
1443
|
+
hook_state_by_agent_process_id = {}
|
|
1444
|
+
for process_id, (started_at, hook_state) in load_hook_states(self.hook_states_file_path).items():
|
|
1445
|
+
process = read_process_info(process_id)
|
|
1446
|
+
if process is not None and process.started_at == started_at:
|
|
1447
|
+
hook_state_by_agent_process_id[process_id] = hook_state
|
|
1448
|
+
return hook_state_by_agent_process_id
|
|
1449
|
+
|
|
1450
|
+
def save_hook_states(self):
|
|
1451
|
+
"""Writes the hook states of the agent processes that still run to their file, each with its
|
|
1452
|
+
process's start time. A write that fails is reported, not raised, as for the pause records."""
|
|
1453
|
+
if not self.hook_states_file_path:
|
|
1454
|
+
return
|
|
1455
|
+
started_at_and_hook_state_by_process_id = {}
|
|
1456
|
+
for process_id, hook_state in self.hook_state_by_agent_process_id.items():
|
|
1457
|
+
process = read_process_info(process_id)
|
|
1458
|
+
if process is not None:
|
|
1459
|
+
started_at_and_hook_state_by_process_id[process_id] = (process.started_at, hook_state)
|
|
1460
|
+
try:
|
|
1461
|
+
save_hook_states(self.hook_states_file_path, started_at_and_hook_state_by_process_id)
|
|
1462
|
+
except OSError as error:
|
|
1463
|
+
print(f"could not save the hook states: {error!r}")
|
|
1464
|
+
|
|
1465
|
+
def list_again_the_paused_agents_that_lost_their_row(self):
|
|
1466
|
+
"""Adds resolve_agent_sessions entries for the agents a pause stopped that are still
|
|
1467
|
+
stopped but no longer listed, in gathered tabs with no other agent: after the dashboard
|
|
1468
|
+
restarted (their tabs show the shell in front, so they are found only through their
|
|
1469
|
+
records), or once a newer agent started at the paused tab's shell has ended
|
|
1470
|
+
(resolve_agent_sessions follows only a tab's latest agent). Their entries are then kept,
|
|
1471
|
+
in the background, while their process lives. A tab whose agents were paused one after
|
|
1472
|
+
another lists the last one paused."""
|
|
1473
|
+
gathered_session_ids = {gathered_tab["first_session"]["session_id"] for gathered_window in self.gathered_windows
|
|
1474
|
+
for gathered_tab in gathered_window["tabs"] if gathered_tab["first_session"]}
|
|
1475
|
+
for (session_id, agent_process_id), pause_record in sorted(self.pause_record_by_tab_and_agent.items(),
|
|
1476
|
+
key=lambda item: item[1].agent_process[1], reverse=True):
|
|
1477
|
+
if (session_id in self.agent_sessions or session_id not in gathered_session_ids
|
|
1478
|
+
or pause_has_ended(pause_record)): # continue_the_processes_of_agents_no_longer_paused continues its processes
|
|
1479
|
+
continue
|
|
1480
|
+
# By the tool's name the pause recorded: a wrapped agent ("node .../codex") can't be
|
|
1481
|
+
# recognized from its process's name alone.
|
|
1482
|
+
adapter = next((adapter for adapter in self.specific_adapters
|
|
1483
|
+
if adapter.agent_tool_name == pause_record.agent_tool_name), self.generic_adapter)
|
|
1484
|
+
self.agent_sessions[session_id] = {
|
|
1485
|
+
"adapter": adapter, "process_id": agent_process_id, "is_in_background": True, "is_stopped": True,
|
|
1486
|
+
"agent_tool_name": pause_record.agent_tool_name,
|
|
1487
|
+
"working_folder": read_process_current_folder(agent_process_id), "started_at": pause_record.agent_process[1]}
|
|
1488
|
+
|
|
1489
|
+
def note_agents_that_ended_without_a_session_end(self, agent_sessions_before, now):
|
|
1490
|
+
"""Keeps an "exited" row for each tab, still open, whose agent process is gone
|
|
1491
|
+
since the last snapshot without a normal session end, though its hooks reported (so one
|
|
1492
|
+
would have come): it crashed or was killed. An agent whose hooks never reported (started
|
|
1493
|
+
before they were installed, or since the app started without an event yet) can't be told
|
|
1494
|
+
apart from one that ended normally, so its row just goes, as does that of an agent ended
|
|
1495
|
+
from the list ("Kill Session"). The rows go after EXITED_ROW_SECONDS, when their tab
|
|
1496
|
+
closes or runs a new agent, or when a late session end arrives (note_hook_event).
|
|
1497
|
+
|
|
1498
|
+
Args:
|
|
1499
|
+
agent_sessions_before: resolve_agent_sessions's result in the last snapshot.
|
|
1500
|
+
now: The current time.
|
|
1501
|
+
"""
|
|
1502
|
+
gathered_session_ids = {gathered_tab["first_session"]["session_id"] for gathered_window in self.gathered_windows
|
|
1503
|
+
for gathered_tab in gathered_window["tabs"] if gathered_tab["first_session"]}
|
|
1504
|
+
for session_id, agent_session in agent_sessions_before.items():
|
|
1505
|
+
process_id = agent_session["process_id"]
|
|
1506
|
+
hook_state = self.hook_state_by_agent_process_id.get(process_id)
|
|
1507
|
+
if (session_id in self.agent_sessions or session_id not in gathered_session_ids or not process_id
|
|
1508
|
+
or process_is_alive(process_id) or hook_state is None or hook_state["session_ended_at"] is not None
|
|
1509
|
+
or process_id in self.process_ids_ended_from_the_list
|
|
1510
|
+
or session_id not in self.last_agent_session_entry_by_session_id):
|
|
1511
|
+
continue
|
|
1512
|
+
self.exited_agent_sessions_by_session_id[session_id] = {
|
|
1513
|
+
"entry": self.last_agent_session_entry_by_session_id[session_id], "ended_at": now, "process_id": process_id}
|
|
1514
|
+
asyncio.get_running_loop().call_later(EXITED_ROW_SECONDS, self.snapshot_needed.set) # when the row goes
|
|
1515
|
+
for session_id, exited_agent_session in list(self.exited_agent_sessions_by_session_id.items()):
|
|
1516
|
+
if (session_id not in gathered_session_ids or session_id in self.agent_sessions
|
|
1517
|
+
or now - exited_agent_session["ended_at"] >= EXITED_ROW_SECONDS):
|
|
1518
|
+
del self.exited_agent_sessions_by_session_id[session_id]
|
|
1519
|
+
|
|
1520
|
+
def forget_agent_processes_that_are_gone(self):
|
|
1521
|
+
"""Forgets the hook states and "Kill Session" marks of processes that no longer run, unless
|
|
1522
|
+
a tab still lists them as its agent (a gather that hasn't noticed yet) or shows their "exited" row."""
|
|
1523
|
+
kept_process_ids = ({agent_session["process_id"] for agent_session in self.agent_sessions.values()}
|
|
1524
|
+
| {exited_agent_session["process_id"] for exited_agent_session in self.exited_agent_sessions_by_session_id.values()})
|
|
1525
|
+
process_ids_gone = [process_id for process_id in self.hook_state_by_agent_process_id
|
|
1526
|
+
if process_id not in kept_process_ids and not process_is_alive(process_id)]
|
|
1527
|
+
for process_id in process_ids_gone:
|
|
1528
|
+
del self.hook_state_by_agent_process_id[process_id]
|
|
1529
|
+
if process_ids_gone:
|
|
1530
|
+
self.save_hook_states()
|
|
1531
|
+
self.process_ids_ended_from_the_list = {process_id for process_id in self.process_ids_ended_from_the_list
|
|
1532
|
+
if process_id in kept_process_ids or process_is_alive(process_id)}
|
|
1533
|
+
|
|
1534
|
+
def note_background_task_counts(self):
|
|
1535
|
+
"""Sets each agent session's background task count: Claude Code's own list of its
|
|
1536
|
+
background shells and agents while its hooks have reported it (hook_event_tracking), plus
|
|
1537
|
+
the detached jobs it started, which that list doesn't hold (user request, 2026-10-28),
|
|
1538
|
+
otherwise the background shells seen below the agent and its detached jobs
|
|
1539
|
+
(read_child_processes_periodically)."""
|
|
1540
|
+
for session_id, agent_session in self.agent_sessions.items():
|
|
1541
|
+
reading = self.screen_readings_by_session_id.setdefault(session_id, {})
|
|
1542
|
+
hook_state = self.hook_state_by_agent_process_id.get(agent_session["process_id"])
|
|
1543
|
+
reported_background_task_ids = hook_state["background_task_ids"] if hook_state is not None else None
|
|
1544
|
+
reading["background_task_count"] = (
|
|
1545
|
+
len(reported_background_task_ids) + reading.get("detached_process_count", 0)
|
|
1546
|
+
if reported_background_task_ids is not None else reading.get("background_shell_count", 0))
|
|
1547
|
+
|
|
1548
|
+
def publish_snapshot_if_changed(self):
|
|
1549
|
+
"""Builds the snapshot from the cached state and publishes it unless only its time changed."""
|
|
1550
|
+
now = time.time()
|
|
1551
|
+
self.update_session_tracking(now)
|
|
1552
|
+
self.record_seen_time_for_the_seen_session()
|
|
1553
|
+
self.window_order = update_window_list_order(
|
|
1554
|
+
self.window_order, [gathered_window["window_id"] for gathered_window in self.gathered_windows])
|
|
1555
|
+
for gathered_window in self.gathered_windows: # the App object follows tab switches itself, without a regather
|
|
1556
|
+
window = self.app.get_window_by_id(gathered_window["window_id"])
|
|
1557
|
+
gathered_window["selected_tab_id"] = window.current_tab.tab_id if window and window.current_tab else None
|
|
1558
|
+
agent_sessions_before = self.agent_sessions
|
|
1559
|
+
self.agent_sessions = resolve_agent_sessions(
|
|
1560
|
+
self.gathered_windows, self.agent_sessions, self.specific_adapters, self.generic_adapter, process_is_alive,
|
|
1561
|
+
process_is_stopped)
|
|
1562
|
+
self.list_again_the_paused_agents_that_lost_their_row()
|
|
1563
|
+
self.remember_codex_sessions_that_share_a_folder()
|
|
1564
|
+
self.continue_the_processes_of_agents_no_longer_paused()
|
|
1565
|
+
self.note_agents_that_ended_without_a_session_end(agent_sessions_before, now)
|
|
1566
|
+
self.forget_agent_processes_that_are_gone()
|
|
1567
|
+
self.note_background_task_counts()
|
|
1568
|
+
seen_session_id, highlighted_session_id = self.find_seen_session_id(), self.find_highlighted_session_id()
|
|
1569
|
+
|
|
1570
|
+
def build_snapshot_of(agent_sessions, exited_agent_sessions_by_session_id):
|
|
1571
|
+
return build_computer_snapshot(
|
|
1572
|
+
self.gathered_windows, agent_sessions, self.monitors, self.window_order, self.session_tracking_by_session_id,
|
|
1573
|
+
self.displayed_state_by_session_id, self.screen_readings_by_session_id, STUCK_THRESHOLD_SECONDS,
|
|
1574
|
+
self.claude_agents_by_process_id, seen_session_id, highlighted_session_id, self.computer_id,
|
|
1575
|
+
self.computer_name, now, exited_agent_sessions_by_session_id, self.hooks_status_per_agent_tool)
|
|
1576
|
+
listed_agent_sessions = {session_id: agent_session for session_id, agent_session in self.agent_sessions.items()
|
|
1577
|
+
if agent_session["agent_tool_name"] not in self.left_out_agent_tool_names}
|
|
1578
|
+
entries_and_end_times_of_exited_agent_sessions_by_session_id = {
|
|
1579
|
+
session_id: (exited_agent_session["entry"], exited_agent_session["ended_at"])
|
|
1580
|
+
for session_id, exited_agent_session in self.exited_agent_sessions_by_session_id.items()}
|
|
1581
|
+
listed_exited_agent_sessions_by_session_id = {
|
|
1582
|
+
session_id: entry_and_end_time for session_id, entry_and_end_time
|
|
1583
|
+
in entries_and_end_times_of_exited_agent_sessions_by_session_id.items()
|
|
1584
|
+
if entry_and_end_time[0].agent_tool_name not in self.left_out_agent_tool_names}
|
|
1585
|
+
snapshot = build_snapshot_of(listed_agent_sessions, listed_exited_agent_sessions_by_session_id)
|
|
1586
|
+
# Sessions left out of the list (Harnesses) keep their shown state current too, so a
|
|
1587
|
+
# suspended agent's state and every state's start are right when they are listed again.
|
|
1588
|
+
snapshot_of_every_session = (
|
|
1589
|
+
snapshot if (len(listed_agent_sessions), len(listed_exited_agent_sessions_by_session_id))
|
|
1590
|
+
== (len(self.agent_sessions), len(entries_and_end_times_of_exited_agent_sessions_by_session_id))
|
|
1591
|
+
else build_snapshot_of(self.agent_sessions, entries_and_end_times_of_exited_agent_sessions_by_session_id))
|
|
1592
|
+
self.displayed_state_by_session_id = {
|
|
1593
|
+
agent_session_entry.session_id: DisplayedState(
|
|
1594
|
+
agent_session_entry.status, agent_session_entry.status_since,
|
|
1595
|
+
self.session_tracking_by_session_id.get(agent_session_entry.session_id, {}).get("status_change_time", now))
|
|
1596
|
+
for _, _, agent_session_entry in iterate_agent_session_entries(snapshot_of_every_session)}
|
|
1597
|
+
self.last_agent_session_entry_by_session_id = {
|
|
1598
|
+
agent_session_entry.session_id: agent_session_entry
|
|
1599
|
+
for _, _, agent_session_entry in iterate_agent_session_entries(snapshot_of_every_session)
|
|
1600
|
+
if agent_session_entry.session_id in self.agent_sessions}
|
|
1601
|
+
snapshot_without_time = snapshot._replace(taken_at=0)
|
|
1602
|
+
if snapshot_without_time != self.last_published_snapshot_without_time:
|
|
1603
|
+
self.last_published_snapshot_without_time = snapshot_without_time
|
|
1604
|
+
self.publish_snapshot(snapshot)
|
|
1605
|
+
|
|
1606
|
+
# ----- subscriptions -----
|
|
1607
|
+
|
|
1608
|
+
async def handle_session_variable_change(self, connection, notification):
|
|
1609
|
+
"""Updates the cached commandLine or status of one session, then asks for a snapshot.
|
|
1610
|
+
|
|
1611
|
+
A change that arrives during a gather would be written into the list that the gather
|
|
1612
|
+
is about to replace, so it asks for another gather instead. The time of a status change
|
|
1613
|
+
is recorded either way, since a gather reads only the value.
|
|
1614
|
+
"""
|
|
1615
|
+
if notification.name == "status":
|
|
1616
|
+
self.status_set_in_iterm2_at_by_session_id[notification.identifier] = time.time()
|
|
1617
|
+
if self.gather_is_in_progress:
|
|
1618
|
+
self.regather_needed.set()
|
|
1619
|
+
return
|
|
1620
|
+
new_value = json.loads(notification.json_new_value) if notification.json_new_value else None
|
|
1621
|
+
field_name = {"commandLine": "command_line", "status": "status_set_in_iterm2"}[notification.name]
|
|
1622
|
+
for gathered_window in self.gathered_windows:
|
|
1623
|
+
for gathered_tab in gathered_window["tabs"]:
|
|
1624
|
+
first_session = gathered_tab["first_session"]
|
|
1625
|
+
if first_session and first_session["session_id"] == notification.identifier:
|
|
1626
|
+
first_session[field_name] = new_value
|
|
1627
|
+
if field_name == "command_line":
|
|
1628
|
+
self.regather_needed.set() # the job process ID and folder change with the job
|
|
1629
|
+
else:
|
|
1630
|
+
first_session["status_set_in_iterm2_at"] = self.status_set_in_iterm2_at_by_session_id[notification.identifier]
|
|
1631
|
+
self.snapshot_needed.set()
|
|
1632
|
+
|
|
1633
|
+
async def listen_for_hook_events(self):
|
|
1634
|
+
"""Receives the app's hook events (hook_event_forwarder), one line per connection, on the
|
|
1635
|
+
socket at hook_events_socket_path, taken over from an earlier run. While another copy of the
|
|
1636
|
+
app (one still giving docked windows their room back as it exits, say)
|
|
1637
|
+
receives them there, this one goes on without them, and takes the socket over once that
|
|
1638
|
+
copy has ended (code review, 2026-10-28). If the socket can't be made, it goes on without
|
|
1639
|
+
hook events (this task must not end: that ends the core)."""
|
|
1640
|
+
if another_process_listens_at(self.hook_events_socket_path):
|
|
1641
|
+
print(f"another copy of the app receives the hook events at {self.hook_events_socket_path}; "
|
|
1642
|
+
f"this one goes on without them until that copy ends")
|
|
1643
|
+
while await asyncio.to_thread(another_process_listens_at, self.hook_events_socket_path):
|
|
1644
|
+
await asyncio.sleep(SECONDS_BETWEEN_CHECKS_FOR_ANOTHER_HOOK_EVENTS_LISTENER)
|
|
1645
|
+
try:
|
|
1646
|
+
if os.path.exists(self.hook_events_socket_path):
|
|
1647
|
+
os.unlink(self.hook_events_socket_path) # left by a run that ended
|
|
1648
|
+
os.makedirs(os.path.dirname(self.hook_events_socket_path), exist_ok=True)
|
|
1649
|
+
server = await asyncio.start_unix_server(self.receive_hook_event, path=self.hook_events_socket_path,
|
|
1650
|
+
limit=LONGEST_HOOK_EVENT_LINE)
|
|
1651
|
+
except OSError as error:
|
|
1652
|
+
print(f"hook events can't be received at {self.hook_events_socket_path}: {error!r}")
|
|
1653
|
+
await asyncio.Event().wait()
|
|
1654
|
+
async with server:
|
|
1655
|
+
await server.serve_forever()
|
|
1656
|
+
|
|
1657
|
+
async def receive_hook_event(self, reader, writer):
|
|
1658
|
+
"""Reads one hook event line from a forwarder's connection, then closes it."""
|
|
1659
|
+
try:
|
|
1660
|
+
line = await reader.readline()
|
|
1661
|
+
event = json.loads(line) if line else None
|
|
1662
|
+
except (ValueError, ConnectionError) as error: # (a line over the limit raises ValueError)
|
|
1663
|
+
print(f"a hook event couldn't be read: {error!r}")
|
|
1664
|
+
event = None
|
|
1665
|
+
finally:
|
|
1666
|
+
writer.close()
|
|
1667
|
+
if isinstance(event, dict):
|
|
1668
|
+
self.note_hook_event(event)
|
|
1669
|
+
|
|
1670
|
+
def note_hook_event(self, event):
|
|
1671
|
+
"""Applies a hook event to the hook state of the agent process that sent it (an agent
|
|
1672
|
+
inside a tab's agent has its own), and takes away the "exited" row of an agent whose
|
|
1673
|
+
normal session end arrives after its process was gone."""
|
|
1674
|
+
ancestor_processes = [ancestor for ancestor in event.get("ancestor_processes") or []
|
|
1675
|
+
if isinstance(ancestor, list) and len(ancestor) == 2 and isinstance(ancestor[0], int)]
|
|
1676
|
+
process_id = find_agent_process_id_of_hook_event(ancestor_processes)
|
|
1677
|
+
if process_id is None:
|
|
1678
|
+
return
|
|
1679
|
+
if self.verbose:
|
|
1680
|
+
print(f"hook event {event.get('hook_event_name')} from {event.get('agent_tool_name')} process {process_id}")
|
|
1681
|
+
hook_state = apply_hook_event(self.hook_state_by_agent_process_id.get(process_id), event)
|
|
1682
|
+
self.hook_state_by_agent_process_id[process_id] = hook_state
|
|
1683
|
+
self.save_hook_states()
|
|
1684
|
+
if hook_state["session_ended_at"] is not None:
|
|
1685
|
+
for session_id, exited_agent_session in list(self.exited_agent_sessions_by_session_id.items()):
|
|
1686
|
+
if exited_agent_session["process_id"] == process_id:
|
|
1687
|
+
del self.exited_agent_sessions_by_session_id[session_id]
|
|
1688
|
+
if (event.get("hook_event_name") == "SessionStart"
|
|
1689
|
+
and event.get("source") in SESSION_START_SOURCES_OF_ANOTHER_CONVERSATION_IN_THE_SAME_PROCESS):
|
|
1690
|
+
# /clear or /resume typed in the terminal: the process goes on in another conversation,
|
|
1691
|
+
# whose ID the gather asked for now gets from `claude agents --json`, as after the list's
|
|
1692
|
+
# own /clear (forget_the_cleared_conversation), so Duplicate doesn't fork the old one
|
|
1693
|
+
# (code review, 2026-10-28).
|
|
1694
|
+
self.process_ids_asked_about_in_claude_agents.discard(process_id)
|
|
1695
|
+
self.regather_needed.set()
|
|
1696
|
+
self.snapshot_needed.set()
|
|
1697
|
+
|
|
1698
|
+
async def check_hooks_periodically(self):
|
|
1699
|
+
"""Keeps hooks_status_per_agent_tool current (hooks_installer.check_hooks), checked every
|
|
1700
|
+
HOOKS_CHECK_INTERVAL_SECONDS (the user can change the files, or approve Codex's hooks, at
|
|
1701
|
+
any time) and at once after the app installed hooks (hooks_check_needed)."""
|
|
1702
|
+
while True:
|
|
1703
|
+
try:
|
|
1704
|
+
hooks_status_per_agent_tool = await asyncio.to_thread(
|
|
1705
|
+
lambda: tuple((agent_tool_name, check_hooks(agent_tool_name)) for agent_tool_name in HOOK_EVENTS_BY_AGENT_TOOL_NAME))
|
|
1706
|
+
except Exception as error: # a check that fails leaves the last status; it must not end the core
|
|
1707
|
+
print(f"the hooks couldn't be checked: {error!r}")
|
|
1708
|
+
hooks_status_per_agent_tool = self.hooks_status_per_agent_tool
|
|
1709
|
+
if hooks_status_per_agent_tool != self.hooks_status_per_agent_tool:
|
|
1710
|
+
self.hooks_status_per_agent_tool = hooks_status_per_agent_tool
|
|
1711
|
+
self.snapshot_needed.set()
|
|
1712
|
+
try:
|
|
1713
|
+
await asyncio.wait_for(self.hooks_check_needed.wait(), HOOKS_CHECK_INTERVAL_SECONDS)
|
|
1714
|
+
except asyncio.TimeoutError:
|
|
1715
|
+
pass
|
|
1716
|
+
self.hooks_check_needed.clear()
|
|
1717
|
+
|
|
1718
|
+
async def watch_layout_changes(self):
|
|
1719
|
+
async with iterm2.LayoutChangeMonitor(self.connection) as monitor:
|
|
1720
|
+
while True:
|
|
1721
|
+
await monitor.async_get()
|
|
1722
|
+
self.regather_needed.set()
|
|
1723
|
+
|
|
1724
|
+
async def watch_new_sessions(self):
|
|
1725
|
+
async with iterm2.NewSessionMonitor(self.connection) as monitor:
|
|
1726
|
+
while True:
|
|
1727
|
+
await monitor.async_get()
|
|
1728
|
+
self.regather_needed.set()
|
|
1729
|
+
|
|
1730
|
+
async def watch_session_terminations(self):
|
|
1731
|
+
async with iterm2.SessionTerminationMonitor(self.connection) as monitor:
|
|
1732
|
+
while True:
|
|
1733
|
+
await monitor.async_get()
|
|
1734
|
+
self.regather_needed.set()
|
|
1735
|
+
|
|
1736
|
+
async def watch_focus_changes(self):
|
|
1737
|
+
"""Tracks which terminal window has keyboard focus, and asks for a snapshot on any focus change.
|
|
1738
|
+
|
|
1739
|
+
The front tab and whether iTerm2 is active come from the iterm2 App object, which handles
|
|
1740
|
+
the same notifications itself; the snapshot is built after the coalescing delay, by which
|
|
1741
|
+
time it has.
|
|
1742
|
+
"""
|
|
1743
|
+
async with iterm2.FocusMonitor(self.connection) as monitor:
|
|
1744
|
+
while True:
|
|
1745
|
+
focus_update = await monitor.async_get_next_update()
|
|
1746
|
+
if focus_update.window_changed is not None:
|
|
1747
|
+
self.update_key_terminal_window(focus_update.window_changed)
|
|
1748
|
+
self.snapshot_needed.set()
|
|
1749
|
+
|
|
1750
|
+
def update_key_terminal_window(self, window_changed):
|
|
1751
|
+
"""Tracks which terminal window has keyboard focus, whatever order iTerm2 reports the
|
|
1752
|
+
old window resigning and the new one becoming key in."""
|
|
1753
|
+
reasons = iterm2.FocusUpdateWindowChanged.Reason
|
|
1754
|
+
if window_changed.event == reasons.TERMINAL_WINDOW_BECAME_KEY:
|
|
1755
|
+
self.key_terminal_window_id = window_changed.window_id
|
|
1756
|
+
elif window_changed.event == reasons.TERMINAL_WINDOW_IS_CURRENT:
|
|
1757
|
+
self.key_terminal_window_id = None # a non-terminal window such as Settings has keyboard focus
|
|
1758
|
+
elif window_changed.event == reasons.TERMINAL_WINDOW_RESIGNED_KEY and self.key_terminal_window_id == window_changed.window_id:
|
|
1759
|
+
self.key_terminal_window_id = None
|
|
1760
|
+
|
|
1761
|
+
async def read_agent_screens_periodically(self):
|
|
1762
|
+
"""Reads the screens the status rules need: the permission dialog of an
|
|
1763
|
+
asking session whose tool needs the check (every SCREEN_CHECK_INTERVAL_SECONDS), and a
|
|
1764
|
+
fingerprint of each working session (every FINGERPRINT_INTERVAL_SECONDS) for "stuck".
|
|
1765
|
+
One screen read serves both. A session that starts asking is read at once, so the count of
|
|
1766
|
+
"Interrupted" lines from before the user could answer is known."""
|
|
1767
|
+
while True:
|
|
1768
|
+
try:
|
|
1769
|
+
await asyncio.wait_for(self.screen_check_needed.wait(), SCREEN_CHECK_INTERVAL_SECONDS)
|
|
1770
|
+
except asyncio.TimeoutError:
|
|
1771
|
+
pass
|
|
1772
|
+
self.screen_check_needed.clear()
|
|
1773
|
+
status_by_session_id = {gathered_tab["first_session"]["session_id"]: gathered_tab["first_session"]["status"]
|
|
1774
|
+
for gathered_window in self.gathered_windows for gathered_tab in gathered_window["tabs"]
|
|
1775
|
+
if gathered_tab["first_session"]}
|
|
1776
|
+
for session_id in set(self.screen_readings_by_session_id) - set(self.agent_sessions):
|
|
1777
|
+
del self.screen_readings_by_session_id[session_id]
|
|
1778
|
+
for session_id, agent_session in list(self.agent_sessions.items()):
|
|
1779
|
+
if agent_session["is_in_background"]:
|
|
1780
|
+
continue
|
|
1781
|
+
state = map_iterm2_status_value_to_state(status_by_session_id.get(session_id))
|
|
1782
|
+
reading = self.screen_readings_by_session_id.setdefault(session_id, {})
|
|
1783
|
+
adapter = agent_session["adapter"]
|
|
1784
|
+
now = time.time()
|
|
1785
|
+
status_change_time = self.session_tracking_by_session_id.get(session_id, {}).get("status_change_time", now)
|
|
1786
|
+
needs_dialog_check = state == "asking" and bool(adapter.permission_dialog_screen_patterns)
|
|
1787
|
+
# An approved tool runs while iTerm2 still says waiting, so it is fingerprinted like "working".
|
|
1788
|
+
is_effectively_working = state == "working" or permission_dialog_was_answered(state, status_change_time, reading)
|
|
1789
|
+
await self.note_command_the_agent_is_waiting_on(session_id, agent_session, reading, state, is_effectively_working, now)
|
|
1790
|
+
needs_fingerprint = is_effectively_working and now - reading.get("fingerprint_checked_at", 0) >= FINGERPRINT_INTERVAL_SECONDS
|
|
1791
|
+
# A row that goes by its own agent while an agent runs inside it (choose_status_value_of_the_tabs_own_agent).
|
|
1792
|
+
needs_turn_check = (session_id in self.iterm2_status_seen_while_an_inner_agent_ran_by_session_id
|
|
1793
|
+
and adapter.working_screen_pattern is not None)
|
|
1794
|
+
if not (needs_dialog_check or needs_fingerprint or needs_turn_check):
|
|
1795
|
+
continue
|
|
1796
|
+
session = self.app.get_session_by_id(session_id)
|
|
1797
|
+
if session is None:
|
|
1798
|
+
continue
|
|
1799
|
+
try:
|
|
1800
|
+
contents = await session.async_get_screen_contents()
|
|
1801
|
+
except iterm2.RPCException:
|
|
1802
|
+
continue # the tab closed meanwhile
|
|
1803
|
+
screen_lines = [contents.line(index).string for index in range(contents.number_of_lines)]
|
|
1804
|
+
if needs_dialog_check:
|
|
1805
|
+
reading = update_permission_dialog_reading(
|
|
1806
|
+
reading, screen_shows_permission_dialog(screen_lines, adapter.permission_dialog_screen_patterns),
|
|
1807
|
+
count_lines_matching(screen_lines, adapter.interrupted_turn_screen_pattern), status_change_time, now)
|
|
1808
|
+
self.screen_readings_by_session_id[session_id] = reading
|
|
1809
|
+
if needs_fingerprint:
|
|
1810
|
+
fingerprint = compute_screen_fingerprint(screen_lines, adapter.progress_noise_patterns)
|
|
1811
|
+
if fingerprint != reading.get("fingerprint"):
|
|
1812
|
+
reading["fingerprint"] = fingerprint
|
|
1813
|
+
reading["fingerprint_changed_at"] = now
|
|
1814
|
+
reading["fingerprint_checked_at"] = now
|
|
1815
|
+
if needs_turn_check:
|
|
1816
|
+
reading["turn_shows_on_screen"] = count_lines_matching(screen_lines, adapter.working_screen_pattern) > 0
|
|
1817
|
+
self.snapshot_needed.set() # also lets "stuck" appear once its time has come
|
|
1818
|
+
|
|
1819
|
+
async def read_context_window_usage_periodically(self):
|
|
1820
|
+
"""Keeps each agent session's context size and preview fields ("context_tokens" and
|
|
1821
|
+
"conversation_preview" in its screen reading) current from the end of its conversation
|
|
1822
|
+
file (context_window_usage, session_preview_computation). The file is looked up
|
|
1823
|
+
(Claude Code: from `claude agents --json`; Codex: by its folder and start time) for each new process or Claude
|
|
1824
|
+
Code conversation and again every minute, and read again only when it changed."""
|
|
1825
|
+
while True:
|
|
1826
|
+
await asyncio.sleep(CONTEXT_USAGE_CHECK_INTERVAL_SECONDS)
|
|
1827
|
+
for session_id in set(self.conversation_files_by_session_id) - set(self.agent_sessions):
|
|
1828
|
+
del self.conversation_files_by_session_id[session_id]
|
|
1829
|
+
for session_id, agent_session in list(self.agent_sessions.items()):
|
|
1830
|
+
await self.update_conversation_file_readings(session_id, agent_session)
|
|
1831
|
+
|
|
1832
|
+
async def update_conversation_file_readings(self, session_id, agent_session):
|
|
1833
|
+
"""Looks up one agent session's conversation file when due and reads its end again when
|
|
1834
|
+
it changed. A /clear can change the session's record (conversation_files_by_session_id)
|
|
1835
|
+
while this waits on a lookup or a read; the record is then fetched again, and the reads'
|
|
1836
|
+
results are dropped."""
|
|
1837
|
+
# Looked up again for a new process or Claude Code conversation (/clear), and every so
|
|
1838
|
+
# often anyway: Codex's /new starts a new file inside the same process.
|
|
1839
|
+
conversation_key = self.find_conversation_key(agent_session)
|
|
1840
|
+
conversation_file = self.conversation_files_by_session_id.get(session_id)
|
|
1841
|
+
now = time.time()
|
|
1842
|
+
seconds_between_lookups = (CONVERSATION_FILE_RETRY_SECONDS if conversation_file is None or conversation_file["path"] is None
|
|
1843
|
+
else CONVERSATION_FILE_RECHECK_SECONDS)
|
|
1844
|
+
if (conversation_file is None or conversation_file["key"] != conversation_key
|
|
1845
|
+
or now - conversation_file["looked_up_at"] >= seconds_between_lookups):
|
|
1846
|
+
path = await self.look_up_conversation_file(session_id, agent_session)
|
|
1847
|
+
if session_id not in self.agent_sessions:
|
|
1848
|
+
return # the tab closed during the lookup
|
|
1849
|
+
conversation_file = self.conversation_files_by_session_id.get(session_id)
|
|
1850
|
+
is_same_conversation = conversation_file is not None and conversation_file["key"] == conversation_key
|
|
1851
|
+
if is_same_conversation and path == conversation_file["cleared_path"]:
|
|
1852
|
+
path = None # the conversation /clear ended; the agent hasn't written its next one yet
|
|
1853
|
+
if is_same_conversation and conversation_file["path"] == path:
|
|
1854
|
+
conversation_file["looked_up_at"] = now
|
|
1855
|
+
else:
|
|
1856
|
+
conversation_file = build_conversation_file_record(
|
|
1857
|
+
conversation_key, path, now, conversation_file["cleared_path"] if is_same_conversation else None)
|
|
1858
|
+
self.conversation_files_by_session_id[session_id] = conversation_file
|
|
1859
|
+
self.forget_conversation_file_readings(session_id)
|
|
1860
|
+
path = conversation_file["path"]
|
|
1861
|
+
if path is None:
|
|
1862
|
+
return
|
|
1863
|
+
try:
|
|
1864
|
+
modified_at = os.path.getmtime(path)
|
|
1865
|
+
except OSError:
|
|
1866
|
+
conversation_file["path"] = None
|
|
1867
|
+
self.forget_conversation_file_readings(session_id)
|
|
1868
|
+
return
|
|
1869
|
+
if modified_at == conversation_file["modified_at"]:
|
|
1870
|
+
return
|
|
1871
|
+
context_tokens = await asyncio.to_thread(agent_session["adapter"].read_context_tokens, path)
|
|
1872
|
+
# None means no usage in the file's end (one huge line), so the last size stays.
|
|
1873
|
+
context_tokens_kept = (context_tokens if context_tokens is not None
|
|
1874
|
+
else self.screen_readings_by_session_id.get(session_id, {}).get("context_tokens"))
|
|
1875
|
+
context_window_tokens = await asyncio.to_thread(
|
|
1876
|
+
agent_session["adapter"].read_context_window_tokens, path, agent_session["process_id"],
|
|
1877
|
+
self.claude_agents_by_process_id.get(agent_session["process_id"]), context_tokens_kept)
|
|
1878
|
+
preview_fields = await asyncio.to_thread(agent_session["adapter"].read_preview_fields, path)
|
|
1879
|
+
if (session_id not in self.agent_sessions or self.conversation_files_by_session_id.get(session_id) is not conversation_file
|
|
1880
|
+
or conversation_file["path"] != path):
|
|
1881
|
+
return # the tab closed, or /clear or a new conversation took this file's place, during the reads
|
|
1882
|
+
conversation_file["modified_at"] = modified_at
|
|
1883
|
+
if context_tokens is not None:
|
|
1884
|
+
self.note_reading_value(session_id, "context_tokens", context_tokens)
|
|
1885
|
+
if context_window_tokens is not None:
|
|
1886
|
+
self.note_reading_value(session_id, "context_window_tokens", context_window_tokens)
|
|
1887
|
+
self.note_reading_value(session_id, "conversation_preview", preview_fields)
|
|
1888
|
+
|
|
1889
|
+
def find_conversation_key(self, agent_session):
|
|
1890
|
+
"""Returns (agent process ID, Claude Code session ID or None): another process, or another
|
|
1891
|
+
Claude Code conversation in the same process (after /clear), is another conversation."""
|
|
1892
|
+
process_id = agent_session["process_id"]
|
|
1893
|
+
return process_id, (self.claude_agents_by_process_id.get(process_id) or {}).get("sessionId")
|
|
1894
|
+
|
|
1895
|
+
async def look_up_conversation_file(self, session_id, agent_session):
|
|
1896
|
+
"""Returns the path of the agent session's conversation file as its adapter finds it, or
|
|
1897
|
+
None. None also for a Codex session that shares or shared its folder with another, whose file
|
|
1898
|
+
can't be told apart from the other's (codex_conversation_may_be_another_sessions): its row
|
|
1899
|
+
then shows no context size or preview rather than the other session's."""
|
|
1900
|
+
if self.codex_conversation_may_be_another_sessions(session_id, agent_session):
|
|
1901
|
+
return None
|
|
1902
|
+
process_id = agent_session["process_id"]
|
|
1903
|
+
return await agent_session["adapter"].find_conversation_file(
|
|
1904
|
+
process_id, self.claude_agents_by_process_id.get(process_id) or {}, self.folders_that_may_hold_claude_code_transcripts)
|
|
1905
|
+
|
|
1906
|
+
def forget_conversation_file_readings(self, session_id):
|
|
1907
|
+
"""Clears the values read from a session's conversation file, when it is no longer its
|
|
1908
|
+
conversation (a new one, a vanished file, /clear)."""
|
|
1909
|
+
for reading_name in CONVERSATION_FILE_READING_NAMES:
|
|
1910
|
+
self.note_reading_value(session_id, reading_name, None)
|
|
1911
|
+
|
|
1912
|
+
def note_reading_value(self, session_id, reading_name, value):
|
|
1913
|
+
"""Stores a value read for a session, from its conversation file ("context_tokens",
|
|
1914
|
+
"conversation_preview") or its processes ("memory_bytes", "cpu_percent"), in its screen
|
|
1915
|
+
reading, asking for a snapshot when it changed."""
|
|
1916
|
+
reading = self.screen_readings_by_session_id.setdefault(session_id, {})
|
|
1917
|
+
if value != reading.get(reading_name):
|
|
1918
|
+
reading[reading_name] = value
|
|
1919
|
+
self.snapshot_needed.set()
|
|
1920
|
+
|
|
1921
|
+
async def read_resource_usage_periodically(self):
|
|
1922
|
+
"""Keeps each agent session's memory and CPU use ("memory_bytes", "cpu_percent" in its
|
|
1923
|
+
screen reading) current while the Memory or CPU column is shown: its agent process and
|
|
1924
|
+
every process below it, read every RESOURCE_USAGE_CHECK_INTERVAL_SECONDS in a worker
|
|
1925
|
+
thread (a few system calls per process, no subprocess). Both are rounded (to the
|
|
1926
|
+
megabyte, to a whole percent, and below CPU_PERCENT_SHOWN_AS_IDLE to 0) so that an idle
|
|
1927
|
+
session's row and the snapshot don't change at every reading."""
|
|
1928
|
+
cpu_time_readings_by_session_id = {} # (process ID, CPU seconds, read at) from the last reading
|
|
1929
|
+
while True:
|
|
1930
|
+
await asyncio.sleep(RESOURCE_USAGE_CHECK_INTERVAL_SECONDS)
|
|
1931
|
+
if not self.resource_usage_is_read:
|
|
1932
|
+
# Columns shown again later start over rather than average over the hidden time.
|
|
1933
|
+
cpu_time_readings_by_session_id.clear()
|
|
1934
|
+
for session_id in list(self.screen_readings_by_session_id):
|
|
1935
|
+
self.note_reading_value(session_id, "memory_bytes", None)
|
|
1936
|
+
self.note_reading_value(session_id, "cpu_percent", None)
|
|
1937
|
+
continue
|
|
1938
|
+
process_ids_by_session_id = {session_id: agent_session["process_id"]
|
|
1939
|
+
for session_id, agent_session in self.agent_sessions.items() if agent_session["process_id"]}
|
|
1940
|
+
usages_by_session_id = await asyncio.to_thread(
|
|
1941
|
+
lambda: {session_id: read_process_tree_resource_usage(process_id)
|
|
1942
|
+
for session_id, process_id in process_ids_by_session_id.items()})
|
|
1943
|
+
now = time.time()
|
|
1944
|
+
for session_id in set(cpu_time_readings_by_session_id) - set(usages_by_session_id):
|
|
1945
|
+
del cpu_time_readings_by_session_id[session_id]
|
|
1946
|
+
for session_id, usage in usages_by_session_id.items():
|
|
1947
|
+
if session_id not in self.agent_sessions:
|
|
1948
|
+
continue # the tab closed during the reading
|
|
1949
|
+
memory_bytes = cpu_percent = None
|
|
1950
|
+
if usage is not None:
|
|
1951
|
+
process_id = process_ids_by_session_id[session_id]
|
|
1952
|
+
previous_reading = cpu_time_readings_by_session_id.get(session_id)
|
|
1953
|
+
# A new agent process in the tab starts its CPU time over.
|
|
1954
|
+
if previous_reading is not None and previous_reading[0] == process_id:
|
|
1955
|
+
cpu_percent = compute_cpu_percent(previous_reading[1:], (usage[1], now))
|
|
1956
|
+
cpu_time_readings_by_session_id[session_id] = (process_id, usage[1], now)
|
|
1957
|
+
memory_bytes, cpu_percent = round_memory_and_cpu_use(usage[0], cpu_percent)
|
|
1958
|
+
self.note_reading_value(session_id, "memory_bytes", memory_bytes)
|
|
1959
|
+
self.note_reading_value(session_id, "cpu_percent", cpu_percent)
|
|
1960
|
+
|
|
1961
|
+
def list_agent_processes_and_their_turns(self):
|
|
1962
|
+
"""Returns {session ID: (agent process ID, whether it is in a turn, when that turn began or
|
|
1963
|
+
None, its Claude Code conversation's ID or None, when the agent started or None)} for
|
|
1964
|
+
read_child_processes_periodically; the conversation's ID and the agent's start find its
|
|
1965
|
+
detached processes. Whether it is in a turn goes by the status value its row goes by, the
|
|
1966
|
+
tracked one: a paused agent's tab has none from iTerm2 while the shell is in front, and
|
|
1967
|
+
its turn goes on once it is back. With no value from iTerm2 at all (after iTerm2
|
|
1968
|
+
restarted), it goes by the state the row shows, from Claude Code's own report (code
|
|
1969
|
+
review, 2026-10-28)."""
|
|
1970
|
+
def agent_is_in_a_turn(session_id):
|
|
1971
|
+
status_value = self.session_tracking_by_session_id.get(session_id, {}).get("status_value")
|
|
1972
|
+
if status_value is None:
|
|
1973
|
+
displayed_state = self.displayed_state_by_session_id.get(session_id)
|
|
1974
|
+
return displayed_state is not None and (displayed_state.state in STATES_OF_A_TURN_UNDER_WAY
|
|
1975
|
+
or displayed_state.state == "stuck")
|
|
1976
|
+
return map_iterm2_status_value_to_state(status_value) in STATES_OF_A_TURN_UNDER_WAY
|
|
1977
|
+
return {
|
|
1978
|
+
session_id: (agent_session["process_id"], agent_is_in_a_turn(session_id),
|
|
1979
|
+
self.session_tracking_by_session_id.get(session_id, {}).get("turn_started_at"),
|
|
1980
|
+
(self.claude_agents_by_process_id.get(agent_session["process_id"]) or {}).get("sessionId"),
|
|
1981
|
+
agent_session.get("started_at"))
|
|
1982
|
+
for session_id, agent_session in self.agent_sessions.items() if agent_session["process_id"]}
|
|
1983
|
+
|
|
1984
|
+
async def read_child_processes_periodically(self):
|
|
1985
|
+
"""Keeps each agent session's child processes ("child_processes", the sub rows of its open
|
|
1986
|
+
tab row; user request, 2026-10-27) and its background shells ("background_shell_count")
|
|
1987
|
+
current, every CHILD_PROCESS_CHECK_INTERVAL_SECONDS, in a worker thread (a few
|
|
1988
|
+
system calls per process, no subprocess). While the Memory or CPU column shows, each
|
|
1989
|
+
child's use is read too, rounded as the agent's is (read_resource_usage_periodically)."""
|
|
1990
|
+
cpu_time_readings_by_child = {} # {(process ID, started at): (CPU seconds, read at)} from the last reading
|
|
1991
|
+
while True: # read at once, then every CHILD_PROCESS_CHECK_INTERVAL_SECONDS (dump-snapshot shows them too)
|
|
1992
|
+
reads_resource_usage = self.resource_usage_is_read
|
|
1993
|
+
agent_process_and_turn_by_session_id = self.list_agent_processes_and_their_turns()
|
|
1994
|
+
|
|
1995
|
+
def read_every_agents_child_processes():
|
|
1996
|
+
# launchd's children are read once for all the agents, only when a conversation's ID is known.
|
|
1997
|
+
agent_starts = [agent_started_at for _, _, _, conversation_id, agent_started_at
|
|
1998
|
+
in agent_process_and_turn_by_session_id.values() if conversation_id and agent_started_at is not None]
|
|
1999
|
+
detached_processes = list_detached_processes(min(agent_starts)) if agent_starts else []
|
|
2000
|
+
return {session_id: read_child_processes(
|
|
2001
|
+
agent_process_id, turn_is_under_way, turn_started_at, reads_resource_usage, time.time(),
|
|
2002
|
+
choose_detached_processes_of_the_conversation(detached_processes, conversation_id, agent_started_at)
|
|
2003
|
+
if agent_started_at is not None else ())
|
|
2004
|
+
for session_id, (agent_process_id, turn_is_under_way, turn_started_at, conversation_id, agent_started_at)
|
|
2005
|
+
in agent_process_and_turn_by_session_id.items()}
|
|
2006
|
+
child_processes_by_session_id = await asyncio.to_thread(read_every_agents_child_processes)
|
|
2007
|
+
cpu_time_readings_by_child = self.note_child_processes(child_processes_by_session_id, cpu_time_readings_by_child,
|
|
2008
|
+
time.time())
|
|
2009
|
+
await asyncio.sleep(CHILD_PROCESS_CHECK_INTERVAL_SECONDS)
|
|
2010
|
+
|
|
2011
|
+
def note_child_processes(self, child_processes_by_session_id, cpu_time_readings_by_child, now):
|
|
2012
|
+
"""Stores one reading of each agent session's child processes (as ChildProcessEntry
|
|
2013
|
+
records) and background shells in its screen reading; returns the CPU time readings for the next one.
|
|
2014
|
+
|
|
2015
|
+
Args:
|
|
2016
|
+
child_processes_by_session_id: {session ID: agent_process_tree.read_child_processes's list}.
|
|
2017
|
+
cpu_time_readings_by_child: {(process ID, started at): (CPU seconds, read at)} from the
|
|
2018
|
+
reading before, for each child's CPU use since then.
|
|
2019
|
+
now: When the processes were read.
|
|
2020
|
+
"""
|
|
2021
|
+
new_cpu_time_readings_by_child = {}
|
|
2022
|
+
for session_id, child_processes in child_processes_by_session_id.items():
|
|
2023
|
+
if session_id not in self.agent_sessions:
|
|
2024
|
+
continue # the tab closed during the reading
|
|
2025
|
+
child_process_entries = []
|
|
2026
|
+
for child_process in child_processes:
|
|
2027
|
+
child, usage = child_process["child"], child_process["resource_usage"]
|
|
2028
|
+
memory_bytes = cpu_percent = None
|
|
2029
|
+
if usage is not None:
|
|
2030
|
+
child_key = (child.process_id, child.started_at) # a reused process ID is another process
|
|
2031
|
+
if child_key in cpu_time_readings_by_child:
|
|
2032
|
+
cpu_percent = compute_cpu_percent(cpu_time_readings_by_child[child_key], (usage[1], now))
|
|
2033
|
+
new_cpu_time_readings_by_child[child_key] = (usage[1], now)
|
|
2034
|
+
memory_bytes, cpu_percent = round_memory_and_cpu_use(usage[0], cpu_percent)
|
|
2035
|
+
child_process_entries.append(ChildProcessEntry(
|
|
2036
|
+
child.process_id, child_process["command_text"][:LONGEST_COMMAND_TEXT], child_process["command_started_at"],
|
|
2037
|
+
child_process["is_background_shell"], memory_bytes, cpu_percent))
|
|
2038
|
+
self.note_reading_value(session_id, "child_processes", tuple(child_process_entries))
|
|
2039
|
+
self.note_reading_value(session_id, "background_shell_count",
|
|
2040
|
+
sum(child_process["is_background_shell"] for child_process in child_processes))
|
|
2041
|
+
self.note_reading_value(session_id, "detached_process_count",
|
|
2042
|
+
sum(child_process["is_detached"] for child_process in child_processes))
|
|
2043
|
+
return new_cpu_time_readings_by_child
|
|
2044
|
+
|
|
2045
|
+
async def note_command_the_agent_is_waiting_on(self, session_id, agent_session, reading, state, is_effectively_working, now):
|
|
2046
|
+
"""Records in the session's screen reading the command a working agent started in this
|
|
2047
|
+
turn and still runs ("running_command": (the name it was started as, started at)), and
|
|
2048
|
+
when one was last seen running, so "stuck" means thinking with nothing new on screen (user
|
|
2049
|
+
request, milestone 2). Between turns it records the processes running then
|
|
2050
|
+
("helper_process_ids", for example MCP servers), which are not commands. A few system
|
|
2051
|
+
calls, no subprocess."""
|
|
2052
|
+
running_command = None
|
|
2053
|
+
if state in STATES_OF_AN_AGENT_WAITING_AT_ITS_PROMPT and agent_session["process_id"] and \
|
|
2054
|
+
now - reading.get("helper_process_ids_recorded_at", 0) >= SECONDS_BETWEEN_HELPER_PROCESS_RECORDINGS:
|
|
2055
|
+
reading["helper_process_ids"] = choose_helper_process_ids(list_descendant_processes(agent_session["process_id"]))
|
|
2056
|
+
reading["helper_process_ids_recorded_at"] = now
|
|
2057
|
+
if is_effectively_working and agent_session["process_id"]:
|
|
2058
|
+
turn_started_at = await self.find_turn_start(session_id, agent_session, now)
|
|
2059
|
+
command = choose_command_the_agent_is_waiting_on(
|
|
2060
|
+
list_descendant_processes(agent_session["process_id"]), turn_started_at,
|
|
2061
|
+
agent_session["adapter"].helper_process_names, now, reading.get("helper_process_ids", frozenset()),
|
|
2062
|
+
lambda process_id: read_process_arguments_and_environment(process_id)[0])
|
|
2063
|
+
if command is not None:
|
|
2064
|
+
command_process, command_started_at = command
|
|
2065
|
+
running_command = (read_name_the_process_was_started_as(command_process.process_id) or command_process.name,
|
|
2066
|
+
command_started_at)
|
|
2067
|
+
if running_command is not None:
|
|
2068
|
+
reading["command_last_seen_running_at"] = now
|
|
2069
|
+
if running_command != reading.get("running_command"):
|
|
2070
|
+
reading["running_command"] = running_command
|
|
2071
|
+
self.snapshot_needed.set()
|
|
2072
|
+
|
|
2073
|
+
async def find_turn_start(self, session_id, agent_session, now):
|
|
2074
|
+
"""Returns when the session's current turn began. It is known when the dashboard saw the
|
|
2075
|
+
status turn working; for a turn already under way when the dashboard started, it is read
|
|
2076
|
+
once from the conversation file (the latest prompt), so a command started in this turn
|
|
2077
|
+
counts and a dev server left from an earlier turn doesn't. Until that file is found, the
|
|
2078
|
+
agent's own start plus SECONDS_AN_AGENT_TAKES_TO_START_ITS_HELPERS stands in."""
|
|
2079
|
+
tracking = self.session_tracking_by_session_id.get(session_id) or {} # set up by update_session_tracking
|
|
2080
|
+
if tracking.get("turn_started_at") is not None:
|
|
2081
|
+
return tracking["turn_started_at"]
|
|
2082
|
+
conversation_file_path = (self.conversation_files_by_session_id.get(session_id) or {}).get("path")
|
|
2083
|
+
if (session_id in self.session_tracking_by_session_id and conversation_file_path
|
|
2084
|
+
and not tracking.get("turn_start_was_read_from_the_conversation_file")):
|
|
2085
|
+
tracking["turn_start_was_read_from_the_conversation_file"] = True
|
|
2086
|
+
turn_started_at = await asyncio.to_thread(agent_session["adapter"].read_turn_started_at, conversation_file_path)
|
|
2087
|
+
if turn_started_at is not None:
|
|
2088
|
+
tracking["turn_started_at"] = turn_started_at
|
|
2089
|
+
return turn_started_at
|
|
2090
|
+
agent_process = read_process_info(agent_session["process_id"])
|
|
2091
|
+
return agent_process.started_at + SECONDS_AN_AGENT_TAKES_TO_START_ITS_HELPERS if agent_process is not None else now
|
|
2092
|
+
|
|
2093
|
+
async def handle_title_change(self, connection, notification):
|
|
2094
|
+
"""A tab or window title changed (here, in iTerm2's own dialogs, or by a program): re-read."""
|
|
2095
|
+
self.regather_needed.set()
|
|
2096
|
+
|
|
2097
|
+
async def poll_window_frames_when_they_matter(self):
|
|
2098
|
+
"""Notices windows moved by hand, which iTerm2 sends no notification for:
|
|
2099
|
+
with several monitors, to regroup them; while a sidebar is docked, to keep them out of its
|
|
2100
|
+
area (a regather makes room). With one monitor and no docked sidebar, frames don't matter."""
|
|
2101
|
+
while True:
|
|
2102
|
+
await asyncio.sleep(FRAME_POLL_INTERVAL_SECONDS)
|
|
2103
|
+
if len(self.monitors) < 2 and self.reserved_screen_area is None:
|
|
2104
|
+
continue
|
|
2105
|
+
for gathered_window in list(self.gathered_windows):
|
|
2106
|
+
window = self.app.get_window_by_id(gathered_window["window_id"])
|
|
2107
|
+
if window is None:
|
|
2108
|
+
continue
|
|
2109
|
+
try:
|
|
2110
|
+
new_frame = await read_window_frame(window)
|
|
2111
|
+
except iterm2.GetPropertyException:
|
|
2112
|
+
continue # closed meanwhile; the layout change handles it
|
|
2113
|
+
if new_frame != gathered_window["frame"]:
|
|
2114
|
+
gathered_window["frame"] = new_frame
|
|
2115
|
+
if self.reserved_screen_area is not None:
|
|
2116
|
+
self.regather_needed.set()
|
|
2117
|
+
else:
|
|
2118
|
+
self.snapshot_needed.set()
|
|
2119
|
+
|
|
2120
|
+
async def refresh_claude_agents_periodically(self):
|
|
2121
|
+
"""Keeps names and folders from `claude agents --json` current (started only when `claude` exists).
|
|
2122
|
+
|
|
2123
|
+
The program is large, so this runs only while Claude Code tabs exist
|
|
2124
|
+
(in phase 2: only those without hooks); new sessions trigger a run of their own.
|
|
2125
|
+
"""
|
|
2126
|
+
while True:
|
|
2127
|
+
await asyncio.sleep(CLAUDE_AGENTS_REFRESH_INTERVAL_SECONDS)
|
|
2128
|
+
if not self.claude_agents_refresh_is_running and self.list_claude_code_process_ids():
|
|
2129
|
+
await self.refresh_claude_agents()
|
|
2130
|
+
|
|
2131
|
+
async def publish_when_needed(self):
|
|
2132
|
+
"""Coalesces requests: at most one regather or rebuild per SNAPSHOT_COALESCING_DELAY_SECONDS."""
|
|
2133
|
+
while True:
|
|
2134
|
+
regather_task = asyncio.ensure_future(self.regather_needed.wait())
|
|
2135
|
+
snapshot_task = asyncio.ensure_future(self.snapshot_needed.wait())
|
|
2136
|
+
await asyncio.wait([regather_task, snapshot_task], return_when=asyncio.FIRST_COMPLETED)
|
|
2137
|
+
regather_task.cancel()
|
|
2138
|
+
snapshot_task.cancel()
|
|
2139
|
+
await asyncio.sleep(SNAPSHOT_COALESCING_DELAY_SECONDS)
|
|
2140
|
+
regather_is_needed = self.regather_needed.is_set()
|
|
2141
|
+
self.regather_needed.clear()
|
|
2142
|
+
self.snapshot_needed.clear()
|
|
2143
|
+
try:
|
|
2144
|
+
if regather_is_needed:
|
|
2145
|
+
await self.regather_and_publish()
|
|
2146
|
+
else:
|
|
2147
|
+
self.publish_snapshot_if_changed()
|
|
2148
|
+
except (iterm2.RPCException, iterm2.GetPropertyException) as error:
|
|
2149
|
+
# For example the app list changed under the refresh; a lost connection is caught elsewhere.
|
|
2150
|
+
print(f"regather failed, trying again: {error!r}")
|
|
2151
|
+
asyncio.get_running_loop().call_later(RETRY_DELAY_SECONDS, self.regather_needed.set)
|
|
2152
|
+
|
|
2153
|
+
async def watch_for_connection_loss(self):
|
|
2154
|
+
"""Returns when the websocket closes or the package's dispatch task ends."""
|
|
2155
|
+
dispatch_future = getattr(self.connection, "_Connection__dispatch_forever_future", None)
|
|
2156
|
+
waiters = [asyncio.ensure_future(self.connection.websocket.wait_closed())]
|
|
2157
|
+
if dispatch_future is not None:
|
|
2158
|
+
waiters.append(dispatch_future)
|
|
2159
|
+
await asyncio.wait(waiters, return_when=asyncio.FIRST_COMPLETED)
|
|
2160
|
+
|
|
2161
|
+
async def start_up_after_connecting(self):
|
|
2162
|
+
"""Reads the App object, subscribes to session variable changes, and publishes the first snapshot."""
|
|
2163
|
+
self.app = await iterm2.async_get_app(self.connection)
|
|
2164
|
+
# FocusMonitor reports only later changes, so read the current focus once. Its window
|
|
2165
|
+
# entry says whether that terminal window has keyboard focus or only is current (for
|
|
2166
|
+
# example while iTerm2's Settings window has focus).
|
|
2167
|
+
focus_info = await iterm2.rpc.async_get_focus_info(self.connection)
|
|
2168
|
+
for notification in focus_info.focus_response.notifications:
|
|
2169
|
+
if notification.HasField("window"):
|
|
2170
|
+
self.update_key_terminal_window(iterm2.FocusUpdateWindowChanged(
|
|
2171
|
+
notification.window.window_id, iterm2.FocusUpdateWindowChanged.Reason(notification.window.window_status)))
|
|
2172
|
+
session_scope, window_scope = api_pb2.VariableScope.Value("SESSION"), api_pb2.VariableScope.Value("WINDOW")
|
|
2173
|
+
for variable_name in SESSION_VARIABLES_TO_WATCH:
|
|
2174
|
+
await async_subscribe_to_variable_change_notification(
|
|
2175
|
+
self.connection, self.handle_session_variable_change, session_scope, variable_name, "all")
|
|
2176
|
+
# Titles set by the user. iTerm2 rejects "all" for the tab scope, but a session's
|
|
2177
|
+
# tab.titleOverrideFormat reports its tab's title (checked against iTerm2 3.7.6).
|
|
2178
|
+
await async_subscribe_to_variable_change_notification(
|
|
2179
|
+
self.connection, self.handle_title_change, session_scope, "tab.titleOverrideFormat", "all")
|
|
2180
|
+
await async_subscribe_to_variable_change_notification(
|
|
2181
|
+
self.connection, self.handle_title_change, window_scope, "titleOverrideFormat", "all")
|
|
2182
|
+
await self.regather_and_publish()
|
|
2183
|
+
|
|
2184
|
+
async def run(self):
|
|
2185
|
+
"""Connects, gathers, subscribes, and runs until the connection is lost.
|
|
2186
|
+
|
|
2187
|
+
Every way this ends calls report_connection_lost, so the app exits and its supervisor
|
|
2188
|
+
restarts it.
|
|
2189
|
+
"""
|
|
2190
|
+
# Before connecting: once iTerm2 quits, its paused agents are gone, and what their pauses
|
|
2191
|
+
# stopped below them (in sessions of their own, which closing the tabs doesn't reach) is
|
|
2192
|
+
# continued even while no connection can be made.
|
|
2193
|
+
self.continue_the_processes_of_agents_no_longer_paused()
|
|
2194
|
+
iterm2.auth.gAppKitAvailable = False # fetch the token with osascript, never NSAppleScript
|
|
2195
|
+
try:
|
|
2196
|
+
self.connection = await iterm2.Connection.async_create()
|
|
2197
|
+
except Exception as error:
|
|
2198
|
+
self.report_connection_lost(f"could not connect to iTerm2: {error}")
|
|
2199
|
+
return
|
|
2200
|
+
# The watchdog starts at once: a request whose answer never comes (iTerm2 quit meanwhile)
|
|
2201
|
+
# would otherwise hang the start-up forever.
|
|
2202
|
+
connection_loss_task = asyncio.ensure_future(self.watch_for_connection_loss())
|
|
2203
|
+
start_up_task = asyncio.ensure_future(self.start_up_after_connecting())
|
|
2204
|
+
await asyncio.wait([start_up_task, connection_loss_task], return_when=asyncio.FIRST_COMPLETED)
|
|
2205
|
+
if not start_up_task.done():
|
|
2206
|
+
start_up_task.cancel()
|
|
2207
|
+
self.report_connection_lost("the iTerm2 connection closed during start-up")
|
|
2208
|
+
return
|
|
2209
|
+
if start_up_task.exception() is not None:
|
|
2210
|
+
self.report_connection_lost(f"the core could not start: {start_up_task.exception()!r}")
|
|
2211
|
+
return
|
|
2212
|
+
coroutines = [self.watch_layout_changes(), self.watch_new_sessions(), self.watch_session_terminations(),
|
|
2213
|
+
self.watch_focus_changes(), self.poll_window_frames_when_they_matter(),
|
|
2214
|
+
self.read_agent_screens_periodically(), self.read_context_window_usage_periodically(),
|
|
2215
|
+
self.read_resource_usage_periodically(), self.read_child_processes_periodically(),
|
|
2216
|
+
self.check_hooks_periodically(), self.publish_when_needed()]
|
|
2217
|
+
if self.claude_command_path:
|
|
2218
|
+
coroutines.append(self.refresh_claude_agents_periodically())
|
|
2219
|
+
if self.hook_events_socket_path:
|
|
2220
|
+
coroutines.append(self.listen_for_hook_events())
|
|
2221
|
+
background_tasks = [asyncio.ensure_future(coroutine) for coroutine in coroutines]
|
|
2222
|
+
done_tasks, _ = await asyncio.wait(background_tasks + [connection_loss_task], return_when=asyncio.FIRST_COMPLETED)
|
|
2223
|
+
failure_message = "the iTerm2 connection closed"
|
|
2224
|
+
for done_task in done_tasks:
|
|
2225
|
+
if done_task is not connection_loss_task and not done_task.cancelled() and done_task.exception():
|
|
2226
|
+
failure_message = f"the core stopped: {done_task.exception()!r}"
|
|
2227
|
+
self.report_connection_lost(failure_message)
|
|
2228
|
+
|
|
2229
|
+
|
|
2230
|
+
class Iterm2ConnectionThread(threading.Thread):
|
|
2231
|
+
"""Runs DashboardCore on its own asyncio event loop, and offers thread-safe entry points."""
|
|
2232
|
+
|
|
2233
|
+
def __init__(self, publish_snapshot, report_connection_lost, verbose=False, docked_window_frames_file_path=None,
|
|
2234
|
+
pause_records_file_path=None, pause_record_by_tab_and_agent_to_start_with=None, hook_events_socket_path=None,
|
|
2235
|
+
hook_states_file_path=None):
|
|
2236
|
+
super().__init__(name="iterm2-connection", daemon=True)
|
|
2237
|
+
self.core_ready = threading.Event()
|
|
2238
|
+
self.core = None
|
|
2239
|
+
self.event_loop = None
|
|
2240
|
+
self.publish_snapshot = publish_snapshot
|
|
2241
|
+
self.report_connection_lost = report_connection_lost
|
|
2242
|
+
self.verbose = verbose
|
|
2243
|
+
self.docked_window_frames_file_path = docked_window_frames_file_path
|
|
2244
|
+
self.pause_records_file_path = pause_records_file_path
|
|
2245
|
+
self.pause_record_by_tab_and_agent_to_start_with = pause_record_by_tab_and_agent_to_start_with
|
|
2246
|
+
self.hook_events_socket_path = hook_events_socket_path
|
|
2247
|
+
self.hook_states_file_path = hook_states_file_path
|
|
2248
|
+
|
|
2249
|
+
def run(self):
|
|
2250
|
+
self.event_loop = asyncio.new_event_loop()
|
|
2251
|
+
asyncio.set_event_loop(self.event_loop)
|
|
2252
|
+
self.core = DashboardCore(self.publish_snapshot, self.report_connection_lost, self.verbose,
|
|
2253
|
+
self.docked_window_frames_file_path, self.pause_records_file_path,
|
|
2254
|
+
self.pause_record_by_tab_and_agent_to_start_with, self.hook_events_socket_path,
|
|
2255
|
+
self.hook_states_file_path)
|
|
2256
|
+
self.core_ready.set()
|
|
2257
|
+
self.event_loop.run_until_complete(self.core.run())
|
|
2258
|
+
|
|
2259
|
+
def give_room_back_and_wait(self, timeout_seconds):
|
|
2260
|
+
"""Thread-safe: ends docking and waits, at most timeout_seconds, until the iTerm2 windows
|
|
2261
|
+
have their room back; called just before the app exits."""
|
|
2262
|
+
if not self.core_ready.is_set():
|
|
2263
|
+
return
|
|
2264
|
+
future = asyncio.run_coroutine_threadsafe(self.core.change_reserved_screen_area(None), self.event_loop)
|
|
2265
|
+
try:
|
|
2266
|
+
future.result(timeout_seconds)
|
|
2267
|
+
except Exception as error: # a timeout or a lost connection: the saved frames still allow a later restore
|
|
2268
|
+
print(f"could not give the iTerm2 windows their room back before exiting: {error!r}")
|
|
2269
|
+
|
|
2270
|
+
def submit_action(self, action_request):
|
|
2271
|
+
"""Thread-safe: schedules an action on the core's loop (the core prints failures); returns
|
|
2272
|
+
a concurrent.futures.Future that completes with its ActionResult."""
|
|
2273
|
+
self.core_ready.wait()
|
|
2274
|
+
return asyncio.run_coroutine_threadsafe(self.core.perform_action(action_request), self.event_loop)
|
|
2275
|
+
|
|
2276
|
+
def send_monitors(self, monitors):
|
|
2277
|
+
"""Thread-safe: passes the monitor rectangles to the core."""
|
|
2278
|
+
self.core_ready.wait()
|
|
2279
|
+
self.event_loop.call_soon_threadsafe(self.core.set_monitors, monitors)
|
|
2280
|
+
|
|
2281
|
+
def send_reserved_screen_area(self, area):
|
|
2282
|
+
"""Thread-safe: passes the docked sidebar's area (or None) to the core."""
|
|
2283
|
+
self.core_ready.wait()
|
|
2284
|
+
self.event_loop.call_soon_threadsafe(self.core.set_reserved_screen_area, area)
|
|
2285
|
+
|
|
2286
|
+
def send_core_settings(self, core_settings):
|
|
2287
|
+
"""Thread-safe: passes the settings the core uses (settings_store.build_core_settings) to the core."""
|
|
2288
|
+
self.core_ready.wait()
|
|
2289
|
+
self.event_loop.call_soon_threadsafe(self.core.set_core_settings, core_settings)
|
|
2290
|
+
|
|
2291
|
+
def send_dashboard_is_active(self, dashboard_is_active):
|
|
2292
|
+
"""Thread-safe: tells the core whether the dashboard is the active app."""
|
|
2293
|
+
self.core_ready.wait()
|
|
2294
|
+
self.event_loop.call_soon_threadsafe(self.core.set_dashboard_is_active, dashboard_is_active)
|
|
2295
|
+
|
|
2296
|
+
def send_hooks_changed(self):
|
|
2297
|
+
"""Thread-safe: has the core check the agent tools' hooks again now (after the app installed them)."""
|
|
2298
|
+
self.core_ready.wait()
|
|
2299
|
+
self.event_loop.call_soon_threadsafe(self.core.hooks_check_needed.set)
|