-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmenu_curses.py
More file actions
1771 lines (1537 loc) · 76.9 KB
/
menu_curses.py
File metadata and controls
1771 lines (1537 loc) · 76.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import curses
import json
import os
import textwrap
from datetime import datetime
from typing import Dict, List, Optional
from gemini_client import GeminiClient, CharacterManager, PersonaManager
class MenuCursesInterface:
def __init__(self, gemini_client, character_manager, persona_manager):
self.gemini_client = gemini_client
self.character_manager = character_manager
self.persona_manager = persona_manager
self.current_character = None
self.conversation_history = []
self.chat_lines = []
self.input_buffer = ""
self._cursor_pos = 0
self._dot_command = False # True after pressing '.' waiting for second key
self.running = True
# Menu state
self.current_screen = "main" # "main", "chat"
self.main_menu_focus = 0
self.character_focus = 0
self.persona_focus = 0
self.selected_character = None
self.selected_persona = None
# Chat persistence
self.chats_dir = os.path.join(os.path.dirname(__file__), "chats")
self.current_chat_id = None
self.saved_chats = {}
self.last_auto_save = 0
self.last_api_call = 0 # For rate limiting
self.scroll_offset = 0 # Scroll offset for chat history
self.scene_state = None # Current scene state (location, outfits, plans, notes)
self.scene_view = False # Toggle for fullscreen scene state view
self.load_saved_chats()
def run(self):
"""Main run loop"""
try:
# Initialize curses
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(True)
# Try to make cursor visible, handle terminal compatibility
try:
curses.curs_set(1) # Normal cursor
except:
try:
curses.curs_set(2) # Very visible cursor
except:
pass # Cursor visibility not supported in this terminal
# Colors
if curses.has_colors():
curses.start_color()
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Title
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) # Selected
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) # Instructions
curses.init_pair(4, curses.COLOR_CYAN, curses.COLOR_BLACK) # Character name
curses.init_pair(5, curses.COLOR_BLACK, curses.COLOR_WHITE) # Focus
curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_BLACK) # Default text
curses.init_pair(7, curses.COLOR_CYAN, curses.COLOR_BLACK) # Action text (**)
curses.init_pair(8, curses.COLOR_BLACK, curses.COLOR_BLACK) # Light gray for quotes ("") - using black with dim
# Main loop
while self.running:
if self.current_screen == "main":
self.show_main_menu(stdscr)
elif self.current_screen == "chat":
self.chat_loop(stdscr)
except Exception as e:
import traceback
with open("/tmp/charcli_error.log", "w") as f:
f.write(traceback.format_exc())
print(f"Error: {e}\n(full traceback in /tmp/charcli_error.log)")
finally:
curses.endwin()
def show_main_menu(self, stdscr):
"""Show main selection menu"""
h, w = stdscr.getmaxyx()
while self.current_screen == "main" and self.running:
stdscr.clear()
# Title
title = "=== charcli ==="
stdscr.addstr(0, (w - len(title)) // 2, title, curses.color_pair(1) | curses.A_BOLD)
# Main menu options
menu_items = ["Select Character (for new chat)", "Select Persona (all chats)", "Start New Chat", "Load old Chat", "Character Maker", "Persona Maker", "Quit"]
menu_y = 3
for i, item in enumerate(menu_items):
attr = curses.color_pair(5) | curses.A_BOLD if i == self.main_menu_focus else curses.A_NORMAL
prefix = "→ " if i == self.main_menu_focus else " "
stdscr.addstr(menu_y + i, 4, f"{prefix}{item}", attr)
# Current selections info
info_y = menu_y + len(menu_items) + 2
if self.selected_character is not None:
characters = list(self.character_manager.get_all_characters().items())
if self.selected_character < len(characters):
char_name = characters[self.selected_character][1]['name']
stdscr.addstr(info_y, 4, f"Character: {char_name}", curses.color_pair(2))
if self.selected_persona is not None:
personas = list(self.persona_manager.get_all_personas().items())
if self.selected_persona == 0:
persona_name = "No Persona"
elif self.selected_persona - 1 < len(personas):
persona_name = personas[self.selected_persona - 1][1]['name']
else:
persona_name = "Unknown"
stdscr.addstr(info_y + 1, 4, f"Persona: {persona_name}", curses.color_pair(2))
# Instructions
inst_y = info_y + 3
instructions = [
"↑↓ - Navigate menu",
"Enter - Select option",
"q - Quit"
]
for i, inst in enumerate(instructions):
stdscr.addstr(inst_y + i, 4, inst, curses.color_pair(3))
stdscr.refresh()
# Handle input
key = stdscr.getch()
if key == ord('q'):
self.running = False
break
elif key == curses.KEY_UP:
if self.main_menu_focus > 0:
self.main_menu_focus -= 1
elif key == curses.KEY_DOWN:
if self.main_menu_focus < len(menu_items) - 1:
self.main_menu_focus += 1
elif key == ord('\n'): # Enter
if self.main_menu_focus == 0: # Select Character
self.show_character_selection(stdscr)
elif self.main_menu_focus == 1: # Select Persona
self.show_persona_selection(stdscr)
elif self.main_menu_focus == 2: # Start Chat
if self.selected_character is not None:
self.apply_selections()
self.start_chat_session()
self.current_screen = "chat"
else:
# Show error
stdscr.addstr(inst_y + 3, 4, "Please select a character first!", curses.color_pair(3) | curses.A_BOLD)
stdscr.refresh()
stdscr.getch()
elif self.main_menu_focus == 3: # Load Chat
self.show_load_chat_menu(stdscr)
elif self.main_menu_focus == 4: # Character Editor
self.show_character_editor(stdscr)
elif self.main_menu_focus == 5: # Persona Editor
self.show_persona_editor(stdscr)
elif self.main_menu_focus == 6: # Quit
self.running = False
def show_character_selection(self, stdscr):
"""Show character selection screen"""
h, w = stdscr.getmaxyx()
characters = list(self.character_manager.get_all_characters().items())
while self.running:
stdscr.clear()
# Title
title = "SELECT CHARACTER"
stdscr.addstr(0, (w - len(title)) // 2, title, curses.color_pair(1) | curses.A_BOLD)
# Character list
list_y = 3
for i, (name, data) in enumerate(characters):
attr = curses.color_pair(5) | curses.A_BOLD if i == self.character_focus else curses.A_NORMAL
marker = "→ " if i == self.character_focus else " "
selected = " ✓" if self.selected_character == i else ""
stdscr.addstr(list_y + i, 4, f"{marker}{i}. {data['name']} - {data['title']}{selected}", attr)
# Instructions
inst_y = list_y + len(characters) + 2
instructions = [
"↑↓ - Navigate",
"Enter - Select character",
"Esc - Back to main menu"
]
for i, inst in enumerate(instructions):
stdscr.addstr(inst_y + i, 4, inst, curses.color_pair(3))
stdscr.refresh()
# Handle input
key = stdscr.getch()
if key == 27: # Esc
break
elif key == curses.KEY_UP:
if self.character_focus > 0:
self.character_focus -= 1
elif key == curses.KEY_DOWN:
if self.character_focus < len(characters) - 1:
self.character_focus += 1
elif key == ord('\n'): # Enter
self.selected_character = self.character_focus
break
def show_persona_selection(self, stdscr):
"""Show persona selection screen"""
h, w = stdscr.getmaxyx()
personas = list(self.persona_manager.get_all_personas().items())
while self.running:
stdscr.clear()
# Title
title = "SELECT PERSONA"
stdscr.addstr(0, (w - len(title)) // 2, title, curses.color_pair(1) | curses.A_BOLD)
# Persona list (including "No Persona")
list_y = 3
persona_items = [("No Persona", 0)] + [(data['name'], i+1) for i, (name, data) in enumerate(personas)]
for i, (display_name, value) in enumerate(persona_items):
attr = curses.color_pair(5) | curses.A_BOLD if i == self.persona_focus else curses.A_NORMAL
marker = "→ " if i == self.persona_focus else " "
selected = " ✓" if self.selected_persona == value else ""
stdscr.addstr(list_y + i, 4, f"{marker}{value}. {display_name}{selected}", attr)
# Instructions
inst_y = list_y + len(persona_items) + 2
instructions = [
"↑↓ - Navigate",
"Enter - Select persona",
"Esc - Back to main menu"
]
for i, inst in enumerate(instructions):
stdscr.addstr(inst_y + i, 4, inst, curses.color_pair(3))
stdscr.refresh()
# Handle input
key = stdscr.getch()
if key == 27: # Esc
break
elif key == curses.KEY_UP:
if self.persona_focus > 0:
self.persona_focus -= 1
elif key == curses.KEY_DOWN:
if self.persona_focus < len(persona_items) - 1:
self.persona_focus += 1
elif key == ord('\n'): # Enter
self.selected_persona = persona_items[self.persona_focus][1]
break
def apply_selections(self):
"""Apply the current selections"""
# Apply character selection
if self.selected_character is not None:
characters = list(self.character_manager.get_all_characters().items())
if self.selected_character < len(characters):
char_name, char_data = characters[self.selected_character]
self.current_character = char_data
# Apply persona selection
if self.selected_persona == 0:
self.persona_manager.set_current_persona(None)
elif self.selected_persona is not None and self.selected_persona > 0:
personas = list(self.persona_manager.get_all_personas().items())
if self.selected_persona - 1 < len(personas):
persona_name, persona_data = personas[self.selected_persona - 1]
self.persona_manager.set_current_persona(persona_name)
def chat_loop(self, stdscr):
"""Main chat loop"""
h, w = stdscr.getmaxyx()
# Only initialize if this is a new chat (no existing data)
if not self.chat_lines:
current_persona = self.persona_manager.get_current_persona()
self.conversation_history = []
self.chat_lines = []
scenario = self.current_character.get('scenario', f"Hello! I'm {self.current_character['name']}. {self.current_character['basic_info']}")
self.add_message(self.current_character['name'], scenario)
self.save_current_chat()
# Build display lines once (rebuild when chat changes)
display_lines = []
self._rebuild_display = True
while self.current_screen == "chat" and self.running:
# Auto-save check
current_time = datetime.now().timestamp()
if self.last_auto_save == 0 or current_time - self.last_auto_save > 30:
self.save_current_chat()
self.last_auto_save = current_time
# Rebuild display lines if needed
if self._rebuild_display:
display_lines = self._build_display_lines(w)
self._rebuild_display = False
# Always define these so _handle_chat_key never gets a NameError
chat_height = h - 2
max_scroll = 0
stdscr.clear()
if self.scene_view:
# ── SCENE STATE SCREEN ──────────────────────────────────────
title = f" Scene State — {self.current_character['name']} "
stdscr.addstr(0, 0, title.center(w), curses.color_pair(1) | curses.A_BOLD)
row = 2
if not self.scene_state:
stdscr.addstr(row, 4, "No scene state yet — send a message first.", curses.color_pair(3))
else:
s = self.scene_state
def section(label, value):
nonlocal row
if row >= h - 2: return
stdscr.addstr(row, 0, f" {label}", curses.color_pair(4) | curses.A_BOLD)
row += 1
text = ', '.join(value) if isinstance(value, list) else str(value or '—')
for line in (textwrap.wrap(text, w - 6) or ['—']):
if row >= h - 2: break
stdscr.addstr(row, 4, line, curses.color_pair(3))
row += 1
row += 1
section("📍 LOCATION", s.get('location', ''))
section("👥 CHARACTERS PRESENT", s.get('characters_present', []))
outfits = s.get('outfits', {})
if outfits and row < h - 2:
stdscr.addstr(row, 0, " 👗 OUTFITS", curses.color_pair(4) | curses.A_BOLD)
row += 1
for name, outfit in outfits.items():
if row >= h - 2: break
stdscr.addstr(row, 4, f"{name}:", curses.color_pair(4))
row += 1
for line in (textwrap.wrap(outfit, w - 8) or ['—']):
if row >= h - 2: break
stdscr.addstr(row, 8, line, curses.color_pair(3))
row += 1
row += 1
plans = s.get('plans', '')
if plans and plans.lower() != 'none':
section("🗺 PLANS", plans)
notes = s.get('notes', '')
if notes:
section("📝 NOTES", notes)
# Relationships
relationships = s.get('relationships', {})
if relationships and row < h - 2:
stdscr.addstr(row, 0, " 💞 RELATIONSHIPS", curses.color_pair(4) | curses.A_BOLD)
row += 1
for pair, rel in relationships.items():
if row >= h - 2: break
status_str = rel.get('status', '')
depth_str = rel.get('depth', '')
info_str = rel.get('info', '')
stdscr.addstr(row, 4, f"{pair}:", curses.color_pair(4))
row += 1
if row < h - 2:
stdscr.addstr(row, 6, f"{status_str} [{depth_str}]", curses.color_pair(3))
row += 1
if info_str and row < h - 2:
for line in (textwrap.wrap(info_str, w - 10) or []):
if row >= h - 2: break
stdscr.addstr(row, 8, line, curses.color_pair(3))
row += 1
row += 1
# Long-term notes
long_term = s.get('long_term_notes', '')
if long_term and row < h - 2:
stdscr.addstr(row, 0, " 📖 STORY SO FAR", curses.color_pair(4) | curses.A_BOLD)
row += 1
for line in (textwrap.wrap(long_term, w - 6) or ['—']):
if row >= h - 2: break
stdscr.addstr(row, 4, line, curses.color_pair(3))
row += 1
row += 1
status = " .s = back to chat | Esc = main menu "
try:
stdscr.addstr(h - 1, 0, status.center(w)[:w-1], curses.color_pair(1))
except:
pass
chat_height = h - 2 # dummy value, not used in scene view
max_scroll = 0
else:
# ── NORMAL CHAT SCREEN ───────────────────────────────────────
# Calculate input box size
input_lines = self._get_input_lines(w - 4)
input_height = max(1, len(input_lines))
min_input_height = 1
max_input_height = min(5, h // 3)
input_height = max(min_input_height, min(input_height, max_input_height))
# Layout: title(1) + chat(remaining) + separator(1) + input(input_height) + status(1)
chat_height = h - 2 - input_height - 1
# Title bar
title = f" Chat with {self.current_character['name']} "
stdscr.addstr(0, 0, title.center(w), curses.color_pair(1) | curses.A_BOLD)
# Chat area with scrolling
total_lines = len(display_lines)
max_scroll = max(0, total_lines - chat_height)
if self.scroll_offset > max_scroll:
self.scroll_offset = max_scroll
if self.scroll_offset == 0:
start = max(0, total_lines - chat_height)
else:
start = max(0, total_lines - chat_height - self.scroll_offset)
for i in range(chat_height):
line_idx = start + i
if line_idx < total_lines:
line = display_lines[line_idx]
if line.startswith('['):
stdscr.addstr(i + 1, 0, line[:w-1], curses.color_pair(4) | curses.A_BOLD)
else:
self.display_formatted_line(stdscr, i + 1, 2, line, w - 2)
if total_lines > chat_height:
if self.scroll_offset > 0:
pct = int((start / max_scroll) * 100) if max_scroll > 0 else 0
indicator = f"↑{pct}%"
else:
indicator = "↓end"
stdscr.addstr(chat_height, w - len(indicator) - 1, indicator, curses.color_pair(3))
# Separator line
sep_y = chat_height + 1
for i in range(w):
stdscr.addch(sep_y, i, curses.ACS_HLINE, curses.color_pair(6))
# Input box
cursor_line, cursor_col = self._get_input_cursor_pos(w - 4)
cursor_line = min(cursor_line, input_height - 1)
input_y = sep_y + 1
for i in range(input_height):
if i < len(input_lines):
if i == 0:
stdscr.addstr(input_y + i, 0, ">> ", curses.A_BOLD)
if i == cursor_line and cursor_col < len(input_lines[i]):
stdscr.addstr(input_y + i, 3, input_lines[i][:cursor_col])
if cursor_col < len(input_lines[i]):
stdscr.addch(input_y + i, 3 + cursor_col, input_lines[i][cursor_col], curses.A_REVERSE)
if cursor_col + 1 < len(input_lines[i]):
stdscr.addstr(input_y + i, 3 + cursor_col + 1, input_lines[i][cursor_col + 1:])
else:
stdscr.addstr(input_y + i, 3, input_lines[i])
else:
if i == cursor_line and cursor_col < len(input_lines[i]):
stdscr.addstr(input_y + i, 3, input_lines[i][:cursor_col])
if cursor_col < len(input_lines[i]):
stdscr.addch(input_y + i, 3 + cursor_col, input_lines[i][cursor_col], curses.A_REVERSE)
if cursor_col + 1 < len(input_lines[i]):
stdscr.addstr(input_y + i, 3 + cursor_col + 1, input_lines[i][cursor_col + 1:])
else:
stdscr.addstr(input_y + i, 3, input_lines[i])
else:
if i == 0:
stdscr.addstr(input_y + i, 0, ">> ", curses.A_BOLD)
try:
stdscr.move(input_y + cursor_line, 3 + cursor_col)
except:
pass
# Status line
status_y = h - 1
if self.scroll_offset > 0:
status = "↑ Scrolled up | ↑↓=scroll PgUp/Dn=page | .r=redo | .s=scene | Esc=menu"
else:
status = "↑↓=scroll PgUp/Dn=page | ←→=cursor | .r=redo | .s=scene | Esc=menu | Enter=send"
stdscr.addstr(status_y, 0, status[:w-1], curses.color_pair(3))
stdscr.refresh()
# Get input with timeout for auto-save
stdscr.timeout(1000)
key = stdscr.getch()
if key == -1:
continue
# Handle key
self._handle_chat_key(stdscr, key, chat_height, max_scroll)
def _build_display_lines(self, width):
"""Build wrapped display lines from chat_lines"""
display_lines = []
current_sender = None
for line in self.chat_lines:
if line.startswith('['):
end_bracket = line.find(']')
if end_bracket != -1:
sender = line[1:end_bracket]
content = line[end_bracket + 2:]
if sender != current_sender:
display_lines.append(f"[{sender}]:")
current_sender = sender
if content.strip():
display_lines.extend(self.wrap_text(content, width - 4))
else:
display_lines.extend(self.wrap_text(line, width - 4))
return display_lines
def _get_input_lines(self, max_width):
"""Get the input buffer split into display lines"""
if not self.input_buffer:
return [""]
return self.wrap_text(self.input_buffer, max_width)
def _get_input_cursor_pos(self, max_width):
"""Get cursor line and column position in the input box"""
text_before_cursor = self.input_buffer[:self._cursor_pos]
lines = self.wrap_text(text_before_cursor, max_width)
if not lines:
return 0, 0
cursor_line = len(lines) - 1
cursor_col = len(lines[-1])
return cursor_line, cursor_col
def _handle_chat_key(self, stdscr, key, chat_height, max_scroll):
"""Handle key input in chat mode"""
# When scene view is active, only .s (toggle off) and Esc (main menu) work
if self.scene_view:
if key == 27: # Esc - back to main menu
self.scene_view = False
self.save_current_chat()
self.current_screen = "main"
self.scroll_offset = 0
elif key == ord('.'):
stdscr.timeout(100)
next_key = stdscr.getch()
stdscr.timeout(-1)
if next_key == ord('s'):
self.scene_view = False
return
# Esc - back to main menu
if key == 27:
self.save_current_chat()
self.current_screen = "main"
self.scroll_offset = 0
return
# Up arrow - scroll chat up (see older messages)
if key == curses.KEY_UP:
self.scroll_offset = min(self.scroll_offset + 3, max_scroll)
return
# Down arrow - scroll chat down (see newer messages)
if key == curses.KEY_DOWN:
self.scroll_offset = max(0, self.scroll_offset - 3)
return
# Page Up - scroll chat up a full page
if key == curses.KEY_PPAGE:
self.scroll_offset = min(self.scroll_offset + chat_height, max_scroll)
return
# Page Down - scroll chat down a full page
if key == curses.KEY_NPAGE:
self.scroll_offset = max(0, self.scroll_offset - chat_height)
return
# Dot commands: .+r = regenerate, .+s = scene state overlay
if key == ord('.') and not self.input_buffer:
stdscr.timeout(100) # Short timeout to detect held keys
next_key = stdscr.getch()
stdscr.timeout(-1) # Reset to blocking BEFORE any sub-screen
if next_key == ord('r'):
self.regenerate_last(stdscr)
return
elif next_key == ord('s'):
self.scene_view = not self.scene_view
self._rebuild_display = True
return
elif next_key != -1:
# neither r nor s, treat . as normal input
self.input_buffer += '.'
self._cursor_pos += 1
return
# Enter - send message
if key == ord('\n'):
if self.input_buffer.strip():
self.scroll_offset = 0
self._rebuild_display = True
self.send_message(stdscr)
self.input_buffer = ""
self._cursor_pos = 0
return
# Backspace - handle multiple possible key codes
if key == curses.KEY_BACKSPACE or key == 127 or key == 8 or key == 263: # Various backspace codes
if self._cursor_pos > 0:
self.input_buffer = self.input_buffer[:self._cursor_pos-1] + self.input_buffer[self._cursor_pos:]
self._cursor_pos -= 1
return
# Delete
if key == curses.KEY_DC:
if self._cursor_pos < len(self.input_buffer):
self.input_buffer = self.input_buffer[:self._cursor_pos] + self.input_buffer[self._cursor_pos+1:]
return
# Left arrow - move cursor left in input
if key == curses.KEY_LEFT:
if self._cursor_pos > 0:
self._cursor_pos -= 1
return
# Right arrow - move cursor right in input
if key == curses.KEY_RIGHT:
if self._cursor_pos < len(self.input_buffer):
self._cursor_pos += 1
return
# Home - cursor to start
if key == curses.KEY_HOME:
self._cursor_pos = 0
return
# End - cursor to end
if key == curses.KEY_END:
self._cursor_pos = len(self.input_buffer)
return
# Printable characters
if 32 <= key <= 126:
char = chr(key)
self.input_buffer = self.input_buffer[:self._cursor_pos] + char + self.input_buffer[self._cursor_pos:]
self._cursor_pos += 1
def display_formatted_line(self, stdscr, y, x, text, max_width):
"""Display text with color formatting for quotes and actions"""
current_x = x
i = 0
text_len = len(text)
in_quotes = False
in_action = False
while i < text_len and current_x < x + max_width:
# Check for quote start
if not in_quotes and not in_action and i + 1 < text_len and text[i] == '"' and text[i+1] == '"':
in_quotes = True
stdscr.addch(y, current_x, '"', curses.color_pair(8) | curses.A_DIM)
current_x += 1
stdscr.addch(y, current_x, '"', curses.color_pair(8) | curses.A_DIM)
current_x += 1
i += 2
continue
# Check for quote end
if in_quotes and i + 1 < text_len and text[i] == '"' and text[i+1] == '"':
in_quotes = False
stdscr.addch(y, current_x, '"', curses.color_pair(8) | curses.A_DIM)
current_x += 1
stdscr.addch(y, current_x, '"', curses.color_pair(8) | curses.A_DIM)
current_x += 1
i += 2
continue
# Check for action start
if not in_action and not in_quotes and i + 1 < text_len and text[i] == '*' and text[i+1] == '*':
in_action = True
stdscr.addch(y, current_x, '*', curses.color_pair(7))
current_x += 1
stdscr.addch(y, current_x, '*', curses.color_pair(7))
current_x += 1
i += 2
continue
# Check for action end
if in_action and i + 1 < text_len and text[i] == '*' and text[i+1] == '*':
in_action = False
stdscr.addch(y, current_x, '*', curses.color_pair(7))
current_x += 1
stdscr.addch(y, current_x, '*', curses.color_pair(7))
current_x += 1
i += 2
continue
# Regular character
if in_quotes:
stdscr.addch(y, current_x, text[i], curses.color_pair(8) | curses.A_DIM)
elif in_action:
stdscr.addch(y, current_x, text[i], curses.color_pair(7))
else:
stdscr.addch(y, current_x, text[i], curses.color_pair(6))
current_x += 1
i += 1
def wrap_text(self, text, width):
"""Wrap text to fit within width"""
if len(text) <= width:
return [text]
lines = []
current_line = ""
for word in text.split(' '):
if len(current_line) + len(word) + 1 <= width:
if current_line:
current_line += " " + word
else:
current_line = word
else:
if current_line:
lines.append(current_line)
# Handle words longer than width
if len(word) > width:
# Break up long words
for i in range(0, len(word), width):
lines.append(word[i:i+width])
else:
current_line = word
if current_line:
lines.append(current_line)
return lines
def add_message(self, sender, message):
"""Add message to chat with proper format"""
# Split message by newlines to handle pre-formatted AI responses
message_parts = message.split('\n')
for part in message_parts:
if part.strip(): # Only add non-empty parts
self.chat_lines.append(f"[{sender}]: {part}")
# Update conversation history
self.conversation_history.append({"role": "user" if sender == "You" else "model", "parts": [message]})
# Keep chat history manageable
if len(self.chat_lines) > 100:
self.chat_lines = self.chat_lines[-50:]
def _show_waiting_indicator(self, stdscr):
"""Show 'AI is answering...' indicator on screen before blocking API call"""
try:
h, w = stdscr.getmaxyx()
msg = f" {self.current_character['name']} is thinking... "
stdscr.addstr(h - 3, (w - len(msg)) // 2, msg, curses.color_pair(3) | curses.A_BOLD)
stdscr.refresh()
except:
pass
def _build_scene_state_lines(self, width):
"""Build compact scene state display lines"""
if not self.scene_state:
return []
s = self.scene_state
lines = []
loc = s.get('location', '')
plans = s.get('plans', '')
notes = s.get('notes', '')
outfits = s.get('outfits', {})
present = s.get('characters_present', [])
# Line 1: location + present
present_str = ', '.join(present) if present else ''
loc_line = f"📍 {loc}"
if present_str:
loc_line += f" 👥 {present_str}"
lines.append(loc_line[:width-1])
# Line 2: outfits
if outfits:
outfit_parts = [f"{k}: {v}" for k, v in outfits.items() if v]
outfit_line = "👗 " + " | ".join(outfit_parts)
lines.append(outfit_line[:width-1])
# Line 3: plans / notes (combined if short enough)
extras = []
if plans and plans.lower() != 'none':
extras.append(f"🗺 {plans}")
if notes:
extras.append(f"📝 {notes}")
if extras:
combined = " ".join(extras)
lines.append(combined[:width-1])
# Line 4: relationships summary (compact)
relationships = s.get('relationships', {})
if relationships:
rel_parts = []
for pair, rel in relationships.items():
status = rel.get('status', '')
rel_parts.append(f"{pair}: {status}")
rel_line = "💞 " + " | ".join(rel_parts)
lines.append(rel_line[:width-1])
# Line 5: long_term_notes first sentence as teaser
long_term = s.get('long_term_notes', '')
if long_term:
first_sentence = long_term.split('.')[0].strip()
if first_sentence:
lines.append(f"📖 {first_sentence[:width-5]}…")
return lines
def _show_scene_state_overlay(self, stdscr):
"""Show fullscreen scene state overlay. Press any key to dismiss."""
h, w = stdscr.getmaxyx()
stdscr.clear()
# Title bar
title = f" Scene State — {self.current_character['name']} "
stdscr.addstr(0, 0, title.center(w), curses.color_pair(1) | curses.A_BOLD)
row = 2
if not self.scene_state:
stdscr.addstr(row, 4, "No scene state yet — send a message first.", curses.color_pair(3))
row += 1
else:
s = self.scene_state
def section(label, value, color=curses.color_pair(3)):
nonlocal row
if row >= h - 2:
return
header = f" {label}"
stdscr.addstr(row, 0, header, curses.color_pair(4) | curses.A_BOLD)
row += 1
if isinstance(value, list):
text = ', '.join(value) if value else '—'
lines = textwrap.wrap(text, w - 6) or ['—']
else:
lines = textwrap.wrap(str(value) if value else '—', w - 6) or ['—']
for line in lines:
if row >= h - 2:
break
stdscr.addstr(row, 4, line, color)
row += 1
row += 1 # blank line between sections
section("📍 LOCATION", s.get('location', ''))
section("👥 CHARACTERS PRESENT", s.get('characters_present', []))
outfits = s.get('outfits', {})
if outfits:
stdscr.addstr(row, 0, " 👗 OUTFITS", curses.color_pair(4) | curses.A_BOLD)
row += 1
for name, outfit in outfits.items():
if row >= h - 2:
break
label_line = f" {name}:"
stdscr.addstr(row, 0, label_line, curses.color_pair(4))
row += 1
for line in (textwrap.wrap(outfit, w - 8) or ['—']):
if row >= h - 2:
break
stdscr.addstr(row, 8, line, curses.color_pair(3))
row += 1
row += 1
plans = s.get('plans', '')
if plans and plans.lower() != 'none':
section("🗺 PLANS", plans)
notes = s.get('notes', '')
if notes:
section("📝 NOTES", notes)
# Relationships
relationships = s.get('relationships', {})
if relationships and row < h - 2:
stdscr.addstr(row, 0, " 💞 RELATIONSHIPS", curses.color_pair(4) | curses.A_BOLD)
row += 1
for pair, rel in relationships.items():
if row >= h - 2: break
status_str = rel.get('status', '')
depth_str = rel.get('depth', '')
info_str = rel.get('info', '')
stdscr.addstr(row, 4, f"{pair}:", curses.color_pair(4))
row += 1
if row < h - 2:
stdscr.addstr(row, 6, f"{status_str} [{depth_str}]", curses.color_pair(3))
row += 1
if info_str and row < h - 2:
for line in (textwrap.wrap(info_str, w - 10) or []):
if row >= h - 2: break
stdscr.addstr(row, 8, line, curses.color_pair(3))
row += 1
row += 1
# Long-term story notes
long_term = s.get('long_term_notes', '')
if long_term and row < h - 2:
stdscr.addstr(row, 0, " 📖 STORY SO FAR", curses.color_pair(4) | curses.A_BOLD)
row += 1
for line in (textwrap.wrap(long_term, w - 6) or ['—']):
if row >= h - 2: break
stdscr.addstr(row, 4, line, curses.color_pair(3))
row += 1
row += 1
# Footer
footer = " Press any key to close "
try:
stdscr.addstr(h - 1, 0, footer.center(w), curses.color_pair(1))
except:
pass
stdscr.refresh()
stdscr.getch() # Already blocking (timeout=-1 set before this was called)
def send_message(self, stdscr=None):
"""Send message to AI"""
# Check rate limiting (wait 2 seconds between API calls)
current_time = datetime.now().timestamp()
if current_time - self.last_api_call < 2:
# Show rate limit message
self.chat_lines.append("[System]: Please wait 2 seconds between messages...")
return
# Add user message
self.add_message("You", self.input_buffer)
# Show "AI is answering..." indicator
self._show_waiting_indicator(stdscr)
# Get AI response
current_persona = self.persona_manager.get_current_persona()
try:
raw_response = self.gemini_client.send_message(
self.current_character,
self.input_buffer,
self.conversation_history[:-1], # Exclude the message we just added
current_persona,
self.scene_state
)
self.last_api_call = current_time
# Extract scene state from response
clean_response, new_scene_state = self.gemini_client.extract_scene_state(raw_response)
if new_scene_state:
self.scene_state = new_scene_state
# Add AI response (clean, without scene_state block)
self.add_message(self.current_character['name'], clean_response)
# Auto-save chat
self.save_current_chat()
except Exception as e:
# Handle API errors
error_msg = f"[System]: API Error: {str(e)}"
self.chat_lines.append(error_msg)
self.last_api_call = current_time
def regenerate_last(self, stdscr):
"""Regenerate the last AI response"""
# Find the last AI message in conversation_history
if not self.conversation_history:
self.chat_lines.append("[System]: Nothing to regenerate.")
return
# Find last model message index in conversation_history
last_model_idx = -1
for i in range(len(self.conversation_history) - 1, -1, -1):
if self.conversation_history[i]['role'] == 'model':
last_model_idx = i
break
if last_model_idx == -1:
self.chat_lines.append("[System]: No AI response to regenerate.")
return
# Find the user message that preceded it
last_user_idx = -1
for i in range(last_model_idx - 1, -1, -1):
if self.conversation_history[i]['role'] == 'user':
last_user_idx = i
break
if last_user_idx == -1:
self.chat_lines.append("[System]: No user message found to regenerate from.")
return
# Get the user message text