forked from lemonade-sdk/lemonade
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtray_app.cpp
More file actions
3447 lines (3018 loc) · 133 KB
/
Copy pathtray_app.cpp
File metadata and controls
3447 lines (3018 loc) · 133 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 "lemon_tray/tray_app.h"
#include "lemon_tray/agent_launcher.h"
#ifdef _WIN32
#include "lemon_tray/platform/windows_tray.h" // For set_menu_update_callback
#endif
#include "LemonadeServiceManager.h" // For macOS service management
#include <lemon/single_instance.h>
#include <lemon/version.h>
#include <lemon/utils/process_manager.h>
#include <lemon/utils/path_utils.h>
#include <httplib.h>
#include <lemon/utils/aixlog.hpp>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <filesystem>
#include <algorithm>
#include <thread>
#include <chrono>
#include <csignal>
#include <cctype>
#include <vector>
#include <set>
#include <optional>
#ifdef _WIN32
#include <winsock2.h> // Must come before windows.h
#include <windows.h>
#include <shellapi.h>
#include <iphlpapi.h>
#include <tlhelp32.h>
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
#else
#include <cstdlib>
#include <cstring> // for strerror
#include <unistd.h> // for readlink
#include <sys/wait.h> // for waitpid
#include <sys/file.h> // for flock
#include <fcntl.h> // for open
#include <cerrno> // for errno
#ifdef HAVE_SYSTEMD
#include <systemd/sd-login.h>
#endif // HAVE_SYSTEMD
#endif // !_WIN32
#include "lemon_tray/platform/linux_systemd.h"
#ifdef __APPLE__
#include <mach-o/dyld.h> // for _NSGetExecutablePath
#endif
namespace fs = std::filesystem;
namespace lemon_tray {
// Helper function to detect if a path is a local filesystem path
// Returns true for absolute paths (Windows: C:\... or D:\..., Unix: /...)
static bool is_local_path(const std::string& path) {
if (path.empty()) return false;
// Windows absolute path: C:\... or D:\... (also handles forward slashes)
if (path.length() >= 3 && std::isalpha(static_cast<unsigned char>(path[0])) &&
path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
return true;
}
// Unix absolute path: /...
if (path[0] == '/') {
return true;
}
return false;
}
// Normalize a host string into one that is valid for outgoing connections.
// "0.0.0.0" is a bind-all address, not a connection target.
// "localhost" can resolve to IPv6 (::1) on some systems, which fails if the
// server only listens on IPv4. Both are mapped to "127.0.0.1".
static std::string normalize_connect_host(const std::string& host) {
if (host.empty() || host == "0.0.0.0" || host == "localhost") {
return "127.0.0.1";
}
return host;
}
static std::string trim_whitespace(const std::string& value) {
const auto begin = value.find_first_not_of(" \t\r\n");
if (begin == std::string::npos) {
return "";
}
const auto end = value.find_last_not_of(" \t\r\n");
return value.substr(begin, end - begin + 1);
}
static std::string build_launch_llamacpp_args(const lemon::TrayConfig& tray_config) {
static const std::string default_args = "-b 16384 -ub 16384 -fa on";
const std::string trimmed_user_args = trim_whitespace(tray_config.launch_llamacpp_args);
if (tray_config.launch_use_recipe) {
return trimmed_user_args;
}
if (!trimmed_user_args.empty()) {
return trimmed_user_args;
}
return default_args;
}
static nlohmann::json build_launch_recipe_options(const lemon::TrayConfig& tray_config) {
nlohmann::json recipe_options = nlohmann::json::object();
const std::string merged_args = build_launch_llamacpp_args(tray_config);
if (!merged_args.empty()) {
recipe_options["llamacpp_args"] = merged_args;
}
return recipe_options;
}
#ifndef _WIN32
// Initialize static signal pipe
int TrayApp::signal_pipe_[2] = {-1, -1};
#endif
#ifdef _WIN32
// Helper function to show a simple Windows notification without tray
static void show_simple_notification(const std::string& title, const std::string& message) {
// Convert UTF-8 to wide string
auto utf8_to_wstring = [](const std::string& str) -> std::wstring {
if (str.empty()) return std::wstring();
int size_needed = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
std::wstring result(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &result[0], size_needed);
if (!result.empty() && result.back() == L'\0') {
result.pop_back();
}
return result;
};
// Create a temporary window class and window for the notification
WNDCLASSW wc = {};
wc.lpfnWndProc = DefWindowProcW;
wc.hInstance = GetModuleHandle(nullptr);
wc.lpszClassName = L"LemonadeNotifyClass";
RegisterClassW(&wc);
HWND hwnd = CreateWindowW(L"LemonadeNotifyClass", L"", 0, 0, 0, 0, 0, nullptr, nullptr, wc.hInstance, nullptr);
if (hwnd) {
NOTIFYICONDATAW nid = {};
nid.cbSize = sizeof(nid);
nid.hWnd = hwnd;
nid.uID = 1;
nid.uFlags = NIF_INFO | NIF_ICON;
nid.dwInfoFlags = NIIF_INFO;
// Use default icon
nid.hIcon = LoadIcon(nullptr, IDI_INFORMATION);
std::wstring title_wide = utf8_to_wstring(title);
std::wstring message_wide = utf8_to_wstring(message);
wcsncpy_s(nid.szInfoTitle, title_wide.c_str(), _TRUNCATE);
wcsncpy_s(nid.szInfo, message_wide.c_str(), _TRUNCATE);
wcsncpy_s(nid.szTip, L"Lemonade Server", _TRUNCATE);
// Add the icon and show notification
Shell_NotifyIconW(NIM_ADD, &nid);
// Keep it displayed briefly then clean up
std::this_thread::sleep_for(std::chrono::milliseconds(100));
Shell_NotifyIconW(NIM_DELETE, &nid);
DestroyWindow(hwnd);
}
UnregisterClassW(L"LemonadeNotifyClass", GetModuleHandle(nullptr));
}
#endif
// Global pointer to the current TrayApp instance for signal handling
static TrayApp* g_tray_app_instance = nullptr;
#ifdef _WIN32
// Windows Ctrl+C handler
BOOL WINAPI console_ctrl_handler(DWORD ctrl_type) {
if (ctrl_type == CTRL_C_EVENT || ctrl_type == CTRL_CLOSE_EVENT || ctrl_type == CTRL_BREAK_EVENT) {
std::cout << "\nReceived interrupt signal, shutting down gracefully..." << std::endl;
std::cout.flush();
if (g_tray_app_instance) {
g_tray_app_instance->shutdown();
}
// Exit the process explicitly to ensure cleanup completes
// Windows will wait for this handler to return before terminating
std::exit(0);
}
return FALSE;
}
#else
// Unix signal handler for SIGINT/SIGTERM
void signal_handler(int signal) {
if (signal == SIGINT) {
// SIGINT = User pressed Ctrl+C
// We MUST clean up children ourselves
// Write to pipe - main thread will handle cleanup
// write() is async-signal-safe
char sig = (char)signal;
ssize_t written = write(TrayApp::signal_pipe_[1], &sig, 1);
(void)written; // Suppress unused variable warning
} else if (signal == SIGTERM) {
// SIGTERM = Stop command is killing us
// Stop command will handle killing children
// Just exit immediately to avoid race condition
std::cout << "\nReceived termination signal, exiting..." << std::endl;
std::cout.flush();
_exit(0);
}
}
// SIGCHLD handler to automatically reap zombie children
void sigchld_handler(int signal) {
// Reap all zombie children without blocking
// This prevents the router process from becoming a zombie
int status;
while (waitpid(-1, &status, WNOHANG) > 0) {
// Child reaped successfully
}
}
// Helper function to check if a process is alive (and not a zombie)
static bool is_process_alive_not_zombie(pid_t pid) {
if (pid <= 0) return false;
// First check if process exists at all
if (kill(pid, 0) != 0) {
return false; // Process doesn't exist
}
#ifdef __APPLE__
// macOS doesn't have /proc — if kill(pid, 0) succeeded, process is alive
// macOS automatically reaps zombies more aggressively, so just trust kill()
return true;
#else
// Check if it's a zombie by reading /proc/PID/stat
std::string stat_path = "/proc/" + std::to_string(pid) + "/stat";
std::ifstream stat_file(stat_path);
if (!stat_file) {
return false; // Can't read stat, assume dead
}
std::string line;
std::getline(stat_file, line);
// Find the state character (after the closing paren of the process name)
size_t paren_pos = line.rfind(')');
if (paren_pos != std::string::npos && paren_pos + 2 < line.length()) {
char state = line[paren_pos + 2];
// Return false if zombie
return (state != 'Z');
}
// If we can't parse the state, assume alive to be safe
return true;
#endif
}
#endif
TrayApp::TrayApp(const lemon::ServerConfig& server_config, const lemon::TrayConfig& tray_config)
: current_version_(LEMON_VERSION_STRING)
, should_exit_(false)
, server_config_(server_config)
, tray_config_(tray_config)
#ifdef _WIN32
, electron_app_process_(nullptr)
, electron_job_object_(nullptr)
#else
, electron_app_pid_(0)
#endif
{
g_tray_app_instance = this;
#ifdef _WIN32
SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
#else
// Create self-pipe for safe signal handling
if (pipe(signal_pipe_) == -1) {
std::cerr << "Failed to create signal pipe: " << strerror(errno) << std::endl;
exit(1);
}
// Set write end to non-blocking to prevent signal handler from blocking
int flags = fcntl(signal_pipe_[1], F_GETFL);
if (flags != -1) {
fcntl(signal_pipe_[1], F_SETFL, flags | O_NONBLOCK);
}
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
// Install SIGCHLD handler to automatically reap zombie children
// This prevents the router process from becoming a zombie when it exits
signal(SIGCHLD, sigchld_handler);
#endif
LOG(DEBUG, "TrayApp") << "Signal handlers installed" << std::endl;
}
TrayApp::~TrayApp() {
// Stop signal monitor thread if running
#ifndef _WIN32
if (signal_monitor_thread_.joinable()) {
stop_signal_monitor_ = true;
signal_monitor_thread_.join();
}
#endif
// Only shutdown if we actually started something
if (server_manager_ || !tray_config_.command.empty()) {
shutdown();
}
#ifndef _WIN32
// Clean up signal pipe
if (signal_pipe_[0] != -1) {
close(signal_pipe_[0]);
close(signal_pipe_[1]);
signal_pipe_[0] = signal_pipe_[1] = -1;
}
#endif
g_tray_app_instance = nullptr;
}
int TrayApp::run() {
LOG(DEBUG, "TrayApp") << "TrayApp::run() starting..." << std::endl;
LOG(DEBUG, "TrayApp") << "Command: " << tray_config_.command << std::endl;
bool server_already_running = false;
bool run_command_already_executed = false;
// Find server binary automatically (not needed for launch/status/stop)
if (server_binary_.empty() && tray_config_.command != "launch" &&
tray_config_.command != "status" && tray_config_.command != "stop") {
LOG(DEBUG, "TrayApp") << "Searching for server binary..." << std::endl;
if (!find_server_binary()) {
std::cerr << "Error: Could not find lemonade-router binary" << std::endl;
#ifdef _WIN32
std::cerr << "Please ensure lemonade-router.exe is in the same directory" << std::endl;
#else
std::cerr << "Please ensure lemonade-router is in the same directory or in PATH" << std::endl;
#endif
return 1;
}
}
LOG(DEBUG, "TrayApp") << "Using server binary: " << server_binary_ << std::endl;
// Handle commands
if (tray_config_.command == "list") {
return execute_list_command();
} else if (tray_config_.command == "pull") {
return execute_pull_command();
} else if (tray_config_.command == "delete") {
return execute_delete_command();
} else if (tray_config_.command == "status") {
return execute_status_command();
} else if (tray_config_.command == "stop") {
return execute_stop_command();
} else if (tray_config_.command == "recipes") {
return execute_recipes_command();
} else if (tray_config_.command == "logs") {
return execute_logs_command();
} else if (tray_config_.command == "launch") {
return execute_launch_command();
} else if (tray_config_.command == "serve" || tray_config_.command == "run") {
auto connect_to_running_server = [this, &server_already_running, &run_command_already_executed](const char* context) -> int {
std::cout << "Lemonade Server is " << context << " already running. Connecting to it..." << std::endl;
auto [pid, running_port] = get_server_info();
(void)pid;
if (running_port == 0) {
std::cerr << "Error: Could not connect to running server" << std::endl;
return 1;
}
server_config_.host = normalize_connect_host(server_config_.host);
server_manager_ = std::make_unique<ServerManager>(server_config_.host, running_port);
server_config_.port = running_port;
server_already_running = true;
if (tray_config_.command == "run") {
int result = execute_run_command();
if (result != 0) {
return result;
}
run_command_already_executed = true;
}
return 0;
};
#ifdef HAVE_SYSTEMD
if (tray_config_.command == "run" &&
is_systemd_any_service_active_other_process()) {
int result = connect_to_running_server("managed by systemd and");
if (result != 0) {
return result;
}
// Continue to tray initialization below
}
#endif
// Check for single instance - only for 'serve' and 'run' commands
// Other commands (status, list, pull, delete, stop) can run alongside a server
if (lemon::SingleInstance::IsAnotherInstanceRunning("Server")) {
// If 'run' command and server is already running, connect to it and execute the run command
if (tray_config_.command == "run") {
int result = connect_to_running_server("");
if (result != 0) {
return result;
}
// Continue to tray initialization below
} else {
// For 'serve' command, don't allow duplicate servers
#ifdef _WIN32
show_simple_notification("Server Already Running", "Lemonade Server is already running");
#endif
std::cerr << "Error: Another instance of lemonade-server serve is already running.\n"
<< "Only one persistent server can run at a time.\n\n"
<< "To check server status: lemonade-server status\n"
<< "To stop the server: lemonade-server stop\n" << std::endl;
return 1;
}
}
// Continue to server initialization below
} else if (tray_config_.command == "tray") {
// Check for single instance - prevent duplicate tray processes,
// the use case here is not for a tray launched by the system its when its being launched by the user or electron app.
#ifdef __APPLE__
if (LemonadeServiceManager::isTrayActive())
{
std::cout << "Lemonade Tray is already running." << std::endl;
return 0;
}
// isTrayActive won't work for when the tray is launched as a service, that requires a bunch of other permissions
// Permissions that have to be entered into a plist and its beyond the scope of this PR, maybe TODO?
if (lemon::SingleInstance::IsAnotherInstanceRunning("Tray")) {
std::cout << "Lemonade Tray is already running." << std::endl;
return 0;
}
#else
if (lemon::SingleInstance::IsAnotherInstanceRunning("Tray")) {
std::cout << "Lemonade Tray is already running." << std::endl;
return 0;
}
#endif
#ifdef __APPLE__
// macOS: Tray mode - show tray, starting server service if necessary
// Check if server service is already running
if (lemon::SingleInstance::IsAnotherInstanceRunning("Server") || LemonadeServiceManager::isServerActive()) {
// Server is already running - get its port and connect
auto [pid, running_port] = get_server_info();
bool server_was_running = (running_port != 0);
if (running_port != 0) {
std::cout << "Connected to Lemonade Server on port " << running_port << std::endl;
// Create server manager to communicate with running server
server_config_.host = normalize_connect_host(server_config_.host);
server_manager_ = std::make_unique<ServerManager>(server_config_.host, running_port);
server_manager_->set_port(running_port);
server_config_.port = running_port; // Update config to match running server
} else {
std::cerr << "Error: Server service is active but no port found: " << running_port << std::endl;
return 1;
}
} else {
// Server is not running - start the service
std::cout << "Starting Lemonade Server service..." << std::endl;
LemonadeServiceManager::startServer();
// Wait for the service to start (up to 30 seconds)
int max_wait = 5;
for (int i = 0; i < max_wait; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
auto [pid, running_port] = get_server_info();
if (running_port != 0) {
std::cout << "Server service started on port " << running_port << std::endl;
// Create server manager to communicate with running server
server_config_.host = normalize_connect_host(server_config_.host);
server_manager_ = std::make_unique<ServerManager>(server_config_.host, server_config_.port);
server_manager_->set_port(running_port);
server_config_.port = running_port; // Update config to match running server
// Continue to tray initialization below
break;
}
if (i == max_wait - 1) {
std::cerr << "Error: Server service failed to start within 30 seconds" << std::endl;
return 1;
}
}
}
#elif !defined(_WIN32)
// Linux/Unix: Try to connect to running server, or start one
{
auto [pid, running_port] = get_server_info();
if (running_port != 0) {
// Server is already running — connect to it
// Track PID only for non-systemd processes (systemd ones are tracked by unit name)
if (!is_any_systemd_service_active()) {
external_server_pid_ = pid;
}
server_config_.host = normalize_connect_host(server_config_.host);
server_manager_ = std::make_unique<ServerManager>(server_config_.host, running_port);
server_manager_->set_port(running_port);
server_config_.port = running_port;
std::cout << "Connected to Lemonade Server on port " << running_port << std::endl;
} else {
// No server running — try to start one
bool started = false;
#ifdef HAVE_SYSTEMD
auto unit = get_first_known_systemd_unit();
if (unit) {
std::cout << "Starting server via systemd: " << unit.name << std::endl;
if (systemd_control_service(unit, /*start=*/true)) {
// Wait up to 10 seconds for server to appear
for (int i = 0; i < 10 && !started; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
auto [spid, sport] = get_server_info();
if (sport != 0) {
server_config_.host = normalize_connect_host(server_config_.host);
server_manager_ = std::make_unique<ServerManager>(server_config_.host, sport);
server_manager_->set_port(sport);
server_config_.port = sport;
started = true;
}
}
}
}
#endif
if (!started) {
// No systemd unit available — spawn lemonade-router directly
std::cout << "Starting Lemonade Server..." << std::endl;
server_config_.host = normalize_connect_host(server_config_.host);
server_manager_ = std::make_unique<ServerManager>(server_config_.host, server_config_.port);
if (!start_server()) {
std::cerr << "Error: Failed to start Lemonade Server" << std::endl;
return 1;
}
process_owns_server_ = true;
}
}
}
#endif // !__APPLE__ && !_WIN32
} else {
std::cerr << "Internal Error: Unhandled command '" << tray_config_.command << "'\n" << std::endl;
return 1;
}
if (!server_already_running && tray_config_.command != "tray") {
// Create server manager
LOG(DEBUG, "TrayApp") << "Creating server manager..." << std::endl;
server_manager_ = std::make_unique<ServerManager>(server_config_.host, server_config_.port);
// Start server
LOG(DEBUG, "TrayApp") << "Starting server..." << std::endl;
if (!start_server()) {
std::cerr << "Error: Failed to start server" << std::endl;
return 1;
}
LOG(DEBUG, "TrayApp") << "Server started successfully!" << std::endl;
if (tray_config_.command == "serve" && tray_config_.save_options) {
tray_config_.save_options = false;
std::cerr << "Warning: Argument --save-options only available for the run command. Ignoring.\n";
}
process_owns_server_ = true;
}
// If this is the 'run' command, load the model and run electron app
if (tray_config_.command == "run" && !run_command_already_executed) {
int result = execute_run_command();
if (result != 0) {
return result;
}
}
// If no-tray mode, just wait for server to exit
if (tray_config_.no_tray) {
if (!is_service_active()) {
std::cout << "Press Ctrl+C to stop" << std::endl;
}
#ifdef _WIN32
// Windows: simple sleep loop (signal handler handles Ctrl+C via console_ctrl_handler)
if (server_already_running) {
while (!should_exit_) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
} else {
while (server_manager_->is_server_running()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
#else
// Linux: monitor signal pipe using select() for proper signal handling
while (server_already_running || server_manager_->is_server_running()) {
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(signal_pipe_[0], &readfds);
struct timeval tv = {1, 0}; // 1 second timeout
int result = select(signal_pipe_[0] + 1, &readfds, nullptr, nullptr, &tv);
if (result > 0 && FD_ISSET(signal_pipe_[0], &readfds)) {
// Signal received (SIGINT from Ctrl+C)
char sig;
ssize_t bytes_read = read(signal_pipe_[0], &sig, 1);
(void)bytes_read; // Suppress unused variable warning
std::cout << "\nReceived interrupt signal, shutting down..." << std::endl;
// Now we're safely in the main thread - call shutdown properly
shutdown();
break;
}
if (!server_already_running && !server_manager_->is_server_running()) {
break;
}
// Timeout or error - just continue checking if server is still running
}
#endif
return 0;
}
// Create tray application
tray_ = create_tray();
if (!tray_) {
std::cerr << "Error: Failed to create tray for this platform" << std::endl;
return 1;
}
LOG(DEBUG, "TrayApp") << "Tray created successfully" << std::endl;
// Set ready callback
LOG(DEBUG, "TrayApp") << "Setting ready callback..." << std::endl;
tray_->set_ready_callback([this]() {
LOG(DEBUG, "TrayApp") << "Ready callback triggered!" << std::endl;
show_notification("Woohoo!", "Lemonade Server is running! Right-click the tray icon to access options.");
});
// Set menu update callback to refresh state before showing menu (Windows only)
LOG(DEBUG, "TrayApp") << "Setting menu update callback..." << std::endl;
#ifdef _WIN32
if (auto* windows_tray = dynamic_cast<WindowsTray*>(tray_.get())) {
windows_tray->set_menu_update_callback([this]() {
LOG(DEBUG, "TrayApp") << "Refreshing menu state from server..." << std::endl;
refresh_menu();
});
}
#endif
// Find icon path (matching the CMake resources structure)
LOG(DEBUG, "TrayApp") << "Searching for icon..." << std::endl;
std::string icon_path;
#ifdef __APPLE__
// On macOS, look for icon in /Library/Application Support/lemonade/resources
icon_path = "/Library/Application Support/lemonade/resources/static/favicon.ico";
LOG(DEBUG, "TrayApp") << "Checking macOS Application Support icon at: " << icon_path << std::endl;
if (!fs::exists(icon_path)) {
std::cout << "WARNING: Icon not found at /Library/Application Support/lemonade/resources/favicon.ico, will use default icon" << std::endl;
} else {
LOG(DEBUG, "TrayApp") << "Icon found at: " << icon_path << std::endl;
}
#elif defined(__linux__)
// On Linux, search XDG data directories for the installed icon first.
// The SVG in the hicolor icon theme is the preferred format for AppIndicator3.
{
std::vector<std::string> data_dirs;
// XDG_DATA_HOME takes priority (defaults to ~/.local/share)
const char* xdg_data_home = getenv("XDG_DATA_HOME");
if (xdg_data_home && xdg_data_home[0]) {
data_dirs.push_back(xdg_data_home);
} else {
const char* home = getenv("HOME");
if (home && home[0]) data_dirs.push_back(std::string(home) + "/.local/share");
}
// Then XDG_DATA_DIRS (system-wide locations)
const char* xdg_data_dirs = getenv("XDG_DATA_DIRS");
if (xdg_data_dirs && xdg_data_dirs[0]) {
std::istringstream ss(xdg_data_dirs);
std::string d;
while (std::getline(ss, d, ':')) {
if (!d.empty()) data_dirs.push_back(d);
}
} else {
data_dirs.push_back("/usr/local/share");
data_dirs.push_back("/usr/share");
data_dirs.push_back("/opt/lemonade/share");
}
for (const auto& d : data_dirs) {
// Preferred: SVG in the hicolor icon theme (installed by RPM/DEB)
auto svg = fs::path(d) / "icons/hicolor/scalable/apps/ai.lemonade_server.Lemonade.svg";
if (fs::exists(svg)) {
icon_path = svg.string();
LOG(DEBUG, "TrayApp") << "Icon found in hicolor theme: " << icon_path << std::endl;
break;
}
// Fallback: favicon.ico in the lemonade-server share directory
auto ico = fs::path(d) / "lemonade-server/resources/static/favicon.ico";
if (fs::exists(ico)) {
icon_path = ico.string();
LOG(DEBUG, "TrayApp") << "Icon found in share dir: " << icon_path << std::endl;
break;
}
}
}
if (icon_path.empty()) {
// Development build: try relative to CWD and executable directory
fs::path exe_path = fs::path(server_binary_).parent_path();
std::vector<fs::path> dev_paths = {
"resources/static/favicon.ico",
exe_path / "resources" / "static" / "favicon.ico",
exe_path / "resources" / "favicon.ico",
};
for (const auto& p : dev_paths) {
if (fs::exists(p)) {
icon_path = p.string();
LOG(DEBUG, "TrayApp") << "Icon found (dev path): " << icon_path << std::endl;
break;
}
}
}
if (icon_path.empty()) {
LOG(WARNING, "TrayApp") << "Icon not found at any known location; will use default icon" << std::endl;
}
#else
// On Windows and other platforms, find icon file path
icon_path = "resources/static/favicon.ico";
LOG(DEBUG, "TrayApp") << "Checking icon at: " << fs::absolute(icon_path).string() << std::endl;
if (!fs::exists(icon_path)) {
// Try relative to executable directory
fs::path exe_path = fs::path(server_binary_).parent_path();
icon_path = (exe_path / "resources" / "static" / "favicon.ico").string();
LOG(DEBUG, "TrayApp") << "Icon not found, trying: " << icon_path << std::endl;
// If still not found, try without static subdir (fallback)
if (!fs::exists(icon_path)) {
icon_path = (exe_path / "resources" / "favicon.ico").string();
LOG(DEBUG, "TrayApp") << "Icon not found, trying fallback: " << icon_path << std::endl;
}
}
if (fs::exists(icon_path)) {
LOG(DEBUG, "TrayApp") << "Icon found at: " << icon_path << std::endl;
} else {
std::cout << "WARNING: Icon not found at any location, will use default icon" << std::endl;
}
#endif
// Initialize tray
LOG(DEBUG, "TrayApp") << "Initializing tray with icon: " << icon_path << std::endl;
if (!tray_->initialize("Lemonade Server", icon_path)) {
std::cerr << "Error: Failed to initialize tray" << std::endl;
return 1;
}
LOG(DEBUG, "TrayApp") << "Tray initialized successfully" << std::endl;
// Build initial menu
LOG(DEBUG, "TrayApp") << "Building menu..." << std::endl;
build_menu();
LOG(DEBUG, "TrayApp") << "Menu built successfully" << std::endl;
#ifndef _WIN32
// On Linux, start a background thread to monitor the signal pipe
// This allows us to handle Ctrl+C cleanly even when tray is running
LOG(DEBUG, "TrayApp") << "Starting signal monitor thread..." << std::endl;
signal_monitor_thread_ = std::thread([this]() {
auto last_tick = std::chrono::steady_clock::now();
while (!stop_signal_monitor_ && !should_exit_) {
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(signal_pipe_[0], &readfds);
struct timeval tv = {0, 100000}; // 100ms timeout
int result = select(signal_pipe_[0] + 1, &readfds, nullptr, nullptr, &tv);
// Check if 5 seconds have passed, refresh menu (both macOS and Linux)
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(now - last_tick).count() >= 5) {
LOG(DEBUG, "TrayApp") << "Checking if menu needs refresh" << std::endl;
refresh_menu();
last_tick = now;
}
if (result > 0 && FD_ISSET(signal_pipe_[0], &readfds)) {
// Signal received (SIGINT from Ctrl+C)
char sig;
ssize_t bytes_read = read(signal_pipe_[0], &sig, 1);
(void)bytes_read; // Suppress unused variable warning
std::cout << "\nReceived interrupt signal, shutting down..." << std::endl;
// Call shutdown from this thread (not signal context, so it's safe)
shutdown();
break;
}
}
LOG(DEBUG, "TrayApp") << "Signal monitor thread exiting" << std::endl;
});
#endif
LOG(DEBUG, "TrayApp") << "Menu built, entering event loop..." << std::endl;
// Run tray event loop
tray_->run();
//Initialize thread to constantly update the tray models
LOG(DEBUG, "TrayApp") << "Event loop exited" << std::endl;
return 0;
}
bool TrayApp::find_server_binary() {
// Look for lemonade binary in common locations
std::vector<std::string> search_paths;
#ifdef _WIN32
std::string binary_name = "lemonade-router.exe";
// Get the directory where this executable is located
char exe_path_buf[MAX_PATH];
DWORD len = GetModuleFileNameA(NULL, exe_path_buf, MAX_PATH);
if (len > 0) {
fs::path exe_dir = fs::path(exe_path_buf).parent_path();
// First priority: same directory as this executable
search_paths.push_back((exe_dir / binary_name).string());
}
#else
std::string binary_name = "lemonade-router";
// On Unix, try to get executable path
char exe_path_buf[1024];
bool got_exe_path = false;
#ifdef __APPLE__
// macOS: Use _NSGetExecutablePath
uint32_t bufsize = sizeof(exe_path_buf);
if (_NSGetExecutablePath(exe_path_buf, &bufsize) == 0) {
got_exe_path = true;
}
#else
// Linux: Use /proc/self/exe
ssize_t len = readlink("/proc/self/exe", exe_path_buf, sizeof(exe_path_buf) - 1);
if (len != -1) {
exe_path_buf[len] = '\0';
got_exe_path = true;
}
#endif
if (got_exe_path) {
fs::path exe_dir = fs::path(exe_path_buf).parent_path();
search_paths.push_back((exe_dir / binary_name).string());
}
#endif
// Current directory
search_paths.push_back(binary_name);
// Parent directory
search_paths.push_back("../" + binary_name);
// Common install locations
#ifdef _WIN32
search_paths.push_back("C:/Program Files/Lemonade/" + binary_name);
#else
search_paths.push_back("/opt/bin/" + binary_name);
search_paths.push_back("/usr/bin/" + binary_name);
#endif
for (const auto& path : search_paths) {
if (fs::exists(path)) {
server_binary_ = fs::absolute(path).string();
LOG(DEBUG, "TrayApp") << "Found server binary: " << server_binary_ << std::endl;
return true;
}
}
return false;
}
bool TrayApp::setup_logging() {
// TODO: Implement logging setup
return true;
}
bool TrayApp::is_server_running_on_port(int port) {
try {
auto health = server_manager_->get_health();
return true;
} catch (...) {
return false;
}
}
static bool http_server_alive(int port) {
httplib::Client cli("localhost", port);
cli.set_connection_timeout(1);
cli.set_read_timeout(1);
auto res = cli.Get("/api/version");
return res != nullptr;
}
std::pair<int, int> TrayApp::get_server_info() {
// Query OS for listening TCP connections and find lemonade-router.exe
#ifdef _WIN32
// Windows: Use GetExtendedTcpTable to find listening connections
// Check both IPv4 and IPv6 since server may bind to either
// Helper lambda to check if a PID is lemonade-router.exe
auto is_lemonade_router = [](DWORD pid) -> bool {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (hProcess) {
WCHAR processName[MAX_PATH];
DWORD size = MAX_PATH;
if (QueryFullProcessImageNameW(hProcess, 0, processName, &size)) {
std::wstring fullPath(processName);
std::wstring exeName = fullPath.substr(fullPath.find_last_of(L"\\/") + 1);
CloseHandle(hProcess);
return (exeName == L"lemonade-router.exe");
}
CloseHandle(hProcess);
}
return false;
};
// Collect all listening ports for lemonade-router.exe.
// The router listens on multiple ports (HTTP + WebSocket), so we must
// identify the HTTP port rather than returning whichever appears first
// in the TCP table (which is non-deterministic).
int router_pid = 0;
std::set<int> candidate_ports;
// Scan IPv4 connections
DWORD size = 0;
GetExtendedTcpTable(nullptr, &size, FALSE, AF_INET, TCP_TABLE_OWNER_PID_LISTENER, 0);
std::vector<BYTE> buffer(size);
PMIB_TCPTABLE_OWNER_PID pTcpTable = reinterpret_cast<PMIB_TCPTABLE_OWNER_PID>(buffer.data());
if (GetExtendedTcpTable(pTcpTable, &size, FALSE, AF_INET, TCP_TABLE_OWNER_PID_LISTENER, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTcpTable->dwNumEntries; i++) {
DWORD pid = pTcpTable->table[i].dwOwningPid;
int port = ntohs((u_short)pTcpTable->table[i].dwLocalPort);
if (is_lemonade_router(pid)) {
router_pid = static_cast<int>(pid);
candidate_ports.insert(port);
}
}
}
// Also scan IPv6 connections
size = 0;
GetExtendedTcpTable(nullptr, &size, FALSE, AF_INET6, TCP_TABLE_OWNER_PID_LISTENER, 0);
buffer.resize(size);
PMIB_TCP6TABLE_OWNER_PID pTcp6Table = reinterpret_cast<PMIB_TCP6TABLE_OWNER_PID>(buffer.data());
if (GetExtendedTcpTable(pTcp6Table, &size, FALSE, AF_INET6, TCP_TABLE_OWNER_PID_LISTENER, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTcp6Table->dwNumEntries; i++) {
DWORD pid = pTcp6Table->table[i].dwOwningPid;
int port = ntohs((u_short)pTcp6Table->table[i].dwLocalPort);
if (is_lemonade_router(pid)) {
router_pid = static_cast<int>(pid);
candidate_ports.insert(port);
}
}
}
if (router_pid != 0 && !candidate_ports.empty()) {
if (candidate_ports.size() == 1) {
return {router_pid, *candidate_ports.begin()};
}