shotgun-sh 0.2.3.dev2__py3-none-any.whl → 0.2.11.dev5__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.

Potentially problematic release.


This version of shotgun-sh might be problematic. Click here for more details.

Files changed (132) hide show
  1. shotgun/agents/agent_manager.py +664 -75
  2. shotgun/agents/common.py +76 -70
  3. shotgun/agents/config/constants.py +0 -6
  4. shotgun/agents/config/manager.py +78 -36
  5. shotgun/agents/config/models.py +41 -1
  6. shotgun/agents/config/provider.py +70 -15
  7. shotgun/agents/context_analyzer/__init__.py +28 -0
  8. shotgun/agents/context_analyzer/analyzer.py +471 -0
  9. shotgun/agents/context_analyzer/constants.py +9 -0
  10. shotgun/agents/context_analyzer/formatter.py +115 -0
  11. shotgun/agents/context_analyzer/models.py +212 -0
  12. shotgun/agents/conversation_history.py +125 -2
  13. shotgun/agents/conversation_manager.py +57 -19
  14. shotgun/agents/export.py +6 -7
  15. shotgun/agents/history/compaction.py +9 -4
  16. shotgun/agents/history/context_extraction.py +93 -6
  17. shotgun/agents/history/history_processors.py +14 -2
  18. shotgun/agents/history/token_counting/anthropic.py +49 -11
  19. shotgun/agents/history/token_counting/base.py +14 -3
  20. shotgun/agents/history/token_counting/openai.py +8 -0
  21. shotgun/agents/history/token_counting/sentencepiece_counter.py +8 -0
  22. shotgun/agents/history/token_counting/tokenizer_cache.py +3 -1
  23. shotgun/agents/history/token_counting/utils.py +0 -3
  24. shotgun/agents/models.py +50 -2
  25. shotgun/agents/plan.py +6 -7
  26. shotgun/agents/research.py +7 -8
  27. shotgun/agents/specify.py +6 -7
  28. shotgun/agents/tasks.py +6 -7
  29. shotgun/agents/tools/__init__.py +0 -2
  30. shotgun/agents/tools/codebase/codebase_shell.py +6 -0
  31. shotgun/agents/tools/codebase/directory_lister.py +6 -0
  32. shotgun/agents/tools/codebase/file_read.py +11 -2
  33. shotgun/agents/tools/codebase/query_graph.py +6 -0
  34. shotgun/agents/tools/codebase/retrieve_code.py +6 -0
  35. shotgun/agents/tools/file_management.py +82 -16
  36. shotgun/agents/tools/registry.py +217 -0
  37. shotgun/agents/tools/web_search/__init__.py +30 -18
  38. shotgun/agents/tools/web_search/anthropic.py +26 -5
  39. shotgun/agents/tools/web_search/gemini.py +23 -11
  40. shotgun/agents/tools/web_search/openai.py +22 -13
  41. shotgun/agents/tools/web_search/utils.py +2 -2
  42. shotgun/agents/usage_manager.py +16 -11
  43. shotgun/api_endpoints.py +7 -3
  44. shotgun/build_constants.py +1 -1
  45. shotgun/cli/clear.py +53 -0
  46. shotgun/cli/compact.py +186 -0
  47. shotgun/cli/config.py +8 -5
  48. shotgun/cli/context.py +111 -0
  49. shotgun/cli/export.py +1 -1
  50. shotgun/cli/feedback.py +4 -2
  51. shotgun/cli/models.py +1 -0
  52. shotgun/cli/plan.py +1 -1
  53. shotgun/cli/research.py +1 -1
  54. shotgun/cli/specify.py +1 -1
  55. shotgun/cli/tasks.py +1 -1
  56. shotgun/cli/update.py +16 -2
  57. shotgun/codebase/core/change_detector.py +5 -3
  58. shotgun/codebase/core/code_retrieval.py +4 -2
  59. shotgun/codebase/core/ingestor.py +10 -8
  60. shotgun/codebase/core/manager.py +13 -4
  61. shotgun/codebase/core/nl_query.py +1 -1
  62. shotgun/llm_proxy/__init__.py +5 -2
  63. shotgun/llm_proxy/clients.py +12 -7
  64. shotgun/logging_config.py +18 -27
  65. shotgun/main.py +73 -11
  66. shotgun/posthog_telemetry.py +23 -7
  67. shotgun/prompts/agents/export.j2 +18 -1
  68. shotgun/prompts/agents/partials/common_agent_system_prompt.j2 +5 -1
  69. shotgun/prompts/agents/partials/interactive_mode.j2 +24 -7
  70. shotgun/prompts/agents/plan.j2 +1 -1
  71. shotgun/prompts/agents/research.j2 +1 -1
  72. shotgun/prompts/agents/specify.j2 +270 -3
  73. shotgun/prompts/agents/state/system_state.j2 +4 -0
  74. shotgun/prompts/agents/tasks.j2 +1 -1
  75. shotgun/prompts/loader.py +2 -2
  76. shotgun/prompts/tools/web_search.j2 +14 -0
  77. shotgun/sentry_telemetry.py +7 -16
  78. shotgun/settings.py +238 -0
  79. shotgun/telemetry.py +18 -33
  80. shotgun/tui/app.py +243 -43
  81. shotgun/tui/commands/__init__.py +1 -1
  82. shotgun/tui/components/context_indicator.py +179 -0
  83. shotgun/tui/components/mode_indicator.py +70 -0
  84. shotgun/tui/components/status_bar.py +48 -0
  85. shotgun/tui/containers.py +91 -0
  86. shotgun/tui/dependencies.py +39 -0
  87. shotgun/tui/protocols.py +45 -0
  88. shotgun/tui/screens/chat/__init__.py +5 -0
  89. shotgun/tui/screens/chat/chat.tcss +54 -0
  90. shotgun/tui/screens/chat/chat_screen.py +1202 -0
  91. shotgun/tui/screens/chat/codebase_index_prompt_screen.py +64 -0
  92. shotgun/tui/screens/chat/codebase_index_selection.py +12 -0
  93. shotgun/tui/screens/chat/help_text.py +40 -0
  94. shotgun/tui/screens/chat/prompt_history.py +48 -0
  95. shotgun/tui/screens/chat.tcss +11 -0
  96. shotgun/tui/screens/chat_screen/command_providers.py +78 -2
  97. shotgun/tui/screens/chat_screen/history/__init__.py +22 -0
  98. shotgun/tui/screens/chat_screen/history/agent_response.py +66 -0
  99. shotgun/tui/screens/chat_screen/history/chat_history.py +116 -0
  100. shotgun/tui/screens/chat_screen/history/formatters.py +115 -0
  101. shotgun/tui/screens/chat_screen/history/partial_response.py +43 -0
  102. shotgun/tui/screens/chat_screen/history/user_question.py +42 -0
  103. shotgun/tui/screens/confirmation_dialog.py +151 -0
  104. shotgun/tui/screens/feedback.py +4 -4
  105. shotgun/tui/screens/github_issue.py +102 -0
  106. shotgun/tui/screens/model_picker.py +49 -24
  107. shotgun/tui/screens/onboarding.py +431 -0
  108. shotgun/tui/screens/pipx_migration.py +153 -0
  109. shotgun/tui/screens/provider_config.py +50 -27
  110. shotgun/tui/screens/shotgun_auth.py +2 -2
  111. shotgun/tui/screens/welcome.py +32 -10
  112. shotgun/tui/services/__init__.py +5 -0
  113. shotgun/tui/services/conversation_service.py +184 -0
  114. shotgun/tui/state/__init__.py +7 -0
  115. shotgun/tui/state/processing_state.py +185 -0
  116. shotgun/tui/utils/mode_progress.py +14 -7
  117. shotgun/tui/widgets/__init__.py +5 -0
  118. shotgun/tui/widgets/widget_coordinator.py +262 -0
  119. shotgun/utils/datetime_utils.py +77 -0
  120. shotgun/utils/file_system_utils.py +22 -2
  121. shotgun/utils/marketing.py +110 -0
  122. shotgun/utils/update_checker.py +69 -14
  123. shotgun_sh-0.2.11.dev5.dist-info/METADATA +130 -0
  124. shotgun_sh-0.2.11.dev5.dist-info/RECORD +193 -0
  125. {shotgun_sh-0.2.3.dev2.dist-info → shotgun_sh-0.2.11.dev5.dist-info}/entry_points.txt +1 -0
  126. {shotgun_sh-0.2.3.dev2.dist-info → shotgun_sh-0.2.11.dev5.dist-info}/licenses/LICENSE +1 -1
  127. shotgun/agents/tools/user_interaction.py +0 -37
  128. shotgun/tui/screens/chat.py +0 -804
  129. shotgun/tui/screens/chat_screen/history.py +0 -352
  130. shotgun_sh-0.2.3.dev2.dist-info/METADATA +0 -467
  131. shotgun_sh-0.2.3.dev2.dist-info/RECORD +0 -154
  132. {shotgun_sh-0.2.3.dev2.dist-info → shotgun_sh-0.2.11.dev5.dist-info}/WHEEL +0 -0
@@ -0,0 +1,1202 @@
1
+ """Main chat screen implementation."""
2
+
3
+ import asyncio
4
+ import logging
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import cast
8
+
9
+ from pydantic_ai.messages import (
10
+ ModelMessage,
11
+ ModelRequest,
12
+ ModelResponse,
13
+ TextPart,
14
+ ToolReturnPart,
15
+ UserPromptPart,
16
+ )
17
+ from textual import events, on, work
18
+ from textual.app import ComposeResult
19
+ from textual.command import CommandPalette
20
+ from textual.containers import Container, Grid
21
+ from textual.keys import Keys
22
+ from textual.reactive import reactive
23
+ from textual.screen import Screen
24
+ from textual.widgets import Static
25
+
26
+ from shotgun.agents.agent_manager import (
27
+ AgentManager,
28
+ ClarifyingQuestionsMessage,
29
+ CompactionCompletedMessage,
30
+ CompactionStartedMessage,
31
+ MessageHistoryUpdated,
32
+ ModelConfigUpdated,
33
+ PartialResponseMessage,
34
+ )
35
+ from shotgun.agents.config import get_config_manager
36
+ from shotgun.agents.config.models import MODEL_SPECS
37
+ from shotgun.agents.conversation_manager import ConversationManager
38
+ from shotgun.agents.history.compaction import apply_persistent_compaction
39
+ from shotgun.agents.history.token_estimation import estimate_tokens_from_messages
40
+ from shotgun.agents.models import (
41
+ AgentDeps,
42
+ AgentType,
43
+ FileOperationTracker,
44
+ )
45
+ from shotgun.codebase.core.manager import (
46
+ CodebaseAlreadyIndexedError,
47
+ CodebaseGraphManager,
48
+ )
49
+ from shotgun.codebase.models import IndexProgress, ProgressPhase
50
+ from shotgun.posthog_telemetry import track_event
51
+ from shotgun.sdk.codebase import CodebaseSDK
52
+ from shotgun.sdk.exceptions import CodebaseNotFoundError, InvalidPathError
53
+ from shotgun.tui.commands import CommandHandler
54
+ from shotgun.tui.components.context_indicator import ContextIndicator
55
+ from shotgun.tui.components.mode_indicator import ModeIndicator
56
+ from shotgun.tui.components.prompt_input import PromptInput
57
+ from shotgun.tui.components.spinner import Spinner
58
+ from shotgun.tui.components.status_bar import StatusBar
59
+ from shotgun.tui.screens.chat.codebase_index_prompt_screen import (
60
+ CodebaseIndexPromptScreen,
61
+ )
62
+ from shotgun.tui.screens.chat.codebase_index_selection import CodebaseIndexSelection
63
+ from shotgun.tui.screens.chat.help_text import (
64
+ help_text_empty_dir,
65
+ help_text_with_codebase,
66
+ )
67
+ from shotgun.tui.screens.chat.prompt_history import PromptHistory
68
+ from shotgun.tui.screens.chat_screen.command_providers import (
69
+ DeleteCodebasePaletteProvider,
70
+ UnifiedCommandProvider,
71
+ )
72
+ from shotgun.tui.screens.chat_screen.hint_message import HintMessage
73
+ from shotgun.tui.screens.chat_screen.history import ChatHistory
74
+ from shotgun.tui.screens.confirmation_dialog import ConfirmationDialog
75
+ from shotgun.tui.screens.onboarding import OnboardingModal
76
+ from shotgun.tui.services.conversation_service import ConversationService
77
+ from shotgun.tui.state.processing_state import ProcessingStateManager
78
+ from shotgun.tui.utils.mode_progress import PlaceholderHints
79
+ from shotgun.tui.widgets.widget_coordinator import WidgetCoordinator
80
+ from shotgun.utils import get_shotgun_home
81
+ from shotgun.utils.marketing import MarketingManager
82
+
83
+ logger = logging.getLogger(__name__)
84
+
85
+
86
+ class ChatScreen(Screen[None]):
87
+ CSS_PATH = "chat.tcss"
88
+
89
+ BINDINGS = [
90
+ ("ctrl+p", "command_palette", "Command Palette"),
91
+ ("shift+tab", "toggle_mode", "Toggle mode"),
92
+ ("ctrl+u", "show_usage", "Show usage"),
93
+ ]
94
+
95
+ COMMANDS = {
96
+ UnifiedCommandProvider,
97
+ }
98
+
99
+ value = reactive("")
100
+ mode = reactive(AgentType.RESEARCH)
101
+ history: PromptHistory = PromptHistory()
102
+ messages = reactive(list[ModelMessage | HintMessage]())
103
+ indexing_job: reactive[CodebaseIndexSelection | None] = reactive(None)
104
+ partial_message: reactive[ModelMessage | None] = reactive(None)
105
+
106
+ # Q&A mode state (for structured output clarifying questions)
107
+ qa_mode = reactive(False)
108
+ qa_questions: list[str] = []
109
+ qa_current_index = reactive(0)
110
+ qa_answers: list[str] = []
111
+
112
+ # Working state - keep reactive for Textual watchers
113
+ working = reactive(False)
114
+
115
+ def __init__(
116
+ self,
117
+ agent_manager: AgentManager,
118
+ conversation_manager: ConversationManager,
119
+ conversation_service: ConversationService,
120
+ widget_coordinator: WidgetCoordinator,
121
+ processing_state: ProcessingStateManager,
122
+ command_handler: CommandHandler,
123
+ placeholder_hints: PlaceholderHints,
124
+ codebase_sdk: CodebaseSDK,
125
+ deps: AgentDeps,
126
+ continue_session: bool = False,
127
+ force_reindex: bool = False,
128
+ ) -> None:
129
+ """Initialize the ChatScreen.
130
+
131
+ All dependencies must be provided via dependency injection.
132
+ No objects are created in the constructor.
133
+
134
+ Args:
135
+ agent_manager: AgentManager instance for managing agent interactions
136
+ conversation_manager: ConversationManager for conversation persistence
137
+ conversation_service: ConversationService for conversation save/load/restore
138
+ widget_coordinator: WidgetCoordinator for centralized widget updates
139
+ processing_state: ProcessingStateManager for managing processing state
140
+ command_handler: CommandHandler for handling slash commands
141
+ placeholder_hints: PlaceholderHints for providing input hints
142
+ codebase_sdk: CodebaseSDK for codebase indexing operations
143
+ deps: AgentDeps configuration for agent dependencies
144
+ continue_session: Whether to continue a previous session
145
+ force_reindex: Whether to force reindexing of codebases
146
+ """
147
+ super().__init__()
148
+
149
+ # All dependencies are now required and injected
150
+ self.deps = deps
151
+ self.codebase_sdk = codebase_sdk
152
+ self.agent_manager = agent_manager
153
+ self.command_handler = command_handler
154
+ self.placeholder_hints = placeholder_hints
155
+ self.conversation_manager = conversation_manager
156
+ self.conversation_service = conversation_service
157
+ self.widget_coordinator = widget_coordinator
158
+ self.processing_state = processing_state
159
+ self.continue_session = continue_session
160
+ self.force_reindex = force_reindex
161
+
162
+ def on_mount(self) -> None:
163
+ # Use widget coordinator to focus input
164
+ self.widget_coordinator.update_prompt_input(focus=True)
165
+ # Hide spinner initially
166
+ self.query_one("#spinner").display = False
167
+
168
+ # Bind spinner to processing state manager
169
+ self.processing_state.bind_spinner(self.query_one("#spinner", Spinner))
170
+
171
+ # Load conversation history if --continue flag was provided
172
+ # Use call_later to handle async exists() check
173
+ if self.continue_session:
174
+ self.call_later(self._check_and_load_conversation)
175
+
176
+ self.call_later(self.check_if_codebase_is_indexed)
177
+ # Initial update of context indicator
178
+ self.update_context_indicator()
179
+
180
+ # Show onboarding popup if not shown before
181
+ self.call_later(self._check_and_show_onboarding)
182
+
183
+ async def on_key(self, event: events.Key) -> None:
184
+ """Handle key presses for cancellation."""
185
+ # If escape is pressed during Q&A mode, exit Q&A
186
+ if event.key in (Keys.Escape, Keys.ControlC) and self.qa_mode:
187
+ self._exit_qa_mode()
188
+ # Re-enable the input
189
+ self.widget_coordinator.update_prompt_input(focus=True)
190
+ # Prevent the event from propagating (don't quit the app)
191
+ event.stop()
192
+ return
193
+
194
+ # If escape or ctrl+c is pressed while agent is working, cancel the operation
195
+ if event.key in (Keys.Escape, Keys.ControlC):
196
+ if self.processing_state.cancel_current_operation(cancel_key=event.key):
197
+ # Show cancellation message
198
+ self.mount_hint("⚠️ Cancelling operation...")
199
+ # Re-enable the input
200
+ self.widget_coordinator.update_prompt_input(focus=True)
201
+ # Prevent the event from propagating (don't quit the app)
202
+ event.stop()
203
+
204
+ @work
205
+ async def check_if_codebase_is_indexed(self) -> None:
206
+ cur_dir = Path.cwd().resolve()
207
+ is_empty = all(
208
+ dir.is_dir() and dir.name in ["__pycache__", ".git", ".shotgun"]
209
+ for dir in cur_dir.iterdir()
210
+ )
211
+ if is_empty or self.continue_session:
212
+ return
213
+
214
+ # If force_reindex is True, delete any existing graphs for this directory
215
+ if self.force_reindex:
216
+ accessible_graphs = (
217
+ await self.codebase_sdk.list_codebases_for_directory()
218
+ ).graphs
219
+ for graph in accessible_graphs:
220
+ try:
221
+ await self.codebase_sdk.delete_codebase(graph.graph_id)
222
+ logger.info(
223
+ f"Deleted existing graph {graph.graph_id} due to --force-reindex"
224
+ )
225
+ except Exception as e:
226
+ logger.warning(
227
+ f"Failed to delete graph {graph.graph_id} during force reindex: {e}"
228
+ )
229
+
230
+ # Check if the current directory has any accessible codebases
231
+ accessible_graphs = (
232
+ await self.codebase_sdk.list_codebases_for_directory()
233
+ ).graphs
234
+ if accessible_graphs:
235
+ self.mount_hint(help_text_with_codebase(already_indexed=True))
236
+ return
237
+
238
+ # Ask user if they want to index the current directory
239
+ should_index = await self.app.push_screen_wait(CodebaseIndexPromptScreen())
240
+ if not should_index:
241
+ self.mount_hint(help_text_empty_dir())
242
+ return
243
+
244
+ self.mount_hint(help_text_with_codebase(already_indexed=False))
245
+
246
+ # Auto-index the current directory with its name
247
+ cwd_name = cur_dir.name
248
+ selection = CodebaseIndexSelection(repo_path=cur_dir, name=cwd_name)
249
+ self.call_later(lambda: self.index_codebase(selection))
250
+
251
+ def watch_mode(self, new_mode: AgentType) -> None:
252
+ """React to mode changes by updating the agent manager."""
253
+
254
+ if self.is_mounted:
255
+ self.agent_manager.set_agent(new_mode)
256
+ # Use widget coordinator for all widget updates
257
+ self.widget_coordinator.update_for_mode_change(new_mode)
258
+
259
+ def watch_working(self, is_working: bool) -> None:
260
+ """Show or hide the spinner based on working state."""
261
+ logger.debug(f"[WATCH] watch_working called - is_working={is_working}")
262
+ if self.is_mounted:
263
+ # Use widget coordinator for all widget updates
264
+ self.widget_coordinator.update_for_processing_state(is_working)
265
+
266
+ def watch_qa_mode(self, qa_mode_active: bool) -> None:
267
+ """Update UI when Q&A mode state changes."""
268
+ if self.is_mounted:
269
+ # Use widget coordinator for all widget updates
270
+ self.widget_coordinator.update_for_qa_mode(qa_mode_active)
271
+
272
+ def watch_messages(self, messages: list[ModelMessage | HintMessage]) -> None:
273
+ """Update the chat history when messages change."""
274
+ if self.is_mounted:
275
+ # Use widget coordinator for all widget updates
276
+ self.widget_coordinator.update_messages(messages)
277
+
278
+ def action_toggle_mode(self) -> None:
279
+ # Prevent mode switching during Q&A
280
+ if self.qa_mode:
281
+ self.notify(
282
+ "Cannot switch modes while answering questions",
283
+ severity="warning",
284
+ timeout=3,
285
+ )
286
+ return
287
+
288
+ modes = [
289
+ AgentType.RESEARCH,
290
+ AgentType.SPECIFY,
291
+ AgentType.PLAN,
292
+ AgentType.TASKS,
293
+ AgentType.EXPORT,
294
+ ]
295
+ self.mode = modes[(modes.index(self.mode) + 1) % len(modes)]
296
+ self.agent_manager.set_agent(self.mode)
297
+ # Re-focus input after mode change
298
+ self.call_later(lambda: self.widget_coordinator.update_prompt_input(focus=True))
299
+
300
+ def action_show_usage(self) -> None:
301
+ usage_hint = self.agent_manager.get_usage_hint()
302
+ logger.info(f"Usage hint: {usage_hint}")
303
+ if usage_hint:
304
+ self.mount_hint(usage_hint)
305
+ else:
306
+ self.notify("No usage hint available", severity="error")
307
+
308
+ async def action_show_context(self) -> None:
309
+ context_hint = await self.agent_manager.get_context_hint()
310
+ if context_hint:
311
+ self.mount_hint(context_hint)
312
+ else:
313
+ self.notify("No context analysis available", severity="error")
314
+
315
+ def action_view_onboarding(self) -> None:
316
+ """Show the onboarding modal."""
317
+ self.app.push_screen(OnboardingModal())
318
+
319
+ @work
320
+ async def action_compact_conversation(self) -> None:
321
+ """Compact the conversation history to reduce size."""
322
+ logger.debug(f"[COMPACT] Starting compaction - working={self.working}")
323
+
324
+ try:
325
+ # Show spinner and enable ESC cancellation
326
+ from textual.worker import get_current_worker
327
+
328
+ self.processing_state.start_processing("Compacting Conversation...")
329
+ self.processing_state.bind_worker(get_current_worker())
330
+ logger.debug(f"[COMPACT] Processing started - working={self.working}")
331
+
332
+ # Get current message count and tokens
333
+ original_count = len(self.agent_manager.message_history)
334
+ original_tokens = await estimate_tokens_from_messages(
335
+ self.agent_manager.message_history, self.deps.llm_model
336
+ )
337
+
338
+ # Log compaction start
339
+ logger.info(
340
+ f"Starting conversation compaction - {original_count} messages, {original_tokens} tokens"
341
+ )
342
+
343
+ # Post compaction started event
344
+ self.agent_manager.post_message(CompactionStartedMessage())
345
+ logger.debug("[COMPACT] Posted CompactionStartedMessage")
346
+
347
+ # Apply compaction with force=True to bypass threshold checks
348
+ compacted_messages = await apply_persistent_compaction(
349
+ self.agent_manager.message_history, self.deps, force=True
350
+ )
351
+
352
+ logger.debug(
353
+ f"[COMPACT] Compacted messages: count={len(compacted_messages)}, "
354
+ f"last_message_type={type(compacted_messages[-1]).__name__ if compacted_messages else 'None'}"
355
+ )
356
+
357
+ # Check last response usage
358
+ last_response = next(
359
+ (
360
+ msg
361
+ for msg in reversed(compacted_messages)
362
+ if isinstance(msg, ModelResponse)
363
+ ),
364
+ None,
365
+ )
366
+ if last_response:
367
+ logger.debug(
368
+ f"[COMPACT] Last response has usage: {last_response.usage is not None}, "
369
+ f"usage={last_response.usage if last_response.usage else 'None'}"
370
+ )
371
+ else:
372
+ logger.warning(
373
+ "[COMPACT] No ModelResponse found in compacted messages!"
374
+ )
375
+
376
+ # Update agent manager's message history
377
+ self.agent_manager.message_history = compacted_messages
378
+ logger.debug("[COMPACT] Updated agent_manager.message_history")
379
+
380
+ # Calculate after metrics
381
+ compacted_count = len(compacted_messages)
382
+ compacted_tokens = await estimate_tokens_from_messages(
383
+ compacted_messages, self.deps.llm_model
384
+ )
385
+
386
+ # Calculate reductions
387
+ message_reduction = (
388
+ ((original_count - compacted_count) / original_count) * 100
389
+ if original_count > 0
390
+ else 0
391
+ )
392
+ token_reduction = (
393
+ ((original_tokens - compacted_tokens) / original_tokens) * 100
394
+ if original_tokens > 0
395
+ else 0
396
+ )
397
+
398
+ # Save to conversation file
399
+ conversation_file = get_shotgun_home() / "conversation.json"
400
+ manager = ConversationManager(conversation_file)
401
+ conversation = await manager.load()
402
+
403
+ if conversation:
404
+ conversation.set_agent_messages(compacted_messages)
405
+ await manager.save(conversation)
406
+
407
+ # Post compaction completed event
408
+ self.agent_manager.post_message(CompactionCompletedMessage())
409
+
410
+ # Post message history updated event
411
+ self.agent_manager.post_message(
412
+ MessageHistoryUpdated(
413
+ messages=self.agent_manager.ui_message_history.copy(),
414
+ agent_type=self.agent_manager._current_agent_type,
415
+ file_operations=None,
416
+ )
417
+ )
418
+ logger.debug("[COMPACT] Posted MessageHistoryUpdated event")
419
+
420
+ # Force immediate context indicator update
421
+ logger.debug("[COMPACT] Calling update_context_indicator()")
422
+ self.update_context_indicator()
423
+
424
+ # Log compaction completion
425
+ logger.info(
426
+ f"Compaction completed: {original_count} → {compacted_count} messages "
427
+ f"({message_reduction:.0f}% message reduction, {token_reduction:.0f}% token reduction)"
428
+ )
429
+
430
+ # Add persistent hint message with stats
431
+ self.mount_hint(
432
+ f"✓ Compacted conversation: {original_count} → {compacted_count} messages "
433
+ f"({message_reduction:.0f}% message reduction, {token_reduction:.0f}% token reduction)"
434
+ )
435
+
436
+ except Exception as e:
437
+ logger.error(f"Failed to compact conversation: {e}", exc_info=True)
438
+ self.notify(f"Failed to compact: {e}", severity="error")
439
+ finally:
440
+ # Hide spinner
441
+ self.processing_state.stop_processing()
442
+ logger.debug(f"[COMPACT] Processing stopped - working={self.working}")
443
+
444
+ @work
445
+ async def action_clear_conversation(self) -> None:
446
+ """Clear the conversation history."""
447
+ # Show confirmation dialog
448
+ should_clear = await self.app.push_screen_wait(
449
+ ConfirmationDialog(
450
+ title="Clear conversation?",
451
+ message="This will permanently delete your entire conversation history. "
452
+ "All messages, context, and progress will be lost. "
453
+ "This action cannot be undone.",
454
+ confirm_label="Clear",
455
+ cancel_label="Keep",
456
+ confirm_variant="warning",
457
+ danger=True,
458
+ )
459
+ )
460
+
461
+ if not should_clear:
462
+ return # User cancelled
463
+
464
+ try:
465
+ # Clear message histories
466
+ self.agent_manager.message_history = []
467
+ self.agent_manager.ui_message_history = []
468
+
469
+ # Use conversation service to clear conversation
470
+ await self.conversation_service.clear_conversation()
471
+
472
+ # Post message history updated event to refresh UI
473
+ self.agent_manager.post_message(
474
+ MessageHistoryUpdated(
475
+ messages=[],
476
+ agent_type=self.agent_manager._current_agent_type,
477
+ file_operations=None,
478
+ )
479
+ )
480
+
481
+ # Show persistent success message
482
+ self.mount_hint("✓ Conversation cleared - Starting fresh!")
483
+
484
+ except Exception as e:
485
+ logger.error(f"Failed to clear conversation: {e}", exc_info=True)
486
+ self.notify(f"Failed to clear: {e}", severity="error")
487
+
488
+ @work(exclusive=False)
489
+ async def update_context_indicator(self) -> None:
490
+ """Update the context indicator with current usage data."""
491
+ logger.debug("[CONTEXT] update_context_indicator called")
492
+ try:
493
+ logger.debug(
494
+ f"[CONTEXT] Getting context analysis - "
495
+ f"message_history_count={len(self.agent_manager.message_history)}"
496
+ )
497
+ analysis = await self.agent_manager.get_context_analysis()
498
+
499
+ if analysis:
500
+ logger.debug(
501
+ f"[CONTEXT] Analysis received - "
502
+ f"agent_context_tokens={analysis.agent_context_tokens}, "
503
+ f"max_usable_tokens={analysis.max_usable_tokens}, "
504
+ f"percentage={round((analysis.agent_context_tokens / analysis.max_usable_tokens) * 100, 1) if analysis.max_usable_tokens > 0 else 0}%"
505
+ )
506
+ else:
507
+ logger.warning("[CONTEXT] Analysis is None!")
508
+
509
+ model_name = self.deps.llm_model.name
510
+ # Use widget coordinator for context indicator update
511
+ self.widget_coordinator.update_context_indicator(analysis, model_name)
512
+ except Exception as e:
513
+ logger.error(
514
+ f"[CONTEXT] Failed to update context indicator: {e}", exc_info=True
515
+ )
516
+
517
+ @work(exclusive=False)
518
+ async def update_context_indicator_with_messages(
519
+ self,
520
+ agent_messages: list[ModelMessage],
521
+ ui_messages: list[ModelMessage | HintMessage],
522
+ ) -> None:
523
+ """Update the context indicator with specific message sets (for streaming updates).
524
+
525
+ Args:
526
+ agent_messages: Agent message history including streaming messages (for token counting)
527
+ ui_messages: UI message history including hints and streaming messages
528
+ """
529
+ try:
530
+ from shotgun.agents.context_analyzer.analyzer import ContextAnalyzer
531
+
532
+ analyzer = ContextAnalyzer(self.deps.llm_model)
533
+ # Analyze the combined message histories for accurate progressive token counts
534
+ analysis = await analyzer.analyze_conversation(agent_messages, ui_messages)
535
+
536
+ if analysis:
537
+ model_name = self.deps.llm_model.name
538
+ self.widget_coordinator.update_context_indicator(analysis, model_name)
539
+ except Exception as e:
540
+ logger.error(
541
+ f"Failed to update context indicator with streaming messages: {e}",
542
+ exc_info=True,
543
+ )
544
+
545
+ def compose(self) -> ComposeResult:
546
+ """Create child widgets for the app."""
547
+ with Container(id="window"):
548
+ yield self.agent_manager
549
+ yield ChatHistory()
550
+ with Container(id="footer"):
551
+ yield Spinner(
552
+ text="Processing...",
553
+ id="spinner",
554
+ classes="" if self.working else "hidden",
555
+ )
556
+ yield StatusBar(working=self.working)
557
+ yield PromptInput(
558
+ text=self.value,
559
+ highlight_cursor_line=False,
560
+ id="prompt-input",
561
+ placeholder=self._placeholder_for_mode(self.mode),
562
+ )
563
+ with Grid():
564
+ yield ModeIndicator(mode=self.mode)
565
+ with Container(id="right-footer-indicators"):
566
+ yield ContextIndicator(id="context-indicator")
567
+ yield Static("", id="indexing-job-display")
568
+
569
+ def mount_hint(self, markdown: str) -> None:
570
+ hint = HintMessage(message=markdown)
571
+ self.agent_manager.add_hint_message(hint)
572
+
573
+ @on(PartialResponseMessage)
574
+ def handle_partial_response(self, event: PartialResponseMessage) -> None:
575
+ self.partial_message = event.message
576
+
577
+ # Filter event.messages to exclude ModelRequest with only ToolReturnPart
578
+ # These are intermediate tool results that would render as empty (UserQuestionWidget
579
+ # filters out ToolReturnPart in format_prompt_parts), causing user messages to disappear
580
+ filtered_event_messages: list[ModelMessage] = []
581
+ for msg in event.messages:
582
+ if isinstance(msg, ModelRequest):
583
+ # Check if this ModelRequest has any user-visible parts
584
+ has_user_content = any(
585
+ not isinstance(part, ToolReturnPart) for part in msg.parts
586
+ )
587
+ if has_user_content:
588
+ filtered_event_messages.append(msg)
589
+ # Skip ModelRequest with only ToolReturnPart
590
+ else:
591
+ # Keep all ModelResponse and other message types
592
+ filtered_event_messages.append(msg)
593
+
594
+ # Build new message list combining existing messages with new streaming content
595
+ new_message_list = self.messages + cast(
596
+ list[ModelMessage | HintMessage], filtered_event_messages
597
+ )
598
+
599
+ # Use widget coordinator to set partial response
600
+ self.widget_coordinator.set_partial_response(
601
+ self.partial_message, new_message_list
602
+ )
603
+
604
+ # Update context indicator with full message history including streaming messages
605
+ # Combine existing agent history with new streaming messages for accurate token count
606
+ combined_agent_history = self.agent_manager.message_history + event.messages
607
+ self.update_context_indicator_with_messages(
608
+ combined_agent_history, new_message_list
609
+ )
610
+
611
+ def _clear_partial_response(self) -> None:
612
+ # Use widget coordinator to clear partial response
613
+ self.widget_coordinator.set_partial_response(None, self.messages)
614
+
615
+ def _exit_qa_mode(self) -> None:
616
+ """Exit Q&A mode and clean up state."""
617
+ # Track cancellation event
618
+ track_event(
619
+ "qa_mode_cancelled",
620
+ {
621
+ "questions_total": len(self.qa_questions),
622
+ "questions_answered": len(self.qa_answers),
623
+ },
624
+ )
625
+
626
+ # Clear Q&A state
627
+ self.qa_mode = False
628
+ self.qa_questions = []
629
+ self.qa_answers = []
630
+ self.qa_current_index = 0
631
+
632
+ # Show cancellation message
633
+ self.mount_hint("⚠️ Q&A cancelled - You can continue the conversation.")
634
+
635
+ @on(ClarifyingQuestionsMessage)
636
+ def handle_clarifying_questions(self, event: ClarifyingQuestionsMessage) -> None:
637
+ """Handle clarifying questions from agent structured output.
638
+
639
+ Note: Hints are now added synchronously in agent_manager.run() before this
640
+ handler is called, so we only need to set up Q&A mode state here.
641
+ """
642
+ # Clear any streaming partial response (removes final_result JSON)
643
+ self._clear_partial_response()
644
+
645
+ # Enter Q&A mode
646
+ self.qa_mode = True
647
+ self.qa_questions = event.questions
648
+ self.qa_current_index = 0
649
+ self.qa_answers = []
650
+
651
+ @on(MessageHistoryUpdated)
652
+ async def handle_message_history_updated(
653
+ self, event: MessageHistoryUpdated
654
+ ) -> None:
655
+ """Handle message history updates from the agent manager."""
656
+ self._clear_partial_response()
657
+ self.messages = event.messages
658
+
659
+ # Use widget coordinator to refresh placeholder and mode indicator
660
+ self.widget_coordinator.update_prompt_input(
661
+ placeholder=self._placeholder_for_mode(self.mode)
662
+ )
663
+ self.widget_coordinator.refresh_mode_indicator()
664
+
665
+ # Update context indicator
666
+ self.update_context_indicator()
667
+
668
+ # If there are file operations, add a message showing the modified files
669
+ if event.file_operations:
670
+ chat_history = self.query_one(ChatHistory)
671
+ if chat_history.vertical_tail:
672
+ tracker = FileOperationTracker(operations=event.file_operations)
673
+ display_path = tracker.get_display_path()
674
+
675
+ if display_path:
676
+ # Create a simple markdown message with the file path
677
+ # The terminal emulator will make this clickable automatically
678
+ path_obj = Path(display_path)
679
+
680
+ if len(event.file_operations) == 1:
681
+ message = f"📝 Modified: `{display_path}`"
682
+ else:
683
+ num_files = len({op.file_path for op in event.file_operations})
684
+ if path_obj.is_dir():
685
+ message = (
686
+ f"📁 Modified {num_files} files in: `{display_path}`"
687
+ )
688
+ else:
689
+ # Common path is a file, show parent directory
690
+ message = (
691
+ f"📁 Modified {num_files} files in: `{path_obj.parent}`"
692
+ )
693
+
694
+ self.mount_hint(message)
695
+
696
+ # Check and display any marketing messages
697
+ from shotgun.tui.app import ShotgunApp
698
+
699
+ app = cast(ShotgunApp, self.app)
700
+ await MarketingManager.check_and_display_messages(
701
+ app.config_manager, event.file_operations, self.mount_hint
702
+ )
703
+
704
+ @on(CompactionStartedMessage)
705
+ def handle_compaction_started(self, event: CompactionStartedMessage) -> None:
706
+ """Update spinner text when compaction starts."""
707
+ # Use widget coordinator to update spinner text
708
+ self.widget_coordinator.update_spinner_text("Compacting Conversation...")
709
+
710
+ @on(CompactionCompletedMessage)
711
+ def handle_compaction_completed(self, event: CompactionCompletedMessage) -> None:
712
+ """Reset spinner text when compaction completes."""
713
+ # Use widget coordinator to update spinner text
714
+ self.widget_coordinator.update_spinner_text("Processing...")
715
+
716
+ async def handle_model_selected(self, result: ModelConfigUpdated | None) -> None:
717
+ """Handle model selection from ModelPickerScreen.
718
+
719
+ Called as a callback when the ModelPickerScreen is dismissed.
720
+
721
+ Args:
722
+ result: ModelConfigUpdated if a model was selected, None if cancelled
723
+ """
724
+ if result is None:
725
+ return
726
+
727
+ try:
728
+ # Update the model configuration in dependencies
729
+ self.deps.llm_model = result.model_config
730
+
731
+ # Update the agent manager's model configuration
732
+ self.agent_manager.deps.llm_model = result.model_config
733
+
734
+ # Get current analysis and update context indicator via coordinator
735
+ analysis = await self.agent_manager.get_context_analysis()
736
+ self.widget_coordinator.update_context_indicator(analysis, result.new_model)
737
+
738
+ # Get model display name for user feedback
739
+ model_spec = MODEL_SPECS.get(result.new_model)
740
+ model_display = (
741
+ model_spec.short_name if model_spec else str(result.new_model)
742
+ )
743
+
744
+ # Format provider information
745
+ key_method = (
746
+ "Shotgun Account" if result.key_provider == "shotgun" else "BYOK"
747
+ )
748
+ provider_display = result.provider.value.title()
749
+
750
+ # Track model switch in telemetry
751
+ track_event(
752
+ "model_switched",
753
+ {
754
+ "old_model": str(result.old_model) if result.old_model else None,
755
+ "new_model": str(result.new_model),
756
+ "provider": result.provider.value,
757
+ "key_provider": result.key_provider.value,
758
+ },
759
+ )
760
+
761
+ # Show confirmation to user with provider info
762
+ self.agent_manager.add_hint_message(
763
+ HintMessage(
764
+ message=f"✓ Switched to {model_display} ({provider_display}, {key_method})"
765
+ )
766
+ )
767
+
768
+ except Exception as e:
769
+ logger.error(f"Failed to handle model selection: {e}")
770
+ self.agent_manager.add_hint_message(
771
+ HintMessage(message=f"⚠ Failed to update model configuration: {e}")
772
+ )
773
+
774
+ @on(PromptInput.Submitted)
775
+ async def handle_submit(self, message: PromptInput.Submitted) -> None:
776
+ text = message.text.strip()
777
+
778
+ # If empty text, just clear input and return
779
+ if not text:
780
+ self.widget_coordinator.update_prompt_input(clear=True)
781
+ self.value = ""
782
+ return
783
+
784
+ # Handle Q&A mode (from structured output clarifying questions)
785
+ if self.qa_mode and self.qa_questions:
786
+ # Collect answer
787
+ self.qa_answers.append(text)
788
+
789
+ # Show answer
790
+ if len(self.qa_questions) == 1:
791
+ self.agent_manager.add_hint_message(
792
+ HintMessage(message=f"**A:** {text}")
793
+ )
794
+ else:
795
+ q_num = self.qa_current_index + 1
796
+ self.agent_manager.add_hint_message(
797
+ HintMessage(message=f"**A{q_num}:** {text}")
798
+ )
799
+
800
+ # Move to next or finish
801
+ self.qa_current_index += 1
802
+
803
+ if self.qa_current_index < len(self.qa_questions):
804
+ # Show next question
805
+ next_q = self.qa_questions[self.qa_current_index]
806
+ next_q_num = self.qa_current_index + 1
807
+ self.agent_manager.add_hint_message(
808
+ HintMessage(message=f"**Q{next_q_num}:** {next_q}")
809
+ )
810
+ else:
811
+ # All answered - format and send back
812
+ if len(self.qa_questions) == 1:
813
+ # Single question - just send the answer
814
+ formatted_qa = f"Q: {self.qa_questions[0]}\nA: {self.qa_answers[0]}"
815
+ else:
816
+ # Multiple questions - format all Q&A pairs
817
+ formatted_qa = "\n\n".join(
818
+ f"Q{i + 1}: {q}\nA{i + 1}: {a}"
819
+ for i, (q, a) in enumerate(
820
+ zip(self.qa_questions, self.qa_answers, strict=True)
821
+ )
822
+ )
823
+
824
+ # Exit Q&A mode
825
+ self.qa_mode = False
826
+ self.qa_questions = []
827
+ self.qa_answers = []
828
+ self.qa_current_index = 0
829
+
830
+ # Send answers back to agent
831
+ self.run_agent(formatted_qa)
832
+
833
+ # Clear input
834
+ self.widget_coordinator.update_prompt_input(clear=True)
835
+ self.value = ""
836
+ return
837
+
838
+ # Check if it's a command
839
+ if self.command_handler.is_command(text):
840
+ success, response = self.command_handler.handle_command(text)
841
+
842
+ # Add the command to history
843
+ self.history.append(message.text)
844
+
845
+ # Display the command in chat history
846
+ user_message = ModelRequest(parts=[UserPromptPart(content=text)])
847
+ self.messages = self.messages + [user_message]
848
+
849
+ # Display the response (help text or error message)
850
+ response_message = ModelResponse(parts=[TextPart(content=response)])
851
+ self.messages = self.messages + [response_message]
852
+
853
+ # Clear the input
854
+ self.widget_coordinator.update_prompt_input(clear=True)
855
+ self.value = ""
856
+ return
857
+
858
+ # Not a command, process as normal
859
+ self.history.append(message.text)
860
+
861
+ # Add user message to agent_manager's history BEFORE running the agent
862
+ # This ensures immediate visual feedback AND proper deduplication
863
+ user_message = ModelRequest.user_text_prompt(text)
864
+ self.agent_manager.ui_message_history.append(user_message)
865
+ self.messages = self.agent_manager.ui_message_history.copy()
866
+
867
+ # Clear the input
868
+ self.value = ""
869
+ self.run_agent(text) # Use stripped text
870
+
871
+ self.widget_coordinator.update_prompt_input(clear=True)
872
+
873
+ def _placeholder_for_mode(self, mode: AgentType, force_new: bool = False) -> str:
874
+ """Return the placeholder text appropriate for the current mode.
875
+
876
+ Args:
877
+ mode: The current agent mode.
878
+ force_new: If True, force selection of a new random hint.
879
+
880
+ Returns:
881
+ Dynamic placeholder hint based on mode and progress.
882
+ """
883
+ return self.placeholder_hints.get_placeholder_for_mode(mode)
884
+
885
+ def index_codebase_command(self) -> None:
886
+ # Simplified: always index current working directory with its name
887
+ cur_dir = Path.cwd().resolve()
888
+ cwd_name = cur_dir.name
889
+ selection = CodebaseIndexSelection(repo_path=cur_dir, name=cwd_name)
890
+ self.call_later(lambda: self.index_codebase(selection))
891
+
892
+ def delete_codebase_command(self) -> None:
893
+ self.app.push_screen(
894
+ CommandPalette(
895
+ providers=[DeleteCodebasePaletteProvider],
896
+ placeholder="Select a codebase to delete…",
897
+ )
898
+ )
899
+
900
+ def delete_codebase_from_palette(self, graph_id: str) -> None:
901
+ stack = getattr(self.app, "screen_stack", None)
902
+ if stack and isinstance(stack[-1], CommandPalette):
903
+ self.app.pop_screen()
904
+
905
+ self.call_later(lambda: self.delete_codebase(graph_id))
906
+
907
+ @work
908
+ async def delete_codebase(self, graph_id: str) -> None:
909
+ try:
910
+ await self.codebase_sdk.delete_codebase(graph_id)
911
+ self.notify(f"Deleted codebase: {graph_id}", severity="information")
912
+ except CodebaseNotFoundError as exc:
913
+ self.notify(str(exc), severity="error")
914
+ except Exception as exc: # pragma: no cover - defensive UI path
915
+ self.notify(f"Failed to delete codebase: {exc}", severity="error")
916
+
917
+ def _is_kuzu_corruption_error(self, exception: Exception) -> bool:
918
+ """Check if error is related to kuzu database corruption.
919
+
920
+ Args:
921
+ exception: The exception to check
922
+
923
+ Returns:
924
+ True if the error indicates kuzu database corruption
925
+ """
926
+ error_str = str(exception).lower()
927
+ error_indicators = [
928
+ "not a directory",
929
+ "errno 20",
930
+ "corrupted",
931
+ ".kuzu",
932
+ "ioexception",
933
+ "unordered_map", # C++ STL map errors from kuzu
934
+ "key not found", # unordered_map::at errors
935
+ "std::exception", # Generic C++ exceptions from kuzu
936
+ ]
937
+ return any(indicator in error_str for indicator in error_indicators)
938
+
939
+ @work
940
+ async def index_codebase(self, selection: CodebaseIndexSelection) -> None:
941
+ label = self.query_one("#indexing-job-display", Static)
942
+ label.update(
943
+ f"[$foreground-muted]Indexing codebase: [bold $text-accent]{selection.name}[/][/]"
944
+ )
945
+ label.refresh()
946
+
947
+ def create_progress_bar(percentage: float, width: int = 20) -> str:
948
+ """Create a visual progress bar using Unicode block characters."""
949
+ filled = int((percentage / 100) * width)
950
+ empty = width - filled
951
+ return "▓" * filled + "░" * empty
952
+
953
+ # Spinner animation frames
954
+ spinner_frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
955
+
956
+ # Progress state (shared between timer and progress callback)
957
+ progress_state: dict[str, int | float] = {
958
+ "frame_index": 0,
959
+ "percentage": 0.0,
960
+ }
961
+
962
+ def update_progress_display() -> None:
963
+ """Update progress bar on timer - runs every 100ms."""
964
+ # Advance spinner frame
965
+ frame_idx = int(progress_state["frame_index"])
966
+ progress_state["frame_index"] = (frame_idx + 1) % len(spinner_frames)
967
+ spinner = spinner_frames[frame_idx]
968
+
969
+ # Get current state
970
+ pct = float(progress_state["percentage"])
971
+ bar = create_progress_bar(pct)
972
+
973
+ # Update label
974
+ label.update(
975
+ f"[$foreground-muted]Indexing codebase: {spinner} {bar} {pct:.0f}%[/]"
976
+ )
977
+
978
+ def progress_callback(progress_info: IndexProgress) -> None:
979
+ """Update progress state (timer renders it independently)."""
980
+ # Calculate overall percentage (0-95%, reserve 95-100% for finalization)
981
+ if progress_info.phase == ProgressPhase.STRUCTURE:
982
+ # Phase 1: 0-10%, always show 5% while running, 10% when complete
983
+ overall_pct = 10.0 if progress_info.phase_complete else 5.0
984
+ elif progress_info.phase == ProgressPhase.DEFINITIONS:
985
+ # Phase 2: 10-80% based on files processed
986
+ if progress_info.total and progress_info.total > 0:
987
+ phase_pct = (progress_info.current / progress_info.total) * 70.0
988
+ overall_pct = 10.0 + phase_pct
989
+ else:
990
+ overall_pct = 10.0
991
+ elif progress_info.phase == ProgressPhase.RELATIONSHIPS:
992
+ # Phase 3: 80-95% based on relationships processed (cap at 95%)
993
+ if progress_info.total and progress_info.total > 0:
994
+ phase_pct = (progress_info.current / progress_info.total) * 15.0
995
+ overall_pct = 80.0 + phase_pct
996
+ else:
997
+ overall_pct = 80.0
998
+ else:
999
+ overall_pct = 0.0
1000
+
1001
+ # Update shared state (timer will render it)
1002
+ progress_state["percentage"] = overall_pct
1003
+
1004
+ # Start progress animation timer (10 fps = 100ms interval)
1005
+ progress_timer = self.set_interval(0.1, update_progress_display)
1006
+
1007
+ # Retry logic for handling kuzu corruption
1008
+ max_retries = 3
1009
+
1010
+ for attempt in range(max_retries):
1011
+ try:
1012
+ # Clean up corrupted DBs before retry (skip on first attempt)
1013
+ if attempt > 0:
1014
+ logger.info(
1015
+ f"Retry attempt {attempt + 1}/{max_retries} - cleaning up corrupted databases"
1016
+ )
1017
+ manager = CodebaseGraphManager(
1018
+ self.codebase_sdk.service.storage_dir
1019
+ )
1020
+ cleaned = await manager.cleanup_corrupted_databases()
1021
+ logger.info(f"Cleaned up {len(cleaned)} corrupted database(s)")
1022
+ self.notify(
1023
+ f"Retrying indexing after cleanup (attempt {attempt + 1}/{max_retries})...",
1024
+ severity="information",
1025
+ )
1026
+
1027
+ # Pass the current working directory as the indexed_from_cwd
1028
+ logger.debug(
1029
+ f"Starting indexing - repo_path: {selection.repo_path}, "
1030
+ f"name: {selection.name}, cwd: {Path.cwd().resolve()}"
1031
+ )
1032
+ result = await self.codebase_sdk.index_codebase(
1033
+ selection.repo_path,
1034
+ selection.name,
1035
+ indexed_from_cwd=str(Path.cwd().resolve()),
1036
+ progress_callback=progress_callback,
1037
+ )
1038
+
1039
+ # Success! Stop progress animation
1040
+ progress_timer.stop()
1041
+
1042
+ # Show 100% completion after indexing finishes
1043
+ final_bar = create_progress_bar(100.0)
1044
+ label.update(
1045
+ f"[$foreground-muted]Indexing codebase: {final_bar} 100%[/]"
1046
+ )
1047
+ label.refresh()
1048
+
1049
+ logger.info(
1050
+ f"Successfully indexed codebase '{result.name}' (ID: {result.graph_id})"
1051
+ )
1052
+ self.notify(
1053
+ f"Indexed codebase '{result.name}' (ID: {result.graph_id})",
1054
+ severity="information",
1055
+ timeout=8,
1056
+ )
1057
+ break # Success - exit retry loop
1058
+
1059
+ except CodebaseAlreadyIndexedError as exc:
1060
+ progress_timer.stop()
1061
+ logger.warning(f"Codebase already indexed: {exc}")
1062
+ self.notify(str(exc), severity="warning")
1063
+ return
1064
+ except InvalidPathError as exc:
1065
+ progress_timer.stop()
1066
+ logger.error(f"Invalid path error: {exc}")
1067
+ self.notify(str(exc), severity="error")
1068
+ return
1069
+
1070
+ except Exception as exc: # pragma: no cover - defensive UI path
1071
+ # Check if this is a kuzu corruption error and we have retries left
1072
+ if attempt < max_retries - 1 and self._is_kuzu_corruption_error(exc):
1073
+ logger.warning(
1074
+ f"Kuzu corruption detected on attempt {attempt + 1}/{max_retries}: {exc}. "
1075
+ f"Will retry after cleanup..."
1076
+ )
1077
+ # Exponential backoff: 1s, 2s
1078
+ await asyncio.sleep(2**attempt)
1079
+ continue
1080
+
1081
+ # Either final retry failed OR not a corruption error - show error
1082
+ logger.exception(
1083
+ f"Failed to index codebase after {attempt + 1} attempts - "
1084
+ f"repo_path: {selection.repo_path}, name: {selection.name}, error: {exc}"
1085
+ )
1086
+ self.notify(
1087
+ f"Failed to index codebase after {attempt + 1} attempts: {exc}",
1088
+ severity="error",
1089
+ timeout=30, # Keep error visible for 30 seconds
1090
+ )
1091
+ break
1092
+
1093
+ # Always stop the progress timer and clean up label
1094
+ progress_timer.stop()
1095
+ label.update("")
1096
+ label.refresh()
1097
+
1098
+ @work
1099
+ async def run_agent(self, message: str) -> None:
1100
+ prompt = None
1101
+
1102
+ # Start processing with spinner
1103
+ from textual.worker import get_current_worker
1104
+
1105
+ self.processing_state.start_processing("Processing...")
1106
+ self.processing_state.bind_worker(get_current_worker())
1107
+
1108
+ # Start context indicator animation immediately
1109
+ self.widget_coordinator.set_context_streaming(True)
1110
+
1111
+ prompt = message
1112
+
1113
+ try:
1114
+ await self.agent_manager.run(
1115
+ prompt=prompt,
1116
+ )
1117
+ except asyncio.CancelledError:
1118
+ # Handle cancellation gracefully - DO NOT re-raise
1119
+ self.mount_hint("⚠️ Operation cancelled by user")
1120
+ except Exception as e:
1121
+ # Log with full stack trace to shotgun.log
1122
+ logger.exception(
1123
+ "Agent run failed",
1124
+ extra={
1125
+ "agent_mode": self.mode.value,
1126
+ "error_type": type(e).__name__,
1127
+ },
1128
+ )
1129
+
1130
+ # Determine user-friendly message based on error type
1131
+ error_name = type(e).__name__
1132
+ error_message = str(e)
1133
+
1134
+ if "APIStatusError" in error_name and "overload" in error_message.lower():
1135
+ hint = "⚠️ The AI service is temporarily overloaded. Please wait a moment and try again."
1136
+ elif "APIStatusError" in error_name and "rate" in error_message.lower():
1137
+ hint = "⚠️ Rate limit reached. Please wait before trying again."
1138
+ elif "APIStatusError" in error_name:
1139
+ hint = f"⚠️ AI service error: {error_message}"
1140
+ else:
1141
+ hint = f"⚠️ An error occurred: {error_message}\n\nCheck logs at ~/.shotgun-sh/logs/shotgun.log"
1142
+
1143
+ self.mount_hint(hint)
1144
+ finally:
1145
+ self.processing_state.stop_processing()
1146
+ # Stop context indicator animation
1147
+ self.widget_coordinator.set_context_streaming(False)
1148
+
1149
+ # Save conversation after each interaction
1150
+ self._save_conversation()
1151
+
1152
+ self.widget_coordinator.update_prompt_input(focus=True)
1153
+
1154
+ def _save_conversation(self) -> None:
1155
+ """Save the current conversation to persistent storage."""
1156
+ # Use conversation service for saving (run async in background)
1157
+ # Use exclusive=True to prevent concurrent saves that can cause file contention
1158
+ self.run_worker(
1159
+ self.conversation_service.save_conversation(self.agent_manager),
1160
+ exclusive=True,
1161
+ )
1162
+
1163
+ async def _check_and_load_conversation(self) -> None:
1164
+ """Check if conversation exists and load it if it does."""
1165
+ if await self.conversation_manager.exists():
1166
+ self._load_conversation()
1167
+
1168
+ def _load_conversation(self) -> None:
1169
+ """Load conversation from persistent storage."""
1170
+
1171
+ # Use conversation service for restoration (run async)
1172
+ async def _do_load() -> None:
1173
+ (
1174
+ success,
1175
+ error_msg,
1176
+ restored_type,
1177
+ ) = await self.conversation_service.restore_conversation(
1178
+ self.agent_manager, self.deps.usage_manager
1179
+ )
1180
+
1181
+ if not success and error_msg:
1182
+ self.mount_hint(error_msg)
1183
+ elif success and restored_type:
1184
+ # Update the current mode to match restored conversation
1185
+ self.mode = restored_type
1186
+
1187
+ self.run_worker(_do_load(), exclusive=False)
1188
+
1189
+ @work
1190
+ async def _check_and_show_onboarding(self) -> None:
1191
+ """Check if onboarding should be shown and display modal if needed."""
1192
+ config_manager = get_config_manager()
1193
+ config = await config_manager.load()
1194
+
1195
+ # Only show onboarding if it hasn't been shown before
1196
+ if config.shown_onboarding_popup is None:
1197
+ # Show the onboarding modal
1198
+ await self.app.push_screen_wait(OnboardingModal())
1199
+
1200
+ # Mark as shown in config with current timestamp
1201
+ config.shown_onboarding_popup = datetime.now(timezone.utc)
1202
+ await config_manager.save(config)