-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_e2e.cpp
More file actions
4263 lines (3541 loc) · 133 KB
/
Copy pathtest_e2e.cpp
File metadata and controls
4263 lines (3541 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
// Copyright (c) 2025 Elias Bachaalany
// SPDX-License-Identifier: MIT
/// @file test_e2e.cpp
/// @brief End-to-end tests using the real Copilot CLI
///
/// These tests require the Copilot CLI to be installed and available in PATH.
/// They test the full SDK stack against the real server.
///
/// Run these tests manually or in CI with Copilot CLI installed:
/// ctest -R E2ETest --output-on-failure
#include <atomic>
#include <cctype>
#include <chrono>
#include <condition_variable>
#include <copilot/copilot.hpp>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <gtest/gtest.h>
#include <iostream>
#include <mutex>
#include <thread>
using namespace copilot;
// =============================================================================
// BYOK Environment File Loader
// =============================================================================
/// Load environment variables from tests/byok.env if it exists.
/// File format: KEY=VALUE per line (no quotes needed, # comments supported)
static void load_byok_env_file()
{
static std::once_flag once;
std::call_once(
once,
[]()
{
// Get directory of this source file and look for byok.env
std::filesystem::path source_path(__FILE__);
std::filesystem::path env_file = source_path.parent_path() / "byok.env";
if (!std::filesystem::exists(env_file))
{
std::cerr << "[E2E] No byok.env file found at: " << env_file << "\n";
return;
}
std::ifstream file(env_file);
if (!file.is_open())
{
std::cerr << "[E2E] Failed to open byok.env file\n";
return;
}
std::cerr << "[E2E] Loading BYOK config from: " << env_file << "\n";
std::string line;
int count = 0;
while (std::getline(file, line))
{
// Skip empty lines and comments
if (line.empty() || line[0] == '#')
continue;
// Trim whitespace
size_t start = line.find_first_not_of(" \t");
if (start == std::string::npos)
continue;
size_t end = line.find_last_not_of(" \t\r\n");
line = line.substr(start, end - start + 1);
// Find KEY=VALUE
size_t eq_pos = line.find('=');
if (eq_pos == std::string::npos)
continue;
std::string key = line.substr(0, eq_pos);
std::string value = line.substr(eq_pos + 1);
// Trim key and value
key.erase(0, key.find_first_not_of(" \t"));
key.erase(key.find_last_not_of(" \t") + 1);
value.erase(0, value.find_first_not_of(" \t"));
value.erase(value.find_last_not_of(" \t\r\n") + 1);
// Set environment variable
#ifdef _WIN32
_putenv_s(key.c_str(), value.c_str());
#else
setenv(key.c_str(), value.c_str(), 1);
#endif
// Mask the value for logging (show only last 4 chars)
std::string masked = value.length() > 4
? std::string(value.length() - 4, '*') + value.substr(value.length() - 4)
: "****";
std::cerr << "[E2E] " << key << "=" << masked << "\n";
count++;
}
std::cerr << "[E2E] Loaded " << count << " environment variables from byok.env\n";
}
);
}
/// Check if BYOK is active (API key env var is set)
/// Used to skip tests that don't work with BYOK providers
static bool is_byok_active()
{
const char* key = std::getenv("COPILOT_SDK_BYOK_API_KEY");
return key != nullptr && key[0] != '\0';
}
// =============================================================================
// Test Fixture
// =============================================================================
class E2ETest : public ::testing::Test
{
protected:
void SetUp() override
{
// Load BYOK environment variables from tests/byok.env if it exists
load_byok_env_file();
// E2E tests run by default. CI can set COPILOT_SDK_CPP_SKIP_E2E=1 to disable.
if (should_skip_e2e_tests())
GTEST_SKIP() << "E2E tests disabled via COPILOT_SDK_CPP_SKIP_E2E";
// Check if Copilot CLI is available
if (!is_copilot_available())
GTEST_SKIP() << "Copilot CLI not found in PATH - skipping E2E tests";
// Check that Copilot CLI can actually make model calls (quota/auth). This avoids
// turning local quota outages into red builds.
ensure_copilot_can_run();
if (!copilot_can_run_.load())
GTEST_SKIP() << copilot_skip_reason_;
}
static bool should_skip_e2e_tests()
{
const char* env = std::getenv("COPILOT_SDK_CPP_SKIP_E2E");
if (!env)
return false;
std::string v(env);
for (auto& c : v)
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
return v == "1" || v == "true" || v == "yes" || v == "on";
}
static bool is_copilot_available()
{
// Try to find copilot in PATH
auto path = find_executable("copilot");
return path.has_value();
}
static void ensure_copilot_can_run()
{
static std::once_flag once;
std::call_once(
once,
[]()
{
try
{
ClientOptions opts;
opts.log_level = LogLevel::Info;
opts.use_stdio = true;
opts.cli_args = std::vector<std::string>{"--allow-all-tools", "--allow-all-paths"};
opts.auto_start = false;
Client client(opts);
client.start().get();
// Use BYOK config if available (from tests/byok.env)
SessionConfig session_config;
session_config.auto_byok_from_env = true;
auto session = client.create_session(session_config).get();
std::mutex mtx;
std::condition_variable cv;
bool done = false;
std::string error_message;
auto sub = session->on(
[&](const SessionEvent& event)
{
if (auto* err = event.try_as<SessionErrorData>())
{
std::lock_guard<std::mutex> lock(mtx);
error_message = err->message;
done = true;
cv.notify_one();
}
else if (event.type == SessionEventType::SessionIdle)
{
std::lock_guard<std::mutex> lock(mtx);
done = true;
cv.notify_one();
}
}
);
MessageOptions msg;
msg.prompt = "ping";
session->send(msg).get();
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::seconds(15), [&]() { return done; });
}
// Clean up before deciding
session->destroy().get();
client.force_stop();
if (!error_message.empty())
{
std::string lower = error_message;
for (auto& c : lower)
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
if (lower.find("quota") != std::string::npos ||
lower.find("402") != std::string::npos ||
lower.find("401") != std::string::npos ||
lower.find("authorization") != std::string::npos ||
lower.find("authentication") != std::string::npos ||
lower.find("unauthorized") != std::string::npos)
{
copilot_can_run_ = false;
copilot_skip_reason_ =
"Copilot CLI cannot make model calls (quota/auth). Error: " +
error_message;
return;
}
}
// If no error and we got idle, assume usable.
copilot_can_run_ = true;
copilot_skip_reason_.clear();
}
catch (const std::exception& e)
{
copilot_can_run_ = false;
copilot_skip_reason_ =
std::string("Copilot CLI preflight failed: ") + e.what();
}
}
);
}
std::unique_ptr<Client> create_client()
{
ClientOptions opts;
opts.log_level = LogLevel::Info;
opts.use_stdio = true;
// Make E2E tests reliable/non-interactive by pre-approving tool and path access.
// These flags are only used for tests; library defaults remain secure-by-default.
opts.cli_args = std::vector<std::string>{"--allow-all-tools", "--allow-all-paths"};
opts.auto_start = false; // We'll start manually
return std::make_unique<Client>(opts);
}
/// Create a default SessionConfig with BYOK env vars enabled.
/// If tests/byok.env exists, it will have been loaded and these vars will be used.
static SessionConfig default_session_config()
{
SessionConfig config;
config.auto_byok_from_env = true;
return config;
}
/// Create a default ResumeSessionConfig with BYOK env vars enabled.
static ResumeSessionConfig default_resume_config()
{
ResumeSessionConfig config;
config.auto_byok_from_env = true;
return config;
}
/// Print test description for verbose output
static void test_info(const char* description)
{
std::cerr << "\n[TEST] " << description << "\n";
std::cerr << std::string(60, '-') << "\n";
}
static inline std::atomic<bool> copilot_can_run_{true};
static inline std::string copilot_skip_reason_;
};
// =============================================================================
// Basic Connection Tests
// =============================================================================
TEST_F(E2ETest, StartAndStop)
{
test_info("Basic connection test: Start CLI process, verify connected, then stop cleanly.");
auto client = create_client();
EXPECT_EQ(client->state(), ConnectionState::Disconnected);
// Start
ASSERT_NO_THROW(client->start().get());
EXPECT_EQ(client->state(), ConnectionState::Connected);
// Stop
ASSERT_NO_THROW(client->stop().get());
EXPECT_EQ(client->state(), ConnectionState::Disconnected);
}
TEST_F(E2ETest, Ping)
{
test_info("Ping test: Send ping RPC to CLI and verify response with protocol version.");
auto client = create_client();
client->start().get();
auto response = client->ping("test message").get();
// Note: Copilot CLI returns "pong: <message>" format
EXPECT_TRUE(response.message.find("test message") != std::string::npos);
EXPECT_EQ(response.protocol_version, kSdkProtocolVersion);
EXPECT_GT(response.timestamp, 0);
client->force_stop(); // Use force_stop for faster cleanup in tests
}
TEST_F(E2ETest, PingWithoutMessage)
{
test_info("Ping without message: Verify ping works with null/empty message.");
auto client = create_client();
client->start().get();
auto response = client->ping().get();
// Message should be null/empty when not provided
EXPECT_EQ(response.protocol_version, kSdkProtocolVersion);
client->force_stop();
}
// =============================================================================
// Session Tests
// =============================================================================
TEST_F(E2ETest, CreateSession)
{
test_info("Create session: Start client, create session with BYOK config, verify session ID returned.");
auto client = create_client();
client->start().get();
auto config = default_session_config();
auto session = client->create_session(config).get();
EXPECT_NE(session, nullptr);
EXPECT_FALSE(session->session_id().empty());
session->destroy().get();
client->force_stop();
}
TEST_F(E2ETest, CreateSessionWithModel)
{
test_info("Create session with explicit model: Test model override in SessionConfig.");
auto client = create_client();
client->start().get();
auto config = default_session_config();
config.model = "gpt-4.1"; // Use a known model
auto session = client->create_session(config).get();
EXPECT_NE(session, nullptr);
EXPECT_FALSE(session->session_id().empty());
session->destroy().get();
client->force_stop();
}
TEST_F(E2ETest, CreateSessionWithTools)
{
test_info("Tool execution test: Register custom tool, ask AI to use it, verify tool called with correct args.");
auto client = create_client();
client->start().get();
// Track tool invocation arguments
std::atomic<bool> tool_called{false};
std::string received_key;
std::mutex arg_mtx;
// Define a custom tool
Tool secret_tool;
secret_tool.name = "get_secret_number";
secret_tool.description = "Returns a secret number that only this tool knows";
secret_tool.parameters_schema = json{
{"type", "object"},
{"properties", {{"key", {{"type", "string"}, {"description", "The key to look up"}}}}},
{"required", {"key"}}
};
secret_tool.handler = [&](const ToolInvocation& inv) -> ToolResultObject
{
ToolResultObject result;
std::string key = inv.arguments.value()["key"].get<std::string>();
// Capture arguments for validation
{
std::lock_guard<std::mutex> lock(arg_mtx);
received_key = key;
tool_called = true;
}
if (key == "ALPHA")
result.text_result_for_llm = "54321";
else
result.text_result_for_llm = "Unknown key";
result.result_type = ToolResultType::Success;
return result;
};
// Create session with the tool
auto config = default_session_config();
config.tools = {secret_tool};
config.on_permission_request = [](const PermissionRequest&) -> PermissionRequestResult
{
PermissionRequestResult r;
r.kind = "approved";
return r;
};
auto session = client->create_session(config).get();
EXPECT_NE(session, nullptr);
EXPECT_FALSE(session->session_id().empty());
// Track events
std::atomic<bool> idle{false};
std::string tool_result_content;
std::mutex mtx;
std::condition_variable cv;
auto sub = session->on(
[&](const SessionEvent& event)
{
if (event.type == SessionEventType::SessionIdle)
{
idle = true;
cv.notify_one();
}
else if (event.type == SessionEventType::ToolExecutionComplete)
{
auto& data = event.as<ToolExecutionCompleteData>();
if (data.result.has_value())
{
std::lock_guard<std::mutex> lock(mtx);
tool_result_content = data.result->content;
}
}
}
);
// Ask the model to use the tool
MessageOptions opts;
opts.prompt = "Use the get_secret_number tool to look up key 'ALPHA' and tell me the number.";
session->send(opts).get();
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::seconds(60), [&]() { return idle.load(); });
}
// Verify the tool was called with correct arguments
EXPECT_TRUE(tool_called.load()) << "Custom tool should have been invoked";
{
std::lock_guard<std::mutex> lock(arg_mtx);
EXPECT_EQ(received_key, "ALPHA") << "Tool should receive the requested key";
}
// Verify the tool result was returned
{
std::lock_guard<std::mutex> lock(mtx);
EXPECT_TRUE(tool_result_content.find("54321") != std::string::npos)
<< "Tool result should contain the secret number. Got: " << tool_result_content;
}
session->destroy().get();
client->force_stop();
}
TEST_F(E2ETest, ListSessions)
{
test_info("List sessions: Create session, send message, verify session appears in history list.");
auto client = create_client();
client->start().get();
// Create a session and send a message to persist it
auto session = client->create_session().get();
std::string session_id = session->session_id();
// Send a message - this persists the session to history
MessageOptions opts;
opts.prompt = "test";
session->send(opts).get();
// Poll until the session appears in history (Copilot CLI timing can vary)
bool found = false;
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60);
while (std::chrono::steady_clock::now() < deadline)
{
auto sessions = client->list_sessions().get();
for (const auto& meta : sessions)
{
if (meta.session_id == session_id)
{
found = true;
break;
}
}
if (found)
break;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
EXPECT_TRUE(found) << "Created session not found in list after sending message";
session->destroy().get();
client->force_stop();
}
TEST_F(E2ETest, GetLastSessionId)
{
test_info("Get last session ID: Create session, destroy it, verify get_last_session_id() works.");
auto client = create_client();
client->start().get();
// Create a session
auto session = client->create_session().get();
std::string session_id = session->session_id();
session->destroy().get();
// Get last session ID
auto last_id = client->get_last_session_id().get();
// Should have some session ID (might be ours or a previous one)
// The important thing is the method works
client->force_stop();
}
// =============================================================================
// Messaging Tests
// =============================================================================
TEST_F(E2ETest, SendMessage)
{
test_info("Send message: Create session, send prompt, wait for SessionIdle, verify events received.");
auto client = create_client();
client->start().get();
auto session = client->create_session(default_session_config()).get();
// Track events
std::mutex mtx;
std::condition_variable cv;
std::atomic<bool> idle{false};
std::vector<SessionEventType> received_events;
auto subscription = session->on(
[&](const SessionEvent& event)
{
{
std::lock_guard<std::mutex> lock(mtx);
received_events.push_back(event.type);
}
if (event.type == SessionEventType::SessionIdle)
{
idle = true;
cv.notify_one();
}
}
);
// Send a simple message
MessageOptions opts;
opts.prompt = "Say exactly: HELLO TEST";
auto message_id = session->send(opts).get();
EXPECT_FALSE(message_id.empty());
// Wait for response (with timeout)
{
std::unique_lock<std::mutex> lock(mtx);
bool completed = cv.wait_for(lock, std::chrono::seconds(60), [&]() { return idle.load(); });
EXPECT_TRUE(completed) << "Timeout waiting for response";
}
// Check we received expected events
EXPECT_FALSE(received_events.empty());
session->destroy().get();
client->force_stop();
}
TEST_F(E2ETest, StreamingResponse)
{
test_info("Streaming response: Enable streaming, send prompt, verify multiple AssistantMessageDelta events.");
auto client = create_client();
client->start().get();
auto config = default_session_config();
config.streaming = true;
auto session = client->create_session(config).get();
// Track streaming deltas
std::mutex mtx;
std::condition_variable cv;
std::atomic<bool> idle{false};
std::atomic<int> delta_count{0};
std::string full_response;
auto subscription = session->on(
[&](const SessionEvent& event)
{
if (auto* delta = event.try_as<AssistantMessageDeltaData>())
{
std::lock_guard<std::mutex> lock(mtx);
delta_count++;
full_response += delta->delta_content;
}
else if (event.type == SessionEventType::SessionIdle)
{
idle = true;
cv.notify_one();
}
}
);
// Send message
MessageOptions opts;
opts.prompt = "Count from 1 to 5";
session->send(opts).get();
// Wait for completion
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::seconds(60), [&]() { return idle.load(); });
}
// In streaming mode, we should receive multiple deltas
std::cout << "Received " << delta_count << " streaming deltas\n";
std::cout << "Full response: " << full_response.substr(0, 200) << "...\n";
EXPECT_GT(delta_count.load(), 0) << "Expected streaming deltas";
session->destroy().get();
client->force_stop();
}
TEST_F(E2ETest, AbortMessage)
{
test_info("Abort message: Send long prompt, call abort() mid-stream, verify session becomes idle.");
auto client = create_client();
client->start().get();
auto session = client->create_session().get();
std::atomic<bool> got_response{false};
std::atomic<bool> idle{false};
std::mutex mtx;
std::condition_variable cv;
auto subscription = session->on(
[&](const SessionEvent& event)
{
if (event.type == SessionEventType::AssistantMessage ||
event.type == SessionEventType::AssistantMessageDelta)
{
got_response = true;
}
if (event.type == SessionEventType::SessionIdle)
{
idle = true;
cv.notify_one();
}
}
);
// Send a message that would take time
MessageOptions opts;
opts.prompt = "Write a very long story about a wizard";
session->send(opts).get();
// Wait a bit then abort
std::this_thread::sleep_for(std::chrono::milliseconds(500));
ASSERT_NO_THROW(session->abort().get());
// Wait for idle
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::seconds(10), [&]() { return idle.load(); });
}
session->destroy().get();
client->force_stop();
}
TEST_F(E2ETest, GetMessages)
{
test_info("Get messages: Send message, wait for response, call get_messages() to retrieve history.");
auto client = create_client();
client->start().get();
auto session = client->create_session().get();
std::atomic<bool> idle{false};
std::mutex mtx;
std::condition_variable cv;
auto subscription = session->on(
[&](const SessionEvent& event)
{
if (event.type == SessionEventType::SessionIdle)
{
idle = true;
cv.notify_one();
}
}
);
// Send a message
MessageOptions opts;
opts.prompt = "Hello";
session->send(opts).get();
// Wait for response
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::seconds(30), [&]() { return idle.load(); });
}
// Get messages
auto messages = session->get_messages().get();
// Should have at least the user message and assistant response
std::cout << "Got " << messages.size() << " messages\n";
session->destroy().get();
client->force_stop();
}
// =============================================================================
// Session Resume Tests
// =============================================================================
TEST_F(E2ETest, ResumeSession)
{
test_info("Resume session: Create session, stop client, restart, resume by ID, verify same session.");
auto client = create_client();
client->start().get();
// Create initial session
auto session1 = client->create_session().get();
std::string session_id = session1->session_id();
std::atomic<bool> idle{false};
std::mutex mtx;
std::condition_variable cv;
auto sub1 = session1->on(
[&](const SessionEvent& event)
{
if (event.type == SessionEventType::SessionIdle)
{
idle = true;
cv.notify_one();
}
}
);
// Send initial message
MessageOptions opts;
opts.prompt = "Remember this: the secret code is XYZ123";
session1->send(opts).get();
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::seconds(30), [&]() { return idle.load(); });
}
// Don't destroy, just stop client
client->stop().get();
// Restart and resume
client = create_client();
client->start().get();
auto resume_config = default_resume_config();
auto session2 = client->resume_session(session_id, resume_config).get();
EXPECT_EQ(session2->session_id(), session_id);
// Clean up
session2->destroy().get();
client->force_stop();
}
TEST_F(E2ETest, ResumeSessionWithTools)
{
test_info("Resume with tools: Create session, stop, resume with new tool, invoke tool successfully.");
// BYOK/OpenAI doesn't support resuming sessions with new tools
auto client = create_client();
client->start().get();
// Create initial session without tools
auto session1 = client->create_session().get();
std::string session_id = session1->session_id();
std::atomic<bool> idle{false};
std::mutex mtx;
std::condition_variable cv;
auto sub1 = session1->on(
[&](const SessionEvent& event)
{
if (event.type == SessionEventType::SessionIdle)
{
idle = true;
cv.notify_one();
}
}
);
// Send initial message
MessageOptions opts;
opts.prompt = "Say hello";
session1->send(opts).get();
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::seconds(30), [&]() { return idle.load(); });
}
// Don't destroy, just stop client
client->stop().get();
// Track tool invocation arguments
std::atomic<bool> tool_called{false};
std::string received_key;
std::mutex arg_mtx;
// Define a custom tool
Tool secret_tool;
secret_tool.name = "get_secret";
secret_tool.description = "Returns a secret value that only this tool knows";
secret_tool.parameters_schema = json{
{"type", "object"},
{"properties", {{"key", {{"type", "string"}, {"description", "The key to look up"}}}}},
{"required", {"key"}}
};
secret_tool.handler = [&](const ToolInvocation& inv) -> ToolResultObject
{
ToolResultObject result;
std::string key = inv.arguments.value()["key"].get<std::string>();
// Capture arguments for validation
{
std::lock_guard<std::mutex> lock(arg_mtx);
received_key = key;
tool_called = true;
}
if (key == "ALPHA")
result.text_result_for_llm = "SECRET_VALUE_12345";
else
result.text_result_for_llm = "Unknown key";
result.result_type = ToolResultType::Success;
return result;
};
// Restart and resume WITH the tool
client = create_client();
client->start().get();
auto resume_config = default_resume_config();
resume_config.tools = {secret_tool};
auto session2 = client->resume_session(session_id, resume_config).get();
EXPECT_EQ(session2->session_id(), session_id);
// Reset for next message
idle = false;
std::string tool_result_content;
auto sub2 = session2->on(
[&](const SessionEvent& event)
{
if (event.type == SessionEventType::SessionIdle)
{
idle = true;
cv.notify_one();
}
else if (event.type == SessionEventType::ToolExecutionComplete)
{
auto& data = event.as<ToolExecutionCompleteData>();
if (data.result.has_value())
{
std::lock_guard<std::mutex> lock(mtx);
tool_result_content = data.result->content;
}
}
}
);
// Ask the model to use the tool
opts.prompt = "Use the get_secret tool to look up the key 'ALPHA' and tell me the value.";
session2->send(opts).get();
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::seconds(60), [&]() { return idle.load(); });
}
// Verify the tool was called with correct arguments
EXPECT_TRUE(tool_called.load()) << "Custom tool should have been invoked";
{
std::lock_guard<std::mutex> lock(arg_mtx);
EXPECT_EQ(received_key, "ALPHA") << "Tool should receive the requested key";
}
// Verify the tool result was returned
{
std::lock_guard<std::mutex> lock(mtx);
EXPECT_TRUE(tool_result_content.find("SECRET_VALUE_12345") != std::string::npos)
<< "Tool result should contain the secret value. Got: " << tool_result_content;
}
// Clean up
session2->destroy().get();
client->force_stop();
}
// =============================================================================
// Event Subscription Tests
// =============================================================================
TEST_F(E2ETest, EventSubscription)
{
test_info("Event subscription: Subscribe to session events, send message, verify events received.");
auto client = create_client();
client->start().get();
auto session = client->create_session().get();
std::mutex mtx;
std::condition_variable cv;
std::vector<SessionEventType> events;
std::atomic<bool> idle{false};
// Subscribe to events
auto subscription = session->on(
[&](const SessionEvent& event)
{
std::lock_guard<std::mutex> lock(mtx);
events.push_back(event.type);
if (event.type == SessionEventType::SessionIdle)
{
idle = true;
cv.notify_one();
}
}
);
// Send message
MessageOptions opts;
opts.prompt = "Hi";
session->send(opts).get();
// Wait for completion
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::seconds(30), [&]() { return idle.load(); });
}
// Check events
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Received events:\n";
for (auto type : events)
std::cout << " - " << static_cast<int>(type) << "\n";
// Should have multiple events
EXPECT_GT(events.size(), 1);
// Unsubscribe (RAII - happens on destruction)