-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathmain.cpp
More file actions
2090 lines (1770 loc) · 72.4 KB
/
main.cpp
File metadata and controls
2090 lines (1770 loc) · 72.4 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 <windows.h>
#include <shobjidl.h>
#include <propkey.h>
#include <propvarutil.h>
#include <shlobj.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Data.Xml.Dom.h>
#include <winrt/Windows.Data.Json.h>
#include <winrt/Windows.UI.Notifications.h>
#include <winrt/Windows.Storage.h>
#include <iostream>
#include <string>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <tlhelp32.h>
#include <winhttp.h>
#include "resource.h"
#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "winhttp.lib")
using namespace winrt;
using namespace Windows::Data::Xml::Dom;
using namespace Windows::Data::Json;
using namespace Windows::UI::Notifications;
namespace fs = std::filesystem;
const wchar_t* APP_ID = L"Toasty.CLI.Notification";
const wchar_t* APP_NAME = L"Toasty";
const wchar_t* PROTOCOL_NAME = L"toasty";
const wchar_t* TOASTY_VERSION = L"0.6";
// Global flags
bool g_dryRun = false;
// RAII wrapper for Windows handles
struct HandleGuard {
HANDLE h;
HandleGuard(HANDLE handle) : h(handle) {}
~HandleGuard() { if (h && h != INVALID_HANDLE_VALUE) CloseHandle(h); }
operator HANDLE() const { return h; }
bool valid() const { return h && h != INVALID_HANDLE_VALUE; }
};
struct AppPreset {
std::wstring name;
std::wstring title;
int iconResourceId;
};
const AppPreset APP_PRESETS[] = {
{ L"claude", L"Claude", IDI_CLAUDE },
{ L"copilot", L"GitHub Copilot", IDI_COPILOT },
{ L"gemini", L"Gemini", IDI_GEMINI },
{ L"codex", L"Codex", IDI_CODEX },
{ L"cursor", L"Cursor", IDI_CURSOR }
};
// Extract embedded PNG resource to temp file and return path
std::wstring extract_icon_to_temp(int resourceId) {
HRSRC hResource = FindResourceW(nullptr, MAKEINTRESOURCEW(resourceId), MAKEINTRESOURCEW(10));
if (!hResource) return L"";
HGLOBAL hLoadedResource = LoadResource(nullptr, hResource);
if (!hLoadedResource) return L"";
LPVOID pLockedResource = LockResource(hLoadedResource);
if (!pLockedResource) return L"";
DWORD resourceSize = SizeofResource(nullptr, hResource);
if (resourceSize == 0) return L"";
// Create temp file path using std::filesystem
wchar_t tempPathBuffer[MAX_PATH];
GetTempPathW(MAX_PATH, tempPathBuffer);
std::filesystem::path tempPath(tempPathBuffer);
std::wstring fileName = L"toasty_icon_" + std::to_wstring(resourceId) + L".png";
tempPath /= fileName;
// Write resource data to temp file
try {
std::ofstream file(tempPath, std::ios::binary);
if (!file) return L"";
file.write(static_cast<const char*>(pLockedResource), resourceSize);
file.close();
if (file.fail()) return L"";
return tempPath.wstring();
} catch (...) {
// Failed to write icon file
return L"";
}
}
// Utility: Convert string to lowercase
std::wstring to_lower(std::wstring str) {
for (auto& c : str) c = towlower(c);
return str;
}
// Find preset by name (case-insensitive)
const AppPreset* find_preset(const std::wstring& name) {
auto lowerName = to_lower(name);
for (const auto& preset : APP_PRESETS) {
if (to_lower(preset.name) == lowerName) {
return &preset;
}
}
return nullptr;
}
// Get command line of a process using NtQueryInformationProcess with ProcessCommandLineInformation
typedef NTSTATUS(NTAPI* NtQueryInformationProcessFn)(HANDLE, ULONG, PVOID, ULONG, PULONG);
std::wstring get_process_command_line(DWORD pid) {
std::wstring cmdLine;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!hProcess) {
return L"";
}
// Get NtQueryInformationProcess
static NtQueryInformationProcessFn NtQueryInformationProcess = nullptr;
if (!NtQueryInformationProcess) {
HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
if (ntdll) {
NtQueryInformationProcess = (NtQueryInformationProcessFn)GetProcAddress(ntdll, "NtQueryInformationProcess");
}
}
if (!NtQueryInformationProcess) {
CloseHandle(hProcess);
return L"";
}
// Use ProcessCommandLineInformation (60) - available on Windows 8.1+
const ULONG ProcessCommandLineInformation = 60;
struct UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
};
// First call to get required size
ULONG returnLength = 0;
NtQueryInformationProcess(hProcess, ProcessCommandLineInformation, nullptr, 0, &returnLength);
if (returnLength == 0) {
CloseHandle(hProcess);
return L"";
}
// Allocate buffer and get command line
std::vector<BYTE> buffer(returnLength);
NTSTATUS status = NtQueryInformationProcess(hProcess, ProcessCommandLineInformation,
buffer.data(), returnLength, &returnLength);
if (status == 0) {
UNICODE_STRING* unicodeString = reinterpret_cast<UNICODE_STRING*>(buffer.data());
if (unicodeString->Length > 0 && unicodeString->Buffer) {
cmdLine.assign(unicodeString->Buffer, unicodeString->Length / sizeof(wchar_t));
}
}
CloseHandle(hProcess);
return cmdLine;
}
// Check if command line contains a known CLI pattern
const AppPreset* check_command_line_for_preset(const std::wstring& cmdLine) {
auto lowerCmd = to_lower(cmdLine);
// Check for Gemini CLI (multiple patterns)
if (lowerCmd.find(L"gemini-cli") != std::wstring::npos ||
lowerCmd.find(L"gemini\\cli") != std::wstring::npos ||
lowerCmd.find(L"gemini/cli") != std::wstring::npos ||
lowerCmd.find(L"@google\\gemini") != std::wstring::npos ||
lowerCmd.find(L"@google/gemini") != std::wstring::npos) {
return find_preset(L"gemini");
}
// Check for Claude Code (in case it runs via Node too)
if (lowerCmd.find(L"claude-code") != std::wstring::npos ||
lowerCmd.find(L"@anthropic") != std::wstring::npos) {
return find_preset(L"claude");
}
// Check for Cursor
if (lowerCmd.find(L"cursor") != std::wstring::npos) {
return find_preset(L"cursor");
}
return nullptr;
}
// Walk up process tree to find a matching AI CLI preset
const AppPreset* detect_preset_from_ancestors(bool debug = false) {
HandleGuard snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
if (!snapshot.valid()) {
return nullptr;
}
DWORD currentPid = GetCurrentProcessId();
if (debug) {
std::wcerr << L"[DEBUG] Starting from PID: " << currentPid << L"\n";
}
// Walk up the process tree (max 20 levels to avoid infinite loops)
for (int depth = 0; depth < 20; depth++) {
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
DWORD parentPid = 0;
// Find current process to get parent PID
if (Process32FirstW(snapshot, &pe32)) {
do {
if (pe32.th32ProcessID == currentPid) {
parentPid = pe32.th32ParentProcessID;
break;
}
} while (Process32NextW(snapshot, &pe32));
}
if (parentPid == 0 || parentPid == currentPid) {
break; // Reached root or loop
}
// Find parent process name
pe32.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(snapshot, &pe32)) {
do {
if (pe32.th32ProcessID == parentPid) {
// Extract just the filename without extension
std::wstring exeName = pe32.szExeFile;
size_t dotPos = exeName.find_last_of(L'.');
if (dotPos != std::wstring::npos) {
exeName = exeName.substr(0, dotPos);
}
// Convert to lowercase for matching
auto lowerExeName = to_lower(exeName);
// Get command line for this process
std::wstring cmdLine = get_process_command_line(parentPid);
if (debug) {
std::wcerr << L"[DEBUG] Level " << depth << L": PID=" << parentPid
<< L" Name=" << exeName << L"\n";
std::wcerr << L"[DEBUG] CmdLine: " << (cmdLine.empty() ? L"(empty)" : cmdLine.substr(0, 100)) << L"\n";
}
// Check if this matches a preset by name
const AppPreset* preset = find_preset(lowerExeName);
if (preset) {
if (debug) std::wcerr << L"[DEBUG] MATCH by name: " << lowerExeName << L"\n";
return preset;
}
// Check command line for CLI patterns (handles node.exe, etc.)
preset = check_command_line_for_preset(cmdLine);
if (preset) {
if (debug) std::wcerr << L"[DEBUG] MATCH by cmdline\n";
return preset;
}
break;
}
} while (Process32NextW(snapshot, &pe32));
}
// Move up to parent
currentPid = parentPid;
}
return nullptr;
}
void print_usage() {
std::wcout << L"toasty - Windows toast notification CLI\n\n"
<< L"Usage:\n"
<< L" toasty <message> [options]\n"
<< L" toasty --install [agent]\n"
<< L" toasty --uninstall\n"
<< L" toasty --status\n\n"
<< L"Options:\n"
<< L" -t, --title <text> Set notification title (default: \"Notification\")\n"
<< L" --app <name> Use AI CLI preset (claude, copilot, gemini, codex, cursor)\n"
<< L" -i, --icon <path> Custom icon path (PNG recommended, 48x48px)\n"
<< L" -v, --version Show version and exit\n"
<< L" -h, --help Show this help\n"
<< L" --install [agent] Install hooks for AI CLI agents (claude, gemini, copilot, codex, or all)\n"
<< L" --uninstall Remove hooks from all AI CLI agents\n"
<< L" --status Show installation status\n"
<< L" --register Re-register app for notifications (troubleshooting)\n"
<< L" --dry-run Show what would happen without executing side effects\n\n"
<< L"Push Notifications:\n"
<< L" Set TOASTY_NTFY_TOPIC to send push notifications to your phone via ntfy.sh.\n"
<< L" Set TOASTY_NTFY_SERVER to use a self-hosted ntfy server (default: ntfy.sh).\n\n"
<< L"Note: Toasty auto-detects known parent processes (Claude, Copilot, etc.)\n"
<< L" and applies the appropriate preset automatically. Use --app to override.\n\n"
<< L"Examples:\n"
<< L" toasty \"Build completed\"\n"
<< L" toasty \"Task done\" -t \"Custom Title\"\n"
<< L" toasty \"Analysis complete\" --app claude\n"
<< L" toasty --install\n"
<< L" toasty --status\n";
}
std::wstring escape_xml(const std::wstring& text) {
std::wstring result;
result.reserve(text.size());
for (wchar_t c : text) {
switch (c) {
case L'&': result += L"&"; break;
case L'<': result += L"<"; break;
case L'>': result += L">"; break;
case L'"': result += L"""; break;
case L'\'': result += L"'"; break;
default: result += c; break;
}
}
return result;
}
// Send push notification via ntfy.sh (non-blocking, fire-and-forget)
// Only sends if TOASTY_NTFY_TOPIC env var is set.
// Uses TOASTY_NTFY_SERVER env var for custom server (default: ntfy.sh).
// Timeout is aggressive (5 seconds) so it never blocks the CLI.
void send_ntfy_notification(const std::wstring& title, const std::wstring& message) {
// Check for topic
wchar_t topicBuf[256] = {};
if (!GetEnvironmentVariableW(L"TOASTY_NTFY_TOPIC", topicBuf, 256) || topicBuf[0] == L'\0') {
return; // ntfy not configured, silently skip
}
std::wstring topic(topicBuf);
// Check for custom server (default: ntfy.sh)
wchar_t serverBuf[256] = {};
std::wstring server = L"ntfy.sh";
if (GetEnvironmentVariableW(L"TOASTY_NTFY_SERVER", serverBuf, 256) && serverBuf[0] != L'\0') {
server = serverBuf;
}
// Build the path: /<topic>
std::wstring path = L"/" + topic;
// Convert title and message to UTF-8 for HTTP body
std::string bodyUtf8;
{
int size = WideCharToMultiByte(CP_UTF8, 0, message.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (size > 0) {
bodyUtf8.resize(size - 1);
WideCharToMultiByte(CP_UTF8, 0, message.c_str(), -1, &bodyUtf8[0], size, nullptr, nullptr);
}
}
std::string titleUtf8;
{
int size = WideCharToMultiByte(CP_UTF8, 0, title.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (size > 0) {
titleUtf8.resize(size - 1);
WideCharToMultiByte(CP_UTF8, 0, title.c_str(), -1, &titleUtf8[0], size, nullptr, nullptr);
}
}
// Fire-and-forget HTTP POST with aggressive timeout
HINTERNET hSession = WinHttpOpen(L"Toasty/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) return;
// Set timeouts: 3s resolve, 3s connect, 5s send, 5s receive
WinHttpSetTimeouts(hSession, 3000, 3000, 5000, 5000);
HINTERNET hConnect = WinHttpConnect(hSession, server.c_str(), INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) {
WinHttpCloseHandle(hSession);
return;
}
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"POST", path.c_str(),
nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!hRequest) {
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return;
}
// Add title header
std::wstring titleHeader = L"Title: " + title;
WinHttpAddRequestHeaders(hRequest, titleHeader.c_str(), (DWORD)-1, WINHTTP_ADDREQ_FLAG_ADD);
// Send the request (body is the message)
BOOL sent = WinHttpSendRequest(hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
(LPVOID)bodyUtf8.c_str(), (DWORD)bodyUtf8.size(), (DWORD)bodyUtf8.size(), 0);
if (sent) {
WinHttpReceiveResponse(hRequest, nullptr); // Wait for response (respects timeout)
}
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
}
// Check if we should check for updates (throttle to once per day)
bool should_check_for_updates() {
HKEY hKey;
std::wstring regKey = std::wstring(L"Software\\") + APP_NAME;
LONG result = RegOpenKeyExW(HKEY_CURRENT_USER, regKey.c_str(), 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS) return true; // No key yet, check
FILETIME lastCheck = {};
DWORD size = sizeof(FILETIME);
result = RegQueryValueExW(hKey, L"LastUpdateCheck", nullptr, nullptr, (BYTE*)&lastCheck, &size);
RegCloseKey(hKey);
if (result != ERROR_SUCCESS) return true; // No value yet, check
// Get current time
FILETIME now;
GetSystemTimeAsFileTime(&now);
// Convert to ULARGE_INTEGER for arithmetic (100-nanosecond intervals)
ULARGE_INTEGER ulNow, ulLast;
ulNow.LowPart = now.dwLowDateTime;
ulNow.HighPart = now.dwHighDateTime;
ulLast.LowPart = lastCheck.dwLowDateTime;
ulLast.HighPart = lastCheck.dwHighDateTime;
// 24 hours in 100-nanosecond intervals
ULONGLONG dayInterval = 24ULL * 60 * 60 * 10000000;
return (ulNow.QuadPart - ulLast.QuadPart) >= dayInterval;
}
// Save the last update check timestamp
void save_update_check_time() {
HKEY hKey;
std::wstring regKey = std::wstring(L"Software\\") + APP_NAME;
LONG result = RegCreateKeyExW(HKEY_CURRENT_USER, regKey.c_str(), 0, nullptr,
REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, nullptr);
if (result != ERROR_SUCCESS) return;
FILETIME now;
GetSystemTimeAsFileTime(&now);
RegSetValueExW(hKey, L"LastUpdateCheck", 0, REG_BINARY, (BYTE*)&now, sizeof(FILETIME));
RegCloseKey(hKey);
}
// Compare version strings (e.g., "0.3" vs "0.4")
// Returns true if remoteVersion is newer than localVersion
bool is_newer_version(const std::wstring& localVersion, const std::wstring& remoteVersion) {
// Strip leading 'v' if present
std::wstring local = localVersion;
std::wstring remote = remoteVersion;
if (!local.empty() && (local[0] == L'v' || local[0] == L'V')) local = local.substr(1);
if (!remote.empty() && (remote[0] == L'v' || remote[0] == L'V')) remote = remote.substr(1);
// Parse major.minor
auto parse = [](const std::wstring& v, int& major, int& minor) {
major = 0; minor = 0;
size_t dot = v.find(L'.');
if (dot != std::wstring::npos) {
try {
major = std::stoi(v.substr(0, dot));
minor = std::stoi(v.substr(dot + 1));
} catch (...) {}
} else {
try { major = std::stoi(v); } catch (...) {}
}
};
int localMajor, localMinor, remoteMajor, remoteMinor;
parse(local, localMajor, localMinor);
parse(remote, remoteMajor, remoteMinor);
if (remoteMajor > localMajor) return true;
if (remoteMajor == localMajor && remoteMinor > localMinor) return true;
return false;
}
// Check GitHub releases for a newer version (non-blocking, throttled)
// Returns true if an update toast was shown
bool check_for_updates() {
if (!should_check_for_updates()) return false;
save_update_check_time(); // Save now so we don't retry on failure
// Hit GitHub API: GET /repos/shanselman/toasty/releases/latest
HINTERNET hSession = WinHttpOpen(L"Toasty/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) return false;
WinHttpSetTimeouts(hSession, 3000, 3000, 5000, 5000);
HINTERNET hConnect = WinHttpConnect(hSession, L"api.github.com", INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) {
WinHttpCloseHandle(hSession);
return false;
}
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET",
L"/repos/shanselman/toasty/releases/latest",
nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!hRequest) {
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return false;
}
// GitHub API requires User-Agent
WinHttpAddRequestHeaders(hRequest, L"Accept: application/vnd.github+json", (DWORD)-1, WINHTTP_ADDREQ_FLAG_ADD);
BOOL sent = WinHttpSendRequest(hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
bool updateAvailable = false;
if (sent && WinHttpReceiveResponse(hRequest, nullptr)) {
// Read response body
std::string responseBody;
DWORD bytesRead = 0;
DWORD bytesAvailable = 0;
while (WinHttpQueryDataAvailable(hRequest, &bytesAvailable) && bytesAvailable > 0) {
std::vector<char> buffer(bytesAvailable);
if (WinHttpReadData(hRequest, buffer.data(), bytesAvailable, &bytesRead)) {
responseBody.append(buffer.data(), bytesRead);
}
// Cap response size to prevent memory issues
if (responseBody.size() > 32768) break;
}
// Parse tag_name from JSON response using WinRT JSON parser
try {
int wideSize = MultiByteToWideChar(CP_UTF8, 0, responseBody.c_str(), -1, nullptr, 0);
if (wideSize > 0) {
std::wstring wideResponse(wideSize - 1, 0);
MultiByteToWideChar(CP_UTF8, 0, responseBody.c_str(), -1, &wideResponse[0], wideSize);
JsonObject json;
if (JsonObject::TryParse(wideResponse, json)) {
std::wstring tagName = json.GetNamedString(L"tag_name", L"").c_str();
std::wstring releaseName = json.GetNamedString(L"name", L"").c_str();
std::wstring htmlUrl = json.GetNamedString(L"html_url", L"").c_str();
if (!tagName.empty() && is_newer_version(TOASTY_VERSION, tagName)) {
// Print to stderr
std::wcerr << L"Update available: v" << TOASTY_VERSION
<< L" → " << tagName
<< L" (https://github.com/shanselman/toasty/releases)\n";
// Show a toast notification about the update
try {
std::wstring updateXml =
L"<toast activationType=\"protocol\" launch=\"https://github.com/shanselman/toasty/releases\">"
L"<visual><binding template=\"ToastGeneric\">"
L"<text>Toasty Update Available</text>"
L"<text>v" + std::wstring(TOASTY_VERSION) + L" → " + tagName + L" — click to download</text>"
L"</binding></visual></toast>";
XmlDocument updateDoc;
updateDoc.LoadXml(updateXml);
ToastNotification updateToast(updateDoc);
auto notifier = ToastNotificationManager::CreateToastNotifier(APP_ID);
notifier.Show(updateToast);
} catch (...) {
// Update toast failed — not critical
}
updateAvailable = true;
}
}
}
} catch (...) {
// JSON parse failed — silently ignore
}
}
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return updateAvailable;
}
bool register_protocol() {
wchar_t exePath[MAX_PATH];
GetModuleFileNameW(nullptr, exePath, MAX_PATH);
HKEY hKey;
std::wstring protocolKey = std::wstring(L"Software\\Classes\\") + PROTOCOL_NAME;
LONG result = RegCreateKeyExW(HKEY_CURRENT_USER, protocolKey.c_str(), 0, nullptr,
REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, nullptr);
if (result != ERROR_SUCCESS) {
return false;
}
RegSetValueExW(hKey, L"URL Protocol", 0, REG_SZ, nullptr, 0);
std::wstring description = L"URL:Toasty Protocol";
RegSetValueExW(hKey, nullptr, 0, REG_SZ, (BYTE*)description.c_str(),
(DWORD)((description.length() + 1) * sizeof(wchar_t)));
RegCloseKey(hKey);
std::wstring commandKey = protocolKey + L"\\shell\\open\\command";
result = RegCreateKeyExW(HKEY_CURRENT_USER, commandKey.c_str(), 0, nullptr,
REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, nullptr);
if (result != ERROR_SUCCESS) {
return false;
}
std::wstring command = L"\"" + std::wstring(exePath) + L"\" --focus \"%1\"";
RegSetValueExW(hKey, nullptr, 0, REG_SZ, (BYTE*)command.c_str(),
(DWORD)((command.length() + 1) * sizeof(wchar_t)));
RegCloseKey(hKey);
return true;
}
// Save the console window handle to registry for later retrieval
bool save_console_window_handle(HWND hwnd) {
HKEY hKey;
std::wstring regKey = std::wstring(L"Software\\") + APP_NAME;
LONG result = RegCreateKeyExW(HKEY_CURRENT_USER, regKey.c_str(), 0, nullptr,
REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, nullptr);
if (result != ERROR_SUCCESS) {
return false;
}
ULONG_PTR handleValue = (ULONG_PTR)hwnd;
RegSetValueExW(hKey, L"LastConsoleWindow", 0, REG_QWORD, (BYTE*)&handleValue, sizeof(ULONG_PTR));
RegCloseKey(hKey);
return true;
}
// Retrieve the saved console window handle from registry
HWND get_saved_console_window_handle() {
HKEY hKey;
std::wstring regKey = std::wstring(L"Software\\") + APP_NAME;
LONG result = RegOpenKeyExW(HKEY_CURRENT_USER, regKey.c_str(), 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS) {
return nullptr;
}
ULONG_PTR handleValue = 0;
DWORD size = sizeof(ULONG_PTR);
result = RegQueryValueExW(hKey, L"LastConsoleWindow", nullptr, nullptr, (BYTE*)&handleValue, &size);
RegCloseKey(hKey);
if (result != ERROR_SUCCESS) {
return nullptr;
}
HWND hwnd = (HWND)(ULONG_PTR)handleValue;
if (IsWindow(hwnd)) {
return hwnd;
}
return nullptr;
}
// Structure to pass data to EnumWindows callback
struct FindWindowData {
DWORD targetPid;
HWND foundWindow;
};
// Find window belonging to a specific process
HWND find_window_for_process(DWORD pid) {
FindWindowData data = { pid, nullptr };
EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL {
FindWindowData* pData = (FindWindowData*)lParam;
DWORD windowPid = 0;
GetWindowThreadProcessId(hwnd, &windowPid);
if (windowPid == pData->targetPid && IsWindowVisible(hwnd)) {
// Check if it has a title (real window, not helper)
wchar_t title[256];
if (GetWindowTextW(hwnd, title, 256) > 0) {
pData->foundWindow = hwnd;
return FALSE; // Stop enumeration
}
}
return TRUE;
}, (LPARAM)&data);
return data.foundWindow;
}
// Walk process tree to find the terminal/IDE window that launched us
HWND find_ancestor_window() {
HandleGuard snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
if (!snapshot.valid()) {
return nullptr;
}
DWORD currentPid = GetCurrentProcessId();
// Walk up the process tree (max 20 levels)
for (int depth = 0; depth < 20; depth++) {
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
DWORD parentPid = 0;
// Find current process to get parent PID
if (Process32FirstW(snapshot, &pe32)) {
do {
if (pe32.th32ProcessID == currentPid) {
parentPid = pe32.th32ParentProcessID;
break;
}
} while (Process32NextW(snapshot, &pe32));
}
if (parentPid == 0 || parentPid == currentPid) {
break;
}
// Check if this parent has a visible window
HWND hwnd = find_window_for_process(parentPid);
if (hwnd) {
return hwnd;
}
currentPid = parentPid;
}
return nullptr;
}
// Helper to forcefully bring a window to foreground (works around Windows restrictions)
bool force_foreground_window(HWND hwnd) {
if (!hwnd || !IsWindow(hwnd)) {
return false;
}
// Get the foreground window's thread
DWORD foregroundThread = GetWindowThreadProcessId(GetForegroundWindow(), nullptr);
DWORD currentThread = GetCurrentThreadId();
// Attach to the foreground thread to get input focus permission
if (foregroundThread != currentThread) {
AttachThreadInput(currentThread, foregroundThread, TRUE);
}
// Restore if minimized
if (IsIconic(hwnd)) {
ShowWindow(hwnd, SW_RESTORE);
}
// Try multiple methods to bring window to front
BringWindowToTop(hwnd);
SetForegroundWindow(hwnd);
// Simulate a keypress to help with focus (empty ALT press)
keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
SetForegroundWindow(hwnd);
SetFocus(hwnd);
// Detach from foreground thread
if (foregroundThread != currentThread) {
AttachThreadInput(currentThread, foregroundThread, FALSE);
}
return true;
}
bool focus_console_window() {
// First try: saved console window handle from registry (most reliable)
HWND savedWindow = get_saved_console_window_handle();
if (savedWindow != nullptr) {
return force_foreground_window(savedWindow);
}
// Second try: enumerate windows to find a console or Windows Terminal
HWND foundWindow = nullptr;
EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL {
wchar_t className[256];
GetClassNameW(hwnd, className, 256);
if (!IsWindowVisible(hwnd)) {
return TRUE;
}
if (wcscmp(className, L"ConsoleWindowClass") == 0 ||
wcscmp(className, L"CASCADIA_HOSTING_WINDOW_CLASS") == 0) {
HWND* pResult = (HWND*)lParam;
*pResult = hwnd;
return FALSE;
}
return TRUE;
}, (LPARAM)&foundWindow);
if (foundWindow != nullptr) {
return force_foreground_window(foundWindow);
}
return false;
}
// Escape backslashes and quotes for JSON strings
std::wstring escape_json_string(const std::wstring& str) {
std::wstring result;
result.reserve(str.size());
for (wchar_t c : str) {
switch (c) {
case L'\\': result += L"\\\\"; break;
case L'"': result += L"\\\""; break;
case L'\n': result += L"\\n"; break;
case L'\r': result += L"\\r"; break;
case L'\t': result += L"\\t"; break;
default: result += c; break;
}
}
return result;
}
// Get the full path to the current executable
std::wstring get_exe_path() {
wchar_t exePath[MAX_PATH];
DWORD result = GetModuleFileNameW(nullptr, exePath, MAX_PATH);
if (result == 0 || result == MAX_PATH) {
// Failed to get exe path, return empty string
return L"";
}
return std::wstring(exePath);
}
// Expand environment variables in a path
std::wstring expand_env(const std::wstring& path) {
wchar_t expanded[MAX_PATH];
DWORD result = ExpandEnvironmentStringsW(path.c_str(), expanded, MAX_PATH);
if (result == 0 || result > MAX_PATH) {
// Failed to expand, return original path
return path;
}
return std::wstring(expanded);
}
// Check if a path exists
bool path_exists(const std::wstring& path) {
DWORD attr = GetFileAttributesW(path.c_str());
return (attr != INVALID_FILE_ATTRIBUTES);
}
// Agent detection functions
bool detect_claude() {
std::wstring claudePath = expand_env(L"%USERPROFILE%\\.claude");
return path_exists(claudePath);
}
bool detect_gemini() {
std::wstring geminiPath = expand_env(L"%USERPROFILE%\\.gemini");
return path_exists(geminiPath);
}
bool detect_copilot() {
// Check for .github directory AND hooks subdirectory as more specific indicator
return path_exists(L".github\\hooks") || path_exists(L".github");
}
bool detect_codex() {
std::wstring codexPath = expand_env(L"%USERPROFILE%\\.codex");
return path_exists(codexPath);
}
// Read file content as string
std::string read_file(const std::wstring& path) {
std::ifstream file(path, std::ios::binary);
if (!file) {
return "";
}
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
// Write string to file
bool write_file(const std::wstring& path, const std::string& content) {
std::ofstream file(path, std::ios::binary);
if (!file) {
return false;
}
file << content;
return file.good();
}
// Backup a file
bool backup_file(const std::wstring& path) {
std::wstring backupPath = path + L".bak";
try {
if (path_exists(path)) {
fs::copy_file(path, backupPath, fs::copy_options::overwrite_existing);
}
return true;
} catch (const std::exception& e) {
// Convert narrow string to wide string
int size = MultiByteToWideChar(CP_UTF8, 0, e.what(), -1, nullptr, 0);
if (size > 0) {
std::wstring wideMsg(size - 1, 0);
MultiByteToWideChar(CP_UTF8, 0, e.what(), -1, &wideMsg[0], size);
std::wcerr << L"Warning: Failed to create backup: " << wideMsg << L"\n";
} else {
std::wcerr << L"Warning: Failed to create backup\n";
}
return false;
}
}
// Convert std::string to winrt::hstring
hstring to_hstring(const std::string& str) {
int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
std::wstring wstr(size - 1, 0);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &wstr[0], size);
return hstring(wstr);
}
// Convert winrt::hstring to std::string
std::string from_hstring(const hstring& hstr) {
std::wstring wstr(hstr.c_str());
int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string str(size - 1, 0);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &str[0], size, nullptr, nullptr);
return str;
}
// Check if a JSON hook array contains toasty
bool has_toasty_hook(const JsonArray& hooks) {
for (const auto& hookItem : hooks) {
if (hookItem.ValueType() == JsonValueType::Object) {
auto hookObj = hookItem.GetObject();
// Check direct command field (correct format)
if (hookObj.HasKey(L"command")) {
std::wstring cmd = hookObj.GetNamedString(L"command").c_str();
if (cmd.find(L"toasty") != std::wstring::npos) {
return true;
}
}
// Also check nested hooks array (legacy format)
if (hookObj.HasKey(L"hooks")) {
auto innerHooks = hookObj.GetNamedArray(L"hooks");
for (const auto& innerHook : innerHooks) {
if (innerHook.ValueType() == JsonValueType::Object) {
auto innerObj = innerHook.GetObject();
if (innerObj.HasKey(L"command")) {
std::wstring cmd = innerObj.GetNamedString(L"command").c_str();
if (cmd.find(L"toasty") != std::wstring::npos) {
return true;
}
}
}
}
}
}
}
return false;
}
// Install hook for Claude Code
bool install_claude(const std::wstring& exePath) {
std::wstring configPath = expand_env(L"%USERPROFILE%\\.claude\\settings.json");
JsonObject rootObj;
std::string existingContent = read_file(configPath);
if (!existingContent.empty()) {
try {
backup_file(configPath);
rootObj = JsonObject::Parse(to_hstring(existingContent));
} catch (const hresult_error& ex) {
std::wcerr << L"Warning: Failed to parse existing config, starting fresh: " << ex.message().c_str() << L"\n";
rootObj = JsonObject();
}
}
// Build hook structure with nested "hooks" array (required by Claude Code)
JsonObject innerHook;
innerHook.SetNamedValue(L"type", JsonValue::CreateStringValue(L"command"));
std::wstring escapedPath = escape_json_string(exePath);
std::wstring command = escapedPath + L" \"Task complete\" -t \"Claude Code\"";
innerHook.SetNamedValue(L"command", JsonValue::CreateStringValue(command));
innerHook.SetNamedValue(L"timeout", JsonValue::CreateNumberValue(5000));