-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathembedding.txt
5810 lines (4862 loc) · 195 KB
/
embedding.txt
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
--- BEGIN FILE: CONTRIBUTING.md ---
# Contributing to ClaudeSync
We're excited that you're interested in contributing to ClaudeSync! This document outlines the process for contributing to this project.
## Getting Started
1. Fork the repository on GitHub.
2. Clone your fork locally:
```
git clone https://github.com/your-username/claudesync.git
```
3. Create a new branch for your feature or bug fix:
```
git checkout -b feature/your-feature-name
```
## Setting Up the Development Environment
1. Ensure you have Python 3.6 or later installed.
2. Install the development dependencies:
```
pip install -r requirements.txt
```
3. Install the package in editable mode:
```
pip install -e .
```
## Making Changes
1. Make your changes in your feature branch.
2. Add or update tests as necessary.
3. Run the tests to ensure they pass:
```
python -m unittest discover tests
```
4. Update the documentation if you've made changes to the API or added new features.
## Submitting Changes
1. Commit your changes:
```
git commit -am "Add a brief description of your changes"
```
2. Push to your fork:
```
git push origin feature/your-feature-name
```
3. Submit a pull request through the GitHub website.
## Code Style
We follow the black style guide for Python code. Please ensure your code adheres to this style.
## Reporting Bugs
If you find a bug, please open an issue on the GitHub repository using our bug report template. To do this:
1. Go to the [Issues](https://github.com/jahwag/claudesync/issues) page of the ClaudeSync repository.
2. Click on "New Issue".
3. Select the "Bug Report" template.
4. Fill out the template with as much detail as possible.
When reporting a bug, please include:
- A clear and concise description of the bug
- Steps to reproduce the behavior
- Expected behavior
- Any error messages or stack traces
- Your environment details (OS, Python version, ClaudeSync version)
- Your ClaudeSync configuration (use `claudesync config list`)
- Any relevant logs (you can increase log verbosity with `claudesync config set log_level DEBUG`)
The more information you provide, the easier it will be for us to reproduce and fix the bug.
## Requesting Features
If you have an idea for a new feature, please open an issue on the GitHub repository. Describe the feature and why you think it would be useful for the project.
## Questions
If you have any questions about contributing, feel free to open an issue for discussion.
Thank you for your interest in improving ClaudeSync!
--- END FILE: CONTRIBUTING.md ---
--- BEGIN FILE: requirements.txt ---
click>=8.1.7
click_completion>=0.5.2
pathspec>=0.12.1
pytest>=8.3.2
python_crontab>=3.2.0
setuptools>=73.0.1
sseclient_py>=1.8.0
tqdm>=4.66.5
pytest-cov>=5.0.0
crontab>=1.0.1
python-crontab>=3.2.0
Brotli>=1.1.0
cryptography>=42.0.4
--- END FILE: requirements.txt ---
--- BEGIN FILE: LICENSE ---
MIT License
Copyright (c) 2024 Jahziah Wagner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--- END FILE: LICENSE ---
--- BEGIN FILE: SECURITY.md ---
# Security Policy
## Reporting Vulnerabilities
We take security seriously and appreciate your help in keeping **claudesync** secure. If you discover a security vulnerability, please follow these guidelines:
1. **Public Disclosure:** If the issue can be safely disclosed, feel free to [open an issue](https://github.com/jahwag/claudesync/issues).
2. **Private Disclosure:** If the issue should not be made public, please contact me directly via DM on Discord:
- **Discord:** [@jahwag](https://discord.gg/pR4qeMH4u4)
--- END FILE: SECURITY.md ---
--- BEGIN FILE: embedding.txt ---
--- END FILE: embedding.txt ---
--- BEGIN FILE: renovate.json ---
{
"extends": ["config:base"],
"pip_requirements": {
"enabled": true
},
"packageRules": [
{
"matchManagers": ["pip_requirements"],
"matchUpdateTypes": ["minor", "patch"],
"groupName": "All non-major Python updates"
},
{
"matchManagers": ["github-actions"],
"groupName": "GitHub Actions updates"
}
],
"automerge": false,
"timezone": "UTC",
"schedule": ["after 10pm and before 5am"],
"labels": ["dependencies", "renovate"],
"dependencyDashboard": true,
"prHourlyLimit": 5,
"prConcurrentLimit": 10
}
--- END FILE: renovate.json ---
--- BEGIN FILE: README.md ---
# ClaudeSync
[](https://opensource.org/licenses/MIT)
[](https://pypi.org/project/claudesync/)
[](https://github.com/jahwag/claudesync/releases)
[](https://github.com/jahwag/ClaudeSync/actions/workflows/python-package.yml)
[](https://github.com/jahwag/claudesync/issues)
[](https://github.com/psf/black)
[](https://github.com/jahwag/claudesync/network/dependencies)
[](https://github.com/jahwag/claudesync/commits/main)
[](https://github.com/sponsors/jahwag)
ClaudeSync bridges your local development environment with Claude.ai projects, enabling seamless synchronization to enhance your AI-powered workflow.

## ⚠️ Disclaimer
ClaudeSync is an independent, open-source project **not affiliated** with Anthropic or Claude.ai. By using ClaudeSync, you agree to:
1. Use it at your own risk.
2. Acknowledge potential violation of Anthropic's Terms of Service.
3. Assume responsibility for any consequences.
4. Understand that Anthropic does not support this tool.
Please review [Anthropic's Terms of Service](https://www.anthropic.com/legal/consumer-terms) before using ClaudeSync.
## 🌟 Features
- **File sync**: Synchronize local files with [Claude.ai projects](https://www.anthropic.com/news/projects).
- **Cross-Platform**: Compatible with [Windows, macOS, and Linux](https://github.com/jahwag/ClaudeSync/releases).
- **Configurable**: Plenty of [configuration options](https://github.com/jahwag/ClaudeSync/wiki/Quick-reference).
- **Integrate**: Designed to be easy to integrate into your pipelines.
- **Secure**: Ensures data privacy and security.
## ⚙️ Prerequisites
### 📄 Supported Claude.ai plans
| [Plan](https://www.anthropic.com/pricing) | Supported |
|--------|-----------|
| Pro | ✅ |
| Team | ✅ |
| Free | ❌ |
### 🔑 SSH Key
Ensure you have an SSH key for secure credential storage. Follow [GitHub's guide](https://docs.github.com/en/authentication/connecting-to-github-with-ssh) to generate and add your SSH key.
### 💻 Software
- **Python**: ≥ [3.10](https://www.python.org/downloads/)
- **pip**: [Python package installer](https://pip.pypa.io/en/stable/installation/)
## 🚀 Quick Start
1. **Install ClaudeSync**
```shell
pip install claudesync
```
2. **Authenticate**
```shell
claudesync auth login
```
3. **Create a Project**
```shell
claudesync project create
```
4. **Start Syncing***
```shell
claudesync push
```
**This is a one-way sync. Files not present locally will be removed from the Claude.ai project unless pruning is [disabled](https://github.com/jahwag/ClaudeSync/wiki/Quick-reference#pruning-remote).*
📚 [Detailed Guides & FAQs](https://github.com/jahwag/claudesync/wiki)
## 🤝 Support & Contribute
Enjoying ClaudeSync? Support us by:
- ⭐ [Starring the Repository](https://github.com/jahwag/claudesync)
- 🐛 [Reporting Issues](https://github.com/jahwag/claudesync/issues)
- 🌍 [Contributing](CONTRIBUTING.md)
- 💬 [Join Our Discord](https://discord.gg/pR4qeMH4u4)
- 💖 [Sponsor Us](https://github.com/sponsors/jahwag)
Your contributions help improve ClaudeSync!
---
[Contributors](https://github.com/jahwag/claudesync/graphs/contributors) • [License](https://github.com/jahwag/claudesync/blob/master/LICENSE) • [Report Bug](https://github.com/jahwag/claudesync/issues) • [Request Feature](https://github.com/jahwag/claudesync/issues/new?labels=enhancement&template=feature_request.md)• [Sponsor](https://github.com/sponsors/jahwag)
--- END FILE: README.md ---
--- BEGIN FILE: CODEOWNERS ---
# Default owner for everything in the repo
* @jahwag
--- END FILE: CODEOWNERS ---
--- BEGIN FILE: pytest.ini ---
[pytest]
testpaths = tests
python_files = test_*.py
addopts = -v --cov=claudesync --cov-report=term-missing
--- END FILE: pytest.ini ---
--- BEGIN FILE: pyproject.toml ---
[project]
name = "claudesync"
version = "0.7.1"
authors = [
{name = "Jahziah Wagner", email = "[email protected]"},
]
description = "A tool to synchronize local files with Claude.ai projects"
license = {file = "LICENSE"}
readme = "README.md"
requires-python = ">=3.10"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
dependencies = [
"click>=8.1.7",
"click_completion>=0.5.2",
"pathspec>=0.12.1",
"pytest>=8.3.2",
"python_crontab>=3.2.0",
"setuptools>=73.0.1",
"sseclient_py>=1.8.0",
"tqdm>=4.66.5",
"pytest-cov>=5.0.0",
"crontab>=1.0.1",
"python-crontab>=3.2.0",
"Brotli>=1.1.0",
"cryptography>=42.0.4",
]
keywords = [
"sync",
"files",
"Claude.ai",
"automation",
"synchronization",
"project management",
"file management",
"cloud sync",
"cli tool",
"command line",
"productivity",
"development tools",
"file synchronization",
"continuous integration",
"devops",
"version control"
]
[project.optional-dependencies]
test = [
"pytest>=8.2.2",
"pytest-cov>=5.0.0",
]
[project.urls]
"Homepage" = "https://github.com/jahwag/claudesync"
"Bug Tracker" = "https://github.com/jahwag/claudesync/issues"
[project.scripts]
claudesync = "claudesync.cli.main:cli"
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[tool.setuptools.packages.find]
where = ["src"]
include = ["claudesync*"]
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = "test_*.py"
addopts = "-v --cov=claudesync --cov-report=term-missing"
--- END FILE: pyproject.toml ---
--- BEGIN FILE: .gitignore ---
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
.idea
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
**/*.egg-info
__pycache__
# claude
claude.sync
config.json
claudesync.log
claude_chats
some_value
.claudesync
ROADMAP.md
--- END FILE: .gitignore ---
--- BEGIN FILE: setup.py ---
from setuptools import setup, find_packages
setup(
packages=find_packages(where="src"),
package_dir={"": "src"},
)
--- END FILE: setup.py ---
--- BEGIN FILE: tests/test_chat_happy_path.py ---
import unittest
import threading
import time
from click.testing import CliRunner
from claudesync.cli.main import cli
from claudesync.configmanager import InMemoryConfigManager
from mock_http_server import run_mock_server
class TestChatHappyPath(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Start the mock server in a separate thread
cls.mock_server_thread = threading.Thread(target=run_mock_server)
cls.mock_server_thread.daemon = True
cls.mock_server_thread.start()
time.sleep(1) # Give the server a moment to start
def setUp(self):
self.runner = CliRunner()
self.config = InMemoryConfigManager()
self.config.set("claude_api_url", "http://localhost:8000/api")
def test_chat_happy_path(self):
# Step 1: Login
result = self.runner.invoke(
cli,
["auth", "login", "--provider", "claude.ai"],
input="sk-ant-1234\nThu, 26 Sep 2099 17:07:53 UTC\n",
obj=self.config,
)
self.assertEqual(result.exit_code, 0)
self.assertIn("Successfully authenticated with claude.ai", result.output)
# Step 2: Set organization
result = self.runner.invoke(
cli, ["organization", "set"], input="1\n", obj=self.config
)
self.assertEqual(result.exit_code, 0)
self.assertIn("Selected organization: Test Org 1", result.output)
# Step 3: Create project using init --new
result = self.runner.invoke(
cli,
[
"project",
"init",
"--new",
"--name",
"Test Project",
"--description",
"Test Description",
"--local-path",
".",
],
obj=self.config,
)
self.assertEqual(result.exit_code, 0)
self.assertIn(
"Project 'New Project' (uuid: new_proj) has been created successfully",
result.output,
)
# Step 4: Send message
result = self.runner.invoke(
cli, ["chat", "message", "Hello, Claude!"], input="1\n", obj=self.config
)
self.assertEqual(result.exit_code, 0)
self.assertIn("Hello there.", result.output)
self.assertIn("I apologize for the confusion. You're right.", result.output)
if __name__ == "__main__":
unittest.main()
--- END FILE: tests/test_chat_happy_path.py ---
--- BEGIN FILE: tests/test_happy_path.py ---
import threading
import time
import unittest
from click.testing import CliRunner
from unittest.mock import patch
from claudesync.cli.main import cli
from claudesync.configmanager import InMemoryConfigManager
from mock_http_server import run_mock_server
class TestClaudeSyncHappyPath(unittest.TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.mock_server_thread = threading.Thread(target=run_mock_server)
cls.mock_server_thread.daemon = True
cls.mock_server_thread.start()
time.sleep(1) # Wait for the mock server to start
def setUp(self):
self.runner = CliRunner()
self.config = InMemoryConfigManager()
self.config.set(
"claude_api_url", "http://127.0.0.1:8000/api"
) # Set BASE_URL for the mock server
@patch("claudesync.utils.get_local_files")
def test_happy_path(self, mock_get_local_files):
# Mock the API calls
mock_get_local_files.return_value = {"test.txt": "content_hash"}
# Login
result = self.runner.invoke(
cli,
["auth", "login", "--provider", "claude.ai"],
input="sk-ant-1234\nThu, 26 Sep 2099 17:07:53 UTC\n",
obj=self.config,
)
self.assertEqual(0, result.exit_code)
self.assertIn("Successfully authenticated with claude.ai", result.output)
# Create project using init --new
result = self.runner.invoke(
cli,
[
"project",
"init",
"--new",
"--name",
"New Project",
"--description",
"Test description",
"--local-path",
"./",
"--provider",
"claude.ai",
],
obj=self.config,
)
self.assertEqual(result.exit_code, 0)
self.assertIn(
"Project 'New Project' (uuid: new_proj) has been created successfully",
result.output,
)
self.assertIn("Project created:", result.output)
self.assertIn("Project location:", result.output)
self.assertIn("Project config location:", result.output)
self.assertIn("Remote URL: https://claude.ai/project/new_proj", result.output)
# Push project
result = self.runner.invoke(cli, ["push"], obj=self.config)
self.assertEqual(result.exit_code, 0)
self.assertIn("Main project 'New Project' synced successfully", result.output)
if __name__ == "__main__":
unittest.main()
--- END FILE: tests/test_happy_path.py ---
--- BEGIN FILE: tests/mock_http_server.py ---
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
class MockClaudeAIHandler(BaseHTTPRequestHandler):
files = {} # Store files in memory
def do_GET(self):
parsed_path = urlparse(self.path)
if parsed_path.path.endswith("/chat_conversations"):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps(
[
{"uuid": "chat1", "name": "Test Chat 1"},
{"uuid": "chat2", "name": "Test Chat 2"},
]
)
self.wfile.write(response.encode())
elif "/chat_conversations/" in parsed_path.path:
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps(
{
"uuid": "chat1",
"name": "Test Chat 1",
"messages": [
{"uuid": "msg1", "content": "Hello"},
{"uuid": "msg2", "content": "World"},
],
}
)
self.wfile.write(response.encode())
else:
print(f"Received GET request: {self.path}")
# time.sleep(0.01) # Add a small delay to simulate network latency
parsed_path = urlparse(self.path)
if parsed_path.path == "/api/organizations":
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps(
[
{
"uuid": "org1",
"name": "Test Org 1",
"capabilities": ["chat", "claude_pro"],
},
{
"uuid": "org2",
"name": "Test Org 2",
"capabilities": ["chat"],
},
]
)
self.wfile.write(response.encode())
elif parsed_path.path.startswith(
"/api/organizations/"
) and parsed_path.path.endswith("/projects"):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps(
[
{
"uuid": "proj1",
"name": "Test Project 1",
"archived_at": None,
},
{
"uuid": "proj2",
"name": "Test Project 2",
"archived_at": "2023-01-01",
},
]
)
self.wfile.write(response.encode())
elif parsed_path.path.startswith(
"/api/organizations/"
) and parsed_path.path.endswith("/docs"):
org_id, project_id = (
parsed_path.path.split("/")[-3],
parsed_path.path.split("/")[-2],
)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
files = self.files.get(f"{org_id}/{project_id}", [])
response = json.dumps(files)
self.wfile.write(response.encode())
else:
self.send_error(404, "Not Found")
def do_POST(self):
content_length = int(self.headers["Content-Length"])
parsed_path = urlparse(self.path)
if parsed_path.path.endswith("/chat_conversations"):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps({"uuid": "new_chat", "name": "New Chat"})
self.wfile.write(response.encode())
elif parsed_path.path.endswith("/completion"):
self.send_response(200)
self.send_header("Content-type", "text/event-stream")
self.end_headers()
self.wfile.write(b'data: {"completion": "Hello"}\n\n')
self.wfile.write(b'data: {"completion": " there. "}\n\n')
self.wfile.write(
b'data: {"completion": "I apologize for the confusion. You\'re right."}\n\n'
)
self.wfile.write(b"event: done\n\n")
else:
# time.sleep(0.01) # Add a small delay to simulate network latency
content_length = int(self.headers["Content-Length"])
post_data = self.rfile.read(content_length)
parsed_path = urlparse(self.path)
if parsed_path.path.startswith(
"/api/organizations/"
) and parsed_path.path.endswith("/projects"):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps({"uuid": "new_proj", "name": "New Project"})
self.wfile.write(response.encode())
elif parsed_path.path.startswith(
"/api/organizations/"
) and parsed_path.path.endswith("/docs"):
org_id, project_id = (
parsed_path.path.split("/")[-3],
parsed_path.path.split("/")[-2],
)
data = json.loads(post_data.decode("utf-8"))
file_data = {
"uuid": f"file_{len(self.files.get(f'{org_id}/{project_id}', []))}",
"file_name": data["file_name"],
"content": data["content"],
"created_at": "2023-01-01T00:00:00Z",
}
if f"{org_id}/{project_id}" not in self.files:
self.files[f"{org_id}/{project_id}"] = []
self.files[f"{org_id}/{project_id}"].append(file_data)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(file_data).encode())
else:
self.send_error(404, "Not Found")
def do_DELETE(self):
# time.sleep(0.01) # Add a small delay to simulate network latency
parsed_path = urlparse(self.path)
if (
parsed_path.path.startswith("/api/organizations/")
and "/docs/" in parsed_path.path
):
org_id, project_id, file_uuid = (
parsed_path.path.split("/")[-4],
parsed_path.path.split("/")[-3],
parsed_path.path.split("/")[-1],
)
if f"{org_id}/{project_id}" in self.files:
self.files[f"{org_id}/{project_id}"] = [
f
for f in self.files[f"{org_id}/{project_id}"]
if f["uuid"] != file_uuid
]
self.send_response(204)
self.end_headers()
else:
self.send_error(404, "Not Found")
def run_mock_server(port=8000):
server_address = ("", port)
httpd = HTTPServer(server_address, MockClaudeAIHandler)
print(f"Mock server running on port {port}")
httpd.serve_forever()
if __name__ == "__main__":
run_mock_server()
--- END FILE: tests/mock_http_server.py ---
--- BEGIN FILE: tests/test_claude_ai.py ---
import unittest
import threading
import time
from unittest.mock import patch
from datetime import datetime
from claudesync.configmanager import InMemoryConfigManager
from claudesync.providers.claude_ai import ClaudeAIProvider
from claudesync.exceptions import ProviderError
from mock_http_server import run_mock_server
class TestClaudeAIProvider(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.mock_server_thread = threading.Thread(target=run_mock_server)
cls.mock_server_thread.daemon = True
cls.mock_server_thread.start()
time.sleep(1)
def setUp(self):
self.config = InMemoryConfigManager()
self.config.set("claude_api_url", "http://127.0.0.1:8000/api")
self.provider = ClaudeAIProvider(self.config)
def test_get_organizations(self):
organizations = self.provider.get_organizations()
self.assertEqual(len(organizations), 1)
self.assertEqual(organizations[0]["id"], "org1")
self.assertEqual(organizations[0]["name"], "Test Org 1")
def test_get_projects(self):
projects = self.provider.get_projects("org1")
self.assertEqual(len(projects), 1)
self.assertEqual(projects[0]["id"], "proj1")
self.assertEqual(projects[0]["name"], "Test Project 1")
def test_create_project(self):
new_project = self.provider.create_project(
"org1", "New Project", "Test description"
)
self.assertEqual(new_project["uuid"], "new_proj")
self.assertEqual(new_project["name"], "New Project")
def test_login(self):
expiry_str = "Thu, 26 Sep 2099 17:07:53 UTC"
with patch("click.prompt", side_effect=["sk-ant-test123", expiry_str]):
with patch.object(
self.provider,
"get_organizations",
return_value=[{"id": "org1", "name": "Test Org"}],
):
session_key, returned_expiry = self.provider.login()
self.assertEqual("sk-ant-test123", session_key)
self.assertIsInstance(returned_expiry, datetime)
def test_list_files(self):
with patch.object(
self.provider,
"_make_request",
return_value=[
{
"uuid": "file1",
"file_name": "test.txt",
"content": "Hello",
"created_at": "2023-01-01T00:00:00Z",
}
],
):
files = self.provider.list_files("org1", "proj1")
self.assertEqual(len(files), 1)
self.assertEqual(files[0]["uuid"], "file1")
self.assertEqual(files[0]["file_name"], "test.txt")
def test_upload_file(self):
with patch.object(
self.provider, "_make_request", return_value={"uuid": "file1"}
):
result = self.provider.upload_file("org1", "proj1", "test.txt", "Hello")
self.assertEqual(result["uuid"], "file1")
def test_delete_file(self):
with patch.object(self.provider, "_make_request", return_value=None):
result = self.provider.delete_file("org1", "proj1", "file1")
self.assertIsNone(result)
def test_archive_project(self):
with patch.object(
self.provider, "_make_request", return_value={"is_archived": True}
):
result = self.provider.archive_project("org1", "proj1")
self.assertTrue(result["is_archived"])
def test_get_published_artifacts(self):
with patch.object(
self.provider,
"_make_request",
return_value=[{"id": "artifact1", "name": "Test Artifact"}],
):
artifacts = self.provider.get_published_artifacts("org1")
self.assertEqual(len(artifacts), 1)
self.assertEqual(artifacts[0]["id"], "artifact1")
def test_get_artifact_content(self):
with patch.object(
self.provider,
"_make_request",
return_value=[
{