-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclia.py
More file actions
1791 lines (1454 loc) · 67.3 KB
/
clia.py
File metadata and controls
1791 lines (1454 loc) · 67.3 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
#!/usr/bin/env python3
"""
CliA - AI-Powered Terminal Assistant
GTK4 application with integrated terminal and AI chat interface
"""
import sys
import os
# Debug: Print typelib search paths
if os.getenv('FLATPAK_ID'):
print("Running in Flatpak")
print(f"GI_TYPELIB_PATH: {os.getenv('GI_TYPELIB_PATH')}")
typelib_paths = []
for path in ['/app/lib/girepository-1.0', '/usr/lib/girepository-1.0', '/usr/lib/x86_64-linux-gnu/girepository-1.0']:
if os.path.exists(path):
typelib_paths.append(path)
files = [f for f in os.listdir(path) if 'Vte' in f]
if files:
print(f"Found in {path}: {files}")
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
# Try to find VTE
try:
gi.require_version('Vte', '3.91')
except ValueError as e:
print(f"Error loading Vte: {e}")
sys.exit(1)
from gi.repository import Gtk, Adw, Vte, GLib, Gdk, Pango
import json
import subprocess
import time
import threading
from pathlib import Path
from datetime import datetime
import requests
class ConfigManager:
"""Manages application configuration and API key storage"""
def __init__(self):
self.config_dir = Path(GLib.get_user_config_dir()) / "clia"
self.config_file = self.config_dir / "config.json"
self.config_dir.mkdir(parents=True, exist_ok=True)
self.config = self.load_config()
def load_config(self):
"""Load configuration from file"""
if self.config_file.exists():
try:
with open(self.config_file, 'r') as f:
return json.load(f)
except Exception as e:
print(f"Error loading config: {e}")
return {}
return {}
def save_config(self):
"""Save configuration to file"""
try:
with open(self.config_file, 'w') as f:
json.dump(self.config, f, indent=2)
# Set file permissions to 600 (read/write only for owner)
self.config_file.chmod(0o600)
except Exception as e:
print(f"Error saving config: {e}")
def get_api_key(self):
"""Get stored API key"""
return self.config.get('api_key', '')
def set_api_key(self, api_key):
"""Set and save API key"""
self.config['api_key'] = api_key
self.save_config()
def get_model(self):
"""Get stored model name"""
return self.config.get('model', 'Qwen/Qwen3-Next-80B-A3B-Instruct')
def set_model(self, model):
"""Set and save model name"""
self.config['model'] = model
self.save_config()
def get_auto_allow_tools(self):
"""Get the auto-allow tools setting"""
return self.config.get('auto_allow_tools', False)
def set_auto_allow_tools(self, allow):
"""Set and save the auto-allow tools setting"""
self.config['auto_allow_tools'] = allow
self.save_config()
def get_theme(self):
"""Get the color scheme setting"""
return self.config.get('theme', 'system')
def set_theme(self, theme):
"""Set and save the color scheme setting"""
self.config['theme'] = theme
self.save_config()
class DoMdManager:
"""Manages the Do.md file for AI to track tasks and thoughts"""
def __init__(self, workspace_path=None):
if workspace_path:
self.do_md_path = Path(workspace_path) / "Do.md"
else:
self.do_md_path = Path.home() / ".clia" / "Do.md"
self.do_md_path.parent.mkdir(parents=True, exist_ok=True)
if not self.do_md_path.exists():
self.do_md_path.write_text("# AI Work Log\n\n")
def read(self):
"""Read current Do.md contents"""
if self.do_md_path.exists():
return self.do_md_path.read_text()
return ""
def write(self, content):
"""Write content to Do.md"""
self.do_md_path.write_text(content)
def append(self, content):
"""Append content to Do.md"""
current = self.read()
self.write(current + "\n" + content)
class ToolExecutor:
"""Executes AI tools on the terminal"""
def __init__(self, terminal_widget, do_md_manager):
self.terminal = terminal_widget
self.do_md_manager = do_md_manager
def execute_tool(self, tool_name, content):
"""Execute a tool and return success status"""
try:
if tool_name == "Input":
return self.execute_input(content)
elif tool_name == "Text":
return self.execute_text(content)
elif tool_name == "Do.md":
return self.execute_domd(content)
elif tool_name == "Success":
return self.execute_success(content)
else:
return False, f"Unknown tool: {tool_name}"
except Exception as e:
return False, f"Error executing {tool_name}: {str(e)}"
def execute_input(self, keys):
"""Send keyboard input to terminal"""
keys = keys.strip()
# Parse key combinations like "Control+C", "Alt+A", etc.
if "+" in keys:
parts = keys.split("+")
modifiers = []
key = parts[-1].strip()
for modifier in parts[:-1]:
modifier = modifier.strip().lower()
if modifier in ["ctrl", "control"]:
modifiers.append("ctrl")
elif modifier in ["alt", "meta"]:
modifiers.append("alt")
elif modifier in ["shift"]:
modifiers.append("shift")
# Handle Control key combinations
if "ctrl" in modifiers:
key_lower = key.lower()
# Map Control+letter to control characters (Ctrl+A = 0x01, Ctrl+B = 0x02, etc.)
if len(key_lower) == 1 and 'a' <= key_lower <= 'z':
ctrl_char = ord(key_lower) - ord('a') + 1
self.terminal.feed_child(bytes([ctrl_char]))
return True, f"Sent key: Ctrl+{key.upper()}"
# Special control combinations
elif key_lower in ["space", " "]:
self.terminal.feed_child(b'\x00') # Ctrl+Space (NUL)
return True, f"Sent key: Ctrl+Space"
elif key_lower in ["[", "{"]:
self.terminal.feed_child(b'\x1b') # Ctrl+[ (ESC)
return True, f"Sent key: Ctrl+["
elif key_lower in ["\\", "|"]:
self.terminal.feed_child(b'\x1c') # Ctrl+\
return True, f"Sent key: Ctrl+\\"
elif key_lower in ["]", "}"]:
self.terminal.feed_child(b'\x1d') # Ctrl+]
return True, f"Sent key: Ctrl+]"
elif key_lower in ["^", "~"]:
self.terminal.feed_child(b'\x1e') # Ctrl+^
return True, f"Sent key: Ctrl+^"
elif key_lower in ["_", "-"]:
self.terminal.feed_child(b'\x1f') # Ctrl+_
return True, f"Sent key: Ctrl+_"
elif key_lower == "?":
self.terminal.feed_child(b'\x7f') # Ctrl+? (DEL)
return True, f"Sent key: Ctrl+?"
else:
return False, f"Unsupported Control+{key} combination"
# Handle Alt key combinations
elif "alt" in modifiers:
key_lower = key.lower()
# Alt+key sends ESC followed by the key
if len(key_lower) == 1:
self.terminal.feed_child(b'\x1b' + key.encode('utf-8'))
return True, f"Sent key: Alt+{key}"
elif key_lower in ["enter", "return"]:
self.terminal.feed_child(b'\x1b\r')
return True, f"Sent key: Alt+Enter"
else:
return False, f"Unsupported Alt+{key} combination"
# Handle Shift combinations (for special keys)
elif "shift" in modifiers:
key_lower = key.lower()
if key_lower == "tab":
self.terminal.feed_child(b'\x1b[Z') # Shift+Tab (reverse tab)
return True, f"Sent key: Shift+Tab"
else:
# For letters, just send uppercase
if len(key) == 1:
self.terminal.feed_child(key.upper().encode('utf-8'))
return True, f"Sent key: {key.upper()}"
return False, f"Unsupported Shift+{key} combination"
return False, f"Unsupported key combination: {keys}"
else:
# Simple key press (no modifiers)
key_lower = keys.lower()
# Special keys
if key_lower in ["enter", "return"]:
self.terminal.feed_child(b'\r')
return True, "Sent key: Enter"
elif key_lower == "tab":
self.terminal.feed_child(b'\t')
return True, "Sent key: Tab"
elif key_lower in ["esc", "escape"]:
self.terminal.feed_child(b'\x1b')
return True, "Sent key: Escape"
elif key_lower == "backspace":
self.terminal.feed_child(b'\x7f')
return True, "Sent key: Backspace"
elif key_lower == "delete":
self.terminal.feed_child(b'\x1b[3~')
return True, "Sent key: Delete"
# Arrow keys
elif key_lower == "up":
self.terminal.feed_child(b'\x1b[A')
return True, "Sent key: Up"
elif key_lower == "down":
self.terminal.feed_child(b'\x1b[B')
return True, "Sent key: Down"
elif key_lower == "right":
self.terminal.feed_child(b'\x1b[C')
return True, "Sent key: Right"
elif key_lower == "left":
self.terminal.feed_child(b'\x1b[D')
return True, "Sent key: Left"
# Home/End/PageUp/PageDown
elif key_lower == "home":
self.terminal.feed_child(b'\x1b[H')
return True, "Sent key: Home"
elif key_lower == "end":
self.terminal.feed_child(b'\x1b[F')
return True, "Sent key: End"
elif key_lower in ["pageup", "pgup"]:
self.terminal.feed_child(b'\x1b[5~')
return True, "Sent key: PageUp"
elif key_lower in ["pagedown", "pgdn", "pgdown"]:
self.terminal.feed_child(b'\x1b[6~')
return True, "Sent key: PageDown"
# Insert
elif key_lower == "insert":
self.terminal.feed_child(b'\x1b[2~')
return True, "Sent key: Insert"
# Function keys (F1-F12)
elif key_lower.startswith("f") and len(key_lower) <= 3:
try:
fkey_num = int(key_lower[1:])
if 1 <= fkey_num <= 12:
fkey_sequences = {
1: b'\x1bOP', 2: b'\x1bOQ', 3: b'\x1bOR', 4: b'\x1bOS',
5: b'\x1b[15~', 6: b'\x1b[17~', 7: b'\x1b[18~', 8: b'\x1b[19~',
9: b'\x1b[20~', 10: b'\x1b[21~', 11: b'\x1b[23~', 12: b'\x1b[24~',
}
self.terminal.feed_child(fkey_sequences[fkey_num])
return True, f"Sent key: F{fkey_num}"
except ValueError:
pass
# Space
elif key_lower == "space":
self.terminal.feed_child(b' ')
return True, "Sent key: Space"
# Single character (letter, number, symbol, etc.)
elif len(keys) == 1:
self.terminal.feed_child(keys.encode('utf-8'))
return True, f"Sent key: {keys}"
# Unknown key
else:
return False, f"Unsupported key: {keys}"
return True, f"Input executed: {keys}"
def execute_text(self, text):
"""Send text to terminal"""
text = text.strip()
self.terminal.feed_child(text.encode('utf-8'))
return True, f"Text sent: {text[:50]}..."
def execute_domd(self, content):
"""Update Do.md file"""
content = content.strip()
# Simple implementation: replace entire content
# Could be enhanced to support specific operations
if content.startswith("APPEND:"):
self.do_md_manager.append(content[7:].strip())
else:
self.do_md_manager.write(content)
return True, "Do.md updated"
def execute_success(self, message):
"""Mark task as successfully completed"""
return True, f"Success: {message}"
class AIAgent:
"""Handles AI interactions with Hugging Face API"""
def __init__(self, api_key="", model_name=""):
self.api_key = api_key
self.model_name = model_name or "Qwen/Qwen3-Next-80B-A3B-Instruct"
self.conversation_history = [] # Will store full conversation
self.system_prompt = None
self.api_url = "https://router.huggingface.co/v1/chat/completions"
def set_api_key(self, api_key):
self.api_key = api_key
def set_model(self, model_name):
self.model_name = model_name
def reset_conversation(self):
"""Reset conversation history for a new task"""
self.conversation_history = []
self.system_prompt = None
def build_prompt(self, user_command, terminal_output, do_md_content, previous_actions):
"""Build the prompt to send to AI"""
# System prompt (only created once per task)
if self.system_prompt is None:
self.system_prompt = f"""You are an AI assistant helping users accomplish tasks in a terminal. You must act like a REAL HUMAN carefully operating a terminal, not an automated script.
User's Task: {user_command}
You can use ONE tool per response in the format [ToolName]content[/ToolName].
Available tools:
1. [Wait]seconds[/Wait] - Wait for specified seconds (use this to observe terminal output)
Example: [Wait]2[/Wait]
2. [Input]key[/Input] - Send keyboard input
Supported inputs:
- Control combinations: Ctrl+A through Ctrl+Z (e.g., Ctrl+C, Ctrl+D, Ctrl+Z)
- Alt combinations: Alt+A through Alt+Z, Alt+Enter
- Shift+Tab for reverse tab
- Arrow keys: Up, Down, Left, Right
- Special keys: Enter, Tab, Escape, Backspace, Delete
- Navigation: Home, End, PageUp, PageDown, Insert
- Function keys: F1 through F12
- Single characters: any letter, number, or symbol
- Space
Examples: [Input]Ctrl+C[/Input], [Input]Enter[/Input], [Input]Up[/Input], [Input]Tab[/Input]
3. [Text]string[/Text] - Type text into terminal (for multiple characters)
Example: [Text]ls -la[/Text]
4. [Do.md]content[/Do.md] - Update your work log
- Use APPEND: prefix to append to existing content
- Otherwise replaces entire content
Example: [Do.md]APPEND: Step 1 completed[/Do.md]
5. [Success]message[/Success] - Mark task as complete
Example: [Success]File successfully created[/Success]
CRITICAL RULES - YOU MUST FOLLOW THESE LIKE A REAL HUMAN:
1. **WORK EXTREMELY SLOWLY AND CAREFULLY**
- Take ONE tiny step at a time
- After EVERY action, wait and observe the result
- Never rush or skip verification steps
2. **THINK BEFORE YOU ACT**
- Carefully analyze the current terminal output
- Consider what could go wrong
- Double-check your next action makes sense
- Explain your reasoning clearly before taking action
3. **OBSERVE AND VERIFY**
- After typing a command, use [Wait] to see the output
- After pressing Enter, use [Wait] to see the result
- Check if your action had the expected effect
- If something unexpected happens, pause and reconsider
4. **USE Do.md RELIGIOUSLY**
- Before starting, write your plan
- After each step, update your progress
- Track what worked and what didn't
- Use it to think through problems
5. **ONE TOOL PER RESPONSE - NO EXCEPTIONS**
- You can ONLY use ONE tool in each response
- Don't try to chain actions
- Each response = one deliberate action
6. **SEPARATE TYPING FROM EXECUTING**
- First use [Text] to type a command
- Then in NEXT response, use [Input]Enter[/Input] to execute it
- Then in NEXT response, use [Wait] to observe the result
- This mimics how a real human works
7. **BE CONSERVATIVE AND SAFE**
- If unsure, use [Wait] to observe more
- If something looks wrong, stop and analyze
- Don't proceed if you're not 100% certain
- It's better to be slow than to make mistakes
8. **ONLY USE [Success] WHEN TRULY DONE**
- Verify the task is completely finished
- Check that the output confirms success
- Don't assume - wait and verify
Example of GOOD behavior:
- Response 1: "I need to list files. Let me type the ls command." → [Text]ls -la[/Text]
- Response 2: "Now I'll execute it." → [Input]Enter[/Input]
- Response 3: "Let me wait to see the output." → [Wait]2[/Wait]
- Response 4: "I can see the file list. Let me update my notes." → [Do.md]APPEND: Listed files successfully[/Do.md]
Example of BAD behavior (DON'T DO THIS):
- Response 1: "I'll type and execute ls" → [Text]ls -la[/Text] (Missing the Enter step!)
9. **CRITICAL: LANGUAGE MATCHING - THIS IS MANDATORY**
- **YOU MUST ALWAYS RESPOND IN THE SAME LANGUAGE THE USER USED IN THEIR COMMAND**
- This is NOT optional - if the user writes in Korean (한국어), you MUST respond in Korean
- If the user writes in English, you MUST respond in English
- If the user writes in Japanese (日本語), you MUST respond in Japanese
- Match the user's language in ALL parts of your response: reasoning, explanations, Do.md updates, everything
- The ONLY exception is if the user explicitly asks you to use a different language
- This rule applies to EVERY SINGLE RESPONSE you give
- **ALWAYS CHECK: What language did the user use in their original task/command? Use that exact language.**
Respond with your careful reasoning and then EXACTLY ONE tool to use."""
# Build current state message
current_state = f"""Current Terminal Output:
{terminal_output}
Do.md (your work log):
{do_md_content}
What is your next action?"""
return current_state
def call_api(self, prompt):
"""Call Hugging Face API using requests with full conversation history"""
if not self.api_key:
return None, "API key not set"
try:
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
# Build messages array with full conversation history
messages = []
# Add system prompt
if self.system_prompt:
messages.append({
"role": "system",
"content": self.system_prompt
})
# Add all previous conversation history
messages.extend(self.conversation_history)
# Add current user prompt
messages.append({
"role": "user",
"content": prompt
})
payload = {
"messages": messages,
"model": self.model_name,
"max_tokens": 2000,
"temperature": 0.7,
"top_p": 0.95
}
response = requests.post(self.api_url, headers=headers, json=payload)
response.raise_for_status()
result = response.json()
# Extract the generated text from the response
if result and "choices" in result and len(result["choices"]) > 0:
generated_text = result["choices"][0]["message"]["content"]
# Add to conversation history
self.conversation_history.append({
"role": "user",
"content": prompt
})
self.conversation_history.append({
"role": "assistant",
"content": generated_text
})
return generated_text, None
else:
return None, "No response from API"
except Exception as e:
return None, f"API Error: {str(e)}"
def parse_tool_from_response(self, response):
"""Parse tool usage from AI response"""
import re
# Look for [ToolName]content[/ToolName] pattern
pattern = r'\[([\w.]+)\](.*?)\[/\1\]'
match = re.search(pattern, response, re.DOTALL)
if match:
tool_name = match.group(1)
content = match.group(2)
reasoning = response[:match.start()].strip()
return tool_name, content, reasoning
return None, None, response
class SettingsDialog(Gtk.Window):
"""Settings dialog for API key configuration"""
def __init__(self, parent, config_manager):
super().__init__()
self.set_transient_for(parent)
self.set_modal(True)
self.set_title("API Settings")
self.set_default_size(450, 200)
self.config_manager = config_manager
# Main box
main_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
main_box.set_margin_start(20)
main_box.set_margin_end(20)
main_box.set_margin_top(20)
main_box.set_margin_bottom(20)
# Title
title = Gtk.Label()
title.set_markup("<big><b>API Key Settings</b></big>")
title.set_halign(Gtk.Align.START)
main_box.append(title)
# API Key section
api_frame = Gtk.Frame()
api_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
api_box.set_margin_start(12)
api_box.set_margin_end(12)
api_box.set_margin_top(12)
api_box.set_margin_bottom(12)
api_label = Gtk.Label(label="Hugging Face API Key")
api_label.set_halign(Gtk.Align.START)
api_label.set_markup("<b>Hugging Face API Key</b>")
self.api_entry = Gtk.Entry()
self.api_entry.set_placeholder_text("hf_...")
self.api_entry.set_visibility(False)
self.api_entry.set_input_purpose(Gtk.InputPurpose.PASSWORD)
self.api_entry.set_text(config_manager.get_api_key())
# Info label
info_label = Gtk.Label()
info_label.set_markup("<small>You can select the model on the main screen.</small>")
info_label.set_halign(Gtk.Align.START)
info_label.add_css_class("dim-label")
api_box.append(api_label)
api_box.append(self.api_entry)
api_box.append(info_label)
api_frame.set_child(api_box)
main_box.append(api_frame)
# Auto-allow tools section
auto_allow_frame = Gtk.Frame()
auto_allow_frame.set_margin_top(10)
auto_allow_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
auto_allow_box.set_margin_start(12)
auto_allow_box.set_margin_end(12)
auto_allow_box.set_margin_top(12)
auto_allow_box.set_margin_bottom(12)
auto_allow_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
auto_allow_label = Gtk.Label(label="Auto-allow AI interaction")
auto_allow_label.set_halign(Gtk.Align.START)
auto_allow_label.set_hexpand(True)
auto_allow_label.set_tooltip_text("Allow AI to use terminal interaction tools (Input, Text) without asking for confirmation.")
self.auto_allow_switch = Gtk.Switch()
self.auto_allow_switch.set_active(config_manager.get_auto_allow_tools())
self.auto_allow_switch.connect("notify::active", self.on_auto_allow_toggled)
auto_allow_hbox.append(auto_allow_label)
auto_allow_hbox.append(self.auto_allow_switch)
auto_allow_box.append(auto_allow_hbox)
auto_allow_frame.set_child(auto_allow_box)
main_box.append(auto_allow_frame)
# Theme selection
theme_frame = Gtk.Frame()
theme_frame.set_margin_top(10)
theme_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
theme_box.set_margin_start(12)
theme_box.set_margin_end(12)
theme_box.set_margin_top(12)
theme_box.set_margin_bottom(12)
theme_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
theme_label = Gtk.Label(label="Color Scheme")
theme_label.set_halign(Gtk.Align.START)
theme_label.set_hexpand(True)
self.theme_combo = Gtk.ComboBoxText()
self.theme_combo.append_text("System")
self.theme_combo.append_text("Light")
self.theme_combo.append_text("Dark")
current_theme = self.config_manager.get_theme()
if current_theme == 'light':
self.theme_combo.set_active(1)
elif current_theme == 'dark':
self.theme_combo.set_active(2)
else: # system
self.theme_combo.set_active(0)
theme_hbox.append(theme_label)
theme_hbox.append(self.theme_combo)
theme_box.append(theme_hbox)
theme_frame.set_child(theme_box)
main_box.append(theme_frame)
# Buttons
button_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
button_box.set_halign(Gtk.Align.END)
button_box.set_margin_top(20)
cancel_button = Gtk.Button(label="Cancel")
cancel_button.connect("clicked", lambda w: self.close())
save_button = Gtk.Button(label="Save")
save_button.add_css_class("suggested-action")
save_button.connect("clicked", self.on_save)
button_box.append(cancel_button)
button_box.append(save_button)
main_box.append(button_box)
self.set_child(main_box)
def on_save(self, button):
"""Save settings"""
api_key = self.api_entry.get_text().strip()
if not api_key:
dialog = Gtk.AlertDialog()
dialog.set_message("Please enter an API key")
dialog.set_buttons(["OK"])
dialog.choose(self, None, None, None)
return
self.config_manager.set_api_key(api_key)
# Save theme setting
theme_text = self.theme_combo.get_active_text().lower()
self.config_manager.set_theme(theme_text)
# Apply the theme immediately
app = self.get_transient_for().get_application()
if app:
app.apply_theme()
self.close()
def on_auto_allow_toggled(self, switch, a):
is_active = switch.get_active()
self.config_manager.set_auto_allow_tools(is_active)
if is_active:
# Show a warning when enabling
dialog = Gtk.AlertDialog()
dialog.set_modal(True)
dialog.set_message("Security Warning")
dialog.set_detail("Enabling auto-allow means the AI can execute any command in your terminal without your permission. This could be dangerous. Only enable this if you fully trust the AI and the model you are using.")
dialog.set_buttons(["OK"])
dialog.choose(self, None, None)
class ToolConfirmationDialog:
"""Handles the tool confirmation dialog using Adw.MessageDialog."""
def __init__(self, parent, tool_name, content, config_manager):
self.parent = parent
self.tool_name = tool_name
self.content = content
self.config_manager = config_manager
self.response = "deny"
self.response_event = threading.Event()
def run(self):
"""Shows the dialog and blocks the calling thread until a response is received."""
GLib.idle_add(self.show_dialog)
self.response_event.wait()
return self.response
def show_dialog(self):
"""Creates and presents the Adw.MessageDialog on the main thread."""
dialog = Adw.MessageDialog(
transient_for=self.parent,
modal=True,
heading=f"AI wants to use the '{self.tool_name}' tool",
body=self.content
)
self.auto_allow_check = Gtk.CheckButton(label="Auto-allow future interactions")
self.auto_allow_check.set_tooltip_text("If checked, all future terminal interactions in this session will be allowed automatically.")
extra_content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
extra_content.append(Gtk.Separator())
extra_content.append(self.auto_allow_check)
dialog.set_extra_child(extra_content)
dialog.add_response("deny", "Deny")
dialog.add_response("allow", "Allow")
dialog.set_response_appearance("allow", Adw.ResponseAppearance.SUGGESTED)
dialog.set_default_response("allow")
dialog.connect("response", self.on_response)
dialog.present()
return False # So GLib.idle_add doesn't call it again
def on_response(self, dialog, response_id):
"""Handles the user's response from the dialog."""
if response_id == "allow":
self.response = "allow"
if self.auto_allow_check.get_active():
if not self.config_manager.get_auto_allow_tools():
self.show_warning()
self.config_manager.set_auto_allow_tools(True)
else:
self.response = "deny"
dialog.close()
self.response_event.set()
def show_warning(self):
"""Shows a security warning dialog."""
warning = Adw.MessageDialog(
transient_for=self.parent,
modal=True,
heading="Security Warning",
body="Enabling auto-allow means the AI can execute any command in your terminal without your permission. This could be dangerous.",
)
warning.add_response("ok", "OK")
warning.set_default_response("ok")
warning.connect("response", lambda d, r: d.close())
warning.present()
class ChatPanel(Gtk.Box):
"""Chat interface panel"""
def __init__(self, on_send_callback, on_stop_callback, config_manager):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.on_send_callback = on_send_callback
self.on_stop_callback = on_stop_callback
self.config_manager = config_manager
self.set_hexpand(True)
self.set_vexpand(True)
# Header with clear button
header_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
header_box.set_margin_start(10)
header_box.set_margin_end(10)
header_box.set_margin_top(6)
chat_label = Gtk.Label()
chat_label.set_markup("<b> </b>")
chat_label.set_halign(Gtk.Align.START)
chat_label.set_hexpand(True)
clear_button = Gtk.Button.new_from_icon_name("edit-clear-all-symbolic")
clear_button.set_tooltip_text("Clear Chat")
clear_button.connect("clicked", self.on_clear_chat)
clear_button.set_halign(Gtk.Align.END)
header_box.append(chat_label)
header_box.append(clear_button)
self.append(header_box)
# Chat display area
self.scrolled_window = Gtk.ScrolledWindow()
self.scrolled_window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
self.scrolled_window.set_vexpand(True)
self.scrolled_window.set_hexpand(True)
self.scrolled_window.set_size_request(300, 200) # Set minimum size
self.chat_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
self.chat_box.set_margin_start(10)
self.chat_box.set_margin_end(10)
self.chat_box.set_margin_top(10)
self.chat_box.set_margin_bottom(10)
self.chat_box.set_valign(Gtk.Align.END) # To make new messages appear at the bottom
self.scrolled_window.set_child(self.chat_box)
self.append(self.scrolled_window)
# Model selection area
model_container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
model_container.set_margin_start(6)
model_container.set_margin_end(6)
model_container.set_margin_top(6)
# First row: label and dropdown
model_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
model_label = Gtk.Label(label="Model:")
model_label.set_width_chars(6)
# Dropdown with common models
self.model_combo = Gtk.ComboBoxText()
self.model_combo.set_hexpand(True)
model_list = [
"Qwen/Qwen3-Next-80B-A3B-Instruct",
"deepseek-ai/DeepSeek-V3.2-Exp",
"zai-org/GLM-4.6",
"Qwen/Qwen3-235B-A22B-Thinking-2507",
"openai/gpt-oss-120b",
"meta-llama/Llama-4-Maverick-17B-128E-Instruct",
"Qwen/Qwen3-Next-80B-A3B-Thinking",
"moonshotai/Kimi-K2-Instruct",
"openai/gpt-oss-20b",
"google/gemma-3-27b-it",
"HuggingFaceTB/SmolLM3-3B"
]
for model in model_list:
self.model_combo.append_text(model)
self.model_combo.append_text("Custom...")
# Set saved model
saved_model = config_manager.get_model()
found = False
for i, model_text in enumerate(model_list):
if model_text == saved_model:
self.model_combo.set_active(i)
found = True
break
if not found:
self.model_combo.set_active(len(model_list)) # Custom
self.model_combo.connect("changed", self.on_model_changed)
model_box.append(model_label)
model_box.append(self.model_combo)
# Second row: custom model entry (full width, hidden by default)
self.custom_model_entry = Gtk.Entry()
self.custom_model_entry.set_placeholder_text("Enter custom model name")
self.custom_model_entry.set_hexpand(True)
self.custom_model_entry.connect("changed", self.on_custom_model_changed)
if not found:
self.custom_model_entry.set_text(saved_model)
self.custom_model_entry.set_visible(True)
else:
self.custom_model_entry.set_visible(False)
model_container.append(model_box)
model_container.append(self.custom_model_entry)
self.append(model_container)
# Input area
input_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
input_box.set_margin_start(6)
input_box.set_margin_end(6)
input_box.set_margin_bottom(6)
# Use a TextView for multiline input, inside a ScrolledWindow for border and scrolling
input_frame = Gtk.Frame()
input_frame.set_hexpand(True)
self.input_view = Gtk.TextView()
self.input_view.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
self.input_view.set_vexpand(False)
self.input_view.set_accepts_tab(False)
self.input_view.get_buffer().connect("changed", self.on_input_buffer_changed)
self.input_view.set_pixels_above_lines(5)
self.input_view.set_pixels_below_lines(5)
self.input_view.set_left_margin(10)
self.input_view.set_right_margin(10)
# Handle Enter key press
key_controller = Gtk.EventControllerKey.new()
key_controller.connect("key-pressed", self.on_key_pressed)
self.input_view.add_controller(key_controller)
input_frame.set_child(self.input_view)
self.action_button = Gtk.Button(label="Send")
self.action_button.connect("clicked", self.on_action_clicked)
self.action_button.set_valign(Gtk.Align.END)
input_box.append(input_frame)
input_box.append(self.action_button)
self.append(input_box)
# Initial size setting
self.on_input_buffer_changed(self.input_view.get_buffer())
self.active_waits = {}
# CSS for chat bubbles
css_provider = Gtk.CssProvider()
css_provider.load_from_string("""
.chat-bubble {
padding: 10px;
border-radius: 12px;
max-width: 80%;
}
.user-bubble {
background-color: #3584e4;
color: white;
}
.ai-bubble, .system-bubble, .error-bubble {
background-color: @window_bg_color;
border: 1px solid @window_border_color;
}
.success-bubble {
background-color: #4caf50;
color: white;
}
.code-snippet {
background-color: rgba(0, 0, 0, 0.1);
padding: 2px 6px;
border-radius: 4px;
font-family: monospace;
}
:root.dark .code-snippet {