forked from usnavy13/LibreCodeInterpreter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_librechat_compat.py
More file actions
2157 lines (1770 loc) · 79.4 KB
/
test_librechat_compat.py
File metadata and controls
2157 lines (1770 loc) · 79.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
"""
LibreChat request/response contract tests.
These are fast in-process checks for the wire contract only. They intentionally
mock the orchestrator and are not the source of truth for end-to-end client
compatibility; the live replay coverage lives under tests/functional/.
"""
import pytest
from fastapi.testclient import TestClient
from unittest.mock import AsyncMock, MagicMock, patch
from datetime import datetime, timezone, timedelta
import concurrent.futures
import io
import json
from src.main import app
from src.models.exec import ExecResponse, FileRef
from src.models.files import FileInfo
from src.models.session import Session, SessionStatus
@pytest.fixture
def client():
"""Create test client."""
return TestClient(app)
@pytest.fixture
def auth_headers():
"""Provide authentication headers for tests."""
return {"x-api-key": "test-api-key-for-testing-12345"}
@pytest.fixture
def mock_exec_response():
"""Standard successful execution response."""
return ExecResponse(
session_id="test-session-123", stdout="output\n", stderr="", files=[]
)
# =============================================================================
# LIBRECHAT EXEC REQUEST FORMAT
# =============================================================================
class TestLibreChatExecRequest:
"""Test /exec request format exactly as LibreChat sends it.
From CodeExecutor.ts, LibreChat sends:
- lang: 'py' | 'js' | 'ts' | ... (required)
- code: string (required)
- session_id?: string (for file access)
- args?: string[] (array only, not string)
- user_id?: string
- files?: Array<{id, session_id, name}>
"""
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_librechat_minimal_request(
self, mock_execute, client, auth_headers, mock_exec_response
):
"""
Test LibreChat minimal request format.
LibreChat sends: {"code": "...", "lang": "py"}
"""
mock_execute.return_value = mock_exec_response
request = {"code": "print('hello')", "lang": "py"}
response = client.post("/exec", json=request, headers=auth_headers)
assert response.status_code == 200
mock_execute.assert_called_once()
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_librechat_request_with_user_id(
self, mock_execute, client, auth_headers, mock_exec_response
):
"""
Test LibreChat request with user_id for tracking.
LibreChat sends: {"code": "...", "lang": "py", "user_id": "user_..."}
"""
mock_execute.return_value = mock_exec_response
request = {"code": "print('hello')", "lang": "py", "user_id": "user_xyz789"}
response = client.post("/exec", json=request, headers=auth_headers)
assert response.status_code == 200
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_librechat_request_with_files(
self, mock_execute, client, auth_headers, mock_exec_response
):
"""
Test LibreChat request with file references.
LibreChat sends files as array of {id, session_id, name}.
"""
mock_execute.return_value = mock_exec_response
request = {
"code": "with open('data.csv') as f: print(f.read())",
"lang": "py",
"entity_id": "asst_test",
"files": [
{
"id": "file-svc-abc123",
"session_id": "sess_xyz789",
"name": "data.csv",
}
],
}
response = client.post("/exec", json=request, headers=auth_headers)
assert response.status_code == 200
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_librechat_request_with_multiple_files(
self, mock_execute, client, auth_headers, mock_exec_response
):
"""Test LibreChat request with multiple file references."""
mock_execute.return_value = mock_exec_response
request = {
"code": "import os; print(os.listdir('.'))",
"lang": "py",
"files": [
{"id": "file-1", "session_id": "sess-1", "name": "file1.txt"},
{"id": "file-2", "session_id": "sess-2", "name": "file2.txt"},
{"id": "file-3", "session_id": "sess-3", "name": "file3.csv"},
],
}
response = client.post("/exec", json=request, headers=auth_headers)
assert response.status_code == 200
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_librechat_args_as_array(
self, mock_execute, client, auth_headers, mock_exec_response
):
"""
Test LibreChat args field format.
LibreChat sends args as string[] array only (from @librechat/agents CodeExecutor.ts).
The Zod schema defines: args: z.array(z.string()).optional()
"""
mock_execute.return_value = mock_exec_response
request = {
"code": "print('test')",
"lang": "py",
"args": ["arg1", "arg2", "arg3"],
}
response = client.post("/exec", json=request, headers=auth_headers)
assert response.status_code == 200
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_librechat_request_with_session_id(
self, mock_execute, client, auth_headers, mock_exec_response
):
"""
Test LibreChat request with session_id for file and Python state continuity.
LibreChat sends session_id to access files from previous executions.
From CodeExecutor.ts: "Session ID from a previous response to access generated files."
In this backend, Python also reuses interpreter state when the session
is reused. Files are loaded into /mnt/data/ and are READ-ONLY.
"""
mock_execute.return_value = mock_exec_response
request = {
"code": "import os; print(os.listdir('/mnt/data'))",
"lang": "py",
"session_id": "prev-session-abc123",
}
response = client.post("/exec", json=request, headers=auth_headers)
assert response.status_code == 200
forwarded_request = mock_execute.call_args.args[0]
assert forwarded_request.session_id == "prev-session-abc123"
# =============================================================================
# LIBRECHAT EXEC RESPONSE FORMAT
# =============================================================================
class TestLibreChatExecResponse:
"""Test /exec response format exactly as LibreChat expects it.
From ExecuteResult type in @librechat/agents:
- session_id: string (required)
- stdout: string (required)
- stderr: string (required)
- files?: Array<{id, name, path?}>
"""
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_response_has_required_fields(self, mock_execute, client, auth_headers):
"""
Test LibreChat response has required fields: session_id, files, stdout, stderr.
LibreChat reads these 4 fields from the response (from @librechat/agents ExecuteResult type).
"""
mock_execute.return_value = ExecResponse(
session_id="resp-session-123", stdout="test output\n", stderr="", files=[]
)
response = client.post(
"/exec", json={"code": "print('test')", "lang": "py"}, headers=auth_headers
)
data = response.json()
# Must have these four fields
assert "session_id" in data
assert "files" in data
assert "stdout" in data
assert "stderr" in data
# Verify types
assert isinstance(data["session_id"], str)
assert isinstance(data["files"], list)
assert isinstance(data["stdout"], str)
assert isinstance(data["stderr"], str)
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_stdout_ends_with_newline(self, mock_execute, client, auth_headers):
"""
Test that stdout ends with newline.
LibreChat UI expects this for proper display.
"""
mock_execute.return_value = ExecResponse(
session_id="resp-session-123", stdout="hello\n", stderr="", files=[]
)
response = client.post(
"/exec", json={"code": "print('hello')", "lang": "py"}, headers=auth_headers
)
data = response.json()
assert data["stdout"].endswith(
"\n"
), "stdout must end with newline for LibreChat"
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_files_array_format(self, mock_execute, client, auth_headers):
"""
Test generated files format: {id, name, path?}
LibreChat expects: {"id": "...", "name": "...", "path": "..."}
"""
mock_execute.return_value = ExecResponse(
session_id="resp-session-123",
stdout="",
stderr="",
files=[FileRef(id="gen-file-abc", name="output.png", path="/output.png")],
)
response = client.post(
"/exec", json={"code": "generate image", "lang": "py"}, headers=auth_headers
)
data = response.json()
assert len(data["files"]) == 1
file_ref = data["files"][0]
# Required fields for LibreChat
assert "id" in file_ref, "File must have 'id' field"
assert "name" in file_ref, "File must have 'name' field"
# path is optional but typically included
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_empty_stderr_on_success(self, mock_execute, client, auth_headers):
"""Test stderr is empty string on successful execution."""
mock_execute.return_value = ExecResponse(
session_id="resp-session-123", stdout="ok\n", stderr="", files=[]
)
response = client.post(
"/exec", json={"code": "print('ok')", "lang": "py"}, headers=auth_headers
)
data = response.json()
assert data["stderr"] == "", "stderr should be empty on success"
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_stderr_populated_on_error(self, mock_execute, client, auth_headers):
"""Test stderr contains error message on failure."""
mock_execute.return_value = ExecResponse(
session_id="resp-session-123",
stdout="",
stderr="Traceback: Exception: error\n",
files=[],
)
response = client.post(
"/exec",
json={"code": "raise Exception('error')", "lang": "py"},
headers=auth_headers,
)
data = response.json()
assert len(data["stderr"]) > 0, "stderr should contain the error"
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_session_id_is_string(self, mock_execute, client, auth_headers):
"""Test session_id is always a non-empty string."""
mock_execute.return_value = ExecResponse(
session_id="resp-session-123", stdout="", stderr="", files=[]
)
response = client.post(
"/exec", json={"code": "pass", "lang": "py"}, headers=auth_headers
)
data = response.json()
assert isinstance(data["session_id"], str)
assert len(data["session_id"]) > 0
# =============================================================================
# LIBRECHAT FILE UPLOAD FORMAT
# =============================================================================
class TestLibreChatFileUpload:
"""Test /upload format exactly as LibreChat sends it.
LibreChat uploads files via POST /upload with:
- 'file' field (singular) containing the file
- 'entity_id' field (optional)
- Headers: X-API-Key, User-Id, User-Agent: 'LibreChat/1.0'
From crud.js: form.append('file', stream, filename)
"""
@pytest.fixture(autouse=True)
def setup_mocks(self):
"""Set up mocks."""
mock_file_service = AsyncMock()
mock_file_service.store_uploaded_file.return_value = "lc-file-123"
mock_file_service.validate_uploads = MagicMock(return_value=None)
mock_session_service = AsyncMock()
mock_session_service.create_session.return_value = Session(
session_id="upload-session-123",
status=SessionStatus.ACTIVE,
created_at=datetime.now(timezone.utc),
last_activity=datetime.now(timezone.utc),
expires_at=datetime.now(timezone.utc) + timedelta(hours=24),
metadata={},
)
from src.dependencies.services import get_file_service, get_session_service
app.dependency_overrides[get_file_service] = lambda: mock_file_service
app.dependency_overrides[get_session_service] = lambda: mock_session_service
yield
app.dependency_overrides.clear()
def test_multipart_upload_format(self, client, auth_headers):
"""
Test LibreChat multipart upload format.
LibreChat sends: multipart/form-data with 'file' (singular) field and 'entity_id'.
From crud.js: form.append('file', stream, filename)
"""
# LibreChat uses 'file' (singular), not 'files'
files = {
"file": ("document.pdf", io.BytesIO(b"PDF content"), "application/pdf")
}
data = {"entity_id": "asst_librechat"}
response = client.post("/upload", files=files, data=data, headers=auth_headers)
assert response.status_code == 200
result = response.json()
# API returns {message, session_id, files: [{fileId, filename}]}
# LibreChat checks: if (result.message !== 'success') throw error
assert result.get("message") == "success", "LibreChat expects message='success'"
assert "files" in result
assert len(result["files"]) == 1
assert "session_id" in result
file_info = result["files"][0]
assert "fileId" in file_info
assert "filename" in file_info
def test_upload_response_has_session_id(self, client, auth_headers):
"""Test that upload response includes a session_id."""
entity_id = "asst_specific_entity"
# LibreChat uses 'file' (singular)
files = {"file": ("test.txt", io.BytesIO(b"content"), "text/plain")}
data = {"entity_id": entity_id}
response = client.post("/upload", files=files, data=data, headers=auth_headers)
result = response.json()
# API generates a new session_id for uploads (entity_id is currently not used)
assert "session_id" in result
assert len(result["session_id"]) > 0
def test_librechat_upload_with_user_id_header(self, client, auth_headers):
"""
Test LibreChat upload includes User-Id header.
LibreChat sends: 'User-Id': req.user.id
From crud.js: headers: { 'User-Id': req.user.id }
"""
files = {"file": ("test.txt", io.BytesIO(b"content"), "text/plain")}
data = {"entity_id": "asst_test"}
# Add User-Id header as LibreChat does
headers = {
**auth_headers,
"User-Id": "user_abc123",
"User-Agent": "LibreChat/1.0",
}
response = client.post("/upload", files=files, data=data, headers=headers)
# Should accept the User-Id header without error
assert response.status_code == 200
# =============================================================================
# LIBRECHAT FILE RETRIEVAL
# =============================================================================
class TestLibreChatFileRetrieval:
"""Test file retrieval endpoints as LibreChat uses them.
LibreChat uses these endpoints to:
1. GET /files/{session_id}?detail=... - List session files
2. GET /download/{session_id}/{fileId} - Download generated files
From CodeExecutor.ts and process.js
"""
@pytest.fixture(autouse=True)
def setup_mocks(self):
"""Set up mocks for file service."""
self.mock_file_service = AsyncMock()
from src.dependencies.services import get_file_service
app.dependency_overrides[get_file_service] = lambda: self.mock_file_service
yield
app.dependency_overrides.clear()
def test_files_endpoint_with_detail_summary(self, client, auth_headers):
"""
Test GET /files/{session_id}?detail=summary endpoint.
LibreChat calls this to check if session files exist.
From process.js: GET /files/{session_id}?detail=summary
"""
self.mock_file_service.list_files.return_value = [
FileInfo(
file_id="file-123",
filename="output.png",
size=1024,
content_type="image/png",
created_at=datetime.now(timezone.utc),
path="/output.png",
)
]
response = client.get(
"/files/test-session-123?detail=summary", headers=auth_headers
)
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
assert len(data) == 1
item = data[0]
assert "name" in item, "Summary must have 'name' field"
assert "lastModified" in item, "Summary must have 'lastModified' field"
# LibreChat parses name with: file.name.startsWith(path) where path = "session_id/fileId"
assert (
item["name"] == "test-session-123/file-123"
), f"name must be 'session_id/fileId' format, got: {item['name']}"
# lastModified must be ISO 8601 with Z suffix for LibreChat's Date parsing
assert item["lastModified"].endswith(
"Z"
), f"lastModified must end with 'Z', got: {item['lastModified']}"
def test_files_endpoint_with_detail_full(self, client, auth_headers):
"""
Test GET /files/{session_id}?detail=full endpoint.
LibreChat calls this to get full file metadata for execution.
From CodeExecutor.ts: GET /files/{session_id}?detail=full
"""
self.mock_file_service.list_files.return_value = [
FileInfo(
file_id="file-456",
filename="data.csv",
size=2048,
content_type="text/csv",
created_at=datetime.now(timezone.utc),
path="/data.csv",
)
]
response = client.get(
"/files/test-session-456?detail=full", headers=auth_headers
)
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
def test_download_endpoint(self, client, auth_headers):
"""
Test GET /download/{session_id}/{fileId} endpoint.
LibreChat downloads generated files using this endpoint.
From crud.js: GET /download/{session_id}/{fileId} with responseType: 'arraybuffer'
"""
self.mock_file_service.get_file_info.return_value = FileInfo(
file_id="file-abc",
filename="output.txt",
size=17,
content_type="text/plain",
created_at=datetime.now(timezone.utc),
path="/output.txt",
)
self.mock_file_service.get_file_content.return_value = b"file content here"
response = client.get(
"/download/test-session-789/file-abc", headers=auth_headers
)
assert response.status_code == 200
assert response.content == b"file content here"
assert "content-disposition" in response.headers
# =============================================================================
# LIBRECHAT AUTHENTICATION
# =============================================================================
class TestLibreChatAuthentication:
"""Test authentication exactly as LibreChat uses it.
LibreChat only uses X-API-Key header for authentication.
From CodeExecutor.ts: headers: { 'X-API-Key': apiKey }
"""
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_x_api_key_header(self, mock_execute, client):
"""
Test x-api-key header authentication on protected endpoint.
LibreChat sends: headers: { 'X-API-Key': apiKey }
"""
mock_execute.return_value = ExecResponse(
session_id="auth-test", stdout="ok\n", stderr="", files=[]
)
headers = {"x-api-key": "test-api-key-for-testing-12345"}
response = client.post(
"/exec", json={"code": "print('ok')", "lang": "py"}, headers=headers
)
assert response.status_code == 200
# =============================================================================
# LIBRECHAT ERROR HANDLING
# =============================================================================
class TestLibreChatErrors:
"""Test error handling as LibreChat expects.
Critical: Code execution errors must return HTTP 200 with error in stderr.
LibreChat does NOT expect HTTP 4xx/5xx for code errors - only for API errors.
"""
def test_validation_error_format(self, client, auth_headers):
"""Test validation errors have expected format."""
# Missing required field - no mock needed, this tests request validation
response = client.post("/exec", json={"lang": "py"}, headers=auth_headers)
assert response.status_code == 422
data = response.json()
# API uses custom error format with 'error' field
assert "error" in data or "detail" in data
def test_auth_error_format(self, client):
"""Test authentication errors have expected format."""
# No mock needed - this tests auth middleware
response = client.post("/exec", json={"code": "test", "lang": "py"})
assert response.status_code == 401
data = response.json()
assert "error" in data
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_execution_error_returns_200(self, mock_execute, client, auth_headers):
"""
Test that code execution errors still return 200.
LibreChat expects 200 with error in stderr, not HTTP error.
"""
mock_execute.return_value = ExecResponse(
session_id="err-session",
stdout="",
stderr="SyntaxError: invalid syntax\n",
files=[],
)
response = client.post(
"/exec",
json={"code": "this is not valid python [[[", "lang": "py"},
headers=auth_headers,
)
# CRITICAL: Should return 200, not 4xx or 5xx
assert response.status_code == 200
data = response.json()
# Should have standard response format with error in stderr
assert "session_id" in data
assert "files" in data
assert "stdout" in data
assert "stderr" in data
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_timeout_returns_200(self, mock_execute, client, auth_headers):
"""Test that timeout still returns 200 with appropriate message."""
mock_execute.return_value = ExecResponse(
session_id="timeout-session",
stdout="",
stderr="Execution timed out after 30 seconds\n",
files=[],
)
response = client.post(
"/exec",
json={"code": "import time; time.sleep(9999)", "lang": "py"},
headers=auth_headers,
)
# Should return 200 even for timeout
assert response.status_code == 200
# =============================================================================
# LIBRECHAT FILE LIFECYCLE
# =============================================================================
class TestLibreChatFileLifecycle:
"""Test the complete file lifecycle as LibreChat performs it.
Full flow:
1. Upload file via POST /upload (with 'file' singular field)
2. Execute code referencing the uploaded file
3. Check output files via GET /files/{session_id}?detail=summary
4. Download output file via GET /download/{session_id}/{fileId}
"""
@pytest.fixture(autouse=True)
def setup_mocks(self):
"""Set up mocks for full lifecycle tests."""
self.mock_file_service = AsyncMock()
self.mock_file_service.store_uploaded_file.return_value = "uploaded-file-001"
self.mock_file_service.validate_uploads = MagicMock(return_value=None)
self.mock_session_service = AsyncMock()
self.mock_session_service.create_session.return_value = Session(
session_id="lifecycle-session-123",
status=SessionStatus.ACTIVE,
created_at=datetime.now(timezone.utc),
last_activity=datetime.now(timezone.utc),
expires_at=datetime.now(timezone.utc) + timedelta(hours=24),
metadata={},
)
from src.dependencies.services import get_file_service, get_session_service
app.dependency_overrides[get_file_service] = lambda: self.mock_file_service
app.dependency_overrides[get_session_service] = (
lambda: self.mock_session_service
)
yield
app.dependency_overrides.clear()
def test_upload_then_check_summary(self, client, auth_headers):
"""
Test upload a file, then verify it appears in session file summary.
This is the primeFiles check: upload -> GET /files/{session_id}?detail=summary
"""
# Step 1: Upload file (LibreChat uses 'file' singular)
upload_files = {
"file": ("data.csv", io.BytesIO(b"col1,col2\n1,2\n"), "text/csv")
}
upload_data = {"entity_id": "asst_test_agent"}
upload_response = client.post(
"/upload", files=upload_files, data=upload_data, headers=auth_headers
)
assert upload_response.status_code == 200
upload_result = upload_response.json()
assert upload_result["message"] == "success"
session_id = upload_result["session_id"]
file_id = upload_result["files"][0]["fileId"]
# Step 2: Check summary endpoint
self.mock_file_service.list_files.return_value = [
FileInfo(
file_id=file_id,
filename="data.csv",
size=14,
content_type="text/csv",
created_at=datetime.now(timezone.utc),
path="/data.csv",
)
]
summary_response = client.get(
f"/files/{session_id}?detail=summary", headers=auth_headers
)
assert summary_response.status_code == 200
summary_data = summary_response.json()
assert isinstance(summary_data, list)
assert len(summary_data) >= 1
# Verify format matches what LibreChat's process.js parses
item = summary_data[0]
assert "name" in item
assert "lastModified" in item
# name must be in "session_id/fileId" format
assert "/" in item["name"], "name must contain '/' separator"
@patch("src.services.orchestrator.ExecutionOrchestrator.execute")
def test_upload_then_exec_with_file_ref(self, mock_execute, client, auth_headers):
"""
Test upload a file, then execute code that references it.
LibreChat sends the session_id and fileId from upload response in exec request.
"""
# Step 1: Upload
upload_files = {"file": ("input.txt", io.BytesIO(b"hello world"), "text/plain")}
upload_response = client.post(
"/upload",
files=upload_files,
data={"entity_id": "asst_test"},
headers=auth_headers,
)
assert upload_response.status_code == 200
upload_result = upload_response.json()
session_id = upload_result["session_id"]
file_id = upload_result["files"][0]["fileId"]
# Step 2: Execute with file reference
mock_execute.return_value = ExecResponse(
session_id=session_id,
stdout="hello world\n",
stderr="",
files=[],
)
exec_response = client.post(
"/exec",
json={
"code": "with open('/mnt/data/input.txt') as f: print(f.read())",
"lang": "py",
"files": [
{"id": file_id, "session_id": session_id, "name": "input.txt"}
],
},
headers=auth_headers,
)
assert exec_response.status_code == 200
exec_data = exec_response.json()
assert exec_data["session_id"] == session_id
assert exec_data["stdout"] == "hello world\n"
def test_download_output_file(self, client, auth_headers):
"""
Test downloading an output file as LibreChat does.
LibreChat calls: GET /download/{session_id}/{fileId} with responseType: 'arraybuffer'
From crud.js: axios({ method: 'get', url, responseType: 'arraybuffer' })
"""
session_id = "lifecycle-session-123"
file_id = "output-file-456"
file_content = b"\x89PNG\r\n\x1a\n fake image content"
self.mock_file_service.get_file_info.return_value = FileInfo(
file_id=file_id,
filename="chart.png",
size=len(file_content),
content_type="image/png",
created_at=datetime.now(timezone.utc),
path="/chart.png",
)
self.mock_file_service.get_file_content.return_value = file_content
response = client.get(f"/download/{session_id}/{file_id}", headers=auth_headers)
assert response.status_code == 200
assert response.content == file_content
assert "content-disposition" in response.headers
def test_librechat_user_agent_header(self, client, auth_headers):
"""
Test that User-Agent: LibreChat/1.0 header works correctly.
LibreChat always sends this header. Verify it doesn't cause issues.
"""
headers = {
**auth_headers,
"User-Agent": "LibreChat/1.0",
"User-Id": "user_abc123",
}
upload_files = {"file": ("test.txt", io.BytesIO(b"test"), "text/plain")}
response = client.post("/upload", files=upload_files, headers=headers)
assert response.status_code == 200
# =============================================================================
# LIBRECHAT PRIME FILES FLOW
# =============================================================================
class TestLibreChatPrimeFiles:
"""Test the primeFiles() flow from LibreChat's process.js.
primeFiles() checks if previously uploaded files still exist in the
code interpreter session, and re-uploads them if they've expired.
Flow:
1. GET /files/{session_id}?detail=summary
2. Check response for file by matching name.startsWith("session_id/fileId")
3. Check if lastModified is less than 23 hours old
4. If missing or expired, re-upload via POST /upload
"""
@pytest.fixture(autouse=True)
def setup_mocks(self):
"""Set up mocks for primeFiles tests."""
self.mock_file_service = AsyncMock()
self.mock_file_service.validate_uploads = MagicMock(return_value=None)
self.mock_file_service.store_uploaded_file.return_value = "reuploaded-file-001"
self.mock_session_service = AsyncMock()
self.mock_session_service.create_session.return_value = Session(
session_id="prime-session-123",
status=SessionStatus.ACTIVE,
created_at=datetime.now(timezone.utc),
last_activity=datetime.now(timezone.utc),
expires_at=datetime.now(timezone.utc) + timedelta(hours=24),
metadata={},
)
from src.dependencies.services import get_file_service, get_session_service
app.dependency_overrides[get_file_service] = lambda: self.mock_file_service
app.dependency_overrides[get_session_service] = (
lambda: self.mock_session_service
)
yield
app.dependency_overrides.clear()
def test_prime_files_check_existing(self, client, auth_headers):
"""
Test checking if a file exists via summary endpoint.
LibreChat calls: GET /files/{session_id}?detail=summary
Then checks: response.data.find(file => file.name.startsWith(path))
"""
session_id = "prime-session-123"
file_id = "prime-file-456"
self.mock_file_service.list_files.return_value = [
FileInfo(
file_id=file_id,
filename="data.csv",
size=100,
content_type="text/csv",
created_at=datetime.now(timezone.utc),
path="/data.csv",
)
]
response = client.get(
f"/files/{session_id}?detail=summary", headers=auth_headers
)
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
assert len(data) == 1
# Simulate LibreChat's client-side parsing:
# file.name.startsWith("session_id/fileId")
file_identifier = f"{session_id}/{file_id}"
matching = [f for f in data if f["name"].startswith(file_identifier)]
assert (
len(matching) == 1
), f"LibreChat expects to find file by name.startsWith('{file_identifier}')"
def test_prime_files_reupload_flow(self, client, auth_headers):
"""
Test the re-upload flow when file is expired.
After checking summary, LibreChat re-uploads via POST /upload
if the file is missing or expired (>23 hours old).
"""
session_id = "expired-session-123"
# Step 1: Summary returns empty (file expired/cleaned up)
self.mock_file_service.list_files.return_value = []
response = client.get(
f"/files/{session_id}?detail=summary", headers=auth_headers
)
assert response.status_code == 200
data = response.json()
assert data == [], "Empty session should return empty array"
# Step 2: Re-upload the file (LibreChat uses 'file' singular)
upload_files = {"file": ("data.csv", io.BytesIO(b"col1,col2\n"), "text/csv")}
upload_data = {"entity_id": "asst_reupload_test"}
upload_response = client.post(
"/upload", files=upload_files, data=upload_data, headers=auth_headers
)
assert upload_response.status_code == 200
result = upload_response.json()
assert result["message"] == "success"
assert "session_id" in result
assert len(result["files"]) == 1
def test_prime_files_empty_session_returns_empty_array(self, client, auth_headers):
"""
Test that non-existent session returns empty array, not 404.
LibreChat expects an empty array for sessions with no files.
A 404 would cause an error in primeFiles().
"""
self.mock_file_service.list_files.return_value = []
response = client.get(
"/files/nonexistent-session-xyz?detail=summary", headers=auth_headers
)
assert response.status_code == 200
data = response.json()
assert data == [], "Non-existent session must return [], not 404"
def test_prime_files_name_format_matches_client_parsing(self, client, auth_headers):
"""
Test that the name field format can be parsed by LibreChat.
LibreChat splits the fileIdentifier as:
const [path, queryString] = fileIdentifier.split('?')
const [session_id, id] = path.split('/')
So the name in summary must be "session_id/fileId" format.
"""
session_id = "parse-test-session"
file_id = "parse-test-file"
self.mock_file_service.list_files.return_value = [
FileInfo(
file_id=file_id,
filename="result.json",
size=50,
content_type="application/json",
created_at=datetime.now(timezone.utc),
path="/result.json",
)
]
response = client.get(