-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.cpp
More file actions
2695 lines (2535 loc) · 111 KB
/
Copy pathmain.cpp
File metadata and controls
2695 lines (2535 loc) · 111 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
// acecode-desktop: WebView 壳 + 共享 daemon(所有 workspace/session 复用一个 daemon)。
//
// 启动流程:
// 1. 扫 .acecode/projects/* → WorkspaceRegistry
// 2. 读 state.json::last_active_workspace_hash
// 3. pick_active 决定首屏 workspace
// 4. 注册 webview JS bridge: aceDesktop_listWorkspaces / activateWorkspace /
// renameWorkspace / addWorkspace
// 5. 若 active workspace 存在 → DaemonPool::activate → 拼 URL → navigate
// 若不存在 → 仍启动 shared daemon 只用于承载前端,sidebar 渲染为空列表 + "+ 添加项目"
// 6. WebHost.run() 阻塞直到窗口关闭
// 7. quit: pool.shutdown_all() 按用户策略 stop/release + 写 last_active
//
// daemon 端通过 workspace-aware API 在同一进程内服务多个 workspace。
#include "daemon_pool.hpp"
#include "agent_browser_host.hpp"
#include "agent_browser_runtime.hpp"
#include "context_items.hpp"
#include "context_picker.hpp"
#include "desktop_about.hpp"
#include "desktop_restart.hpp"
#include "dpi_win.hpp"
#include "edge_app_launcher.hpp"
#include "external_url.hpp"
#include "folder_picker.hpp"
#include "locale.hpp"
#include "notifications.hpp"
#include "open_request.hpp"
#include "open_in_explorer.hpp"
#include "pick_active.hpp"
#include "single_instance.hpp"
#include "splash_screen.hpp"
#include "startup_progress.hpp"
#include "strings.hpp"
#include "tray_menu_bridge.hpp"
#include "tray_icon_win.hpp"
#include "url_builder.hpp"
#include "web_host.hpp"
#include "web_host_close_policy.hpp"
#include "workspace_registry.hpp"
#include "../config/config.hpp"
#include "../daemon/platform.hpp"
#include "../daemon/runtime_files.hpp"
#include "../utils/clipboard.hpp"
#include "../utils/base64.hpp"
#include "../utils/cwd_hash.hpp"
#include "../utils/encoding.hpp"
#include "../utils/logger.hpp"
#include "../utils/state_file.hpp"
#include "../utils/utf8_path.hpp"
#include "../utils/uuid.hpp"
#include "version.hpp"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <atomic>
#include <cstdlib>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <random>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <cpr/cpr.h>
#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <windows.h>
# include <shellapi.h>
#endif
#ifdef __APPLE__
# include <mach-o/dyld.h>
#endif
namespace fs = std::filesystem;
namespace {
constexpr const char* kSharedDaemonSlotHash = "__shared_daemon__";
constexpr const char* kSharedDaemonContextId = "default";
constexpr const char* kDesktopCloseRequestEvent =
"acecode:desktop-close-requested";
nlohmann::json agent_browser_state_json(
const acecode::desktop::AgentBrowserState& state) {
nlohmann::json result{
{"supported", state.supported},
{"ready", state.ready},
{"loading", state.loading},
{"visible", state.visible},
{"active", state.active},
{"closed", state.closed},
{"can_go_back", state.can_go_back},
{"can_go_forward", state.can_go_forward},
{"shared_with_agent", state.shared_with_agent},
{"element_selection_active", state.element_selection_active},
{"element_selection_serial", state.element_selection_serial},
{"url", state.url},
{"title", state.title},
{"favicon", state.favicon},
{"content_state", state.content_state},
{"failure_kind", state.failure_kind},
{"error", state.error},
{"diagnostic", state.diagnostic},
{"page_id", state.page_id},
};
if (!state.selected_element_json.empty()) {
const auto selected = nlohmann::json::parse(
state.selected_element_json, nullptr, false);
if (!selected.is_discarded()) result["selected_element"] = selected;
}
return result;
}
nlohmann::json context_item_json(const acecode::desktop::ContextItem& item) {
nlohmann::json value{
{"kind", item.kind == acecode::desktop::ContextItemKind::Folder
? "folder" : "file"},
{"path", item.path},
{"name", item.name},
};
if (item.kind == acecode::desktop::ContextItemKind::File) {
value["mime_type"] = item.mime_type;
value["size_bytes"] = item.size_bytes;
if (item.reference_only) {
value["reference_only"] = true;
} else {
value["data_base64"] = acecode::base64_encode(item.bytes);
}
}
return value;
}
nlohmann::json context_items_json(const std::vector<std::string>& paths) {
auto materialized = acecode::desktop::materialize_context_items(paths);
if (!materialized) {
return nlohmann::json{{"ok", false}, {"error", materialized.error}};
}
nlohmann::json items = nlohmann::json::array();
for (const auto& item : materialized.items) {
items.push_back(context_item_json(item));
}
return nlohmann::json{{"ok", true}, {"items", std::move(items)}};
}
struct ContextPickerFolderReference {
std::string path;
std::optional<std::string> relative_path;
};
std::optional<ContextPickerFolderReference> context_picker_folder_reference(
const std::string& cwd,
const std::string& selected_path,
std::string& error) {
if (selected_path.empty()) {
error = "selected folder is unavailable";
return std::nullopt;
}
std::error_code ec;
const fs::path selected = fs::weakly_canonical(
acecode::path_from_utf8(selected_path), ec);
if (ec || !fs::is_directory(selected, ec) || ec) {
error = "selected folder is unavailable";
return std::nullopt;
}
ContextPickerFolderReference result{
acecode::path_to_utf8_generic(selected), std::nullopt};
if (!cwd.empty()) {
ec.clear();
const fs::path root = fs::weakly_canonical(acecode::path_from_utf8(cwd), ec);
if (!ec) {
if (selected == root) {
result.relative_path = std::string{};
} else {
const fs::path relative = selected.lexically_relative(root);
bool inside = !relative.empty() && !relative.is_absolute();
for (const auto& part : relative) {
if (part == "..") {
inside = false;
break;
}
}
if (inside) {
result.relative_path = acecode::path_to_utf8_generic(relative);
}
}
}
}
return result;
}
bool is_webapp_arg(const std::string& arg) {
return arg == "--webapp";
}
bool desktop_webapp_requested(const std::vector<std::string>& argv) {
for (std::size_t index = argv.empty() ? 0 : 1;
index < argv.size();
++index) {
if (is_webapp_arg(argv[index])) return true;
}
return false;
}
#ifdef _WIN32
std::vector<std::string> desktop_process_arguments() {
int argc = 0;
LPWSTR* argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
if (!argv) return {};
std::vector<std::string> result;
result.reserve(static_cast<std::size_t>((std::max)(argc, 0)));
for (int index = 0; index < argc; ++index) {
result.push_back(acecode::wide_to_utf8(argv[index]));
}
::LocalFree(argv);
return result;
}
std::string desktop_exe_dir() {
wchar_t buf[MAX_PATH] = {0};
DWORD n = ::GetModuleFileNameW(nullptr, buf, MAX_PATH);
if (n == 0 || n == MAX_PATH) return "";
std::wstring wpath(buf, n);
return acecode::wide_to_utf8(fs::path(wpath).parent_path().wstring());
}
#elif defined(__APPLE__)
std::vector<std::string> desktop_process_arguments(int argc, char** argv) {
std::vector<std::string> result;
result.reserve(static_cast<std::size_t>((std::max)(argc, 0)));
for (int index = 0; index < argc; ++index) {
result.emplace_back(argv[index] ? argv[index] : "");
}
return result;
}
std::string desktop_exe_dir() {
uint32_t size = 1024;
std::vector<char> buf(size);
if (_NSGetExecutablePath(buf.data(), &size) != 0) {
buf.assign(static_cast<size_t>(size) + 1, '\0');
if (_NSGetExecutablePath(buf.data(), &size) != 0) return "";
}
fs::path exe(buf.data());
std::error_code ec;
fs::path resolved = fs::weakly_canonical(exe, ec);
if (ec) {
ec.clear();
resolved = fs::absolute(exe, ec);
if (ec) resolved = exe;
}
return acecode::path_to_utf8(resolved.parent_path());
}
#else
std::vector<std::string> desktop_process_arguments(int argc, char** argv) {
std::vector<std::string> result;
result.reserve(static_cast<std::size_t>((std::max)(argc, 0)));
for (int index = 0; index < argc; ++index) {
result.emplace_back(argv[index] ? argv[index] : "");
}
return result;
}
std::string desktop_exe_dir() {
std::error_code ec;
auto p = fs::current_path(ec);
if (ec) return "";
return acecode::path_to_utf8(p);
}
#endif
#ifdef _WIN32
void show_error(const std::string& msg) {
std::wstring w = acecode::utf8_to_wide(msg);
const std::wstring title = acecode::utf8_to_wide(std::string(
acecode::desktop::native_string(
acecode::desktop::DesktopStringId::StartupFailedTitle)));
::MessageBoxW(nullptr, w.c_str(), title.c_str(), MB_ICONERROR | MB_OK);
}
#endif
fs::path path_from_utf8(const std::string& path) {
return acecode::path_from_utf8(path);
}
std::string path_to_utf8(const fs::path& path) {
return acecode::path_to_utf8(path);
}
std::string append_query_param(const std::string& url,
const std::string& key,
const std::string& value) {
if (url.empty() || url == "about:blank") return url;
const char separator = url.find('?') == std::string::npos ? '?' : '&';
return url + separator +
acecode::desktop::percent_encode(key) + "=" +
acecode::desktop::percent_encode(value);
}
std::string locate_daemon_exe() {
auto dir = desktop_exe_dir();
if (dir.empty()) return "";
#ifdef _WIN32
std::vector<const char*> candidates{"acecode.exe"};
#elif defined(__APPLE__)
std::vector<const char*> candidates{"acecode-daemon", "acecode"};
#else
std::vector<const char*> candidates{"acecode"};
#endif
for (const char* name : candidates) {
fs::path p = path_from_utf8(dir) / name;
if (fs::exists(p)) return path_to_utf8(p);
}
return "";
}
// dev 模式: 探到仓库 web/dist/ (Vite build 产物) → 让 daemon 走
// FileSystemAssetSource,`pnpm build` 后 F5 即生效,无需重 build acecode。
//
// **必须是 web/dist/ 不是 web/** — web/ 是 Vite 源码(index.html 里写
// <script src="/src/main.jsx">),daemon 不会 transpile JSX,加载会挂。
//
// 探测顺序:
// 1. 环境变量 ACECODE_DEV_WEB_DIR(显式指定绝对路径,信用户判断)
// 2. 自动猜:从 desktop exe 向上找 "web/dist/index.html"
// Windows: build/Release/acecode-desktop.exe → ../../web/dist
// macOS: build/ACECode.app/Contents/MacOS/ACECode → ../../../../web/dist
// 找不到返回空字符串 → daemon 走 embedded(cmake 已把 web/dist 嵌进二进制)。
std::string detect_dev_web_dir() {
std::string env = acecode::getenv_utf8("ACECODE_DEV_WEB_DIR");
if (!env.empty()) {
fs::path p = path_from_utf8(env) / "index.html";
if (fs::exists(p)) return env;
}
auto dir = desktop_exe_dir();
if (dir.empty()) return "";
fs::path cur = path_from_utf8(dir);
for (int i = 0; i < 8; ++i) {
fs::path candidate = cur / "web" / "dist";
if (fs::exists(candidate / "index.html")) return path_to_utf8(candidate);
if (!cur.has_parent_path()) break;
cur = cur.parent_path();
}
return "";
}
std::string projects_dir() {
return path_to_utf8(path_from_utf8(acecode::get_acecode_dir()) / "projects");
}
std::string desktop_shared_run_dir() {
return path_to_utf8(path_from_utf8(acecode::get_acecode_dir()) / "run" / "desktop-shared");
}
std::string current_cwd() {
std::error_code ec;
auto p = fs::current_path(ec);
if (ec) return "";
return path_to_utf8(p);
}
bool is_existing_directory(const std::string& path) {
if (path.empty()) return false;
#ifdef _WIN32
std::wstring wide = acecode::utf8_to_wide(path);
if (wide.empty()) return false;
DWORD attrs = ::GetFileAttributesW(wide.c_str());
return attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY) != 0;
#else
std::error_code ec;
return fs::is_directory(path, ec) && !ec;
#endif
}
std::string daemon_exe_parent_dir(const std::string& daemon_exe) {
if (daemon_exe.empty()) return "";
fs::path p = path_from_utf8(daemon_exe).parent_path();
if (p.empty()) return "";
return path_to_utf8(p);
}
std::string choose_launch_cwd(const std::string& preferred,
const std::string& proc_cwd,
const std::string& daemon_exe) {
if (is_existing_directory(preferred)) return preferred;
if (is_existing_directory(proc_cwd)) return proc_cwd;
std::string exe_dir = daemon_exe_parent_dir(daemon_exe);
if (is_existing_directory(exe_dir)) return exe_dir;
return "";
}
void log_legacy_workspace_run_dirs(const std::string& proj_dir) {
std::error_code ec;
fs::path native_proj_dir = path_from_utf8(proj_dir);
if (!fs::is_directory(native_proj_dir, ec) || ec) return;
int count = 0;
for (const auto& project_entry : fs::directory_iterator(native_proj_dir, ec)) {
if (ec) break;
if (!project_entry.is_directory(ec) || ec) continue;
fs::path run_dir = project_entry.path() / "run";
if (!fs::is_directory(run_dir, ec) || ec) continue;
for (const auto& run_entry : fs::directory_iterator(run_dir, ec)) {
if (ec) break;
if (!run_entry.is_directory(ec) || ec) continue;
++count;
if (count <= 8) {
LOG_WARN("[desktop] legacy workspace run dir ignored by shared daemon: " +
path_to_utf8(run_entry.path()));
}
}
}
if (count > 8) {
LOG_WARN("[desktop] legacy workspace run dirs ignored by shared daemon: " +
std::to_string(count) + " total");
}
}
// JSON 工具:把 daemon_state 枚举转成前端用的字符串
const char* state_string(acecode::desktop::DaemonState s) {
switch (s) {
case acecode::desktop::DaemonState::Stopped: return "stopped";
case acecode::desktop::DaemonState::Starting: return "starting";
case acecode::desktop::DaemonState::Running: return "running";
case acecode::desktop::DaemonState::Failed: return "failed";
}
return "stopped";
}
// onboarding fallback:正常情况下即使 registry 为空也会启动 shared daemon 来
// 承载前端。只有 daemon 启动失败时才落到 about:blank。
const char* onboarding_url() { return "about:blank"; }
bool is_desktop_debug_mode() {
#ifndef NDEBUG
return true;
#else
return false;
#endif
}
std::string short_random_hex() {
static constexpr char kHex[] = "0123456789abcdef";
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dist(0, 15);
std::string out;
out.reserve(8);
for (int i = 0; i < 8; ++i) out.push_back(kHex[dist(gen)]);
return out;
}
bool post_resume_to_daemon(int port, const std::string& token,
const std::string& session_id,
const std::string& workspace_hash,
std::string& error) {
std::string path = workspace_hash.empty()
? "/api/sessions/" + session_id + "/resume"
: "/api/workspaces/" + workspace_hash + "/sessions/" + session_id + "/resume";
auto r = cpr::Post(
cpr::Url{"http://127.0.0.1:" + std::to_string(port) + path},
cpr::Header{{"X-ACECode-Token", token},
{"Content-Type", "application/json"}},
cpr::Body{"{}"},
cpr::Timeout{5000});
if (r.status_code >= 200 && r.status_code < 300) return true;
std::ostringstream oss;
oss << "resume endpoint failed status=" << r.status_code;
if (!r.text.empty()) oss << " body=" << r.text;
if (r.error.code != cpr::ErrorCode::OK) oss << " error=" << r.error.message;
error = oss.str();
return false;
}
bool post_workspace_to_daemon(int port, const std::string& token,
const std::string& cwd,
std::string& error) {
auto r = cpr::Post(
cpr::Url{"http://127.0.0.1:" + std::to_string(port) + "/api/workspaces"},
cpr::Header{{"X-ACECode-Token", token},
{"Content-Type", "application/json"}},
cpr::Body{nlohmann::json{{"cwd", cwd}}.dump()},
cpr::Timeout{5000});
if (r.status_code >= 200 && r.status_code < 300) return true;
std::ostringstream oss;
oss << "workspace endpoint failed status=" << r.status_code;
if (!r.text.empty()) oss << " body=" << r.text;
if (r.error.code != cpr::ErrorCode::OK) oss << " error=" << r.error.message;
error = oss.str();
return false;
}
#ifdef _WIN32
// 在指定进程的可见顶层窗口里挑一个拉到前台(best-effort)。Edge --app + 干净
// profile 下,我们启动的 msedge 就是浏览器进程、拥有 app 窗口,按 pid 能找到。
struct FindWindowByPidCtx {
DWORD pid = 0;
HWND found = nullptr;
};
BOOL CALLBACK find_window_by_pid_cb(HWND hwnd, LPARAM lparam) {
auto* ctx = reinterpret_cast<FindWindowByPidCtx*>(lparam);
DWORD wpid = 0;
::GetWindowThreadProcessId(hwnd, &wpid);
if (wpid == ctx->pid && ::IsWindowVisible(hwnd) &&
::GetWindow(hwnd, GW_OWNER) == nullptr) {
ctx->found = hwnd;
return FALSE; // 找到一个顶层可见窗口就停
}
return TRUE;
}
void focus_process_main_window(unsigned long pid) {
if (pid == 0) return;
FindWindowByPidCtx ctx;
ctx.pid = static_cast<DWORD>(pid);
::EnumWindows(find_window_by_pid_cb, reinterpret_cast<LPARAM>(&ctx));
if (!ctx.found) return;
if (::IsIconic(ctx.found)) ::ShowWindow(ctx.found, SW_RESTORE);
::SetForegroundWindow(ctx.found);
}
#endif
// 浏览器兜底宿主:embedded WebView2 用不了时(运行时损坏/缺失/被策略封锁),用
// 外部浏览器显示 daemon 的 Web UI,并由 desktop 进程在后台托住 daemon。
//
// 关键设计(修白屏 + daemon 被提前杀):
// - 不再用 WaitForSingleObject(msedge) 当生命周期 —— Chromium 的 single-instance
// 转交会让被等的进程瞬间退出,导致 daemon 被误杀 → Edge 窗口连不上 → 白屏。
// - 改为:启动浏览器(Edge --app 优先,失败再退到系统默认浏览器),然后跑一个带
// 托盘图标的 Win32 消息循环托住进程;daemon 全程存活。
// - Edge --app(有可靠进程句柄 + 干净 profile)额外挂一个 watcher:app 窗口关闭
// → 进程退出 → 请求退出循环,保持"关窗即退出"的直觉。
// - 默认浏览器那条(拿不到可靠句柄)只能靠托盘"退出"。
int run_browser_fallback(const std::string& url,
acecode::desktop::SplashScreen& splash,
acecode::desktop::DaemonPool& pool,
const std::string& reason,
const std::string& webview_error) {
using namespace acecode::desktop;
LOG_WARN("[desktop] starting browser fallback mode: " + reason);
// daemon 没起来 → 没有可显示的 URL,浏览器也救不了,直接报清楚的错。
if (url.empty() || url == onboarding_url()) {
LOG_ERROR("[desktop] browser fallback has no daemon URL to show "
"(daemon failed to start)");
splash.close();
#ifdef _WIN32
show_error(format_browser_fallback_no_daemon_message(
reason, webview_error, native_locale()));
#endif
auto failures = pool.stop_all();
return failures.empty() ? 1 : 100;
}
const std::string browser_url = append_query_param(url, "ace_webapp", "1");
#ifdef _WIN32
// 1) 启动浏览器:Edge --app 优先(拿到进程句柄),失败退到默认浏览器。
void* edge_process = nullptr;
unsigned long edge_pid = 0;
bool opened = false;
std::string launch_detail;
auto edge = launch_edge_app(browser_url);
if (edge.ok) {
edge_process = edge.process;
edge_pid = edge.pid;
opened = true;
} else {
launch_detail = "Edge app mode: " + edge.error;
LOG_WARN("[desktop] Edge app mode unavailable, trying default browser: " + edge.error);
auto ext = acecode::desktop::open_external_url(browser_url);
if (ext.ok) {
opened = true;
LOG_INFO("[desktop] opened daemon UI in default browser");
} else {
launch_detail += " | default browser: " + ext.error;
}
}
splash.close();
if (!opened) {
LOG_ERROR("[desktop] browser fallback failed to open any browser: " + launch_detail);
show_error(format_browser_fallback_open_failed_message(
reason, launch_detail, webview_error, native_locale()));
if (edge_process) ::CloseHandle(static_cast<HANDLE>(edge_process));
auto failures = pool.stop_all();
return failures.empty() ? 1 : 100;
}
// 2) 托盘 + 消息循环托住 daemon 生命周期。
const DWORD main_tid = ::GetCurrentThreadId();
std::atomic<bool> quit_requested{false};
auto request_quit = [&quit_requested, main_tid]() {
quit_requested.store(true);
::PostThreadMessageW(main_tid, WM_NULL, 0, 0); // 唤醒阻塞中的 GetMessage
};
void* tray_hwnd = nullptr;
bool tray_ok = init_tray_icon(
/*on_show=*/[edge_pid]() {
if (edge_pid) focus_process_main_window(edge_pid);
},
/*on_quit=*/[&request_quit]() { request_quit(); },
&tray_hwnd);
if (!tray_ok) {
LOG_WARN("[desktop] tray icon unavailable in browser fallback; "
"window close still quits for Edge app mode");
}
// 3) Edge --app:app 窗口关闭(进程退出)→ 请求退出。stop_event 让 watcher 可被
// join(否则 WaitForMultipleObjects 无法取消)。
// 只有 edge_process 和 stop_event 都有效才起 watcher —— 这样 watcher 总能被
// stop_event 唤醒后 join,不会在退出时因 WaitForSingleObject 无法取消而卡死。
HANDLE stop_event = ::CreateEventW(nullptr, TRUE, FALSE, nullptr);
const bool can_autoquit_on_close = (edge_process != nullptr) && (stop_event != nullptr);
std::thread watcher;
if (can_autoquit_on_close) {
watcher = std::thread([edge_process, stop_event, &request_quit]() {
HANDLE waits[2] = {static_cast<HANDLE>(edge_process), stop_event};
::WaitForMultipleObjects(2, waits, FALSE, INFINITE);
request_quit();
});
}
if (!tray_ok && !can_autoquit_on_close) {
// 托盘装不上 + 无法在窗口关闭时自动退出 → 没有任何主动退出途径。日志点明,
// 避免静默"卡住"难诊断;daemon 会随 desktop 进程被杀而随之退出。
LOG_ERROR("[desktop] browser fallback has neither tray nor a process handle "
"to quit on; close the desktop process to stop the daemon");
}
// 4) 消息循环
MSG msg;
while (!quit_requested.load()) {
BOOL got = ::GetMessageW(&msg, nullptr, 0, 0);
if (got == 0 || got == -1) break; // WM_QUIT / 错误
::TranslateMessage(&msg);
::DispatchMessageW(&msg);
}
// 5) teardown:先放 watcher,再清托盘,最后停 daemon。
if (stop_event) ::SetEvent(stop_event);
if (watcher.joinable()) watcher.join();
if (stop_event) ::CloseHandle(stop_event);
if (edge_process) ::CloseHandle(static_cast<HANDLE>(edge_process));
shutdown_tray_icon();
auto failures = pool.shutdown_all();
return failures.empty() ? 0 : 100;
#else
// 非 Windows:desktop 用 WebKitGTK,几乎不会走到这里。best-effort 开默认浏览器
// 后收尾(无托盘宿主)。
(void)webview_error;
auto ext = acecode::desktop::open_external_url(browser_url);
splash.close();
if (!ext.ok) {
LOG_ERROR("[desktop] browser fallback failed to open default browser: " + ext.error);
}
auto failures = pool.shutdown_all();
return failures.empty() ? (ext.ok ? 0 : 1) : 100;
#endif
}
} // namespace
#ifdef _WIN32
int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) {
const auto process_arguments = desktop_process_arguments();
#else
int main(int argc, char** argv) {
const auto process_arguments = desktop_process_arguments(argc, argv);
#endif
const bool force_webapp = desktop_webapp_requested(process_arguments);
const auto startup_open_parse =
acecode::desktop::parse_desktop_open_request_arguments(
process_arguments);
// 顶层 try/catch:wWinMain 是 Windows 子系统的 EXE 入口,任何未捕获的
// C++ 异常会触发 std::terminate → 系统弹"未经处理的异常"调试器对话框,
// 普通用户既看不懂也无从下手。把整个 body 包成 IIFE lambda 让 catch 兜
// 底:落 LOG_ERROR、弹中文 MessageBox 给用户可执行的修复指引,然后
// return 1 走正常退出。
//
// 注意 logger 初始化也在 lambda 内,因为它本身也可能抛(磁盘满 / 路径
// 受 GPO 锁)。catch 里依然先调 LOG_ERROR(失败时是 no-op,不影响
// MessageBox 给用户提示)。
auto run = [
force_webapp,
startup_open_request = startup_open_parse.request,
startup_open_request_error = startup_open_parse.error
]() -> int {
using namespace acecode::desktop;
// desktop 自己的日志路径: ~/.acecode/logs/desktop-<date>.log。和 daemon
// 日志(daemon-<date>.log)同目录便于一次 tail。mirror_stderr=false 因为
// WIN32 子系统下 stderr 是 invalid handle。
acecode::Logger::instance().init_with_rotation(acecode::get_logs_dir(), "desktop", false);
acecode::Logger::instance().set_level(acecode::LogLevel::Dbg);
LOG_INFO("[desktop] starting acecode-desktop");
DesktopStartupTimeline startup_timeline;
const std::string desktop_system_locale =
acecode::desktop::detect_system_locale_tag();
std::string startup_locale = acecode::desktop::resolve_ui_locale(
acecode::desktop::kLocalePreferenceAuto, desktop_system_locale);
WebHost* startup_progress_host = nullptr;
bool startup_navigation_started = false;
bool startup_splash_open = false;
if (!startup_open_request_error.empty()) {
LOG_WARN("[desktop] ignored invalid open request: " +
startup_open_request_error);
}
const fs::path desktop_restart_target = current_desktop_executable_path();
if (desktop_restart_target.empty()) {
LOG_WARN("[desktop] could not resolve installed executable path; automatic restart will be unavailable");
}
if (force_webapp) {
LOG_INFO("[desktop] --webapp requested; embedded WebView will be skipped");
}
#ifdef _WIN32
LOG_INFO(std::string("[desktop] DPI awareness ") +
(acecode::desktop::enable_desktop_dpi_awareness() ? "enabled" : "not enabled"));
#endif
const std::int64_t desktop_instance_started_at_ms =
acecode::daemon::now_unix_ms();
// 单例锁:per-user。已有实例时把对方拉前 + 自己 exit(0),避免多份 desktop /
// 多份 daemon 子进程同时存在。设计见 src/desktop/single_instance.hpp。
SingleInstance singleton;
if (!singleton.try_acquire()) {
if (startup_open_request.has_value()) {
std::string handoff_error;
if (!publish_pending_desktop_open_request(
*startup_open_request, &handoff_error)) {
LOG_WARN("[desktop] failed to publish open request to existing "
"instance: " + handoff_error);
}
}
LOG_INFO("[desktop] another acecode-desktop instance is running, focusing it");
focus_existing_instance(); // POSIX 端是 stub,返回 false 也只是 exit
return 0;
}
const std::int64_t desktop_owner_pid =
acecode::daemon::current_pid();
const std::string desktop_owner_instance = acecode::generate_uuid();
const std::string shared_run_dir = desktop_shared_run_dir();
if (!acecode::daemon::write_desktop_owner_record(
shared_run_dir,
acecode::daemon::DesktopOwnerRecord{
desktop_owner_pid,
desktop_owner_instance,
acecode::daemon::now_unix_ms(),
})) {
LOG_WARN("[desktop] failed to publish Desktop owner record");
}
SplashScreen splash;
auto publish_startup_snapshot = [&]() {
if (!startup_progress_host || !startup_navigation_started) return;
const std::string snapshot = startup_timeline.snapshot_json();
startup_progress_host->eval(
"(function(snapshot){try{"
"window.__ACECODE_DESKTOP_STARTUP__=snapshot;"
"window.dispatchEvent(new CustomEvent(" +
nlohmann::json(kDesktopStartupProgressEvent).dump() +
",{detail:snapshot}));"
"}catch(e){}})(" + snapshot + ");");
};
auto mark_startup = [&](const std::string& stage,
const std::string& source = "native",
std::optional<double> frontend_ms = std::nullopt) {
const auto event = startup_timeline.record(
stage,
desktop_startup_stage_message(stage, startup_locale),
source,
is_terminal_startup_stage(stage),
frontend_ms);
std::string log =
"[startup] stage=" + event.stage +
" sequence=" + std::to_string(event.sequence) +
" source=" + event.source +
" elapsed_ms=" + std::to_string(event.elapsed_ms);
if (event.frontend_ms.has_value()) {
std::ostringstream value;
value << *event.frontend_ms;
log += " frontend_ms=" + value.str();
}
LOG_INFO(log);
if (startup_splash_open) {
splash.set_status(event.message, event.elapsed_ms);
}
publish_startup_snapshot();
return event;
};
startup_splash_open = true;
mark_startup("desktop_starting");
splash.show();
// 加载 desktop 端用到的 config(窗口关闭行为、通知、后台进程等)。
// 失败回退默认 AppConfig — 不阻断启动,与 daemon 一致;只是 close-to-tray
// 默认值仍生效。Daemon 子进程会自己再次 load_config,所以 Desktop 这次读
// 不会污染或覆盖 daemon 端配置。
acecode::AppConfig desktop_cfg;
std::mutex desktop_config_mu;
mark_startup("config_load_begin");
try {
desktop_cfg = acecode::load_config();
} catch (const std::exception& e) {
LOG_WARN(std::string("[desktop] load_config failed, using defaults: ") + e.what());
}
std::string desktop_effective_locale = acecode::desktop::resolve_ui_locale(
desktop_cfg.ui.locale, desktop_system_locale);
startup_locale = desktop_effective_locale;
acecode::desktop::set_native_locale(desktop_effective_locale);
LOG_INFO("[desktop] GUI locale preference=" + desktop_cfg.ui.locale +
" effective=" + desktop_effective_locale);
mark_startup("config_load_end");
std::string daemon_exe = locate_daemon_exe();
if (daemon_exe.empty()) {
splash.close();
#ifdef _WIN32
show_error(format_daemon_missing_message(native_locale()));
#endif
return 1;
}
// dev 模式探测 — 找到 web/ 后所有 spawn 出来的 daemon 都拿这个 static_dir
std::string dev_web_dir = detect_dev_web_dir();
if (!dev_web_dir.empty()) {
LOG_INFO("[desktop] dev mode: serving web/ from " + dev_web_dir +
" (file changes hot-reload on F5)");
}
std::string proj_dir = projects_dir();
std::error_code ec;
fs::create_directories(proj_dir, ec); // 首次启动时不存在
// 1. 扫已有 workspace
mark_startup("workspace_scan_begin");
WorkspaceRegistry registry;
registry.scan(proj_dir);
log_legacy_workspace_run_dirs(proj_dir);
mark_startup("workspace_scan_end");
// 2. 决定 active workspace
std::string last_active = acecode::read_last_active_workspace_hash();
std::string proc_cwd = current_cwd();
std::optional<WorkspaceMeta> startup_open_workspace;
if (startup_open_request.has_value()) {
if (!is_existing_directory(startup_open_request->cwd)) {
LOG_WARN("[desktop] requested TUI workspace is unavailable: " +
startup_open_request->cwd);
} else {
startup_open_workspace =
registry.register_new(proj_dir, startup_open_request->cwd);
LOG_INFO("[desktop] registered requested TUI workspace hash=" +
startup_open_workspace->hash + " cwd=" +
startup_open_workspace->cwd);
}
}
std::string active_hash = startup_open_workspace.has_value()
? startup_open_workspace->hash
: pick_active(last_active, proc_cwd, registry);
if (!active_hash.empty()) {
auto active_meta = registry.get(active_hash);
if (active_meta && !is_existing_directory(active_meta->cwd)) {
LOG_WARN("[desktop] active workspace cwd unavailable, falling back: hash=" +
active_meta->hash + " cwd=" + active_meta->cwd);
active_hash.clear();
for (const auto& candidate : registry.list()) {
if (is_existing_directory(candidate.cwd)) {
active_hash = candidate.hash;
LOG_INFO("[desktop] selected fallback workspace hash=" + active_hash +
" cwd=" + candidate.cwd);
break;
}
}
}
}
// 没有任何显式可见 workspace 时保持 onboarding。不要把 process cwd 自动
// 注册进 Desktop,否则首次打开会重新暴露 TUI 里用过的历史目录。
// 3. pool 准备 + 提前 activate daemon(在创建窗口前)
//
// 启动闪屏修复:webview 库在自建窗口路径里会硬编码 ShowWindow(SW_SHOW)
// + 默认 640×480。这里改走 WebHost 自建父窗口路径,先在屏幕外渲染。
//
// 当前做法:
// a) 把 daemon activate 提到 WebHost 构造之前 — 窗口出现时 URL 就绪
// b) WebView2 parent 不 hide,只是在屏幕外可见,避免 hidden controller
// 暂停渲染,同时用户只能看到透明 icon。
DaemonPool pool;
pool.set_keep_alive_on_exit(
desktop_cfg.desktop.continue_background_process);
auto configure_managed_request =
[&](ActivateRequest& request) {
request.run_dir = shared_run_dir;
request.desktop_managed = true;
request.desktop_owner_pid = desktop_owner_pid;
request.desktop_owner_instance = desktop_owner_instance;
};
std::mutex active_mu;
std::string active_hash_dynamic = active_hash; // 后续切 workspace 时更新
std::string url = onboarding_url();
const bool daemon_activation_attempted =
!active_hash.empty() || !proc_cwd.empty();
bool daemon_activation_recorded = false;
if (daemon_activation_attempted) {
mark_startup("daemon_activate_begin");
}
if (!active_hash.empty()) {
auto m = registry.get(active_hash);
if (m) {
const bool workspace_available = is_existing_directory(m->cwd);
std::string launch_cwd = choose_launch_cwd(m->cwd, proc_cwd, daemon_exe);
if (launch_cwd.empty()) {
LOG_ERROR("[desktop] no usable cwd available to start daemon");
} else if (!workspace_available) {
LOG_WARN("[desktop] starting shared daemon from fallback cwd=" + launch_cwd +
" because workspace cwd is unavailable: " + m->cwd);
}
ActivateRequest req;
req.hash = kSharedDaemonSlotHash;
req.cwd = launch_cwd;
req.daemon_exe_path = daemon_exe;
req.static_dir = dev_web_dir;
req.context_id = kSharedDaemonContextId;
configure_managed_request(req);
req.native_folder_picker_enabled = true;
ActivateResult r;
if (launch_cwd.empty()) {
r.error = "no usable working directory for daemon";
} else {
r = pool.activate(req);
}
if (r.ok) {
daemon_activation_recorded = true;
mark_startup("daemon_activate_end");
std::string werr;
if (workspace_available) {
mark_startup("workspace_register_begin");
if (!post_workspace_to_daemon(r.port, r.token, m->cwd, werr)) {
LOG_ERROR("[desktop] post_workspace failed during startup: " + werr);
mark_startup("workspace_register_failed");
} else {
mark_startup("workspace_register_end");
}
}
url = build_loopback_url(r.port, r.token);
} else {
daemon_activation_recorded = true;
mark_startup("daemon_activate_failed");
#ifdef _WIN32
show_error(format_daemon_workspace_failed_message(
m->name, r.error, native_locale()));
#endif
// 不致命退出 — 仍打开 onboarding,用户可重试 / 切其它 workspace
}
}
} else if (!proc_cwd.empty()) {
// 没有显式可见 workspace 时仍要启动 shared daemon 来 serve Web UI。
// 关键点:这里只启动 daemon,不 POST /api/workspaces,也不 register_new。
// daemon worker 的 ensure_workspace_metadata 会写 desktop_visible=false,
// 所以前端拿到的 workspace 列表仍为空,只显示"添加项目"入口。
std::string launch_cwd = choose_launch_cwd(proc_cwd, proc_cwd, daemon_exe);
ActivateRequest req;
req.hash = kSharedDaemonSlotHash;
req.cwd = launch_cwd;
req.daemon_exe_path = daemon_exe;
req.static_dir = dev_web_dir;
req.context_id = kSharedDaemonContextId;
configure_managed_request(req);
req.native_folder_picker_enabled = true;
ActivateResult r;
if (launch_cwd.empty()) {
r.error = "no usable working directory for daemon";
} else {
r = pool.activate(req);