-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage_renderer.zig
More file actions
1756 lines (1509 loc) · 80.3 KB
/
message_renderer.zig
File metadata and controls
1756 lines (1509 loc) · 80.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
// Message rendering module - handles all display logic for messages
const std = @import("std");
const mem = std.mem;
const json = std.json;
const ui = @import("ui");
const markdown = @import("markdown");
const render = @import("render");
const types = @import("types");
// Import App type from app module (will be set up after app.zig imports this)
const app_module = @import("app");
const App = app_module.App;
const Message = types.Message;
/// Line type for message layout - helps identify what each line represents
pub const LineType = enum {
thinking_header,
thinking_content,
collapsed_thinking,
agent_analysis_hint,
agent_analysis_content,
collapsed_agent,
tool_header,
tool_content,
collapsed_tool,
main_content,
permission_header,
permission_details,
separator,
empty,
};
/// Represents a single line in a message layout with its type and content
pub const MessageLine = struct {
line_type: LineType,
content: []const u8, // Owned by the MessageLayout
pub fn deinit(self: *MessageLine, allocator: mem.Allocator) void {
allocator.free(self.content);
}
};
/// Message layout - contains all lines for a message and its height
/// This is the single source of truth for message structure
pub const MessageLayout = struct {
lines: std.ArrayListUnmanaged(MessageLine),
height: usize, // Total height including borders and spacing
pub fn init() MessageLayout {
return .{
.lines = .{},
.height = 0,
};
}
pub fn deinit(self: *MessageLayout, allocator: mem.Allocator) void {
for (self.lines.items) |*line| {
line.deinit(allocator);
}
self.lines.deinit(allocator);
}
};
/// Build message layout - single source of truth for message structure
/// This function determines what lines appear in a message and in what order
/// Both height calculation and rendering use this same logic
pub fn buildMessageLayout(app: *App, message: *Message) !MessageLayout {
const left_padding = 2;
const max_content_width = if (app.terminal_size.width > left_padding + 4)
app.terminal_size.width - left_padding - 4
else
0;
var layout = MessageLayout.init();
errdefer layout.deinit(app.allocator);
// Add thinking section if present
const has_thinking = message.thinking_content != null and message.processed_thinking_content != null;
if (has_thinking) {
if (message.thinking_expanded) {
// Header
try layout.lines.append(app.allocator, .{
.line_type = .thinking_header,
.content = try app.allocator.dupe(u8, "Thinking"),
});
// Content lines
if (message.processed_thinking_content) |*thinking_processed| {
var thinking_lines = std.ArrayListUnmanaged([]const u8){};
defer {
for (thinking_lines.items) |line| app.allocator.free(line);
thinking_lines.deinit(app.allocator);
}
try renderItemsToLines(app, thinking_processed, &thinking_lines, 0, max_content_width);
for (thinking_lines.items) |line| {
try layout.lines.append(app.allocator, .{
.line_type = .thinking_content,
.content = try app.allocator.dupe(u8, line),
});
}
}
// Separator
try layout.lines.append(app.allocator, .{
.line_type = .separator,
.content = try app.allocator.dupe(u8, ""),
});
} else {
// Collapsed thinking
try layout.lines.append(app.allocator, .{
.line_type = .collapsed_thinking,
.content = try app.allocator.dupe(u8, "💭 Thinking (Ctrl+O to expand)"),
});
try layout.lines.append(app.allocator, .{
.line_type = .separator,
.content = try app.allocator.dupe(u8, ""),
});
}
}
// Add agent analysis section if present
const has_agent_analysis = message.agent_analysis_name != null;
if (has_agent_analysis) {
if (message.agent_analysis_completed and !message.agent_analysis_expanded) {
// Collapsed agent analysis
const agent_time = message.tool_execution_time orelse 0;
const summary = try std.fmt.allocPrint(
app.allocator,
"🤔 {s} Analysis (✅ completed, {d}ms) - Ctrl+O to expand",
.{ message.agent_analysis_name.?, agent_time }
);
try layout.lines.append(app.allocator, .{
.line_type = .collapsed_agent,
.content = summary,
});
try layout.lines.append(app.allocator, .{
.line_type = .separator,
.content = try app.allocator.dupe(u8, ""),
});
} else {
// Expanded or streaming agent analysis
if (message.agent_analysis_completed) {
try layout.lines.append(app.allocator, .{
.line_type = .agent_analysis_hint,
.content = try app.allocator.dupe(u8, "(Ctrl+O to collapse)"),
});
}
// Content lines
var content_lines = std.ArrayListUnmanaged([]const u8){};
defer {
for (content_lines.items) |line| app.allocator.free(line);
content_lines.deinit(app.allocator);
}
try renderItemsToLines(app, &message.processed_content, &content_lines, 0, max_content_width);
for (content_lines.items) |line| {
try layout.lines.append(app.allocator, .{
.line_type = .agent_analysis_content,
.content = try app.allocator.dupe(u8, line),
});
}
try layout.lines.append(app.allocator, .{
.line_type = .separator,
.content = try app.allocator.dupe(u8, ""),
});
}
}
// Add tool call section if present
const has_tool_call = message.tool_name != null;
if (has_tool_call) {
if (message.tool_call_expanded) {
// Header
const tool_header_text = try std.fmt.allocPrint(
app.allocator,
"Tool: {s}",
.{message.tool_name.?}
);
try layout.lines.append(app.allocator, .{
.line_type = .tool_header,
.content = tool_header_text,
});
// Content lines
var tool_lines = std.ArrayListUnmanaged([]const u8){};
defer {
for (tool_lines.items) |line| app.allocator.free(line);
tool_lines.deinit(app.allocator);
}
try renderItemsToLines(app, &message.processed_content, &tool_lines, 0, max_content_width);
for (tool_lines.items) |line| {
try layout.lines.append(app.allocator, .{
.line_type = .tool_content,
.content = try app.allocator.dupe(u8, line),
});
}
try layout.lines.append(app.allocator, .{
.line_type = .separator,
.content = try app.allocator.dupe(u8, ""),
});
} else {
// Collapsed tool call
const status_icon = if (message.tool_success orelse false) "✅" else "❌";
const status_text = if (message.tool_success orelse false) "SUCCESS" else "FAILED";
var summary = std.ArrayListUnmanaged(u8){};
defer summary.deinit(app.allocator);
try summary.print(
app.allocator,
"🔧 Used tool: {s} ({s} {s})",
.{ message.tool_name.?, status_icon, status_text }
);
if (message.tool_execution_time) |exec_time| {
try summary.print(app.allocator, ", {d}ms", .{exec_time});
}
try summary.appendSlice(app.allocator, " - Ctrl+O to expand");
try layout.lines.append(app.allocator, .{
.line_type = .collapsed_tool,
.content = try summary.toOwnedSlice(app.allocator),
});
try layout.lines.append(app.allocator, .{
.line_type = .separator,
.content = try app.allocator.dupe(u8, ""),
});
}
}
// Add main content (if not handled by agent/tool sections above)
if (!has_agent_analysis and !has_tool_call) {
var content_lines = std.ArrayListUnmanaged([]const u8){};
defer {
for (content_lines.items) |line| app.allocator.free(line);
content_lines.deinit(app.allocator);
}
try renderItemsToLines(app, &message.processed_content, &content_lines, 0, max_content_width);
for (content_lines.items) |line| {
try layout.lines.append(app.allocator, .{
.line_type = .main_content,
.content = try app.allocator.dupe(u8, line),
});
}
}
// Add permission request section if present
if (message.permission_request) |_| {
// Note: Permission rendering is complex and stays in drawMessage for now
// We just mark that there is permission UI here
try layout.lines.append(app.allocator, .{
.line_type = .permission_header,
.content = try app.allocator.dupe(u8, "[Permission Request]"),
});
}
// Calculate total height: lines + borders + spacing
const box_height = layout.lines.items.len + 2; // +2 for top/bottom borders
layout.height = box_height + 1; // +1 for spacing after message
return layout;
}
/// Finalize a progress message with beautiful formatting (agents, GraphRAG, etc.)
/// This unified function replaces separate finalization logic in app.zig and app_graphrag.zig
/// Takes a ProgressDisplayContext pointer (using anytype to avoid circular module dependencies)
pub fn finalizeProgressMessage(ctx: anytype) !void {
const allocator = ctx.app.allocator;
const idx = ctx.current_message_idx orelse return;
var msg = &ctx.app.messages.items[idx];
// Calculate execution time
const end_time = std.time.milliTimestamp();
const execution_time = end_time - ctx.start_time;
// Free old content
allocator.free(msg.content);
for (msg.processed_content.items) |*item| {
item.deinit(allocator);
}
msg.processed_content.deinit(allocator);
if (msg.thinking_content) |tc| allocator.free(tc);
if (msg.processed_thinking_content) |*ptc| {
for (ptc.items) |*item| {
item.deinit(allocator);
}
ptc.deinit(allocator);
}
// Build final formatted message
var final_content = std.ArrayListUnmanaged(u8){};
defer final_content.deinit(allocator);
const writer = final_content.writer(allocator);
// Header with task name and icon
try writer.print("{s} **{s} Analysis**\n", .{ ctx.task_icon, ctx.task_name });
try writer.writeAll("─────────────────────────────────\n\n");
// Content (thinking + main content)
if (ctx.thinking_buffer.items.len > 0) {
try writer.writeAll(ctx.thinking_buffer.items);
if (ctx.content_buffer.items.len > 0) {
try writer.writeAll("\n\n");
}
}
if (ctx.content_buffer.items.len > 0) {
try writer.writeAll(ctx.content_buffer.items);
}
// Task-specific metadata (for GraphRAG)
if (ctx.metadata) |meta| {
try writer.writeAll("\n\n**Statistics:**\n");
if (meta.file_path) |path| {
try writer.print("- File: {s}\n", .{path});
}
if (meta.nodes_created > 0) {
try writer.print("- Nodes created: {d}\n", .{meta.nodes_created});
}
if (meta.edges_created > 0) {
try writer.print("- Edges created: {d}\n", .{meta.edges_created});
}
if (meta.embeddings_created > 0) {
try writer.print("- Embeddings: {d}\n", .{meta.embeddings_created});
}
}
// Footer
try writer.writeAll("\n\n─────────────────────────────────");
// Update message
const display_content = try final_content.toOwnedSlice(allocator);
msg.content = display_content;
msg.processed_content = try markdown.processMarkdown(allocator, display_content);
msg.thinking_content = null;
msg.processed_thinking_content = null;
// Set metadata for collapse/expand
msg.agent_analysis_completed = true; // Enable collapse button
msg.agent_analysis_expanded = false; // Auto-collapse to save space
msg.tool_execution_time = execution_time; // Store execution time for display
// Redraw screen to show finalized message
_ = try redrawScreen(ctx.app);
ctx.app.updateCursorToBottom();
}
/// Calculate message height using shared layout logic
/// This is now a simple wrapper around buildMessageLayout - no duplication!
fn calculateMessageHeight(app: *App, message: *Message) !usize {
var layout = try buildMessageLayout(app, message);
defer layout.deinit(app.allocator);
return layout.height;
}
/// Calculate deterministic hash of message content for change detection
/// Used by incremental rendering to detect if a message has changed
/// Only hashes fields that affect visual rendering
pub fn calculateMessageHash(message: *const Message) u64 {
var hasher = std.hash.Wyhash.init(0);
// Hash content (includes role via content structure)
hasher.update(message.content);
// Hash thinking content if present
if (message.thinking_content) |thinking| {
hasher.update(thinking);
}
// Hash tool call fields (affects tool result rendering)
if (message.tool_name) |tool_name| {
hasher.update(tool_name);
}
if (message.tool_success) |success| {
hasher.update(&[_]u8{if (success) 1 else 0});
}
if (message.tool_execution_time) |time| {
const time_bytes = std.mem.asBytes(&time);
hasher.update(time_bytes);
}
// Hash agent analysis name (affects agent section rendering)
if (message.agent_analysis_name) |name| {
hasher.update(name);
}
// Hash expansion states (affects what's rendered)
const expansion_bits: u8 =
(@as(u8, if (message.thinking_expanded) 1 else 0) << 0) |
(@as(u8, if (message.tool_call_expanded) 1 else 0) << 1) |
(@as(u8, if (message.agent_analysis_expanded) 1 else 0) << 2) |
(@as(u8, if (message.agent_analysis_completed) 1 else 0) << 3) |
(@as(u8, if (message.permission_request != null) 1 else 0) << 4);
hasher.update(&[_]u8{expansion_bits});
return hasher.final();
}
// Recursive markdown rendering function
pub fn renderItemsToLines(
app: *App,
items: *const std.ArrayListUnmanaged(markdown.RenderableItem),
output_lines: *std.ArrayListUnmanaged([]const u8),
indent_level: usize,
max_content_width: usize,
) !void {
const indent_str = " ";
for (items.items) |*item| {
switch (item.tag) {
.styled_text => {
var wrapped_lines = try render.wrapRawText(app.allocator, item.payload.styled_text, max_content_width - (indent_level * indent_str.len));
defer {
for (wrapped_lines.items) |l| app.allocator.free(l);
wrapped_lines.deinit(app.allocator);
}
for (wrapped_lines.items) |line| {
var full_line = std.ArrayListUnmanaged(u8){};
for (0..indent_level) |_| try full_line.appendSlice(app.allocator, indent_str);
try full_line.appendSlice(app.allocator, line);
try output_lines.append(app.allocator, try full_line.toOwnedSlice(app.allocator));
}
},
.blockquote => {
var sub_lines = std.ArrayListUnmanaged([]const u8){};
defer {
for (sub_lines.items) |l| app.allocator.free(l);
sub_lines.deinit(app.allocator);
}
// Pre-calculate the total width of the prefix the parent will add.
const prefix_width = (indent_level * indent_str.len) + 2;
// Use saturating subtraction to prevent underflow.
const sub_max_width = max_content_width -| prefix_width;
try renderItemsToLines(app, &item.payload.blockquote, &sub_lines, 0, sub_max_width);
for (sub_lines.items) |line| {
var full_line = std.ArrayListUnmanaged(u8){};
// The parent adds the full prefix to the un-indented child line.
for (0..indent_level) |_| try full_line.appendSlice(app.allocator, indent_str);
try full_line.appendSlice(app.allocator, "┃ ");
try full_line.appendSlice(app.allocator, line);
try output_lines.append(app.allocator, try full_line.toOwnedSlice(app.allocator));
}
},
.list => {
for (item.payload.list.items.items, 0..) |list_item_blocks, i| {
// --- START: New logic to calculate dynamic padding ---
var marker_buf: [16]u8 = undefined;
var marker_text: []const u8 = undefined;
if (item.payload.list.is_ordered) {
marker_text = try std.fmt.bufPrint(&marker_buf, "{d}. ", .{item.payload.list.start_number + i});
} else {
marker_text = "• ";
}
var alignment_padding_buf = std.ArrayListUnmanaged(u8){};
defer alignment_padding_buf.deinit(app.allocator);
for (0..ui.AnsiParser.getVisibleLength(marker_text)) |_| {
try alignment_padding_buf.append(app.allocator, ' ');
}
const alignment_padding = alignment_padding_buf.items;
// --- END: New logic ---
const prefix_width = (indent_level * indent_str.len) + alignment_padding.len;
const sub_max_width = max_content_width -| prefix_width;
var sub_lines = std.ArrayListUnmanaged([]const u8){};
defer {
for (sub_lines.items) |l| app.allocator.free(l);
sub_lines.deinit(app.allocator);
}
try renderItemsToLines(app, &list_item_blocks, &sub_lines, 0, sub_max_width);
for (sub_lines.items, 0..) |line, line_idx| {
var full_line = std.ArrayListUnmanaged(u8){};
for (0..indent_level) |_| try full_line.appendSlice(app.allocator, indent_str);
if (line_idx == 0) {
try full_line.appendSlice(app.allocator, marker_text);
} else {
// Use the new dynamic padding for alignment
try full_line.appendSlice(app.allocator, alignment_padding);
}
try full_line.appendSlice(app.allocator, line);
try output_lines.append(app.allocator, try full_line.toOwnedSlice(app.allocator));
}
}
},
.horizontal_rule => {
var hr_line = std.ArrayListUnmanaged(u8){};
for (0..indent_level) |_| try hr_line.appendSlice(app.allocator, indent_str);
for (0..(max_content_width / 2)) |_| try hr_line.appendSlice(app.allocator, "─");
try output_lines.append(app.allocator, try hr_line.toOwnedSlice(app.allocator));
},
.code_block => {
var box_lines = std.ArrayListUnmanaged([]const u8){};
defer {
box_lines.deinit(app.allocator);
}
var content_lines = try render.wrapRawText(app.allocator, item.payload.code_block.content, max_content_width - (indent_level * indent_str.len) - 4);
defer {
for(content_lines.items) |l| app.allocator.free(l);
content_lines.deinit(app.allocator);
}
var max_line_len : usize = 0;
for(content_lines.items) |l| {
const len = ui.AnsiParser.getVisibleLength(l);
if (len > max_line_len) max_line_len = len;
}
// Top border
var top_border = std.ArrayListUnmanaged(u8){};
for (0..indent_level) |_| try top_border.appendSlice(app.allocator,indent_str);
try top_border.appendSlice(app.allocator,"┌");
for(0..max_line_len+2) |_| try top_border.appendSlice(app.allocator,"─");
try top_border.appendSlice(app.allocator,"┐");
try box_lines.append(app.allocator, try top_border.toOwnedSlice(app.allocator));
// Content
for(content_lines.items) |l| {
var content_line = std.ArrayListUnmanaged(u8){};
for (0..indent_level) |_| try content_line.appendSlice(app.allocator,indent_str);
try content_line.appendSlice(app.allocator,"│ ");
try content_line.appendSlice(app.allocator,l);
const padding = max_line_len - ui.AnsiParser.getVisibleLength(l);
for(0..padding) |_| try content_line.appendSlice(app.allocator," ");
try content_line.appendSlice(app.allocator," │");
try box_lines.append(app.allocator, try content_line.toOwnedSlice(app.allocator));
}
// Bottom border
var bot_border = std.ArrayListUnmanaged(u8){};
for (0..indent_level) |_| try bot_border.appendSlice(app.allocator,indent_str);
try bot_border.appendSlice(app.allocator,"└");
for(0..max_line_len+2) |_| try bot_border.appendSlice(app.allocator,"─");
try bot_border.appendSlice(app.allocator,"┘");
try box_lines.append(app.allocator, try bot_border.toOwnedSlice(app.allocator));
try output_lines.appendSlice(app.allocator,box_lines.items);
},
.link => {
const link_text = item.payload.link.text;
const link_url = item.payload.link.url;
// Format: "Link Text" (URL) with underline styling
var formatted_text = std.ArrayListUnmanaged(u8){};
defer formatted_text.deinit(app.allocator);
try formatted_text.appendSlice(app.allocator,"\x1b[4m"); // Start underline
try formatted_text.appendSlice(app.allocator, app.config.color_link); // Link color from config
try formatted_text.appendSlice(app.allocator,link_text);
try formatted_text.appendSlice(app.allocator,"\x1b[0m"); // Reset
try formatted_text.appendSlice(app.allocator," (");
try formatted_text.appendSlice(app.allocator,link_url);
try formatted_text.appendSlice(app.allocator,")");
var wrapped_lines = try render.wrapRawText(app.allocator, formatted_text.items, max_content_width - (indent_level * indent_str.len));
defer {
for (wrapped_lines.items) |l| app.allocator.free(l);
wrapped_lines.deinit(app.allocator);
}
for (wrapped_lines.items) |line| {
var full_line = std.ArrayListUnmanaged(u8){};
for (0..indent_level) |_| try full_line.appendSlice(app.allocator, indent_str);
try full_line.appendSlice(app.allocator, line);
try output_lines.append(app.allocator, try full_line.toOwnedSlice(app.allocator));
}
},
.table => {
const table = item.payload.table;
const column_count = table.column_count;
// Calculate ideal column widths and natural minimums
var col_widths = try app.allocator.alloc(usize, column_count);
defer app.allocator.free(col_widths);
var col_natural_mins = try app.allocator.alloc(usize, column_count);
defer app.allocator.free(col_natural_mins);
// Initialize with absolute minimum
for (col_widths) |*w| w.* = 3;
for (col_natural_mins) |*m| m.* = 3;
// Check header widths and calculate natural minimums
for (table.headers, 0..) |header, i| {
const len = ui.AnsiParser.getVisibleLength(header);
if (len > col_widths[i]) col_widths[i] = len;
// Natural minimum is the header length (headers shouldn't wrap)
const longest_word = render.getLongestWordLength(header);
col_natural_mins[i] = @max(col_natural_mins[i], @max(longest_word, len));
}
// Check body cell widths and update natural minimums
for (table.rows, 0..) |cell_text, idx| {
const col_idx = idx % column_count;
const len = ui.AnsiParser.getVisibleLength(cell_text);
if (len > col_widths[col_idx]) col_widths[col_idx] = len;
// Update natural minimum based on longest word in this cell
const longest_word = render.getLongestWordLength(cell_text);
col_natural_mins[col_idx] = @max(col_natural_mins[col_idx], longest_word);
}
// Adjust if total width exceeds available
const indent_width = indent_level * indent_str.len;
const available_width = if (max_content_width > indent_width) max_content_width - indent_width else 0;
// Calculate total width needed: borders + padding + content
// Format: "│ content │ content │" = (column_count + 1) borders + column_count * 2 spaces + sum(widths)
var total_width: usize = column_count + 1; // borders
for (col_widths) |w| total_width += w + 2; // content + padding
// Intelligent width distribution
if (total_width > available_width) {
// Calculate minimum required width with natural minimums
var min_total_width: usize = column_count + 1; // borders
for (col_natural_mins) |m| min_total_width += m + 2; // content + padding
if (available_width >= min_total_width) {
// We can fit the table with natural minimums - distribute intelligently
// Step 1: Set all columns to their natural minimum
for (col_widths, 0..) |*w, i| {
w.* = col_natural_mins[i];
}
// Step 2: Distribute remaining space to columns proportionally
// but give more weight to columns that originally wanted more space
var current_total: usize = min_total_width;
const extra_space = available_width - min_total_width;
if (extra_space > 0) {
// Calculate total "demand" (how much extra each column wants)
var total_demand: usize = 0;
var demands = try app.allocator.alloc(usize, column_count);
defer app.allocator.free(demands);
for (col_widths, 0..) |ideal_width, i| {
// How much does this column want beyond its natural minimum?
const demand = if (ideal_width > col_natural_mins[i])
ideal_width - col_natural_mins[i]
else
0;
demands[i] = demand;
total_demand += demand;
}
// Distribute extra space proportionally to demand
if (total_demand > 0) {
for (col_widths, 0..) |*w, i| {
const extra = (extra_space * demands[i]) / total_demand;
w.* += extra;
}
} else {
// No demand - distribute evenly
const per_column = extra_space / column_count;
for (col_widths) |*w| {
w.* += per_column;
}
}
}
// Recalculate and fine-tune if needed
current_total = column_count + 1;
for (col_widths) |w| current_total += w + 2;
// Final adjustment: if still too wide, shrink widest columns
while (current_total > available_width) {
// Find column with most excess above its natural minimum
var max_excess: usize = 0;
var max_idx: usize = 0;
for (col_widths, 0..) |w, i| {
const excess = if (w > col_natural_mins[i]) w - col_natural_mins[i] else 0;
if (excess > max_excess) {
max_excess = excess;
max_idx = i;
}
}
if (max_excess == 0) break; // All at natural minimum
col_widths[max_idx] -= 1;
current_total -= 1;
}
} else {
// Terminal too narrow even for natural minimums - use absolute minimums
const absolute_min: usize = 3;
for (col_widths) |*w| w.* = absolute_min;
// Still try to be smart: give slightly more to label columns
var abs_min_total: usize = column_count + 1;
for (col_widths) |w| abs_min_total += w + 2;
if (abs_min_total <= available_width) {
const extra = available_width - abs_min_total;
// Give extra to narrowest columns first (likely labels)
for (0..extra) |_| {
var min_width: usize = 1000;
var min_idx: usize = 0;
for (col_natural_mins, 0..) |nat_min, i| {
if (nat_min < min_width) {
min_width = nat_min;
min_idx = i;
}
}
col_widths[min_idx] += 1;
}
}
}
}
// Top border
var top_border = std.ArrayListUnmanaged(u8){};
defer top_border.deinit(app.allocator);
for (0..indent_level) |_| try top_border.appendSlice(app.allocator, indent_str);
try top_border.appendSlice(app.allocator, "┌");
for (col_widths, 0..) |width, i| {
for (0..width + 2) |_| try top_border.appendSlice(app.allocator, "─");
if (i < column_count - 1) {
try top_border.appendSlice(app.allocator, "┬");
}
}
try top_border.appendSlice(app.allocator, "┐");
try output_lines.append(app.allocator, try top_border.toOwnedSlice(app.allocator));
// Header row
var header_line = std.ArrayListUnmanaged(u8){};
defer header_line.deinit(app.allocator);
for (0..indent_level) |_| try header_line.appendSlice(app.allocator, indent_str);
try header_line.appendSlice(app.allocator, "│");
for (table.headers, 0..) |header, i| {
try header_line.appendSlice(app.allocator, " ");
// Truncate header to fit column width
const truncated_header = try render.truncateTextToWidth(app.allocator, header, col_widths[i]);
defer app.allocator.free(truncated_header);
const content_len = ui.AnsiParser.getVisibleLength(truncated_header);
const padding = if (content_len >= col_widths[i]) 0 else col_widths[i] - content_len;
// Apply alignment
const alignment = table.alignments[i];
if (alignment == .center) {
const left_pad = padding / 2;
const right_pad = padding - left_pad;
for (0..left_pad) |_| try header_line.appendSlice(app.allocator, " ");
try header_line.appendSlice(app.allocator, truncated_header);
for (0..right_pad) |_| try header_line.appendSlice(app.allocator, " ");
} else if (alignment == .right) {
for (0..padding) |_| try header_line.appendSlice(app.allocator, " ");
try header_line.appendSlice(app.allocator, truncated_header);
} else { // left
try header_line.appendSlice(app.allocator, truncated_header);
for (0..padding) |_| try header_line.appendSlice(app.allocator, " ");
}
try header_line.appendSlice(app.allocator, " │");
}
try output_lines.append(app.allocator, try header_line.toOwnedSlice(app.allocator));
// Header separator
var separator = std.ArrayListUnmanaged(u8){};
defer separator.deinit(app.allocator);
for (0..indent_level) |_| try separator.appendSlice(app.allocator, indent_str);
try separator.appendSlice(app.allocator, "├");
for (col_widths, 0..) |width, i| {
for (0..width + 2) |_| try separator.appendSlice(app.allocator, "─");
if (i < column_count - 1) {
try separator.appendSlice(app.allocator, "┼");
}
}
try separator.appendSlice(app.allocator, "┤");
try output_lines.append(app.allocator, try separator.toOwnedSlice(app.allocator));
// Body rows - with multi-line cell support
const row_count = table.rows.len / column_count;
for (0..row_count) |row_idx| {
// Wrap all cells in this row
var wrapped_cells = try app.allocator.alloc(std.ArrayListUnmanaged([]const u8), column_count);
defer {
for (wrapped_cells) |*cell_lines| {
for (cell_lines.items) |line| app.allocator.free(line);
cell_lines.deinit(app.allocator);
}
app.allocator.free(wrapped_cells);
}
// Wrap each cell's text and find max line count
// Wrap to (col_width - 2) to leave room for continuation line indent
var max_lines: usize = 1;
for (0..column_count) |col_idx| {
const cell_idx = row_idx * column_count + col_idx;
const cell_text = table.rows[cell_idx];
// Reserve 2 chars for indent on continuation lines
const wrap_width = if (col_widths[col_idx] >= 2) col_widths[col_idx] - 2 else col_widths[col_idx];
wrapped_cells[col_idx] = try render.wrapRawText(app.allocator, cell_text, wrap_width);
if (wrapped_cells[col_idx].items.len > max_lines) {
max_lines = wrapped_cells[col_idx].items.len;
}
}
// Render each line of the row
for (0..max_lines) |line_idx| {
var row_line = std.ArrayListUnmanaged(u8){};
defer row_line.deinit(app.allocator);
for (0..indent_level) |_| try row_line.appendSlice(app.allocator, indent_str);
try row_line.appendSlice(app.allocator, "│");
for (0..column_count) |col_idx| {
try row_line.appendSlice(app.allocator, " ");
const cell_lines = wrapped_cells[col_idx].items;
const cell_content = if (line_idx < cell_lines.len) blk: {
// Add indentation for continuation lines (not the first line)
if (line_idx > 0) {
var indented = std.ArrayListUnmanaged(u8){};
try indented.appendSlice(app.allocator, " "); // 2-space indent
try indented.appendSlice(app.allocator, cell_lines[line_idx]);
break :blk try indented.toOwnedSlice(app.allocator);
} else {
break :blk try app.allocator.dupe(u8, cell_lines[line_idx]);
}
} else blk: {
break :blk try app.allocator.dupe(u8, "");
};
defer app.allocator.free(cell_content);
const content_len = ui.AnsiParser.getVisibleLength(cell_content);
const padding = if (content_len >= col_widths[col_idx]) 0 else col_widths[col_idx] - content_len;
const alignment = table.alignments[col_idx];
if (alignment == .center and line_idx == 0) { // Only center first line
const left_pad = padding / 2;
const right_pad = padding - left_pad;
for (0..left_pad) |_| try row_line.appendSlice(app.allocator, " ");
try row_line.appendSlice(app.allocator, cell_content);
for (0..right_pad) |_| try row_line.appendSlice(app.allocator, " ");
} else if (alignment == .right and line_idx == 0) { // Only right-align first line
for (0..padding) |_| try row_line.appendSlice(app.allocator, " ");
try row_line.appendSlice(app.allocator, cell_content);
} else { // left (or continuation lines)
try row_line.appendSlice(app.allocator, cell_content);
for (0..padding) |_| try row_line.appendSlice(app.allocator, " ");
}
try row_line.appendSlice(app.allocator, " │");
}
try output_lines.append(app.allocator, try row_line.toOwnedSlice(app.allocator));
}
}
// Bottom border
var bottom_border = std.ArrayListUnmanaged(u8){};
defer bottom_border.deinit(app.allocator);
for (0..indent_level) |_| try bottom_border.appendSlice(app.allocator, indent_str);
try bottom_border.appendSlice(app.allocator, "└");
for (col_widths, 0..) |width, i| {
for (0..width + 2) |_| try bottom_border.appendSlice(app.allocator, "─");
if (i < column_count - 1) {
try bottom_border.appendSlice(app.allocator, "┴");
}
}
try bottom_border.appendSlice(app.allocator, "┘");
try output_lines.append(app.allocator, try bottom_border.toOwnedSlice(app.allocator));
},
.blank_line => {
try output_lines.append(app.allocator, try app.allocator.dupe(u8, ""));
},
}
}
}
pub fn drawMessage(
app: *App,
writer: anytype,
message: *Message,
message_index: usize,
absolute_y: *usize,
input_field_height: usize,
) !void {
const left_padding = 2;
const y_start = absolute_y.*;
const max_content_width = if (app.terminal_size.width > left_padding + 4) app.terminal_size.width - left_padding - 4 else 0;
// Build unified list of all lines to render (thinking + content)
var all_lines = std.ArrayListUnmanaged([]const u8){};
defer {
for (all_lines.items) |line| app.allocator.free(line);
all_lines.deinit(app.allocator);
}
// Add thinking section if present
const has_thinking = message.thinking_content != null and message.processed_thinking_content != null;
if (has_thinking) {
if (message.thinking_expanded) {
// Expanded thinking: add header + thinking lines + separator
var thinking_header = std.ArrayListUnmanaged(u8){};
defer thinking_header.deinit(app.allocator);
try thinking_header.appendSlice(app.allocator, app.config.color_thinking_header);
try thinking_header.appendSlice(app.allocator, "Thinking\x1b[0m");
try all_lines.append(app.allocator, try thinking_header.toOwnedSlice(app.allocator));
var thinking_lines = std.ArrayListUnmanaged([]const u8){};
defer thinking_lines.deinit(app.allocator); // Only deinit the ArrayList, not the strings
if (message.processed_thinking_content) |*thinking_processed| {
try renderItemsToLines(app, thinking_processed, &thinking_lines, 0, max_content_width);
}
// Add thinking lines with dim styling (transfer ownership to all_lines)
for (thinking_lines.items) |line| {
var styled_line = std.ArrayListUnmanaged(u8){};
try styled_line.appendSlice(app.allocator, app.config.color_thinking_dim); // Dim from config
try styled_line.appendSlice(app.allocator, line);
try styled_line.appendSlice(app.allocator, "\x1b[0m"); // Reset
try all_lines.append(app.allocator, try styled_line.toOwnedSlice(app.allocator));
// Free the original line since we created a styled copy
app.allocator.free(line);
}
// Add separator
try all_lines.append(app.allocator, try app.allocator.dupe(u8, "SEPARATOR"));
} else {
// Collapsed thinking: just show header
try all_lines.append(app.allocator, try app.allocator.dupe(u8, "\x1b[2m💭 Thinking (Ctrl+O to expand)\x1b[0m"));
try all_lines.append(app.allocator, try app.allocator.dupe(u8, "SEPARATOR"));
}
}
// Add agent analysis section if present (for sub-agent thinking - file_curator, graphrag, etc.)
const has_agent_analysis = message.agent_analysis_name != null;
if (has_agent_analysis) {
if (message.agent_analysis_completed and !message.agent_analysis_expanded) {
// COLLAPSED: Show one-liner summary
const agent_time = message.tool_execution_time orelse 0;
var summary = std.ArrayListUnmanaged(u8){};
defer summary.deinit(app.allocator);
try summary.print(
app.allocator,
"\x1b[2m🤔 {s} Analysis (✅ completed, {d}ms) - Ctrl+O to expand\x1b[0m",
.{message.agent_analysis_name.?, agent_time}
);
try all_lines.append(app.allocator, try summary.toOwnedSlice(app.allocator));
try all_lines.append(app.allocator, try app.allocator.dupe(u8, "SEPARATOR"));
} else {
// EXPANDED or STREAMING: Show full content
// Add hint if completed (can be collapsed)
if (message.agent_analysis_completed) {
try all_lines.append(app.allocator, try app.allocator.dupe(u8, "\x1b[2m(Ctrl+O to collapse)\x1b[0m"));
}
// Render agent analysis content
var content_lines = std.ArrayListUnmanaged([]const u8){};
defer content_lines.deinit(app.allocator);
try renderItemsToLines(app, &message.processed_content, &content_lines, 0, max_content_width);
for (content_lines.items) |line| {
try all_lines.append(app.allocator, line);
}
try all_lines.append(app.allocator, try app.allocator.dupe(u8, "SEPARATOR"));
}
}
// Add tool call section if present (for system messages showing tool results)
const has_tool_call = message.tool_name != null;
if (has_tool_call) {
if (message.tool_call_expanded) {
// Expanded tool call: add header + tool output + separator
var tool_header = std.ArrayListUnmanaged(u8){};
defer tool_header.deinit(app.allocator);
try tool_header.appendSlice(app.allocator, app.config.color_thinking_header);
try tool_header.print(app.allocator, "Tool: {s}\x1b[0m", .{message.tool_name.?});
try all_lines.append(app.allocator, try tool_header.toOwnedSlice(app.allocator));
var tool_lines = std.ArrayListUnmanaged([]const u8){};
defer tool_lines.deinit(app.allocator);
try renderItemsToLines(app, &message.processed_content, &tool_lines, 0, max_content_width);
// Add tool lines with dim styling (transfer ownership to all_lines)
for (tool_lines.items) |line| {
var styled_line = std.ArrayListUnmanaged(u8){};
try styled_line.appendSlice(app.allocator, app.config.color_thinking_dim);
try styled_line.appendSlice(app.allocator, line);
try styled_line.appendSlice(app.allocator, "\x1b[0m");
try all_lines.append(app.allocator, try styled_line.toOwnedSlice(app.allocator));
app.allocator.free(line);
}
// Add separator