-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1224 lines (997 loc) · 44.9 KB
/
app.py
File metadata and controls
1224 lines (997 loc) · 44.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main application module for Null terminal."""
import asyncio
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
if TYPE_CHECKING:
from textual.worker import Worker
from textual.app import App, ComposeResult
from textual.binding import Binding, BindingType
from textual.containers import Container, Horizontal
from textual.widgets import DirectoryTree, Label, TextArea
from ai.factory import AIFactory
from ai.manager import AIManager
from config import Config, get_settings
from handlers import ExecutionHandler, InputHandler, SlashCommandHandler
from managers import AgentManager, BranchManager, ProcessManager, VoiceManager
from mcp import MCPManager
from models import BlockState, BlockType
from screens import ConfirmDialog, HelpScreen, ModelListScreen
from themes import get_all_themes
from widgets import (
AppHeader,
BaseBlockWidget,
BlockSearch,
CommandPalette,
CommandSuggester,
HistorySearch,
HistoryViewport,
InputController,
Sidebar,
StatusBar,
create_block,
)
# For backwards compatibility
BlockWidget = create_block
class NullApp(App):
CSS_PATH = "styles/main.tcss"
LAYERS: ClassVar[list[str]] = ["base", "overlay"]
BINDINGS: ClassVar[list[BindingType]] = [
Binding("escape", "cancel_operation", "Cancel", id="cancel"),
Binding("ctrl+l", "clear_history", "Clear History", id="clear_history"),
Binding("ctrl+s", "quick_export", "Export", id="quick_export"),
Binding("ctrl+r", "search_history", "Search History", id="search_history"),
Binding("ctrl+f", "search_blocks", "Search Blocks", id="search_blocks"),
Binding(
"ctrl+p", "open_command_palette", "Command Palette", id="command_palette"
),
Binding("f1", "open_help", "Help", id="help"),
Binding("f2", "select_model", "Select Model", id="select_model"),
Binding("f3", "select_theme", "Change Theme", id="select_theme"),
Binding("f4", "select_provider", "Select Provider", id="select_provider"),
Binding("ctrl+space", "toggle_ai_mode", "Toggle AI Mode", id="toggle_ai_mode"),
Binding(
"ctrl+t",
"toggle_ai_mode",
"Toggle AI Mode",
show=False,
id="toggle_ai_mode_alt",
),
Binding("ctrl+backslash", "toggle_file_tree", "Files", id="toggle_file_tree"),
Binding("ctrl+b", "toggle_branches", "Branches", id="toggle_branches"),
Binding("ctrl+m", "toggle_voice", "Voice Input", id="toggle_voice"),
]
def __init__(self):
super().__init__()
# Register custom themes (built-in + user themes from ~/.null/themes/)
for theme in get_all_themes().values():
self.register_theme(theme)
self.config = Config.load_all()
# Apply saved theme or default to null-dark
saved_theme = self.config.get("theme", "null-dark")
if saved_theme in self.available_themes:
self.theme = saved_theme
else:
self.theme = "null-dark"
self.blocks = []
# Initialize Storage
from config import StorageManager
self.storage = StorageManager()
# self.executor removed - executor is now per-process
self.process_manager = ProcessManager()
self.branch_manager = BranchManager()
# Agent Manager
self.agent_manager = AgentManager()
from tools.builtin import set_agent_manager
set_agent_manager(self.agent_manager)
# Plan Manager
from managers.planning import PlanManager
self.plan_manager = PlanManager()
# Error Detector
from managers.error_detector import ErrorDetector
self.error_detector = ErrorDetector()
self._watch_mode = False
# Review Manager
from managers.review import ReviewManager
self.review_manager = ReviewManager()
# Suggestion Engine
from managers.suggestions import SuggestionEngine
self.suggestion_engine = SuggestionEngine()
# CLI session tracking
self.current_cli_block: BlockState | None = None
self.current_cli_widget: BaseBlockWidget | None = None
# AI state
self._ai_cancelled = False
self._active_worker: Worker | None = None
# AI Manager
self.ai_manager = AIManager()
# Legacy/Convenience pointer to active provider for existing checks
self.ai_provider = self.ai_manager.get_active_provider()
# MCP Manager
self.mcp_manager = MCPManager()
# Voice Manager
self.voice_manager = VoiceManager(get_settings().voice)
# Initialize handlers
self.command_handler = SlashCommandHandler(self)
self.execution_handler = ExecutionHandler(self)
self.input_handler = InputHandler(self)
self._register_internal_commands()
self._apply_custom_keybindings()
def _register_internal_commands(self):
commands = [
(cmd.name, cmd.description)
for cmd in self.command_handler.get_all_commands()
]
self.suggestion_engine.set_internal_commands(commands)
def _apply_custom_keybindings(self):
from config import get_keybinding_manager
manager = get_keybinding_manager()
keymap = manager.get_keymap()
if keymap:
result = self._bindings.apply_keymap(keymap)
if result.clashed_bindings:
self.log(f"Keybinding conflicts detected: {result.clashed_bindings}")
def compose(self) -> ComposeResult:
yield AppHeader(id="app-header")
yield CommandSuggester(id="suggester")
yield CommandPalette(id="command-palette")
with Horizontal(id="main-area"):
yield Sidebar()
yield HistoryViewport(id="history")
# History search replaces input container when active
yield HistorySearch(id="history-search")
yield BlockSearch(id="block-search")
with Container(id="input-container"):
yield Label(self._get_prompt_text(), id="prompt-line")
input_widget = InputController(placeholder="Type a command...", id="input")
input_widget.cmd_history = Config._get_storage().load_history()
yield input_widget
yield StatusBar(id="status-bar")
async def push_screen_wait(self, screen) -> Any:
"""Push a screen and wait for it to be dismissed with a result."""
future: asyncio.Future[Any] = asyncio.Future()
def on_dismiss(result: Any) -> None:
if not future.done():
future.set_result(result)
self.push_screen(screen, on_dismiss)
return await future
# -------------------------------------------------------------------------
# Lifecycle
# -------------------------------------------------------------------------
async def on_mount(self):
"""Load previous session on startup."""
# Check for first-run disclaimer
storage = Config._get_storage()
if not storage.get_config("disclaimer_accepted"):
from screens import DisclaimerScreen
def on_disclaimer_accepted(accepted: bool | None):
if accepted:
storage.set_config("disclaimer_accepted", "true")
else:
# User didn't accept - exit the app
self.exit()
self.push_screen(DisclaimerScreen(), on_disclaimer_accepted)
saved_blocks = storage.load_session()
if saved_blocks:
self.blocks = saved_blocks
history_vp = self.query_one("#history", HistoryViewport)
for block in self.blocks:
block.is_running = False
block_widget = BlockWidget(block)
await history_vp.add_block(block_widget)
history_vp.scroll_end(animate=False)
self.notify(f"Restored {len(saved_blocks)} blocks from previous session")
self._update_status_bar()
# Initial provider/header update - use run_worker for async
self.run_worker(self._check_provider_health())
# Periodic health check
self.set_interval(30, self._check_provider_health)
# Initialize MCP
self.run_worker(self._init_mcp())
# Auto-detect model for local providers
self.run_worker(self._detect_local_model())
# Register process manager callback
self.process_manager.on_change(self._update_process_count)
# Apply cursor settings from config
self._apply_cursor_settings()
# Auto-focus the input prompt
self.query_one("#input", InputController).focus()
# Set up periodic auto-save if enabled
settings = get_settings()
if settings.terminal.auto_save_session:
self.set_interval(settings.terminal.auto_save_interval, self._auto_save)
def _apply_cursor_settings(self):
"""Apply cursor style and blink settings from config."""
from utils.terminal import apply_cursor_settings
settings = get_settings()
apply_cursor_settings(
style=settings.terminal.cursor_style, blink=settings.terminal.cursor_blink
)
async def on_key(self, event) -> None:
"""Handle global key events."""
if event.key == "ctrl+c":
self.action_smart_quit()
def _update_process_count(self):
"""Update process count in status bar."""
try:
status_bar = self.query_one("#status-bar", StatusBar)
count = self.process_manager.get_count()
status_bar.set_process_count(count)
except Exception as e:
self.log(f"Error in _update_process_count: {e}")
async def _init_mcp(self):
"""Initialize MCP server connections."""
try:
await self.mcp_manager.initialize()
tools = self.mcp_manager.get_all_tools()
if tools:
self.notify(f"MCP: Connected with {len(tools)} tools available")
except Exception as e:
self.log(f"Error in _init_mcp: {e}")
async def _detect_local_model(self):
"""Auto-detect model for local providers (lm_studio, ollama)."""
try:
provider_name = Config.get("ai.provider")
if provider_name not in ("lm_studio", "ollama"):
return
# Fetch models to trigger auto-detection
_, models, _ = await self.ai_manager._fetch_models_for_provider(
provider_name
)
if models and self.ai_provider:
# Update the cached provider reference
self.ai_provider = self.ai_manager.get_provider(provider_name)
self._update_status_bar()
except Exception as e:
self.log(f"Error in _detect_local_model: {e}")
async def _connect_new_mcp_server(self, name: str):
"""Connect to a newly added MCP server."""
try:
if await self.mcp_manager.connect_server(name):
client = self.mcp_manager.clients.get(name)
if client:
self.notify(f"Connected to {name} ({len(client.tools)} tools)")
else:
self.notify(f"Failed to connect to {name}", severity="warning")
except Exception as e:
self.notify(f"Error connecting to {name}: {e}", severity="error")
# -------------------------------------------------------------------------
# Actions
# -------------------------------------------------------------------------
def action_toggle_ai_mode(self):
"""Toggle between CLI and AI mode."""
self.query_one("#input", InputController).toggle_mode()
def action_toggle_agent_mode(self):
"""Toggle agent mode on/off."""
current = Config.get("ai.agent_mode") or False
new_value = not current
Config.set("ai.agent_mode", new_value)
try:
status_bar = self.query_one("#status-bar", StatusBar)
status_bar.set_agent_mode(new_value)
except Exception:
pass
self.notify(f"Agent mode {'enabled' if new_value else 'disabled'}")
async def action_toggle_voice(self):
try:
status_bar = self.query_one("#status-bar", StatusBar)
except Exception:
status_bar = None
result = await self.voice_manager.toggle_recording()
if result is None:
if status_bar:
status_bar.set_recording(True)
self.notify("Recording started...")
elif result.text:
if status_bar:
status_bar.set_recording(False)
input_ctrl = self.query_one("#input", InputController)
input_ctrl.insert(result.text)
self.notify("Transcription complete")
elif result.error:
if status_bar:
status_bar.set_recording(False)
self.notify(f"Voice error: {result.error}", severity="error")
else:
if status_bar:
status_bar.set_recording(False)
self.notify("Recording stopped")
def action_cancel_operation(self):
"""Cancel any running operation."""
cancelled = False
# Determine target process to stop
target_block_id = None
# 1. Check if a specific block is focused
focused = self.screen.focused
if focused is not None and hasattr(focused, "block_id"): # TerminalBlock
target_block_id = getattr(focused, "block_id", None)
elif focused is not None and hasattr(
focused, "block"
): # CommandBlock/BlockWidget
block = getattr(focused, "block", None)
if block:
target_block_id = block.id
# 2. Fallback to current CLI session block
if not target_block_id and self.current_cli_block:
target_block_id = self.current_cli_block.id
# Stop specific process if identified
if target_block_id and self.process_manager.is_running(target_block_id):
if self.process_manager.stop(target_block_id):
cancelled = True
# Only stop all if we really assume that's what Ctrl+C means globally?
# No, 'stop all' is dangerous.
# If nothing stopped and we have active processes, maybe we should warn?
# For now, let's strictly stop only what's in context.
# Reset CLI session
if self.current_cli_widget:
self.current_cli_widget.set_loading(False)
if self.current_cli_block:
self.current_cli_block.is_running = False
self.current_cli_block = None
self.current_cli_widget = None
if self._active_worker and not self._active_worker.is_finished:
self._ai_cancelled = True
self._active_worker.cancel()
cancelled = True
if cancelled:
self.notify("Operation cancelled", severity="warning")
def action_smart_quit(self):
"""Smart Ctrl+C: Cancel if busy, quit if idle."""
if self.is_busy():
self.action_cancel_operation()
else:
self._do_quit()
def _do_quit(self):
"""Handle quit with confirm_on_exit and clear_on_exit settings."""
settings = get_settings()
if settings.terminal.confirm_on_exit:
# Show confirmation dialog
async def on_confirm(confirmed: bool | None):
if confirmed:
await self._perform_exit(settings.terminal.clear_on_exit)
self.push_screen(
ConfirmDialog(
title="Confirm Exit", message="Are you sure you want to quit?"
),
on_confirm,
)
else:
self.run_worker(self._perform_exit(settings.terminal.clear_on_exit))
async def _perform_exit(self, clear_session: bool):
"""Perform the actual exit, optionally clearing the session."""
if hasattr(self, "ai_manager"):
await self.ai_manager.close_all()
if clear_session:
try:
# Clear the saved session
Config._get_storage().save_current_session([])
except Exception:
pass # Non-critical: session clear on exit can safely fail
self.exit()
def is_busy(self) -> bool:
"""Check if any operation is currently running."""
worker_active = (
self._active_worker is not None and not self._active_worker.is_finished
)
return self.process_manager.get_count() > 0 or worker_active
def action_quick_export(self):
"""Quick export to markdown."""
self._do_export("md")
def action_search_history(self):
"""Open history search."""
try:
self.query_one("#history-search", HistorySearch).show()
except Exception:
pass # Widget may not be mounted yet
def action_search_blocks(self):
"""Open block content search."""
try:
self.query_one("#block-search", BlockSearch).show()
except Exception:
pass # Widget may not be mounted yet
def action_open_command_palette(self):
"""Open the command palette."""
try:
self.query_one("#command-palette", CommandPalette).show()
except Exception:
pass # Widget may not be mounted yet
def action_open_help(self):
"""Show the help screen."""
self.push_screen(HelpScreen())
def action_select_provider(self):
"""Switch and configure AI Provider."""
providers = AIFactory.list_providers()
def on_provider_selected(provider_name):
if not provider_name:
return
sm = Config._get_storage()
current_conf = {
"api_key": sm.get_config(f"ai.{provider_name}.api_key", ""),
"endpoint": sm.get_config(f"ai.{provider_name}.endpoint", ""),
"region": sm.get_config(f"ai.{provider_name}.region", ""),
"model": sm.get_config(f"ai.{provider_name}.model", ""),
}
from screens import ProviderConfigScreen
def on_config_saved(result):
if result is not None:
for k, v in result.items():
Config.set(f"ai.{provider_name}.{k}", v)
Config.set("ai.provider", provider_name)
self.notify(f"Provider switched to {provider_name}")
try:
# Refresh config loading
self.config = Config.load_all()
# Re-initialize the specific provider through the manager
# This ensures the manager has the latest instance
self.ai_manager.get_provider(provider_name)
# Update raw pointer for legacy support
self.ai_provider = self.ai_manager.get_provider(provider_name)
except Exception as e:
self.notify(
f"Error initializing provider: {e}", severity="error"
)
self.push_screen(
ProviderConfigScreen(provider_name, current_conf), on_config_saved
)
from screens import SelectionListScreen
self.push_screen(
SelectionListScreen("Select Provider", providers), on_provider_selected
)
def action_toggle_file_tree(self):
try:
sidebar = self.query_one("Sidebar", Sidebar)
if sidebar.display and sidebar.current_view == "files":
sidebar.toggle_visibility()
else:
sidebar.set_view("files")
if not sidebar.display:
sidebar.toggle_visibility()
except Exception:
pass
def action_toggle_branches(self):
try:
sidebar = self.query_one("Sidebar", Sidebar)
if sidebar.display and sidebar.current_view == "branches":
sidebar.toggle_visibility()
else:
sidebar.set_view("branches")
if not sidebar.display:
sidebar.toggle_visibility()
except Exception:
pass
def action_select_model(self):
"""Select an AI model from ALL providers."""
def on_model_select(selection):
if selection:
provider_name, model_name = selection
# Normalize provider name
provider_name = provider_name.lower()
# Check if we need to switch active provider
current_provider = Config.get("ai.provider", "").lower()
if provider_name != current_provider:
Config.set("ai.provider", provider_name)
# Also sync to JSON settings
from config import SettingsManager
SettingsManager().set("ai", "provider", provider_name)
self.notify(f"Switched provider to {provider_name}")
# Update the model for that provider
Config.set(f"ai.{provider_name}.model", str(model_name))
self.notify(f"Model set to {model_name}")
# Force refresh of provider instance
self.ai_provider = self.ai_manager.get_provider(provider_name)
# Ensure the provider instance knows its model (some store it internally)
if self.ai_provider:
self.ai_provider.model = str(model_name)
self._update_status_bar()
self._update_header(provider_name, str(model_name), connected=True)
# Show screen immediately with async fetch
self.push_screen(
ModelListScreen(fetch_func=self.ai_manager.list_all_models), on_model_select
)
def action_select_theme(self):
"""Change the application theme."""
# Get all available themes, with custom null-* themes first
all_themes = list(self.available_themes)
null_themes = sorted([t for t in all_themes if t.startswith("null-")])
other_themes = sorted([t for t in all_themes if not t.startswith("null-")])
themes = null_themes + other_themes
def on_theme_select(selected_theme):
if selected_theme:
Config.update_key(["theme"], str(selected_theme))
self.theme = selected_theme
self.notify(f"Theme set to {selected_theme}")
from screens import ThemeSelectionScreen
self.push_screen(ThemeSelectionScreen("Select Theme", themes), on_theme_select)
def action_select_prompt(self):
"""Select a system prompt (persona)."""
from prompts import get_prompt_manager
prompt_manager = get_prompt_manager()
prompts_list = prompt_manager.list_prompts()
# Format: "key - description" for display
display_items = []
key_map = {}
for key, name, _desc, is_user in prompts_list:
prefix = "[user] " if is_user else ""
display = f"{prefix}{name}"
display_items.append(display)
key_map[display] = key
def on_prompt_select(selected):
if selected and selected in key_map:
key = key_map[selected]
Config.update_key(["ai", "active_prompt"], key)
self.notify(f"System Persona set to: {selected}")
self.config["ai"]["active_prompt"] = key
from screens import SelectionListScreen
self.push_screen(
SelectionListScreen("Select Persona", display_items), on_prompt_select
)
def action_clear_history(self):
"""Clear history and context."""
self.blocks = []
self.current_cli_block = None
self.current_cli_widget = None
try:
history = self.query_one("#history")
history.remove_children()
except Exception:
pass
try:
status_bar = self.query_one("#status-bar")
if hasattr(status_bar, "reset_token_usage"):
status_bar.reset_token_usage()
except Exception:
pass
self.notify("History cleared")
# -------------------------------------------------------------------------
# Event Handlers
# -------------------------------------------------------------------------
def on_click(self, event) -> None:
"""Handle clicks - dismiss popups and focus input on background clicks."""
# Dismiss command suggester
try:
suggester = self.query_one("#suggester", CommandSuggester)
if suggester.display:
if not suggester.region.contains(event.x, event.y):
suggester.display = False
except Exception:
pass # Suggester may not be mounted yet
# Dismiss history search
try:
history_search = self.query_one("#history-search", HistorySearch)
if history_search.has_class("visible"):
if not history_search.region.contains(event.x, event.y):
history_search.hide()
return # Don't focus input if we just closed search
except Exception:
pass # History search may not be mounted yet
try:
history_vp = self.query_one("#history", HistoryViewport)
input_ctrl = self.query_one("#input", InputController)
if history_vp.region.contains(event.x, event.y):
clicked_on_focusable = False
for block in history_vp.query(BaseBlockWidget):
if block.region.contains(event.x, event.y):
for focusable in block.query("Button, Input, TextArea"):
if focusable.region.contains(event.x, event.y):
clicked_on_focusable = True
break
break
if not clicked_on_focusable:
input_ctrl.focus()
except Exception:
pass
async def on_input_controller_submitted(self, message: InputController.Submitted):
"""Handle input submission."""
await self.input_handler.handle_submission(message.value)
async def on_text_area_changed(self, message: TextArea.Changed):
"""Update command suggester."""
suggester = self.query_one("#suggester", CommandSuggester)
suggester.update_filter(message.text_area.text)
def on_input_controller_toggled(self, message: InputController.Toggled):
"""Handle mode toggle."""
self._update_status_bar()
self._update_prompt()
# Update container class for focus styling
try:
container = self.query_one("#input-container", Container)
if message.mode == "AI":
container.add_class("ai-mode")
else:
container.remove_class("ai-mode")
except Exception:
pass # Container may not be mounted yet
def on_history_search_selected(self, message: HistorySearch.Selected):
"""Handle history search selection."""
input_ctrl = self.query_one("#input", InputController)
input_ctrl.text = message.command
input_ctrl.focus()
input_ctrl.move_cursor((len(message.command), 0))
def on_history_search_cancelled(self, message: HistorySearch.Cancelled):
"""Handle history search cancellation."""
self.query_one("#input", InputController).focus()
async def on_command_palette_action_selected(
self, message: CommandPalette.ActionSelected
):
"""Handle command palette action selection."""
action = message.action
action_id = action.action_id
# Focus main input after palette closes
try:
self.query_one("#input", InputController).focus()
except Exception:
pass # Input may not be mounted yet
if action_id.startswith("slash:"):
# Execute slash command
cmd = action_id[6:] # Remove "slash:" prefix
await self.input_handler.handle_submission(cmd)
elif action_id.startswith("action:"):
# Execute action
action_name = action_id[7:] # Remove "action:" prefix
action_map = {
"toggle_ai_mode": self.action_toggle_ai_mode,
"clear_history": self.action_clear_history,
"quick_export": self.action_quick_export,
"search_history": self.action_search_history,
"open_help": self.action_open_help,
"select_model": self.action_select_model,
"change_theme": self.action_select_theme,
"select_provider": self.action_select_provider,
"cancel_operation": self.action_cancel_operation,
}
if action_name in action_map:
action_map[action_name]()
elif action_id.startswith("history:"):
# Put command in input
cmd = action_id[8:] # Remove "history:" prefix
input_ctrl = self.query_one("#input", InputController)
input_ctrl.text = cmd
input_ctrl.move_cursor((len(cmd), 0))
def on_command_palette_closed(self, message: CommandPalette.Closed):
"""Handle command palette close."""
try:
self.query_one("#input", InputController).focus()
except Exception:
pass # Input may not be mounted yet
async def on_base_block_widget_retry_requested(
self, message: BaseBlockWidget.RetryRequested
):
"""Handle retry button click."""
block = next((b for b in self.blocks if b.id == message.block_id), None)
if not block:
self.notify("Block not found", severity="error")
return
widget = self._find_widget_for_block(message.block_id)
if not widget:
self.notify("Widget not found", severity="error")
return
await self.execution_handler.regenerate_ai(block, widget)
async def on_base_block_widget_edit_requested(
self, message: BaseBlockWidget.EditRequested
):
"""Handle edit button click."""
input_ctrl = self.query_one("#input", InputController)
input_ctrl.text = message.content
input_ctrl.focus()
if not input_ctrl.is_ai_mode:
input_ctrl.toggle_mode()
self.notify("Edit and resubmit your query")
async def on_base_block_widget_copy_requested(
self, message: BaseBlockWidget.CopyRequested
):
"""Handle copy button click."""
copied = False
try:
import pyperclip
pyperclip.copy(message.content)
copied = True
except ImportError:
import asyncio
import subprocess
import sys
try:
if sys.platform == "darwin":
await asyncio.to_thread(
subprocess.run,
["pbcopy"],
input=message.content.encode(),
check=True,
)
else:
await asyncio.to_thread(
subprocess.run,
["xclip", "-selection", "clipboard"],
input=message.content.encode(),
check=True,
)
copied = True
except Exception:
self.notify("Failed to copy - install pyperclip", severity="error")
except Exception as e:
self.notify(f"Copy failed: {e}", severity="error")
if copied:
self._show_copy_feedback(message.block_id, message.copy_type)
def _show_copy_feedback(self, block_id: str, copy_type: str = "full") -> None:
from widgets.blocks.actions import ActionBar
from widgets.blocks.copy_types import CopyType
type_labels = {
CopyType.FULL: "Copied",
CopyType.CODE: "Code copied",
CopyType.MARKDOWN: "Markdown copied",
CopyType.RAW: "Raw text copied",
}
label = type_labels.get(copy_type, "Copied")
try:
history = self.query_one("#history")
for widget in history.query("ActionBar"):
if isinstance(widget, ActionBar) and widget.block_id == block_id:
widget.show_copy_feedback(label)
break
except Exception:
pass
async def on_base_block_widget_copy_menu_requested(
self, message: BaseBlockWidget.CopyMenuRequested
):
from widgets.blocks.actions import ActionBar
try:
history = self.query_one("#history")
for widget in history.query("ActionBar"):
if (
isinstance(widget, ActionBar)
and widget.block_id == message.block_id
):
widget.show_copy_menu()
break
except Exception:
pass
async def on_base_block_widget_fork_requested(
self, message: BaseBlockWidget.ForkRequested
):
"""Handle fork button click to create a conversation branch."""
block = next((b for b in self.blocks if b.id == message.block_id), None)
if not block:
self.notify("Block not found", severity="error")
return
# Create a fork point
branch_name = f"fork-{block.id[:4]}-{datetime.now().strftime('%H%M')}"
try:
self.branch_manager.fork(branch_name, self.blocks, block.id)
self.notify(f"Created branch: {branch_name}")
# Switch UI to the new branch (for now, we just truncate the view)
# In a full implementation, we'd clear history and re-mount blocks from branch
self.blocks = list(self.branch_manager.branches[branch_name])
history_vp = self.query_one("#history", HistoryViewport)
await history_vp.query(BaseBlockWidget).remove()
for b in self.blocks:
await history_vp.add_block(create_block(b))
history_vp.scroll_end()
except Exception as e:
self.notify(f"Fork failed: {e}", severity="error")
async def on_code_block_widget_run_code_requested(self, message):
"""Handle run code button click from code blocks."""
from widgets.blocks import execute_code
code = message.code
language = message.language
self.notify(f"Running {language} code...")
# Execute the code (output and exit_code unused - showing result handled elsewhere)
await execute_code(code, language)
async def on_code_block_widget_save_code_requested(self, message):
"""Handle save code button click from code blocks."""
from screens import SaveFileDialog
from widgets.blocks import get_file_extension
code = message.code
language = message.language
# Suggest a filename based on language
ext = get_file_extension(language)
suggested_name = f"code{ext}"
def on_saved(filepath):
if filepath:
self.notify(f"Code saved to {filepath}")
self.push_screen(SaveFileDialog(suggested_name, code), on_saved)
async def on_stop_button_pressed(self, message):
"""Handle stop button press from BlockFooter."""
await self._stop_process(message.block_id)
async def _stop_process(self, block_id: str):
"""Stop a running process by block ID."""
stopped = False
# Try to stop via process manager (executor cancellation happens inside stop if mapped)
if self.process_manager.stop(block_id):
stopped = True
if stopped:
self.notify("Process stopped", severity="warning")
# Reset CLI session so new commands create new blocks
if self.current_cli_block and self.current_cli_block.id == block_id:
# Update the widget state
if self.current_cli_widget:
self.current_cli_widget.set_loading(False)
self.current_cli_block.is_running = False
self.current_cli_block = None
self.current_cli_widget = None
else:
self.notify("No process to stop", severity="warning")
async def on_terminal_block_input_requested(self, message):
"""Handle keyboard input from TUI terminal blocks."""
block_id = message.block_id
data = message.data