-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.cpp
More file actions
6574 lines (6145 loc) · 296 KB
/
Copy pathmain.cpp
File metadata and controls
6574 lines (6145 loc) · 296 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
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <cctype>
#include <algorithm>
#include <array>
#include <sstream>
#include <string_view>
#include <random>
#include <filesystem>
#include <optional>
#include <unordered_set>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <io.h>
#include <direct.h>
#include <imm.h>
#pragma comment(lib, "Imm32.lib")
#else
#include <termios.h>
#include <unistd.h>
#endif
#include <ftxui/component/component.hpp>
#include <ftxui/component/screen_interactive.hpp>
#include <ftxui/dom/elements.hpp>
#include <ftxui/screen/string.hpp>
#include <ftxui/screen/terminal.hpp>
#include "version.hpp"
#include "config/config.hpp"
#include "network/proxy_resolver.hpp"
#include "remote_control/remote_control_service.hpp"
#include "provider/provider_factory.hpp"
#include "provider/copilot_provider.hpp"
#include "provider/model_context_resolver.hpp"
#include "provider/model_pool_status.hpp"
#include "provider/models_dev_registry.hpp"
#include "provider/model_resolver.hpp"
#include "provider/cwd_model_override.hpp"
#include "provider/apply_model_to_session.hpp"
#include "tool/tool_executor.hpp"
#include "tool/bash_tool.hpp"
#include "tool/builtin_tool_registry.hpp"
#include "tool/file_read_tool.hpp"
#include "tool/file_write_tool.hpp"
#include "tool/file_edit_tool.hpp"
#include "tool/grep_tool.hpp"
#include "tool/glob_tool.hpp"
#include "tool/task_complete_tool.hpp"
#include "tool/goal_tool.hpp"
#include "tool/mcp_manager.hpp"
#include "tool/mcp_startup_coordination.hpp"
#include "tool/skills_tool.hpp"
#include "tool/skill_view_tool.hpp"
#include "tool/memory_read_tool.hpp"
#include "tool/memory_write_tool.hpp"
#include "tool/ask_user_question_tool.hpp"
#include "tool/ask_overlay_input.hpp"
#include "tool/ace_browser_bridge/browser_tools.hpp"
#include "tui/confirm_question.hpp"
#include "skills/skill_init.hpp"
#include "skills/skill_registry.hpp"
#include "skills/skill_commands.hpp"
#include "skills/default_skill_seeder.hpp"
#include "hooks/hook_config.hpp"
#include "hooks/hook_manager.hpp"
#include "hooks/hook_payload.hpp"
#include "memory/memory_paths.hpp"
#include "memory/memory_registry.hpp"
#include "tool/web_search/runtime.hpp"
#include "tool/web_search/backend_router.hpp"
#include "tool/web_search/region_detector.hpp"
#include "tool/web_search/web_search_tool.hpp"
#include "utils/logger.hpp"
#include "permissions.hpp"
#include "agent_loop.hpp"
#include "commands/configure.hpp"
#include "daemon/cli.hpp"
#ifdef _WIN32
# include "daemon/service_win.hpp"
#endif
#include "upgrade/apply.hpp"
#include "upgrade/check.hpp"
#include "upgrade/manifest.hpp"
#include "upgrade/upgrade.hpp"
#include "commands/command_registry.hpp"
#include "commands/builtin_commands.hpp"
#include "commands/compact.hpp"
#include "commands/resume_state_sync.hpp"
#include "utils/token_tracker.hpp"
#include "markdown/markdown_formatter.hpp"
#include "session/session_manager.hpp"
#include "session/session_registry.hpp"
#include "session/session_resume_restore.hpp"
#include "tui/chat_scroll.hpp"
#include "tui/chat_render_window.hpp"
#include "tui/diff_view.hpp"
#include "tui/unclipped_reflect.hpp"
#include "tui/paste_handler.hpp"
#include "tui/ask_question_overlay.hpp"
#include "tui/picker_scroll.hpp"
#include "tui/render_mode_factory.hpp"
#include "utils/terminal_capability.hpp"
#include "utils/state_file.hpp"
#include "tui/slash_dropdown.hpp"
#include "tui/text_truncation.hpp"
#include "tui/thick_vscroll_bar.hpp"
#include "tui/non_selectable.hpp"
#include "tui/tool_progress.hpp"
#include "tui/theme_palette.hpp"
#include "utils/terminal_theme_detect.hpp"
#include "tui/sidebar_model.hpp"
#include "tui/todo_checklist_view.hpp"
#include "tui/input_history_navigation.hpp"
#include "tui/ctrl_c_exit.hpp"
#include "utils/base64.hpp"
#include "utils/clipboard.hpp"
#include "utils/drag_scroll.hpp"
#include "utils/terminal_title.hpp"
#include "session/attachment_store.hpp"
#include "session/session_storage.hpp"
#include "history/input_history_store.hpp"
#include "desktop/workspace_registry.hpp"
#include <cstdio>
using namespace ftxui;
using namespace acecode;
namespace {
static const std::string EN_THINKING_PHRASES[50] = {
"Analyzing", "Pondering", "Investigating", "Synthesizing", "Reviewing",
"Processing", "Compiling", "Evaluating", "Formulating", "Brainstorming",
"Searching", "Deciphering", "Gathering", "Debugging", "Inspecting",
"Generating", "Organizing", "Mapping", "Exploring", "Tracing",
"Validating", "Considering", "Reflecting", "Simulating", "Calculating",
"Abstracting", "Diving", "Looking", "Troubleshooting", "Crafting",
"Polishing", "Assembling", "Connecting", "Building", "Parsing",
"Extracting", "Tuning", "Optimizing", "Designing", "Theorizing",
"Hypothesizing", "Seeking", "Interpreting", "Measuring", "Weighing",
"Reading", "Preparing", "Reasoning", "Constructing", "Finalizing"
};
static const std::string ZH_THINKING_PHRASES[50] = {
"分析中", "思考中", "研究中", "探索中", "综合中",
"审查中", "处理中", "编译中", "评估中", "规划中",
"构思中", "搜索中", "解码中", "收集中", "调试中",
"检查中", "生成中", "组织中", "映射中", "推理中",
"验证中", "考虑中", "反思中", "模拟中", "计算中",
"抽象中", "深挖中", "寻找中", "排查中", "打磨中",
"完善中", "组装中", "连接中", "构建中", "解析中",
"提取中", "微调中", "优化中", "设计中", "推论中",
"假设中", "路线中", "解读中", "测量中", "权衡中",
"阅读中", "准备中", "追溯中", "构造中", "总结中"
};
static bool is_user_chinese(const acecode::TuiState& state) {
if (state.conversation.empty()) return false;
for (auto it = state.conversation.rbegin(); it != state.conversation.rend(); ++it) {
if (it->role == "user") {
for (unsigned char c : it->content) {
if (c >= 0xE0) return true;
}
return false;
}
}
return false;
}
static std::string get_random_thinking_phrase(bool is_zh) {
static thread_local std::random_device rd;
static thread_local std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 49);
return is_zh ? ZH_THINKING_PHRASES[dis(gen)] : EN_THINKING_PHRASES[dis(gen)];
}
// A ToolSummary whose metrics contain `exit`, `aborted`, or `timeout` indicates
// a failure; used by the tool_result renderer to pick colour and decide whether
// to show the inline error tail.
static bool is_success_summary(const acecode::ToolSummary& s) {
for (const auto& kv : s.metrics) {
if (kv.first == "exit" && kv.second != "0") return false;
if (kv.first == "aborted" && kv.second == "true") return false;
if (kv.first == "timeout" && kv.second == "true") return false;
}
return true;
}
static std::string renderable_tool_summary_line(const acecode::ToolSummary& s,
const std::string& metric_str,
int max_visual_width) {
const std::string prefix = s.icon + " " + s.verb + " \xC2\xB7 ";
const std::string suffix = metric_str.empty()
? std::string()
: " \xC2\xB7 " + metric_str;
return acecode::tui::truncate_middle_segment(
prefix, s.object, suffix, max_visual_width);
}
static std::string collapse_sidebar_title_whitespace(std::string_view text) {
std::string out;
bool in_space = false;
for (unsigned char c : text) {
if (std::isspace(c)) {
if (!out.empty() && !in_space) {
out.push_back(' ');
}
in_space = true;
} else {
out.push_back(static_cast<char>(c));
in_space = false;
}
}
if (!out.empty() && out.back() == ' ') {
out.pop_back();
}
return out;
}
static std::string first_user_message_title(const acecode::TuiState& state) {
std::string explicit_title =
collapse_sidebar_title_whitespace(state.current_session_title);
if (!explicit_title.empty()) return explicit_title;
for (const auto& msg : state.conversation) {
if (msg.role == "user") {
std::string title = collapse_sidebar_title_whitespace(msg.content);
if (!title.empty()) {
return title;
}
}
}
return std::string("New session");
}
static void trim_ascii_space_suffix(std::string& text) {
while (!text.empty() && text.back() == ' ') {
text.pop_back();
}
}
static std::string truncate_cells_prefix(std::string_view text, int max_cells) {
if (max_cells <= 0) {
return {};
}
std::string out;
int used = 0;
for (const auto& glyph : ftxui::Utf8ToGlyphs(std::string(text))) {
if (glyph.empty()) {
continue;
}
const int width = std::max(0, ftxui::string_width(glyph));
if (used + width > max_cells) {
break;
}
out += glyph;
used += width;
}
return out;
}
static std::string truncate_cells_middle_ascii(std::string_view text, int max_cells) {
if (max_cells <= 0) {
return {};
}
const std::string input(text);
if (ftxui::string_width(input) <= max_cells) {
return input;
}
if (max_cells <= 3) {
return truncate_cells_prefix(input, max_cells);
}
const int body_cells = max_cells - 3;
const int head_cells = std::max(1, body_cells / 2);
const int tail_cells = std::max(0, body_cells - head_cells);
const auto glyphs = ftxui::Utf8ToGlyphs(input);
std::string head;
int used_head = 0;
for (const auto& glyph : glyphs) {
const int width = std::max(0, ftxui::string_width(glyph));
if (used_head + width > head_cells) {
break;
}
head += glyph;
used_head += width;
}
std::vector<std::string> tail_glyphs;
int used_tail = 0;
for (std::size_t i = glyphs.size(); i > 0; --i) {
const auto& glyph = glyphs[i - 1];
const int width = std::max(0, ftxui::string_width(glyph));
if (used_tail + width > tail_cells) {
break;
}
tail_glyphs.push_back(glyph);
used_tail += width;
}
std::reverse(tail_glyphs.begin(), tail_glyphs.end());
std::string out = head + "...";
for (const auto& glyph : tail_glyphs) {
out += glyph;
}
return out;
}
static Element sidebar_section_header(const std::string& label, int count) {
return hbox({
text(label) | color(tui::theme().ui.text_muted) | dim,
text(" " + std::to_string(count)) | color(tui::theme().ui.text_dim) | dim,
});
}
static std::string sidebar_change_stats_text(
const acecode::tui::SidebarFileChange& change) {
std::string out;
if (change.additions > 0) {
out += "+" + std::to_string(change.additions);
}
if (change.deletions > 0) {
if (!out.empty()) {
out += " ";
}
out += "-" + std::to_string(change.deletions);
}
return out.empty() ? std::string("0") : out;
}
static Element render_sidebar_change_row(
const acecode::tui::SidebarFileChange& change,
int content_width) {
const std::string stats_text = sidebar_change_stats_text(change);
const int file_width =
std::max(1, content_width - 2 - static_cast<int>(stats_text.size()) - 1);
Elements stats_parts;
if (change.additions > 0) {
stats_parts.push_back(
text("+" + std::to_string(change.additions)) |
color(tui::theme().semantic.success));
}
if (change.deletions > 0) {
if (!stats_parts.empty()) {
stats_parts.push_back(text(" "));
}
stats_parts.push_back(
text("-" + std::to_string(change.deletions)) |
color(tui::theme().semantic.error));
}
if (stats_parts.empty()) {
stats_parts.push_back(text("0") | color(tui::theme().ui.text_dim) | dim);
}
return hbox({
text(" ") | color(tui::theme().ui.text_dim),
text(truncate_cells_middle_ascii(
change.display_file.empty() ? change.file : change.display_file,
file_width)) |
color(tui::theme().ui.text_muted),
filler(),
hbox(std::move(stats_parts)),
});
}
static std::string mcp_state_label(McpServerState state) {
switch (state) {
case McpServerState::Starting: return "starting";
case McpServerState::Connected: return "connected";
case McpServerState::Disabled: return "disabled";
case McpServerState::Failed: return "failed";
case McpServerState::Cancelled: return "cancelled";
case McpServerState::TimedOut: return "timed_out";
}
return "unknown";
}
static Color mcp_sidebar_state_color(const std::string& state) {
if (state == "connected") return tui::theme().semantic.success;
if (state == "starting") return Color::White;
if (state == "failed" || state == "timed_out") return tui::theme().semantic.error;
if (state == "cancelled") return tui::theme().semantic.warning;
return tui::theme().ui.text_dim;
}
static bool mcp_sidebar_has_loading(
const std::vector<acecode::TuiState::McpSidebarServer>& servers) {
for (const auto& server : servers) {
if (server.state == "starting") return true;
}
return false;
}
static bool mcp_sidebar_has_loading(const acecode::TuiState& state) {
return mcp_sidebar_has_loading(state.mcp_sidebar_servers);
}
static Element render_white_shimmer_text(const std::string& label,
int anim_tick,
bool with_dots = true) {
std::vector<std::string> glyphs = ftxui::Utf8ToGlyphs(label);
const int total = static_cast<int>(glyphs.size());
const int wave_pos = std::max(0, anim_tick) % (total > 0 ? total + 2 : 8);
Elements parts;
for (int i = 0; i < total; ++i) {
int dist = i - wave_pos;
if (dist < 0) dist = -dist;
Color c;
if (dist == 0) {
c = Color::White;
} else if (dist == 1) {
c = Color::GrayLight;
} else if (dist == 2) {
c = Color::GrayDark;
} else {
c = tui::theme().ui.text_dim;
}
parts.push_back(text(glyphs[static_cast<std::size_t>(i)]) | color(c));
}
if (with_dots) {
const int dot_count = (std::max(0, anim_tick) % 3) + 1;
for (int i = 0; i < 3; ++i) {
parts.push_back(
text(".") |
color(i < dot_count ? Color::White : tui::theme().ui.text_dim));
}
}
return hbox(std::move(parts));
}
static std::string format_tool_count(size_t tool_count) {
return std::to_string(tool_count) + (tool_count == 1 ? " tool" : " tools");
}
static std::string uppercase_ascii(std::string text) {
for (char& c : text) {
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
}
return text;
}
static std::vector<acecode::TuiState::McpSidebarServer>
build_mcp_sidebar_servers(const McpManager& manager) {
auto server_infos = manager.list_servers();
std::vector<acecode::TuiState::McpSidebarServer> out;
out.reserve(server_infos.size());
for (const auto& info : server_infos) {
acecode::TuiState::McpSidebarServer server;
server.name = info.name;
server.state = mcp_state_label(info.state);
server.transport = info.transport;
server.error = info.error;
server.tool_count = info.tool_count;
out.push_back(std::move(server));
}
return out;
}
static void set_mcp_sidebar_servers_locked(
acecode::TuiState& state,
std::vector<acecode::TuiState::McpSidebarServer> servers) {
state.mcp_sidebar_servers = std::move(servers);
}
static Element render_mcp_sidebar_section(
const std::vector<acecode::TuiState::McpSidebarServer>& servers,
int content_width,
int anim_tick) {
if (servers.empty()) {
return emptyElement();
}
Elements rows;
rows.push_back(text("MCP") | bold | color(tui::theme().ui.text_primary));
constexpr std::size_t kMaxServers = 8;
std::size_t shown_servers = 0;
for (const auto& server : servers) {
if (shown_servers >= kMaxServers) {
break;
}
++shown_servers;
const Color state_color = mcp_sidebar_state_color(server.state);
const bool server_loading = server.state == "starting";
const bool server_connected = server.state == "connected";
const bool server_failed =
server.state == "failed" || server.state == "timed_out";
const std::string bullet = "\xE2\x80\xA2"; // bullet
Element status;
if (server_loading) {
status = render_white_shimmer_text("Loading", anim_tick);
} else if (server_connected) {
status = text("Connected (" + format_tool_count(server.tool_count) + ")") |
color(tui::theme().ui.text_muted);
} else if (server_failed && !server.error.empty()) {
status = hbox({
text(uppercase_ascii(server.transport) + " error: ") |
color(tui::theme().semantic.error),
paragraph(server.error) |
color(tui::theme().ui.text_muted) | dim | flex,
});
} else {
status = text(server.state) | color(state_color) | dim;
}
const int name_width = std::max(1, content_width / 2);
rows.push_back(hbox({
text(" " + bullet + " ") | color(state_color),
text(truncate_cells_middle_ascii(server.name, name_width)) |
bold | color(tui::theme().ui.text_primary),
text(" "),
status | flex,
}));
}
if (servers.size() > shown_servers) {
rows.push_back(
text(" +" + std::to_string(servers.size() - shown_servers) +
" more servers") |
color(tui::theme().ui.text_dim) | dim);
}
return vbox(std::move(rows));
}
static Element queued_badge() {
return text(" QUEUED ") | bold | color(tui::theme().ui.text_primary) |
bgcolor(tui::theme().ui.queued_bg);
}
static std::string repeat_utf8_glyph(const char* glyph, int count) {
std::string out;
if (count <= 0) {
return out;
}
const std::string g(glyph);
out.reserve(g.size() * static_cast<std::size_t>(count));
for (int i = 0; i < count; ++i) {
out += g;
}
return out;
}
static Color token_progress_color(int percent) {
const auto& s = tui::theme().semantic;
if (percent <= 0) return tui::theme().ui.text_dim;
if (percent > 90) return s.error;
if (percent >= 60) return s.warning;
return s.success;
}
// 当前活动模型的 PUB 池负载百分比(-1 = 未知/非 PUB,不渲染)。由 model-pool 监控
// 的后台轮询回调写入(atomic,UI 线程 render 读),配套 PostEvent 触发重绘。
static std::atomic<int> g_model_load_percent{-1};
// 模型池负载色阶(与 web / 后端 model_load_tier 一致):<70 绿 / 70..90 黄 / >90 红。
static Color model_load_color(int percent) {
const auto& s = tui::theme().semantic;
if (percent < 0) return tui::theme().ui.text_dim;
if (percent > 90) return s.error;
if (percent >= 70) return s.warning;
return s.success;
}
// 底部状态栏的模型池负载 chip:递增信号格 + 百分比,按负载档染色。负载未知
// (g_model_load_percent < 0,即非 PUB 模型或监控无数据)时不渲染。
static Element render_model_load_chip() {
const int percent = g_model_load_percent.load();
if (percent < 0) return text("");
const Color c = model_load_color(percent);
return hbox({
text("\xE2\x96\x81\xE2\x96\x83\xE2\x96\x85\xE2\x96\x87") | color(c), // ▁▃▅▇ 递增信号格
text(" " + std::to_string(percent) + "% ") | color(c),
});
}
static Color status_line_color(const std::string& status_line) {
return status_line.find("(deleted)") != std::string::npos
? tui::theme().semantic.error
: tui::theme().ui.text_primary;
}
static Element render_token_usage_chip(const acecode::TuiState& state) {
if (state.token_status.empty()) {
return text("");
}
constexpr int kBarCells = 10;
constexpr const char* kFilled = "\xE2\x96\x88";
constexpr const char* kEmpty = "\xE2\x96\x91";
const int percent = std::clamp(state.token_percent, 0, 100);
const int filled = percent <= 0 ? 0 : std::clamp((percent + 9) / 10, 1, kBarCells);
const int empty = kBarCells - filled;
const Color progress_color = token_progress_color(percent);
return hbox({
text(" " + state.token_status + " ") | dim | color(tui::theme().ui.accent_alt),
text("[") | dim | color(tui::theme().ui.text_dim),
text(repeat_utf8_glyph(kFilled, filled)) | color(progress_color),
text(repeat_utf8_glyph(kEmpty, empty)) | dim | color(tui::theme().ui.text_dim),
text("] ") | dim | color(tui::theme().ui.text_dim),
text(std::to_string(percent) + "% ") | dim | color(progress_color),
});
}
static Element render_pending_queue_block(const acecode::TuiState& state,
int available_width) {
if (state.pending_queue.empty()) {
return emptyElement();
}
constexpr std::size_t kMaxVisibleQueuedPrompts = 3;
constexpr int kBadgeCells = 8;
const int prompt_width =
std::max(10, available_width - kBadgeCells - 5);
const std::size_t visible =
std::min(kMaxVisibleQueuedPrompts, state.pending_queue.size());
Elements rows;
const std::size_t hidden =
state.pending_queue.size() > visible
? state.pending_queue.size() - visible
: 0;
if (hidden > 0) {
rows.push_back(
text(" +" + std::to_string(hidden) + " more queued") |
color(tui::theme().ui.text_dim) | dim);
}
const std::size_t start = state.pending_queue.size() - visible;
for (std::size_t i = start; i < state.pending_queue.size(); ++i) {
const std::string preview = collapse_sidebar_title_whitespace(
state.pending_queue[i]);
rows.push_back(hbox({
text(" "),
queued_badge(),
text(" "),
text(truncate_cells_middle_ascii(preview, prompt_width)) |
color(tui::theme().ui.text_primary),
}));
}
return vbox(std::move(rows));
}
static Element render_pending_attachment_block(const acecode::TuiState& state,
int available_width) {
if (state.pending_attachments.empty()) {
return emptyElement();
}
Elements rows;
const int label_width = std::max(12, available_width - 18);
for (const auto& attachment : state.pending_attachments) {
const std::string kind = attachment.value("kind", std::string{"file"});
const std::string name = attachment.value("name", std::string{"attachment"});
const std::string prefix = kind == "image" ? " image " : " file ";
rows.push_back(hbox({
text(" "),
text(prefix) | bold | color(tui::theme().ui.badge_fg) | bgcolor(tui::theme().ui.badge_bg),
text(" "),
text(truncate_cells_middle_ascii(name, label_width)) |
color(tui::theme().ui.text_primary),
}));
}
return vbox(std::move(rows));
}
static std::vector<std::string> sidebar_title_lines(const std::string& title,
int max_width) {
max_width = std::max(1, max_width);
const auto glyphs = ftxui::Utf8ToGlyphs(title);
std::vector<std::string> lines;
std::size_t index = 0;
for (int line_index = 0; line_index < 2 && index < glyphs.size(); ++line_index) {
std::string line;
int width = 0;
while (index < glyphs.size()) {
const auto& glyph = glyphs[index];
const int glyph_width = std::max(0, ftxui::string_width(glyph));
if (width > 0 && width + glyph_width > max_width) {
break;
}
if (width == 0 && glyph_width > max_width) {
line += glyph;
++index;
break;
}
line += glyph;
width += glyph_width;
++index;
}
trim_ascii_space_suffix(line);
lines.push_back(std::move(line));
while (index < glyphs.size() && glyphs[index] == " ") {
++index;
}
}
if (lines.empty()) {
lines.push_back("New session");
}
if (index < glyphs.size()) {
if (lines.size() == 1) {
lines.push_back("");
}
const int body_width = std::max(0, max_width - 3);
lines[1] = truncate_cells_prefix(lines[1], body_width);
trim_ascii_space_suffix(lines[1]);
lines[1] += "...";
}
return lines;
}
static Element render_regular_sidebar(const acecode::TuiState& state,
const std::string& version_str,
const std::string& cwd_display,
int sidebar_width,
int anim_tick) {
const int content_width = std::max(1, sidebar_width - 2);
Elements top_rows;
for (const auto& line : sidebar_title_lines(first_user_message_title(state),
content_width)) {
top_rows.push_back(text(line) | bold | color(tui::theme().ui.text_primary));
}
Element mcp_section = render_mcp_sidebar_section(
state.mcp_sidebar_servers, content_width, anim_tick);
if (!state.mcp_sidebar_servers.empty()) {
top_rows.push_back(text(""));
top_rows.push_back(std::move(mcp_section));
}
const auto file_changes =
acecode::tui::collect_sidebar_file_changes(state.conversation,
cwd_display);
top_rows.push_back(text(""));
top_rows.push_back(sidebar_section_header(
"Files Changed", static_cast<int>(file_changes.size())));
constexpr std::size_t kMaxSidebarFiles = 10;
const std::size_t shown_files =
std::min(kMaxSidebarFiles, file_changes.size());
for (std::size_t i = 0; i < shown_files; ++i) {
top_rows.push_back(
render_sidebar_change_row(file_changes[i], content_width));
}
if (file_changes.size() > shown_files) {
top_rows.push_back(
text(" +" + std::to_string(file_changes.size() - shown_files) +
" more") |
color(tui::theme().ui.text_dim) | dim);
}
Elements bottom_rows;
if (!state.todos.empty()) {
bottom_rows.push_back(
acecode::tui::render_todo_checklist_block(state.todos,
content_width));
bottom_rows.push_back(text(""));
}
const bool show_bash_task =
state.tool_running && state.tool_progress.tool_name == "bash";
if (show_bash_task) {
bottom_rows.push_back(sidebar_section_header("Background Tasks", 1));
std::string command = state.tool_progress.command_preview.empty()
? std::string("bash")
: state.tool_progress.command_preview;
bottom_rows.push_back(
text(" " + truncate_cells_middle_ascii(command,
std::max(1, content_width - 2))) |
color(tui::theme().ui.text_muted));
bottom_rows.push_back(text(""));
}
bottom_rows.push_back(paragraph(version_str) | color(tui::theme().ui.text_muted) | dim);
if (!state.update_notice.empty()) {
bottom_rows.push_back(paragraph(state.update_notice) |
color(tui::theme().semantic.warning));
}
if (!state.status_line.empty()) {
bottom_rows.push_back(paragraph(state.status_line) |
color(status_line_color(state.status_line)));
}
if (!cwd_display.empty()) {
bottom_rows.push_back(paragraph(cwd_display) | color(tui::theme().ui.accent_alt) | dim);
}
const bool is_light = tui::theme().name == "light";
Element sidebar = hbox({
text(" "),
vbox({
vbox(std::move(top_rows)),
filler(),
vbox(std::move(bottom_rows)),
}) | flex,
text(" "),
}) | size(WIDTH, EQUAL, sidebar_width) |
bgcolor(is_light ? Color::RGB(240, 240, 242) : Color::RGB(18, 18, 20));
return acecode::tui::non_selectable(std::move(sidebar));
}
static Element render_tool_result_lines_preserving_breaks(
const std::string& display_content) {
Elements lines;
size_t pos = 0;
while (pos <= display_content.size()) {
const size_t nl = display_content.find('\n', pos);
const std::string line = (nl == std::string::npos)
? display_content.substr(pos)
: display_content.substr(pos, nl - pos);
Element line_el = line.empty() ? text(" ") : paragraph(line);
lines.push_back(line_el | color(tui::theme().ui.text_muted) | dim);
if (nl == std::string::npos) break;
pos = nl + 1;
}
return vbox(std::move(lines));
}
bool is_space_glyph(const std::string& glyph) {
return glyph == " " || glyph == "\t";
}
bool is_narrow_glyph(const std::string& glyph) {
return ftxui::string_width(glyph) == 1;
}
bool is_opening_cjk_punctuation(const std::string& glyph) {
static constexpr std::array<std::string_view, 8> kOpening = {
"(", "《", "「", "【", "‘", "“", "〈", "『"
};
for (const auto& candidate : kOpening) {
if (glyph == candidate) {
return true;
}
}
return false;
}
bool is_closing_cjk_punctuation(const std::string& glyph) {
static constexpr std::array<std::string_view, 15> kClosing = {
",", "。", "!", "?", ";", ":", "、", ")",
"》", "」", "】", "’", "”", "〉", "』"
};
for (const auto& candidate : kClosing) {
if (glyph == candidate) {
return true;
}
}
return false;
}
void flush_ascii_run(std::string* ascii_run,
std::string* pending_prefix,
std::vector<std::string>* output) {
if (ascii_run->empty()) {
return;
}
std::string token = std::move(*ascii_run);
ascii_run->clear();
if (!pending_prefix->empty()) {
token = std::move(*pending_prefix) + token;
pending_prefix->clear();
}
output->push_back(std::move(token));
}
std::vector<std::string> tokenize_wrapped_input(const std::string& text) {
std::vector<std::string> tokens;
std::string ascii_run;
std::string pending_prefix;
for (const auto& glyph : ftxui::Utf8ToGlyphs(text)) {
if (glyph.empty()) {
continue;
}
if (is_space_glyph(glyph)) {
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
if (!tokens.empty()) {
tokens.back() += " ";
}
continue;
}
if (is_opening_cjk_punctuation(glyph)) {
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
pending_prefix += glyph;
continue;
}
if (is_closing_cjk_punctuation(glyph)) {
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
if (!tokens.empty()) {
tokens.back() += glyph;
} else if (!pending_prefix.empty()) {
pending_prefix += glyph;
} else {
tokens.push_back(glyph);
}
continue;
}
if (is_narrow_glyph(glyph)) {
ascii_run += glyph;
continue;
}
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
std::string token = glyph;
if (!pending_prefix.empty()) {
token = std::move(pending_prefix) + token;
pending_prefix.clear();
}
tokens.push_back(std::move(token));
}
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
if (!pending_prefix.empty()) {
if (!tokens.empty()) {
tokens.back() += pending_prefix;
} else {
tokens.push_back(std::move(pending_prefix));
}
}
return tokens;
}
Element render_wrapped_input_text(const std::string& input_value, size_t cursor_bytes) {
if (cursor_bytes > input_value.size()) cursor_bytes = input_value.size();
// Split input into head/cursor_glyph/tail so the caret block can be drawn
// over the glyph under the caret (or a space when the caret sits at end).
std::string head = input_value.substr(0, cursor_bytes);
std::string cursor_glyph;
std::string tail;
if (cursor_bytes < input_value.size()) {
size_t next = cursor_bytes + 1;
while (next < input_value.size() &&
(static_cast<unsigned char>(input_value[next]) & 0xC0) == 0x80) {
next++;
}
cursor_glyph = input_value.substr(cursor_bytes, next - cursor_bytes);
tail = input_value.substr(next);
}
auto tokens_head = tokenize_wrapped_input(head);
auto tokens_tail = tokenize_wrapped_input(tail);
auto cursor_elem = ftxui::text(cursor_glyph.empty() ? std::string(" ") : cursor_glyph)
| focusCursorBlock;
if (tokens_head.empty() && tokens_tail.empty()) {
return cursor_elem;
}
Elements parts;
parts.reserve(tokens_head.size() + tokens_tail.size() + 1);
// Emit all but the last head token as standalone flex items.
for (size_t i = 0; i + 1 < tokens_head.size(); ++i) {
parts.push_back(ftxui::text(std::move(tokens_head[i])));
}
// Fuse (last_head_token, cursor_elem, first_tail_token) into one hbox so
// the caret never lands at a natural wrap boundary.
Elements compound;
if (!tokens_head.empty()) {
compound.push_back(ftxui::text(std::move(tokens_head.back())));
}
compound.push_back(cursor_elem);
size_t tail_start = 0;
if (!tokens_tail.empty()) {
compound.push_back(ftxui::text(std::move(tokens_tail[0])));
tail_start = 1;
}
parts.push_back(hbox(std::move(compound)));