-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.c
More file actions
4601 lines (3845 loc) · 130 KB
/
main.c
File metadata and controls
4601 lines (3845 loc) · 130 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
#define _DEFAULT_SOURCE
#define _XOPEN_SOURCE
#define TB_OPT_ATTR_W 64
#define TB_OPT_EGC
#define TB_OPT_PRINTF_BUF 8192
#define TB_OPT_READ_BUF 128
#define TB_IMPL
#include <ApplicationServices/ApplicationServices.h>
#include <CoreFoundation/CoreFoundation.h>
#include <errno.h>
#include <inttypes.h>
#include <locale.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <wchar.h>
#include "ai.h"
#include "third-party/cJSON.h"
#include "third-party/md4c_ansi.h"
#include "third-party/termbox2.h"
#define SIDEBAR_WIDTH 30
#define INPUT_MIN_HEIGHT 3
#define INPUT_MAX_HEIGHT 10
#define MIN_CHAT_WIDTH 40
#define MIN_TERM_WIDTH 90
#define MIN_TERM_HEIGHT 10
#define MAX_MESSAGE_LENGTH 4096
#define MAX_TOOL_RESPONSE_LENGTH 2048
#define MAX_TOOLS 32
#define APP_DIR_NAME ".momo"
#define MESSAGE_MARGIN 4
#define TARGET_FPS 60
#define FRAME_TIME_US (1000000 / TARGET_FPS)
#define MAX_FRAME_TIME_US (1000000 / 30)
#define UTF8_PLAIN_TEXT_TYPE CFSTR("public.utf8-plain-text")
#define PLAIN_TEXT_TYPE CFSTR("public.plain-text")
#define COLOR_BG TB_DEFAULT
#define COLOR_FG 0xE8E8E8
#define COLOR_ACCENT 0x00AAFF
#define COLOR_USER 0x4A90E2
#define COLOR_ASSISTANT 0x7ED321
#define COLOR_SYSTEM 0xF5A623
#define COLOR_ERROR 0xD0021B
#define COLOR_SUCCESS 0x50E3C2
#define COLOR_PANEL 0xF0F0F0
#define COLOR_DIM 0x888888
#define COLOR_TOOL 0xBD10E0
#define COLOR_DIVIDER 0x2D2D2D
#define COLOR_TIMESTAMP 0x666666
#define COLOR_METADATA 0x999999
#define COLOR_BORDER 0x404040
#define COLOR_HIGHLIGHT 0x3D4043
#define COLOR_USER_BG 0x1A1D29
#define COLOR_ASSISTANT_BG 0x1A2617
#define COLOR_SYSTEM_BG 0x292317
#define COLOR_JSON_KEY 0x66D9EF
#define COLOR_JSON_STRING 0xA6E22E
#define COLOR_JSON_NUMBER 0xAE81FF
#define COLOR_JSON_BOOLEAN 0xF92672
#define COLOR_JSON_NULL 0x75715E
#define COLOR_JSON_BRACE 0xF8F8F2
#define COLOR_JSON_COLON 0xF8F8F2
#define COLOR_LABEL_USER 0x5DADE2
#define COLOR_LABEL_ASSISTANT 0x58D68D
#define COLOR_LABEL_SYSTEM 0xF39C12
#define COLOR_LABEL_TOOL_EXEC 0xE74C3C
#define COLOR_LABEL_TOOL_RESP 0x9B59B6
#define COLOR_LOGO_DARK 0x4A5568
#define COLOR_LOGO_LIGHT 0x8BB9E8
#define MESSAGE_PADDING 2
#define MESSAGE_SEPARATOR_HEIGHT 1
#define HEADER_SPACING 2
const uint32_t momo_line1[] = {0x2588, 0x2588, 0x2588, 0x0020, 0x0020,
0x0020, 0x0020, 0x2588, 0x2588, 0x2588,
0x0020, 0x0020, 0x2588, 0x2588, 0x2588,
0x2588, 0x2588, 0x2588, 0x0020, 0x0000};
const uint32_t momo_line2[] = {0x2588, 0x2588, 0x2588, 0x2588, 0x0020,
0x0020, 0x2588, 0x2588, 0x2588, 0x2588,
0x0020, 0x2588, 0x2588, 0x0020, 0x0020,
0x0020, 0x0020, 0x2588, 0x2588, 0x0000};
const uint32_t momo_line3[] = {0x2588, 0x2588, 0x0020, 0x2588, 0x2588,
0x2588, 0x2588, 0x0020, 0x2588, 0x2588,
0x0020, 0x2588, 0x2588, 0x0020, 0x0020,
0x0020, 0x0020, 0x2588, 0x2588, 0x0000};
const uint32_t momo_line4[] = {0x2588, 0x2588, 0x0020, 0x0020, 0x2588,
0x2588, 0x0020, 0x0020, 0x2588, 0x2588,
0x0020, 0x2588, 0x2588, 0x0020, 0x0020,
0x0020, 0x0020, 0x2588, 0x2588, 0x0000};
const uint32_t momo_line5[] = {0x2588, 0x2588, 0x0020, 0x0020, 0x0020,
0x0020, 0x0020, 0x0020, 0x2588, 0x2588,
0x0020, 0x0020, 0x2588, 0x2588, 0x2588,
0x2588, 0x2588, 0x2588, 0x0020, 0x0000};
typedef struct {
struct timeval last_frame;
struct timeval current_frame;
long frame_delta_us;
int fps_counter;
time_t fps_last_second;
int current_fps;
float smooth_fps;
bool first_frame;
} frame_timing_t;
typedef struct {
char *type;
char *command;
char **args;
int arg_count;
char **env;
int env_count;
} mcp_config_t;
typedef struct {
char *name;
char *description;
char *input_schema;
mcp_config_t *mcp;
bool is_builtin;
} tool_config_t;
typedef enum { STATE_WELCOME, STATE_CHAT, STATE_SETTINGS } app_state_t;
typedef enum {
MSG_USER,
MSG_ASSISTANT,
MSG_SYSTEM,
MSG_TOOL_CALL,
MSG_TOOL_RESPONSE
} message_type_t;
typedef enum {
RESPONSE_MODE_NORMAL,
RESPONSE_MODE_TOOLS_ENABLED
} response_mode_t;
typedef struct tool_execution {
char *tool_name;
char *parameters;
char *response;
struct tool_execution *next;
} tool_execution_t;
typedef struct {
bool enable_tools;
bool enable_history;
bool enable_guardrails;
response_mode_t response_mode;
double temperature;
int max_tokens;
} session_config_t;
typedef struct rendered_line {
char *text;
uintattr_t color;
struct rendered_line *next;
} rendered_line_t;
typedef struct message {
message_type_t type;
char *content;
char *tool_name;
time_t timestamp;
bool is_streaming;
tool_execution_t *tool_executions;
rendered_line_t *lines;
int line_count;
bool needs_rerender;
struct message *next;
} message_t;
typedef struct message_update {
message_t *target_message;
char *new_content;
bool is_streaming;
tool_execution_t *new_tool_executions;
bool process_markdown;
struct message_update *next;
} message_update_t;
typedef struct {
message_update_t *head;
message_update_t *tail;
pthread_mutex_t mutex;
pthread_cond_t cond;
} update_queue_t;
typedef struct {
bool active;
ai_stream_id_t stream_id;
char *accumulated_text;
size_t accumulated_length;
bool waiting_for_stream;
pthread_mutex_t mutex;
} streaming_context_t;
typedef struct {
int thinking_frame;
int cursor_blink_frame;
int loading_dots_frame;
long animation_timer_us;
bool show_cursor;
} animation_state_t;
typedef struct {
int scroll_offset;
bool auto_scroll;
int total_lines;
int visible_lines;
} chat_display_t;
static struct {
int term_width;
int term_height;
bool running;
bool needs_resize;
frame_timing_t timing;
animation_state_t animation;
ai_context_t *ai_context;
ai_session_id_t ai_session;
ai_availability_t ai_availability;
char *availability_reason;
app_state_t state;
session_config_t session_config;
tool_config_t tools[MAX_TOOLS];
int tool_count;
char *tools_json;
char *app_dir;
int chat_width;
int sidebar_x;
int chat_height;
int input_height;
bool show_sidebar;
message_t *messages;
message_t *current_streaming;
int message_count;
chat_display_t chat;
update_queue_t update_queue;
char input_buffer[MAX_MESSAGE_LENGTH];
int input_pos;
int input_scroll;
streaming_context_t streaming;
ai_stats_t stats;
} app;
static void init_app(void);
static void cleanup_app(void);
static bool init_ai_session(void);
static void cleanup_ai_session(void);
static bool init_app_directory(void);
static char *load_schema_from_file(const char *filepath) {
FILE *file = fopen(filepath, "r");
if (!file) {
return NULL;
}
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
fseek(file, 0, SEEK_SET);
if (file_size <= 0) {
fclose(file);
return NULL;
}
char *content = malloc(file_size + 1);
if (!content) {
fclose(file);
return NULL;
}
size_t read_size = fread(content, 1, file_size, file);
content[read_size] = '\0';
fclose(file);
return content;
}
static bool parse_schema_directive(const char *input, char **extracted_message,
char **schema_content) {
*extracted_message = NULL;
*schema_content = NULL;
const char *schema_start = strstr(input, "/schema ");
if (!schema_start) {
return false;
}
const char *filepath_start = schema_start + 8;
while (*filepath_start == ' ' || *filepath_start == '\t') {
filepath_start++;
}
if (*filepath_start == '\0') {
return false;
}
const char *filepath_end = filepath_start;
while (*filepath_end != '\0' && *filepath_end != ' ' &&
*filepath_end != '\t' && *filepath_end != '\n') {
filepath_end++;
}
size_t filepath_len = filepath_end - filepath_start;
char *filepath = malloc(filepath_len + 1);
if (!filepath) {
return false;
}
strncpy(filepath, filepath_start, filepath_len);
filepath[filepath_len] = '\0';
*schema_content = load_schema_from_file(filepath);
free(filepath);
if (!*schema_content) {
return false;
}
size_t input_len = strlen(input);
size_t directive_start = schema_start - input;
size_t directive_len = filepath_end - schema_start;
size_t before_len = directive_start;
size_t after_len = input_len - (directive_start + directive_len);
while (*filepath_end == ' ' || *filepath_end == '\t') {
filepath_end++;
after_len = input_len - (filepath_end - input);
}
*extracted_message = malloc(before_len + after_len + 1);
if (!*extracted_message) {
free(*schema_content);
*schema_content = NULL;
return false;
}
strncpy(*extracted_message, input, before_len);
strcpy(*extracted_message + before_len, filepath_end);
char *end = *extracted_message + strlen(*extracted_message) - 1;
while (end >= *extracted_message &&
(*end == ' ' || *end == '\t' || *end == '\n')) {
*end = '\0';
end--;
}
return true;
}
static char *get_clipboard_text() {
PasteboardRef pasteboard;
OSStatus status;
ItemCount item_count;
PasteboardItemID item_id;
CFDataRef clipboard_data;
CFStringRef clipboard_string;
char *result = NULL;
// Create a reference to the system clipboard
status = PasteboardCreate(kPasteboardClipboard, &pasteboard);
if (status != noErr) {
return NULL;
}
// Synchronize with the current clipboard contents
PasteboardSynchronize(pasteboard);
// Get the number of items on the clipboard
status = PasteboardGetItemCount(pasteboard, &item_count);
if (status != noErr || item_count < 1) {
CFRelease(pasteboard);
return NULL;
}
// Get the first item's ID
status = PasteboardGetItemIdentifier(pasteboard, 1, &item_id);
if (status != noErr) {
CFRelease(pasteboard);
return NULL;
}
// Try to get text data from the clipboard
status = PasteboardCopyItemFlavorData(pasteboard, item_id,
UTF8_PLAIN_TEXT_TYPE, &clipboard_data);
if (status != noErr) {
// If UTF-8 fails, try plain text
status = PasteboardCopyItemFlavorData(pasteboard, item_id, PLAIN_TEXT_TYPE,
&clipboard_data);
if (status != noErr) {
CFRelease(pasteboard);
return NULL;
}
}
// Convert CFData to CFString
clipboard_string = CFStringCreateFromExternalRepresentation(
kCFAllocatorDefault, clipboard_data, kCFStringEncodingUTF8);
if (clipboard_string) {
// Get the length needed for C string
CFIndex string_length = CFStringGetLength(clipboard_string);
CFIndex max_size = CFStringGetMaximumSizeForEncoding(
string_length, kCFStringEncodingUTF8) +
1;
// Allocate memory and convert to C string
result = malloc(max_size);
if (result) {
Boolean success = CFStringGetCString(clipboard_string, result, max_size,
kCFStringEncodingUTF8);
if (!success) {
free(result);
result = NULL;
}
}
CFRelease(clipboard_string);
}
// Clean up
CFRelease(clipboard_data);
CFRelease(pasteboard);
return result;
}
static void free_tools_config(void);
static void free_mcp_config(mcp_config_t *mcp);
static char *create_tools_json_for_bridge(void);
static char *execute_mcp_tool(const mcp_config_t *mcp, const char *input_json);
static char *load_schema_from_file(const char *filepath);
static bool parse_schema_directive(const char *input, char **extracted_message,
char **schema_content);
static void init_update_queue(void);
static void cleanup_update_queue(void);
static void queue_message_update(message_t *msg, const char *content,
bool is_streaming,
tool_execution_t *tool_executions);
static void process_message_updates(void);
static message_update_t *create_message_update(
message_t *msg, const char *content, bool is_streaming,
tool_execution_t *tool_executions);
static void free_message_update(message_update_t *update);
static tool_execution_t *clone_tool_executions(tool_execution_t *src);
static void add_tool_execution_to_list(tool_execution_t **list,
const char *tool_name,
const char *parameters,
const char *response);
static void free_tool_executions(tool_execution_t *executions);
static void init_frame_timing(void);
static void update_frame_timing(void);
static void wait_for_next_frame(void);
static void update_animations(long delta_us);
static void init_animations(void);
typedef struct {
char *accumulated_output;
size_t output_length;
size_t output_capacity;
} markdown_render_context_t;
static void markdown_output_callback(const MD_CHAR *data, MD_SIZE data_size,
void *userdata) {
markdown_render_context_t *ctx = (markdown_render_context_t *)userdata;
if (!ctx || !data || data_size == 0) return;
size_t needed = ctx->output_length + data_size + 1;
if (needed > ctx->output_capacity) {
size_t new_capacity = ctx->output_capacity * 2;
if (new_capacity < needed) new_capacity = needed;
char *new_buffer = realloc(ctx->accumulated_output, new_capacity);
if (!new_buffer) return;
ctx->accumulated_output = new_buffer;
ctx->output_capacity = new_capacity;
}
memcpy(ctx->accumulated_output + ctx->output_length, data, data_size);
ctx->output_length += data_size;
ctx->accumulated_output[ctx->output_length] = '\0';
}
static char *process_markdown_to_ansi(const char *markdown_content) {
if (!markdown_content) return NULL;
markdown_render_context_t ctx;
ctx.output_capacity = strlen(markdown_content) * 2;
ctx.accumulated_output = malloc(ctx.output_capacity);
ctx.output_length = 0;
if (!ctx.accumulated_output) return NULL;
ctx.accumulated_output[0] = '\0';
unsigned parser_flags = 0;
parser_flags |= MD_FLAG_TABLES;
parser_flags |= MD_FLAG_STRIKETHROUGH;
parser_flags |= MD_FLAG_TASKLISTS;
parser_flags |= MD_FLAG_LATEXMATHSPANS;
parser_flags |= MD_FLAG_WIKILINKS;
unsigned renderer_flags = 0;
int result =
md_ansi(markdown_content, strlen(markdown_content),
markdown_output_callback, &ctx, parser_flags, renderer_flags);
if (result != 0) {
free(ctx.accumulated_output);
return NULL;
}
return ctx.accumulated_output;
}
static void rebuild_all_message_rendering(void);
static void free_message_lines(message_t *msg);
static void add_rendered_line(message_t *msg, const char *text,
uintattr_t color);
static void render_content_lines(message_t *msg, const char *content,
uintattr_t color, int indent);
static void render_tool_executions(message_t *msg);
static void calculate_chat_metrics(void);
static void scroll_chat(int lines);
static void scroll_to_bottom(void);
static void scroll_to_top(void);
static void draw_chat_messages(void);
static char *sanitize_utf8_string(const char *input);
static void wrap_text_to_lines(const char *text, int max_width, char ***lines,
int *line_count);
static bool is_json_content(const char *content);
static bool is_word_boundary(uint32_t codepoint);
static const char *get_message_label_text(message_type_t type);
static const char *get_message_label_icon(message_type_t type);
static uintattr_t get_message_label_color(message_type_t type);
static void move_cursor_up_in_input(void) {
if (app.input_pos == 0) return;
int line_start = app.input_pos;
while (line_start > 0 && app.input_buffer[line_start - 1] != '\n') {
line_start--;
}
if (line_start == 0) return;
int prev_line_end = line_start - 2;
while (prev_line_end >= 0 && app.input_buffer[prev_line_end] != '\n') {
prev_line_end--;
}
int prev_line_start = prev_line_end + 1;
int current_col = app.input_pos - line_start;
int prev_line_len = (line_start - 1) - prev_line_start;
int target_col = (current_col < prev_line_len) ? current_col : prev_line_len;
app.input_pos = prev_line_start + target_col;
}
static void move_cursor_down_in_input(void) {
int line_start = app.input_pos;
while (line_start > 0 && app.input_buffer[line_start - 1] != '\n') {
line_start--;
}
int line_end = app.input_pos;
while (line_end < (int)strlen(app.input_buffer) &&
app.input_buffer[line_end] != '\n') {
line_end++;
}
if (line_end >= (int)strlen(app.input_buffer)) return;
int next_line_start = line_end + 1;
int next_line_end = next_line_start;
while (next_line_end < (int)strlen(app.input_buffer) &&
app.input_buffer[next_line_end] != '\n') {
next_line_end++;
}
int current_col = app.input_pos - line_start;
int next_line_len = next_line_end - next_line_start;
int target_col = (current_col < next_line_len) ? current_col : next_line_len;
app.input_pos = next_line_start + target_col;
}
static void move_to_line_start(void) {
while (app.input_pos > 0 && app.input_buffer[app.input_pos - 1] != '\n') {
app.input_pos--;
}
}
static void move_to_line_end(void) {
while (app.input_pos < (int)strlen(app.input_buffer) &&
app.input_buffer[app.input_pos] != '\n') {
app.input_pos++;
}
}
static void move_to_previous_word(void) {
if (app.input_pos == 0) return;
uint32_t current_codepoint = 0;
if (app.input_pos > 0) {
int pos = app.input_pos - 1;
while (pos > 0 && (app.input_buffer[pos] & 0x80) &&
!(app.input_buffer[pos] & 0x40)) {
pos--;
}
tb_utf8_char_to_unicode(¤t_codepoint, app.input_buffer + pos);
}
if (!is_word_boundary(current_codepoint) && current_codepoint != '\n') {
while (app.input_pos > 0) {
int prev_pos = app.input_pos - 1;
while (prev_pos > 0 && (app.input_buffer[prev_pos] & 0x80) &&
!(app.input_buffer[prev_pos] & 0x40)) {
prev_pos--;
}
uint32_t codepoint;
int byte_len =
tb_utf8_char_to_unicode(&codepoint, app.input_buffer + prev_pos);
if (byte_len <= 0) break;
if (is_word_boundary(codepoint) || codepoint == '\n') {
break;
}
app.input_pos = prev_pos;
}
} else {
while (app.input_pos > 0) {
int prev_pos = app.input_pos - 1;
while (prev_pos > 0 && (app.input_buffer[prev_pos] & 0x80) &&
!(app.input_buffer[prev_pos] & 0x40)) {
prev_pos--;
}
uint32_t codepoint;
int byte_len =
tb_utf8_char_to_unicode(&codepoint, app.input_buffer + prev_pos);
if (byte_len <= 0) break;
if (!is_word_boundary(codepoint) && codepoint != '\n') {
app.input_pos = prev_pos;
while (app.input_pos > 0) {
int prev_pos2 = app.input_pos - 1;
while (prev_pos2 > 0 && (app.input_buffer[prev_pos2] & 0x80) &&
!(app.input_buffer[prev_pos2] & 0x40)) {
prev_pos2--;
}
uint32_t codepoint2;
tb_utf8_char_to_unicode(&codepoint2, app.input_buffer + prev_pos2);
if (is_word_boundary(codepoint2) || codepoint2 == '\n') {
break;
}
app.input_pos = prev_pos2;
}
break;
}
app.input_pos = prev_pos;
}
}
}
static void move_to_next_word(void) {
int input_len = strlen(app.input_buffer);
if (app.input_pos >= input_len) return;
uint32_t current_codepoint = 0;
if (app.input_pos < input_len) {
tb_utf8_char_to_unicode(¤t_codepoint,
app.input_buffer + app.input_pos);
}
if (!is_word_boundary(current_codepoint) && current_codepoint != '\n') {
while (app.input_pos < input_len) {
uint32_t codepoint;
int byte_len =
tb_utf8_char_to_unicode(&codepoint, app.input_buffer + app.input_pos);
if (byte_len <= 0) {
app.input_pos++;
continue;
}
if (is_word_boundary(codepoint) || codepoint == '\n') {
break;
}
app.input_pos += byte_len;
}
} else {
while (app.input_pos < input_len) {
uint32_t codepoint;
int byte_len =
tb_utf8_char_to_unicode(&codepoint, app.input_buffer + app.input_pos);
if (byte_len <= 0) {
app.input_pos++;
continue;
}
if (!is_word_boundary(codepoint) && codepoint != '\n') {
break;
}
app.input_pos += byte_len;
}
}
};
static int calculate_input_lines(void);
static void update_input_height(void);
char *tool_get_current_time(const char *parameters_json, void *user_data);
char *tool_calculate(const char *parameters_json, void *user_data);
char *tool_system_info(const char *parameters_json, void *user_data);
char *mcp_tool_handler(const char *parameters_json, void *user_data);
static void update_dimensions(void);
static void handle_input(struct tb_event *ev);
static void draw_welcome_screen(void);
static void draw_chat_interface(void);
static void draw_sidebar(void);
static void draw_input_bar(void);
static void render_frame(void);
static void process_command(const char *input);
static void send_message(const char *message);
static void add_message(message_type_t type, const char *content);
static void start_streaming_response(const char *prompt, const char *schema);
static void streaming_callback(ai_context_t *context, const char *chunk,
void *user_data);
static void free_messages(void);
static char *format_time(time_t timestamp);
static void draw_logo_line(int x, int y, const uint32_t *line,
uintattr_t color);
static int get_unicode_line_length(const uint32_t *line);
static void show_error_with_code(ai_result_t result, const char *context_msg);
static void show_error_message(const char *message);
static void update_app_stats(void);
static volatile sig_atomic_t resize_pending = 0;
static void handle_sigwinch(int sig) {
(void)sig;
resize_pending = 1;
}
static void init_update_queue(void) {
app.update_queue.head = NULL;
app.update_queue.tail = NULL;
pthread_mutex_init(&app.update_queue.mutex, NULL);
pthread_cond_init(&app.update_queue.cond, NULL);
}
static void cleanup_update_queue(void) {
pthread_mutex_lock(&app.update_queue.mutex);
message_update_t *current = app.update_queue.head;
while (current) {
message_update_t *next = current->next;
free_message_update(current);
current = next;
}
app.update_queue.head = NULL;
app.update_queue.tail = NULL;
pthread_mutex_unlock(&app.update_queue.mutex);
pthread_mutex_destroy(&app.update_queue.mutex);
pthread_cond_destroy(&app.update_queue.cond);
}
static message_update_t *create_message_update(
message_t *msg, const char *content, bool is_streaming,
tool_execution_t *tool_executions) {
message_update_t *update = malloc(sizeof(message_update_t));
if (!update) return NULL;
update->target_message = msg;
update->new_content = content ? strdup(content) : NULL;
update->is_streaming = is_streaming;
update->new_tool_executions = clone_tool_executions(tool_executions);
update->process_markdown = (content != NULL);
update->next = NULL;
return update;
}
static void free_message_update(message_update_t *update) {
if (!update) return;
if (update->new_content) free(update->new_content);
free_tool_executions(update->new_tool_executions);
free(update);
}
static void queue_message_update(message_t *msg, const char *content,
bool is_streaming,
tool_execution_t *tool_executions) {
message_update_t *update =
create_message_update(msg, content, is_streaming, tool_executions);
if (!update) return;
pthread_mutex_lock(&app.update_queue.mutex);
if (app.update_queue.tail) {
app.update_queue.tail->next = update;
app.update_queue.tail = update;
} else {
app.update_queue.head = app.update_queue.tail = update;
}
pthread_cond_signal(&app.update_queue.cond);
pthread_mutex_unlock(&app.update_queue.mutex);
}
static void render_markdown_lines(message_t *msg, const char *ansi_content) {
if (!msg || !ansi_content) return;
free_message_lines(msg);
if (msg->type == MSG_ASSISTANT && msg->tool_executions) {
render_tool_executions(msg);
add_rendered_line(msg, "", COLOR_FG);
}
const char *ptr = ansi_content;
const char *line_start = ptr;
while (*ptr) {
if (*ptr == '\n') {
size_t line_len = ptr - line_start;
char *line = malloc(line_len + 1);
if (line) {
strncpy(line, line_start, line_len);
line[line_len] = '\0';
add_rendered_line(msg, line, COLOR_FG);
free(line);
}
ptr++;
line_start = ptr;
} else {
ptr++;
}
}
if (line_start < ptr) {
size_t line_len = ptr - line_start;
char *line = malloc(line_len + 1);
if (line) {
strncpy(line, line_start, line_len);
line[line_len] = '\0';
add_rendered_line(msg, line, COLOR_FG);
free(line);
}
}
if (msg->is_streaming) {
pthread_mutex_lock(&app.streaming.mutex);
bool waiting = app.streaming.waiting_for_stream;
bool active = app.streaming.active;
pthread_mutex_unlock(&app.streaming.mutex);
if (active) {
if (waiting) {
const char *frames[] = {"⠋", "⠙", "⠹", "⠸"};
char thinking[32];
snprintf(thinking, sizeof(thinking), " %s Thinking...",
frames[app.animation.thinking_frame]);
add_rendered_line(msg, thinking, COLOR_ACCENT | TB_BOLD);
} else {
if (app.animation.show_cursor) {
add_rendered_line(msg, " ▋", COLOR_ACCENT);
}
}
}
}
msg->needs_rerender = false;
}
static void process_message_updates(void) {
pthread_mutex_lock(&app.update_queue.mutex);
message_update_t *current = app.update_queue.head;
app.update_queue.head = NULL;
app.update_queue.tail = NULL;
pthread_mutex_unlock(&app.update_queue.mutex);
while (current) {
message_update_t *next = current->next;
if (current->target_message) {
if (current->new_content) {
if (current->target_message->content)
free(current->target_message->content);
current->target_message->content = strdup(current->new_content);
}
current->target_message->is_streaming = current->is_streaming;
if (current->new_tool_executions) {
free_tool_executions(current->target_message->tool_executions);
current->target_message->tool_executions =
clone_tool_executions(current->new_tool_executions);
}
if (current->process_markdown && current->new_content) {
char *rendered_markdown =
process_markdown_to_ansi(current->new_content);
if (rendered_markdown) {
render_markdown_lines(current->target_message, rendered_markdown);
free(rendered_markdown);
} else {
current->target_message->needs_rerender = true;
}
} else {
current->target_message->needs_rerender = true;
}
}
free_message_update(current);
current = next;
}
}
static tool_execution_t *clone_tool_executions(tool_execution_t *src) {
if (!src) return NULL;
tool_execution_t *head = NULL;
tool_execution_t *tail = NULL;
tool_execution_t *current = src;
while (current) {
tool_execution_t *clone = malloc(sizeof(tool_execution_t));
if (!clone) break;
clone->tool_name = current->tool_name ? strdup(current->tool_name) : NULL;
clone->parameters =
current->parameters ? strdup(current->parameters) : NULL;
clone->response = current->response ? strdup(current->response) : NULL;
clone->next = NULL;
if (tail) {
tail->next = clone;
tail = clone;
} else {
head = tail = clone;
}
current = current->next;
}
return head;
}
static void add_tool_execution_to_list(tool_execution_t **list,
const char *tool_name,
const char *parameters,
const char *response) {
tool_execution_t *exec = malloc(sizeof(tool_execution_t));
if (!exec) return;