-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathask.py
More file actions
367 lines (304 loc) · 13.1 KB
/
ask.py
File metadata and controls
367 lines (304 loc) · 13.1 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
import flet as ft
import asyncio
import os
import re
import glob
import argparse
from functools import partial
# Import your services and original utils
from src.services import ChatService, TokenCounterService, ConversationService, ContextService, StartupService
from src.chat_utils import configure_api, start_chat_session
# --- Welcome Message Constant ---
WELCOME_MESSAGE = """
# Welcome to InsightCoder
Your AI-powered codebase analysis assistant.
**⚠️ Important Privacy Notice**: This tool sends your project's source code to an external LLM service for analysis. **Do not use this tool on repositories containing personal, confidential, or sensitive information.**
### How to get started:
1. Ask a question about your codebase in the text box below.
2. Use `Shift+Enter` for a new line in the input box.
3. Press `Enter` to send your message.
*This message will be replaced by your conversation history once you send your first message.*
"""
# --- 1. State Management ---
class AppState:
"""A class to hold the application's state."""
def __init__(self, project_path=".", conversation_path=None):
self.project_path = project_path
self.conversation_path = conversation_path
# Chat settings
self.model_name = "gemini-2.5-pro" # Default model
# Backend objects
self.api_client = None
self.chat_session = None
# UI state
self.chat_history_md = "" # Start with empty history
self.is_processing = False
self.conversation_counter = 1
# --- 2. UI Components ---
class ChatView(ft.ListView):
"""Component for displaying chat messages."""
def __init__(self):
super().__init__(
expand=True,
spacing=10,
auto_scroll=True,
)
# Wrap the welcome message to make it selectable
self.controls = [
ft.SelectionArea(content=ft.Markdown(
WELCOME_MESSAGE,
extension_set="gitHubWeb",
#code_theme="atom-one-dark",
))
]
class InputBar(ft.Row):
"""Component for the user input text field and action buttons."""
def __init__(self, on_send_message, on_reload_context, on_input_change):
self.user_input = ft.TextField(
hint_text="Ask a question about the codebase...",
expand=True,
multiline=True,
shift_enter=True,
on_submit=on_send_message,
on_change=on_input_change,
)
self.send_button = ft.IconButton(
icon=ft.Icons.SEND_ROUNDED,
tooltip="Send message",
on_click=on_send_message,
)
self.reload_button = ft.IconButton(
icon=ft.Icons.REFRESH,
tooltip="Reload Context",
on_click=on_reload_context,
)
super().__init__(
controls=[
self.user_input,
self.send_button,
self.reload_button,
]
)
# --- 3. Main Application ---
class InsightCoderApp:
def __init__(self, page: ft.Page, state: AppState):
self.page = page
self.state = state
self.page.title = "InsightCoder"
self.page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
# For debouncing token count
self.debounce_task = None
# Initialize UI Components
self.chat_view = ChatView()
self.input_bar = InputBar(
on_send_message=self.send_message_click,
on_reload_context=self.reload_context_click,
on_input_change=self.handle_input_change,
)
self.model_selector = ft.Dropdown(
hint_text="Choose a model",
options=[
ft.dropdown.Option("gemini-2.5-pro"),
ft.dropdown.Option("gemini-2.5-flash"),
],
value=self.state.model_name,
on_change=self.on_model_change,
width=220,
tooltip="Select the AI model. Reload context to apply.",
)
self.token_count_label = ft.Text("Tokens: 0", text_align=ft.TextAlign.RIGHT, color=ft.Colors.ON_SURFACE_VARIANT)
self.chat_service = ChatService()
self.token_service = TokenCounterService()
self.conversation_service = ConversationService()
self.context_service = ContextService()
self.build_ui()
def build_ui(self):
self.page.add(
ft.Container(
content=self.chat_view,
border=ft.border.all(1, ft.Colors.OUTLINE),
border_radius=5,
padding=10,
expand=True
),
self.input_bar,
ft.Row(
controls=[
self.model_selector,
self.token_count_label,
],
alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
),
)
self.page.update()
async def send_message_click(self, e):
user_text = self.input_bar.user_input.value
if not user_text.strip() or self.state.is_processing:
return
self.state.is_processing = True
self.input_bar.user_input.value = ""
self.input_bar.user_input.disabled = True
self.input_bar.send_button.disabled = True
self.input_bar.reload_button.disabled = True
# Clear welcome message on first message
if len(self.chat_view.controls) == 1 and "Welcome" in self.chat_view.controls[0].content.value:
self.chat_view.controls.clear()
# Display user message
user_message_md = ft.Markdown(
f"**User:**\n\n{user_text}",
extension_set="gitHubWeb",
#code_theme="atom-one-dark"
)
# Wrap in SelectionArea to make it selectable
self.chat_view.controls.append(ft.SelectionArea(content=user_message_md))
self.page.update()
# Display placeholder for model response
model_response_md = ft.Markdown(
"**Model:**\n\nThinking...",
extension_set="gitHubWeb",
#code_theme="atom-one-dark"
)
# Wrap in SelectionArea to make it selectable
self.chat_view.controls.append(ft.SelectionArea(content=model_response_md))
self.page.update()
# Yield to the UI thread to render messages before starting the API call
await asyncio.sleep(0.01)
# Stream the response
model_reply_text = ""
async def on_chunk(chunk):
nonlocal model_reply_text
model_reply_text += chunk
model_response_md.value = f"**Model:**\n\n{model_reply_text}▍"
self.page.update()
await self.chat_service.send_message_stream(self.state, user_text, on_chunk)
# Finalize response
model_response_md.value = f"**Model:**\n\n{model_reply_text}"
# The full history has been updated inside send_message_stream
await self.conversation_service.save_conversation_and_summarize_async(self.state)
self.state.is_processing = False
self.input_bar.user_input.disabled = False
self.input_bar.send_button.disabled = False
self.input_bar.reload_button.disabled = False
self.input_bar.user_input.focus()
self.page.update()
async def handle_input_change(self, e):
"""Debounces the token count update."""
if self.debounce_task:
self.debounce_task.cancel()
# Create a new task to update the token count after a short delay
self.debounce_task = asyncio.create_task(self._update_token_count_debounced(e.data))
async def _update_token_count_debounced(self, text_value):
"""Waits for a pause in typing, then updates the token count."""
try:
await asyncio.sleep(0.5) # 500ms delay
self.token_count_label.value = "Tokens: Counting..."
self.page.update()
# Note: We pass the entire state because the service needs access to the
# chat session history and API client for an accurate count.
token_count = await self.token_service.count_tokens_async(self.state, text_value)
if token_count != -1:
self.token_count_label.value = f"Tokens: {token_count}"
else:
self.token_count_label.value = "Tokens: Error"
self.page.update()
except asyncio.CancelledError:
# This is expected if the user types again quickly. We do nothing.
pass
async def reload_context_click(self, e):
"""Handles the reload context action."""
if self.state.is_processing:
return
print("UI: Reload context button clicked.")
self.state.is_processing = True
self.input_bar.user_input.disabled = True
self.input_bar.send_button.disabled = True
self.input_bar.reload_button.disabled = True
original_token_text = self.token_count_label.value
self.token_count_label.value = "Reloading codebase context..."
self.page.update()
new_chat_session = await self.context_service.reload_context_and_create_session_async(self.state)
if new_chat_session:
self.state.chat_session = new_chat_session
self.token_count_label.value = "Context reloaded successfully."
# A small delay before reverting the token label
await asyncio.sleep(2)
self.token_count_label.value = original_token_text
else:
self.token_count_label.value = "Error: Failed to reload context."
await asyncio.sleep(3)
self.token_count_label.value = original_token_text
self.state.is_processing = False
self.input_bar.user_input.disabled = False
self.input_bar.send_button.disabled = False
self.input_bar.reload_button.disabled = False
self.input_bar.user_input.focus()
self.page.update()
async def on_model_change(self, e):
"""Handles model selection change."""
self.state.model_name = self.model_selector.value
print(f"UI: Model selection changed to {self.state.model_name}")
# Give the user feedback that a reload is required.
original_token_text = self.token_count_label.value
self.token_count_label.value = "Model changed. Reload context to apply."
self.page.update()
await asyncio.sleep(3)
# Revert the label only if no other process is running
if not self.state.is_processing:
self.token_count_label.value = original_token_text
self.page.update()
async def main(page: ft.Page, project_path: str, conversation_path: str or None):
# Apply theme for better readability and aesthetics
page.theme_mode = ft.ThemeMode.SYSTEM
state = AppState(project_path=project_path, conversation_path=conversation_path)
if state.conversation_path is None:
state.conversation_path = os.path.join(state.project_path, "project_info", "conversations")
os.makedirs(state.conversation_path, exist_ok=True)
# First, configure the API client, as it's needed for summarization
state.api_client = configure_api()
# Run the startup summarization and wait for it to complete
startup_service = StartupService()
await startup_service.summarize_startup_conversations_async(state)
# Now, calculate the conversation counter (it will be accurate after startup summaries)
pattern_md = os.path.join(state.conversation_path, "conversation_*.md")
pattern_summary = os.path.join(state.conversation_path, "conversation_*_summary.md")
all_conv_files = glob.glob(pattern_md) + glob.glob(pattern_summary)
numbers = set()
for filepath in all_conv_files:
basename = os.path.basename(filepath)
match = re.search(r'conversation_(\d+)', basename)
if match:
numbers.add(int(match.group(1)))
state.conversation_counter = max(numbers) + 1 if numbers else 1
print(f"Next conversation number is: {state.conversation_counter}")
# Initialize chat session (it will now correctly load all summaries)
print("Initializing chat session with updated context...")
_, state.chat_session = start_chat_session(
state.api_client,
state.project_path,
state.conversation_path,
state.model_name # Pass the selected model
)
print("Initialization complete.")
# Finally, create and run the UI
app = InsightCoderApp(page, state)
if __name__ == "__main__":
# --- ADD ARGUMENT PARSING ---
parser = argparse.ArgumentParser(description="InsightCoder: AI-powered codebase analysis.")
parser.add_argument(
"--project-path",
"-p",
type=str,
default=".",
help="Path to the project directory you want to analyze."
)
parser.add_argument(
"--conversation-path",
"-c",
type=str,
default=None,
help="Path to the directory where conversation history will be saved."
)
args = parser.parse_args()
# Create a partial function to pass arguments to the Flet app target
main_with_args = partial(main, project_path=args.project_path, conversation_path=args.conversation_path)
ft.app(target=main_with_args)