-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver_helpers.cpp
More file actions
2393 lines (2199 loc) · 96 KB
/
Copy pathserver_helpers.cpp
File metadata and controls
2393 lines (2199 loc) · 96 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
// server_helpers.cpp — Shared helper method definitions for WebServer::Impl.
// This file contains auth/CORS, workspace, session serialization, attention,
// session draft/title/todo, and session-options helpers that are used by
// multiple route TUs.
#include "server_impl.hpp"
#include "remote_control_session_event.hpp"
#include "session_status_routing.hpp"
#include "../config/saved_models_revision.hpp"
#include "../prompt/context_usage_breakdown.hpp"
#include "../session/session_user_message_search.hpp"
#include "../utils/encoding.hpp"
namespace acecode::web {
using nlohmann::json;
// =====================================================================
// Free functions (formerly anonymous-namespace, now shared across route TUs)
// =====================================================================
std::uint64_t parse_seq(const std::string& s) {
if (s.empty()) return 0;
try { return std::stoull(s); } catch (...) { return 0; }
}
std::string trim_trailing_slash(std::string value) {
while (!value.empty() && value.back() == '/') value.pop_back();
return value;
}
std::optional<std::string> preview_blob_mime(const std::string& path) {
auto dot = path.find_last_of('.');
if (dot == std::string::npos || dot + 1 >= path.size()) return std::nullopt;
std::string ext = path.substr(dot + 1);
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
if (ext == "png") return "image/png";
if (ext == "jpg" || ext == "jpeg") return "image/jpeg";
if (ext == "gif") return "image/gif";
if (ext == "webp") return "image/webp";
if (ext == "bmp") return "image/bmp";
if (ext == "ico") return "image/x-icon";
if (ext == "svg") return "image/svg+xml";
if (ext == "pdf") return "application/pdf";
if (ext == "docx") return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
if (ext == "xlsx") return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (ext == "xlsm") return "application/vnd.ms-excel.sheet.macroEnabled.12";
if (ext == "pptx") return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
return std::nullopt;
}
std::int64_t now_unix_ms() {
using namespace std::chrono;
return duration_cast<milliseconds>(
system_clock::now().time_since_epoch()).count();
}
bool cwd_is_directory(const std::string& cwd) {
if (cwd.empty()) return false;
std::error_code ec;
#ifdef _WIN32
return std::filesystem::is_directory(std::filesystem::u8path(cwd), ec) && !ec;
#else
return std::filesystem::is_directory(cwd, ec) && !ec;
#endif
}
json chat_message_to_json(const ChatMessage& m) {
return chat_message_to_payload_json(m);
}
json ui_preferences_to_json(const WebUiPreferencesConfig& cfg) {
return json{
{"show_acecode_avatar", false},
{"theme", cfg.theme},
{"color_theme", cfg.color_theme},
{"font_size", cfg.font_size},
};
}
json upgrade_config_to_json(const UpgradeConfig& cfg) {
return json{{"base_url", normalize_upgrade_base_url(cfg.base_url)}};
}
json update_check_to_json(const acecode::upgrade::UpdateCheckResult& result) {
json out = {
{"status", acecode::upgrade::update_check_status_name(result.status)},
{"update_available", result.update_available()},
{"current_version", result.current_version},
{"latest_version", result.latest_version},
{"target", result.target},
{"manifest_url", result.manifest_url},
};
out["releases"] = json::array();
for (const auto& release : result.releases) {
out["releases"].push_back({
{"version", release.version},
{"published_at", release.published_at},
{"notes", release.notes},
});
}
if (!result.package_file.empty()) out["package_file"] = result.package_file;
if (!result.package_url.empty()) out["package_url"] = result.package_url;
if (result.package_size) out["package_size"] = *result.package_size;
if (result.http_status != 0) out["http_status"] = result.http_status;
if (!result.error.empty()) out["error"] = result.error;
return out;
}
json custom_instructions_to_json(const CustomInstructionsConfig& cfg) {
return json{{"text", cfg.text_snapshot()}};
}
bool has_non_whitespace(const std::string& value) {
return std::any_of(value.begin(), value.end(), [](unsigned char c) {
return !std::isspace(c);
});
}
std::string json_string_field(const json& object, const char* key) {
if (!object.is_object() || !object.contains(key) || !object[key].is_string()) {
return {};
}
return object[key].get<std::string>();
}
int json_positive_int_field(const json& object, const char* key) {
if (!object.is_object() || !object.contains(key)) return 0;
const auto& value = object[key];
if (value.is_number_integer()) {
const int number = value.get<int>();
return number > 0 ? number : 0;
}
if (value.is_number_unsigned()) {
const auto number = value.get<unsigned int>();
return number > 0 ? static_cast<int>(number) : 0;
}
return 0;
}
std::optional<std::int64_t> json_nonnegative_int_field(const json& object,
const char* key) {
if (!object.is_object() || !object.contains(key)) return std::nullopt;
const auto& value = object[key];
if (value.is_number_unsigned()) {
const auto number = value.get<std::uint64_t>();
if (number <= static_cast<std::uint64_t>(
std::numeric_limits<std::int64_t>::max())) {
return static_cast<std::int64_t>(number);
}
} else if (value.is_number_integer()) {
const auto number = value.get<std::int64_t>();
if (number >= 0) return number;
}
return std::nullopt;
}
std::string truncate_selection_context_text(std::string text) {
if (text.size() <= kMaxSelectionContextChars) return text;
text = truncate_utf8_prefix(text, kMaxSelectionContextChars, "");
text += "\n[Selection truncated]";
return text;
}
std::string truncate_selection_anchor_text(std::string text) {
std::string normalized;
normalized.reserve(text.size());
for (std::size_t i = 0; i < text.size(); ++i) {
if (text[i] == '\r') {
normalized.push_back('\n');
if (i + 1 < text.size() && text[i + 1] == '\n') ++i;
} else {
normalized.push_back(text[i]);
}
}
if (normalized.size() > kMaxSelectionContextChars) {
normalized =
truncate_utf8_prefix(normalized, kMaxSelectionContextChars, "");
}
return normalized;
}
std::string truncate_selection_annotation_text(std::string text) {
if (text.size() <= kMaxSelectionAnnotationChars) return text;
text = truncate_utf8_prefix(text, kMaxSelectionAnnotationChars, "");
text += "\n[Annotation truncated]";
return text;
}
json sanitized_selection_annotations(const json& ctx) {
constexpr std::size_t kMaxAnnotationIdBytes = 256;
constexpr std::size_t kMaxAnnotationTimestampBytes = 64;
json annotations = json::array();
if (!ctx.is_object() || !ctx.contains("annotations") ||
!ctx["annotations"].is_array()) {
return annotations;
}
std::unordered_set<std::string> seen_ids;
std::size_t fallback_id = 0;
for (const auto& raw : ctx["annotations"]) {
if (annotations.size() >= kMaxSelectionAnnotations) break;
if (!raw.is_object()) continue;
std::string text =
truncate_selection_annotation_text(json_string_field(raw, "text"));
if (!has_non_whitespace(text)) continue;
std::string id = truncate_utf8_prefix(
json_string_field(raw, "id"), kMaxAnnotationIdBytes, "");
if (!has_non_whitespace(id)) {
id = "annotation-" + std::to_string(++fallback_id);
}
if (!seen_ids.insert(id).second) continue;
json annotation{{"id", id}, {"text", std::move(text)}};
const std::string created_at = truncate_utf8_prefix(
json_string_field(raw, "created_at"),
kMaxAnnotationTimestampBytes,
"");
if (has_non_whitespace(created_at)) {
annotation["created_at"] = created_at;
}
annotations.push_back(std::move(annotation));
}
return annotations;
}
std::string selection_line_suffix(const json& source) {
const int start = json_positive_int_field(source, "start_line");
const int end = json_positive_int_field(source, "end_line");
if (start <= 0) return {};
if (end <= 0 || end == start) return ":" + std::to_string(start);
return ":" + std::to_string(start) + "-" + std::to_string(end);
}
std::optional<json> sanitized_selection_context_meta(const json& ctx) {
constexpr std::size_t kMaxContentRevisionBytes = 128;
if (!ctx.is_object() || json_string_field(ctx, "type") != "selection") {
return std::nullopt;
}
const std::string text = json_string_field(ctx, "text");
if (!has_non_whitespace(text)) return std::nullopt;
json source = json::object();
if (ctx.contains("source") && ctx["source"].is_object()) {
const auto& raw_source = ctx["source"];
const std::string path = json_string_field(raw_source, "path");
const std::string kind = json_string_field(raw_source, "kind");
if (!path.empty()) source["path"] = path;
if (!kind.empty()) source["kind"] = kind;
const int start = json_positive_int_field(raw_source, "start_line");
const int end = json_positive_int_field(raw_source, "end_line");
const int line_count = json_positive_int_field(raw_source, "line_count");
if (start > 0) source["start_line"] = start;
if (end > 0) source["end_line"] = end;
if (line_count > 0) source["line_count"] = line_count;
const std::string view = json_string_field(raw_source, "view");
if (view == "source" || view == "rendered") source["view"] = view;
const auto start_offset =
json_nonnegative_int_field(raw_source, "start_offset");
const auto end_offset =
json_nonnegative_int_field(raw_source, "end_offset");
if (start_offset.has_value() && end_offset.has_value() &&
*end_offset > *start_offset) {
source["start_offset"] = *start_offset;
source["end_offset"] = *end_offset;
}
const std::string content_revision = truncate_utf8_prefix(
json_string_field(raw_source, "content_revision"),
kMaxContentRevisionBytes,
"");
if (has_non_whitespace(content_revision)) {
source["content_revision"] = content_revision;
}
}
json meta = json::object();
meta["type"] = "selection";
const std::string id = json_string_field(ctx, "id");
const std::string label = json_string_field(ctx, "label");
const std::string note = json_string_field(ctx, "note");
if (!id.empty()) meta["id"] = id;
if (!label.empty()) meta["label"] = label;
if (!note.empty()) meta["note"] = note;
if (!source.empty()) meta["source"] = std::move(source);
std::string selected_text = json_string_field(ctx, "selected_text");
if (!has_non_whitespace(selected_text)) selected_text = text;
selected_text = truncate_selection_anchor_text(std::move(selected_text));
if (has_non_whitespace(selected_text)) {
meta["selected_text"] = std::move(selected_text);
}
json annotations = sanitized_selection_annotations(ctx);
if (!annotations.empty()) meta["annotations"] = std::move(annotations);
return meta;
}
SelectionPromptContext build_selection_prompt_context(const json& contexts) {
SelectionPromptContext out;
if (!contexts.is_array()) return out;
std::ostringstream body;
int count = 0;
for (const auto& ctx : contexts) {
auto meta = sanitized_selection_context_meta(ctx);
if (!meta.has_value()) continue;
std::string text = truncate_selection_context_text(json_string_field(ctx, "text"));
if (!has_non_whitespace(text)) continue;
++count;
out.meta.push_back(*meta);
const json source = meta->contains("source") && (*meta)["source"].is_object()
? (*meta)["source"]
: json::object();
std::string source_label = json_string_field(source, "path");
if (!source_label.empty()) {
source_label += selection_line_suffix(source);
} else {
source_label = json_string_field(*meta, "label");
}
body << "[selection " << count << "]\n";
if (!source_label.empty()) {
body << "Source: " << source_label << "\n";
}
body << "Text:\n" << text << "\n\n";
if (meta->contains("annotations") && (*meta)["annotations"].is_array() &&
!(*meta)["annotations"].empty()) {
body << "Annotations:\n";
int annotation_number = 0;
for (const auto& annotation : (*meta)["annotations"]) {
const std::string annotation_text =
json_string_field(annotation, "text");
if (!has_non_whitespace(annotation_text)) continue;
body << ++annotation_number << ". " << annotation_text << "\n";
}
body << "\n";
}
}
if (count > 0) {
out.prompt =
"The user pinned the following selected text as reference context. "
"Use it when it is relevant to the request.\n\n" + body.str();
}
return out;
}
std::string build_selection_augmented_prompt(const SelectionPromptContext& selection,
const std::string& original_text) {
std::ostringstream out;
out << selection.prompt << "User request:\n";
if (original_text.empty()) {
out << "(no additional typed prompt)";
} else {
out << original_text;
}
return out.str();
}
json session_event_to_json(const SessionEvent& evt,
const std::string& session_id,
const std::string& workspace_hash,
const std::string& cwd) {
json msg;
msg["type"] = to_string(evt.kind);
msg["seq"] = evt.seq;
msg["timestamp_ms"] = evt.timestamp_ms;
msg["payload"] = evt.payload;
if (!session_id.empty()) {
msg["session_id"] = session_id;
if (msg["payload"].is_object() && !msg["payload"].contains("session_id")) {
msg["payload"]["session_id"] = session_id;
}
}
if (!workspace_hash.empty()) {
msg["workspace_hash"] = workspace_hash;
if (msg["payload"].is_object() && !msg["payload"].contains("workspace_hash")) {
msg["payload"]["workspace_hash"] = workspace_hash;
}
}
if (!cwd.empty()) {
if (msg["payload"].is_object() && !msg["payload"].contains("cwd")) {
msg["payload"]["cwd"] = cwd;
}
}
return msg;
}
void log_unauthorized(const std::string& path,
const std::string& client_ip,
const char* reason) {
LOG_WARN(std::string("[web] 401 ") + reason + " path=" + path
+ " client_ip=" + client_ip);
}
bool is_loopback_origin(const std::string& origin) {
return origin.rfind("http://127.0.0.1:", 0) == 0 ||
origin.rfind("http://localhost:", 0) == 0 ||
origin.rfind("http://[::1]:", 0) == 0 ||
origin.rfind("https://127.0.0.1:", 0) == 0 ||
origin.rfind("https://localhost:", 0) == 0 ||
origin.rfind("https://[::1]:", 0) == 0;
}
std::string ascii_lower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return s;
}
bool is_loopback_host(const std::string& host) {
auto h = ascii_lower(host);
return h == "localhost" || h == "::1" ||
h == "127.0.0.1" ||
(h.size() > 4 && h.substr(0, 4) == "127.");
}
bool is_same_request_origin(const crow::request& req,
const std::string& origin) {
auto host = req.get_header_value("Host");
if (host.empty()) return false;
if (origin == ("http://" + host) || origin == ("https://" + host)) {
return true;
}
auto o = parse_origin(origin);
auto h = split_host_port(host);
if (h.port.empty()) h.port = (o.scheme == "https") ? "443" : "80";
return !o.host.empty() && !h.host.empty() &&
o.port == h.port &&
is_loopback_host(o.host) &&
is_loopback_host(h.host);
}
AuthResult check_explicit_token(std::string_view server_token,
std::string_view header_token,
std::string_view query_token) {
if (header_token.empty() && query_token.empty()) return AuthResult::NoToken;
if (!server_token.empty() &&
(header_token == server_token || query_token == server_token)) {
return AuthResult::Allowed;
}
return AuthResult::BadToken;
}
// =====================================================================
// Impl member helpers — Auth
// =====================================================================
AuthResult WebServer::Impl::auth_result_for_request(const crow::request& req,
const std::string& header_token,
const std::string& query_token) const {
auto origin = req.get_header_value("Origin");
if (!origin.empty() && !is_same_request_origin(req, origin)) {
if (!is_loopback_origin(origin)) return AuthResult::BadToken;
return check_explicit_token(deps.token, header_token, query_token);
}
return check_request_auth(req.remote_ip_address, deps.token,
header_token, query_token);
}
std::optional<crow::response> WebServer::Impl::require_auth(const crow::request& req) {
std::string header_token;
auto h = req.get_header_value("X-ACECode-Token");
if (!h.empty()) header_token = h;
std::string query_token;
auto qt = req.url_params.get("token");
if (qt) query_token = qt;
auto result = auth_result_for_request(req, header_token, query_token);
if (result == AuthResult::Allowed) return std::nullopt;
const char* reason = (result == AuthResult::NoToken)
? "no token" : "bad token";
log_unauthorized(req.url, req.remote_ip_address, reason);
crow::response resp(401);
resp.add_header("Content-Type", "application/json");
resp.body = json{{"error", reason}}.dump();
add_cors(req, resp);
return resp;
}
void WebServer::Impl::add_cors(const crow::request& req, crow::response& resp) {
std::string origin = req.get_header_value("Origin");
if (origin.empty() || !is_loopback_origin(origin)) return;
resp.add_header("Access-Control-Allow-Origin", origin);
resp.add_header("Vary", "Origin");
resp.add_header("Access-Control-Allow-Credentials", "false");
resp.add_header("Access-Control-Allow-Headers", "Content-Type, X-ACECode-Token");
resp.add_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}
crow::response WebServer::Impl::with_cors(const crow::request& req, crow::response resp) {
add_cors(req, resp);
return resp;
}
crow::response WebServer::Impl::cors_preflight(const crow::request& req) {
crow::response r(204);
add_cors(req, r);
return r;
}
// =====================================================================
// Impl member helpers — Workspace
// =====================================================================
std::string WebServer::Impl::projects_dir() const {
if (!deps.projects_dir.empty()) return deps.projects_dir;
return path_to_utf8(path_from_utf8(get_acecode_dir()) / "projects");
}
std::string WebServer::Impl::no_workspace_cache_root() const {
return deps.no_workspace_cache_root.empty()
? default_no_workspace_cache_root()
: deps.no_workspace_cache_root;
}
acecode::desktop::WorkspaceMeta WebServer::Impl::compatibility_workspace() const {
acecode::desktop::WorkspaceMeta m;
m.cwd = deps.cwd;
m.hash = compute_cwd_hash(deps.cwd);
m.name = acecode::desktop::default_workspace_name(deps.cwd);
return m;
}
std::optional<acecode::desktop::WorkspaceMeta> WebServer::Impl::resolve_workspace(const std::string& hash) const {
if (hash == "__local__") return compatibility_workspace();
if (deps.workspace_registry) {
if (auto m = deps.workspace_registry->get(hash)) {
return m;
}
} else {
auto compat = compatibility_workspace();
if (hash == compat.hash) return compat;
}
// Registry membership means "visible in Desktop", not "valid session
// workspace". Fall back to the exact persisted project directory without
// registering it or changing desktop_visible. Restrict the path component
// to the canonical 16-hex hash format before touching disk.
const bool safe_hash = hash.size() == 16 &&
std::all_of(hash.begin(), hash.end(), [](unsigned char c) {
return (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
});
if (!safe_hash) return std::nullopt;
if (auto persisted = acecode::desktop::load_workspace_metadata(
projects_dir(), hash)) {
if (acecode::desktop::workspace_hash_matches_cwd(hash, persisted->cwd)) {
return persisted;
}
}
const std::string project_dir = path_to_utf8(
path_from_utf8(projects_dir()) / hash);
try {
for (const auto& meta : SessionStorage::list_session_metadata(project_dir)) {
if (meta.no_workspace || meta.cwd.empty()) continue;
if (!acecode::desktop::workspace_hash_matches_cwd(hash, meta.cwd)) {
continue;
}
acecode::desktop::WorkspaceMeta inferred;
inferred.hash = hash;
inferred.cwd = meta.cwd;
inferred.name = acecode::desktop::default_workspace_name(meta.cwd);
inferred.desktop_visible = false;
return inferred;
}
} catch (const std::exception& e) {
LOG_WARN("[web] hidden workspace metadata scan failed for " + hash +
": " + e.what());
}
return std::nullopt;
}
bool WebServer::Impl::archived_query_requested(const crow::request& req) const {
auto raw = req.url_params.get("archived");
if (!raw) return false;
const std::string value = ascii_lower(raw);
return value == "1" || value == "true" || value == "yes";
}
UsageLedgerQuery WebServer::Impl::usage_query_from_request(const crow::request& req) const {
UsageLedgerQuery query;
if (auto raw_days = req.url_params.get("days")) {
try {
query.days = std::stoi(raw_days);
} catch (...) {
query.days = 30;
}
}
if (auto raw_workspace = req.url_params.get("workspace")) {
query.workspace_hash = raw_workspace;
}
if (auto raw_tz = req.url_params.get("timezone_offset_minutes")) {
try {
query.timezone_offset_minutes = std::clamp(std::stoi(raw_tz), -1440, 1440);
} catch (...) {
query.timezone_offset_minutes = 0;
}
}
return query;
}
std::vector<UsageLedgerScope> WebServer::Impl::usage_scopes_for_request(
const std::string& workspace_hash) const {
std::vector<UsageLedgerScope> scopes;
std::unordered_set<std::string> seen;
auto add = [&](const acecode::desktop::WorkspaceMeta& ws) {
if (!workspace_hash.empty() &&
workspace_hash != "__local__" &&
ws.hash != workspace_hash) {
return;
}
if (ws.hash.empty() || seen.count(ws.hash)) return;
seen.insert(ws.hash);
scopes.push_back(UsageLedgerScope{
SessionStorage::get_project_dir(ws.cwd),
ws.hash,
ws.name.empty() ? acecode::desktop::default_workspace_name(ws.cwd) : ws.name,
ws.cwd,
});
};
if (workspace_hash == "__local__") {
add(compatibility_workspace());
return scopes;
}
add(compatibility_workspace());
if (deps.workspace_registry) {
deps.workspace_registry->scan(projects_dir());
for (const auto& ws : deps.workspace_registry->list()) {
add(ws);
}
}
return scopes;
}
std::vector<std::string> WebServer::Impl::allowed_file_cwds() const {
std::vector<std::string> out;
std::unordered_set<std::string> seen;
auto add = [&](const std::string& cwd) {
if (cwd.empty() || seen.count(cwd)) return;
seen.insert(cwd);
out.push_back(cwd);
};
add(deps.cwd);
if (deps.workspace_registry) {
for (const auto& m : deps.workspace_registry->list()) {
add(m.cwd);
}
}
if (deps.session_registry) {
for (const auto& session : deps.session_registry->list_active()) {
// A session's own cwd is a legitimate file root: it is where that
// session's tools already read and write. no-workspace sessions live
// under <data_dir>/cache/no-workspace/<id> and belong to no registered
// workspace, so without this they matched nothing in the allow list and
// every preview request came back 400 — files the agent had just
// created in that very directory were unopenable.
add(session.cwd);
add(session.worktree_path);
}
}
return out;
}
json WebServer::Impl::workspace_to_json(const acecode::desktop::WorkspaceMeta& m) const {
json o;
o["hash"] = m.hash;
o["cwd"] = m.cwd;
o["name"] = m.name;
o["available"] = cwd_is_directory(m.cwd);
return o;
}
// =====================================================================
// Impl member helpers — Session serialization
// =====================================================================
bool WebServer::Impl::token_usage_has_values(const TokenUsage& usage) {
return usage.has_data ||
usage.prompt_tokens != 0 ||
usage.completion_tokens != 0 ||
usage.total_tokens != 0 ||
usage.cache_read_tokens != 0 ||
usage.cache_write_tokens != 0 ||
usage.reasoning_tokens != 0 ||
usage.context_breakdown.has_data;
}
json WebServer::Impl::token_usage_to_json(const TokenUsage& usage) {
json value = {
{"prompt_tokens", usage.prompt_tokens},
{"completion_tokens", usage.completion_tokens},
{"total_tokens", usage.total_tokens},
{"cache_read_tokens", usage.cache_read_tokens},
{"cache_write_tokens", usage.cache_write_tokens},
{"reasoning_tokens", usage.reasoning_tokens},
{"has_data", usage.has_data},
};
if (usage.context_breakdown.has_data) {
value["context_breakdown"] =
context_usage_breakdown_to_json(usage.context_breakdown);
}
return value;
}
json WebServer::Impl::token_usage_or_null(const TokenUsage& usage) {
return token_usage_has_values(usage) ? token_usage_to_json(usage) : json(nullptr);
}
bool WebServer::Impl::session_model_deleted(const std::string& model_name) const {
if (model_name.empty() || model_name.rfind("(session:", 0) == 0 || !deps.app_config) {
return false;
}
std::shared_lock<std::shared_mutex> config_lock(app_config_mu);
for (const auto& entry : deps.app_config->saved_models) {
if (entry.name == model_name) return false;
}
return true;
}
namespace {
void append_worktree_session(json& target, const WorktreeSessionInfo& worktree) {
if (!worktree.active()) return;
target["worktree"] = {
{"name", worktree.worktree_name},
{"branch", worktree.worktree_branch},
{"path", worktree.worktree_path},
};
}
void append_loop_execution(json& target,
const std::string& loop_id,
const std::string& loop_run_id) {
if (loop_id.empty()) return;
target["loop_execution"] = {
{"loop_id", loop_id},
{"run_id", loop_run_id},
};
}
std::string existing_session_jsonl_path(const std::string& cwd,
const std::string& session_id) {
if (cwd.empty() || session_id.empty()) return {};
const std::string path = SessionStorage::session_path(
SessionStorage::get_project_dir(cwd), session_id);
std::error_code ec;
if (!std::filesystem::is_regular_file(path_from_utf8(path), ec) || ec) {
return {};
}
return path;
}
} // namespace
json WebServer::Impl::session_info_to_json(const SessionInfo& s, const SessionMeta* m) const {
json o;
const std::string model_name =
!s.model_name.empty() ? s.model_name : (m ? m->model_preset : "");
const bool model_deleted = s.model_deleted || session_model_deleted(model_name);
const bool no_workspace = s.no_workspace || (m && m->no_workspace);
const std::string workspace_hash = no_workspace
? std::string{}
: (!s.workspace_hash.empty() ? s.workspace_hash : (m ? compute_cwd_hash(m->cwd) : ""));
const std::string storage_cwd = !s.cwd.empty() ? s.cwd : (m ? m->cwd : "");
const std::string cwd = no_workspace ? std::string{} : storage_cwd;
o["id"] = s.id;
o["active"] = true;
o["status"] = s.busy ? "running" : "idle";
if (!s.active_turn_id.empty()) {
o["active_turn_id"] = s.active_turn_id;
}
o["workspace_hash"] = workspace_hash;
o["cwd"] = cwd;
// `cwd` stays empty for no-workspace sessions because callers treat it as the
// workspace binding. File preview needs the real directory regardless of
// workspace membership, so it is published separately instead of overloading
// `cwd` and disturbing workspace attribution.
o["working_cwd"] = storage_cwd;
o["session_path"] = existing_session_jsonl_path(storage_cwd, s.id);
o["no_workspace"] = no_workspace;
// A user rename persisted by another process (Desktop keeps one daemon per
// workspace, and only the active one serves the UI) leaves this daemon's
// in-memory title stale. The disk snapshot is read after list_active(), so
// a persisted user title is authoritative even when the live copy already
// carries an older user title from an earlier rename.
const bool meta_user_title =
m && (m->title_source == "user" || m->title_source == "user-cleared");
if (meta_user_title) {
o["title"] = m->title;
o["title_source"] = m->title_source;
} else {
o["title"] = !s.title.empty() ? s.title : (m ? m->title : "");
o["title_source"] = !s.title_source.empty()
? s.title_source
: (m ? m->title_source : "");
}
o["summary"] = !s.summary.empty() ? s.summary : (m ? m->summary : "");
o["created_at"] = !s.created_at.empty() ? s.created_at : (m ? m->created_at : "");
o["updated_at"] = !s.updated_at.empty() ? s.updated_at : (m ? m->updated_at : "");
o["provider"] = model_deleted ? "" : (!s.provider.empty() ? s.provider : (m ? m->provider : ""));
o["model"] = model_deleted ? "" : (!s.model.empty() ? s.model : (m ? m->model : ""));
o["model_name"] = model_name;
o["model_preset"] = o["model_name"];
o["context_window"] = s.context_window;
o["deleted"] = model_deleted;
o["message_count"] = s.message_count > 0 ? s.message_count : (m ? m->message_count : 0);
o["turn_count"] = s.turn_count > 0 ? s.turn_count : (m ? m->turn_count : 0);
o["permission_mode"] = !s.permission_mode.empty()
? s.permission_mode
: (m ? m->permission_mode : "default");
o["token_usage"] = token_usage_or_null(
token_usage_has_values(s.last_token_usage)
? s.last_token_usage
: (m ? m->last_token_usage : TokenUsage{}));
o["session_token_usage"] = token_usage_or_null(
token_usage_has_values(s.session_token_usage)
? s.session_token_usage
: (m ? m->session_token_usage : TokenUsage{}));
WorktreeSessionInfo worktree = m ? m->worktree : WorktreeSessionInfo{};
if (!s.worktree_path.empty()) {
worktree.worktree_path = s.worktree_path;
if (!s.worktree_name.empty()) worktree.worktree_name = s.worktree_name;
if (!s.worktree_branch.empty()) worktree.worktree_branch = s.worktree_branch;
}
append_worktree_session(o, worktree);
if (m) {
append_loop_execution(o, m->loop_id, m->loop_run_id);
}
if (!o.contains("loop_execution") && deps.session_registry) {
if (auto entry = deps.session_registry->acquire(s.id);
entry && entry->loop_execution) {
append_loop_execution(o, entry->loop_id, entry->loop_run_id);
}
}
if (m && !m->todos.empty()) {
o["todos"] = todo_items_to_json(m->todos);
o["todo_summary"] = todo_summary_to_json(m->todos);
}
o["archived"] = m ? m->archived : false;
o["parent_session_id"] = !s.parent_session_id.empty()
? s.parent_session_id
: (m ? m->parent_session_id : std::string{});
const std::string expert_id = !s.expert_id.empty()
? s.expert_id : (m ? m->expert_id : std::string{});
const std::string expert_member_id = !s.expert_member_id.empty()
? s.expert_member_id : (m ? m->expert_member_id : std::string{});
o["expert_id"] = expert_id;
o["expert_member_id"] = expert_member_id;
if (!expert_id.empty()) {
json expert_json = {
{"id", expert_id},
{"member_id", expert_member_id},
{"missing", s.expert_missing},
};
if (!s.expert_display_name.empty()) {
expert_json["display_name"] = s.expert_display_name;
expert_json["type"] = s.expert_type;
expert_json["source"] = s.expert_source;
} else if (deps.expert_registry && m) {
if (auto resolved = deps.expert_registry->find(m->cwd, expert_id)) {
expert_json["display_name"] = resolved->display_name;
expert_json["type"] = to_string(resolved->type);
expert_json["source"] = resolved->source;
expert_json["missing"] = false;
} else {
expert_json["missing"] = true;
}
}
o["expert"] = std::move(expert_json);
}
append_attention_fields(o, s.id, workspace_hash, cwd, s.busy);
return o;
}
json WebServer::Impl::session_meta_to_json(const SessionMeta& m, const std::string& workspace_hash) const {
json o;
const bool model_deleted = session_model_deleted(m.model_preset);
const std::string effective_workspace_hash = m.no_workspace ? std::string{} : workspace_hash;
const std::string effective_cwd = m.no_workspace ? std::string{} : m.cwd;
o["id"] = m.id;
o["active"] = false;
o["status"] = "idle";
o["workspace_hash"] = effective_workspace_hash;
o["cwd"] = effective_cwd;
o["session_path"] = existing_session_jsonl_path(m.cwd, m.id);
o["no_workspace"] = m.no_workspace;
o["title"] = m.title;
o["title_source"] = m.title_source;
o["summary"] = m.summary;
o["created_at"] = m.created_at;
o["updated_at"] = m.updated_at;
o["provider"] = model_deleted ? "" : m.provider;
o["model"] = model_deleted ? "" : m.model;
o["model_name"] = m.model_preset;
o["model_preset"] = m.model_preset;
o["deleted"] = model_deleted;
o["message_count"] = m.message_count;
o["turn_count"] = m.turn_count;
o["permission_mode"] = m.permission_mode.empty() ? "default" : m.permission_mode;
o["token_usage"] = token_usage_or_null(m.last_token_usage);
o["session_token_usage"] = token_usage_or_null(m.session_token_usage);
// 会话的 worktree 状态(add-webui-git-session-pill):前端 pill 与侧栏
// 据此恢复只读状态。inactive 时省略字段。
append_worktree_session(o, m.worktree);
append_loop_execution(o, m.loop_id, m.loop_run_id);
if (!m.todos.empty()) {
o["todos"] = todo_items_to_json(m.todos);
o["todo_summary"] = todo_summary_to_json(m.todos);
}
o["archived"] = m.archived;
o["parent_session_id"] = m.parent_session_id;
o["expert_id"] = m.expert_id;
o["expert_member_id"] = m.expert_member_id;
if (!m.expert_id.empty()) {
json expert_json = {
{"id", m.expert_id},
{"member_id", m.expert_member_id},
{"missing", true},
};
if (deps.expert_registry) {
if (auto resolved = deps.expert_registry->find(m.cwd, m.expert_id)) {
expert_json["display_name"] = resolved->display_name;
expert_json["type"] = to_string(resolved->type);
expert_json["source"] = resolved->source;
expert_json["missing"] = false;
}
}
o["expert"] = std::move(expert_json);
}
append_attention_fields(o, m.id, effective_workspace_hash, effective_cwd, false);
return o;
}
void WebServer::Impl::append_session_runtime_snapshot(json& wrapper,
const std::string& session_id) const {
if (session_id.empty()) return;
SessionMeta meta;
bool have_meta = false;
if (deps.session_registry) {
if (auto entry = deps.session_registry->acquire(session_id)) {
if (entry->no_workspace) {
wrapper["no_workspace"] = true;
wrapper["workspace_hash"] = "";
wrapper["cwd"] = "";
}
if (entry->loop) {
wrapper["busy"] = entry->loop->is_busy();
const std::string active_turn_id =
entry->loop->active_turn_id();
if (!active_turn_id.empty()) {
wrapper["active_turn_id"] = active_turn_id;
}
}
if (entry->sm) {
meta = entry->sm->load_session_meta(session_id);
have_meta = !meta.id.empty();
wrapper["turn_count"] = entry->sm->current_turn_count();
wrapper["permission_mode"] = entry->sm->current_permission_mode();
wrapper["token_usage"] = token_usage_or_null(entry->sm->current_last_token_usage());
wrapper["session_token_usage"] =
token_usage_or_null(entry->sm->current_session_token_usage());
auto todos = entry->sm->current_todos();
if (!todos.empty()) {
wrapper["todos"] = todo_items_to_json(todos);
wrapper["todo_summary"] = todo_summary_to_json(todos);
}
}
}
}
if (!have_meta) {
auto project_dir = SessionStorage::get_project_dir(deps.cwd);
auto meta_path = SessionStorage::meta_path(project_dir, session_id);
meta = SessionStorage::read_meta(meta_path);
have_meta = !meta.id.empty();
if (!have_meta) {
auto no_workspace_meta = find_no_workspace_session_meta(session_id);
if (no_workspace_meta.has_value()) {
meta = *no_workspace_meta;
have_meta = true;
}
}
}
if (have_meta) {
if (meta.no_workspace) {
wrapper["no_workspace"] = true;
wrapper["workspace_hash"] = "";
wrapper["cwd"] = "";
}