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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. agent_command_tab/__init__.py +4 -0
  2. agent_command_tab/agent_adapters/__init__.py +48 -0
  3. agent_command_tab/agent_adapters/base.py +162 -0
  4. agent_command_tab/agent_adapters/claude_code.py +120 -0
  5. agent_command_tab/agent_adapters/codex.py +102 -0
  6. agent_command_tab/agent_adapters/generic.py +22 -0
  7. agent_command_tab/agent_process_tree.py +557 -0
  8. agent_command_tab/agent_session_pausing.py +254 -0
  9. agent_command_tab/app_controller.py +947 -0
  10. agent_command_tab/claude_code_transcript_records.py +75 -0
  11. agent_command_tab/command_line.py +187 -0
  12. agent_command_tab/context_window_usage.py +230 -0
  13. agent_command_tab/dashboard_core_api.py +57 -0
  14. agent_command_tab/docked_window_frames_store.py +60 -0
  15. agent_command_tab/global_shortcut_key_filter.py +167 -0
  16. agent_command_tab/hook_event_forwarder.py +116 -0
  17. agent_command_tab/hook_event_tracking.py +129 -0
  18. agent_command_tab/hook_states_store.py +60 -0
  19. agent_command_tab/hooks_installer.py +300 -0
  20. agent_command_tab/installed_copy_paths.py +41 -0
  21. agent_command_tab/iterm2_actions.py +325 -0
  22. agent_command_tab/iterm2_connection_thread.py +2299 -0
  23. agent_command_tab/iterm2_snapshot_builder.py +403 -0
  24. agent_command_tab/list_sorting.py +117 -0
  25. agent_command_tab/messages_between_agent_sessions.py +78 -0
  26. agent_command_tab/monitor_assignment.py +109 -0
  27. agent_command_tab/pause_records_store.py +61 -0
  28. agent_command_tab/screen_readings.py +108 -0
  29. agent_command_tab/session_preview_computation.py +228 -0
  30. agent_command_tab/session_status_computation.py +235 -0
  31. agent_command_tab/settings_store.py +292 -0
  32. agent_command_tab/snapshot_data_classes.py +145 -0
  33. agent_command_tab/start_with_iterm2.py +138 -0
  34. agent_command_tab/tab_order_computation.py +26 -0
  35. agent_command_tab/user_interface/__init__.py +1 -0
  36. agent_command_tab/user_interface/agent_session_outline_view.py +2120 -0
  37. agent_command_tab/user_interface/agent_tool_icons.py +124 -0
  38. agent_command_tab/user_interface/app_icon.py +75 -0
  39. agent_command_tab/user_interface/control_helpers.py +38 -0
  40. agent_command_tab/user_interface/list_window.py +116 -0
  41. agent_command_tab/user_interface/menu_bar_status_item.py +193 -0
  42. agent_command_tab/user_interface/named_colors.py +58 -0
  43. agent_command_tab/user_interface/pointing_hand_button.py +42 -0
  44. agent_command_tab/user_interface/popover_container.py +461 -0
  45. agent_command_tab/user_interface/row_text_rendering.py +342 -0
  46. agent_command_tab/user_interface/screen_layout.py +91 -0
  47. agent_command_tab/user_interface/settings_window.py +530 -0
  48. agent_command_tab/user_interface/sidebar_panel.py +486 -0
  49. agent_command_tab/user_interface/sidebar_placement.py +105 -0
  50. agent_command_tab/user_interface/talk_to_each_other_alert.py +130 -0
  51. agent_command_tab/window_list_ordering.py +44 -0
  52. agent_command_tab-0.1.0.dist-info/METADATA +85 -0
  53. agent_command_tab-0.1.0.dist-info/RECORD +57 -0
  54. agent_command_tab-0.1.0.dist-info/WHEEL +5 -0
  55. agent_command_tab-0.1.0.dist-info/entry_points.txt +2 -0
  56. agent_command_tab-0.1.0.dist-info/licenses/LICENSE +21 -0
  57. agent_command_tab-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,947 @@
1
+ """Starts the AppKit main thread and the core's background thread, and routes snapshots and actions.
2
+
3
+ Snapshots arrive on the background thread and are handed to the
4
+ main thread with AppHelper.callAfter, coalesced so that only the newest is drawn. The app
5
+ controller is also the owner that the list controllers, the panels, the sidebar, the menu bar
6
+ item and the settings window report to.
7
+ """
8
+
9
+ import os
10
+ import sys
11
+ import threading
12
+ import time
13
+
14
+ from AppKit import (NSAlert, NSAlertFirstButtonReturn, NSAlertSecondButtonReturn, NSAlertStyleWarning, NSApp, NSAppearance,
15
+ NSAppearanceNameAqua, NSAppearanceNameDarkAqua, NSApplication, NSApplicationActivationPolicyAccessory, NSApplicationDidBecomeActiveNotification,
16
+ NSApplicationDidChangeScreenParametersNotification, NSApplicationDidResignActiveNotification,
17
+ NSApplicationWillTerminateNotification, NSEvent, NSEventModifierFlagCommand, NSEventModifierFlagShift,
18
+ NSMakeRect, NSMenu, NSMenuItem, NSModalPanelWindowLevel, NSMouseInRect, NSPopoverBehaviorApplicationDefined,
19
+ NSPopoverBehaviorTransient, NSRunningApplication, NSWorkspace, NSWorkspaceApplicationKey,
20
+ NSWorkspaceDidActivateApplicationNotification)
21
+ from Foundation import NSNotificationCenter, NSObject, NSRunLoop, NSRunLoopCommonModes, NSTimer
22
+ from PyObjCTools import AppHelper
23
+ import objc
24
+
25
+ from agent_command_tab.command_line import RECONNECT_EXIT_STATUS, SECONDS_TO_WAIT_FOR_ROOM_BACK_BEFORE_EXITING
26
+ from agent_command_tab.dashboard_core_api import ActionRequest
27
+ from agent_command_tab.docked_window_frames_store import DOCKED_WINDOW_FRAMES_FILE_PATH
28
+ from agent_command_tab.global_shortcut_key_filter import GlobalShortcutKeyFilter
29
+ from agent_command_tab.hook_event_forwarder import HOOK_EVENTS_SOCKET_PATH
30
+ from agent_command_tab.hook_states_store import HOOK_STATES_FILE_PATH
31
+ from agent_command_tab.hooks_installer import BACKUP_FILE_SUFFIX, install_hooks, list_settings_file_paths
32
+ from agent_command_tab.iterm2_connection_thread import Iterm2ConnectionThread
33
+ from agent_command_tab.monitor_assignment import compute_frame_clear_of_area
34
+ from agent_command_tab.pause_records_store import PAUSE_RECORDS_FILE_PATH
35
+ from agent_command_tab.settings_store import (SMALLEST_WINDOW_SIZES, build_core_settings, list_included_agent_tool_names,
36
+ load_settings_resolving_paths_at_first_run,
37
+ move_the_settings_folder_of_the_old_name, save_settings)
38
+ from agent_command_tab.snapshot_data_classes import choose_folder_for_new_agent_window
39
+ from agent_command_tab.start_with_iterm2 import (AUTOLAUNCH_SCRIPT_FILE_NAME, build_command_that_starts_this_copy_of_the_app,
40
+ find_iterm2_autolaunch_folder, update_autolaunch_script_to_match_setting)
41
+ from agent_command_tab.user_interface.agent_session_outline_view import AgentSessionListController
42
+ from agent_command_tab.user_interface.app_icon import build_app_icon
43
+ from agent_command_tab.user_interface.list_window import ListWindowController
44
+ from agent_command_tab.user_interface.menu_bar_status_item import MenuBarStatusItemController
45
+ from agent_command_tab.user_interface.popover_container import ListPanelController, build_dropdown_popover
46
+ from agent_command_tab.user_interface.screen_layout import (compute_list_window_content_rect_for_a_dragged_sidebar,
47
+ convert_rect_to_frame_list, grow_frame_to_smallest_size,
48
+ read_monitors_from_screens)
49
+ from agent_command_tab.user_interface.settings_window import SettingsWindowController
50
+ from agent_command_tab.user_interface.sidebar_panel import SidebarController
51
+ from agent_command_tab.user_interface.talk_to_each_other_alert import build_talk_to_each_other_alert
52
+
53
+ ITERM2_BUNDLE_IDENTIFIER = "com.googlecode.iterm2"
54
+ SECONDS_TO_SHOW_CONNECTION_PROBLEM_BEFORE_EXITING = 10
55
+ SECONDS_BEFORE_SAVING_A_MOVED_WINDOWS_FRAME = 0.5
56
+ # The settings' Appearance (settings_store.APPEARANCE_CHOICES; user request, 2026-10-27): the
57
+ # NSAppearance name the app is drawn in, or None to follow macOS's Light or Dark setting.
58
+ APPEARANCE_NAMES_BY_CHOICE = {"auto": None, "dark": NSAppearanceNameDarkAqua, "light": NSAppearanceNameAqua}
59
+ # The settings whose change can put the sidebar where an open settings window is.
60
+ SETTINGS_THAT_PLACE_THE_SIDEBAR = ("show_as", "sidebar_mode", "sidebar_edge", "sidebar_width")
61
+
62
+
63
+ def build_main_menu_with_the_edit_shortcuts():
64
+ """Returns a main menu holding just an Edit menu: Undo, Redo, Cut, Copy, Paste and Select All.
65
+
66
+ The dashboard, an accessory app, never shows a menu bar, but AppKit finds the Command-key
67
+ editing shortcuts in the main menu's items; without them, Command-C, V, X, A and Z do
68
+ nothing in its text fields (the Talk to Each Other note, renames, the settings). The items
69
+ have no target, so each goes to the field being edited.
70
+ """
71
+ edit_menu = NSMenu.alloc().initWithTitle_("Edit")
72
+ for title, action_name, key, modifier_flags in (
73
+ ("Undo", "undo:", "z", NSEventModifierFlagCommand),
74
+ ("Redo", "redo:", "z", NSEventModifierFlagCommand | NSEventModifierFlagShift),
75
+ ("Cut", "cut:", "x", NSEventModifierFlagCommand),
76
+ ("Copy", "copy:", "c", NSEventModifierFlagCommand),
77
+ ("Paste", "paste:", "v", NSEventModifierFlagCommand),
78
+ ("Select All", "selectAll:", "a", NSEventModifierFlagCommand)):
79
+ menu_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(title, action_name, key)
80
+ menu_item.setKeyEquivalentModifierMask_(modifier_flags)
81
+ edit_menu.addItem_(menu_item)
82
+ edit_menu_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Edit", None, "")
83
+ edit_menu_item.setSubmenu_(edit_menu)
84
+ main_menu = NSMenu.alloc().initWithTitle_("")
85
+ main_menu.addItem_(edit_menu_item)
86
+ return main_menu
87
+
88
+
89
+ def choose_what_the_global_shortcut_does(show_as, sidebar_mode, sidebar_is_shown, list_window_is_in_front, dropdown_is_open):
90
+ """Returns what a press of the global shortcut does: it shows the list the way the settings
91
+ ask, or hides it when it shows (user request, 2026-10-21), except that a sidebar set to stay
92
+ visible stays, or comes back if the menu bar icon's menu hid it (code review, 2026-10-28).
93
+
94
+ Returns:
95
+ "show_sidebar", "hide_sidebar", "nothing", "show_window", "hide_window",
96
+ "open_dropdown" or "close_dropdown".
97
+ """
98
+ if show_as == "sidebar":
99
+ if sidebar_mode != "auto_hide":
100
+ return "nothing" if sidebar_is_shown else "show_sidebar"
101
+ return "hide_sidebar" if sidebar_is_shown else "show_sidebar"
102
+ if show_as == "window":
103
+ return "hide_window" if list_window_is_in_front else "show_window"
104
+ return "close_dropdown" if dropdown_is_open else "open_dropdown"
105
+
106
+
107
+ def yield_activation_to(application):
108
+ """Lets an app (an NSRunningApplication) become the active one when it asks: macOS 14 and
109
+ later may refuse another app's activation while this one is active unless this one hands it
110
+ over. Older macOS has no such hand-over and needs none (code review, 2026-10-28)."""
111
+ if NSApp.respondsToSelector_("yieldActivationToApplication:"):
112
+ NSApp.yieldActivationToApplication_(application)
113
+
114
+
115
+ class AppController(NSObject):
116
+ """Owns the views, the settings and the connection thread."""
117
+
118
+ def initWithVerbose_(self, verbose):
119
+ self = objc.super(AppController, self).init()
120
+ if self is None:
121
+ return None
122
+ self.verbose = verbose
123
+ move_the_settings_folder_of_the_old_name() # before the settings and the docked window frames are read
124
+ self.settings = load_settings_resolving_paths_at_first_run()
125
+ self.reserved_screen_area = None
126
+ self.application_in_front_before_dropdown = None
127
+ # The last app other than the dashboard to be active: hiding the list window with the
128
+ # shortcut gives the keyboard back to it. Noted at the start (the app that started the
129
+ # dashboard sends no activation notification), when the window is shown, and whenever
130
+ # another app becomes active (anotherApplicationBecameActive_).
131
+ self.last_other_active_application = None
132
+ self.note_application_unless_it_is_the_dashboard(NSWorkspace.sharedWorkspace().frontmostApplication())
133
+ self.peek_in_progress = None # {"application_in_front"} while a tab row is held
134
+ self.settings_save_is_scheduled = False # a moved window's frame waits to be written (window_frame_changed)
135
+ self.peek_waiting_for_put_back = None # a released peek until the app in front before is back
136
+ self.list_window_drag_check_timer = None # while the list window's title bar is dragged
137
+ self.latest_snapshot_lock = threading.Lock()
138
+ self.latest_snapshot = None
139
+ self.snapshot_delivery_is_scheduled = False
140
+ self.dropdown_list_controller = AgentSessionListController.alloc().initWithOwner_(self)
141
+ self.dropdown_panel_controller = ListPanelController.alloc().initWithListController_(self.dropdown_list_controller)
142
+ self.popover = build_dropdown_popover(self.dropdown_panel_controller)
143
+ self.popover.setDelegate_(self) # popoverWillClose_
144
+ self.status_item_controller = MenuBarStatusItemController.alloc().initWithPopover_owner_(self.popover, self)
145
+ self.sidebar_controller = SidebarController.alloc().initWithOwner_(self)
146
+ self.list_window_controller = ListWindowController.alloc().initWithOwner_(self)
147
+ self.settings_window_controller = SettingsWindowController.alloc().initWithOwner_(self)
148
+ # Calls back on the key filter's own thread.
149
+ self.global_shortcut_key_filter = GlobalShortcutKeyFilter(lambda: AppHelper.callAfter(self.global_shortcut_pressed))
150
+ self.connection_thread = Iterm2ConnectionThread(self.receive_snapshot_on_background_thread,
151
+ self.receive_connection_lost_on_background_thread, verbose,
152
+ DOCKED_WINDOW_FRAMES_FILE_PATH, PAUSE_RECORDS_FILE_PATH,
153
+ hook_events_socket_path=HOOK_EVENTS_SOCKET_PATH,
154
+ hook_states_file_path=HOOK_STATES_FILE_PATH)
155
+ notification_center = NSNotificationCenter.defaultCenter()
156
+ for notification_name, selector_name in (
157
+ (NSApplicationDidChangeScreenParametersNotification, "screenParametersChanged:"),
158
+ (NSApplicationDidBecomeActiveNotification, "dashboardBecameActive:"),
159
+ (NSApplicationDidResignActiveNotification, "dashboardResignedActive:"),
160
+ (NSApplicationWillTerminateNotification, "applicationWillTerminate:")):
161
+ notification_center.addObserver_selector_name_object_(self, selector_name, notification_name, None)
162
+ NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(
163
+ self, "anotherApplicationBecameActive:", NSWorkspaceDidActivateApplicationNotification, None)
164
+ return self
165
+
166
+ @objc.python_method
167
+ def start(self):
168
+ self.connection_thread.start()
169
+ self.connection_thread.send_monitors(read_monitors_from_screens())
170
+ self.apply_settings_to_the_core_and_every_list(self.settings)
171
+ self.apply_appearance(self.settings["appearance"])
172
+ self.apply_start_with_iterm2_setting(self.settings["app_starts_with_iterm2"])
173
+ self.global_shortcut_key_filter.use_global_shortcut(self.settings["global_shortcut"])
174
+ if self.global_shortcut_key_filter.lacks_permission():
175
+ print("agent-command-tab: the global shortcut needs the Accessibility permission (see Settings)", flush=True)
176
+ if self.settings["show_as"] == "window":
177
+ self.list_window_controller.show(self.settings["list_window_frame"], takes_keyboard_focus=False,
178
+ stays_behind_other_windows=True)
179
+ # Always once at start, also when not docked (reserve_screen_area only sends changes): the
180
+ # core waits for it before giving back room still owed from before a restart.
181
+ self.connection_thread.send_reserved_screen_area(self.reserved_screen_area)
182
+
183
+ # ----- background thread to main thread -----
184
+
185
+ @objc.python_method
186
+ def receive_snapshot_on_background_thread(self, snapshot):
187
+ with self.latest_snapshot_lock:
188
+ self.latest_snapshot = snapshot
189
+ if self.snapshot_delivery_is_scheduled:
190
+ return
191
+ self.snapshot_delivery_is_scheduled = True
192
+ AppHelper.callAfter(self.deliver_latest_snapshot)
193
+
194
+ @objc.python_method
195
+ def deliver_latest_snapshot(self):
196
+ with self.latest_snapshot_lock:
197
+ snapshot = self.latest_snapshot
198
+ self.snapshot_delivery_is_scheduled = False
199
+ for list_controller in self.list_all_list_controllers():
200
+ list_controller.apply_snapshot(snapshot)
201
+ self.status_item_controller.show_snapshot(snapshot)
202
+ if self.popover.isShown() and not self.dropdown_list_controller.rename_in_progress:
203
+ self.dropdown_panel_controller.fit_size_to_rows()
204
+
205
+ @objc.python_method
206
+ def receive_connection_lost_on_background_thread(self, message):
207
+ AppHelper.callAfter(self.exit_to_reconnect, message)
208
+
209
+ @objc.python_method
210
+ def exit_to_reconnect(self, message):
211
+ """Shows the problem for a while, then exits so the supervisor reconnects.
212
+
213
+ The `iterm2` package can't reconnect within one process.
214
+ """
215
+ print(f"agent-command-tab: {message}; exiting so the supervisor reconnects", flush=True)
216
+ # The user's wording, 2026-10-28.
217
+ explanation = f"{message}. Retrying soon. Make sure iTerm2 is running, with Settings > General > Magic > Enable Python API on."
218
+ for list_panel_controller in self.list_all_list_panel_controllers():
219
+ list_panel_controller.show_message(explanation)
220
+ self.status_item_controller.show_connection_problem()
221
+ AppHelper.callLater(SECONDS_TO_SHOW_CONNECTION_PROBLEM_BEFORE_EXITING, self.exit_now_with_reconnect_status)
222
+
223
+ @objc.python_method
224
+ def exit_now_with_reconnect_status(self):
225
+ self.save_settings_before_exiting() # as quit does (code review, 2026-10-28)
226
+ sys.stdout.flush()
227
+ os._exit(RECONNECT_EXIT_STATUS)
228
+
229
+ # ----- owner methods for the list controllers and panels -----
230
+
231
+ @objc.python_method
232
+ def list_all_list_panel_controllers(self):
233
+ """The dropdown's, the sidebar's and the list window's panels: each has its own list controller."""
234
+ return [self.dropdown_panel_controller, self.sidebar_controller.list_panel_controller,
235
+ self.list_window_controller.list_panel_controller]
236
+
237
+ @objc.python_method
238
+ def list_all_list_controllers(self):
239
+ return [list_panel_controller.list_controller for list_panel_controller in self.list_all_list_panel_controllers()]
240
+
241
+ @objc.python_method
242
+ def menu_bar_icon_clicked(self):
243
+ """A left click on the menu bar icon shows the list the way the settings ask: the dropdown
244
+ opens or closes, an auto-hiding sidebar slides in for a few seconds or, while it is in, out
245
+ (user request, 2026-10-28; a sidebar set to stay visible stays, as for the global
246
+ shortcut, and comes back if the menu's Show popup or Show window hid it), or the window
247
+ comes to the front. An open settings window closes first (user request, 2026-10-28), so a
248
+ dropdown it kept open closes too. It also retries a global shortcut that lacked the
249
+ permission, since the sidebar slides in without making the app active (the other retry)."""
250
+ self.settings_window_controller.close_if_open()
251
+ self.retry_the_global_shortcut_if_it_lacks_permission()
252
+ self.close_a_dropdown_the_menu_showed()
253
+ if self.settings["show_as"] == "sidebar":
254
+ if self.settings["sidebar_mode"] == "auto_hide" and self.sidebar_controller.is_shown:
255
+ self.sidebar_controller.hide_now()
256
+ else:
257
+ self.show_the_sidebar()
258
+ elif self.settings["show_as"] == "window":
259
+ self.show_the_list_window()
260
+ else:
261
+ self.status_item_controller.toggle_popover()
262
+
263
+ @objc.python_method
264
+ def show_the_list_as(self, show_as_choice):
265
+ """The menu bar icon's menu's "Show popup", "Show sidebar" and "Show window" (user requests,
266
+ 2026-10-28): shows the list as that "Show as" choice would, whatever "Show as" is, without
267
+ changing it. Nothing happens while the list already shows that way; otherwise the other
268
+ ways it shows are hidden first, a sidebar set to stay visible too (until it is shown
269
+ again), and a window behind other windows too (code review, 2026-10-28). A sidebar shown
270
+ while "Show as" is another slides out again after a few seconds, as an auto-hiding one does."""
271
+ if show_as_choice in self.list_the_ways_the_list_shows():
272
+ return
273
+ if show_as_choice != "popup" and self.popover.isShown():
274
+ self.close_dropdown()
275
+ if show_as_choice != "sidebar" and self.sidebar_controller.is_shown:
276
+ self.sidebar_controller.hide_until_shown_again()
277
+ if show_as_choice != "window" and self.list_window_controller.window.isVisible():
278
+ self.list_window_controller.hide()
279
+ self.list_window_closed() # the settings window no longer stays level with it, as for the global shortcut
280
+ if show_as_choice == "popup":
281
+ self.status_item_controller.show_popover()
282
+ elif show_as_choice == "sidebar":
283
+ self.show_the_sidebar()
284
+ else:
285
+ self.show_the_list_window()
286
+
287
+ @objc.python_method
288
+ def list_the_ways_the_list_shows(self):
289
+ """Returns which of "popup", "sidebar" and "window" show the list right now: the window
290
+ only while it is in front (as for the global shortcut), so Show window brings forward one
291
+ that other windows cover or that is on another desktop (code review, 2026-10-28)."""
292
+ return [show_as_choice for show_as_choice, is_shown in (
293
+ ("popup", self.popover.isShown()), ("sidebar", self.sidebar_controller.is_shown),
294
+ ("window", self.list_window_controller.is_in_front())) if is_shown]
295
+
296
+ @objc.python_method
297
+ def show_the_sidebar(self):
298
+ """Slides the sidebar in: one set to stay visible (Show as: Sidebar, an Always mode) for
299
+ good, a docked one taking its room again, also after the menu hid it
300
+ (SidebarController.hide_until_shown_again); any other for a few seconds."""
301
+ if self.settings["show_as"] == "sidebar" and self.settings["sidebar_mode"] != "auto_hide":
302
+ self.sidebar_controller.show_again()
303
+ else:
304
+ self.sidebar_controller.show_for_a_few_seconds()
305
+
306
+ @objc.python_method
307
+ def close_a_dropdown_the_menu_showed(self):
308
+ """Closes a dropdown that the menu bar icon's menu's Show popup opened while "Show as" is
309
+ Sidebar or Window (an open settings window keeps it open), before a click on the icon or
310
+ the global shortcut shows the list the way the settings ask (code review, 2026-10-28)."""
311
+ if self.settings["show_as"] != "popup":
312
+ self.close_dropdown()
313
+
314
+ @objc.python_method
315
+ def global_shortcut_pressed(self):
316
+ """The global shortcut shows the list as the menu bar icon does and, pressed again, hides
317
+ it, giving the keyboard back to the app that had it (user request, 2026-10-21)
318
+ (choose_what_the_global_shortcut_does)."""
319
+ self.close_a_dropdown_the_menu_showed()
320
+ what_to_do = choose_what_the_global_shortcut_does(
321
+ self.settings["show_as"], self.settings["sidebar_mode"], self.sidebar_controller.is_shown,
322
+ self.list_window_controller.is_in_front(), self.popover.isShown())
323
+ if what_to_do == "show_sidebar":
324
+ self.show_the_sidebar() # for a few seconds, or for good if it stays visible
325
+ elif what_to_do == "hide_sidebar":
326
+ self.sidebar_controller.hide_now()
327
+ elif what_to_do == "show_window":
328
+ self.show_the_list_window()
329
+ elif what_to_do == "hide_window":
330
+ self.list_window_controller.hide()
331
+ self.list_window_closed()
332
+ if NSApp.isActive(): # otherwise (always on top) the app with the keyboard keeps it
333
+ self.give_activation_to(self.last_other_active_application)
334
+ elif what_to_do == "open_dropdown":
335
+ self.status_item_controller.show_popover()
336
+ elif what_to_do == "close_dropdown":
337
+ self.close_dropdown()
338
+ self.give_activation_to(self.application_in_front_before_dropdown)
339
+
340
+ @objc.python_method
341
+ def show_the_list_window(self):
342
+ """Brings the list window to the front with the keyboard (the menu bar icon and the shortcut)."""
343
+ self.note_application_unless_it_is_the_dashboard(NSWorkspace.sharedWorkspace().frontmostApplication())
344
+ self.list_window_controller.show(self.settings["list_window_frame"])
345
+ self.place_the_settings_window_above_the_lists(self.popover.isShown())
346
+
347
+ @objc.python_method
348
+ def give_activation_to(self, application):
349
+ """Makes an app the active one again (nothing for None)."""
350
+ if application is not None:
351
+ yield_activation_to(application)
352
+ application.activateWithOptions_(0)
353
+
354
+ @objc.python_method
355
+ def global_shortcut_lacks_permission(self):
356
+ """Whether a global shortcut is chosen but macOS refuses its key filter (no Accessibility permission)."""
357
+ return self.global_shortcut_key_filter.lacks_permission()
358
+
359
+ @objc.python_method
360
+ def retry_the_global_shortcut_if_it_lacks_permission(self):
361
+ """The Accessibility permission may have been given since macOS refused the shortcut's key
362
+ filter (Settings' button opens its page): tries again, and updates an open settings window."""
363
+ if self.global_shortcut_key_filter.lacks_permission():
364
+ self.global_shortcut_key_filter.use_global_shortcut(self.settings["global_shortcut"])
365
+ self.settings_window_controller.reflect_settings(self.settings)
366
+
367
+ @objc.python_method
368
+ def window_frame_changed(self, setting_name, frame):
369
+ """The list window or the settings window was moved or resized: its frame is kept under
370
+ setting_name (settings_store.SMALLEST_WINDOW_SIZES), so it opens there next time. Nothing
371
+ else depends on a frame, so settings_changed's other steps are skipped, and the settings
372
+ file is written once the window has stopped moving (a drag moves it at every pointer step)."""
373
+ if frame == self.settings[setting_name]:
374
+ return
375
+ self.settings = dict(self.settings, **{setting_name: frame})
376
+ if not self.settings_save_is_scheduled:
377
+ self.settings_save_is_scheduled = True
378
+ AppHelper.callLater(SECONDS_BEFORE_SAVING_A_MOVED_WINDOWS_FRAME, self.save_settings_if_scheduled)
379
+
380
+ @objc.python_method
381
+ def save_settings_if_scheduled(self):
382
+ if self.settings_save_is_scheduled:
383
+ self.settings_save_is_scheduled = False
384
+ save_settings(self.settings)
385
+
386
+ # Dragging the dropdown's top bar detaches it into the list window, and dropping the list
387
+ # window on the menu bar icon turns it back into the dropdown (user request, 2026-10-19).
388
+ # Dragging the sidebar's top bar turns it into the list window too (user request, 2026-10-22).
389
+
390
+ @objc.python_method
391
+ def top_bar_dragged(self, list_panel_controller, start_point_on_screen):
392
+ """A list's top bar was dragged: the dropdown's turns into the list window where the
393
+ dropdown was, and the sidebar's into the list window at the window's last size (the user's
394
+ choice), its top bar under the pointer. The window then follows the pointer until the
395
+ button comes up."""
396
+ list_window = self.list_window_controller.window
397
+ if list_panel_controller is self.dropdown_panel_controller and self.popover.isShown():
398
+ dropdown_window = list_panel_controller.view().window()
399
+ content_rect = dropdown_window.convertRectToScreen_(list_panel_controller.view().frame())
400
+ # A dropdown with few rows is shorter than the list window may be; it grows downward.
401
+ window_frame = grow_frame_to_smallest_size(
402
+ convert_rect_to_frame_list(list_window.frameRectForContentRect_(content_rect)),
403
+ SMALLEST_WINDOW_SIZES["list_window_frame"])
404
+ elif list_panel_controller is self.sidebar_controller.list_panel_controller:
405
+ # Its saved frame, or the size it was built with if it has never been shown.
406
+ saved_frame = self.settings["list_window_frame"]
407
+ content_size = list_window.contentRectForFrameRect_(
408
+ NSMakeRect(*saved_frame) if saved_frame is not None else list_window.frame()).size
409
+ content_rect = compute_list_window_content_rect_for_a_dragged_sidebar(
410
+ convert_rect_to_frame_list(self.sidebar_controller.window.frame()), start_point_on_screen,
411
+ (content_size.width, content_size.height))
412
+ window_frame = convert_rect_to_frame_list(list_window.frameRectForContentRect_(NSMakeRect(*content_rect)))
413
+ # At once, without sliding: the window takes its place. Even one shown from the menu,
414
+ # which "Show as: Window" would leave in for a few seconds.
415
+ self.sidebar_controller.hide_now(animate=False)
416
+ else:
417
+ return
418
+ pointer_offset = (start_point_on_screen[0] - window_frame[0], start_point_on_screen[1] - window_frame[1])
419
+ show_as_before = self.settings["show_as"]
420
+ self.settings_changed(dict(self.settings, show_as="window", list_window_frame=window_frame))
421
+ if show_as_before == "window":
422
+ # The dropdown or the sidebar shown from the menu bar icon's menu while the list shows
423
+ # as a window, which may be closed or behind other windows: settings_changed closes
424
+ # the dropdown and shows the window only when "Show as" changes.
425
+ self.close_dropdown()
426
+ self.list_window_controller.show(window_frame, takes_keyboard_focus=not self.settings_window_controller.is_open())
427
+ if self.settings_window_controller.is_open(): # it stays in front, as when settings_changed shows the window
428
+ self.place_the_settings_window_above_the_lists(self.popover.isShown())
429
+ self.settings_window_controller.window.orderFront_(None)
430
+ # A window that was open already (behind other windows, say) keeps its frame in show, so
431
+ # it takes the dragged one here, or pointer_offset wouldn't put its top bar under the pointer (code review, 2026-10-28).
432
+ list_window.setFrame_display_(NSMakeRect(*window_frame), True)
433
+ self.list_window_controller.follow_the_pointer_until_the_button_comes_up(pointer_offset)
434
+
435
+ @objc.python_method
436
+ def list_window_drag_started(self):
437
+ """The list window's title bar is being dragged: until the button comes up, the menu bar
438
+ icon is highlighted while the pointer is on it."""
439
+ if self.list_window_drag_check_timer is None:
440
+ self.list_window_drag_check_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
441
+ 0.05, self, "listWindowDragCheckTimerFired:", None, True)
442
+ NSRunLoop.currentRunLoop().addTimer_forMode_(self.list_window_drag_check_timer, NSRunLoopCommonModes)
443
+
444
+ def listWindowDragCheckTimerFired_(self, timer):
445
+ if NSEvent.pressedMouseButtons() & 1:
446
+ self.list_window_is_being_dragged()
447
+ return
448
+ timer.invalidate()
449
+ self.list_window_drag_check_timer = None
450
+ self.list_window_drag_ended()
451
+
452
+ @objc.python_method
453
+ def list_window_is_being_dragged(self):
454
+ self.status_item_controller.highlight(self.pointer_is_on_the_menu_bar_icon())
455
+
456
+ @objc.python_method
457
+ def list_window_drag_ended(self):
458
+ """Dropped on the menu bar icon, the list window turns back into the dropdown: with Show
459
+ as: Window, Show as becomes Popup; a window the menu's Show window opened for another Show
460
+ as just hides, leaving the settings as they are (code review, 2026-10-28)."""
461
+ self.status_item_controller.highlight(False)
462
+ if not self.pointer_is_on_the_menu_bar_icon():
463
+ return
464
+ if self.settings["show_as"] == "window":
465
+ self.settings_changed(dict(self.settings, show_as="popup"))
466
+ else:
467
+ self.list_window_controller.hide()
468
+ self.list_window_closed()
469
+ self.status_item_controller.show_popover()
470
+
471
+ @objc.python_method
472
+ def pointer_is_on_the_menu_bar_icon(self):
473
+ # NSMouseInRect counts the frame's top edge as inside: a pointer pushed against the top of
474
+ # the screen, the usual way to aim at the menu bar, is exactly there.
475
+ return NSMouseInRect(NSEvent.mouseLocation(), self.status_item_controller.find_icon_frame_on_screen(), False)
476
+
477
+ @objc.python_method
478
+ def submit_action(self, action_request):
479
+ """Sends an action to the core; returns a future that completes with its ActionResult."""
480
+ if action_request.action in ("focus_agent_session", "focus_window", "peek_agent_session"):
481
+ # macOS may refuse another app's activation while the dashboard is active, so hand it over first.
482
+ for iterm2_application in NSRunningApplication.runningApplicationsWithBundleIdentifier_(ITERM2_BUNDLE_IDENTIFIER):
483
+ yield_activation_to(iterm2_application)
484
+ return self.connection_thread.submit_action(action_request)
485
+
486
+ def popoverDidShow_(self, notification):
487
+ self.place_the_settings_window_above_the_lists(dropdown_is_open=True) # an open settings window stays above it
488
+
489
+ def popoverWillClose_(self, notification):
490
+ self.status_item_controller.note_dropdown_closing() # so a click on the icon that closed it doesn't open it again
491
+ self.dropdown_list_controller.cancel_rename() # an open rename would keep the list from updating
492
+ self.place_the_settings_window_above_the_lists(dropdown_is_open=False)
493
+
494
+ @objc.python_method
495
+ def update_dropdown_closing_behavior(self):
496
+ """The dropdown closes when you click elsewhere, except while a tab is shown for a moment
497
+ (a peek brings iTerm2 forward) and while the settings window is open (user request,
498
+ 2026-10-19: changing settings mustn't close it)."""
499
+ keeps_the_dropdown_open = (self.peek_in_progress is not None or self.peek_waiting_for_put_back is not None
500
+ or self.settings_window_controller.is_open())
501
+ self.popover.setBehavior_(NSPopoverBehaviorApplicationDefined if keeps_the_dropdown_open else NSPopoverBehaviorTransient)
502
+
503
+ @objc.python_method
504
+ def settings_window_closed(self):
505
+ self.update_dropdown_closing_behavior()
506
+
507
+ @objc.python_method
508
+ def list_window_closed(self):
509
+ """The list window's close button hid it: the settings window no longer stays level with it."""
510
+ self.place_the_settings_window_above_the_lists(self.popover.isShown())
511
+
512
+ @objc.python_method
513
+ def note_application_in_front_before_dropdown(self, application):
514
+ """The dropdown activates the dashboard; a peek ends by bringing back what was in front before."""
515
+ self.application_in_front_before_dropdown = application
516
+
517
+ @objc.python_method
518
+ def start_peek(self, session_id):
519
+ """Pressing and holding a tab row: shows the tab until the button is released (user request,
520
+ milestone 2). The dropdown stays open meanwhile, though iTerm2 becomes the active app."""
521
+ peek_still_being_put_back, self.peek_waiting_for_put_back = self.peek_waiting_for_put_back, None
522
+ if peek_still_being_put_back is not None:
523
+ # Held again before the last peek was put back: iTerm2 is still in front, so take over
524
+ # what that peek was to bring back (its own put-back now does nothing).
525
+ self.peek_in_progress = dict(peek_still_being_put_back)
526
+ else:
527
+ application_in_front = NSWorkspace.sharedWorkspace().frontmostApplication()
528
+ if application_in_front is not None and application_in_front.processIdentifier() == os.getpid():
529
+ # The dashboard is in front: with the dropdown open, bring back what was in front before
530
+ # it opened; with the list window in front, the dashboard itself; otherwise (Settings or
531
+ # a rename is open) bring back nothing.
532
+ if self.popover.isShown():
533
+ application_in_front = self.application_in_front_before_dropdown
534
+ elif not self.list_window_controller.window.isKeyWindow():
535
+ application_in_front = None
536
+ self.peek_in_progress = {"application_in_front": application_in_front}
537
+ self.update_dropdown_closing_behavior()
538
+ self.submit_action(ActionRequest("peek_agent_session", {"session_id": session_id}))
539
+
540
+ @objc.python_method
541
+ def end_peek(self):
542
+ """The button was released: puts back whatever tab, window or app was in front before."""
543
+ peek, self.peek_in_progress = self.peek_in_progress, None
544
+ if peek is None:
545
+ return
546
+ application = peek["application_in_front"]
547
+ iterm2_was_in_front = application is not None and application.bundleIdentifier() == ITERM2_BUNDLE_IDENTIFIER
548
+ self.peek_waiting_for_put_back = peek
549
+ end_peek_future = self.submit_action(ActionRequest("end_peek", {}, {"bring_back_iterm2_window": iterm2_was_in_front}))
550
+ # Only once the core is done (after the peek's own activation of iTerm2, which may still
551
+ # be under way), or iTerm2 would come back in front of the app brought back here.
552
+ end_peek_future.add_done_callback(
553
+ lambda future: AppHelper.callAfter(self.bring_back_application_after_peek, peek, iterm2_was_in_front))
554
+
555
+ @objc.python_method
556
+ def bring_back_application_after_peek(self, peek, iterm2_was_in_front):
557
+ if self.peek_waiting_for_put_back is not peek:
558
+ return # a newer hold took over; its own release puts things back
559
+ self.peek_waiting_for_put_back = None
560
+ if not iterm2_was_in_front:
561
+ self.give_activation_to(peek["application_in_front"])
562
+ self.update_dropdown_closing_behavior()
563
+
564
+ @objc.python_method
565
+ def tab_was_focused(self, list_controller):
566
+ """The dropdown closes after a tab is focused; the sidebar stays until the pointer leaves."""
567
+ if list_controller is self.dropdown_list_controller and self.popover.isShown():
568
+ self.popover.performClose_(None)
569
+
570
+ @objc.python_method
571
+ def rows_changed(self, list_controller):
572
+ if list_controller is self.dropdown_list_controller and self.popover.isShown():
573
+ self.dropdown_panel_controller.fit_size_to_rows()
574
+
575
+ @objc.python_method
576
+ def list_agent_tool_names(self):
577
+ """The agent tools the menus offer for new agent sessions: those the settings include."""
578
+ return list_included_agent_tool_names(self.settings)
579
+
580
+ @objc.python_method
581
+ def confirm_closing_window(self, window_entry):
582
+ """Asks "Are you sure?" before an iTerm2 window, and the agent sessions in it, is closed."""
583
+ agent_session_count = len(window_entry.agent_sessions)
584
+ other_tab_count = window_entry.total_tab_count - agent_session_count
585
+ explanation = (f'Closing "{window_entry.title}" ends the {agent_session_count} agent '
586
+ f'session{"" if agent_session_count == 1 else "s"} running in it')
587
+ if other_tab_count:
588
+ explanation += f' and closes its {other_tab_count} other tab{"" if other_tab_count == 1 else "s"}'
589
+ return self.ask_for_confirmation(explanation + ".", "close_window")
590
+
591
+ @objc.python_method
592
+ def ask_for_confirmation(self, explanation, action_name):
593
+ """Asks "Are you sure?" with this explanation before the action (one of
594
+ settings_store.ACTIONS_THAT_ASK_FOR_CONFIRMATION); returns True for Yes. No is the default
595
+ button, so Return keeps things as they are. A Yes with "Remember my choice" checked is
596
+ saved, and the action then runs without asking; a No isn't remembered, so a menu item
597
+ never silently does nothing (user request, 2026-10-27, with no setting to ask again)."""
598
+ if action_name in self.settings["actions_that_run_without_asking"]:
599
+ return True
600
+ alert = NSAlert.alloc().init()
601
+ alert.setAlertStyle_(NSAlertStyleWarning)
602
+ alert.setMessageText_("Are you sure?")
603
+ alert.setInformativeText_(explanation)
604
+ alert.addButtonWithTitle_("No") # the first button is the default and sits rightmost
605
+ alert.addButtonWithTitle_("Yes")
606
+ alert.setShowsSuppressionButton_(True) # AppKit's "Do not show this message again" checkbox
607
+ alert.suppressionButton().setTitle_("Remember my choice")
608
+ alert.suppressionButton().setToolTip_( # the user's wording, 2026-10-28
609
+ "With Yes, this action will be applied without asking from now on. A No isn't remembered.")
610
+ answer_is_yes = self.run_alert_in_front(alert) == NSAlertSecondButtonReturn
611
+ if answer_is_yes and alert.suppressionButton().state():
612
+ self.settings_changed(dict(self.settings, actions_that_run_without_asking=[
613
+ *self.settings["actions_that_run_without_asking"], action_name]))
614
+ return answer_is_yes
615
+
616
+ @objc.python_method
617
+ def install_hooks(self, agent_tool_names):
618
+ """Adds the app's hooks to these agent tools' settings files (the list's Install Hooks
619
+ button; user request, 2026-10-27), once the user agrees, then has the core check them again."""
620
+ home_folder = os.path.expanduser("~")
621
+ file_paths = [file_path.replace(home_folder, "~", 1) for agent_tool_name in agent_tool_names
622
+ for file_path in list_settings_file_paths(agent_tool_name)]
623
+ alert = NSAlert.alloc().init()
624
+ alert.setMessageText_(f"Install the hooks for {' and '.join(agent_tool_names)}?")
625
+ alert.setInformativeText_(
626
+ "They are added to:\n\n" + "\n".join(file_paths)
627
+ + f"\n\nEach file is first copied to its name plus {BACKUP_FILE_SUFFIX}. Sessions started after this will use the hooks."
628
+ + (" Codex then asks you to approve them: type /hooks in Codex." if "Codex" in agent_tool_names else ""))
629
+ alert.addButtonWithTitle_("Install")
630
+ alert.addButtonWithTitle_("Cancel")
631
+ if self.run_alert_in_front(alert) != NSAlertFirstButtonReturn:
632
+ return
633
+ try:
634
+ for agent_tool_name in agent_tool_names:
635
+ install_hooks(agent_tool_name)
636
+ except (OSError, ValueError) as error:
637
+ failure_alert = NSAlert.alloc().init()
638
+ failure_alert.setMessageText_("The hooks couldn't be installed")
639
+ failure_alert.setInformativeText_(str(error))
640
+ self.run_alert_in_front(failure_alert)
641
+ self.connection_thread.send_hooks_changed()
642
+
643
+ @objc.python_method
644
+ def ask_for_note_asking_agent_sessions_to_talk_to_each_other(self, agent_session_entries, left_out_agent_session_entries):
645
+ """Shows the Talk to Each Other window (user request, 2026-10-21); returns (the note as the
646
+ user left it, the agent session entries chosen to get it: one, or all of them, user request,
647
+ 2026-10-28), or None for Cancel or an empty note."""
648
+ alert, note_text_view, recipient_choices = build_talk_to_each_other_alert(agent_session_entries,
649
+ left_out_agent_session_entries)
650
+ if self.run_alert_in_front(alert) != NSAlertFirstButtonReturn or not note_text_view.string().strip():
651
+ return None
652
+ return note_text_view.string().strip(), recipient_choices.list_chosen_recipients()
653
+
654
+ @objc.python_method
655
+ def run_alert_in_front(self, alert):
656
+ """Shows an alert and returns the button chosen, after closing the dropdown, which (with a
657
+ settings window kept above it) would cover the alert while it waits for an answer. The
658
+ sidebar, above other apps' windows at the status bar's level, goes just under the alert's
659
+ level meanwhile: a wide one would cover it. The alert shows the app's icon: NSAlert takes
660
+ Python.app's own (its rocket), whatever NSApp's icon is set to."""
661
+ alert.setIcon_(build_app_icon())
662
+ self.close_dropdown()
663
+ NSApp.activateIgnoringOtherApps_(True)
664
+ sidebar_window = self.sidebar_controller.window
665
+ sidebar_window_level = sidebar_window.level()
666
+ sidebar_window.setLevel_(NSModalPanelWindowLevel - 1)
667
+ try:
668
+ return alert.runModal()
669
+ finally:
670
+ sidebar_window.setLevel_(sidebar_window_level)
671
+
672
+ @objc.python_method
673
+ def submit_action_and_report_failure(self, action_request, failure_title):
674
+ """Sends an action the user chose from a menu to the core and, should it fail, says why
675
+ in an alert, since the list alone wouldn't show it (a command not typed, say)."""
676
+ self.submit_action(action_request).add_done_callback(
677
+ lambda done_future: AppHelper.callAfter(self.report_action_failure, done_future.result(), failure_title))
678
+
679
+ @objc.python_method
680
+ def report_action_failure(self, action_result, failure_title):
681
+ if action_result.succeeded:
682
+ return
683
+ alert = NSAlert.alloc().init()
684
+ alert.setMessageText_(failure_title)
685
+ alert.setInformativeText_(action_result.message[:1].upper() + action_result.message[1:] + ".")
686
+ self.run_alert_in_front(alert)
687
+
688
+ @objc.python_method
689
+ def find_launch_command(self, agent_tool_name):
690
+ return next((agent_tool["launch_command"] for agent_tool in self.settings["agent_tools"]
691
+ if agent_tool["agent_tool_name"] == agent_tool_name), "")
692
+
693
+ @objc.python_method
694
+ def duplicate_agent_session(self, tab_id, folder, agent_tool_name):
695
+ """Opens a copy of a tab's agent session right after it, continuing a copy of its
696
+ conversation where the tool allows (like Chrome's Duplicate, user request, milestone 2)."""
697
+ self.submit_action(ActionRequest("duplicate_agent_session", {"tab_id": tab_id},
698
+ {"folder": folder or "~", "launch_command": self.find_launch_command(agent_tool_name)}))
699
+
700
+ @objc.python_method
701
+ def start_agent_session_from_menu(self, window_id, folder, agent_tool_name):
702
+ """Starts an agent tool in a new tab of a window, or in a new window in the
703
+ folder of the tab in front, else of the tab used most recently within a day, else the
704
+ home folder (no folder picker: user request, milestone 2)."""
705
+ launch_command = self.find_launch_command(agent_tool_name)
706
+ if window_id is not None:
707
+ self.submit_action(ActionRequest("start_agent_session", {"window_id": window_id},
708
+ {"folder": folder or "~", "launch_command": launch_command}))
709
+ return
710
+ with self.latest_snapshot_lock:
711
+ snapshot = self.latest_snapshot
712
+ self.close_dropdown()
713
+ self.submit_action(ActionRequest("start_agent_session", {}, {
714
+ "folder": choose_folder_for_new_agent_window(snapshot, time.time(), os.path.expanduser("~")),
715
+ "launch_command": launch_command}))
716
+
717
+ @objc.python_method
718
+ def open_settings(self):
719
+ """Opens the settings window; over an open dropdown, which stays open while it is (user request, 2026-10-19),
720
+ and clear of a shown sidebar."""
721
+ self.settings_window_controller.show(self.settings)
722
+ self.move_the_settings_window_clear_of_the_sidebar()
723
+ self.place_the_settings_window_above_the_lists(self.popover.isShown())
724
+ self.update_dropdown_closing_behavior()
725
+
726
+ @objc.python_method
727
+ def move_the_settings_window_clear_of_the_sidebar(self):
728
+ """Moves the settings window sideways, keeping its size where the monitor has room, off a
729
+ shown sidebar's strip: the sidebar is above other windows and would cover it."""
730
+ sidebar_controller = self.sidebar_controller
731
+ if not sidebar_controller.window.isVisible() or sidebar_controller.placement is None:
732
+ return
733
+ settings_window = self.settings_window_controller.window
734
+ settings_frame = convert_rect_to_frame_list(settings_window.frame())
735
+ frame_clear_of_the_sidebar = compute_frame_clear_of_area(
736
+ settings_frame, convert_rect_to_frame_list(sidebar_controller.window.frame()), sidebar_controller.placement.edge,
737
+ sidebar_controller.screens[sidebar_controller.placement.screen_index]["visible_frame"], settings_frame[2])
738
+ if frame_clear_of_the_sidebar is not None:
739
+ settings_window.setFrame_display_(NSMakeRect(*frame_clear_of_the_sidebar), True)
740
+
741
+ @objc.python_method
742
+ def place_the_settings_window_above_the_lists(self, dropdown_is_open):
743
+ """Puts the settings window at the level of the windows it would otherwise open under: just
744
+ above an open dropdown, and level with the list window while that is shown and always on
745
+ top (in front of it when opened); otherwise at the normal level. Not the sidebar's: the
746
+ settings window opens clear of it instead (move_the_settings_window_clear_of_the_sidebar),
747
+ so other apps' windows can still cover it and close it."""
748
+ window_levels = []
749
+ if dropdown_is_open:
750
+ window_levels.append(self.dropdown_panel_controller.view().window().level() + 1)
751
+ list_window = self.list_window_controller.window
752
+ if list_window.isVisible() and self.settings["list_window_is_always_on_top"]:
753
+ window_levels.append(list_window.level())
754
+ self.settings_window_controller.set_window_level(max(window_levels) if window_levels else None)
755
+
756
+ # ----- settings -----
757
+
758
+ @objc.python_method
759
+ def settings_changed(self, new_settings):
760
+ """Saves new settings and applies them to the global shortcut, the appearance, the sidebar,
761
+ the list window (shown when "Show as" turns to Window, hidden when it turns away) and an
762
+ open settings window."""
763
+ show_as_before = self.settings["show_as"]
764
+ list_window_was_always_on_top = self.settings["list_window_is_always_on_top"]
765
+ sidebar_may_have_moved = any(new_settings[name] != self.settings[name] for name in SETTINGS_THAT_PLACE_THE_SIDEBAR)
766
+ if new_settings["global_shortcut"] != self.settings["global_shortcut"]:
767
+ self.global_shortcut_key_filter.use_global_shortcut(new_settings["global_shortcut"])
768
+ if new_settings["appearance"] != self.settings["appearance"]:
769
+ self.apply_appearance(new_settings["appearance"])
770
+ if new_settings["app_starts_with_iterm2"] != self.settings["app_starts_with_iterm2"]:
771
+ self.apply_start_with_iterm2_setting(new_settings["app_starts_with_iterm2"])
772
+ self.settings = new_settings
773
+ save_settings(new_settings)
774
+ self.settings_save_is_scheduled = False # a frame waiting to be written is in new_settings too
775
+ list_window_is_shown_now = new_settings["show_as"] == "window" and show_as_before != "window"
776
+ if new_settings["show_as"] != show_as_before:
777
+ self.close_dropdown()
778
+ if list_window_is_shown_now:
779
+ # Chosen in the settings window, which keeps the keyboard.
780
+ self.list_window_controller.show(new_settings["list_window_frame"],
781
+ takes_keyboard_focus=not self.settings_window_controller.is_open())
782
+ elif show_as_before == "window":
783
+ self.list_window_controller.hide()
784
+ self.apply_settings_to_the_core_and_every_list(new_settings)
785
+ self.settings_window_controller.reflect_settings(new_settings)
786
+ if self.settings_window_controller.is_open():
787
+ if sidebar_may_have_moved: # a sidebar widened at its edge or in the window would cover it (code review, 2026-10-28)
788
+ self.move_the_settings_window_clear_of_the_sidebar()
789
+ self.place_the_settings_window_above_the_lists(self.popover.isShown())
790
+ if list_window_is_shown_now or new_settings["list_window_is_always_on_top"] != list_window_was_always_on_top:
791
+ self.settings_window_controller.window.orderFront_(None) # the list window just shown or put on top stays behind it
792
+
793
+ @objc.python_method
794
+ def apply_appearance(self, appearance_choice):
795
+ """Draws the app's windows, the sidebar and the dropdown always dark, always light, or, for
796
+ "auto", in macOS's Light or Dark setting. The dropdown is set by itself: a popover takes the
797
+ look of the menu bar it opens from rather than the app's, and on "auto" it keeps doing so,
798
+ as before. The menu bar icon keeps the menu bar's look either way."""
799
+ appearance_name = APPEARANCE_NAMES_BY_CHOICE[appearance_choice]
800
+ appearance = NSAppearance.appearanceNamed_(appearance_name) if appearance_name else None
801
+ NSApp.setAppearance_(appearance)
802
+ self.popover.setAppearance_(appearance)
803
+
804
+ @objc.python_method
805
+ def apply_start_with_iterm2_setting(self, app_starts_with_iterm2):
806
+ """Adds, keeps or removes the script in iTerm2's AutoLaunch folder that starts this copy of
807
+ the app whenever iTerm2 starts (start_with_iterm2), and says so in the output when it adds or
808
+ removes it."""
809
+ autolaunch_script_path = os.path.join(find_iterm2_autolaunch_folder(), AUTOLAUNCH_SCRIPT_FILE_NAME)
810
+ try:
811
+ what_was_done = update_autolaunch_script_to_match_setting(
812
+ app_starts_with_iterm2, build_command_that_starts_this_copy_of_the_app(), autolaunch_script_path)
813
+ except OSError as error:
814
+ print(f"agent-command-tab: couldn't {'add' if app_starts_with_iterm2 else 'remove'} {autolaunch_script_path} "
815
+ f"({error})", flush=True)
816
+ return
817
+ if what_was_done == "added":
818
+ print(f"agent-command-tab: added {autolaunch_script_path}, so iTerm2 starts the app whenever iTerm2 starts "
819
+ "(Settings > Start with iTerm2 turns it off)", flush=True)
820
+ elif what_was_done == "removed":
821
+ print(f"agent-command-tab: removed {autolaunch_script_path}; iTerm2 no longer starts the app", flush=True)
822
+
823
+ @objc.python_method
824
+ def apply_settings_to_the_core_and_every_list(self, settings):
825
+ """Hands the settings to the core, the sidebar, the list window and the three lists: at
826
+ the start and after every change."""
827
+ self.connection_thread.send_core_settings(build_core_settings(settings))
828
+ self.sidebar_controller.apply_settings(settings)
829
+ self.list_window_controller.apply_settings(settings)
830
+ self.apply_list_settings(settings)
831
+
832
+ @objc.python_method
833
+ def list_sort_order_chosen(self, list_sort_order, list_sort_order_is_reversed):
834
+ """The Sort pop-up at the top of the dropdown, the sidebar or the list window, or a click
835
+ on a column's title: one choice for all, saved with the settings."""
836
+ if ((list_sort_order, list_sort_order_is_reversed)
837
+ != (self.settings["list_sort_order"], self.settings["list_sort_order_is_reversed"])):
838
+ self.settings_changed(dict(self.settings, list_sort_order=list_sort_order,
839
+ list_sort_order_is_reversed=list_sort_order_is_reversed))
840
+
841
+ @objc.python_method
842
+ def idle_tabs_are_hidden_chosen(self, idle_tabs_are_hidden):
843
+ """The Hide Idle / Show Idle button at the top of the dropdown, the sidebar or the list window: one choice for all, saved with the settings."""
844
+ if idle_tabs_are_hidden != self.settings["idle_tabs_are_hidden"]:
845
+ self.settings_changed(dict(self.settings, idle_tabs_are_hidden=idle_tabs_are_hidden))
846
+
847
+ @objc.python_method
848
+ def apply_list_settings(self, settings):
849
+ """Gives the dropdown's, the sidebar's and the list window's lists the same sort order, idle tabs shown or hidden, and shown columns."""
850
+ for list_panel_controller in self.list_all_list_panel_controllers():
851
+ list_panel_controller.show_list_sort_order(settings["list_sort_order"], settings["list_sort_order_is_reversed"])
852
+ list_panel_controller.show_idle_tabs_are_hidden(settings["idle_tabs_are_hidden"])
853
+ list_panel_controller.list_controller.set_shown_columns(settings["shown_columns"])
854
+
855
+ @objc.python_method
856
+ def reserve_screen_area(self, frame):
857
+ """Docked sidebar: asks the core to keep iTerm2 windows out of frame (None ends it)."""
858
+ if frame != self.reserved_screen_area:
859
+ self.reserved_screen_area = frame
860
+ self.connection_thread.send_reserved_screen_area(frame)
861
+
862
+ @objc.python_method
863
+ def sidebar_width_changed(self, width):
864
+ self.settings_changed(dict(self.settings, sidebar_width=width))
865
+
866
+ # ----- notifications -----
867
+
868
+ @objc.python_method
869
+ def close_dropdown(self):
870
+ if self.popover.isShown():
871
+ self.popover.performClose_(None)
872
+
873
+ def screenParametersChanged_(self, notification):
874
+ self.connection_thread.send_monitors(read_monitors_from_screens())
875
+ self.sidebar_controller.screen_layout_changed()
876
+ self.settings_window_controller.screen_layout_changed()
877
+
878
+ def anotherApplicationBecameActive_(self, notification):
879
+ if self.peek_in_progress is None and self.peek_waiting_for_put_back is None: # a peek activates iTerm2 only for a moment
880
+ self.note_application_unless_it_is_the_dashboard(notification.userInfo()[NSWorkspaceApplicationKey])
881
+
882
+ @objc.python_method
883
+ def note_application_unless_it_is_the_dashboard(self, application):
884
+ """Notes an active app (an NSRunningApplication, or None) as last_other_active_application, unless it is the dashboard itself."""
885
+ if application is not None and application.processIdentifier() != os.getpid():
886
+ self.last_other_active_application = application
887
+
888
+ def dashboardBecameActive_(self, notification):
889
+ self.connection_thread.send_dashboard_is_active(True)
890
+ self.retry_the_global_shortcut_if_it_lacks_permission()
891
+
892
+ def dashboardResignedActive_(self, notification):
893
+ self.connection_thread.send_dashboard_is_active(False)
894
+ # An open settings window keeps the dropdown open while you click elsewhere in the dashboard
895
+ # (update_dropdown_closing_behavior); a click in another app still closes it, unless a peek
896
+ # brought iTerm2 forward on purpose.
897
+ if self.peek_in_progress is None and self.peek_waiting_for_put_back is None:
898
+ self.close_dropdown()
899
+
900
+ @objc.python_method
901
+ def quit(self):
902
+ """Quits, first saving what waits to be saved and giving iTerm2 windows back the room a
903
+ docked sidebar took."""
904
+ self.save_settings_before_exiting()
905
+ self.give_room_back_before_exiting()
906
+ os._exit(0)
907
+
908
+ def applicationWillTerminate_(self, notification):
909
+ # For example after Ctrl+C in the terminal that started the app, or at logout.
910
+ self.save_settings_before_exiting()
911
+ self.give_room_back_before_exiting()
912
+
913
+ @objc.python_method
914
+ def save_settings_before_exiting(self):
915
+ """Saves a launch command or width being typed in the settings window (its field saves it
916
+ as its editing ends) and a moved window's frame waiting to be saved."""
917
+ if self.settings_window_controller.window is not None:
918
+ self.settings_window_controller.window.makeFirstResponder_(None)
919
+ self.save_settings_if_scheduled()
920
+
921
+ @objc.python_method
922
+ def give_room_back_before_exiting(self):
923
+ """Ends docking and waits, at most a few seconds, until the iTerm2 windows have their room
924
+ back. If that fails, the saved frames still let the next run restore them."""
925
+ if self.reserved_screen_area is not None:
926
+ self.reserved_screen_area = None
927
+ self.connection_thread.give_room_back_and_wait(SECONDS_TO_WAIT_FOR_ROOM_BACK_BEFORE_EXITING)
928
+
929
+
930
+ def run_menu_bar_app(verbose):
931
+ """Runs the menu bar app until it quits; returns the exit status."""
932
+ application = NSApplication.sharedApplication()
933
+ application.setActivationPolicy_(NSApplicationActivationPolicyAccessory) # no Dock icon, no Info.plist needed
934
+ # For anything else that shows NSApp's icon; the dialogs get it from run_alert_in_front (user request, 2026-10-28).
935
+ application.setApplicationIconImage_(build_app_icon())
936
+ application.setMainMenu_(build_main_menu_with_the_edit_shortcuts())
937
+ app_controller = AppController.alloc().initWithVerbose_(verbose)
938
+ app_controller.start()
939
+ # runEventLoop(installInterrupt=True) installs its Ctrl+C handler only when no NSApplication
940
+ # exists yet, and one was made above, so it is installed here. Ctrl+C then terminates the app,
941
+ # which calls applicationWillTerminate_.
942
+ AppHelper.installMachInterrupt()
943
+ AppHelper.runEventLoop()
944
+ # Ctrl+C can stop the event loop without terminating the app.
945
+ app_controller.save_settings_before_exiting()
946
+ app_controller.give_room_back_before_exiting()
947
+ return 0