Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8b6e5b330 | ||
|
|
744f74442a | ||
|
|
23467b7b1f | ||
|
|
022d3d2f3e | ||
|
|
3bb72fe119 | ||
|
|
d8aa2f85df | ||
|
|
64d6938cf4 | ||
|
|
0a88719a3a | ||
|
|
0bc94bc24e | ||
|
|
19eb9e7227 | ||
|
|
aa5521dcfb | ||
|
|
2d03847ccd | ||
|
|
d303ac39cb | ||
|
|
48fc85e7fe | ||
|
|
0ea639196a | ||
|
|
6f51725732 | ||
|
|
8622b952ca | ||
|
|
f47c1f1046 | ||
|
|
145ddfc408 | ||
|
|
0bb787b90d | ||
|
|
59f23d7bfd | ||
|
|
4a4795e5f0 | ||
|
|
5b58f74e9a | ||
|
|
32dca3b76b | ||
|
|
6358444900 | ||
|
|
792ad4b5c1 | ||
|
|
d41781987c | ||
|
|
fc6507066e | ||
|
|
bf9c828aef | ||
|
|
7b676b76de | ||
|
|
d5f2333173 | ||
|
|
40e7dbdae9 | ||
|
|
a60daa1c76 | ||
|
|
bc1024caf0 | ||
|
|
a1c428b6e2 | ||
|
|
00f3efb95b | ||
|
|
7f3387a86c | ||
|
|
5462d50177 | ||
|
|
f82bae1668 | ||
|
|
9e60597174 | ||
|
|
afc807ac3f | ||
|
|
58ba4f1263 | ||
|
|
5513845fd5 | ||
|
|
33773ff17e | ||
|
|
64d21bd6d2 | ||
|
|
5210a833a5 | ||
|
|
5b1d5c1220 | ||
|
|
f4617e7b19 | ||
|
|
c426452239 | ||
|
|
73b2f255a9 | ||
|
|
ce463a5360 | ||
|
|
52fa6a7333 | ||
|
|
04298962be | ||
|
|
61f983098b | ||
|
|
32c1f98a02 | ||
|
|
5851b8aca4 | ||
|
|
3e2df5a782 | ||
|
|
f0cdaf94c2 | ||
|
|
48196e67a7 | ||
|
|
80a176fe1f | ||
|
|
42ea7cfae1 | ||
|
|
d2e6c82709 | ||
|
|
23b3f0c3d0 | ||
|
|
e08cea3a23 | ||
|
|
83eb396c40 | ||
|
|
59a383e1ea | ||
|
|
fb7260792f | ||
|
|
d8a485ea7e | ||
|
|
02989fe600 | ||
|
|
648f0676bd | ||
|
|
add5f34619 | ||
|
|
9403429a7a | ||
|
|
37cf0c1144 | ||
|
|
bf1f3e1c4f | ||
|
|
2aa11ae076 | ||
|
|
8888f6a0c9 | ||
|
|
ff8d87ddee | ||
|
|
3289a25e57 | ||
|
|
df5bde7e11 | ||
|
|
b3bca04caf | ||
|
|
bf71e0bc5e | ||
|
|
a542a3b168 | ||
|
|
56d13faa1a | ||
|
|
2a435aef66 | ||
|
|
28afb14004 | ||
|
|
8f3515572d | ||
|
|
529315b4c8 | ||
|
|
0a503d0cde | ||
|
|
d4a7e1ac0b | ||
|
|
be1abc88fd | ||
|
|
384f35084e | ||
|
|
1371ce2cce | ||
|
|
d6408a2949 | ||
|
|
e823f8f14e | ||
|
|
2b08d86696 | ||
|
|
e11fb6e778 | ||
|
|
d415558915 | ||
|
|
843d6d8678 | ||
|
|
754cded24a | ||
|
|
2b6640af1e | ||
|
|
9e29c9d728 | ||
|
|
ef2569196f | ||
|
|
34cef6202b | ||
|
|
25c7003226 | ||
|
|
46e63b3612 | ||
|
|
d373389703 | ||
|
|
bc12421736 | ||
|
|
8f11ea44a7 | ||
|
|
56660b04e9 | ||
|
|
2a237c2001 | ||
|
|
77716b4ccb | ||
|
|
fb18b2de16 | ||
|
|
0de5742b04 | ||
|
|
b500a36a94 | ||
|
|
1310045629 | ||
|
|
579a69eb77 | ||
|
|
9ee8c4f543 | ||
|
|
55560f5116 | ||
|
|
3710ddb611 | ||
|
|
3fce14bbcf | ||
|
|
d430a0624b | ||
|
|
765c1dc9e4 | ||
|
|
e6d9a271fc | ||
|
|
4b811dae61 | ||
|
|
6d76865e74 | ||
|
|
2bb71f41c3 | ||
|
|
cc2ab00074 | ||
|
|
8b8e8b38e5 | ||
|
|
46ea594f02 | ||
|
|
790fda1a97 | ||
|
|
89ffcf42eb | ||
|
|
876bbd715a | ||
|
|
ac0d1f52a0 | ||
|
|
d0ae0adc99 | ||
|
|
995a26660e | ||
|
|
dfd62cfb86 | ||
|
|
64dc07a8e5 | ||
|
|
ae4ae9973c | ||
|
|
36473f7de6 | ||
|
|
a14debc83e | ||
|
|
71a7473a81 | ||
|
|
5c03fb62c4 | ||
|
|
727c0cfcbf | ||
|
|
dcd2e5c34f | ||
|
|
1e276573c2 | ||
|
|
db17ff3323 | ||
|
|
b496ae8395 | ||
|
|
724f54c2c1 | ||
|
|
b6eba3347d | ||
|
|
74c22628b3 | ||
|
|
224acebb57 | ||
|
|
85c174a6ca | ||
|
|
581d242925 | ||
|
|
d9d0216e98 | ||
|
|
c52ad29b31 | ||
|
|
fcbf3f3c22 | ||
|
|
ab0002f99d | ||
|
|
f63cda22fa | ||
|
|
b60a34eba4 | ||
|
|
ed4be2c849 | ||
|
|
5e23e9c7c7 | ||
|
|
c3bfcc36b8 | ||
|
|
a33cc8c758 | ||
|
|
a01d712751 | ||
|
|
774cff9a74 | ||
|
|
e3d46b687c | ||
|
|
8636ea0ec4 | ||
|
|
ff6a66dcab | ||
|
|
2ac735657e | ||
|
|
bbab1fc891 | ||
|
|
82a50da8b1 | ||
|
|
7ddcb239c5 | ||
|
|
9e4e221970 | ||
|
|
e8b0126371 | ||
|
|
90d9a2ad1f | ||
|
|
065ef922bd | ||
|
|
7d11533490 | ||
|
|
1031a226f8 | ||
|
|
ddd98876b5 | ||
|
|
dfd41da2fd | ||
|
|
b37279ca21 | ||
|
|
13eeb07f5f | ||
|
|
1e9bac7f6e | ||
|
|
1c290767f2 | ||
|
|
9becb3f40a | ||
|
|
2c351726ae | ||
|
|
9e891d2e97 | ||
|
|
b8d07eb852 | ||
|
|
223c3dc800 | ||
|
|
afb6e89bfd | ||
|
|
9309edf4f4 | ||
|
|
d28ced8fd7 | ||
|
|
076608021c | ||
|
|
fb4f9aa58e | ||
|
|
de21f4dcd7 | ||
|
|
442bc9540e | ||
|
|
f7570712a7 | ||
|
|
2847655a1a | ||
|
|
268016d872 | ||
|
|
ac3f22c274 | ||
|
|
b36888e9cc | ||
|
|
9bb9023009 | ||
|
|
f70cb5de45 | ||
|
|
3d3586800e | ||
|
|
767de271e9 | ||
|
|
9d2c2cae37 | ||
|
|
dcccca3f7b | ||
|
|
4ed89e4ba7 | ||
|
|
99dbe4ff02 | ||
|
|
2fc0b01c18 | ||
|
|
3a86b60680 | ||
|
|
eb7c428a2d | ||
|
|
9fb9467ed1 | ||
|
|
e42036485f | ||
|
|
f9c3aff294 | ||
|
|
3503dbc7d5 | ||
|
|
b5dde6b9d8 | ||
|
|
a6b22ec1c9 | ||
|
|
bb49ebf6e5 | ||
|
|
2f5e626029 | ||
|
|
82c0a45ea0 | ||
|
|
e765051f14 | ||
|
|
f5e4df5cab | ||
|
|
1f47cc6f4e | ||
|
|
074d3af79c | ||
|
|
6593645c80 | ||
|
|
296eb82c31 | ||
|
|
7a377fc5e4 | ||
|
|
90e0c2ab15 | ||
|
|
7a3d4d1f31 | ||
|
|
e354e8697f | ||
|
|
993b578512 | ||
|
|
ed518ef19f | ||
|
|
47117a7d85 | ||
|
|
f623810903 | ||
|
|
e9ffd5752b | ||
|
|
24122b1762 | ||
|
|
081a6dacdb | ||
|
|
9fdb45be1e | ||
|
|
b946f00f1a | ||
|
|
b030f69a83 | ||
|
|
b0e1b3368e | ||
|
|
ce7b24bfb1 | ||
|
|
5c286cab8b | ||
|
|
75ca0d4fa4 | ||
|
|
8282b11fb5 | ||
|
|
45744cc789 | ||
|
|
4b6a0c433c | ||
|
|
304a14de7d | ||
|
|
c585128bbe | ||
|
|
acd92f9b06 | ||
|
|
4088b7ac3c | ||
|
|
8e8904a159 | ||
|
|
16f3490aee | ||
|
|
651084e8c0 | ||
|
|
812bb99f5c | ||
|
|
5bc79807ec | ||
|
|
8fe21d7583 | ||
|
|
412331aa61 | ||
|
|
cd1c3df89c | ||
|
|
3738373aa5 | ||
|
|
9b9006fed5 | ||
|
|
42234b8f7c | ||
|
|
39f65703e7 | ||
|
|
b7f954a904 | ||
|
|
a20815ece6 | ||
|
|
1c43bad705 | ||
|
|
18b6590d2e | ||
|
|
d62ffa7560 | ||
|
|
59e2944fb7 | ||
|
|
17942787aa | ||
|
|
5815ba24e2 | ||
|
|
5de8e9d1ae | ||
|
|
96e1e3db5e | ||
|
|
5dd36bc5ad | ||
|
|
6271b989bc | ||
|
|
57aa6bf16c | ||
|
|
40a7f4b4b1 | ||
|
|
cba0f23a9e | ||
|
|
a7ec0179fb | ||
|
|
c97c6b7836 | ||
|
|
59b0527c38 | ||
|
|
b74c7a79ab | ||
|
|
f772720d8c | ||
|
|
0763a35fbc | ||
|
|
e1c33dcd33 | ||
|
|
0a902790ca | ||
|
|
0837c8b639 | ||
|
|
5a90b6be9c | ||
|
|
42675571c9 | ||
|
|
e9f00f65ca | ||
|
|
04b95e37c5 | ||
|
|
5820e1b6ff | ||
|
|
8c904ffe34 | ||
|
|
9fa9cb4b31 | ||
|
|
24599aaeed | ||
|
|
f403b23e9a | ||
|
|
39c71a0394 | ||
|
|
d249e628ee | ||
|
|
40fcb6bdf8 | ||
|
|
d58ff5de26 | ||
|
|
e28ad18106 | ||
|
|
525411101d | ||
|
|
0f208447ed | ||
|
|
71e0573459 | ||
|
|
c63ea8d25b | ||
|
|
b9e529e0b5 | ||
|
|
0f702fcd62 | ||
|
|
13f2f9bc58 | ||
|
|
91cf202177 | ||
|
|
d21a8d597b | ||
|
|
14022f1d00 | ||
|
|
28c62f3efd | ||
|
|
268bb4bfa3 | ||
|
|
477b4f9d0e | ||
|
|
d5d88270f0 | ||
|
|
373725f96e | ||
|
|
fcb1a50ee4 | ||
|
|
ec3778bbf4 | ||
|
|
8c5b8d3b72 | ||
|
|
010ba70561 | ||
|
|
6ee057e25b | ||
|
|
551aebc604 | ||
|
|
9de85ea16e | ||
|
|
10dde452f9 | ||
|
|
116c8c5e8e | ||
|
|
f8886e874d | ||
|
|
2435a9cd58 | ||
|
|
78d53062d1 | ||
|
|
697d71d57d | ||
|
|
d74b086aaf | ||
|
|
6496aedc92 | ||
|
|
e972fad300 | ||
|
|
1bd4d6d953 | ||
|
|
e9655d43d5 | ||
|
|
f0a7ddaf80 | ||
|
|
ed6c12c709 | ||
|
|
a1b75fe17f | ||
|
|
2e5e75699e | ||
|
|
be308beacc | ||
|
|
2589176c82 | ||
|
|
adfd99bdec | ||
|
|
1683ee7b11 | ||
|
|
e6575c4149 | ||
|
|
ae7283e021 | ||
|
|
640a2cca9f | ||
|
|
12edc3455c | ||
|
|
26f631b638 | ||
|
|
981cf40561 | ||
|
|
689dda59e9 | ||
|
|
0a67f9dd39 | ||
|
|
df6bb188d4 | ||
|
|
03053d9ee0 | ||
|
|
9c4d7a83e2 | ||
|
|
7425a3c4b3 | ||
|
|
344e04b623 | ||
|
|
7b71e234e0 | ||
|
|
77f67d1766 | ||
|
|
1c2ed75937 | ||
|
|
17e6cad479 | ||
|
|
feff86638e | ||
|
|
ad28eaa86f | ||
|
|
d36bbc177d | ||
|
|
aeddb57594 | ||
|
|
f2253269dd | ||
|
|
d08cecf126 | ||
|
|
afad39d125 | ||
|
|
f97916f371 | ||
|
|
86e204439e | ||
|
|
04a931fc79 | ||
|
|
75354bbd96 | ||
|
|
6a10e97a97 | ||
|
|
1542b00db2 | ||
|
|
f79f8bac80 | ||
|
|
92f1a4aa3c | ||
|
|
11f929c397 | ||
|
|
0616338911 | ||
|
|
58427d565d | ||
|
|
9b3dbada17 | ||
|
|
4797f99cf8 | ||
|
|
50f35351a2 | ||
|
|
c7460bde16 | ||
|
|
2c110e8ce2 | ||
|
|
5707a6ee1d | ||
|
|
291411a45e | ||
|
|
87abc22f39 | ||
|
|
441582dbb8 | ||
|
|
1b1ede92ba | ||
|
|
4ec7ae33c5 | ||
|
|
317fcc659b | ||
|
|
ff7e084a33 | ||
|
|
c590beb4e3 | ||
|
|
e9ced44ac6 | ||
|
|
802cd127d1 | ||
|
|
931c56b2d0 | ||
|
|
484662b2d4 | ||
|
|
2cd04f08c1 | ||
|
|
4916dad78e | ||
|
|
d5c97faac5 | ||
|
|
531b12e192 | ||
|
|
b293b083fc | ||
|
|
b297e20f4e | ||
|
|
44be7f3ac3 | ||
|
|
ea5a100a74 | ||
|
|
6841fa17d4 | ||
|
|
5c03804bac | ||
|
|
d6ed393255 | ||
|
|
2d9139767a | ||
|
|
95fcc89074 | ||
|
|
eb59853596 | ||
|
|
a2682de421 | ||
|
|
325c0a3687 | ||
|
|
7c7fcf46c2 | ||
|
|
0c39733cbf | ||
|
|
a76413594e | ||
|
|
1100d5a6f7 | ||
|
|
9abf967700 | ||
|
|
cc83094bc6 | ||
|
|
f5bdc138f6 | ||
|
|
2d8ca48175 | ||
|
|
4ca4a1f99c | ||
|
|
5470801c4a | ||
|
|
2ad2d3e6f5 | ||
|
|
b175d6b2a3 | ||
|
|
c5c12aa738 | ||
|
|
7241400edd | ||
|
|
310fd0b187 | ||
|
|
db94743220 | ||
|
|
07aaf37fd4 | ||
|
|
65a808808f | ||
|
|
cca1aa1588 | ||
|
|
c9d4b773c9 | ||
|
|
e23f3102f4 | ||
|
|
ec89587c37 | ||
|
|
32d89806d7 | ||
|
|
2fd4e06b34 | ||
|
|
3cffdce1c1 | ||
|
|
6d2f4f4cdf | ||
|
|
865d7bd684 | ||
|
|
392d63231c | ||
|
|
7559f5ad70 | ||
|
|
605e8143e0 | ||
|
|
5b056cd337 | ||
|
|
6c350489b1 | ||
|
|
2ae63f4aa2 | ||
|
|
3d0233e3b0 | ||
|
|
64f2c3a465 | ||
|
|
0a12333448 | ||
|
|
9db54c9b19 | ||
|
|
34430e3514 | ||
|
|
99e44f2c23 | ||
|
|
7a0f2d9b30 | ||
|
|
4bf310f7ca | ||
|
|
8b9fbe701d | ||
|
|
0c5be023e4 | ||
|
|
86e87a8789 | ||
|
|
404e78a506 | ||
|
|
73563c7c25 | ||
|
|
326595b148 | ||
|
|
41a8468b08 | ||
|
|
ced2ecb6ba | ||
|
|
2d746b3a7e | ||
|
|
e6ac39de75 | ||
|
|
b76a0a6c91 | ||
|
|
9fdec3c2c8 | ||
|
|
760fe643e8 | ||
|
|
93af851dc5 | ||
|
|
fabb3e0734 | ||
|
|
9ca9a862a5 | ||
|
|
827dc9ff9f | ||
|
|
09b32ac9dd | ||
|
|
253684e280 | ||
|
|
f6d40ce841 | ||
|
|
36fb1bb7e4 | ||
|
|
4a82c1608f | ||
|
|
3efb3da007 | ||
|
|
11606fd9c6 | ||
|
|
a935db07ef | ||
|
|
98860a9549 | ||
|
|
7688742b2a | ||
|
|
b2efe4f83c | ||
|
|
f934b435fa | ||
|
|
3c121585da | ||
|
|
40acfbd2df | ||
|
|
0af61bf6ba | ||
|
|
7b2968f2ff | ||
|
|
a1c7b98f98 | ||
|
|
99ea16a969 | ||
|
|
ebe44d03a5 | ||
|
|
dcd2d50768 | ||
|
|
f11764c517 | ||
|
|
77c81b7468 | ||
|
|
7a5ccd3310 | ||
|
|
e4df6fcf8e | ||
|
|
b2be7f4e4f | ||
|
|
94beb21a43 | ||
|
|
30e05538b7 | ||
|
|
c884947ea8 | ||
|
|
61289a152d | ||
|
|
906550f9af | ||
|
|
c2aaa89b57 | ||
|
|
dde48e9414 | ||
|
|
b1608f41ad | ||
|
|
78d89e3d35 | ||
|
|
1309495218 | ||
|
|
c34a4c69e5 | ||
|
|
2f6cac0cf0 | ||
|
|
5c26df3a4f | ||
|
|
302323a64b | ||
|
|
b981fad920 | ||
|
|
8a2f2a5c2b | ||
|
|
e319735ed1 | ||
|
|
e7790490f1 | ||
|
|
a638978b75 | ||
|
|
4a08686e74 | ||
|
|
b3de2bd926 | ||
|
|
b81ec02984 | ||
|
|
de61c0c42b | ||
|
|
ecb4a1efa4 | ||
|
|
1b0093a483 | ||
|
|
06fc364ee1 | ||
|
|
094859bbc7 | ||
|
|
5e78386cdc | ||
|
|
c378afeff8 | ||
|
|
bf7002209e | ||
|
|
a3aa4bd189 | ||
|
|
5a0006f7ef | ||
|
|
9e2e73c070 | ||
|
|
c530e5d50f | ||
|
|
674720c6cd | ||
|
|
58c9e4b96d | ||
|
|
feb286379c | ||
|
|
cefe641586 | ||
|
|
664451c296 | ||
|
|
fd4ff8ca46 | ||
|
|
1bcfbdf287 | ||
|
|
4e45c1a6ab | ||
|
|
32fe80d164 | ||
|
|
6e93d42023 | ||
|
|
6f50867aa1 | ||
|
|
4fca60469d | ||
|
|
afcd824ae9 | ||
|
|
f84f279738 | ||
|
|
246624ad3c | ||
|
|
410444aead | ||
|
|
7522d3bde3 | ||
|
|
ed26b84177 | ||
|
|
ad4d12cf94 | ||
|
|
f6fd760e4e | ||
|
|
506a5260dc | ||
|
|
d4c90d696d | ||
|
|
be4d26a1b3 | ||
|
|
5c09614319 | ||
|
|
4c846332c5 | ||
|
|
a3a0cbf0f8 | ||
|
|
2c7101092a | ||
|
|
9f068356a4 | ||
|
|
f239c90628 | ||
|
|
991dd05e72 | ||
|
|
96bf54e293 | ||
|
|
5ca9b54d66 | ||
|
|
4ab5fca4ca | ||
|
|
69a4fa8215 | ||
|
|
9e04bad0a5 | ||
|
|
a574d9c936 | ||
|
|
005e13089a | ||
|
|
d9cce6402a | ||
|
|
508872e04b | ||
|
|
aced302b63 | ||
|
|
0b8dfee17b | ||
|
|
6ab246676e | ||
|
|
122c94a24a | ||
|
|
b59c6d6ab1 | ||
|
|
c9995995a4 | ||
|
|
545a9193e2 | ||
|
|
fa0205cba3 | ||
|
|
8a20bd7f54 | ||
|
|
10660f376c | ||
|
|
ae235f7155 | ||
|
|
a356cd0d0f | ||
|
|
58b932ffb8 | ||
|
|
d58af33fba | ||
|
|
a56418f8bc | ||
|
|
596e1590df | ||
|
|
70c9147c7f | ||
|
|
c0054cb56f | ||
|
|
41734dfbbf | ||
|
|
8f42d34db9 | ||
|
|
70857ce299 | ||
|
|
5e0ec38383 | ||
|
|
913d0409f6 | ||
|
|
ac0e720de1 | ||
|
|
5144d32b77 | ||
|
|
128cc21516 | ||
|
|
215ff36362 | ||
|
|
505b4d0bc3 | ||
|
|
343c0a9472 | ||
|
|
82681606d0 | ||
|
|
c91b79b6e2 | ||
|
|
5e55aa387f | ||
|
|
a21095bc9a | ||
|
|
ba03241df3 | ||
|
|
a8059dc2c0 | ||
|
|
be873bca3e | ||
|
|
e8bde958f1 | ||
|
|
95f21c1099 | ||
|
|
8cd92150b1 | ||
|
|
d0ab35931e | ||
|
|
882684a80c | ||
|
|
96efd1cef0 | ||
|
|
c8974ede6d | ||
|
|
0c637e3d5e | ||
|
|
0e2d50a620 | ||
|
|
f3b3c54859 | ||
|
|
02eca40c3b | ||
|
|
c6ee3aee9f | ||
|
|
586e0ecea9 | ||
|
|
dcd18413a2 | ||
|
|
73f296b4cf | ||
|
|
1419bf3989 | ||
|
|
dca85c402c | ||
|
|
56a3ad0f8b | ||
|
|
36f484c25a | ||
|
|
03c6685097 | ||
|
|
23afddfbf9 | ||
|
|
e3a2dfb9d0 | ||
|
|
3dd004c323 | ||
|
|
1af43dbf90 | ||
|
|
16fed12dcc | ||
|
|
29825f2f8a | ||
|
|
efcee4b863 | ||
|
|
26edcab8b4 | ||
|
|
c626892adf | ||
|
|
3c66cdf2fe | ||
|
|
db31c36213 |
No files matched your search
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: btca-cli
|
||||
description: btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
|
||||
---
|
||||
|
||||
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
|
||||
|
||||
For example, assuming you have a resource named `codex`, you can ask questions like:
|
||||
|
||||
```bash
|
||||
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
|
||||
```
|
||||
|
||||
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
|
||||
|
||||
New resources can be created if the ones you need do not yet exist.
|
||||
|
||||
```bash
|
||||
btca add -n svelte-dev https://github.com/sveltejs/svelte.dev
|
||||
```
|
||||
@@ -1,3 +0,0 @@
|
||||
interface:
|
||||
display_name: "BTCA CLI"
|
||||
short_description: "Help with BTCA CLI setup and usage workflows"
|
||||
@@ -0,0 +1,143 @@
|
||||
# Architecture
|
||||
|
||||
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ Browser (React + Vite) │
|
||||
│ wsTransport (state machine) │
|
||||
│ Typed push decode at boundary │
|
||||
└──────────┬──────────────────────┘
|
||||
│ ws://localhost:3773
|
||||
┌──────────▼──────────────────────┐
|
||||
│ apps/server (Node.js) │
|
||||
│ WebSocket + HTTP static server │
|
||||
│ ServerPushBus (ordered pushes) │
|
||||
│ ServerReadiness (startup gate) │
|
||||
│ OrchestrationEngine │
|
||||
│ ProviderService │
|
||||
│ CheckpointReactor │
|
||||
│ RuntimeReceiptBus │
|
||||
└──────────┬──────────────────────┘
|
||||
│ JSON-RPC over stdio
|
||||
┌──────────▼──────────────────────┐
|
||||
│ codex app-server │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Components
|
||||
|
||||
- **Browser app**: The React app renders session state, owns the client-side WebSocket transport, and treats typed push events as the boundary between server runtime details and UI state.
|
||||
|
||||
- **Server**: `apps/server` is the main coordinator. It serves the web app, accepts WebSocket requests, waits for startup readiness before welcoming clients, and sends all outbound pushes through a single ordered push path.
|
||||
|
||||
- **Provider runtime**: `codex app-server` does the actual provider/session work. The server talks to it over JSON-RPC on stdio and translates those runtime events into the app's orchestration model.
|
||||
|
||||
- **Background workers**: Long-running async flows such as runtime ingestion, command reaction, and checkpoint processing run as queue-backed workers. This keeps work ordered, reduces timing races, and gives tests a deterministic way to wait for the system to go idle.
|
||||
|
||||
- **Runtime signals**: The server emits lightweight typed receipts when important async milestones finish, such as checkpoint capture, diff finalization, or a turn becoming fully quiescent. Tests and orchestration code wait on these signals instead of polling internal state.
|
||||
|
||||
## Event Lifecycle
|
||||
|
||||
### Startup and client connect
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Browser
|
||||
participant Transport as WsTransport
|
||||
participant Server as wsServer
|
||||
participant Layers as serverLayers
|
||||
participant Ready as ServerReadiness
|
||||
participant Push as ServerPushBus
|
||||
|
||||
Browser->>Transport: Load app and open WebSocket
|
||||
Transport->>Server: Connect
|
||||
Server->>Layers: Start runtime services
|
||||
Server->>Ready: Wait for startup barriers
|
||||
Ready-->>Server: Ready
|
||||
Server->>Push: Publish server.welcome
|
||||
Push-->>Transport: Ordered welcome push
|
||||
Transport-->>Browser: Hydrate initial state
|
||||
```
|
||||
|
||||
1. The browser boots [`WsTransport`][1] and registers typed listeners in [`wsNativeApi`][2].
|
||||
2. The server accepts the connection in [`wsServer`][3] and brings up the runtime graph defined in [`serverLayers`][7].
|
||||
3. [`ServerReadiness`][4] waits until the key startup barriers are complete.
|
||||
4. Once the server is ready, [`wsServer`][3] sends `server.welcome` from the contracts in [`ws.ts`][6] through [`ServerPushBus`][5].
|
||||
5. The browser receives that ordered push through [`WsTransport`][1], and [`wsNativeApi`][2] uses it to seed local client state.
|
||||
|
||||
### User turn flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Browser
|
||||
participant Transport as WsTransport
|
||||
participant Server as wsServer
|
||||
participant Provider as ProviderService
|
||||
participant Codex as codex app-server
|
||||
participant Ingest as ProviderRuntimeIngestion
|
||||
participant Engine as OrchestrationEngine
|
||||
participant Push as ServerPushBus
|
||||
|
||||
Browser->>Transport: Send user action
|
||||
Transport->>Server: Typed WebSocket request
|
||||
Server->>Provider: Route request
|
||||
Provider->>Codex: JSON-RPC over stdio
|
||||
Codex-->>Ingest: Provider runtime events
|
||||
Ingest->>Engine: Normalize into orchestration events
|
||||
Engine-->>Server: Domain events
|
||||
Server->>Push: Publish orchestration.domainEvent
|
||||
Push-->>Browser: Typed push
|
||||
```
|
||||
|
||||
1. A user action in the browser becomes a typed request through [`WsTransport`][1] and the browser API layer in [`nativeApi`][12].
|
||||
2. [`wsServer`][3] decodes that request using the shared WebSocket contracts in [`ws.ts`][6] and routes it to the right service.
|
||||
3. [`ProviderService`][8] starts or resumes a session and talks to `codex app-server` over JSON-RPC on stdio.
|
||||
4. Provider-native events are pulled back into the server by [`ProviderRuntimeIngestion`][9], which converts them into orchestration events.
|
||||
5. [`OrchestrationEngine`][10] persists those events, updates the read model, and exposes them as domain events.
|
||||
6. [`wsServer`][3] pushes those updates to the browser through [`ServerPushBus`][5] on channels defined in [`orchestration.ts`][11].
|
||||
|
||||
### Async completion flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Server as wsServer
|
||||
participant Worker as Queue-backed workers
|
||||
participant Cmd as ProviderCommandReactor
|
||||
participant Checkpoint as CheckpointReactor
|
||||
participant Receipt as RuntimeReceiptBus
|
||||
participant Push as ServerPushBus
|
||||
participant Browser
|
||||
|
||||
Server->>Worker: Enqueue follow-up work
|
||||
Worker->>Cmd: Process provider commands
|
||||
Worker->>Checkpoint: Process checkpoint tasks
|
||||
Checkpoint->>Receipt: Publish completion receipt
|
||||
Cmd-->>Server: Produce orchestration changes
|
||||
Checkpoint-->>Server: Produce orchestration changes
|
||||
Server->>Push: Publish resulting state updates
|
||||
Push-->>Browser: User-visible push
|
||||
```
|
||||
|
||||
1. Some work continues after the initial request returns, especially in [`ProviderRuntimeIngestion`][9], [`ProviderCommandReactor`][13], and [`CheckpointReactor`][14].
|
||||
2. These flows run as queue-backed workers using [`DrainableWorker`][16], which helps keep side effects ordered and test synchronization deterministic.
|
||||
3. When a milestone completes, the server emits a typed receipt on [`RuntimeReceiptBus`][15], such as checkpoint completion or turn quiescence.
|
||||
4. Tests and orchestration code wait on those receipts instead of polling git state, projections, or timers.
|
||||
5. Any user-visible state changes produced by that async work still go back through [`wsServer`][3] and [`ServerPushBus`][5].
|
||||
|
||||
[1]: ../apps/web/src/wsTransport.ts
|
||||
[2]: ../apps/web/src/wsNativeApi.ts
|
||||
[3]: ../apps/server/src/wsServer.ts
|
||||
[4]: ../apps/server/src/wsServer/readiness.ts
|
||||
[5]: ../apps/server/src/wsServer/pushBus.ts
|
||||
[6]: ../packages/contracts/src/ws.ts
|
||||
[7]: ../apps/server/src/serverLayers.ts
|
||||
[8]: ../apps/server/src/provider/Layers/ProviderService.ts
|
||||
[9]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
|
||||
[10]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
|
||||
[11]: ../packages/contracts/src/orchestration.ts
|
||||
[12]: ../apps/web/src/nativeApi.ts
|
||||
[13]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
|
||||
[14]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts
|
||||
[15]: ../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
|
||||
[16]: ../packages/shared/src/DrainableWorker.ts
|
||||
@@ -0,0 +1,6 @@
|
||||
# CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
|
||||
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
|
||||
- See `docs/release.md` for full release/signing setup checklist.
|
||||
@@ -0,0 +1,5 @@
|
||||
# Codex prerequisites
|
||||
|
||||
- Install Codex CLI so `codex` is on your PATH.
|
||||
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
|
||||
- T3 Code starts the server via `codex app-server` per session.
|
||||
@@ -0,0 +1,180 @@
|
||||
# Encyclopedia
|
||||
|
||||
This is a living glossary for T3 Code. It explains what common terms mean in this codebase.
|
||||
|
||||
## Table of contents
|
||||
|
||||
- [Project and workspace](#project-and-workspace)
|
||||
- [Thread timeline](#thread-timeline)
|
||||
- [Orchestration](#orchestration)
|
||||
- [Provider runtime](#provider-runtime)
|
||||
- [Checkpointing](#checkpointing)
|
||||
|
||||
## Concepts
|
||||
|
||||
### Project and workspace
|
||||
|
||||
#### Project
|
||||
|
||||
The top-level workspace record in the app. In [the orchestration contracts][1], a project has a `workspaceRoot`, a title, and one or more threads. See [workspace-layout.md][2].
|
||||
|
||||
#### Workspace root
|
||||
|
||||
The root filesystem path for a project. In [the orchestration model][1], it is the base directory for branches and optional worktrees. See [workspace-layout.md][2].
|
||||
|
||||
#### Worktree
|
||||
|
||||
A Git worktree used as an isolated workspace for a thread. If a thread has a `worktreePath` in [the contracts][1], it runs there instead of in the main working tree. Git operations live in [GitCore.ts][3].
|
||||
|
||||
### Thread timeline
|
||||
|
||||
#### Thread
|
||||
|
||||
The main durable unit of conversation and workspace history. In [the orchestration contracts][1], a thread holds messages, activities, checkpoints, and session-related state. See [projector.ts][4].
|
||||
|
||||
#### Turn
|
||||
|
||||
A single user-to-assistant work cycle inside a thread. It starts with user input and ends when follow-up work like checkpointing settles. See [the contracts][1], [ProviderRuntimeIngestion.ts][5], and [CheckpointReactor.ts][6].
|
||||
|
||||
#### Activity
|
||||
|
||||
A user-visible log item attached to a thread. In [the contracts][1], activities cover important non-message events like approvals, tool actions, and failures. They are projected into thread state in [projector.ts][4].
|
||||
|
||||
### Orchestration
|
||||
|
||||
Orchestration is the server-side domain layer that turns runtime activity into stable app state. The main entry point is [OrchestrationEngine.ts][7], with core logic in [decider.ts][8] and [projector.ts][4].
|
||||
|
||||
#### Aggregate
|
||||
|
||||
The domain object a command or event belongs to. In [the contracts][1], that is usually `project` or `thread`. See [decider.ts][8].
|
||||
|
||||
#### Command
|
||||
|
||||
A typed request to change domain state. In [the contracts][1], commands are validated in [commandInvariants.ts][9] and turned into events by [decider.ts][8].
|
||||
Examples include `thread.create`, `thread.turn.start`, and `thread.checkpoint.revert`.
|
||||
|
||||
#### Domain Event
|
||||
|
||||
A persisted fact that something already happened. In [the contracts][1], events are the source of truth, and [projector.ts][4] shows how they are applied.
|
||||
Examples include `thread.created`, `thread.message-sent`, and `thread.turn-diff-completed`.
|
||||
|
||||
#### Decider
|
||||
|
||||
The pure orchestration logic that turns commands plus current state into events. The core implementation is in [decider.ts][8], with preconditions in [commandInvariants.ts][9].
|
||||
|
||||
#### Projection
|
||||
|
||||
A read-optimized view derived from events. See [projector.ts][4], [ProjectionPipeline.ts][11], and [ProjectionSnapshotQuery.ts][10].
|
||||
|
||||
#### Projector
|
||||
|
||||
The logic that applies domain events to the read model or projection tables. See [projector.ts][4] and [ProjectionPipeline.ts][11].
|
||||
|
||||
#### Read model
|
||||
|
||||
The current materialized view of orchestration state. In [the contracts][1], it holds projects, threads, messages, activities, checkpoints, and session state. See [ProjectionSnapshotQuery.ts][10] and [OrchestrationEngine.ts][7].
|
||||
|
||||
#### Reactor
|
||||
|
||||
A side-effecting service that handles follow-up work after events or runtime signals. Examples include [CheckpointReactor.ts][6], [ProviderCommandReactor.ts][12], and [ProviderRuntimeIngestion.ts][5].
|
||||
|
||||
#### Receipt
|
||||
|
||||
A lightweight typed runtime signal emitted when an async milestone completes. See [RuntimeReceiptBus.ts][13].
|
||||
Examples include `checkpoint.baseline.captured`, `checkpoint.diff.finalized`, and `turn.processing.quiesced`, which are emitted by flows such as [CheckpointReactor.ts][6].
|
||||
|
||||
#### Quiesced
|
||||
|
||||
"Quiesced" means a turn has gone quiet and stable. In [the receipt schema][13], it means the follow-up work has settled, including work in [CheckpointReactor.ts][6].
|
||||
|
||||
### Provider runtime
|
||||
|
||||
The live backend agent implementation and its event stream. The main service is [ProviderService.ts][14], the adapter contract is [ProviderAdapter.ts][15], and the overview is in [provider-architecture.md][16].
|
||||
|
||||
#### Provider
|
||||
|
||||
The backend agent runtime that actually performs work. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17].
|
||||
|
||||
#### Session
|
||||
|
||||
The live provider-backed runtime attached to a thread. Session shape is in [the orchestration contracts][1], and lifecycle is managed in [ProviderService.ts][14].
|
||||
|
||||
#### Runtime mode
|
||||
|
||||
The safety/access mode for a thread or session. In [the contracts][1], the main values are `approval-required` and `full-access`. See [runtime-modes.md][18].
|
||||
|
||||
#### Interaction mode
|
||||
|
||||
The agent interaction style for a thread. In [the contracts][1], the main values are `default` and `plan`. See [runtime-modes.md][18].
|
||||
|
||||
#### Assistant delivery mode
|
||||
|
||||
Controls how assistant text reaches the thread timeline. In [the contracts][1], `streaming` updates incrementally and `buffered` delivers a completed result. See [ProviderService.ts][14].
|
||||
|
||||
#### Snapshot
|
||||
|
||||
A point-in-time view of state. The word is used in multiple layers, including orchestration, provider, and checkpointing. See [ProjectionSnapshotQuery.ts][10], [ProviderAdapter.ts][15], and [CheckpointStore.ts][19].
|
||||
|
||||
### Checkpointing
|
||||
|
||||
Checkpointing captures workspace state over time so the app can diff turns and restore earlier points. The main pieces are [CheckpointStore.ts][19], [CheckpointDiffQuery.ts][20], and [CheckpointReactor.ts][6].
|
||||
|
||||
#### Checkpoint
|
||||
|
||||
A saved snapshot of a thread workspace at a particular turn. In practice it is a hidden Git ref in [CheckpointStore.ts][19] plus a projected summary from [ProjectionCheckpoints.ts][21]. Capture and lifecycle work happen in [CheckpointReactor.ts][6].
|
||||
|
||||
#### Checkpoint ref
|
||||
|
||||
The durable identifier for a filesystem checkpoint, stored as a Git ref. It is typed in [the contracts][1], constructed in [Utils.ts][22], and used by [CheckpointStore.ts][19].
|
||||
|
||||
#### Checkpoint baseline
|
||||
|
||||
The starting checkpoint for diffing a thread timeline. This flow is surfaced through [RuntimeReceiptBus.ts][13], coordinated in [CheckpointReactor.ts][6], and supported by [Utils.ts][22].
|
||||
|
||||
#### Checkpoint diff
|
||||
|
||||
The patch difference between two checkpoints. Query logic lives in [CheckpointDiffQuery.ts][20], diff parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6].
|
||||
|
||||
#### Turn diff
|
||||
|
||||
The file patch and changed-file summary for one turn. It is usually computed in [CheckpointDiffQuery.ts][20], represented in [the contracts][1], and recorded into thread state by [projector.ts][4].
|
||||
|
||||
## Practical Shortcuts
|
||||
|
||||
- If you see `requested`, think "intent recorded".
|
||||
- If you see `completed`, think "result applied".
|
||||
- If you see `receipt`, think "async milestone signal".
|
||||
- If you see `checkpoint`, think "workspace snapshot for diff/restore".
|
||||
- If you see `quiesced`, think "all relevant follow-up work has gone idle".
|
||||
|
||||
## Related Docs
|
||||
|
||||
- [architecture.md][24]
|
||||
- [provider-architecture.md][16]
|
||||
- [runtime-modes.md][18]
|
||||
- [workspace-layout.md][2]
|
||||
|
||||
[1]: ../packages/contracts/src/orchestration.ts
|
||||
[2]: ./workspace-layout.md
|
||||
[3]: ../apps/server/src/git/Layers/GitCore.ts
|
||||
[4]: ../apps/server/src/orchestration/projector.ts
|
||||
[5]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
|
||||
[6]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts
|
||||
[7]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
|
||||
[8]: ../apps/server/src/orchestration/decider.ts
|
||||
[9]: ../apps/server/src/orchestration/commandInvariants.ts
|
||||
[10]: ../apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
|
||||
[11]: ../apps/server/src/orchestration/Layers/ProjectionPipeline.ts
|
||||
[12]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
|
||||
[13]: ../apps/server/src/orchestration/Services/RuntimeReceiptBus.ts
|
||||
[14]: ../apps/server/src/provider/Layers/ProviderService.ts
|
||||
[15]: ../apps/server/src/provider/Services/ProviderAdapter.ts
|
||||
[16]: ./provider-architecture.md
|
||||
[17]: ../apps/server/src/provider/Layers/CodexAdapter.ts
|
||||
[18]: ./runtime-modes.md
|
||||
[19]: ../apps/server/src/checkpointing/Services/CheckpointStore.ts
|
||||
[20]: ../apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts
|
||||
[21]: ../apps/server/src/persistence/Services/ProjectionCheckpoints.ts
|
||||
[22]: ../apps/server/src/checkpointing/Utils.ts
|
||||
[23]: ../apps/server/src/checkpointing/Diffs.ts
|
||||
[24]: ./architecture.md
|
||||
@@ -0,0 +1,30 @@
|
||||
# Provider architecture
|
||||
|
||||
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
|
||||
|
||||
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
|
||||
- **Push events**: typed envelopes with `channel`, `sequence` (monotonic per connection), and channel-specific `data`
|
||||
|
||||
Push channels: `server.welcome`, `server.configUpdated`, `terminal.event`, `orchestration.domainEvent`. Payloads are schema-validated at the transport boundary (`wsTransport.ts`). Decode failures produce structured `WsDecodeDiagnostic` with `code`, `reason`, and path info.
|
||||
|
||||
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
|
||||
|
||||
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
|
||||
- `providers.respondToRequest`, `providers.stopSession`
|
||||
- `shell.openInEditor`, `server.getConfig`
|
||||
|
||||
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
|
||||
|
||||
## Client transport
|
||||
|
||||
`wsTransport.ts` manages connection state: `connecting` → `open` → `reconnecting` → `closed` → `disposed`. Outbound requests are queued while disconnected and flushed on reconnect. Inbound pushes are decoded and validated at the boundary, then cached per channel. Subscribers can opt into `replayLatest` to receive the last push on subscribe.
|
||||
|
||||
## Server-side orchestration layers
|
||||
|
||||
Provider runtime events flow through queue-based workers:
|
||||
|
||||
1. **ProviderRuntimeIngestion** — consumes provider runtime streams, emits orchestration commands
|
||||
2. **ProviderCommandReactor** — reacts to orchestration intent events, dispatches provider calls
|
||||
3. **CheckpointReactor** — captures git checkpoints on turn start/complete, publishes runtime receipts
|
||||
|
||||
All three use `DrainableWorker` internally and expose `drain()` for deterministic test synchronization.
|
||||
@@ -0,0 +1,22 @@
|
||||
# Quick start
|
||||
|
||||
```bash
|
||||
# Development (with hot reload)
|
||||
bun run dev
|
||||
|
||||
# Desktop development
|
||||
bun run dev:desktop
|
||||
|
||||
# Desktop development on an isolated port set
|
||||
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
|
||||
|
||||
# Production
|
||||
bun run build
|
||||
bun run start
|
||||
|
||||
# Build a shareable macOS .dmg (arm64 by default)
|
||||
bun run dist:desktop:dmg
|
||||
|
||||
# Or from any project directory after publishing:
|
||||
npx t3
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
# Runtime modes
|
||||
|
||||
T3 Code has a global runtime mode switch in the chat toolbar:
|
||||
|
||||
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
|
||||
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||
`bun run dev -- --base-dir ~/.t3-2`
|
||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
|
||||
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
|
||||
|
||||
## Desktop `.dmg` packaging notes
|
||||
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
|
||||
- Windows `--signed` uses Azure Trusted Signing and expects:
|
||||
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
|
||||
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
## Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
- Default ports: server `3773`, web `5733`
|
||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||
|
||||
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Workspace layout
|
||||
|
||||
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
|
||||
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
|
||||
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
|
||||
- `/packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
- `/packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`, `@t3tools/shared/DrainableWorker`) — no barrel index.
|
||||
@@ -0,0 +1,2 @@
|
||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,117 @@
|
||||
name: Bug report
|
||||
description: Report broken behavior, regressions, crashes, or reliability issues.
|
||||
title: "[Bug]: "
|
||||
labels:
|
||||
- bug
|
||||
- needs-triage
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use this form for broken behavior, regressions, crashes, or reliability problems.
|
||||
Search existing issues first and keep the report focused on one problem.
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Before submitting
|
||||
options:
|
||||
- label: I searched existing issues and did not find a duplicate.
|
||||
required: true
|
||||
- label: I included enough detail to reproduce or investigate the problem.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: Which part of the project is affected?
|
||||
options:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
- Not sure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: Provide a minimal, deterministic repro.
|
||||
placeholder: |
|
||||
1. Start the app with ...
|
||||
2. Open ...
|
||||
3. Disconnect the network
|
||||
4. Reconnect and send another prompt
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
placeholder: The thread should resume normally and accept the new message.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: Actual behavior
|
||||
placeholder: The composer clears, no new turn starts, and the session stays in a pending state.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: impact
|
||||
attributes:
|
||||
label: Impact
|
||||
description: How bad is this in practice?
|
||||
options:
|
||||
- Blocks work completely
|
||||
- Major degradation or frequent failure
|
||||
- Minor bug or occasional failure
|
||||
- Cosmetic issue
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version or commit
|
||||
description: Release version, commit SHA, or branch name if known.
|
||||
placeholder: main @ abc1234
|
||||
|
||||
- type: input
|
||||
id: environment
|
||||
attributes:
|
||||
label: Environment
|
||||
description: OS, browser or desktop app version, Node/Bun version, provider/model if relevant.
|
||||
placeholder: macOS 15.3, Chrome 135, Bun 1.3.9, Codex app-server ...
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Logs or stack traces
|
||||
description: Paste the most relevant output only. Redact secrets.
|
||||
render: shell
|
||||
|
||||
- type: upload
|
||||
id: attachments
|
||||
attributes:
|
||||
label: Screenshots, recordings, or supporting files
|
||||
description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading.
|
||||
validations:
|
||||
required: false
|
||||
accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip"
|
||||
|
||||
- type: textarea
|
||||
id: workaround
|
||||
attributes:
|
||||
label: Workaround
|
||||
description: If you found a temporary workaround, include it.
|
||||
placeholder: Restarting the provider session clears the stuck state.
|
||||
@@ -0,0 +1,101 @@
|
||||
name: Feature request
|
||||
description: Propose a scoped improvement or new capability.
|
||||
title: "[Feature]: "
|
||||
labels:
|
||||
- enhancement
|
||||
- needs-triage
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use this form for new capabilities or meaningful improvements to existing behavior.
|
||||
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Before submitting
|
||||
options:
|
||||
- label: I searched existing issues and did not find a duplicate.
|
||||
required: true
|
||||
- label: I am describing a concrete problem or use case, not just a vague idea.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: Which part of the project would this change affect?
|
||||
options:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
- Not sure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem or use case
|
||||
description: What are you trying to do? What is hard, slow, or impossible today?
|
||||
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed solution
|
||||
description: Describe the behavior, API, or UX you want.
|
||||
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: value
|
||||
attributes:
|
||||
label: Why this matters
|
||||
description: Who benefits, and what outcome does this unlock?
|
||||
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Smallest useful scope
|
||||
description: What is the narrowest version of this request that would still solve your problem?
|
||||
placeholder: A first pass only needs to support restoring the active session for the current thread.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives considered
|
||||
description: Workarounds, prior art, or other approaches you considered.
|
||||
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
|
||||
|
||||
- type: textarea
|
||||
id: tradeoffs
|
||||
attributes:
|
||||
label: Risks or tradeoffs
|
||||
description: What costs, complexity, or edge cases should be considered?
|
||||
placeholder: This may require careful handling when the underlying provider session has already exited.
|
||||
|
||||
- type: textarea
|
||||
id: references
|
||||
attributes:
|
||||
label: Examples or references
|
||||
description: Links, screenshots, mockups, or comparable tools.
|
||||
|
||||
- type: checkboxes
|
||||
id: contribution
|
||||
attributes:
|
||||
label: Contribution
|
||||
options:
|
||||
- label: I would be open to helping implement this.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Trust list for this repository.
|
||||
#
|
||||
# External contributors listed here are treated as trusted by the vouch
|
||||
# workflow. Collaborators with write access are automatically trusted and
|
||||
# do not need to be duplicated in this file.
|
||||
#
|
||||
# Syntax:
|
||||
# github:username
|
||||
# -github:username reason for denouncement
|
||||
#
|
||||
# Keep entries sorted alphabetically.
|
||||
github:adityavardhansharma
|
||||
github:binbandit
|
||||
github:chuks-qua
|
||||
github:cursoragent
|
||||
github:gbarros-dev
|
||||
github:github-actions[bot]
|
||||
github:hwanseoc
|
||||
github:jamesx0416
|
||||
github:jasonLaster
|
||||
github:JoeEverest
|
||||
github:maria-rcks
|
||||
github:nmggithub
|
||||
github:Noojuno
|
||||
github:notkainoa
|
||||
github:PatrickBauer
|
||||
github:realAhmedRoach
|
||||
github:shiroyasha9
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
github:shivamhwp
|
||||
@@ -0,0 +1,33 @@
|
||||
<!--
|
||||
⚠️ READ BEFORE OPENING ⚠️
|
||||
|
||||
We are not actively accepting contributions right now.
|
||||
|
||||
You can still open a PR, but please do so knowing there is a high chance
|
||||
we may close it without merging it, or never review it.
|
||||
|
||||
- Small, focused PRs are strongly preferred. Bug fixes are most likely to be merged.
|
||||
- New features will most likely just annoy us.
|
||||
- 1,000+ line PRs with a bunch of new features will probably get you banned from the repo.
|
||||
-->
|
||||
|
||||
## What Changed
|
||||
|
||||
<!-- Describe the change clearly and keep scope tight. -->
|
||||
|
||||
## Why
|
||||
|
||||
<!-- Explain the problem being solved and why this approach is the right one. -->
|
||||
|
||||
## UI Changes
|
||||
|
||||
<!-- If this PR changes UI, include clear before/after screenshots.
|
||||
If the change involves motion or interaction, include a short video.
|
||||
Delete this section if not applicable. -->
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] This PR is small and focused
|
||||
- [ ] I explained what changed and why
|
||||
- [ ] I included before/after screenshots for any UI changes
|
||||
- [ ] I included a video for animation/interaction changes
|
||||
@@ -8,11 +8,11 @@ on:
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Build
|
||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -20,12 +20,12 @@ jobs:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
@@ -34,9 +34,20 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Format
|
||||
run: bun run fmt:check
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
@@ -46,6 +57,14 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: |
|
||||
cd apps/web
|
||||
bunx playwright install --with-deps chromium
|
||||
|
||||
- name: Browser test
|
||||
run: bun run --cwd apps/web test:browser
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
|
||||
@@ -53,3 +72,23 @@ jobs:
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Exercise release-only workflow steps
|
||||
run: node scripts/release-smoke.ts
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Issue Labels
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- .github/ISSUE_TEMPLATE/**
|
||||
- .github/workflows/issue-labels.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
name: Sync issue labels
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Ensure managed issue labels exist
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const managedLabels = [
|
||||
{
|
||||
name: "bug",
|
||||
color: "d73a4a",
|
||||
description: "Something is broken or behaving incorrectly.",
|
||||
},
|
||||
{
|
||||
name: "enhancement",
|
||||
color: "a2eeef",
|
||||
description: "Requested improvement or new capability.",
|
||||
},
|
||||
{
|
||||
name: "needs-triage",
|
||||
color: "fbca04",
|
||||
description: "Issue needs maintainer review and initial categorization.",
|
||||
},
|
||||
];
|
||||
|
||||
for (const label of managedLabels) {
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== label.color ||
|
||||
(existing.description ?? "") !== label.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
name: PR Size
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
prepare-config:
|
||||
name: Prepare PR size config
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
labels_json: ${{ steps.config.outputs.labels_json }}
|
||||
steps:
|
||||
- id: config
|
||||
name: Build PR size label config
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
result-encoding: string
|
||||
script: |
|
||||
const managedLabels = [
|
||||
{
|
||||
name: "size:XS",
|
||||
color: "0e8a16",
|
||||
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:S",
|
||||
color: "5ebd3e",
|
||||
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:M",
|
||||
color: "fbca04",
|
||||
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:L",
|
||||
color: "fe7d37",
|
||||
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:XL",
|
||||
color: "d93f0b",
|
||||
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:XXL",
|
||||
color: "b60205",
|
||||
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
];
|
||||
|
||||
core.setOutput("labels_json", JSON.stringify(managedLabels));
|
||||
sync-label-definitions:
|
||||
name: Sync PR size label definitions
|
||||
needs: prepare-config
|
||||
if: github.event_name != 'pull_request_target'
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- name: Ensure PR size labels exist
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||
with:
|
||||
script: |
|
||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||
|
||||
for (const label of managedLabels) {
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== label.color ||
|
||||
(existing.description ?? "") !== label.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
} catch (createError) {
|
||||
if (createError.status !== 422) {
|
||||
throw createError;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
label:
|
||||
name: Label PR size
|
||||
needs: prepare-config
|
||||
if: github.event_name == 'pull_request_target'
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
issues: read
|
||||
pull-requests: write
|
||||
concurrency:
|
||||
group: pr-size-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Sync PR size label
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||
with:
|
||||
script: |
|
||||
const { execFileSync } = require("node:child_process");
|
||||
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
const baseSha = context.payload.pull_request.base.sha;
|
||||
const headSha = context.payload.pull_request.head.sha;
|
||||
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
|
||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
// Keep this aligned with the repo's test entrypoints and test-only support files.
|
||||
const testExcludePathspecs = [
|
||||
":(glob,exclude)**/__tests__/**",
|
||||
":(glob,exclude)**/test/**",
|
||||
":(glob,exclude)**/tests/**",
|
||||
":(glob,exclude)apps/server/integration/**",
|
||||
":(glob,exclude)**/*.test.*",
|
||||
":(glob,exclude)**/*.spec.*",
|
||||
":(glob,exclude)**/*.browser.*",
|
||||
":(glob,exclude)**/*.integration.*",
|
||||
];
|
||||
|
||||
const sumNumstat = (text) =>
|
||||
text
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.reduce((total, line) => {
|
||||
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
|
||||
const additions =
|
||||
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
|
||||
const deletions =
|
||||
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
|
||||
|
||||
return total + additions + deletions;
|
||||
}, 0);
|
||||
|
||||
const resolveSizeLabel = (totalChangedLines) => {
|
||||
if (totalChangedLines < 10) {
|
||||
return "size:XS";
|
||||
}
|
||||
|
||||
if (totalChangedLines < 30) {
|
||||
return "size:S";
|
||||
}
|
||||
|
||||
if (totalChangedLines < 100) {
|
||||
return "size:M";
|
||||
}
|
||||
|
||||
if (totalChangedLines < 500) {
|
||||
return "size:L";
|
||||
}
|
||||
|
||||
if (totalChangedLines < 1000) {
|
||||
return "size:XL";
|
||||
}
|
||||
|
||||
return "size:XXL";
|
||||
};
|
||||
|
||||
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
execFileSync(
|
||||
"git",
|
||||
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
||||
{
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
|
||||
if (resolvedHeadSha !== headSha) {
|
||||
core.warning(
|
||||
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
||||
);
|
||||
}
|
||||
|
||||
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--numstat",
|
||||
"--ignore-all-space",
|
||||
"--ignore-blank-lines",
|
||||
`${baseSha}...${resolvedHeadSha}`,
|
||||
];
|
||||
|
||||
const totalChangedLines = sumNumstat(
|
||||
execFileSync(
|
||||
"git",
|
||||
diffArgs,
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
);
|
||||
const nonTestChangedLines = sumNumstat(
|
||||
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
);
|
||||
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
|
||||
|
||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
||||
const nextLabelName = resolveSizeLabel(changedLines);
|
||||
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
for (const label of currentLabels) {
|
||||
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: label.name,
|
||||
});
|
||||
} catch (removeError) {
|
||||
if (removeError.status !== 404) {
|
||||
throw removeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!currentLabels.some((label) => label.name === nextLabelName)) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [nextLabelName],
|
||||
});
|
||||
}
|
||||
|
||||
const classification =
|
||||
nonTestChangedLines === 0
|
||||
? testChangedLines > 0
|
||||
? "test-only PR"
|
||||
: "no line changes"
|
||||
: testChangedLines > 0
|
||||
? "test lines excluded"
|
||||
: "all non-test changes";
|
||||
|
||||
core.info(
|
||||
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
|
||||
);
|
||||
@@ -0,0 +1,199 @@
|
||||
name: PR Vouch
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- .github/VOUCHED.td
|
||||
- .github/workflows/pr-vouch.yml
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
collect-targets:
|
||||
name: Collect PR targets
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
targets: ${{ steps.collect.outputs.targets }}
|
||||
steps:
|
||||
- id: collect
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
if (context.eventName === "pull_request_target") {
|
||||
const pr = context.payload.pull_request;
|
||||
core.setOutput("targets", JSON.stringify([{ number: pr.number, user: pr.user.login }]));
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.eventName === "issue_comment") {
|
||||
const issue = context.payload.issue;
|
||||
const body = context.payload.comment?.body ?? "";
|
||||
if (!issue?.pull_request || !body.includes("/recheck-vouch")) {
|
||||
core.setOutput("targets", "[]");
|
||||
return;
|
||||
}
|
||||
|
||||
core.setOutput(
|
||||
"targets",
|
||||
JSON.stringify([{ number: issue.number, user: issue.user.login }]),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const pulls = await github.paginate(github.rest.pulls.list, {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
state: "open",
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const targets = pulls.map((pull) => ({
|
||||
number: pull.number,
|
||||
user: pull.user.login,
|
||||
}));
|
||||
core.setOutput("targets", JSON.stringify(targets));
|
||||
|
||||
label:
|
||||
name: Label PR ${{ matrix.target.number }}
|
||||
needs: collect-targets
|
||||
if: ${{ needs.collect-targets.outputs.targets != '[]' }}
|
||||
runs-on: ubuntu-24.04
|
||||
concurrency:
|
||||
group: pr-vouch-${{ matrix.target.number }}
|
||||
cancel-in-progress: true
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
target: ${{ fromJson(needs.collect-targets.outputs.targets) }}
|
||||
steps:
|
||||
- id: vouch
|
||||
name: Check PR author trust
|
||||
uses: mitchellh/vouch/action/check-user@v1
|
||||
with:
|
||||
user: ${{ matrix.target.user }}
|
||||
allow-fail: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Sync PR labels
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_NUMBER: ${{ matrix.target.number }}
|
||||
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
|
||||
with:
|
||||
script: |
|
||||
const issueNumber = Number(process.env.PR_NUMBER);
|
||||
const status = process.env.VOUCH_STATUS;
|
||||
const managedLabels = [
|
||||
{
|
||||
name: "vouch:trusted",
|
||||
color: "1f883d",
|
||||
description: "PR author is trusted by repo permissions or the VOUCHED list.",
|
||||
},
|
||||
{
|
||||
name: "vouch:unvouched",
|
||||
color: "fbca04",
|
||||
description: "PR author is not yet trusted in the VOUCHED list.",
|
||||
},
|
||||
{
|
||||
name: "vouch:denounced",
|
||||
color: "d1242f",
|
||||
description: "PR author is explicitly blocked by the VOUCHED list.",
|
||||
},
|
||||
];
|
||||
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
|
||||
for (const label of managedLabels) {
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== label.color ||
|
||||
(existing.description ?? "") !== label.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
} catch (createError) {
|
||||
if (createError.status !== 422) {
|
||||
throw createError;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const nextLabelName =
|
||||
status === "denounced"
|
||||
? "vouch:denounced"
|
||||
: ["bot", "collaborator", "vouched"].includes(status)
|
||||
? "vouch:trusted"
|
||||
: "vouch:unvouched";
|
||||
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
for (const label of currentLabels) {
|
||||
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: label.name,
|
||||
});
|
||||
} catch (removeError) {
|
||||
if (removeError.status !== 404) {
|
||||
throw removeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!currentLabels.some((label) => label.name === nextLabelName)) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [nextLabelName],
|
||||
});
|
||||
}
|
||||
|
||||
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
|
||||
@@ -0,0 +1,377 @@
|
||||
name: Release Desktop
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Release version (for example 1.2.3 or v1.2.3)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
|
||||
make_latest: ${{ steps.release_meta.outputs.make_latest }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${{ github.event.inputs.version }}"
|
||||
else
|
||||
raw="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
|
||||
version="${raw#v}"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "Invalid release version: $raw" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- label: macOS arm64
|
||||
runner: macos-14
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
- label: macOS x64
|
||||
runner: macos-15-intel
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
- label: Linux x64
|
||||
runner: ubuntu-24.04
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
- label: Windows x64
|
||||
runner: windows-2022
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
CSC_LINK: ${{ secrets.CSC_LINK }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
|
||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
|
||||
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
|
||||
run: |
|
||||
args=(
|
||||
--platform "${{ matrix.platform }}"
|
||||
--target "${{ matrix.target }}"
|
||||
--arch "${{ matrix.arch }}"
|
||||
--build-version "${{ needs.preflight.outputs.version }}"
|
||||
--verbose
|
||||
)
|
||||
|
||||
has_all() {
|
||||
for value in "$@"; do
|
||||
if [[ -z "$value" ]]; then
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" ]]; then
|
||||
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
|
||||
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||
printf '%s' "$APPLE_API_KEY" > "$key_path"
|
||||
export APPLE_API_KEY="$key_path"
|
||||
echo "macOS signing enabled."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||
fi
|
||||
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
if has_all \
|
||||
"$AZURE_TENANT_ID" \
|
||||
"$AZURE_CLIENT_ID" \
|
||||
"$AZURE_CLIENT_SECRET" \
|
||||
"$AZURE_TRUSTED_SIGNING_ENDPOINT" \
|
||||
"$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \
|
||||
"$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \
|
||||
"$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then
|
||||
echo "Windows signing enabled (Azure Trusted Signing)."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)."
|
||||
fi
|
||||
else
|
||||
echo "Signing disabled for ${{ matrix.platform }}."
|
||||
fi
|
||||
|
||||
bun run dist:desktop:artifact -- "${args[@]}"
|
||||
|
||||
- name: Collect release assets
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p release-publish
|
||||
|
||||
shopt -s nullglob
|
||||
for pattern in \
|
||||
"release/*.dmg" \
|
||||
"release/*.zip" \
|
||||
"release/*.AppImage" \
|
||||
"release/*.exe" \
|
||||
"release/*.blockmap" \
|
||||
"release/latest*.yml"; do
|
||||
for file in $pattern; do
|
||||
cp "$file" release-publish/
|
||||
done
|
||||
done
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
|
||||
if [[ -f release-publish/latest-mac.yml ]]; then
|
||||
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: desktop-*
|
||||
merge-multiple: true
|
||||
path: release-assets
|
||||
|
||||
- name: Merge macOS updater manifests
|
||||
run: |
|
||||
node scripts/merge-mac-update-manifests.ts \
|
||||
release-assets/latest-mac.yml \
|
||||
release-assets/latest-mac-x64.yml
|
||||
rm -f release-assets/latest-mac-x64.yml
|
||||
|
||||
- name: Publish release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
persist-credentials: true
|
||||
|
||||
- id: app_bot
|
||||
name: Resolve GitHub App bot identity
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app_token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
|
||||
run: |
|
||||
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
|
||||
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
|
||||
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bun install --lockfile-only --ignore-scripts
|
||||
|
||||
- name: Commit and push version bump
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
|
||||
run: |
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
echo "No version changes to commit."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
@@ -5,10 +5,19 @@ node_modules
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
apps/*/dist
|
||||
.astro
|
||||
packages/*/dist
|
||||
.env
|
||||
.env.local
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
release-mock/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
@@ -0,0 +1,3 @@
|
||||
[tools]
|
||||
node = "24.13.1"
|
||||
bun = "1.3.9"
|
||||
@@ -1,13 +1,15 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
".reference",
|
||||
".plans",
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts"
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js"
|
||||
],
|
||||
"experimentalSortPackageJson": {}
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -1,20 +1,24 @@
|
||||
# Plan: Centralize Model Normalization in Contracts
|
||||
|
||||
## Summary
|
||||
|
||||
Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth.
|
||||
|
||||
## Motivation
|
||||
|
||||
- Removes duplicated logic between:
|
||||
- `apps/desktop/src/codexAppServerManager.ts`
|
||||
- `apps/renderer/src/model-logic.ts`
|
||||
- Prevents behavior drift when model aliases/defaults are updated.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add shared model utilities to contracts.
|
||||
- Update desktop and renderer to consume shared utilities.
|
||||
- Keep renderer-specific display options in renderer.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add `packages/contracts/src/model.ts` with:
|
||||
- Canonical model list
|
||||
- Alias map
|
||||
@@ -29,14 +33,17 @@ Move model alias/default normalization into `packages/contracts` so desktop and
|
||||
- Keep renderer tests focused on renderer-only behavior.
|
||||
|
||||
## Risks
|
||||
|
||||
- Desktop/renderer may currently rely on slightly different fallback behavior.
|
||||
- Import graph must avoid bundling issues for Electron main/preload.
|
||||
|
||||
## Validation
|
||||
|
||||
- `bun run test`
|
||||
- `bun run typecheck`
|
||||
- Manual check that model selection and session start still send expected model slug.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- No duplicated alias/default map in desktop and renderer.
|
||||
- Shared model utilities are contract-tested.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Strengthen Typed IPC Boundaries in Main Process
|
||||
|
||||
## Summary
|
||||
|
||||
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
|
||||
- Casts can hide contract breakages until runtime.
|
||||
|
||||
## Scope
|
||||
|
||||
- Desktop main process IPC registration.
|
||||
- Optional shared helper for handler registration.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:
|
||||
- Parse payload(s) with Zod schemas
|
||||
- Standardize typed handler signatures
|
||||
@@ -24,14 +28,17 @@ Replace loose payload casting in IPC handlers with strict schema parsing and typ
|
||||
4. Add tests for handler parsing failure paths (invalid payloads).
|
||||
|
||||
## Risks
|
||||
|
||||
- Refactor can subtly change IPC error shape/messages.
|
||||
- Helper abstraction should stay simple and not obscure control flow.
|
||||
|
||||
## Validation
|
||||
|
||||
- `bun run test`
|
||||
- `bun run typecheck`
|
||||
- Manual invalid payload check from renderer/devtools to confirm fast failure.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- No provider handler uses `payload as Parameters<...>`.
|
||||
- All IPC entrypoints parse unknown payloads at boundary.
|
||||
@@ -1,9 +1,11 @@
|
||||
# Plan: Decompose CodexAppServerManager
|
||||
|
||||
## Summary
|
||||
|
||||
Split `CodexAppServerManager` into smaller modules with clear responsibilities.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
|
||||
- Process lifecycle
|
||||
- JSON-RPC parsing/routing
|
||||
@@ -12,10 +14,12 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
|
||||
- This increases regression risk and slows changes.
|
||||
|
||||
## Scope
|
||||
|
||||
- Desktop provider internals only.
|
||||
- Keep external behavior/API stable.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Extract modules:
|
||||
- `codex/processLifecycle.ts`
|
||||
- `codex/jsonrpcRouter.ts`
|
||||
@@ -29,13 +33,16 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
|
||||
- Session state transitions
|
||||
|
||||
## Risks
|
||||
|
||||
- Reordering event handling can change behavior.
|
||||
- Must preserve pending request timeout/cancellation semantics.
|
||||
|
||||
## Validation
|
||||
|
||||
- Existing tests pass.
|
||||
- Add module-level tests for parsing and transition logic.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- Main manager file materially smaller and orchestration-focused.
|
||||
- Core protocol/state logic covered by focused tests.
|
||||
@@ -1,9 +1,11 @@
|
||||
# Plan: Split ChatView into Smaller UI/Logic Units
|
||||
|
||||
## Summary
|
||||
|
||||
Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/renderer/src/components/ChatView.tsx` is large and handles:
|
||||
- Session orchestration
|
||||
- Send/interrupt actions
|
||||
@@ -13,10 +15,12 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
|
||||
- Hard to test and maintain as one component.
|
||||
|
||||
## Scope
|
||||
|
||||
- Renderer component boundaries and hooks.
|
||||
- Keep visual behavior unchanged.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Create hook: `apps/renderer/src/hooks/useChatSession.ts`
|
||||
- `ensureSession`
|
||||
- `sendTurn`
|
||||
@@ -29,12 +33,15 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
|
||||
4. Add focused tests for hook behavior (error handling, session reuse).
|
||||
|
||||
## Risks
|
||||
|
||||
- Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send).
|
||||
|
||||
## Validation
|
||||
|
||||
- `bun run test`
|
||||
- Manual smoke: send, stream, interrupt, model switch.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- `ChatView.tsx` significantly reduced and easier to scan.
|
||||
- Session logic isolated from rendering.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Move Renderer Persisted-State Validation to Zod
|
||||
|
||||
## Summary
|
||||
|
||||
Use explicit Zod schemas for localStorage state parsing and migration.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/renderer/src/store.ts` has large manual sanitize functions.
|
||||
- Manual type guards are verbose and easier to get wrong during schema evolution.
|
||||
|
||||
## Scope
|
||||
|
||||
- Renderer state hydration/persistence path.
|
||||
- No backend/protocol changes.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add schema module: `apps/renderer/src/persistenceSchema.ts`
|
||||
- Persisted payload versions (`v1`, `v2`)
|
||||
- Thread/message/project schemas
|
||||
@@ -23,12 +27,15 @@ Use explicit Zod schemas for localStorage state parsing and migration.
|
||||
- Unknown thread/project references filtered
|
||||
|
||||
## Risks
|
||||
|
||||
- Overly strict schemas could drop valid historical data unexpectedly.
|
||||
|
||||
## Validation
|
||||
|
||||
- Unit tests for migration/hydration.
|
||||
- Manual reload test with existing localStorage data.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- Store hydration logic is schema-driven.
|
||||
- Migration behavior is tested and documented.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Add Provider Log Stream Lifecycle Management
|
||||
|
||||
## Summary
|
||||
|
||||
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
|
||||
- Stream lifecycle is not explicit on shutdown.
|
||||
|
||||
## Scope
|
||||
|
||||
- Desktop provider logging behavior.
|
||||
- App shutdown integration.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add explicit `dispose()` on `ProviderManager`:
|
||||
- Remove event listeners
|
||||
- End/close log stream
|
||||
@@ -20,12 +24,15 @@ Ensure `ProviderManager` logging stream is initialized, rotated/structured, and
|
||||
4. Optional: per-session log files under `.logs/providers/`.
|
||||
|
||||
## Risks
|
||||
|
||||
- Improper close sequencing may lose final log lines.
|
||||
|
||||
## Validation
|
||||
|
||||
- Manual run/quit cycle to ensure no open handle warnings.
|
||||
- Confirm logs flush on quit and file descriptors are not leaked.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- ProviderManager owns complete log stream lifecycle.
|
||||
- Shutdown path explicitly disposes provider resources.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Add CI Workflow for Core Quality Gates
|
||||
|
||||
## Summary
|
||||
|
||||
Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs.
|
||||
|
||||
## Motivation
|
||||
|
||||
- Repository currently has no CI workflow files.
|
||||
- Quality checks are only local/manual.
|
||||
|
||||
## Scope
|
||||
|
||||
- `.github/workflows/ci.yml`
|
||||
- Bun + Turbo setup in CI.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add `ci.yml` with jobs:
|
||||
- Setup Bun and Node environment
|
||||
- Install deps
|
||||
@@ -22,13 +26,16 @@ Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-tes
|
||||
3. Configure caching for Bun/Turbo as appropriate.
|
||||
|
||||
## Risks
|
||||
|
||||
- Smoke test may be flaky in headless CI environments.
|
||||
- CI runtime can grow if caching is misconfigured.
|
||||
|
||||
## Validation
|
||||
|
||||
- Verify workflow runs on a branch PR.
|
||||
- Ensure failures surface clearly by job name.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- CI blocks regressions in lint/typecheck/test.
|
||||
- Workflow docs added to README.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Add Pre-Commit Formatting/Lint Hooks
|
||||
|
||||
## Summary
|
||||
|
||||
Introduce pre-commit automation so formatting and basic lint checks happen before commits.
|
||||
|
||||
## Motivation
|
||||
|
||||
- Current lint failures include formatting-only issues.
|
||||
- Shift-left feedback reduces noisy CI failures and cleanup churn.
|
||||
|
||||
## Scope
|
||||
|
||||
- Root tooling config and package scripts.
|
||||
- No runtime code changes.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add hook tooling (e.g. Husky + lint-staged or Lefthook).
|
||||
2. Configure staged-file tasks:
|
||||
- `biome format --write`
|
||||
@@ -20,13 +24,16 @@ Introduce pre-commit automation so formatting and basic lint checks happen befor
|
||||
4. Keep checks fast to avoid developer friction.
|
||||
|
||||
## Risks
|
||||
|
||||
- Slow hooks can frustrate contributors and be bypassed.
|
||||
- Need to ensure compatibility with Bun workspace setup.
|
||||
|
||||
## Validation
|
||||
|
||||
- Create sample staged changes and verify hook behavior.
|
||||
- Confirm formatting fixes are applied automatically.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- Pre-commit hook installed and documented.
|
||||
- Formatting-only lint failures drop significantly.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Expand Event/State Transition Test Coverage
|
||||
|
||||
## Summary
|
||||
|
||||
Add focused tests for renderer event handling and session evolution logic.
|
||||
|
||||
## Motivation
|
||||
|
||||
- Core behavior is event-driven and stateful.
|
||||
- Existing renderer tests cover only a subset of timeline/model behavior.
|
||||
|
||||
## Scope
|
||||
|
||||
- `apps/renderer/src/session-logic.test.ts`
|
||||
- Optional reducer tests for `apps/renderer/src/store.ts`.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add tests for `evolveSession`:
|
||||
- `thread/started`
|
||||
- `turn/started`
|
||||
@@ -24,12 +28,15 @@ Add focused tests for renderer event handling and session evolution logic.
|
||||
3. Add reducer integration tests for `APPLY_EVENT`.
|
||||
|
||||
## Risks
|
||||
|
||||
- Tests may be brittle if event payload fixtures are too coupled to implementation details.
|
||||
|
||||
## Validation
|
||||
|
||||
- `bun run test`
|
||||
- Ensure new tests remain deterministic and fast.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- High-risk event transitions are covered by unit tests.
|
||||
- Regressions in stream assembly/session status are caught quickly.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Unify Process and PTY Session Abstractions in ProcessManager
|
||||
|
||||
## Summary
|
||||
|
||||
Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.
|
||||
- New execution backends/providers will multiply complexity.
|
||||
|
||||
## Scope
|
||||
|
||||
- Desktop process execution internals.
|
||||
- Preserve public `ProcessManager` API.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Introduce internal interface (e.g. `RuntimeSession`):
|
||||
- `write(data)`
|
||||
- `kill()`
|
||||
@@ -24,12 +28,15 @@ Refactor `ProcessManager` to use a single runtime-session interface for child-pr
|
||||
5. Add tests for both implementations.
|
||||
|
||||
## Risks
|
||||
|
||||
- PTY behavior differs by platform; abstraction must not hide required differences.
|
||||
|
||||
## Validation
|
||||
|
||||
- Existing `processManager.test.ts` passes.
|
||||
- Add PTY-path tests where feasible.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- Manager no longer branches per backend in `write/kill/killAll`.
|
||||
- Session backends are independently testable.
|
||||
@@ -1,5 +1,3 @@
|
||||
|
||||
|
||||
PR 1: Service contracts + error taxonomy
|
||||
Add ProviderService, CodexService, CheckpointStore as Context.Tag service defs.
|
||||
Add typed Schema.TaggedError hierarchies for all 3 services (cause: Schema.optional(Schema.Defect) on each).
|
||||
@@ -39,4 +37,4 @@ Remove throw-based flow entirely from provider path.
|
||||
PR 10: Cleanup + deprecation removal
|
||||
Remove legacy class implementations/adapters once parity is proven.
|
||||
Finalize layer composition and startup graph docs.
|
||||
Add architecture notes for service boundaries and error model.
|
||||
Add architecture notes for service boundaries and error model.
|
||||
@@ -1,12 +1,14 @@
|
||||
# Effect Migration Plan (From Current State)
|
||||
|
||||
Current status summary:
|
||||
|
||||
- Service contracts, typed errors, and most checkpoint/persistence services exist.
|
||||
- `ProviderServiceLive` is already native orchestration (not a thin adapter).
|
||||
- Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`.
|
||||
- Checkpoint flow now avoids snapshot re-sync and is write-time driven.
|
||||
|
||||
## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer`
|
||||
|
||||
- Build one runtime layer graph for provider + checkpoint + persistence + orchestration.
|
||||
- Resolve `ProviderService` from runtime in `wsServer`.
|
||||
- Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls.
|
||||
@@ -14,12 +16,14 @@ Current status summary:
|
||||
- Keep WS method/push payloads identical.
|
||||
|
||||
## PR 2: Runtime Composition + Startup Ownership
|
||||
|
||||
- Create/centralize `AppLive` composition for server startup.
|
||||
- Ensure outer runtime provides Node/platform services once.
|
||||
- Ensure migrations run at startup via scoped/layer startup path.
|
||||
- Remove ad-hoc service initialization in request-time paths.
|
||||
|
||||
## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants
|
||||
|
||||
- Add explicit checkpoint session cleanup on `stopSession` / `stopAll`.
|
||||
- Remove per-session lock/cwd map leaks.
|
||||
- Keep strict invariant model:
|
||||
@@ -29,12 +33,14 @@ Current status summary:
|
||||
- Add tests for lifecycle cleanup and invariant-failure surfaces.
|
||||
|
||||
## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation)
|
||||
|
||||
- Keep `ProviderService` as the public event surface.
|
||||
- Internally move callback fanout to Effect concurrency primitives (`Queue`/`PubSub`) for ordering/backpressure control.
|
||||
- Keep API as `subscribeToEvents` unless we explicitly choose stream API later.
|
||||
- Add tests for ordering and subscriber isolation under load.
|
||||
|
||||
## PR 5: Codex Runtime Split (Scoped Effect Core)
|
||||
|
||||
- Extract `CodexAppServerManager` responsibilities into Effect-native layers:
|
||||
- scoped process lifecycle
|
||||
- RPC request/response + pending map via `Deferred`
|
||||
@@ -43,16 +49,19 @@ Current status summary:
|
||||
- Preserve protocol behavior and timeout semantics.
|
||||
|
||||
## PR 6: Codex Protocol Decode Hardening
|
||||
|
||||
- Replace ad-hoc unknown parsing with runtime schema decode.
|
||||
- Map decode failures to typed tagged errors with `cause` retained.
|
||||
- Add regression tests for malformed/partial protocol frames.
|
||||
|
||||
## PR 7: Remove Legacy Provider Stack
|
||||
|
||||
- Remove `ProviderManager` + legacy checkpoint integration from runtime path.
|
||||
- Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling).
|
||||
- Update tests to assert only Effect service path is used.
|
||||
|
||||
## PR 8: Final Cleanup + Docs
|
||||
|
||||
- Update architecture docs with final layer graph and service boundaries.
|
||||
- Document error model and recovery semantics.
|
||||
- Trim dead compatibility code and stale plan references.
|
||||
@@ -1,6 +1,7 @@
|
||||
# ProviderService Integration Test Plan
|
||||
|
||||
Goal:
|
||||
|
||||
- Validate end-to-end `ProviderService` behavior with real layers:
|
||||
- `ProviderServiceLive`
|
||||
- `CheckpointServiceLive`
|
||||
@@ -13,6 +14,7 @@ Goal:
|
||||
## Test Harness
|
||||
|
||||
Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`:
|
||||
|
||||
- Service contract: `ProviderAdapterShape<ProviderAdapterError>`.
|
||||
- Internal state:
|
||||
- session registry (session + cwd + threadId)
|
||||
@@ -29,13 +31,15 @@ Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Lay
|
||||
- `readThread`, `rollbackThread`, `stopSession`, `stopAll`.
|
||||
|
||||
Use real git-backed temporary workspaces in integration tests:
|
||||
|
||||
- initialize repo with baseline commit
|
||||
- run provider turn in workspace
|
||||
- assert checkpoint diffs against real git refs
|
||||
|
||||
## Core Integration Specs
|
||||
|
||||
1) `startSession` initializes checkpoint root exactly once
|
||||
1. `startSession` initializes checkpoint root exactly once
|
||||
|
||||
- Arrange:
|
||||
- start provider session in git repo.
|
||||
- Assert:
|
||||
@@ -43,7 +47,8 @@ Use real git-backed temporary workspaces in integration tests:
|
||||
- checkpoint ref exists in git.
|
||||
- second `startSession` for new session creates a new independent root.
|
||||
|
||||
2) Turn without filesystem change
|
||||
2. Turn without filesystem change
|
||||
|
||||
- Arrange:
|
||||
- emit normal turn events, no file mutation.
|
||||
- Assert:
|
||||
@@ -54,7 +59,8 @@ Use real git-backed temporary workspaces in integration tests:
|
||||
- `listCheckpoints` returns root + turn 1.
|
||||
- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.
|
||||
|
||||
3) Turn with filesystem change
|
||||
3. Turn with filesystem change
|
||||
|
||||
- Arrange:
|
||||
- mutate `README.md` during turn.
|
||||
- Assert:
|
||||
@@ -62,7 +68,8 @@ Use real git-backed temporary workspaces in integration tests:
|
||||
- `getCheckpointDiff(0 -> 1)` contains file path and hunk.
|
||||
- persisted checkpoint metadata includes non-empty `checkpointRef`.
|
||||
|
||||
4) Multi-turn sequencing and checkpoint monotonicity
|
||||
4. Multi-turn sequencing and checkpoint monotonicity
|
||||
|
||||
- Arrange:
|
||||
- turn 1: no file change
|
||||
- turn 2: file change
|
||||
@@ -72,7 +79,8 @@ Use real git-backed temporary workspaces in integration tests:
|
||||
- latest checkpoint is marked current.
|
||||
- diffs for adjacent turns map to expected filesystem deltas.
|
||||
|
||||
5) Revert to checkpoint
|
||||
5. Revert to checkpoint
|
||||
|
||||
- Arrange:
|
||||
- execute 3 turns with at least one file-changing turn.
|
||||
- call `revertToCheckpoint(turnCount=1)`.
|
||||
@@ -82,7 +90,8 @@ Use real git-backed temporary workspaces in integration tests:
|
||||
- DB rows for turns >1 are removed.
|
||||
- later refs are deleted from git.
|
||||
|
||||
6) Capture failure surface
|
||||
6. Capture failure surface
|
||||
|
||||
- Arrange:
|
||||
- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.
|
||||
- Assert:
|
||||
@@ -92,6 +101,7 @@ Use real git-backed temporary workspaces in integration tests:
|
||||
## WebSocket Coverage (Thin Integration)
|
||||
|
||||
Add one ws server integration spec:
|
||||
|
||||
- Subscribe to `providers.event`.
|
||||
- Run a deterministic provider turn through ws methods.
|
||||
- Assert push stream includes:
|
||||
@@ -101,10 +111,13 @@ Add one ws server integration spec:
|
||||
## Proposed PR Split
|
||||
|
||||
PR A:
|
||||
|
||||
- Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup).
|
||||
|
||||
PR B:
|
||||
|
||||
- Core ProviderService integration specs (cases 1-4).
|
||||
|
||||
PR C:
|
||||
|
||||
- Revert + failure-path specs (cases 5-6) + ws thin integration spec.
|
||||
@@ -1,6 +1,7 @@
|
||||
# Server-Authoritative Event-Sourcing Cleanup Plan
|
||||
|
||||
Goal:
|
||||
|
||||
- Move to a cleaner service architecture with:
|
||||
- durable, server-authoritative event sourcing
|
||||
- strict command routing/validation
|
||||
@@ -85,6 +86,7 @@ CheckpointCatalog ------> SQLite
|
||||
## Commit Series
|
||||
|
||||
### Commit 1: Split public vs system orchestration command contracts
|
||||
|
||||
- Create separate schemas/types:
|
||||
- `ClientOrchestrationCommandSchema`
|
||||
- `SystemOrchestrationCommandSchema`
|
||||
@@ -100,6 +102,7 @@ CheckpointCatalog ------> SQLite
|
||||
- preserve internal dispatch functionality for system commands
|
||||
|
||||
### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary
|
||||
|
||||
- Add dedicated router service to validate, authorize, and route commands.
|
||||
- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers.
|
||||
- Add aggregate-level invariant checks before append (thread exists, project exists, etc.).
|
||||
@@ -113,6 +116,7 @@ CheckpointCatalog ------> SQLite
|
||||
- handler happy-path tests per command type
|
||||
|
||||
### Commit 3: Harden event store for idempotency + optimistic append metadata
|
||||
|
||||
- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null).
|
||||
- Extend append API to support idempotent replays and deterministic return of prior event on duplicate `commandId`.
|
||||
- Add optional aggregate version metadata for future optimistic concurrency.
|
||||
@@ -125,6 +129,7 @@ CheckpointCatalog ------> SQLite
|
||||
- concurrent append behavior stays ordered and deterministic
|
||||
|
||||
### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer`
|
||||
|
||||
- Create `ProviderRuntimeIngestionService` that:
|
||||
- subscribes to `ProviderService.streamEvents`
|
||||
- translates runtime events into orchestration commands
|
||||
@@ -139,6 +144,7 @@ CheckpointCatalog ------> SQLite
|
||||
- ws integration confirms same external push behavior
|
||||
|
||||
### Commit 5: Make session directory durable (`ProviderSessionRegistry`)
|
||||
|
||||
- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry.
|
||||
- Keep in-memory cache optional, but source of truth must be persistent.
|
||||
- Add startup reconciliation to prune dead sessions / keep known thread mapping.
|
||||
@@ -152,6 +158,7 @@ CheckpointCatalog ------> SQLite
|
||||
- stale session cleanup semantics
|
||||
|
||||
### Commit 6: Re-key checkpoint metadata from session to thread identity
|
||||
|
||||
- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`.
|
||||
- Keep `session_id` as nullable metadata only.
|
||||
- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity.
|
||||
@@ -165,6 +172,7 @@ CheckpointCatalog ------> SQLite
|
||||
- revert/diff still work after session churn
|
||||
|
||||
### Commit 7: Add durable projection persistence for orchestration read models
|
||||
|
||||
- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency.
|
||||
- Keep event stream as source of truth; projection rebuild stays deterministic.
|
||||
- `getSnapshot` reads from projection store (memory cache optional).
|
||||
@@ -177,6 +185,7 @@ CheckpointCatalog ------> SQLite
|
||||
- projection rebuild from events yields same result as previous reducer semantics
|
||||
|
||||
### Commit 8: Narrow `ProviderService` responsibilities
|
||||
|
||||
- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream.
|
||||
- Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service.
|
||||
- Preserve adapter pluggability and provider-neutral contracts.
|
||||
@@ -188,6 +197,7 @@ CheckpointCatalog ------> SQLite
|
||||
- checkpoint capture still triggered by turn completion through new coordinator
|
||||
|
||||
### Commit 9: Look over schemas (contracts and events)
|
||||
|
||||
- Scan for unused schemas.
|
||||
- Use effect/Schema everywhere
|
||||
- Analyze which we need
|
||||
@@ -196,6 +206,7 @@ CheckpointCatalog ------> SQLite
|
||||
- Persistence entities
|
||||
|
||||
### Commit 10: Remove dead legacy path and finalize docs
|
||||
|
||||
- Remove unused legacy manager/store path from active architecture:
|
||||
- `providerManager.ts`
|
||||
- `filesystemCheckpointStore.ts` (if no longer needed by tests/tools)
|
||||
@@ -210,6 +221,7 @@ CheckpointCatalog ------> SQLite
|
||||
- no regressions in WS protocol behavior
|
||||
|
||||
## Risk Controls
|
||||
|
||||
- Keep WS method names and payload contracts stable throughout.
|
||||
- Gate each commit with targeted integration tests before moving forward.
|
||||
- Avoid broad event-type churn in one step; migrate schemas incrementally with clear compatibility windows.
|
||||
@@ -1,10 +1,11 @@
|
||||
Rewrite `createServer` and `index.ts` to be Effect native.
|
||||
|
||||
Maybe use `effect/unstable/Socket` for the web socket server
|
||||
|
||||
- https://github.com/Effect-TS/effect-smol/blob/main/packages/effect/src/unstable/socket/SocketServer.ts
|
||||
- https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts
|
||||
|
||||
- Migrate remaining runtime code to Effect
|
||||
- `gitManager` -> `src/git`
|
||||
- `terminalManager` -> `src/terminal` (Manager + PTY)
|
||||
- ...
|
||||
- ...
|
||||
@@ -24,21 +24,25 @@
|
||||
- Mark invalid/false-positive items with explicit rationale.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Every open thread is mapped to one canonical fix item or marked invalid.
|
||||
|
||||
## Phase 1: Runtime Survival and Critical Event Wiring
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Worker loop/fiber fatal error handling in orchestration reactors.
|
||||
- WebSocket message error boundaries and unhandled rejection guards.
|
||||
- Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected).
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
|
||||
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
|
||||
- `apps/server/src/wsServer.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- A single event-processing failure cannot permanently stop ingestion/reactor loops.
|
||||
- WS message handling cannot produce unhandled promise rejections.
|
||||
- Invalid provider-event-channel review findings are closed with architecture rationale.
|
||||
@@ -46,17 +50,20 @@ Exit criteria:
|
||||
## Phase 2: State Consistency and Ordering
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Fire-and-forget revert completion causing consistency windows.
|
||||
- Non-atomic append/projection paths and retry behavior.
|
||||
- Race-sensitive thread/event association issues.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
|
||||
- `apps/server/src/orchestration/Layers/OrchestrationEngine.ts`
|
||||
- `apps/server/src/orchestration/Layers/ProjectionPipeline.ts`
|
||||
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Revert flow is deterministically reflected in read model updates.
|
||||
- Append/project failure mode is explicit and safe under retry.
|
||||
- No cross-thread misassociation under concurrent runtime events.
|
||||
@@ -64,12 +71,14 @@ Exit criteria:
|
||||
## Phase 3: Checkpointing Correctness Bundle
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Checkpoint input normalization consistency.
|
||||
- Snapshot/projector coverage mismatches.
|
||||
- Checkpoint ref/workspace CWD utility duplication.
|
||||
- Checkpoint diff/error handling behavior gaps.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/checkpointing/Layers/CheckpointStore.ts`
|
||||
- `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts`
|
||||
- `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts`
|
||||
@@ -77,6 +86,7 @@ Primary files:
|
||||
- `apps/server/src/wsServer.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Checkpoint capture/restore/revert paths use one normalization policy.
|
||||
- Required projectors are actually represented in snapshot reads.
|
||||
- Shared checkpoint/ref/CWD helpers are centralized.
|
||||
@@ -84,27 +94,32 @@ Exit criteria:
|
||||
## Phase 4: Memory and Lifecycle Hygiene
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Unbounded in-memory dedup sets/maps.
|
||||
- Missing cleanup/lifecycle protections in long-lived effects/resources.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
|
||||
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
|
||||
- `apps/server/src/config.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Long-running server memory does not grow unbounded from dedup bookkeeping.
|
||||
- Resource cleanup paths are registered for interruption/shutdown.
|
||||
|
||||
## Phase 5: Transport, Parsing, and Platform Edge Cases
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- UTF-8 chunk boundary decode correctness.
|
||||
- Markdown/file-link parsing edge cases.
|
||||
- Shell/OS-specific PATH parsing behavior.
|
||||
- Git rename parsing and small keybinding edge cases.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- `apps/server/src/git/Layers/CodexTextGeneration.ts`
|
||||
- `apps/web/src/markdown-links.ts`
|
||||
@@ -113,23 +128,27 @@ Primary files:
|
||||
- `apps/server/src/keybindings.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Edge-case parsers are robust across valid but non-trivial inputs.
|
||||
- Platform-dependent command behavior has safe fallbacks.
|
||||
|
||||
## Phase 6: Build and Maintainability Cleanup
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Build script/runtime assumption cleanup.
|
||||
- Redundant error-union declarations and utility/type duplication.
|
||||
- Non-functional cleanup comments/docs markers.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/package.json`
|
||||
- `apps/server/src/checkpointing/Errors.ts`
|
||||
- Shared utility locations introduced during earlier phases
|
||||
- `AGENTS.md` (if cleanup is still pending)
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Build path is explicit and environment-safe.
|
||||
- Redundant types/utilities are removed in favor of single sources of truth.
|
||||
|
||||
@@ -140,6 +159,7 @@ Exit criteria:
|
||||
- Resolve threads with fix references per canonical checklist item.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Lint passes.
|
||||
- Backend tests pass.
|
||||
- All actionable review threads are resolved or explicitly justified.
|
||||
@@ -5,6 +5,7 @@ _Last updated: 2026-02-26_
|
||||
This is the working checklist for remediation execution.
|
||||
|
||||
Status values:
|
||||
|
||||
- `TODO`: Not started
|
||||
- `IN_PROGRESS`: Currently being worked
|
||||
- `BLOCKED`: Waiting on decision/dependency
|
||||
@@ -150,7 +151,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/web/src/wsTransport.ts:59`
|
||||
- Threads: PRRT_kwDORLtfbc5whtrN
|
||||
- Audit note: Transport _tag override risk exists but current callsites are constrained.
|
||||
- Audit note: Transport \_tag override risk exists but current callsites are constrained.
|
||||
|
||||
### Phase 2
|
||||
|
||||
@@ -181,7 +182,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
|
||||
- Threads: PRRT_kwDORLtfbc5whxJO
|
||||
- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated.
|
||||
|
||||
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes *after* the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes _after_ the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
@@ -198,7 +199,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
|
||||
- Severity: `Medium`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:94`
|
||||
- Threads: PRRT_kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv_, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
|
||||
- Threads: PRRT*kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv*, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
|
||||
- Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary.
|
||||
|
||||
- [x] `C017` `REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
@@ -250,7 +251,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
|
||||
|
||||
### Phase 5
|
||||
|
||||
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after ` => ` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after `=>` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
# Plan: Claude Code Integration (Orchestration Architecture)
|
||||
|
||||
## Why this plan was rewritten
|
||||
|
||||
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
|
||||
|
||||
1. `orchestration.dispatchCommand` (client intent)
|
||||
2. `OrchestrationEngine` (decide + persist + publish domain events)
|
||||
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
|
||||
4. `ProviderService` (adapter routing + canonical runtime stream)
|
||||
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
|
||||
6. `orchestration.domainEvent` (single push channel consumed by web)
|
||||
|
||||
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
|
||||
|
||||
---
|
||||
|
||||
## Current constraints to design around (post-Stage 1)
|
||||
|
||||
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
|
||||
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
|
||||
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
|
||||
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
|
||||
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
|
||||
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
|
||||
|
||||
---
|
||||
|
||||
## Architecture target
|
||||
|
||||
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
|
||||
|
||||
Key decisions:
|
||||
|
||||
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
|
||||
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
|
||||
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
|
||||
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Contracts and command shape updates
|
||||
|
||||
### 1.1 Provider-aware model contract
|
||||
|
||||
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
|
||||
|
||||
Expected outcomes:
|
||||
|
||||
1. Introduce provider-scoped model lists (Codex + Claude).
|
||||
2. Add helpers that resolve model by provider.
|
||||
3. Preserve backwards compatibility for existing Codex defaults.
|
||||
|
||||
### 1.2 Turn-start provider intent
|
||||
|
||||
Update `packages/contracts/src/orchestration.ts`:
|
||||
|
||||
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
|
||||
2. Carry provider through `ThreadTurnStartRequestedPayload`.
|
||||
3. Keep existing command valid when provider is omitted.
|
||||
|
||||
This removes the implicit “Codex unless session already exists” behavior as the only path.
|
||||
|
||||
### 1.3 Provider session start input for Claude runtime knobs (completed)
|
||||
|
||||
Update `packages/contracts/src/provider.ts`:
|
||||
|
||||
1. Move provider-specific start fields into typed `providerOptions`:
|
||||
- `providerOptions.codex`
|
||||
- `providerOptions.claudeCode`
|
||||
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
|
||||
3. Deprecate/remove `resumeThreadId` from the generic start contract.
|
||||
4. Treat `resumeCursor` as adapter-owned opaque state.
|
||||
|
||||
### 1.4 Contract tests (completed)
|
||||
|
||||
Update/add tests in `packages/contracts/src/*.test.ts` for:
|
||||
|
||||
1. New command payload shape.
|
||||
2. Provider-aware model resolution behavior.
|
||||
3. Breaking-change expectations for removed top-level provider fields.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Claude adapter implementation
|
||||
|
||||
### 2.1 Add adapter service + layer
|
||||
|
||||
Create:
|
||||
|
||||
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
|
||||
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
|
||||
|
||||
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
|
||||
|
||||
### 2.1.a SDK dependency and baseline config
|
||||
|
||||
Add server dependency:
|
||||
|
||||
1. `@anthropic-ai/claude-agent-sdk`
|
||||
|
||||
Baseline adapter options to support from day one:
|
||||
|
||||
1. `cwd`
|
||||
2. `model`
|
||||
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
|
||||
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
|
||||
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
|
||||
6. `resume`
|
||||
7. `resumeSessionAt`
|
||||
8. `includePartialMessages`
|
||||
9. `canUseTool`
|
||||
10. `hooks`
|
||||
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
|
||||
|
||||
### 2.2 Claude runtime bridge
|
||||
|
||||
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
|
||||
|
||||
Required capabilities:
|
||||
|
||||
1. Long-lived session context per adapter session.
|
||||
2. Multi-turn input queue.
|
||||
3. Interrupt support.
|
||||
4. Approval request/response bridge.
|
||||
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
|
||||
|
||||
#### 2.2.a Agent SDK details to preserve
|
||||
|
||||
The adapter should explicitly rely on these SDK capabilities:
|
||||
|
||||
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
|
||||
2. Multi-turn input is supported via async-iterable prompt input.
|
||||
3. Tool approval decisions are provided via `canUseTool`.
|
||||
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
|
||||
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
|
||||
|
||||
#### 2.2.b Effect-native session lifecycle skeleton
|
||||
|
||||
```ts
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { Effect } from "effect";
|
||||
|
||||
const acquireSession = (input: ProviderSessionStartInput) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const claudeOptions = input.providerOptions?.claudeCode;
|
||||
const resumeState = readClaudeResumeState(input.resumeCursor);
|
||||
const abortController = new AbortController();
|
||||
const result = query({
|
||||
prompt: makePromptAsyncIterable(),
|
||||
options: {
|
||||
cwd: input.cwd,
|
||||
model: input.model,
|
||||
permissionMode: claudeOptions?.permissionMode,
|
||||
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
|
||||
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
|
||||
resume: resumeState?.threadId,
|
||||
resumeSessionAt: resumeState?.sessionAt,
|
||||
signal: abortController.signal,
|
||||
includePartialMessages: true,
|
||||
canUseTool: makeCanUseTool(),
|
||||
hooks: makeClaudeHooks(),
|
||||
},
|
||||
});
|
||||
return { abortController, result };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId: "pending",
|
||||
detail: "Failed to start Claude runtime session.",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
({ abortController }) => Effect.sync(() => abortController.abort()),
|
||||
);
|
||||
```
|
||||
|
||||
#### 2.2.c AsyncIterable -> Effect Stream integration
|
||||
|
||||
Preferred when available in the pinned Effect version:
|
||||
|
||||
```ts
|
||||
const sdkMessageStream = Stream.fromAsyncIterable(
|
||||
session.result,
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Portable fallback (already aligned with current server patterns):
|
||||
|
||||
```ts
|
||||
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
for await (const message of session.result) {
|
||||
if (cancelled) break;
|
||||
emit.single(message);
|
||||
}
|
||||
emit.end();
|
||||
} catch (cause) {
|
||||
emit.fail(
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
return Effect.sync(() => {
|
||||
cancelled = true;
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### 2.3 Canonical event mapping
|
||||
|
||||
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
|
||||
|
||||
Initial mapping target:
|
||||
|
||||
1. assistant text deltas -> `content.delta`
|
||||
2. final assistant text -> `item.completed` and/or `turn.completed`
|
||||
3. approval requests -> `request.opened`
|
||||
4. approval results -> `request.resolved`
|
||||
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
|
||||
6. errors -> `runtime.error`
|
||||
7. plan/proposed-plan content when derivable
|
||||
|
||||
Implementation note:
|
||||
|
||||
1. Keep raw Claude message on `raw` for debugging.
|
||||
2. Prefer canonical item/request kinds over provider-native enums.
|
||||
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
|
||||
|
||||
### 2.4 Resume cursor strategy
|
||||
|
||||
Define Claude-owned opaque resume state, e.g.:
|
||||
|
||||
```ts
|
||||
interface ClaudeResumeCursor {
|
||||
readonly version: 1;
|
||||
readonly threadId?: string;
|
||||
readonly sessionAt?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Serialize only adapter-owned state into `resumeCursor`.
|
||||
2. Parse/validate only inside Claude adapter.
|
||||
3. Store updated cursor when Claude runtime yields enough data to resume safely.
|
||||
4. Never overload orchestration thread id as Claude thread id.
|
||||
|
||||
### 2.5 Interrupt and stop semantics
|
||||
|
||||
Map orchestration stop/interrupt expectations onto SDK controls:
|
||||
|
||||
1. `interruptTurn()` -> active query interrupt.
|
||||
2. `stopSession()` -> close session resources and prevent future sends.
|
||||
3. `rollbackThread()` -> see Phase 4.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Provider service and composition
|
||||
|
||||
### 3.1 Register Claude adapter
|
||||
|
||||
Update provider registry layer to include Claude:
|
||||
|
||||
1. add `claudeCode` -> `ClaudeAdapter`
|
||||
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
|
||||
|
||||
### 3.2 Persist provider binding
|
||||
|
||||
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
|
||||
|
||||
Required validation:
|
||||
|
||||
1. Claude bindings survive restart.
|
||||
2. resume cursor remains opaque and round-trips untouched.
|
||||
3. stopAll + restart can recover Claude sessions when possible.
|
||||
|
||||
### 3.3 Provider start routing
|
||||
|
||||
Update `ProviderCommandReactor` / orchestration flow:
|
||||
|
||||
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
|
||||
2. If a thread already has Claude session binding, reuse it.
|
||||
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Checkpoint and revert strategy
|
||||
|
||||
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
|
||||
|
||||
Pick one explicit strategy:
|
||||
|
||||
### Option A: provider-native rewind
|
||||
|
||||
If SDK/runtime supports safe rewind:
|
||||
|
||||
1. implement in Claude adapter
|
||||
2. keep `CheckpointReactor` unchanged
|
||||
|
||||
### Option B: session restart + state truncation shim
|
||||
|
||||
If no native rewind exists:
|
||||
|
||||
1. Claude adapter returns successful rollback by:
|
||||
- stopping current Claude session
|
||||
- clearing/rewriting stored Claude resume cursor to last safe resumable point
|
||||
- forcing next turn to recreate session from persisted orchestration state
|
||||
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
|
||||
|
||||
Whichever option is chosen:
|
||||
|
||||
1. behavior must be deterministic
|
||||
2. checkpoint revert tests must pass under orchestration expectations
|
||||
3. user-visible activity log should explain failures clearly when provider rollback is impossible
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Web integration
|
||||
|
||||
### 5.1 Provider picker and model picker
|
||||
|
||||
Update web state/UI:
|
||||
|
||||
1. allow choosing Claude as thread provider before first turn
|
||||
2. show Claude model list from provider-aware model helpers
|
||||
3. preserve existing Codex default behavior when provider omitted
|
||||
|
||||
Likely touch points:
|
||||
|
||||
1. `apps/web/src/store.ts`
|
||||
2. `apps/web/src/components/ChatView.tsx`
|
||||
3. `apps/web/src/types.ts`
|
||||
4. `packages/shared/src/model.ts`
|
||||
|
||||
### 5.2 Settings for Claude executable/options
|
||||
|
||||
Add app settings if needed for:
|
||||
|
||||
1. Claude binary path
|
||||
2. default permission mode
|
||||
3. default max thinking tokens
|
||||
|
||||
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
|
||||
|
||||
### 5.3 Session rendering
|
||||
|
||||
No new WS channel should be needed. Claude should appear through existing:
|
||||
|
||||
1. thread messages
|
||||
2. activities/worklog
|
||||
3. approvals
|
||||
4. session state
|
||||
5. checkpoints/diffs
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Testing strategy
|
||||
|
||||
### 6.1 Contract tests
|
||||
|
||||
Cover:
|
||||
|
||||
1. provider-aware model schemas
|
||||
2. provider field on turn-start command
|
||||
3. provider-specific start options schema
|
||||
|
||||
### 6.2 Adapter layer tests
|
||||
|
||||
Add `ClaudeAdapter.test.ts` covering:
|
||||
|
||||
1. session start
|
||||
2. event mapping
|
||||
3. approval bridge
|
||||
4. resume cursor parse/serialize
|
||||
5. interrupt behavior
|
||||
6. rollback behavior or explicit unsupported error path
|
||||
|
||||
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
|
||||
|
||||
### 6.3 Provider service integration tests
|
||||
|
||||
Extend provider integration coverage so Claude is exercised through `ProviderService`:
|
||||
|
||||
1. start Claude session
|
||||
2. send turn
|
||||
3. receive canonical runtime events
|
||||
4. restart/recover using persisted binding
|
||||
|
||||
### 6.4 Orchestration integration tests
|
||||
|
||||
Add/extend integration tests around:
|
||||
|
||||
1. first-turn provider selection
|
||||
2. Claude approval requests routed through orchestration
|
||||
3. Claude runtime ingestion -> messages/activities/session updates
|
||||
4. checkpoint revert behavior under Claude
|
||||
5. stopAll/restart recovery
|
||||
|
||||
These should validate real orchestration flows, not just adapter behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: Rollout order
|
||||
|
||||
Recommended implementation order:
|
||||
|
||||
1. contracts/provider-aware models
|
||||
2. provider field on turn-start
|
||||
3. Claude adapter skeleton + start/send/stream
|
||||
4. canonical event mapping
|
||||
5. provider registry/service wiring
|
||||
6. orchestration recovery + checkpoint strategy
|
||||
7. web provider/model picker
|
||||
8. full integration tests
|
||||
|
||||
---
|
||||
|
||||
## Non-goals
|
||||
|
||||
1. Reintroducing provider-specific WS methods/channels.
|
||||
2. Storing provider-native thread ids as orchestration ids.
|
||||
3. Bypassing orchestration engine for Claude-specific UI flows.
|
||||
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
|
||||
@@ -1,546 +0,0 @@
|
||||
# Plan: Claude Code Integration (Orchestration Architecture)
|
||||
|
||||
## Why this plan was rewritten
|
||||
|
||||
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
|
||||
|
||||
1. `orchestration.dispatchCommand` (client intent)
|
||||
2. `OrchestrationEngine` (decide + persist + publish domain events)
|
||||
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
|
||||
4. `ProviderService` (adapter routing + canonical runtime stream)
|
||||
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
|
||||
6. `orchestration.domainEvent` (single push channel consumed by web)
|
||||
|
||||
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
|
||||
|
||||
---
|
||||
|
||||
## Current constraints to design around
|
||||
|
||||
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
|
||||
2. `ProviderService.startSession` currently defaults to `provider: "codex"` unless explicitly provided.
|
||||
3. `thread.turn.start` has no provider field today, so first-turn provider selection cannot be explicitly requested.
|
||||
4. `ProviderService` requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
|
||||
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
|
||||
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
|
||||
|
||||
---
|
||||
|
||||
## Architecture target
|
||||
|
||||
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
|
||||
|
||||
Key decisions:
|
||||
|
||||
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
|
||||
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
|
||||
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
|
||||
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Contracts and command shape updates
|
||||
|
||||
### 1.1 Provider-aware model contract
|
||||
|
||||
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
|
||||
|
||||
Expected outcomes:
|
||||
|
||||
1. Introduce provider-scoped model lists (Codex + Claude).
|
||||
2. Add helpers that resolve model by provider.
|
||||
3. Preserve backwards compatibility for existing Codex defaults.
|
||||
|
||||
### 1.2 Turn-start provider intent
|
||||
|
||||
Update `packages/contracts/src/orchestration.ts`:
|
||||
|
||||
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
|
||||
2. Carry provider through `ThreadTurnStartRequestedPayload`.
|
||||
3. Keep existing command valid when provider is omitted.
|
||||
|
||||
This removes the implicit “Codex unless session already exists” behavior as the only path.
|
||||
|
||||
### 1.3 Provider session start input for Claude runtime knobs
|
||||
|
||||
Update `packages/contracts/src/provider.ts`:
|
||||
|
||||
1. Extend `ProviderSessionStartInput` with optional Claude-specific fields (for example `claudeBinaryPath`, `permissionMode`, `maxThinkingTokens`).
|
||||
2. Keep fields optional so current call sites remain valid.
|
||||
3. Continue using generic `resumeThreadId` + `resumeCursor` as the cross-provider recovery mechanism.
|
||||
|
||||
### 1.4 Contract tests
|
||||
|
||||
Update/add tests in `packages/contracts/src/*.test.ts` for:
|
||||
|
||||
1. New command payload shape.
|
||||
2. Provider-aware model resolution behavior.
|
||||
3. Backward compatibility of existing command/schema decoding.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Claude adapter implementation
|
||||
|
||||
### 2.1 Add adapter service + layer
|
||||
|
||||
Create:
|
||||
|
||||
1. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts`
|
||||
2. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts`
|
||||
|
||||
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
|
||||
|
||||
### 2.1.a SDK dependency and baseline config
|
||||
|
||||
Add server dependency:
|
||||
|
||||
1. `@anthropic-ai/claude-agent-sdk`
|
||||
|
||||
Baseline adapter options to support from day one:
|
||||
|
||||
1. `cwd`
|
||||
2. `model`
|
||||
3. `pathToClaudeCodeExecutable` (from `claudeBinaryPath`)
|
||||
4. `permissionMode`
|
||||
5. `maxThinkingTokens`
|
||||
6. `resume`
|
||||
7. `resumeSessionAt`
|
||||
8. `includePartialMessages`
|
||||
9. `canUseTool`
|
||||
10. `hooks`
|
||||
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
|
||||
|
||||
### 2.2 Claude runtime bridge
|
||||
|
||||
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
|
||||
|
||||
Required capabilities:
|
||||
|
||||
1. Long-lived session context per adapter session.
|
||||
2. Multi-turn input queue.
|
||||
3. Interrupt support.
|
||||
4. Approval request/response bridge.
|
||||
5. Resume support via `resumeThreadId` / `resumeCursor`.
|
||||
|
||||
#### 2.2.a Agent SDK details to preserve
|
||||
|
||||
The adapter should explicitly rely on these SDK capabilities:
|
||||
|
||||
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
|
||||
2. Multi-turn input is supported via async-iterable prompt input.
|
||||
3. Tool approval decisions are provided via `canUseTool`.
|
||||
4. Resume support uses `resume` and optional `resumeSessionAt`.
|
||||
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
|
||||
|
||||
#### 2.2.b Effect-native session lifecycle skeleton
|
||||
|
||||
```ts
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { Effect } from "effect";
|
||||
|
||||
const acquireSession = (input: ProviderSessionStartInput) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const abortController = new AbortController();
|
||||
const result = query({
|
||||
prompt: makePromptAsyncIterable(input.sessionId),
|
||||
options: {
|
||||
cwd: input.cwd,
|
||||
model: input.model,
|
||||
permissionMode: input.permissionMode,
|
||||
maxThinkingTokens: input.maxThinkingTokens,
|
||||
pathToClaudeCodeExecutable: input.claudeBinaryPath,
|
||||
resume: input.resumeThreadId,
|
||||
resumeSessionAt: readResumeCursor(input.resumeCursor),
|
||||
signal: abortController.signal,
|
||||
includePartialMessages: true,
|
||||
canUseTool: makeCanUseTool(input.sessionId),
|
||||
hooks: makeClaudeHooks(input.sessionId),
|
||||
},
|
||||
});
|
||||
return { abortController, result };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId: "pending",
|
||||
detail: "Failed to start Claude runtime session.",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
({ abortController }) => Effect.sync(() => abortController.abort()),
|
||||
);
|
||||
```
|
||||
|
||||
#### 2.2.c AsyncIterable -> Effect Stream integration
|
||||
|
||||
Preferred when available in the pinned Effect version:
|
||||
|
||||
```ts
|
||||
const sdkMessageStream = Stream.fromAsyncIterable(
|
||||
session.result,
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Portable fallback (already aligned with current server patterns):
|
||||
|
||||
```ts
|
||||
const queue = yield* Queue.unbounded<ClaudeSdkMessage>();
|
||||
yield* Effect.forkScoped(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
for await (const message of session.result) {
|
||||
Queue.offerAllUnsafe(queue, [message]);
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream pump failed.",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const sdkMessageStream = Stream.fromQueue(queue);
|
||||
```
|
||||
|
||||
#### 2.2.d Multi-turn prompt queue pattern (Effect)
|
||||
|
||||
Use an Effect queue as the single input boundary:
|
||||
|
||||
```ts
|
||||
const promptQueue = yield* Queue.unbounded<ClaudePromptEnvelope>();
|
||||
|
||||
const prompt: AsyncIterable<ClaudePromptEnvelope> = {
|
||||
[Symbol.asyncIterator]() {
|
||||
return {
|
||||
next: async () => {
|
||||
const item = await Effect.runPromise(Queue.take(promptQueue));
|
||||
if (item.type === "terminate") {
|
||||
return { done: true, value: undefined };
|
||||
}
|
||||
return { done: false, value: item };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
`sendTurn()` enqueues a user envelope, while `stopSession()` enqueues terminate and aborts.
|
||||
|
||||
#### 2.2.e Approval bridge with `canUseTool`
|
||||
|
||||
Map SDK approval checks to existing orchestration approval flows:
|
||||
|
||||
```ts
|
||||
const canUseTool = async (toolName: string, toolInput: Record<string, unknown>) => {
|
||||
if (approvalModeIsFullAccess(sessionId)) {
|
||||
return { behavior: "allow", updatedInput: toolInput };
|
||||
}
|
||||
|
||||
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
|
||||
emitRuntimeEvent({
|
||||
type: "approval.requested",
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
requestId,
|
||||
requestKind: classifyTool(toolName),
|
||||
detail: summarizeToolRequest(toolName, toolInput),
|
||||
// ... eventId/createdAt
|
||||
});
|
||||
|
||||
const decision = await waitForApprovalDecision(requestId);
|
||||
emitRuntimeEvent({
|
||||
type: "approval.resolved",
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
// ... eventId/createdAt
|
||||
});
|
||||
|
||||
return decision === "accept" || decision === "acceptForSession"
|
||||
? { behavior: "allow", updatedInput: toolInput }
|
||||
: { behavior: "deny", message: "User declined tool execution." };
|
||||
};
|
||||
```
|
||||
|
||||
#### 2.2.f Hooks and checkpoint signals
|
||||
|
||||
If Claude hooks provide cleaner turn boundaries, convert them into canonical runtime events (`turn.completed` and optionally `checkpoint.captured`) so `CheckpointReactor` remains unchanged:
|
||||
|
||||
```ts
|
||||
hooks: {
|
||||
Stop: [
|
||||
{
|
||||
matcher: {},
|
||||
hooks: [
|
||||
async () => {
|
||||
emitRuntimeEvent({
|
||||
type: "checkpoint.captured",
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
threadId,
|
||||
turnId: activeTurnId,
|
||||
turnCount: nextTurnCount(),
|
||||
// ... eventId/createdAt
|
||||
});
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
#### 2.2.g Runtime control method wiring
|
||||
|
||||
Adapter should expose SDK controls through existing service methods and runtime payload updates:
|
||||
|
||||
1. `interruptTurn()` -> `result.interrupt()`
|
||||
2. Model override on send turn -> `result.setModel(model)` before enqueuing prompt
|
||||
3. Runtime mode changes -> `result.setPermissionMode(mode)` if we support live mode switching
|
||||
4. Thinking budget updates -> `result.setMaxThinkingTokens(tokens)` when configured
|
||||
|
||||
### 2.3 Canonical event mapping
|
||||
|
||||
Map Claude SDK events to `ProviderRuntimeEvent`:
|
||||
|
||||
1. `session.started` / `session.exited`
|
||||
2. `turn.started` / `turn.completed`
|
||||
3. `message.delta` / `message.completed`
|
||||
4. `tool.started` / `tool.completed`
|
||||
5. `approval.requested` / `approval.resolved`
|
||||
6. `runtime.error`
|
||||
|
||||
No provider-native event methods should leak beyond the adapter boundary.
|
||||
|
||||
Reference mapping table:
|
||||
|
||||
| Claude SDK message/callback | Canonical runtime event(s) | Notes |
|
||||
|---|---|---|
|
||||
| assistant partial text | `message.delta` | Emit deltas only (do not resend full content each chunk). |
|
||||
| assistant final message | `message.completed` | Must include stable `itemId` for dedupe/finalize behavior. |
|
||||
| result (success) | `turn.completed` (`status: "completed"`) | This is the main turn boundary for checkpointing. |
|
||||
| result (interrupted/cancelled) | `turn.completed` (`status: "interrupted"`/`"cancelled"`) | Preserve state semantics used by ingestion + UI. |
|
||||
| result (error) | `runtime.error` and `turn.completed` (`status: "failed"`) | Include concise error message. |
|
||||
| tool start | `tool.started` | Set `toolKind` using shared classifier (`command`, `file-change`, `other`). |
|
||||
| tool result | `tool.completed` | Include detail summary used by activity feed. |
|
||||
| canUseTool prompt | `approval.requested` | Source of request id shown in UI. |
|
||||
| approval decision returned | `approval.resolved` | Must correlate using same request id. |
|
||||
| session initialization | `session.started`, optional `thread.started` | Ensure `threadId` is emitted early and consistently. |
|
||||
| process exit/close | `session.exited` | Required for session status projection cleanup. |
|
||||
|
||||
### 2.4 Session/thread/resume identifiers
|
||||
|
||||
Define explicit adapter semantics:
|
||||
|
||||
1. `sessionId`: adapter-owned stable session id.
|
||||
2. `threadId`: Claude conversation/session identifier returned as `ProviderThreadId`.
|
||||
3. `resumeCursor`: provider-specific cursor (for example message id) needed for precise recovery/rollback.
|
||||
|
||||
### 2.5 Rollback/read strategy
|
||||
|
||||
Implement `readThread()` and `rollbackThread()` in a way compatible with `CheckpointReactor`.
|
||||
|
||||
Preferred:
|
||||
|
||||
1. Track per-turn resume cursors and reconstruct session state on rollback.
|
||||
2. Keep adapter `sessionId` stable across internal rehydration/restart.
|
||||
|
||||
Fallback (explicitly documented if chosen):
|
||||
|
||||
1. Filesystem revert succeeds even when conversation rewind is partial.
|
||||
2. Reactor behavior is updated to surface a clear warning activity instead of silent drift.
|
||||
|
||||
### 2.6 Adapter unit tests
|
||||
|
||||
Add tests mirroring Codex adapter coverage:
|
||||
|
||||
1. Provider validation (`provider === "claudeCode"`).
|
||||
2. Event mapping to canonical runtime events.
|
||||
3. Approval request lifecycle.
|
||||
4. Resume/recovery behavior.
|
||||
5. Rollback behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Register adapter in runtime composition
|
||||
|
||||
### 3.1 Adapter registry wiring
|
||||
|
||||
Update:
|
||||
|
||||
1. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
|
||||
|
||||
Register both Codex and Claude adapters.
|
||||
|
||||
### 3.2 Server layer composition
|
||||
|
||||
Update:
|
||||
|
||||
1. `apps/server/src/serverLayers.ts`
|
||||
|
||||
Provide `ClaudeCodeAdapterLive` alongside Codex in `makeServerProviderLayer()`.
|
||||
|
||||
### 3.3 Composition tests
|
||||
|
||||
Update integration tests to ensure:
|
||||
|
||||
1. Registry exposes Claude provider.
|
||||
2. Provider service can route Claude sessions.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Orchestration command/reactor updates
|
||||
|
||||
### 4.1 Decider propagation
|
||||
|
||||
Update `apps/server/src/orchestration/decider.ts`:
|
||||
|
||||
1. Carry optional `provider` from `thread.turn.start` command into `thread.turn-start-requested` event payload.
|
||||
|
||||
### 4.2 ProviderCommandReactor provider selection
|
||||
|
||||
Update `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`:
|
||||
|
||||
1. Prefer provider from turn-start event payload when starting a new session.
|
||||
2. Fallback to existing thread session provider when payload omitted.
|
||||
3. Fallback to default provider only when neither is present.
|
||||
|
||||
Switch behavior policy (explicit in implementation):
|
||||
|
||||
1. If active session provider differs from requested provider, stop and recreate session before sending turn.
|
||||
2. Keep current provider when request omits provider.
|
||||
|
||||
### 4.3 Reactor/invariant tests
|
||||
|
||||
Update/add tests in:
|
||||
|
||||
1. `apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts`
|
||||
2. `apps/server/src/orchestration/*.test.ts` as needed
|
||||
|
||||
Validate first-turn provider choice, provider switching semantics, and backward compatibility when provider is omitted.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Web provider UX enablement
|
||||
|
||||
### 5.1 Enable Claude option
|
||||
|
||||
Update `apps/web/src/session-logic.ts`:
|
||||
|
||||
1. Mark Claude provider option as available.
|
||||
|
||||
### 5.2 Provider selection in composer
|
||||
|
||||
Update `apps/web/src/components/ChatView.tsx`:
|
||||
|
||||
1. Add provider picker near model/runtime controls.
|
||||
2. Include selected provider in `thread.turn.start` command payload.
|
||||
3. Keep selected provider sticky per thread in client state (or derive from active session provider when present).
|
||||
|
||||
### 5.3 Provider-aware model picker
|
||||
|
||||
Update model picker usage so model options reflect selected provider.
|
||||
|
||||
### 5.4 Web tests
|
||||
|
||||
Update/add tests for:
|
||||
|
||||
1. Provider picker interactions.
|
||||
2. Turn-start command includes provider.
|
||||
3. Model list switches by provider.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Checkpoint and revert compatibility
|
||||
|
||||
### 6.1 Validate checkpoint reactor expectations
|
||||
|
||||
Exercise `apps/server/src/orchestration/Layers/CheckpointReactor.ts` flows with Claude:
|
||||
|
||||
1. Turn baseline capture.
|
||||
2. Turn completion checkpoint capture.
|
||||
3. Revert + provider rollback coordination.
|
||||
|
||||
### 6.2 Policy for partial rollback support
|
||||
|
||||
If Claude cannot support full conversation rewind at parity with Codex:
|
||||
|
||||
1. Document behavior clearly.
|
||||
2. Emit explicit thread activity for degraded rollback behavior.
|
||||
3. Ensure filesystem state remains correct and predictable.
|
||||
|
||||
### 6.3 Checkpoint tests
|
||||
|
||||
Add/update tests in checkpoint + provider service integration suites for Claude revert behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: End-to-end hardening and observability
|
||||
|
||||
### 7.1 Integration tests
|
||||
|
||||
Add integration coverage for:
|
||||
|
||||
1. `thread.turn.start` with `provider: "claudeCode"` from fresh thread.
|
||||
2. Session recovery after restart (provider session alias/recovery path).
|
||||
3. Approval request/respond flow.
|
||||
4. Interrupt behavior.
|
||||
5. Revert flow with rollback.
|
||||
|
||||
### 7.2 WS behavior regression check
|
||||
|
||||
Ensure no contract regressions:
|
||||
|
||||
1. Client still consumes only `orchestration.domainEvent`.
|
||||
2. No new provider-specific WS channels introduced.
|
||||
|
||||
### 7.3 Logging
|
||||
|
||||
Confirm both native and canonical provider logs remain useful with multi-adapter setup:
|
||||
|
||||
1. `provider-native.ndjson`
|
||||
2. `provider-canonical.ndjson`
|
||||
|
||||
---
|
||||
|
||||
## File checklist
|
||||
|
||||
Likely files to touch:
|
||||
|
||||
1. `packages/contracts/src/model.ts`
|
||||
2. `packages/contracts/src/orchestration.ts`
|
||||
3. `packages/contracts/src/provider.ts`
|
||||
4. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts` (new)
|
||||
5. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts` (new)
|
||||
6. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
|
||||
7. `apps/server/src/serverLayers.ts`
|
||||
8. `apps/server/src/orchestration/decider.ts`
|
||||
9. `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
|
||||
10. `apps/web/src/session-logic.ts`
|
||||
11. `apps/web/src/components/ChatView.tsx`
|
||||
12. Related tests under `packages/contracts/src`, `apps/server/src/provider/Layers`, `apps/server/src/orchestration/Layers`, `apps/server/integration`, and `apps/web/src`.
|
||||
|
||||
---
|
||||
|
||||
## Delivery order
|
||||
|
||||
1. Contracts for provider selection + models.
|
||||
2. Claude adapter + unit tests.
|
||||
3. Registry/layer wiring.
|
||||
4. Reactor updates for provider-aware session start.
|
||||
5. Web provider picker + provider-aware models.
|
||||
6. Checkpoint/revert compatibility.
|
||||
7. End-to-end integration tests and stabilization.
|
||||
|
||||
This order keeps risk isolated and maintains a working orchestrated path at each stage.
|
||||
@@ -0,0 +1,109 @@
|
||||
# Plan: Provider-Neutral Runtime Determinism and Flake Elimination
|
||||
|
||||
## Summary
|
||||
Replace timing-sensitive websocket and orchestration behavior with explicit typed runtime boundaries, ordered push delivery, and server-owned completion receipts. The cutover is broad and single-shot: no compatibility shim, no mixed old/new transport. The design must reduce flakes without baking Codex-specific lifecycle semantics into generic runtime code.
|
||||
|
||||
## Implementation Status
|
||||
|
||||
All 7 sections are implemented. CI passes (format, lint, typecheck, test, browser test, build). One deferred item remains: the shared `WsTestClient` helper from section 7 — tests use direct transport subscription and receipt-based waits instead.
|
||||
|
||||
### New files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `packages/shared/src/DrainableWorker.ts` | Queue-based Effect worker with deterministic `drain` signal |
|
||||
| `packages/shared/src/schemaJson.ts` | Two-phase JSON→Schema decode helpers (`decodeJsonResult`, `formatSchemaError`) |
|
||||
| `apps/server/src/wsServer/pushBus.ts` | `ServerPushBus` — ordered typed push pipeline with auto-incrementing sequence |
|
||||
| `apps/server/src/wsServer/readiness.ts` | `ServerReadiness` — Deferred-based barriers for startup sequencing |
|
||||
| `apps/server/src/orchestration/Services/RuntimeReceiptBus.ts` | Receipt schema union: checkpoint captured, diff finalized, turn quiesced |
|
||||
| `apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts` | PubSub-backed receipt bus implementation |
|
||||
| `apps/server/src/watchFileWithStatPolling.ts` | Stat-polling file watcher for containers where `fs.watch` is unreliable |
|
||||
| `apps/server/vitest.config.ts` | Server-specific test config (timeout bumps) |
|
||||
| `apps/server/src/wsServer/pushBus.test.ts` | Push bus serialization and welcome-gating tests |
|
||||
| `packages/shared/src/DrainableWorker.test.ts` | Drainable worker enqueue/drain lifecycle tests |
|
||||
|
||||
### Key modifications
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `packages/contracts/src/ws.ts` | Channel-indexed `WsPushPayloadByChannel` map, `WsPush` union schema, `WsPushSequence` |
|
||||
| `apps/server/src/wsServer.ts` | Integrated `ServerPushBus` and `ServerReadiness`; welcome gated on readiness |
|
||||
| `apps/server/src/keybindings.ts` | Explicit runtime with `start`/`ready`/`snapshot`; dual `fs.watch` + stat-polling watcher |
|
||||
| `apps/web/src/wsTransport.ts` | Connection state machine (`connecting`→`open`→`reconnecting`→`closed`→`disposed`); two-phase decode at boundary; cached latest push by channel |
|
||||
| `apps/web/src/wsNativeApi.ts` | Removed decode logic; delegates to pre-validated transport messages |
|
||||
| `apps/server/src/orchestration/Layers/CheckpointReactor.ts` | Uses `DrainableWorker`; publishes completion receipts |
|
||||
| `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts` | Uses `DrainableWorker` for command processing |
|
||||
| `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` | Uses `DrainableWorker` for event ingestion |
|
||||
| `apps/server/integration/OrchestrationEngineHarness.integration.ts` | Receipt-based waits replace polling loops |
|
||||
|
||||
## Key Changes
|
||||
### 1. Strengthen the generic boundaries, not the Codex boundary — DONE
|
||||
- `ProviderRuntimeEvent` remains the canonical provider event contract; `ProviderService` remains the only cross-provider facade.
|
||||
- Raw Codex payloads and event ordering stay isolated in `CodexAdapter.ts` and `codexAppServerManager.ts`.
|
||||
- `ProviderKind` was not expanded. The runtime stays provider-neutral by contract.
|
||||
|
||||
### 2. Replace loose websocket envelopes with channel-indexed typed pushes — DONE
|
||||
- `packages/contracts/src/ws.ts` now derives push messages from a `WsPushPayloadByChannel` channel-to-schema map. `WsPush` is a union schema replacing `channel: string` + `data: unknown`.
|
||||
- Every server push carries `sequence: number`, auto-incremented in `ServerPushBus`.
|
||||
- `packages/shared/src/schemaJson.ts` provides structured decode diagnostics via `formatSchemaError`.
|
||||
- `packages/contracts/src/ws.test.ts` covers typed push envelope validation and channel/payload mismatch rejection.
|
||||
|
||||
### 3. Introduce explicit server readiness and a single push pipeline — DONE
|
||||
- `apps/server/src/wsServer/pushBus.ts`: `ServerPushBus` with `publishAll` (broadcast) and `publishClient` (targeted) methods, backed by one ordered path. All pushes flow through it.
|
||||
- `apps/server/src/wsServer/readiness.ts`: `ServerReadiness` with Deferred-based barriers for HTTP listening, push bus, keybindings, terminal subscriptions, and orchestration subscriptions.
|
||||
- `server.welcome` is emitted only after connection-scoped and server-scoped readiness is complete.
|
||||
- `wsServer.ts` no longer publishes directly from ad hoc background streams.
|
||||
|
||||
### 4. Turn background watchers into explicit runtimes — DONE
|
||||
- `apps/server/src/keybindings.ts` refactored as explicit `KeybindingsShape` service with `start`, `ready`, `snapshot` semantics.
|
||||
- Initial config load, cache warmup, and dual watcher attachment (`fs.watch` + `watchFileWithStatPolling`) complete before `ready` resolves.
|
||||
- `watchFileWithStatPolling.ts` is the thin adapter for environments where `fs.watch` is unreliable.
|
||||
|
||||
### 5. Replace polling-based orchestration waiting with receipts — DONE
|
||||
- `RuntimeReceiptBus` service defines three receipt types: `CheckpointBaselineCapturedReceipt`, `CheckpointDiffFinalizedReceipt` (with `status: "ready"|"missing"|"error"`), and `TurnProcessingQuiescedReceipt`.
|
||||
- `CheckpointReactor`, `ProviderCommandReactor`, and `ProviderRuntimeIngestion` use `DrainableWorker` and publish receipts on completion.
|
||||
- Integration harness and checkpoint tests await receipts instead of polling snapshots and git refs.
|
||||
|
||||
### 6. Centralize client transport state and decoding — DONE
|
||||
- `apps/web/src/wsTransport.ts` implements an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
|
||||
- Two-phase decode (JSON parse → Schema validate) happens at the transport boundary. `wsNativeApi.ts` receives pre-validated messages.
|
||||
- Cached latest welcome/config modeled as explicit `latestPushByChannel` state.
|
||||
|
||||
### 7. Replace ad hoc test helpers with semantic test clients — MOSTLY DONE
|
||||
- `DrainableWorker` replaces timing-sensitive `Effect.sleep` with deterministic `drain()` across reactor tests.
|
||||
- Orchestration harness waits on receipts/barriers instead of `waitForThread`, `waitForGitRef`, and retry loops.
|
||||
- Behavioral assertions moved to deterministic unit-style harnesses; narrow integration tests kept for real filesystem/socket behavior.
|
||||
- **Deferred:** Shared `WsTestClient` helper (connect, awaitSemanticWelcome, awaitTypedPush, trackSequence, matchRpcResponseById). Tests use direct transport subscription instead.
|
||||
|
||||
## Provider-Coupling Guardrails
|
||||
- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes.
|
||||
- No readiness barrier may be defined as "Codex has emitted X." Readiness is owned by the server runtime, not by provider event order.
|
||||
- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal.
|
||||
- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code.
|
||||
- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only.
|
||||
- Keep UI/provider-specific knobs such as Codex-only options scoped to provider UX code. Do not pull them into generic transport or orchestration state.
|
||||
|
||||
## Test Plan
|
||||
- Contracts:
|
||||
- schema tests for typed push envelopes and structured decode diagnostics
|
||||
- ordering tests for `sequence`
|
||||
- Server:
|
||||
- readiness tests proving `server.welcome` cannot precede runtime readiness
|
||||
- push bus tests proving terminal/config/orchestration pushes are serialized and typed
|
||||
- keybindings runtime tests with fake watch source plus one real watcher integration test
|
||||
- Orchestration:
|
||||
- receipt tests proving checkpoint refs and projections are complete before completion signals resolve
|
||||
- replacement of polling-based checkpoint/integration waits with receipt-based waits
|
||||
- Web:
|
||||
- transport tests for invalid JSON, invalid envelope, invalid payload, reconnect queue flushing, cached semantic state
|
||||
- Validation gate:
|
||||
- `bun run lint`
|
||||
- `bun run typecheck`
|
||||
- `mise exec -- bun run test`
|
||||
- repeated full-suite run after cutover to confirm flake removal
|
||||
|
||||
## Assumptions and Defaults
|
||||
- This remains a single-provider product during the cutover, but the runtime contracts must stay provider-neutral.
|
||||
- No backward-compatibility layer is required for old websocket push envelopes.
|
||||
- The goal is deterministic runtime behavior first; reducing retries and sleeps in tests is a consequence, not the primary mechanism.
|
||||
- If a completion signal cannot be expressed provider-neutrally, it does not belong in the shared runtime layer and must stay adapter-local.
|
||||
@@ -0,0 +1,89 @@
|
||||
# Replace React Query With AtomRpc + Atom State
|
||||
|
||||
## Summary
|
||||
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
|
||||
- Keep Zustand for orchestration read model and UI state.
|
||||
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
|
||||
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
|
||||
|
||||
## Target Architecture
|
||||
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
|
||||
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
|
||||
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
|
||||
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
|
||||
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
|
||||
|
||||
## Phase 1: Infrastructure First
|
||||
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
|
||||
2. Build the AtomRpc client on top of that layer.
|
||||
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
|
||||
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
|
||||
5. Land this as a no-behavior-change PR.
|
||||
|
||||
## Phase 2: Replace `wsNativeApi`-Owned Push State
|
||||
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
|
||||
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
|
||||
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
|
||||
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
|
||||
|
||||
## Phase 3: Replace React Query Domain By Domain
|
||||
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
|
||||
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
|
||||
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
|
||||
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
|
||||
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
|
||||
6. Defer the desktop updater until the last phase.
|
||||
|
||||
## Phase 4: Move Root Invalidation Off `queryClient`
|
||||
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
|
||||
2. Keep Zustand orchestration/event application unchanged.
|
||||
3. Map current effects exactly:
|
||||
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
|
||||
- file creation/deletion/restoration touches `project:${cwd}`
|
||||
- config-affecting server events touch `server-config`
|
||||
|
||||
## Phase 5: Remove Imperative `NativeApi` Usage
|
||||
1. Create narrow modules instead of a replacement mega-facade:
|
||||
- `rpc/orchestrationActions.ts`
|
||||
- `rpc/terminalActions.ts`
|
||||
- `rpc/gitActions.ts`
|
||||
- `rpc/projectActions.ts`
|
||||
- `platform/desktopBridge.ts`
|
||||
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
|
||||
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
|
||||
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
|
||||
|
||||
## Phase 6: Remove React Query Completely
|
||||
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
|
||||
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
|
||||
4. Delete the old query-option tests.
|
||||
|
||||
## Public Interfaces And Types
|
||||
- Preserve the current server-state hook names during the transition.
|
||||
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
|
||||
- Do not expose raw AtomRpc clients to components.
|
||||
- Do not add Suspense as part of this migration.
|
||||
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
|
||||
|
||||
## Test Plan
|
||||
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
|
||||
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
|
||||
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
|
||||
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
|
||||
- Acceptance scenarios:
|
||||
- welcome still bootstraps snapshot and navigation
|
||||
- keybindings toast still responds to config stream updates
|
||||
- git status/branches refresh after checkout/pull/worktree actions
|
||||
- PR resolve dialog keeps cached result while typing
|
||||
- `@` path search refreshes after file mutations and orchestration events
|
||||
- diff panel refreshes when checkpoints arrive
|
||||
- desktop updater still reflects push events and button actions
|
||||
|
||||
## Assumptions And Defaults
|
||||
- Zustand stays in scope; only `react-query` is being removed.
|
||||
- `desktopBridge` remains the only non-RPC boundary.
|
||||
- The migration lands as 5-6 small PRs, each green independently.
|
||||
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
|
||||
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
|
||||
@@ -3,13 +3,16 @@
|
||||
Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft.
|
||||
|
||||
Execution mode for this plan:
|
||||
|
||||
- Hard cutover only. Existing DB and migration history are disposable.
|
||||
- Intermediate steps are allowed to break runtime, tests, typecheck, and lint.
|
||||
- We optimize for small, reviewable work units, not continuous app operability.
|
||||
- Only the final gate requires everything to run cleanly.
|
||||
|
||||
## 1. Freeze SPEC contract as source of truth
|
||||
|
||||
Work units:
|
||||
|
||||
- Create `.plans/spec-contract-matrix.md` with one row per requirement in `SPEC.md` sections `7.1`-`7.4`.
|
||||
- Add exact SQL-level requirements per row: table, column, type, nullability, PK/unique, index, and invariants.
|
||||
- Add app-level requirements per row: writer path, reader path, and owning module.
|
||||
@@ -17,17 +20,22 @@ Work units:
|
||||
- Identify any ambiguous spec lines and record a concrete interpretation in the matrix.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Complete matrix file with no unclassified rows.
|
||||
- Single source checklist used by all later steps.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- No code changes required yet.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Every requirement in `7.1`-`7.4` has exactly one matrix row.
|
||||
|
||||
## 2. Hard cutover migrations (replace current migration set)
|
||||
|
||||
Work units:
|
||||
|
||||
- Delete the current legacy migration files and rewrite migration loader ordering.
|
||||
- Create `001_orchestration_events.ts` with full envelope columns and required event indexes.
|
||||
- Create `002_orchestration_command_receipts.ts` with PK + lookup indexes.
|
||||
@@ -47,17 +55,22 @@ Work units:
|
||||
- Ensure old tables (`projects`, `provider_checkpoints`, `provider_sessions`) are not recreated.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- New 5-file migration chain.
|
||||
- Updated migration loader references only new migrations.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Repositories/services can be temporarily broken due to removed old tables.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Fresh DB initializes with only canonical tables plus migration bookkeeping.
|
||||
|
||||
## 3. Align persistence row/request schemas to DB 1:1
|
||||
|
||||
Work units:
|
||||
|
||||
- Define row schemas for each canonical table (contracts or persistence layer module).
|
||||
- Define request schemas for every insert/update/query operation touching canonical tables.
|
||||
- Remove or deprecate row/request schemas tied to deleted legacy tables.
|
||||
@@ -65,17 +78,22 @@ Work units:
|
||||
- Ensure SQL aliases map 1:1 to schema field names (no implicit shape transforms).
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Canonical row/request schemas committed.
|
||||
- Zero references to legacy row schemas in active code paths.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Runtime can still fail while query layers are being rewired.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Every canonical table used in code has a typed row schema and typed request schema.
|
||||
|
||||
## 4. Rewrite event store for full persisted envelope
|
||||
|
||||
Work units:
|
||||
|
||||
- Refactor append path to write full envelope fields:
|
||||
- `event_id`, `aggregate_kind`, `stream_id`, `stream_version`, `event_type`, `occurred_at`, `command_id`, `causation_event_id`, `correlation_id`, `actor_kind`, `payload_json`, `metadata_json`
|
||||
- Implement stream version assignment/checking per aggregate stream.
|
||||
@@ -84,16 +102,21 @@ Work units:
|
||||
- Add explicit SQL ordering guarantees for replay (`ORDER BY sequence ASC`).
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Event store append/replay fully aligned with canonical envelope.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Command dispatch flow can be partially broken until receipts/projectors are updated.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Event store no longer depends on legacy event table shape.
|
||||
|
||||
## 5. Add command receipt idempotency
|
||||
|
||||
Work units:
|
||||
|
||||
- Introduce persistence access layer for `orchestration_command_receipts`.
|
||||
- In command dispatch flow, check existing receipt by `commandId` before append.
|
||||
- On first execution, persist accepted receipt with `resultSequence`.
|
||||
@@ -102,16 +125,21 @@ Work units:
|
||||
- Ensure receipt write and event append ordering is deterministic.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Dispatch path with idempotency behavior wired through receipts.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Snapshot/read model may still be inconsistent until projectors are fully wired.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Duplicate command IDs no longer create duplicate events.
|
||||
|
||||
## 6. Build DB-backed projection pipeline
|
||||
|
||||
Work units:
|
||||
|
||||
- Create projector runner that consumes events and applies table-specific projections.
|
||||
- Implement projector handlers for each projection table.
|
||||
- For each handler, update target row(s) and `projection_state.last_applied_sequence` in the same transaction.
|
||||
@@ -120,16 +148,21 @@ Work units:
|
||||
- Add safe resume logic from projector `last_applied_sequence`.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Persistent projector pipeline writing all `projection_*` tables.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Web/API layer may still read old in-memory model until step 7.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Events drive projection rows in DB; projection state advances transactionally.
|
||||
|
||||
## 7. Move RPC reads to projections and diff blobs
|
||||
|
||||
Work units:
|
||||
|
||||
- Implement snapshot query service reading only projection tables.
|
||||
- Build thread hydration from projection rows: messages, activities, checkpoints, session.
|
||||
- Compute `snapshotSequence` as the minimum required projector sequence from `projection_state`.
|
||||
@@ -138,16 +171,21 @@ Work units:
|
||||
- Validate replay handoff contract: snapshot sequence -> replay from `fromSequenceExclusive`.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Provider runtime persistence may still be partially legacy until step 8.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- No orchestration read RPC depends on legacy tables or in-memory-only state.
|
||||
|
||||
## 8. Migrate provider runtime persistence to canonical table
|
||||
|
||||
Work units:
|
||||
|
||||
- Create repository/service for `provider_session_runtime`.
|
||||
- Update adapter/session manager to persist runtime/resume cursor in new table.
|
||||
- Ensure domain-visible session state still flows through orchestration events to `projection_thread_sessions`.
|
||||
@@ -155,16 +193,21 @@ Work units:
|
||||
- Verify restart/resume path reads runtime state from canonical table only.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Provider runtime state entirely backed by `provider_session_runtime`.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Some legacy interfaces may still exist but should be disconnected.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Runtime restore no longer reads/writes legacy provider session persistence.
|
||||
|
||||
## 9. Remove old cruft aggressively
|
||||
|
||||
Work units:
|
||||
|
||||
- Delete legacy repositories/services that map to removed tables.
|
||||
- Remove dead migration imports and obsolete persistence service interfaces.
|
||||
- Remove compatibility code paths that translate legacy row shapes.
|
||||
@@ -172,16 +215,21 @@ Work units:
|
||||
- Update internal docs/comments to reference canonical projection/event model only.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Legacy persistence and translation layers removed from active codebase.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Temporary compile failures acceptable while deletion/refactor is in progress.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- No production code path references deleted legacy tables/services.
|
||||
|
||||
## 10. Final verification gate (first point where green is required)
|
||||
|
||||
Work units:
|
||||
|
||||
- Add migration tests that assert canonical tables, columns, constraints, and indexes.
|
||||
- Add event store tests for envelope persistence, metadata, actor kind, and replay.
|
||||
- Add receipt idempotency tests for accept/reject/duplicate paths.
|
||||
@@ -192,10 +240,13 @@ Work units:
|
||||
- Run project lint/typecheck/tests and fix failures.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Green checks with canonical schema + persistence model in place.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- None at end of step.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- SPEC `7.1`-`7.4` requirements satisfied and validated by tests.
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPEC Contract Matrix (Sections 7.1-7.4)
|
||||
|
||||
Status legend:
|
||||
|
||||
- `required`: requirement acknowledged, no current implementation claim yet.
|
||||
- `implemented`: requirement currently satisfied in code + schema.
|
||||
- `to-replace`: partial/misaligned implementation exists and must be replaced.
|
||||
@@ -9,6 +10,7 @@ Status legend:
|
||||
## 7.1 Write-Side Persisted Tables
|
||||
|
||||
### W1
|
||||
|
||||
- Spec ref: `7.1.1 orchestration_events`
|
||||
- Requirement: append-only event store with canonical envelope columns.
|
||||
- SQL contract:
|
||||
@@ -32,6 +34,7 @@ Status legend:
|
||||
- Notes: current migration/table lacks `stream_id`, `stream_version`, `causation_event_id`, `correlation_id`, `actor_kind`, `metadata_json`.
|
||||
|
||||
### W2
|
||||
|
||||
- Spec ref: `7.1.2 orchestration_command_receipts`
|
||||
- Requirement: command idempotency + ack replay receipts table.
|
||||
- SQL contract:
|
||||
@@ -49,6 +52,7 @@ Status legend:
|
||||
- Notes: missing table and missing idempotency flow.
|
||||
|
||||
### W3
|
||||
|
||||
- Spec ref: `7.1.3 checkpoint_diff_blobs`
|
||||
- Requirement: store large plaintext diffs separate from checkpoint summaries.
|
||||
- SQL contract:
|
||||
@@ -65,6 +69,7 @@ Status legend:
|
||||
- Notes: no canonical diff blob table yet.
|
||||
|
||||
### W4
|
||||
|
||||
- Spec ref: `7.1.4 provider_session_runtime`
|
||||
- Requirement: server-internal provider runtime/resume state.
|
||||
- SQL contract:
|
||||
@@ -86,6 +91,7 @@ Status legend:
|
||||
## 7.2 Canonical Persisted Event Schema
|
||||
|
||||
### E1
|
||||
|
||||
- Spec ref: `7.2 OrchestrationPersistedEventSchema`
|
||||
- Requirement: full typed persisted event envelope in shared contracts.
|
||||
- SQL contract: envelope fields in W1 must map 1:1 to contracts schema.
|
||||
@@ -96,6 +102,7 @@ Status legend:
|
||||
- Notes: contract schema exists; DB + store mapping still incomplete.
|
||||
|
||||
### E2
|
||||
|
||||
- Spec ref: `7.2 Rules/payload discriminated by eventType`
|
||||
- Requirement: `payload` validation keyed by `eventType`.
|
||||
- SQL contract: `event_type` drives payload decode schema; invalid combinations rejected.
|
||||
@@ -106,6 +113,7 @@ Status legend:
|
||||
- Notes: decode is present but DB does not persist full envelope columns.
|
||||
|
||||
### E3
|
||||
|
||||
- Spec ref: `7.2 Rules/provider ids scope`
|
||||
- Requirement: provider ids live in metadata/provider payload, not as thread identity replacement.
|
||||
- SQL contract: provider fields persisted inside `metadata_json`; `stream_id` remains project/thread id.
|
||||
@@ -116,6 +124,7 @@ Status legend:
|
||||
- Notes: metadata plumbing is incomplete in persistence path.
|
||||
|
||||
### E4
|
||||
|
||||
- Spec ref: `7.2 Rules/streamVersion concurrency guard`
|
||||
- Requirement: stream version monotonic per aggregate stream; enforced on write.
|
||||
- SQL contract: `stream_version INTEGER NOT NULL` + uniqueness/invariant enforcement per stream.
|
||||
@@ -128,6 +137,7 @@ Status legend:
|
||||
## 7.3 Required Projected Tables (Read Models)
|
||||
|
||||
### P1
|
||||
|
||||
- Spec ref: `7.3.1 projection_projects`
|
||||
- Requirement: persisted project projection table.
|
||||
- SQL contract:
|
||||
@@ -145,6 +155,7 @@ Status legend:
|
||||
- Notes: legacy `projects` table is separate concept and should be removed from orchestration model.
|
||||
|
||||
### P2
|
||||
|
||||
- Spec ref: `7.3.2 projection_threads`
|
||||
- Requirement: persisted thread projection table.
|
||||
- SQL contract:
|
||||
@@ -165,6 +176,7 @@ Status legend:
|
||||
- Notes: missing table and projector writes.
|
||||
|
||||
### P3
|
||||
|
||||
- Spec ref: `7.3.3 projection_thread_messages`
|
||||
- Requirement: persisted thread message projection table.
|
||||
- SQL contract:
|
||||
@@ -183,6 +195,7 @@ Status legend:
|
||||
- Notes: missing table and message projection writes.
|
||||
|
||||
### P4
|
||||
|
||||
- Spec ref: `7.3.4 projection_thread_activities`
|
||||
- Requirement: persisted thread activity projection table.
|
||||
- SQL contract:
|
||||
@@ -201,6 +214,7 @@ Status legend:
|
||||
- Notes: no canonical activity projection persistence.
|
||||
|
||||
### P5
|
||||
|
||||
- Spec ref: `7.3.5 projection_thread_sessions`
|
||||
- Requirement: persisted thread session projection table.
|
||||
- SQL contract:
|
||||
@@ -219,6 +233,7 @@ Status legend:
|
||||
- Notes: current provider session table is not this domain projection.
|
||||
|
||||
### P6
|
||||
|
||||
- Spec ref: `7.3.6 projection_thread_turns`
|
||||
- Requirement: persisted thread turn projection table.
|
||||
- SQL contract:
|
||||
@@ -237,6 +252,7 @@ Status legend:
|
||||
- Notes: missing table and projection logic.
|
||||
|
||||
### P7
|
||||
|
||||
- Spec ref: `7.3.7 projection_checkpoints`
|
||||
- Requirement: persisted checkpoint summary projection table.
|
||||
- SQL contract:
|
||||
@@ -256,6 +272,7 @@ Status legend:
|
||||
- Notes: current table semantics do not match canonical checkpoint projection schema.
|
||||
|
||||
### P8
|
||||
|
||||
- Spec ref: `7.3.8 projection_pending_approvals`
|
||||
- Requirement: persisted pending-approval projection table.
|
||||
- SQL contract:
|
||||
@@ -273,6 +290,7 @@ Status legend:
|
||||
- Notes: missing table and projection logic.
|
||||
|
||||
### P9
|
||||
|
||||
- Spec ref: `7.3.9 projection_state`
|
||||
- Requirement: projector progress tracking table.
|
||||
- SQL contract:
|
||||
@@ -286,6 +304,7 @@ Status legend:
|
||||
- Notes: missing table and projector bookkeeping.
|
||||
|
||||
### P10
|
||||
|
||||
- Spec ref: `7.3 Projection consistency rules`
|
||||
- Requirement: projector row updates and `projection_state` update must be atomic per event.
|
||||
- SQL contract: per-projector transaction boundary covering both projection write and state update.
|
||||
@@ -296,6 +315,7 @@ Status legend:
|
||||
- Notes: requires transactional projection executor.
|
||||
|
||||
### P11
|
||||
|
||||
- Spec ref: `7.3 Optional debug field`
|
||||
- Requirement: `lastEventSequence` on projection rows is optional and not required for correctness.
|
||||
- SQL contract: optional; not required in baseline schema.
|
||||
@@ -308,6 +328,7 @@ Status legend:
|
||||
## 7.4 Snapshot and RPC Requirements
|
||||
|
||||
### R1
|
||||
|
||||
- Spec ref: `7.4.1`
|
||||
- Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`.
|
||||
- SQL contract: snapshot query joins/reads only `projection_*` + `projection_state`.
|
||||
@@ -318,6 +339,7 @@ Status legend:
|
||||
- Notes: current in-memory read model path must be removed for SPEC compliance.
|
||||
|
||||
### R2
|
||||
|
||||
- Spec ref: `7.4.2`
|
||||
- Requirement: snapshot `projects[]` source is `projection_projects`.
|
||||
- SQL contract: `projects` collection assembled from `projection_projects` rows.
|
||||
@@ -328,6 +350,7 @@ Status legend:
|
||||
- Notes: no DB project projection reader exists yet.
|
||||
|
||||
### R3
|
||||
|
||||
- Spec ref: `7.4.3`
|
||||
- Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields.
|
||||
- SQL contract: fields `turnId`, `completedAt`, `status`, `files[]`, `checkpointRef`, optional `assistantMessageId`, `checkpointTurnCount`.
|
||||
@@ -338,6 +361,7 @@ Status legend:
|
||||
- Notes: canonical projection table and reader not implemented.
|
||||
|
||||
### R4
|
||||
|
||||
- Spec ref: `7.4.4`
|
||||
- Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs.
|
||||
- SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only.
|
||||
@@ -348,6 +372,7 @@ Status legend:
|
||||
- Notes: current checkpoint repository is not canonical source.
|
||||
|
||||
### R5
|
||||
|
||||
- Spec ref: `7.4.5`
|
||||
- Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`.
|
||||
- SQL contract: session lookup by `thread_id` from projection table.
|
||||
@@ -358,6 +383,7 @@ Status legend:
|
||||
- Notes: remove provider-session-as-routing-key behavior.
|
||||
|
||||
### R6
|
||||
|
||||
- Spec ref: `7.4.6`
|
||||
- Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors.
|
||||
- SQL contract: `MIN(last_applied_sequence)` across required projector keys.
|
||||
@@ -368,6 +394,7 @@ Status legend:
|
||||
- Notes: must move from in-memory sequence to DB projection-state semantics.
|
||||
|
||||
### R7
|
||||
|
||||
- Spec ref: `7.4.7`
|
||||
- Requirement: snapshot/replay handoff has no gap (`getSnapshot` -> subscribe from snapshot sequence).
|
||||
- SQL contract: read consistency strategy guaranteeing no missing events between snapshot visibility and replay start.
|
||||
@@ -380,22 +407,27 @@ Status legend:
|
||||
## Ambiguous/Interpretation Decisions (tracked upfront)
|
||||
|
||||
### A1
|
||||
|
||||
- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming.
|
||||
- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.
|
||||
|
||||
### A2
|
||||
|
||||
- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload.
|
||||
- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.
|
||||
|
||||
### A3
|
||||
|
||||
- Topic: `snapshotSequence` dependency set for min-sequence computation.
|
||||
- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).
|
||||
|
||||
### A4
|
||||
|
||||
- Topic: no-gap handoff mechanism in `7.4.7`.
|
||||
- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.
|
||||
|
||||
## Checklist Completeness Statement
|
||||
|
||||
- Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`.
|
||||
- Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`.
|
||||
- Unclassified rows: `0`.
|
||||
@@ -1,64 +0,0 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg", "favicon.ico", "favicon.png",
|
||||
"public/favicon.svg", "public/favicon.ico", "public/favicon.png",
|
||||
"app/favicon.ico", "app/favicon.png", "app/icon.svg", "app/icon.png", "app/icon.ico",
|
||||
"src/favicon.ico", "src/favicon.svg", "src/app/favicon.ico", "src/app/icon.svg", "src/app/icon.png",
|
||||
];
|
||||
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html", "public/index.html",
|
||||
"app/routes/__root.tsx", "src/routes/__root.tsx",
|
||||
"app/root.tsx", "src/root.tsx", "src/index.html",
|
||||
];
|
||||
|
||||
const LINK_ICON_HTML_RE = /<link[^>]*rel=["'](?:icon|shortcut icon)["'][^>]*href=["']([^"'?]+)/i;
|
||||
const LINK_ICON_OBJ_RE = /rel:\s*["'](?:icon|shortcut icon)["'][^}]*href:\s*["']([^"'?]+)/i;
|
||||
|
||||
function test(projectCwd) {
|
||||
console.log("--- Testing:", projectCwd, "---");
|
||||
|
||||
for (const c of FAVICON_CANDIDATES) {
|
||||
const full = path.join(projectCwd, c);
|
||||
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
|
||||
console.log(" Phase 1 FOUND:", c);
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log(" Phase 1: no match");
|
||||
|
||||
for (const sf of ICON_SOURCE_FILES) {
|
||||
const full = path.join(projectCwd, sf);
|
||||
if (!fs.existsSync(full)) continue;
|
||||
const content = fs.readFileSync(full, "utf8");
|
||||
const href = content.match(LINK_ICON_HTML_RE)?.[1] || content.match(LINK_ICON_OBJ_RE)?.[1];
|
||||
if (href) {
|
||||
const clean = href.replace(/^\//, "");
|
||||
const tryPaths = [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
for (const p of tryPaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
console.log(" Phase 2 FOUND:", sf, "->", href, "->", p);
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log(" Phase 2 href found but file missing:", href);
|
||||
}
|
||||
}
|
||||
console.log(" Phase 2: no match");
|
||||
}
|
||||
|
||||
function getTestPaths() {
|
||||
const cliPaths = process.argv.slice(2).map((p) => p.trim()).filter(Boolean);
|
||||
if (cliPaths.length > 0) return cliPaths;
|
||||
|
||||
const envPaths = process.env.TEST_PATHS?.split(path.delimiter).map((p) => p.trim()).filter(Boolean);
|
||||
if (envPaths?.length) return envPaths;
|
||||
|
||||
return [process.cwd()];
|
||||
}
|
||||
|
||||
for (const p of getTestPaths()) {
|
||||
test(path.resolve(p));
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
# CLAUDE.md
|
||||
# AGENTS.md
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
|
||||
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
||||
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
|
||||
|
||||
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
||||
|
||||
@@ -14,11 +19,16 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
|
||||
|
||||
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
||||
|
||||
## Maintainability
|
||||
|
||||
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
||||
|
||||
## Package Roles
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
|
||||
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
|
||||
|
||||
## Codex App Server (Important)
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# Contributing
|
||||
|
||||
## Read This First
|
||||
|
||||
We are not actively accepting contributions right now.
|
||||
|
||||
You can still open an issue or PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it.
|
||||
|
||||
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
|
||||
|
||||
PRs are automatically labeled with a `vouch:*` trust status and a `size:*` diff size based on changed lines.
|
||||
|
||||
If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td).
|
||||
|
||||
## What We Are Most Likely To Accept
|
||||
|
||||
Small, focused bug fixes.
|
||||
|
||||
Small reliability fixes.
|
||||
|
||||
Small performance improvements.
|
||||
|
||||
Tightly scoped maintenance work that clearly improves the project without changing its direction.
|
||||
|
||||
## What We Are Least Likely To Accept
|
||||
|
||||
Large PRs.
|
||||
|
||||
Drive-by feature work.
|
||||
|
||||
Opinionated rewrites.
|
||||
|
||||
Anything that expands product scope without us asking for it first.
|
||||
|
||||
If you open a 1,000+ line PR full of new features, we will probably close it quickly and remember that you ignored the clearly written instructions.
|
||||
|
||||
## If You Still Want To Open A PR
|
||||
|
||||
Keep it small.
|
||||
|
||||
Explain exactly what changed.
|
||||
|
||||
Explain exactly why the change should exist.
|
||||
|
||||
Do not mix unrelated fixes together.
|
||||
|
||||
If the PR makes anything resembling a UI change, include clear before/after images.
|
||||
|
||||
If the change depends on motion, timing, transitions, or interaction details, include a short video.
|
||||
|
||||
If we have to guess what changed, we are much less likely to review it.
|
||||
|
||||
## Issues First
|
||||
|
||||
If you are thinking about a non-trivial change, open an issue first.
|
||||
|
||||
That still does not mean we will want the PR, but it gives you a chance to avoid wasting your time.
|
||||
|
||||
## Be Realistic
|
||||
|
||||
Opening a PR does not create an obligation on our side.
|
||||
|
||||
We may close it. We may ignore it. We may ask you to shrink it. We may reimplement the idea ourselves later.
|
||||
|
||||
If you are fine with that, proceed.
|
||||
@@ -51,7 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
|
||||
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 T3 Tools Inc.
|
||||
|
||||
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.
|
||||
@@ -1,124 +1,52 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
|
||||
Run `npx t3` in any project directory to launch the web interface.
|
||||
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
|
||||
## Installation
|
||||
|
||||
## Architecture
|
||||
> [!WARNING]
|
||||
> T3 Code currently supports Codex and Claude.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
||||
> - Claude: install Claude Code and run `claude auth login`
|
||||
|
||||
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ Browser (React + Vite) │
|
||||
│ Connected via WebSocket │
|
||||
└──────────┬──────────────────────┘
|
||||
│ ws://localhost:3773
|
||||
┌──────────▼──────────────────────┐
|
||||
│ apps/server (Node.js) │
|
||||
│ WebSocket + HTTP static server │
|
||||
│ ProviderManager │
|
||||
│ CodexAppServerManager │
|
||||
└──────────┬──────────────────────┘
|
||||
│ JSON-RPC over stdio
|
||||
┌──────────▼──────────────────────┐
|
||||
│ codex app-server │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Workspace layout
|
||||
|
||||
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
|
||||
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
|
||||
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
|
||||
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
|
||||
## Codex prerequisites
|
||||
|
||||
- Install Codex CLI so `codex` is on your PATH.
|
||||
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
|
||||
- T3 Code starts the server via `codex app-server` per session.
|
||||
|
||||
## Quick start
|
||||
### Run without installing
|
||||
|
||||
```bash
|
||||
# Development (with hot reload)
|
||||
bun run dev
|
||||
|
||||
# Desktop development
|
||||
bun run dev:desktop
|
||||
|
||||
# Desktop development on an isolated port set
|
||||
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
|
||||
|
||||
# Production
|
||||
bun run build
|
||||
bun run start
|
||||
|
||||
# Build a shareable macOS .dmg (arm64 by default)
|
||||
bun run dist:desktop:dmg
|
||||
|
||||
# Or from any project directory after publishing:
|
||||
npx t3
|
||||
```
|
||||
|
||||
## Scripts
|
||||
### Desktop app
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||
`bun run dev -- --state-dir ~/.t3/another-dev-state`
|
||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
#### Windows (`winget`)
|
||||
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
```bash
|
||||
winget install T3Tools.T3Code
|
||||
```
|
||||
|
||||
### Running multiple dev instances
|
||||
#### macOS (Homebrew)
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
```bash
|
||||
brew install --cask t3-code
|
||||
```
|
||||
|
||||
- Default ports: server `3773`, web `5733`
|
||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||
#### Arch Linux (AUR)
|
||||
|
||||
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
|
||||
```bash
|
||||
yay -S t3code-bin
|
||||
```
|
||||
|
||||
## Runtime modes
|
||||
## Some notes
|
||||
|
||||
T3 Code has a global runtime mode switch in the chat toolbar:
|
||||
We are very very early in this project. Expect bugs.
|
||||
|
||||
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
|
||||
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
|
||||
We are not accepting contributions yet.
|
||||
|
||||
## Provider architecture
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
|
||||
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
|
||||
|
||||
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
|
||||
|
||||
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
|
||||
- `providers.respondToRequest`, `providers.stopSession`
|
||||
- `shell.openInEditor`, `server.getConfig`
|
||||
|
||||
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
|
||||
|
||||
## CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -6,21 +6,24 @@ Use this when you want to open T3 Code from another device (phone, tablet, anoth
|
||||
|
||||
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ---------------------------------- |
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
|
||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
|
||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
|
||||
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
|
||||
|
||||
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||
|
||||
## Security First
|
||||
|
||||
- Always set `--auth-token` before exposing the server outside localhost.
|
||||
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
|
||||
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
|
||||
- Treat the token like a password.
|
||||
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
||||
|
||||
|
||||
@@ -1,582 +0,0 @@
|
||||
# Orchestration Interface Spec (Required State)
|
||||
|
||||
Status: Required target architecture (not a description of current behavior).
|
||||
|
||||
## 1. Identifier Schema (Branded)
|
||||
|
||||
All identifiers are branded and never plain `string` in schema definitions.
|
||||
|
||||
```ts
|
||||
const ThreadId = Schema.String.pipe(Schema.brand("ThreadId"));
|
||||
const ProjectId = Schema.String.pipe(Schema.brand("ProjectId"));
|
||||
const CommandId = Schema.String.pipe(Schema.brand("CommandId"));
|
||||
const EventId = Schema.String.pipe(Schema.brand("EventId"));
|
||||
const MessageId = Schema.String.pipe(Schema.brand("MessageId"));
|
||||
const TurnId = Schema.String.pipe(Schema.brand("TurnId"));
|
||||
|
||||
const ProviderSessionId = Schema.String.pipe(Schema.brand("ProviderSessionId"));
|
||||
const ProviderThreadId = Schema.String.pipe(Schema.brand("ProviderThreadId"));
|
||||
const ProviderTurnId = Schema.String.pipe(Schema.brand("ProviderTurnId"));
|
||||
const ProviderItemId = Schema.String.pipe(Schema.brand("ProviderItemId"));
|
||||
const ApprovalRequestId = Schema.String.pipe(Schema.brand("ApprovalRequestId"));
|
||||
|
||||
const CheckpointRef = Schema.String.pipe(Schema.brand("CheckpointRef"));
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `ThreadId` is app/orchestration thread identity.
|
||||
- `ProviderThreadId` is provider runtime thread identity.
|
||||
- They are never assigned to each other.
|
||||
- `ProviderSessionId` is internal server/provider routing identity; clients do not send it.
|
||||
- use e.g. `ThreadId.make(randomUUID())` to create new entity ids at the source (e.g. client create thread id and send to server, provider adapter creates the provider thread id from the codex app server etc)
|
||||
|
||||
## 2. Client Commands (Domain Commands)
|
||||
|
||||
All commands are sent through one RPC: `orchestration.dispatchCommand`.
|
||||
|
||||
Output for every command: `DispatchResultSchema = { sequence: number }`.
|
||||
|
||||
### 2.1 Client-Dispatchable Commands
|
||||
|
||||
1. `project.create`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `workspaceRoot: string`
|
||||
- `defaultModel?: string`
|
||||
- `createdAt: IsoDateTime`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
2. `project.meta.update`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `projectId: ProjectId`
|
||||
- optional `{ title, workspaceRoot, defaultModel, scripts }`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
3. `project.delete`
|
||||
|
||||
- Input: `commandId`, `projectId`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
4. `thread.create`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `threadId: ThreadId`
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `model: string`
|
||||
- `branch: string | null`
|
||||
- `worktreePath: string | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
5. `thread.delete`
|
||||
|
||||
- Input: `commandId`, `threadId`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
6. `thread.meta.update`
|
||||
|
||||
- Input: `commandId`, `threadId`, optional `{ title, model, branch, worktreePath }`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
7. `thread.turn.start`
|
||||
|
||||
- Input:
|
||||
- `commandId`
|
||||
- `threadId`
|
||||
- `message`:
|
||||
- `messageId: MessageId`
|
||||
- `role: "user"`
|
||||
- `text: string`
|
||||
- `attachments: ChatAttachment[]` (schema-shared)
|
||||
- `model?: string`
|
||||
- `effort?: string`
|
||||
- `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
8. `thread.turn.interrupt`
|
||||
|
||||
- Input: `commandId`, `threadId`, optional `turnId: TurnId`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
9. `thread.approval.respond`
|
||||
|
||||
- Input:
|
||||
- `commandId`
|
||||
- `threadId`
|
||||
- `requestId: ApprovalRequestId`
|
||||
- `decision: "accept" | "acceptForSession" | "decline" | "cancel"`
|
||||
- `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
10. `thread.checkpoint.revert`
|
||||
|
||||
- Input: `commandId`, `threadId`, `turnCount: number`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
11. `thread.session.stop`
|
||||
|
||||
- Input: `commandId`, `threadId`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
### 2.2 Internal-Only Commands (Not Client Dispatchable)
|
||||
|
||||
1. `thread.session.set`
|
||||
|
||||
- Server-owned projection update for session lifecycle.
|
||||
|
||||
2. `thread.message.assistant.delta`
|
||||
|
||||
- Server-owned incremental assistant content append.
|
||||
|
||||
3. `thread.message.assistant.complete`
|
||||
|
||||
- Server-owned assistant message completion marker.
|
||||
|
||||
4. `thread.turn.diff.complete`
|
||||
|
||||
- Server-owned checkpoint diff summary write.
|
||||
|
||||
5. `thread.activity.append`
|
||||
|
||||
- Server-owned activity feed append.
|
||||
|
||||
## 3. Client RPC (Required)
|
||||
|
||||
These are the required client-facing RPC methods.
|
||||
|
||||
1. `orchestration.getSnapshot`
|
||||
|
||||
- Input: `{}`
|
||||
- Output: `OrchestrationReadModel`
|
||||
|
||||
2. `orchestration.dispatchCommand`
|
||||
|
||||
- Input: `ClientOrchestrationCommand` (`Schema.Union` of all client-dispatchable commands)
|
||||
- Output: `DispatchResult`
|
||||
|
||||
3. `orchestration.getTurnDiff`
|
||||
|
||||
- Input:
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- Output:
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- `diff: string`
|
||||
|
||||
4. `orchestration.replayEvents` (optional operational/debug API)
|
||||
|
||||
- Input: `{ fromSequenceExclusive: number }`
|
||||
- Output: `OrchestrationEvent[]`
|
||||
|
||||
### 3.1 RPC To Remove
|
||||
|
||||
Remove from client boundary:
|
||||
|
||||
- `providers.startSession`
|
||||
- `providers.sendTurn`
|
||||
- `providers.interruptTurn`
|
||||
- `providers.respondToRequest`
|
||||
- `providers.stopSession`
|
||||
- `providers.listCheckpoints`
|
||||
- `providers.getCheckpointDiff`
|
||||
- `providers.revertToCheckpoint`
|
||||
|
||||
Rationale:
|
||||
|
||||
- Session/turn/checkpoint control belongs to orchestrator command path.
|
||||
- Snapshot already includes checkpoint summaries (`checkpoints`); only full textual diff needs explicit query RPC.
|
||||
|
||||
## 4. Server Orchestrator Command <-> Event Schemas
|
||||
|
||||
Each command deterministically yields one or more domain events that are persisted to the event store.
|
||||
|
||||
1. `project.create` -> `project.created`
|
||||
2. `project.meta.update` -> `project.meta-updated`
|
||||
3. `project.delete` -> `project.deleted`
|
||||
4. `thread.create` -> `thread.created`
|
||||
5. `thread.delete` -> `thread.deleted`
|
||||
6. `thread.meta.update` -> `thread.meta-updated`
|
||||
7. `thread.turn.start` ->
|
||||
|
||||
- `thread.message-sent` (user message append)
|
||||
- `thread.turn-start-requested`
|
||||
- then (async side effect success) `thread.session-set` + provider-driven message/turn events
|
||||
|
||||
8. `thread.turn.interrupt` -> `thread.turn-interrupt-requested`
|
||||
9. `thread.approval.respond` -> `thread.approval-response-requested`
|
||||
10. `thread.checkpoint.revert` -> `thread.checkpoint-revert-requested` then `thread.reverted`
|
||||
11. `thread.session.stop` -> `thread.session-stop-requested` then `thread.session-set`
|
||||
|
||||
Internal command/event path:
|
||||
|
||||
- `thread.session.set` -> `thread.session-set`
|
||||
- `thread.message.assistant.delta` -> `thread.message-sent` (assistant streaming)
|
||||
- `thread.message.assistant.complete` -> `thread.message-sent` (streaming false)
|
||||
- `thread.turn.diff.complete` -> `thread.turn-diff-completed`
|
||||
- `thread.activity.append` -> `thread.activity-appended`
|
||||
|
||||
## 5. Orchestration Events <-> Generic Provider Events <-> Raw Provider Events
|
||||
|
||||
Required mapping pipeline:
|
||||
|
||||
`Raw Provider Event (adapter-specific)`
|
||||
-> `GenericProviderRuntimeEvent` (provider-agnostic schema)
|
||||
-> `Internal Orchestration Command`
|
||||
-> `Orchestration Domain Event`
|
||||
|
||||
### 5.1 Mapping Table for Codex Adapter
|
||||
|
||||
1. Raw `thread/started`
|
||||
|
||||
- Generic: `thread.started`
|
||||
- Internal command: `thread.session.set` (attach `ProviderThreadId`, status `ready|running`)
|
||||
- Domain event: `thread.session-set`
|
||||
|
||||
2. Raw `turn/started`
|
||||
|
||||
- Generic: `turn.started`
|
||||
- Internal command: `thread.session.set` (status `running`, active turn)
|
||||
- Domain event: `thread.session-set`
|
||||
|
||||
3. Raw `item/agentMessage/delta`
|
||||
|
||||
- Generic: `message.delta`
|
||||
- Internal command: `thread.message.assistant.delta`
|
||||
- Domain event: `thread.message-sent` (assistant, streaming)
|
||||
|
||||
4. Raw `item/completed` (agent message)
|
||||
|
||||
- Generic: `message.completed`
|
||||
- Internal command: `thread.message.assistant.complete`
|
||||
- Domain event: `thread.message-sent` (assistant, completed)
|
||||
|
||||
5. Raw `turn/completed`
|
||||
|
||||
- Generic: `turn.completed`
|
||||
- Internal commands:
|
||||
- `thread.session.set` (ready/error)
|
||||
- `thread.activity.append` (optional summary)
|
||||
- Domain events: `thread.session-set`, `thread.activity-appended`
|
||||
|
||||
6. Raw approval request
|
||||
|
||||
- Generic: `approval.requested`
|
||||
- Internal command: `thread.activity.append` (typed `requestId`, `requestKind`)
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
7. Raw approval decision ack
|
||||
|
||||
- Generic: `approval.resolved`
|
||||
- Internal command: `thread.activity.append`
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
8. Raw tool start/complete
|
||||
|
||||
- Generic: `tool.started` / `tool.completed`
|
||||
- Internal command: `thread.activity.append`
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
9. Checkpoint capture (server-produced)
|
||||
|
||||
- Generic: `checkpoint.captured`
|
||||
- Internal command: `thread.turn.diff.complete`
|
||||
- Domain event: `thread.turn-diff-completed`
|
||||
|
||||
10. Raw/runtime error
|
||||
|
||||
- Generic: `runtime.error`
|
||||
- Internal commands:
|
||||
- `thread.session.set` (status `error`)
|
||||
- `thread.activity.append` (`tone=error`)
|
||||
- Domain events: `thread.session-set`, `thread.activity-appended`
|
||||
|
||||
## 6. Schema Section (Boundary + Reuse)
|
||||
|
||||
### 6.1 Shared Schemas (contracts package)
|
||||
|
||||
Expose to both web and server:
|
||||
|
||||
- `OrchestrationReadModelSchema`
|
||||
- `ClientOrchestrationCommandSchema`
|
||||
- `OrchestrationEventSchema`
|
||||
- `OrchestrationRpcSchemas` (`getSnapshot`, `dispatchCommand`, `getTurnDiff`, optional replay)
|
||||
- `GenericProviderRuntimeEventSchema` (used for diagnostics/ingestion tests)
|
||||
- Shared message/activity/checkpoint summary schemas used in snapshot
|
||||
|
||||
### 6.2 Server-Internal Schemas
|
||||
|
||||
Not exposed to web:
|
||||
|
||||
- `InternalOrchestrationCommandSchema`
|
||||
- Adapter raw-event schemas and provider-specific payload schemas
|
||||
- Provider session directory records and persistence-only row schemas
|
||||
- Git service cache/query schemas (non-orchestration read model)
|
||||
|
||||
### 6.3 Reuse Requirements
|
||||
|
||||
- Snapshot checkpoint summary schema is source of truth for checkpoint list UI.
|
||||
- `getTurnDiff` response reuses `ThreadId`/turn count brands and textual `diff` only.
|
||||
- Activity schemas are reused for approval/tool/runtime annotations; no separate UI-only structure.
|
||||
- Session schema must include both `threadId: ThreadId` and optional `providerThreadId: ProviderThreadId` (explicitly distinct).
|
||||
|
||||
## 7. Persistence Model (Required)
|
||||
|
||||
This section defines required persisted tables, the canonical persisted event envelope, and required projected/read tables.
|
||||
|
||||
### 7.1 Write-Side Persisted Tables
|
||||
|
||||
1. `orchestration_events` (append-only event store)
|
||||
|
||||
- `sequence: number` (global monotonic sequence, primary key)
|
||||
- `eventId: EventId` (unique)
|
||||
- `aggregateKind: "project" | "thread"`
|
||||
- `streamId: ProjectId | ThreadId` (aggregate stream id)
|
||||
- `streamVersion: number` (per-aggregate monotonic version)
|
||||
- `eventType: OrchestrationEventType`
|
||||
- `occurredAt: IsoDateTime`
|
||||
- `commandId: CommandId | null`
|
||||
- `causationEventId: EventId | null`
|
||||
- `correlationId: CommandId | null`
|
||||
- `actorKind: "client" | "server" | "provider"`
|
||||
- `payload: OrchestrationEventPayload` (type-validated by `eventType`)
|
||||
- `metadata: OrchestrationEventMetadata`
|
||||
|
||||
2. `orchestration_command_receipts` (idempotency + ack replay)
|
||||
|
||||
- `commandId: CommandId` (primary key)
|
||||
- `aggregateKind: "project" | "thread"`
|
||||
- `aggregateId: ProjectId | ThreadId`
|
||||
- `acceptedAt: IsoDateTime`
|
||||
- `resultSequence: number`
|
||||
- `status: "accepted" | "rejected"`
|
||||
- `error: string | null`
|
||||
|
||||
3. `checkpoint_diff_blobs` (large plaintext diffs; separate from summaries)
|
||||
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- `diff: string`
|
||||
- `createdAt: IsoDateTime`
|
||||
- unique key: `(threadId, fromTurnCount, toTurnCount)`
|
||||
|
||||
4. `provider_session_runtime` (server-internal adapter resume state)
|
||||
|
||||
- `providerSessionId: ProviderSessionId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `providerName: string`
|
||||
- `adapterKey: string`
|
||||
- `providerThreadId: ProviderThreadId | null`
|
||||
- `status: "starting" | "running" | "stopped" | "error"`
|
||||
- `lastSeenAt: IsoDateTime`
|
||||
- `resumeCursor: JsonValue | null` (adapter-specific opaque state)
|
||||
- `runtimePayload: JsonValue | null` (adapter-specific opaque state)
|
||||
|
||||
### 7.2 Canonical Persisted Event Schema
|
||||
|
||||
`OrchestrationPersistedEventSchema` (full envelope):
|
||||
|
||||
```ts
|
||||
type OrchestrationPersistedEvent = {
|
||||
sequence: number;
|
||||
eventId: EventId;
|
||||
aggregateKind: "project" | "thread";
|
||||
streamId: ProjectId | ThreadId;
|
||||
streamVersion: number;
|
||||
eventType: OrchestrationEventType;
|
||||
occurredAt: IsoDateTime;
|
||||
commandId: CommandId | null;
|
||||
causationEventId: EventId | null;
|
||||
correlationId: CommandId | null;
|
||||
actorKind: "client" | "server" | "provider";
|
||||
payload: OrchestrationEventPayload;
|
||||
metadata: {
|
||||
providerSessionId?: ProviderSessionId;
|
||||
providerThreadId?: ProviderThreadId;
|
||||
providerTurnId?: ProviderTurnId;
|
||||
providerItemId?: ProviderItemId;
|
||||
adapterKey?: string;
|
||||
requestId?: ApprovalRequestId;
|
||||
ingestedAt?: IsoDateTime;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `payload` must be schema-discriminated by `eventType`.
|
||||
- provider identifiers only appear in `metadata` and provider-specific payload sub-shapes; they do not replace `ThreadId`.
|
||||
- `streamVersion` is concurrency guard for aggregate writes.
|
||||
|
||||
### 7.3 Required Projected Tables (Read Models)
|
||||
|
||||
1. `projection_projects`
|
||||
|
||||
- `projectId: ProjectId` (primary key)
|
||||
- `title: string`
|
||||
- `workspaceRoot: string`
|
||||
- `defaultModel: string | null`
|
||||
- `scripts: ProjectScript[]`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
- `deletedAt: IsoDateTime | null`
|
||||
|
||||
2. `projection_threads`
|
||||
|
||||
- `threadId: ThreadId` (primary key)
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `model: string`
|
||||
- `branch: string | null`
|
||||
- `worktreePath: string | null`
|
||||
- `latestTurnId: TurnId | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
- `deletedAt: IsoDateTime | null`
|
||||
|
||||
3. `projection_thread_messages`
|
||||
|
||||
- `messageId: MessageId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `role: "user" | "assistant" | "system"`
|
||||
- `text: string`
|
||||
- `isStreaming: boolean`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
4. `projection_thread_activities`
|
||||
|
||||
- `activityId: EventId` (primary key; derived from source event)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `tone: "info" | "tool" | "approval" | "error"`
|
||||
- `kind: string`
|
||||
- `summary: string`
|
||||
- `payload: JsonValue`
|
||||
- `createdAt: IsoDateTime`
|
||||
|
||||
5. `projection_thread_sessions`
|
||||
|
||||
- `threadId: ThreadId` (primary key)
|
||||
- `status: "idle" | "starting" | "running" | "ready" | "interrupted" | "stopped" | "error"`
|
||||
- `providerName: string | null`
|
||||
- `providerSessionId: ProviderSessionId | null`
|
||||
- `providerThreadId: ProviderThreadId | null`
|
||||
- `activeTurnId: TurnId | null`
|
||||
- `lastError: string | null`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
6. `projection_thread_turns`
|
||||
|
||||
- `turnId: TurnId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnCount: number`
|
||||
- `status: "running" | "completed" | "interrupted" | "error"`
|
||||
- `userMessageId: MessageId | null`
|
||||
- `assistantMessageId: MessageId | null`
|
||||
- `startedAt: IsoDateTime`
|
||||
- `completedAt: IsoDateTime | null`
|
||||
|
||||
7. `projection_checkpoints`
|
||||
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId`
|
||||
- `checkpointTurnCount: number`
|
||||
- `checkpointRef: CheckpointRef`
|
||||
- `status: "ready" | "missing" | "error"`
|
||||
- `files: JsonArray` (typed as file diff summary schema)
|
||||
- `assistantMessageId: MessageId | null`
|
||||
- `completedAt: IsoDateTime`
|
||||
- unique key: `(threadId, checkpointTurnCount)`
|
||||
|
||||
8. `projection_pending_approvals`
|
||||
|
||||
- `requestId: ApprovalRequestId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `status: "pending" | "resolved"`
|
||||
- `decision: "accept" | "acceptForSession" | "decline" | "cancel" | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `resolvedAt: IsoDateTime | null`
|
||||
|
||||
9. `projection_state`
|
||||
|
||||
- `projector: string` (primary key; e.g. `threads`, `messages`, `sessions`)
|
||||
- `lastAppliedSequence: number`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
Projection consistency rules:
|
||||
|
||||
- Every projector applies read-model row updates and `projection_state.lastAppliedSequence` in the same database transaction.
|
||||
- Optional debug field on projection rows: `lastEventSequence: number` (not required for correctness).
|
||||
|
||||
### 7.4 Snapshot and RPC Requirements
|
||||
|
||||
1. `orchestration.getSnapshot` is fully served from projection tables and returns `snapshotSequence: number`.
|
||||
2. Snapshot must include `projects[]` from `projection_projects`.
|
||||
3. Thread snapshot must include `checkpoints[]` from `projection_checkpoints`:
|
||||
|
||||
- `turnId: TurnId`
|
||||
- `completedAt: IsoDateTime`
|
||||
- `status`
|
||||
- `files[]` (`path`, `kind`, `additions`, `deletions`)
|
||||
- `checkpointRef: CheckpointRef`
|
||||
- `assistantMessageId?: MessageId`
|
||||
- `checkpointTurnCount: number`
|
||||
|
||||
4. Client does not require `listCheckpoints` RPC:
|
||||
|
||||
- checkpoint list comes from snapshot projections
|
||||
- full diff text comes from `orchestration.getTurnDiff` backed by `checkpoint_diff_blobs`
|
||||
|
||||
5. Provider session identity is not a client routing key:
|
||||
|
||||
- client acts on `ThreadId`
|
||||
- server resolves provider session internally via `projection_thread_sessions`
|
||||
|
||||
6. `snapshotSequence` is derived from `projection_state`:
|
||||
|
||||
- if snapshot depends on multiple projectors, use the minimum `lastAppliedSequence` across those projectors.
|
||||
|
||||
7. Event subscription handoff contract:
|
||||
|
||||
- client performs `getSnapshot` and reads `snapshotSequence`
|
||||
- client subscribes/replays with `fromSequenceExclusive = snapshotSequence`
|
||||
- server guarantees no gap between snapshot visibility and subsequent event stream from that sequence.
|
||||
|
||||
### 7.5 External Derived State (Non-Orchestration)
|
||||
|
||||
1. Current git/worktree state is not projected from orchestration events.
|
||||
2. If persisted, it belongs in a separate git cache/read model (for example `git_state_cache`) owned by a git service.
|
||||
3. Orchestration may embed git metadata only when captured as a domain fact (for example checkpoint metadata at turn completion).
|
||||
4. Any RPC for current git status should be outside orchestration RPC (for example `git.getThreadState`).
|
||||
|
||||
### 7.6 Existing Repository Placement
|
||||
|
||||
1. `ProjectsRepository`
|
||||
|
||||
- Fits as projection/query access on top of `projection_projects` plus orchestration command dispatch for writes.
|
||||
- Must not bypass command->event append path for mutations.
|
||||
|
||||
2. `CheckpointsRepository`
|
||||
|
||||
- Fits as projection/query access on top of `projection_checkpoints` plus `checkpoint_diff_blobs` (or git-service on-demand diff implementation).
|
||||
- Represents the same concept as prior `turn_diff_summary`; canonical naming is `checkpoint`.
|
||||
- Must not be an independent source of truth outside orchestration events.
|
||||
|
||||
3. `ProviderSessionsRepository`
|
||||
|
||||
- Fits as server-internal runtime persistence on top of `provider_session_runtime`, with domain-visible state projected into `projection_thread_sessions`.
|
||||
- Not part of client RPC/domain aggregate boundary.
|
||||
@@ -2,24 +2,12 @@
|
||||
|
||||
## Small things
|
||||
|
||||
- [ ] Plan mode
|
||||
- [ ] Submitting new messages should scroll to bottom
|
||||
- [ ] 1 click copy in codeblocks
|
||||
- [x] Pasting/adding images to submit with prompts
|
||||
- [ ] Only show last 10 threads for a given project
|
||||
- [ ] Thread archiving
|
||||
- [x] Selecting folder should instantly create project
|
||||
- [ ] New projects should go on top
|
||||
- [ ] Projects should be sorted by latest thread update
|
||||
- [x] "Response" bar should ONLY appear on work completed
|
||||
- [x] "Response" bar should ONLY appear above the FINAL message in a series
|
||||
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
||||
- [x] Insta focus input on new thread creation
|
||||
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [x] Making new thread should auto-focus input box
|
||||
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
||||
|
||||
## Bigger things
|
||||
|
||||
- [ ] Queueing messages
|
||||
- [x] External runners (i.e. running the cli on a mac mini)
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0",
|
||||
"version": "0.0.15",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
@@ -14,16 +14,17 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron": "40.6.0"
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@types/node": "^22.10.2",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"wait-on": "^8.0.2"
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
}
|
||||
@@ -1,43 +1,182 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import electronmon from "electronmon";
|
||||
import waitOn from "wait-on";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
const requiredFiles = [
|
||||
"dist-electron/main.js",
|
||||
"dist-electron/preload.js",
|
||||
"../server/dist/bin.mjs",
|
||||
];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
|
||||
await waitOn({
|
||||
resources: [
|
||||
`tcp:${port}`,
|
||||
"file:dist-electron/main.js",
|
||||
"file:dist-electron/preload.js",
|
||||
"file:../server/dist/index.mjs",
|
||||
],
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
files: requiredFiles,
|
||||
tcpPort: port,
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const monitor = await electronmon({
|
||||
cwd: desktopDir,
|
||||
args: ["dist-electron/main.js"],
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
electronPath: resolveElectronPath(),
|
||||
});
|
||||
|
||||
let shuttingDown = false;
|
||||
let restartTimer = null;
|
||||
let currentApp = null;
|
||||
let restartQueue = Promise.resolve();
|
||||
const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function startApp() {
|
||||
if (shuttingDown || currentApp !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
currentApp = app;
|
||||
|
||||
app.once("error", () => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
|
||||
app.once("exit", (code, signal) => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
const exitedAbnormally = signal !== null || code !== 0;
|
||||
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stopApp() {
|
||||
const app = currentApp;
|
||||
if (!app) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentApp = null;
|
||||
expectedExits.add(app);
|
||||
|
||||
await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
|
||||
const finish = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
resolve();
|
||||
};
|
||||
|
||||
app.once("exit", finish);
|
||||
app.kill("SIGTERM");
|
||||
killChildTreeByPid(app.pid, "TERM");
|
||||
|
||||
setTimeout(() => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
app.kill("SIGKILL");
|
||||
killChildTreeByPid(app.pid, "KILL");
|
||||
finish();
|
||||
}, forcedShutdownTimeoutMs).unref();
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleRestart() {
|
||||
if (shuttingDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
}
|
||||
|
||||
restartTimer = setTimeout(() => {
|
||||
restartTimer = null;
|
||||
restartQueue = restartQueue
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
await stopApp();
|
||||
if (!shuttingDown) {
|
||||
startApp();
|
||||
}
|
||||
});
|
||||
}, restartDebounceMs);
|
||||
}
|
||||
|
||||
function startWatchers() {
|
||||
for (const { directory, files } of watchedDirectories) {
|
||||
const watcher = watch(
|
||||
join(desktopDir, directory),
|
||||
{ persistent: true },
|
||||
(_eventType, filename) => {
|
||||
if (typeof filename !== "string" || !files.has(filename)) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleRestart();
|
||||
},
|
||||
);
|
||||
|
||||
watchers.push(watcher);
|
||||
}
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
@@ -45,20 +184,29 @@ async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
try {
|
||||
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
}
|
||||
|
||||
for (const watcher of watchers) {
|
||||
watcher.close();
|
||||
}
|
||||
|
||||
await stopApp();
|
||||
killChildTree("TERM");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, childTreeGracePeriodMs);
|
||||
});
|
||||
killChildTree("KILL");
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
startWatchers();
|
||||
cleanupStaleDevApps();
|
||||
startApp();
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import * as FileSystem from "node:fs/promises";
|
||||
import * as Net from "node:net";
|
||||
import * as Path from "node:path";
|
||||
import * as Timers from "node:timers/promises";
|
||||
|
||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
||||
|
||||
async function fileExists(filePath) {
|
||||
try {
|
||||
await FileSystem.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
|
||||
return new Promise((resolveReady) => {
|
||||
const socket = Net.createConnection({ host, port });
|
||||
let settled = false;
|
||||
|
||||
const finish = (ready) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
socket.removeAllListeners();
|
||||
socket.destroy();
|
||||
resolveReady(ready);
|
||||
};
|
||||
|
||||
socket.once("connect", () => {
|
||||
finish(true);
|
||||
});
|
||||
socket.once("timeout", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.once("error", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.setTimeout(connectTimeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
|
||||
const pendingFiles = [];
|
||||
|
||||
for (const relativeFilePath of files) {
|
||||
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
|
||||
if (!ready) {
|
||||
pendingFiles.push(relativeFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
let tcpReady = false;
|
||||
for (const host of tcpHosts) {
|
||||
tcpReady = await tcpPortIsReady({
|
||||
host,
|
||||
port: tcpPort,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
if (tcpReady) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pendingFiles,
|
||||
tcpReady,
|
||||
};
|
||||
}
|
||||
|
||||
export async function waitForResources({
|
||||
baseDir,
|
||||
files = [],
|
||||
intervalMs = 100,
|
||||
timeoutMs = 120_000,
|
||||
tcpHost,
|
||||
tcpPort,
|
||||
connectTimeoutMs = 500,
|
||||
}) {
|
||||
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
|
||||
throw new TypeError("waitForResources requires a positive integer tcpPort");
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
|
||||
|
||||
while (true) {
|
||||
const { pendingFiles, tcpReady } = await resolvePendingResources({
|
||||
baseDir,
|
||||
files,
|
||||
tcpPort,
|
||||
tcpHosts,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
|
||||
if (pendingFiles.length === 0 && tcpReady) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
const pendingResources = [];
|
||||
if (!tcpReady) {
|
||||
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
|
||||
}
|
||||
for (const filePath of pendingFiles) {
|
||||
pendingResources.push(`file:${filePath}`);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
await Timers.setTimeout(intervalMs);
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: CONFIRM_BUTTON_INDEX,
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
} catch {
|
||||
// Keep inherited PATH if shell lookup fails.
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,26 @@ import type { DesktopBridge } from "@t3tools/contracts";
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
getWsUrl: () => {
|
||||
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
|
||||
return typeof result === "string" ? result : null;
|
||||
},
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
showContextMenu: (items) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
@@ -25,4 +35,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
onUpdateState: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
|
||||
if (typeof state !== "object" || state === null) return;
|
||||
listener(state as Parameters<typeof listener>[0]);
|
||||
};
|
||||
|
||||
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
} satisfies DesktopBridge);
|
||||
@@ -0,0 +1,74 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
|
||||
tempRoots.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempRoots.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("RotatingFileSink", () => {
|
||||
it("rotates when writes exceed max bytes", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 10,
|
||||
maxFiles: 3,
|
||||
});
|
||||
|
||||
sink.write("12345");
|
||||
sink.write("67890");
|
||||
sink.write("abc");
|
||||
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
|
||||
});
|
||||
|
||||
it("retains only maxFiles backups", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "server-child.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 4,
|
||||
maxFiles: 2,
|
||||
});
|
||||
|
||||
sink.write("aaaa");
|
||||
sink.write("bbbb");
|
||||
sink.write("cccc");
|
||||
sink.write("dddd");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
|
||||
});
|
||||
|
||||
it("prunes stale backups above maxFiles on startup", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
|
||||
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 16,
|
||||
maxFiles: 2,
|
||||
});
|
||||
sink.write("hello");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
|
||||
describe("resolveDesktopRuntimeInfo", () => {
|
||||
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
|
||||
const runtimeInfo = resolveDesktopRuntimeInfo({
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
runningUnderArm64Translation: true,
|
||||
});
|
||||
|
||||
expect(runtimeInfo).toEqual({
|
||||
hostArch: "arm64",
|
||||
appArch: "x64",
|
||||
runningUnderArm64Translation: true,
|
||||
});
|
||||
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(true);
|
||||
});
|
||||
|
||||
it("detects native Apple Silicon builds", () => {
|
||||
const runtimeInfo = resolveDesktopRuntimeInfo({
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
});
|
||||
|
||||
expect(runtimeInfo).toEqual({
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
});
|
||||
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(false);
|
||||
});
|
||||
|
||||
it("passes through non-mac builds without translation", () => {
|
||||
const runtimeInfo = resolveDesktopRuntimeInfo({
|
||||
platform: "linux",
|
||||
processArch: "x64",
|
||||
runningUnderArm64Translation: true,
|
||||
});
|
||||
|
||||
expect(runtimeInfo).toEqual({
|
||||
hostArch: "x64",
|
||||
appArch: "x64",
|
||||
runningUnderArm64Translation: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { DesktopRuntimeArch, DesktopRuntimeInfo } from "@t3tools/contracts";
|
||||
|
||||
interface ResolveDesktopRuntimeInfoInput {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly processArch: string;
|
||||
readonly runningUnderArm64Translation: boolean;
|
||||
}
|
||||
|
||||
function normalizeDesktopArch(arch: string): DesktopRuntimeArch {
|
||||
if (arch === "arm64") return "arm64";
|
||||
if (arch === "x64") return "x64";
|
||||
return "other";
|
||||
}
|
||||
|
||||
export function resolveDesktopRuntimeInfo(
|
||||
input: ResolveDesktopRuntimeInfoInput,
|
||||
): DesktopRuntimeInfo {
|
||||
const appArch = normalizeDesktopArch(input.processArch);
|
||||
|
||||
if (input.platform !== "darwin") {
|
||||
return {
|
||||
hostArch: appArch,
|
||||
appArch,
|
||||
runningUnderArm64Translation: false,
|
||||
};
|
||||
}
|
||||
|
||||
const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
|
||||
|
||||
return {
|
||||
hostArch,
|
||||
appArch,
|
||||
runningUnderArm64Translation: input.runningUnderArm64Translation,
|
||||
};
|
||||
}
|
||||
|
||||
export function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
|
||||
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
|
||||
describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "darwin",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "darwin",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("preserves inherited values when the login shell omits them", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "darwin",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "linux",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/usr/local/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).not.toHaveBeenCalled();
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
options: {
|
||||
platform?: NodeJS.Platform;
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
]);
|
||||
|
||||
if (shellEnvironment.PATH) {
|
||||
env.PATH = shellEnvironment.PATH;
|
||||
}
|
||||
|
||||
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
||||
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
} catch {
|
||||
// Keep inherited environment if shell lookup fails.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
reduceDesktopUpdateStateOnCheckStart,
|
||||
reduceDesktopUpdateStateOnDownloadComplete,
|
||||
reduceDesktopUpdateStateOnDownloadFailure,
|
||||
reduceDesktopUpdateStateOnDownloadProgress,
|
||||
reduceDesktopUpdateStateOnDownloadStart,
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
|
||||
const runtimeInfo = {
|
||||
hostArch: "x64",
|
||||
appArch: "x64",
|
||||
runningUnderArm64Translation: false,
|
||||
} as const;
|
||||
|
||||
describe("updateMachine", () => {
|
||||
it("clears transient errors when a check starts", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
message: "network",
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("checking");
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
expect(state.canRetry).toBe(false);
|
||||
});
|
||||
|
||||
it("records a check failure without exposing an action", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"network unavailable",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("error");
|
||||
expect(state.errorContext).toBe("check");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves available version on download failure for retry", () => {
|
||||
const state = reduceDesktopUpdateStateOnDownloadFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
downloadPercent: 43,
|
||||
},
|
||||
"checksum mismatch",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("available");
|
||||
expect(state.availableVersion).toBe("1.1.0");
|
||||
expect(state.errorContext).toBe("download");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("transitions to downloaded and then preserves install retry state", () => {
|
||||
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
},
|
||||
"1.1.0",
|
||||
);
|
||||
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(
|
||||
downloaded,
|
||||
"backend shutdown timed out",
|
||||
);
|
||||
|
||||
expect(downloaded.status).toBe("downloaded");
|
||||
expect(downloaded.downloadedVersion).toBe("1.1.0");
|
||||
expect(failedInstall.status).toBe("downloaded");
|
||||
expect(failedInstall.errorContext).toBe("install");
|
||||
expect(failedInstall.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("clears stale download state when no update is available", () => {
|
||||
const state = reduceDesktopUpdateStateOnNoUpdate(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
downloadedVersion: "1.1.0",
|
||||
message: "old failure",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("up-to-date");
|
||||
expect(state.availableVersion).toBeNull();
|
||||
expect(state.downloadedVersion).toBeNull();
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
});
|
||||
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"1.1.0",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
expect(progress.errorContext).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||
|
||||
export function createInitialDesktopUpdateState(
|
||||
currentVersion: string,
|
||||
runtimeInfo: DesktopRuntimeInfo,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
enabled: false,
|
||||
status: "disabled",
|
||||
currentVersion,
|
||||
hostArch: runtimeInfo.hostArch,
|
||||
appArch: runtimeInfo.appArch,
|
||||
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckStart(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "checking",
|
||||
checkedAt,
|
||||
message: null,
|
||||
downloadPercent: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "error",
|
||||
message,
|
||||
checkedAt,
|
||||
downloadPercent: null,
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "available",
|
||||
availableVersion: version,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnNoUpdate(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "up-to-date",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadStart(
|
||||
state: DesktopUpdateState,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: 0,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: nextStatusAfterDownloadFailure(state),
|
||||
message,
|
||||
downloadPercent: null,
|
||||
errorContext: "download",
|
||||
canRetry: getCanRetryAfterDownloadFailure(state),
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadProgress(
|
||||
state: DesktopUpdateState,
|
||||
percent: number,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: percent,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadComplete(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
availableVersion: version,
|
||||
downloadedVersion: version,
|
||||
downloadPercent: 100,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnInstallFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
message,
|
||||
errorContext: "install",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
getCanRetryAfterDownloadFailure,
|
||||
getAutoUpdateDisabledReason,
|
||||
nextStatusAfterDownloadFailure,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
currentVersion: "1.0.0",
|
||||
hostArch: "x64",
|
||||
appArch: "x64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
|
||||
describe("shouldBroadcastDownloadProgress", () => {
|
||||
it("broadcasts the first downloading progress update", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: null },
|
||||
1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("skips progress updates within the same 10% bucket", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 11.2 },
|
||||
18.7,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a new 10% bucket is reached", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 19.9 },
|
||||
20.1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a retry resets the download percentage", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 50.4 },
|
||||
0.2,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAutoUpdateDisabledReason", () => {
|
||||
it("reports development builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: true,
|
||||
isPackaged: false,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("packaged production builds");
|
||||
});
|
||||
|
||||
it("reports env-disabled auto updates", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: true,
|
||||
}),
|
||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||
});
|
||||
|
||||
it("reports linux non-AppImage builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "linux",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("AppImage");
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextStatusAfterDownloadFailure", () => {
|
||||
it("returns available when an update version is still known", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe("available");
|
||||
});
|
||||
|
||||
it("returns error when no update version can be retried", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCanRetryAfterDownloadFailure", () => {
|
||||
it("returns true when an available version is still present", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when no version is available to retry", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
export function shouldBroadcastDownloadProgress(
|
||||
currentState: DesktopUpdateState,
|
||||
nextPercent: number,
|
||||
): boolean {
|
||||
if (currentState.status !== "downloading") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const currentPercent = currentState.downloadPercent;
|
||||
if (currentPercent === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const previousStep = Math.floor(currentPercent / 10);
|
||||
const nextStep = Math.floor(nextPercent / 10);
|
||||
return nextStep !== previousStep || nextPercent === 100;
|
||||
}
|
||||
|
||||
export function nextStatusAfterDownloadFailure(
|
||||
currentState: DesktopUpdateState,
|
||||
): DesktopUpdateState["status"] {
|
||||
return currentState.availableVersion ? "available" : "error";
|
||||
}
|
||||
|
||||
export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean {
|
||||
return currentState.availableVersion !== null;
|
||||
}
|
||||
|
||||
export function getAutoUpdateDisabledReason(args: {
|
||||
isDevelopment: boolean;
|
||||
isPackaged: boolean;
|
||||
platform: NodeJS.Platform;
|
||||
appImage?: string | undefined;
|
||||
disabledByEnv: boolean;
|
||||
}): string | null {
|
||||
if (args.isDevelopment || !args.isPackaged) {
|
||||
return "Automatic updates are only available in packaged production builds.";
|
||||
}
|
||||
if (args.disabledByEnv) {
|
||||
return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
|
||||
}
|
||||
if (args.platform === "linux" && !args.appImage) {
|
||||
return "Automatic updates on Linux require running the AppImage build.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from "astro/config";
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
port: Number(process.env.PORT ?? 4173),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@t3tools/marketing",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"build": "astro build",
|
||||
"preview": "astro preview",
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^6.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.7",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 414 B |
|
After Width: | Height: | Size: 662 B |
|
After Width: | Height: | Size: 9.9 KiB |
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 652 KiB |
@@ -0,0 +1,228 @@
|
||||
---
|
||||
interface Props {
|
||||
title?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
const {
|
||||
title = "T3 Code",
|
||||
description = "T3 Code — The best way to code with AI.",
|
||||
} = Astro.props;
|
||||
---
|
||||
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content={description} />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<title>{title}</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<nav class="nav">
|
||||
<a href="/" class="nav-brand">
|
||||
<img src="/icon.png" alt="T3" class="nav-icon" />
|
||||
</a>
|
||||
<a
|
||||
href="https://github.com/pingdotgg/t3code"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="nav-github"
|
||||
>
|
||||
GitHub
|
||||
<span class="nav-github-arrow" aria-hidden="true">↗</span>
|
||||
</a>
|
||||
</nav>
|
||||
|
||||
<main class="main">
|
||||
<slot />
|
||||
</main>
|
||||
|
||||
<footer class="footer">
|
||||
<span class="footer-copy">© {new Date().getFullYear()} T3 Tools Inc</span>
|
||||
<div class="footer-links">
|
||||
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
<style is:global>
|
||||
:root {
|
||||
--bg: #09090b;
|
||||
--fg: #fafafa;
|
||||
--fg-muted: #a1a1aa;
|
||||
--fg-dim: #71717a;
|
||||
--border: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
html {
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
min-height: 100vh;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
body::after {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
opacity: 0.035;
|
||||
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
|
||||
background-repeat: repeat;
|
||||
background-size: 256px 256px;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@keyframes fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
/* ── Page ── */
|
||||
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
/* ── Navbar ── */
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1.5rem 2.5rem;
|
||||
opacity: 0.5;
|
||||
transition: opacity 0.4s ease;
|
||||
}
|
||||
|
||||
.nav:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.nav-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.nav-github {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
color: var(--fg-muted);
|
||||
font-size: 0.875rem;
|
||||
transition: color 0.3s ease;
|
||||
}
|
||||
|
||||
.nav-github:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.nav-github-arrow {
|
||||
display: inline-block;
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.nav-github:hover .nav-github-arrow {
|
||||
transform: translateX(2px) translateY(-1px);
|
||||
}
|
||||
|
||||
/* ── Main content ── */
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* ── Footer ── */
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1.5rem 2.5rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--fg-dim);
|
||||
}
|
||||
|
||||
.footer-links {
|
||||
display: flex;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.footer-links a {
|
||||
color: var(--fg-dim);
|
||||
transition: color 0.3s ease;
|
||||
}
|
||||
|
||||
.footer-links a:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
/* ── Mobile ── */
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.nav {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.footer {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,30 @@
|
||||
const REPO = "pingdotgg/t3code";
|
||||
|
||||
export const RELEASES_URL = `https://github.com/${REPO}/releases`;
|
||||
|
||||
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
|
||||
const CACHE_KEY = "t3code-latest-release";
|
||||
|
||||
export interface ReleaseAsset {
|
||||
name: string;
|
||||
browser_download_url: string;
|
||||
}
|
||||
|
||||
export interface Release {
|
||||
tag_name: string;
|
||||
html_url: string;
|
||||
assets: ReleaseAsset[];
|
||||
}
|
||||
|
||||
export async function fetchLatestRelease(): Promise<Release> {
|
||||
const cached = sessionStorage.getItem(CACHE_KEY);
|
||||
if (cached) return JSON.parse(cached);
|
||||
|
||||
const data = await fetch(API_URL).then((r) => r.json());
|
||||
|
||||
if (data?.assets) {
|
||||
sessionStorage.setItem(CACHE_KEY, JSON.stringify(data));
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
---
|
||||
|
||||
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||
<h1 class="heading">Download T3 Code</h1>
|
||||
<p class="subheading">
|
||||
<span id="version-label">Loading latest release…</span>
|
||||
<a id="changelog-link" class="changelog-link" href="#" target="_blank" rel="noopener noreferrer" style="display:none">View changelog<span aria-hidden="true"> ↗</span></a>
|
||||
</p>
|
||||
|
||||
<div class="platforms" id="platforms">
|
||||
<!-- macOS -->
|
||||
<section class="platform-section">
|
||||
<div class="platform-header">
|
||||
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
|
||||
<h2 class="platform-name">macOS</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="arm64.dmg" href="#">
|
||||
<span class="card-arch">Apple Silicon (arm64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
<a class="download-card" data-asset="x64.dmg" href="#">
|
||||
<span class="card-arch">Intel (x64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Windows -->
|
||||
<section class="platform-section">
|
||||
<div class="platform-header">
|
||||
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
|
||||
<h2 class="platform-name">Windows</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x64.exe" href="#">
|
||||
<span class="card-arch">Windows 10, 11</span>
|
||||
<span class="card-format">.exe</span>
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Linux -->
|
||||
<section class="platform-section">
|
||||
<div class="platform-header">
|
||||
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
|
||||
<h2 class="platform-name">Linux</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href="#">
|
||||
<span class="card-arch">x86_64</span>
|
||||
<span class="card-format">AppImage</span>
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<p class="releases-link">
|
||||
Looking for older versions? Check the
|
||||
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
|
||||
GitHub releases page<span aria-hidden="true"> ↗</span>
|
||||
</a>
|
||||
</p>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
import { fetchLatestRelease, RELEASES_URL } from "../lib/releases";
|
||||
|
||||
async function init() {
|
||||
const versionLabel = document.getElementById("version-label");
|
||||
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
|
||||
|
||||
try {
|
||||
const release = await fetchLatestRelease();
|
||||
|
||||
if (versionLabel && release.tag_name) {
|
||||
versionLabel.textContent = `Latest (${release.tag_name})`;
|
||||
}
|
||||
|
||||
const changelogLink = document.getElementById("changelog-link") as HTMLAnchorElement | null;
|
||||
if (changelogLink && release.html_url) {
|
||||
changelogLink.href = release.html_url;
|
||||
changelogLink.style.display = "";
|
||||
}
|
||||
|
||||
cards.forEach((card) => {
|
||||
const suffix = card.dataset.asset;
|
||||
if (!suffix) return;
|
||||
|
||||
const match = (release.assets ?? []).find((a) => a.name.endsWith(`-${suffix}`));
|
||||
if (match) {
|
||||
card.href = match.browser_download_url;
|
||||
} else {
|
||||
card.href = RELEASES_URL;
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
if (versionLabel) {
|
||||
versionLabel.textContent = "Could not load release info.";
|
||||
}
|
||||
cards.forEach((card) => {
|
||||
card.href = RELEASES_URL;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.main {
|
||||
padding: 8vh 1.5rem 4rem;
|
||||
}
|
||||
|
||||
/* ── Heading ── */
|
||||
|
||||
.heading {
|
||||
font-weight: 500;
|
||||
font-size: clamp(1.75rem, 4vw, 2.75rem);
|
||||
letter-spacing: -0.035em;
|
||||
line-height: 1.15;
|
||||
text-align: center;
|
||||
margin-bottom: 0.5rem;
|
||||
opacity: 0;
|
||||
animation: fade-in 1s ease-out forwards;
|
||||
}
|
||||
|
||||
.subheading {
|
||||
font-size: 0.9rem;
|
||||
color: var(--fg-dim);
|
||||
margin-bottom: 3.5rem;
|
||||
opacity: 0;
|
||||
animation: fade-in 1s ease-out 0.1s forwards;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.changelog-link {
|
||||
color: var(--fg-muted);
|
||||
font-size: 0.8rem;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: rgba(161, 161, 170, 0.4);
|
||||
text-underline-offset: 3px;
|
||||
transition: color 0.3s ease, text-decoration-color 0.3s ease;
|
||||
}
|
||||
|
||||
.changelog-link:hover {
|
||||
color: var(--fg);
|
||||
text-decoration-color: var(--fg);
|
||||
}
|
||||
|
||||
/* ── Platforms ── */
|
||||
|
||||
.platforms {
|
||||
width: 100%;
|
||||
max-width: 720px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2.5rem;
|
||||
opacity: 0;
|
||||
animation: fade-in 1s ease-out 0.2s forwards;
|
||||
}
|
||||
|
||||
.platform-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.platform-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.platform-icon {
|
||||
width: 1.15em;
|
||||
height: 1.15em;
|
||||
color: var(--fg-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.platform-name {
|
||||
font-weight: 500;
|
||||
font-size: 1.1rem;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
/* ── Download cards ── */
|
||||
|
||||
.download-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.download-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--border);
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
transition: background 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.download-card:hover {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border-color: rgba(255, 255, 255, 0.15);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.download-card:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.card-arch {
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.card-format {
|
||||
font-size: 0.8rem;
|
||||
color: var(--fg-dim);
|
||||
}
|
||||
|
||||
/* ── Releases link ── */
|
||||
|
||||
.releases-link {
|
||||
margin-top: 3rem;
|
||||
font-size: 0.825rem;
|
||||
color: var(--fg-dim);
|
||||
opacity: 0;
|
||||
animation: fade-in 1s ease-out 0.35s forwards;
|
||||
}
|
||||
|
||||
.releases-link a {
|
||||
color: var(--fg-muted);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: rgba(161, 161, 170, 0.4);
|
||||
text-underline-offset: 3px;
|
||||
transition: color 0.3s ease, text-decoration-color 0.3s ease;
|
||||
}
|
||||
|
||||
.releases-link a:hover {
|
||||
color: var(--fg);
|
||||
text-decoration-color: var(--fg);
|
||||
}
|
||||
|
||||
/* ── Mobile ── */
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.main {
|
||||
padding: 5vh 1.25rem 4rem;
|
||||
}
|
||||
|
||||
.platforms {
|
||||
padding: 0 0.25rem;
|
||||
}
|
||||
|
||||
.download-cards {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,237 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
|
||||
|
||||
<a
|
||||
id="download-btn"
|
||||
href="https://github.com/pingdotgg/t3code/releases"
|
||||
class="hero-button"
|
||||
>
|
||||
<svg class="hero-button-icon hero-button-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
|
||||
<svg class="hero-button-icon hero-button-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
|
||||
<svg class="hero-button-icon hero-button-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
|
||||
<span id="download-label">Download now</span>
|
||||
</a>
|
||||
|
||||
<a href="/download" class="other-platforms">Other platforms</a>
|
||||
|
||||
<div class="screenshot-wrap">
|
||||
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
|
||||
</div>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
import { fetchLatestRelease, RELEASES_URL, type ReleaseAsset } from "../lib/releases";
|
||||
|
||||
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
|
||||
|
||||
function detectPlatform(): Platform | null {
|
||||
const ua = navigator.userAgent;
|
||||
if (/Win/i.test(ua)) return { os: "win", label: "Download for Windows" };
|
||||
if (/Mac/i.test(ua)) {
|
||||
return {
|
||||
os: "mac",
|
||||
label: `Download for macOS`,
|
||||
arch: "arm64",
|
||||
};
|
||||
}
|
||||
if (/Linux/i.test(ua)) return { os: "linux", label: "Download for Linux" };
|
||||
return null;
|
||||
}
|
||||
|
||||
function pickAsset(assets: ReleaseAsset[], platform: Platform): string | null {
|
||||
if (platform.os === "win") {
|
||||
return (
|
||||
assets.find((a) => a.name.endsWith("-x64.exe"))
|
||||
?.browser_download_url ?? null
|
||||
);
|
||||
}
|
||||
if (platform.os === "mac") {
|
||||
const preferred = assets.find((a) =>
|
||||
a.name.endsWith(`-${platform.arch}.dmg`),
|
||||
);
|
||||
const fallback = assets.find((a) => a.name.endsWith(".dmg"));
|
||||
return (preferred ?? fallback)?.browser_download_url ?? null;
|
||||
}
|
||||
if (platform.os === "linux") {
|
||||
return (
|
||||
assets.find((a) => a.name.endsWith(".AppImage"))
|
||||
?.browser_download_url ?? null
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function init() {
|
||||
const btn = document.getElementById("download-btn") as HTMLAnchorElement | null;
|
||||
const label = document.getElementById("download-label");
|
||||
if (!btn || !label) return;
|
||||
|
||||
const platform = detectPlatform();
|
||||
if (!platform) return;
|
||||
|
||||
document.documentElement.dataset.platform = platform.os;
|
||||
label.textContent = platform.label;
|
||||
|
||||
try {
|
||||
const release = await fetchLatestRelease();
|
||||
const url = pickAsset(release.assets ?? [], platform);
|
||||
if (url) {
|
||||
btn.href = url;
|
||||
btn.removeAttribute("target");
|
||||
btn.removeAttribute("rel");
|
||||
}
|
||||
} catch {
|
||||
btn.href = RELEASES_URL;
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.main {
|
||||
padding-top: 10vh;
|
||||
}
|
||||
|
||||
/* ── Tagline ── */
|
||||
|
||||
.tagline {
|
||||
font-weight: 500;
|
||||
font-size: clamp(2rem, 5vw, 3.5rem);
|
||||
letter-spacing: -0.035em;
|
||||
line-height: 1.15;
|
||||
text-align: center;
|
||||
margin: 0 0 6vh;
|
||||
opacity: 0;
|
||||
animation: fade-in 1s ease-out forwards;
|
||||
}
|
||||
|
||||
/* ── Hero button ── */
|
||||
|
||||
.hero-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
background: #fafafa;
|
||||
color: #09090b;
|
||||
padding: 0.75rem 2rem;
|
||||
border-radius: 999px;
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 1.25rem;
|
||||
opacity: 0;
|
||||
animation: fade-in 1s ease-out 0.15s forwards;
|
||||
transition: transform 0.25s ease, box-shadow 0.25s ease;
|
||||
}
|
||||
|
||||
.hero-button:hover {
|
||||
transform: scale(1.03);
|
||||
box-shadow: 0 0 24px rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.hero-button:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.hero-button-icon {
|
||||
display: none;
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:global([data-platform="mac"]) .hero-button-icon--apple {
|
||||
display: block;
|
||||
}
|
||||
|
||||
:global([data-platform="win"]) .hero-button-icon--windows {
|
||||
display: block;
|
||||
}
|
||||
|
||||
:global([data-platform="linux"]) .hero-button-icon--linux {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* ── Other platforms link ── */
|
||||
|
||||
.other-platforms {
|
||||
font-size: 0.825rem;
|
||||
color: var(--fg-dim);
|
||||
margin-bottom: 5vh;
|
||||
opacity: 0;
|
||||
animation: fade-in 1s ease-out 0.3s forwards;
|
||||
transition: color 0.3s ease;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: rgba(113, 113, 122, 0.4);
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.other-platforms:hover {
|
||||
color: var(--fg-muted);
|
||||
text-decoration-color: var(--fg-muted);
|
||||
}
|
||||
|
||||
/* ── Screenshot ── */
|
||||
|
||||
.screenshot-wrap {
|
||||
margin: 0 auto;
|
||||
width: min(95vw, 1400px);
|
||||
opacity: 0;
|
||||
transform: scale(0.98);
|
||||
animation: screenshot-in 1s ease-out 0.15s forwards;
|
||||
}
|
||||
|
||||
.screenshot {
|
||||
width: 100%;
|
||||
display: block;
|
||||
border-radius: 16px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
|
||||
-webkit-mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
|
||||
}
|
||||
|
||||
.screenshot-wrap::after {
|
||||
content: "";
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 120px;
|
||||
background: inherit;
|
||||
margin-top: -1px;
|
||||
opacity: 0.04;
|
||||
transform: scaleY(-1);
|
||||
mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
|
||||
-webkit-mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@keyframes screenshot-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.98);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Mobile ── */
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.main {
|
||||
padding-top: 7vh;
|
||||
}
|
||||
|
||||
.tagline {
|
||||
margin-bottom: 4vh;
|
||||
}
|
||||
|
||||
.screenshot-wrap {
|
||||
width: 95vw;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "astro/tsconfigs/strict"
|
||||
}
|
||||
@@ -1,20 +1,21 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
ProviderKind,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Option,
|
||||
Path,
|
||||
Ref,
|
||||
Schedule,
|
||||
Schema,
|
||||
Scope,
|
||||
@@ -23,6 +24,9 @@ import {
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||
@@ -34,12 +38,17 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
|
||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||
@@ -49,11 +58,18 @@ import {
|
||||
} from "../src/orchestration/Services/OrchestrationEngine.ts";
|
||||
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
RuntimeReceiptBus,
|
||||
type OrchestrationRuntimeReceipt,
|
||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
|
||||
import {
|
||||
makeTestProviderAdapterHarness,
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -63,14 +79,16 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
});
|
||||
}
|
||||
|
||||
function initializeGitWorkspace(cwd: string) {
|
||||
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
|
||||
runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { join } = yield* Path.Path;
|
||||
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
|
||||
runGit(cwd, ["add", "."]);
|
||||
runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
}
|
||||
});
|
||||
|
||||
export function gitRefExists(cwd: string, ref: string): boolean {
|
||||
try {
|
||||
@@ -108,7 +126,7 @@ function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 3000,
|
||||
timeoutMs = 40_000,
|
||||
): Effect.Effect<A, never> {
|
||||
const RETRY_SIGNAL = "wait_for_retry";
|
||||
const retryIntervalMs = 10;
|
||||
@@ -147,7 +165,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly rootDir: string;
|
||||
readonly workspaceDir: string;
|
||||
readonly dbPath: string;
|
||||
readonly adapterHarness: TestProviderAdapterHarness;
|
||||
readonly adapterHarness: TestProviderAdapterHarness | null;
|
||||
readonly engine: OrchestrationEngineShape;
|
||||
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
|
||||
readonly providerService: ProviderService["Service"];
|
||||
@@ -179,222 +197,320 @@ export interface OrchestrationIntegrationHarness {
|
||||
},
|
||||
never
|
||||
>;
|
||||
readonly waitForReceipt: {
|
||||
(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
|
||||
<Receipt extends OrchestrationRuntimeReceipt>(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt, never>;
|
||||
};
|
||||
readonly dispose: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
const adapterHarness = yield* makeTestProviderAdapterHarness;
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
const stateDir = path.join(rootDir, "state");
|
||||
const dbPath = path.join(stateDir, "state.sqlite");
|
||||
fs.mkdirSync(workspaceDir, { recursive: true });
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
initializeGitWorkspace(workspaceDir);
|
||||
export const makeOrchestrationIntegrationHarness = (
|
||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
const provider = options?.provider ?? "codex";
|
||||
const useRealCodex = options?.realCodex === true;
|
||||
const adapterHarness = useRealCodex
|
||||
? null
|
||||
: yield* makeTestProviderAdapterHarness({
|
||||
provider,
|
||||
});
|
||||
const fakeRegistry = adapterHarness
|
||||
? Layer.succeed(ProviderAdapterRegistry, {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === adapterHarness.provider
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service)
|
||||
: null;
|
||||
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-orchestration-integration-",
|
||||
});
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
|
||||
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
|
||||
yield* initializeGitWorkspace(workspaceDir);
|
||||
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
);
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexAdapter = yield* CodexAdapter;
|
||||
return {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === "codex"
|
||||
? Effect.succeed(codexAdapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed(["codex"] as const),
|
||||
} as typeof ProviderAdapterRegistry.Service;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(makeCodexAdapterLive()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
const providerLayer = useRealCodex
|
||||
? makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(realCodexRegistry),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
)
|
||||
: makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(fakeRegistry!),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
CheckpointStoreLive,
|
||||
providerLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
).pipe(Effect.orDie);
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionPendingApprovalRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
yield* sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
snapshotQuery
|
||||
.getSnapshot()
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
|
||||
),
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||
Effect.succeed({ branch: input.newBranch }),
|
||||
} as unknown as GitCoreShape);
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
|
||||
),
|
||||
(events) => events.some(predicate),
|
||||
"domain event",
|
||||
timeoutMs,
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
|
||||
requestId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
onNone: () => null,
|
||||
onSome: (value) => ({
|
||||
status: value.status,
|
||||
decision: value.decision,
|
||||
resolvedAt: value.resolvedAt,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
(
|
||||
row,
|
||||
): row is {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
).pipe(Effect.orDie);
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionPendingApprovalRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const runtimeReceiptBus = yield* tryRuntimePromise("load RuntimeReceiptBus service", () =>
|
||||
runtime.runPromise(Effect.service(RuntimeReceiptBus)),
|
||||
).pipe(Effect.orDie);
|
||||
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
||||
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* Effect.sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
) =>
|
||||
waitFor(
|
||||
snapshotQuery
|
||||
.getSnapshot()
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
|
||||
),
|
||||
),
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
|
||||
let disposed = false;
|
||||
const dispose = Effect.gen(function* () {
|
||||
if (disposed) {
|
||||
return;
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
|
||||
),
|
||||
(events) => events.some(predicate),
|
||||
"domain event",
|
||||
timeoutMs,
|
||||
);
|
||||
|
||||
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
|
||||
requestId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
onNone: () => null,
|
||||
onSome: (value) => ({
|
||||
status: value.status,
|
||||
decision: value.decision,
|
||||
resolvedAt: value.resolvedAt,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
(
|
||||
row,
|
||||
): row is {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
|
||||
function waitForReceipt(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
|
||||
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt, never>;
|
||||
function waitForReceipt(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
) {
|
||||
const readMatchingReceipt = Ref.get(receiptHistory).pipe(
|
||||
Effect.map((history) => history.find(predicate)),
|
||||
);
|
||||
|
||||
return waitFor(
|
||||
readMatchingReceipt,
|
||||
(receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
|
||||
"runtime receipt",
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
disposed = true;
|
||||
|
||||
const shutdown = Effect.gen(function* () {
|
||||
const stopAllExit = yield* Effect.exit(
|
||||
Effect.promise(() => runtime.runPromise(providerService.stopAll())),
|
||||
);
|
||||
const closeScopeExit = yield* Effect.exit(
|
||||
Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void))),
|
||||
);
|
||||
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
|
||||
let disposed = false;
|
||||
const dispose = Effect.gen(function* () {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
|
||||
const failureCause = Exit.isFailure(stopAllExit)
|
||||
? stopAllExit.cause
|
||||
: Exit.isFailure(closeScopeExit)
|
||||
const shutdown = Effect.gen(function* () {
|
||||
const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
|
||||
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
|
||||
|
||||
const failureCause = Exit.isFailure(closeScopeExit)
|
||||
? closeScopeExit.cause
|
||||
: Exit.isFailure(disposeRuntimeExit)
|
||||
? disposeRuntimeExit.cause
|
||||
: null;
|
||||
|
||||
if (failureCause) {
|
||||
return yield* Effect.failCause(failureCause);
|
||||
}
|
||||
if (failureCause) {
|
||||
return yield* Effect.failCause(failureCause);
|
||||
}
|
||||
});
|
||||
|
||||
yield* shutdown;
|
||||
});
|
||||
|
||||
yield* shutdown.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
checkpointStore,
|
||||
checkpointRepository,
|
||||
pendingApprovalRepository,
|
||||
waitForThread,
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
waitForReceipt,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
|
||||
return {
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
checkpointStore,
|
||||
checkpointRepository,
|
||||
pendingApprovalRepository,
|
||||
waitForThread,
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
@@ -5,11 +5,12 @@ import {
|
||||
EventId,
|
||||
ProviderApprovalDecision,
|
||||
ProviderRuntimeEvent,
|
||||
RuntimeSessionId,
|
||||
ProviderSession,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
@@ -25,13 +26,29 @@ import type {
|
||||
} from "../src/provider/Services/ProviderAdapter.ts";
|
||||
|
||||
export interface TestTurnResponse {
|
||||
readonly events: ReadonlyArray<ProviderRuntimeEvent>;
|
||||
readonly events: ReadonlyArray<FixtureProviderRuntimeEvent>;
|
||||
readonly mutateWorkspace?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly turnCount: number;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
readonly itemId?: string | undefined;
|
||||
readonly requestId?: string | undefined;
|
||||
readonly payload?: unknown | undefined;
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
// Temporary alias while fixtures migrate to the new name.
|
||||
export type LegacyProviderRuntimeEvent = FixtureProviderRuntimeEvent;
|
||||
|
||||
interface SessionState {
|
||||
readonly session: ProviderSession;
|
||||
snapshot: ProviderThreadSnapshot;
|
||||
@@ -40,329 +57,505 @@ interface SessionState {
|
||||
readonly rollbackCalls: Array<number>;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupted" | "cancelled" {
|
||||
if (
|
||||
value === "completed" ||
|
||||
value === "failed" ||
|
||||
value === "interrupted" ||
|
||||
value === "cancelled"
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return "completed";
|
||||
}
|
||||
|
||||
function mapRequestType(
|
||||
requestKind: unknown,
|
||||
): "command_execution_approval" | "file_change_approval" | "unknown" {
|
||||
if (requestKind === "command") {
|
||||
return "command_execution_approval";
|
||||
}
|
||||
if (requestKind === "file-change") {
|
||||
return "file_change_approval";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function mapItemType(toolKind: unknown): "command_execution" | "file_change" | "unknown" {
|
||||
if (toolKind === "command") {
|
||||
return "command_execution";
|
||||
}
|
||||
if (toolKind === "file-change") {
|
||||
return "file_change";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRuntimeEvent {
|
||||
const type = typeof rawEvent.type === "string" ? rawEvent.type : "";
|
||||
switch (type) {
|
||||
case "turn.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.started",
|
||||
payload: isRecord(rawEvent.payload) ? rawEvent.payload : {},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "turn.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.completed",
|
||||
payload: isRecord(rawEvent.payload)
|
||||
? rawEvent.payload
|
||||
: {
|
||||
state: normalizeTurnState(rawEvent.status),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.delta":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: typeof rawEvent.delta === "string" ? rawEvent.delta : "",
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.started",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
status: "completed",
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.requested":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.opened",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.resolved":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.resolved",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.decision === "string" ? { decision: rawEvent.decision } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
default:
|
||||
return rawEvent as ProviderRuntimeEvent;
|
||||
}
|
||||
}
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: ProviderKind;
|
||||
readonly queueTurnResponse: (
|
||||
sessionId: string,
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
|
||||
readonly queueTurnResponseForNextSession: (
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, never>;
|
||||
readonly getRollbackCalls: (sessionId: string) => ReadonlyArray<number>;
|
||||
readonly getApprovalResponses: (sessionId: string) => ReadonlyArray<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly getStartCount: () => number;
|
||||
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
|
||||
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
|
||||
readonly listActiveSessionIds: () => ReadonlyArray<ThreadId>;
|
||||
readonly getApprovalResponses: (threadId: ThreadId) => ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>;
|
||||
}
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: ProviderKind;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function sessionNotFound(sessionId: string): ProviderAdapterSessionNotFoundError {
|
||||
function sessionNotFound(
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider: PROVIDER,
|
||||
sessionId,
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
});
|
||||
}
|
||||
|
||||
function missingSessionEffect(sessionId: string): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(sessionId));
|
||||
function missingSessionEffect(
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
}
|
||||
|
||||
export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<string, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const approvalResponsesBySession = new Map<
|
||||
string,
|
||||
Array<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>
|
||||
>();
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = options?.provider ?? "codex";
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<ThreadId, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const interruptCallsBySession = new Map<ThreadId, Array<TurnId | undefined>>();
|
||||
const approvalResponsesBySession = new Map<
|
||||
ThreadId,
|
||||
Array<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>
|
||||
>();
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
|
||||
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== provider) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
sessionCount += 1;
|
||||
const sessionId = ProviderSessionId.makeUnsafe(`test-session-${sessionCount}`);
|
||||
const threadId = ProviderThreadId.makeUnsafe(`test-thread-${sessionCount}`);
|
||||
const createdAt = nowIso();
|
||||
sessionCount += 1;
|
||||
const threadId = input.threadId;
|
||||
const createdAt = nowIso();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: PROVIDER,
|
||||
status: "ready",
|
||||
threadId,
|
||||
cwd: input.cwd,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(sessionId, {
|
||||
session,
|
||||
snapshot: {
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId,
|
||||
turns: [],
|
||||
},
|
||||
turnCount: 0,
|
||||
queuedResponses: queuedResponsesForNextSession.splice(0),
|
||||
rollbackCalls: [],
|
||||
cwd: input.cwd,
|
||||
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(threadId, {
|
||||
session,
|
||||
snapshot: {
|
||||
threadId,
|
||||
turns: [],
|
||||
},
|
||||
turnCount: 0,
|
||||
queuedResponses: queuedResponsesForNextSession.splice(0),
|
||||
rollbackCalls: [],
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(input.threadId);
|
||||
if (!state) {
|
||||
return yield* missingSessionEffect(provider, input.threadId);
|
||||
}
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(input.sessionId);
|
||||
if (!state) {
|
||||
return yield* missingSessionEffect(input.sessionId);
|
||||
}
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = ProviderTurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "sendTurn",
|
||||
issue: `No queued turn response for thread ${input.threadId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: `No queued turn response for session ${input.sessionId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const assistantDeltas: string[] = [];
|
||||
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
|
||||
for (const fixtureEvent of response.events) {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider: PROVIDER,
|
||||
sessionId: input.sessionId,
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
if (Object.hasOwn(rawEvent, "threadId")) {
|
||||
const assistantDeltas: string[] = [];
|
||||
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
|
||||
for (const fixtureEvent of response.events) {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
}
|
||||
if (Object.hasOwn(rawEvent, "turnId")) {
|
||||
rawEvent.turnId = turnId;
|
||||
if (Object.hasOwn(rawEvent, "turnId")) {
|
||||
rawEvent.turnId = turnId;
|
||||
}
|
||||
|
||||
const runtimeEvent = normalizeFixtureEvent(rawEvent);
|
||||
const runtimeType = (runtimeEvent as { type: string }).type;
|
||||
if (runtimeType === "content.delta") {
|
||||
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
|
||||
if (typeof payload?.delta === "string") {
|
||||
assistantDeltas.push(payload.delta);
|
||||
}
|
||||
} else if (runtimeType === "message.delta") {
|
||||
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
|
||||
if (typeof legacyDelta === "string") {
|
||||
assistantDeltas.push(legacyDelta);
|
||||
}
|
||||
}
|
||||
if (runtimeEvent.type === "turn.completed") {
|
||||
deferredTurnCompletedEvents.push(runtimeEvent);
|
||||
continue;
|
||||
}
|
||||
|
||||
yield* emit(runtimeEvent);
|
||||
}
|
||||
|
||||
const runtimeEvent = rawEvent as ProviderRuntimeEvent;
|
||||
if (runtimeEvent.type === "message.delta") {
|
||||
assistantDeltas.push(runtimeEvent.delta);
|
||||
}
|
||||
if (runtimeEvent.type === "turn.completed") {
|
||||
deferredTurnCompletedEvents.push(runtimeEvent);
|
||||
continue;
|
||||
if (response.mutateWorkspace && state.session.cwd) {
|
||||
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
|
||||
}
|
||||
|
||||
yield* emit(runtimeEvent);
|
||||
}
|
||||
const userItem = {
|
||||
type: "userMessage",
|
||||
content: [{ type: "text", text: input.input }],
|
||||
} as const;
|
||||
const assistantText = assistantDeltas.join("");
|
||||
const nextItems: Array<unknown> =
|
||||
assistantText.length > 0
|
||||
? [userItem, { type: "agentMessage", text: assistantText }]
|
||||
: [userItem];
|
||||
|
||||
if (response.mutateWorkspace && state.session.cwd) {
|
||||
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
|
||||
}
|
||||
const nextTurn: ProviderThreadTurnSnapshot = {
|
||||
id: turnId,
|
||||
items: nextItems,
|
||||
};
|
||||
|
||||
const userItem = {
|
||||
type: "userMessage",
|
||||
content: [{ type: "text", text: input.input }],
|
||||
} as const;
|
||||
const assistantText = assistantDeltas.join("");
|
||||
const nextItems: Array<unknown> =
|
||||
assistantText.length > 0
|
||||
? [userItem, { type: "agentMessage", text: assistantText }]
|
||||
: [userItem];
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: [...state.snapshot.turns, nextTurn],
|
||||
};
|
||||
|
||||
const nextTurn: ProviderThreadTurnSnapshot = {
|
||||
id: turnId,
|
||||
items: nextItems,
|
||||
};
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
for (const completedEvent of deferredTurnCompletedEvents) {
|
||||
yield* emit(completedEvent);
|
||||
}
|
||||
}
|
||||
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: [...state.snapshot.turns, nextTurn],
|
||||
};
|
||||
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
provider: PROVIDER,
|
||||
sessionId: input.sessionId,
|
||||
createdAt: nowIso(),
|
||||
return {
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
status: "completed",
|
||||
});
|
||||
} else {
|
||||
for (const completedEvent of deferredTurnCompletedEvents) {
|
||||
yield* emit(completedEvent);
|
||||
}
|
||||
} satisfies ProviderTurnStartResult;
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
threadId,
|
||||
turnId,
|
||||
) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.sync(() => {
|
||||
const existing = interruptCallsBySession.get(threadId) ?? [];
|
||||
existing.push(turnId);
|
||||
interruptCallsBySession.set(threadId, existing);
|
||||
})
|
||||
: missingSessionEffect(provider, threadId);
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.sync(() => {
|
||||
const existing = approvalResponsesBySession.get(threadId) ?? [];
|
||||
existing.push({
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
});
|
||||
approvalResponsesBySession.set(threadId, existing);
|
||||
})
|
||||
: missingSessionEffect(provider, threadId);
|
||||
|
||||
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
|
||||
threadId,
|
||||
_requestId,
|
||||
_answers,
|
||||
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
|
||||
Effect.sync(() => {
|
||||
sessions.delete(threadId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
|
||||
Effect.succeed(sessions.has(threadId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(provider, threadId);
|
||||
}
|
||||
return Effect.succeed(state.snapshot);
|
||||
};
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
threadId,
|
||||
numTurns,
|
||||
) => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(provider, threadId);
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer between 0 and current turn count.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
} satisfies ProviderTurnStartResult;
|
||||
});
|
||||
return Effect.sync(() => {
|
||||
state.rollbackCalls.push(numTurns);
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
|
||||
};
|
||||
state.turnCount = state.snapshot.turns.length;
|
||||
return state.snapshot;
|
||||
});
|
||||
};
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
sessionId,
|
||||
_turnId,
|
||||
) => (sessions.has(sessionId) ? Effect.void : missingSessionEffect(sessionId));
|
||||
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
|
||||
Effect.sync(() => {
|
||||
sessions.clear();
|
||||
});
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
sessions.has(sessionId)
|
||||
? Effect.sync(() => {
|
||||
const existing = approvalResponsesBySession.get(sessionId) ?? [];
|
||||
existing.push({
|
||||
sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
});
|
||||
approvalResponsesBySession.set(sessionId, existing);
|
||||
})
|
||||
: missingSessionEffect(sessionId);
|
||||
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
|
||||
provider,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
};
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (sessionId) =>
|
||||
Effect.sync(() => {
|
||||
sessions.delete(sessionId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (sessionId) =>
|
||||
Effect.succeed(sessions.has(sessionId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (sessionId) => {
|
||||
const state = sessions.get(sessionId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(sessionId);
|
||||
}
|
||||
return Effect.succeed(state.snapshot);
|
||||
};
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
sessionId,
|
||||
numTurns,
|
||||
) => {
|
||||
const state = sessions.get(sessionId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(sessionId);
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer between 0 and current turn count.",
|
||||
}),
|
||||
const queueTurnResponse = (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
|
||||
Effect.sync(() => sessions.get(threadId)).pipe(
|
||||
Effect.flatMap((state) =>
|
||||
state
|
||||
? Effect.sync(() => {
|
||||
state.queuedResponses.push(response);
|
||||
})
|
||||
: Effect.fail(sessionNotFound(provider, threadId)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.sync(() => {
|
||||
state.rollbackCalls.push(numTurns);
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
|
||||
};
|
||||
state.turnCount = state.snapshot.turns.length;
|
||||
return state.snapshot;
|
||||
});
|
||||
};
|
||||
const queueTurnResponseForNextSession = (
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, never> =>
|
||||
Effect.sync(() => {
|
||||
queuedResponsesForNextSession.push(response);
|
||||
});
|
||||
|
||||
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
|
||||
Effect.sync(() => {
|
||||
sessions.clear();
|
||||
});
|
||||
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return [];
|
||||
}
|
||||
return [...state.rollbackCalls];
|
||||
};
|
||||
|
||||
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
|
||||
provider: PROVIDER,
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
};
|
||||
const getStartCount = (): number => sessionCount;
|
||||
|
||||
const queueTurnResponse = (
|
||||
sessionId: string,
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
|
||||
Effect.sync(() => sessions.get(sessionId)).pipe(
|
||||
Effect.flatMap((state) =>
|
||||
state
|
||||
? Effect.sync(() => {
|
||||
state.queuedResponses.push(response);
|
||||
})
|
||||
: Effect.fail(sessionNotFound(sessionId)),
|
||||
),
|
||||
);
|
||||
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
|
||||
const calls = interruptCallsBySession.get(threadId);
|
||||
if (!calls) {
|
||||
return [];
|
||||
}
|
||||
return [...calls];
|
||||
};
|
||||
|
||||
const queueTurnResponseForNextSession = (
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, never> =>
|
||||
Effect.sync(() => {
|
||||
queuedResponsesForNextSession.push(response);
|
||||
});
|
||||
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
|
||||
Array.from(sessions.values(), (state) => state.session.threadId);
|
||||
|
||||
const getRollbackCalls = (sessionId: string): ReadonlyArray<number> => {
|
||||
const state = sessions.get(sessionId);
|
||||
if (!state) {
|
||||
return [];
|
||||
}
|
||||
return [...state.rollbackCalls];
|
||||
};
|
||||
const getApprovalResponses = (
|
||||
threadId: ThreadId,
|
||||
): ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}> => {
|
||||
const responses = approvalResponsesBySession.get(threadId);
|
||||
if (!responses) {
|
||||
return [];
|
||||
}
|
||||
return [...responses];
|
||||
};
|
||||
|
||||
const getApprovalResponses = (
|
||||
sessionId: string,
|
||||
): ReadonlyArray<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}> => {
|
||||
const responses = approvalResponsesBySession.get(sessionId);
|
||||
if (!responses) {
|
||||
return [];
|
||||
}
|
||||
return [...responses];
|
||||
};
|
||||
|
||||
return {
|
||||
adapter,
|
||||
queueTurnResponse,
|
||||
queueTurnResponseForNextSession,
|
||||
getRollbackCalls,
|
||||
getApprovalResponses,
|
||||
} satisfies TestProviderAdapterHarness;
|
||||
});
|
||||
return {
|
||||
adapter,
|
||||
provider,
|
||||
queueTurnResponse,
|
||||
queueTurnResponseForNextSession,
|
||||
getStartCount,
|
||||
getRollbackCalls,
|
||||
getInterruptCalls,
|
||||
listActiveSessionIds,
|
||||
getApprovalResponses,
|
||||
} satisfies TestProviderAdapterHarness;
|
||||
});
|
||||
@@ -1,22 +1,16 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = ProviderSessionId.makeUnsafe("fixture-session");
|
||||
const THREAD_ID = ProviderThreadId.makeUnsafe("fixture-thread");
|
||||
const TURN_ID = ProviderTurnId.makeUnsafe("fixture-turn");
|
||||
const REQUEST_ID = ApprovalRequestId.makeUnsafe("req-1");
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<ProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.makeUnsafe(eventId),
|
||||
provider: PROVIDER,
|
||||
@@ -31,29 +25,38 @@ export const codexTurnTextFixture = [
|
||||
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "I will make a small update.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "I will make a small update.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Done.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Done.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnToolFixture = [
|
||||
{
|
||||
@@ -61,40 +64,51 @@ export const codexTurnToolFixture = [
|
||||
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
type: "item.started",
|
||||
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
title: "Ran command",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
type: "item.completed",
|
||||
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Applied the requested edit.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Applied the requested edit.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnApprovalFixture = [
|
||||
{
|
||||
@@ -102,37 +116,47 @@ export const codexTurnApprovalFixture = [
|
||||
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
type: "request.opened",
|
||||
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Please approve command",
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "Please approve command",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "approval.resolved",
|
||||
type: "request.resolved",
|
||||
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
requestKind: "command",
|
||||
decision: "accept",
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
decision: "accept",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Approval received and command executed.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Approval received and command executed.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ProviderRuntimeEvent, ProviderSessionId } from "@t3tools/contracts";
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
||||
@@ -12,6 +13,8 @@ import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../src/provider/Services/ProviderService.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||
|
||||
@@ -42,7 +45,7 @@ interface IntegrationFixture {
|
||||
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness;
|
||||
const harness = yield* makeTestProviderAdapterHarness();
|
||||
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
@@ -59,6 +62,8 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
AnalyticsService.layerTest,
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
@@ -93,18 +98,18 @@ const collectEventsDuring = <A, E, R>(
|
||||
const runTurn = (input: {
|
||||
readonly provider: ProviderServiceShape;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly userText: string;
|
||||
readonly response: TestTurnResponse;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.sessionId, input.response);
|
||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
input.provider.sendTurn({
|
||||
sessionId: input.sessionId,
|
||||
threadId: input.threadId,
|
||||
input: input.userText,
|
||||
attachments: [],
|
||||
}),
|
||||
@@ -120,8 +125,10 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -129,7 +136,7 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "hello",
|
||||
response: { events: codexTurnTextFixture },
|
||||
});
|
||||
@@ -153,8 +160,10 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -162,7 +171,7 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "make a small change",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
@@ -190,8 +199,10 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -199,7 +210,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
@@ -215,7 +226,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
const secondTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
@@ -242,8 +253,10 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -251,7 +264,7 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
@@ -263,7 +276,7 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
@@ -273,11 +286,11 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
});
|
||||
|
||||
yield* provider.rollbackConversation({
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
numTurns: 1,
|
||||
});
|
||||
|
||||
const rollbackCalls = fixture.harness.getRollbackCalls(session.sessionId);
|
||||
const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId);
|
||||
assert.deepEqual(rollbackCalls, [1]);
|
||||
|
||||
const readme = yield* readFileString(join(fixture.cwd, "README.md"));
|
||||
|
||||
@@ -1,41 +1,50 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.1.0",
|
||||
"version": "0.0.15",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
"directory": "apps/server"
|
||||
},
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
"t3": "./dist/bin.mjs"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.mjs",
|
||||
"scripts": {
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
|
||||
"build": "tsdown && node scripts/bundle-client.ts",
|
||||
"start": "node dist/index.mjs",
|
||||
"dev": "bun run src/bin.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
"open": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.16 || ^23.11 || >=24.10"
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* Copies the built web app into dist/client/ so the published npm package
|
||||
* includes the web UI. This runs as a post-build step.
|
||||
*/
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
|
||||
const target = path.resolve(import.meta.dirname, "../dist/client");
|
||||
|
||||
if (!fs.existsSync(webDist)) {
|
||||
console.log(
|
||||
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.cpSync(webDist, target, { recursive: true });
|
||||
console.log("✓ Bundled web app into dist/client");
|
||||
@@ -0,0 +1,266 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
DEVELOPMENT_ICON_OVERRIDES,
|
||||
PUBLISH_ICON_OVERRIDES,
|
||||
} from "../../../scripts/lib/brand-assets.ts";
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
|
||||
);
|
||||
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(command);
|
||||
const exitCode = yield* child.exitCode;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new CliError({
|
||||
message: `Command exited with non-zero exit code (${exitCode})`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
interface PublishIconBackup {
|
||||
readonly targetPath: string;
|
||||
readonly backupPath: string;
|
||||
}
|
||||
|
||||
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
|
||||
repoRoot: string,
|
||||
serverDir: string,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const backups: PublishIconBackup[] = [];
|
||||
|
||||
for (const override of PUBLISH_ICON_OVERRIDES) {
|
||||
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
|
||||
const targetPath = path.join(serverDir, override.targetRelativePath);
|
||||
const backupPath = `${targetPath}.publish-bak`;
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing publish icon source: ${sourcePath}`,
|
||||
});
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fs.copyFile(targetPath, backupPath);
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
backups.push({ targetPath, backupPath });
|
||||
}
|
||||
|
||||
yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
|
||||
return backups as ReadonlyArray<PublishIconBackup>;
|
||||
});
|
||||
|
||||
const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
|
||||
backups: ReadonlyArray<PublishIconBackup>,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
for (const backup of backups) {
|
||||
if (!(yield* fs.exists(backup.backupPath))) {
|
||||
continue;
|
||||
}
|
||||
yield* fs.rename(backup.backupPath, backup.targetPath);
|
||||
}
|
||||
});
|
||||
|
||||
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
|
||||
repoRoot: string,
|
||||
serverDir: string,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
for (const override of DEVELOPMENT_ICON_OVERRIDES) {
|
||||
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
|
||||
const targetPath = path.join(serverDir, override.targetRelativePath);
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing development icon source: ${sourcePath}`,
|
||||
});
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing development icon target: ${targetPath}. Build web first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
}
|
||||
|
||||
yield* Effect.log("[cli] Applied development icon overrides to dist/client");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// build subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const buildCmd = Command.make(
|
||||
"build",
|
||||
{
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
|
||||
shell: process.platform === "win32",
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
const clientTarget = path.join(serverDir, "dist/client");
|
||||
|
||||
if (yield* fs.exists(webDist)) {
|
||||
yield* fs.copy(webDist, clientTarget);
|
||||
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
|
||||
yield* Effect.log("[cli] Bundled web app into dist/client");
|
||||
} else {
|
||||
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||
}
|
||||
}),
|
||||
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// publish subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const publishCmd = Command.make(
|
||||
"publish",
|
||||
{
|
||||
tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
|
||||
access: Flag.string("access").pipe(Flag.withDefault("public")),
|
||||
appVersion: Flag.string("app-version").pipe(Flag.optional),
|
||||
provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
|
||||
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
// Resolve catalog dependencies before any file mutations. If this throws,
|
||||
// acquire fails and no release hook runs, so filesystem must still be untouched.
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
type: serverPackageJson.type,
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
};
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
}),
|
||||
// Use: npm publish
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["publish", "--access", config.access, "--tag", config.tag];
|
||||
if (config.provenance) args.push("--provenance");
|
||||
if (config.dryRun) args.push("--dry-run");
|
||||
|
||||
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
|
||||
yield* runCommand(
|
||||
ChildProcess.make("npm", [...args], {
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims.
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore
|
||||
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
|
||||
),
|
||||
);
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
).pipe(Command.withDescription("Publish the server package to npm."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// root command
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const cli = Command.make("cli").pipe(
|
||||
Command.withDescription("T3 server build & publish CLI."),
|
||||
Command.withSubcommands([buildCmd, publishCmd]),
|
||||
);
|
||||
|
||||
Command.run(cli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -0,0 +1,28 @@
|
||||
import path from "node:path";
|
||||
|
||||
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
||||
|
||||
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
|
||||
const normalized = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||
if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
|
||||
return null;
|
||||
}
|
||||
return normalized.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
export function resolveAttachmentRelativePath(input: {
|
||||
readonly attachmentsDir: string;
|
||||
readonly relativePath: string;
|
||||
}): string | null {
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
||||
if (!normalizedRelativePath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const attachmentsRoot = path.resolve(input.attachmentsDir);
|
||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||
return null;
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createAttachmentId,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
resolveAttachmentPathById,
|
||||
} from "./attachmentStore.ts";
|
||||
|
||||
describe("attachmentStore", () => {
|
||||
it("sanitizes thread ids when creating attachment ids", () => {
|
||||
const attachmentId = createAttachmentId("thread.folder/unsafe space");
|
||||
expect(attachmentId).toBeTruthy();
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||
expect(threadSegment).toBeTruthy();
|
||||
expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i);
|
||||
expect(threadSegment).not.toContain(".");
|
||||
expect(threadSegment).not.toContain("%");
|
||||
expect(threadSegment).not.toContain("/");
|
||||
});
|
||||
|
||||
it("parses exact thread segments from attachment ids without prefix collisions", () => {
|
||||
const fooId = "foo-00000000-0000-4000-8000-000000000001";
|
||||
const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002";
|
||||
|
||||
expect(parseThreadSegmentFromAttachmentId(fooId)).toBe("foo");
|
||||
expect(parseThreadSegmentFromAttachmentId(fooBarId)).toBe("foo-bar");
|
||||
});
|
||||
|
||||
it("normalizes created thread segments to lowercase", () => {
|
||||
const attachmentId = createAttachmentId("Thread.Foo");
|
||||
expect(attachmentId).toBeTruthy();
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
|
||||
});
|
||||
|
||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
try {
|
||||
const attachmentId = "thread-1-attachment";
|
||||
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
||||
|
||||
const resolved = resolveAttachmentPathById({
|
||||
attachmentsDir,
|
||||
attachmentId,
|
||||
});
|
||||
expect(resolved).toBe(pngPath);
|
||||
} finally {
|
||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns null when no attachment file exists for the id", () => {
|
||||
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
try {
|
||||
const resolved = resolveAttachmentPathById({
|
||||
attachmentsDir,
|
||||
attachmentId: "thread-1-missing",
|
||||
});
|
||||
expect(resolved).toBeNull();
|
||||
} finally {
|
||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths.ts";
|
||||
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
|
||||
|
||||
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
|
||||
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
const ATTACHMENT_ID_PATTERN = new RegExp(
|
||||
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
|
||||
"i",
|
||||
);
|
||||
|
||||
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||
const segment = threadId
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_-]+/gi, "-")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^[-_]+|[-_]+$/g, "")
|
||||
.slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
|
||||
.replace(/[-_]+$/g, "");
|
||||
if (segment.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return segment;
|
||||
}
|
||||
|
||||
export function createAttachmentId(threadId: string): string | null {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
return null;
|
||||
}
|
||||
return `${threadSegment}-${randomUUID()}`;
|
||||
}
|
||||
|
||||
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
return null;
|
||||
}
|
||||
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return match[1]?.toLowerCase() ?? null;
|
||||
}
|
||||
|
||||
export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||
switch (attachment.type) {
|
||||
case "image": {
|
||||
const extension = inferImageExtension({
|
||||
mimeType: attachment.mimeType,
|
||||
fileName: attachment.name,
|
||||
});
|
||||
return `${attachment.id}${extension}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveAttachmentPath(input: {
|
||||
readonly attachmentsDir: string;
|
||||
readonly attachment: ChatAttachment;
|
||||
}): string | null {
|
||||
return resolveAttachmentRelativePath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: attachmentRelativePath(input.attachment),
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveAttachmentPathById(input: {
|
||||
readonly attachmentsDir: string;
|
||||
readonly attachmentId: string;
|
||||
}): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
return null;
|
||||
}
|
||||
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||
const maybePath = resolveAttachmentRelativePath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: `${normalizedId}${extension}`,
|
||||
});
|
||||
if (maybePath && existsSync(maybePath)) {
|
||||
return maybePath;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
|
||||
const normalized = normalizeAttachmentRelativePath(relativePath);
|
||||
if (!normalized || normalized.includes("/")) {
|
||||
return null;
|
||||
}
|
||||
const extensionIndex = normalized.lastIndexOf(".");
|
||||
if (extensionIndex <= 0) {
|
||||
return null;
|
||||
}
|
||||
const id = normalized.slice(0, extensionIndex);
|
||||
return id.length > 0 && !id.includes(".") ? id : null;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { cli } from "./cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
Command.run(cli, { version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -0,0 +1,149 @@
|
||||
import * as NFS from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { FileSystem, Schema } from "effect";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
||||
|
||||
vi.mock("node:fs", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:fs")>();
|
||||
return {
|
||||
...actual,
|
||||
openSync: (...args: Parameters<typeof actual.openSync>) => {
|
||||
const [filePath, flags] = args;
|
||||
if (
|
||||
typeof filePath === "string" &&
|
||||
filePath === openSyncInterceptor.failPath &&
|
||||
flags === "r"
|
||||
) {
|
||||
const error = new Error("no such device or address");
|
||||
Object.assign(error, { code: "ENXIO" });
|
||||
throw error;
|
||||
}
|
||||
return (actual.openSync as (...a: typeof args) => number)(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
|
||||
|
||||
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
it.effect("uses platform-specific fd paths", () =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(resolveFdPath(3, "linux"), "/proc/self/fd/3");
|
||||
assert.equal(resolveFdPath(3, "darwin"), "/dev/fd/3");
|
||||
assert.equal(resolveFdPath(3, "win32"), undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads a bootstrap envelope from a provided fd", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NFS.openSync(filePath, "r")),
|
||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
||||
);
|
||||
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertSome(payload, {
|
||||
mode: "desktop",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
|
||||
// so the stream owns the fd lifecycle and closes it asynchronously on end.
|
||||
// Attempting to also close it synchronously in a finalizer races with the
|
||||
// stream's async close and produces an uncaught EBADF.
|
||||
const fd = NFS.openSync(filePath, "r");
|
||||
|
||||
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
|
||||
try {
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertSome(payload, {
|
||||
mode: "desktop",
|
||||
});
|
||||
} finally {
|
||||
openSyncInterceptor.failPath = null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the fd is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = NFS.openSync("/dev/null", "r");
|
||||
NFS.closeSync(fd);
|
||||
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertNone(payload);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
|
||||
const fifoPath = path.join(tempDir, "bootstrap.pipe");
|
||||
|
||||
yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath]));
|
||||
|
||||
const _writer = yield* Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
|
||||
stdio: ["ignore", "ignore", "ignore"],
|
||||
}),
|
||||
),
|
||||
(writer) =>
|
||||
Effect.sync(() => {
|
||||
writer.kill("SIGKILL");
|
||||
}),
|
||||
);
|
||||
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NFS.openSync(fifoPath, "r")),
|
||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
||||
);
|
||||
|
||||
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
||||
timeoutMs: 100,
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(100));
|
||||
|
||||
const payload = yield* Fiber.join(fiber);
|
||||
assertNone(payload);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import * as NFS from "node:fs";
|
||||
import * as Net from "node:net";
|
||||
import * as readline from "node:readline";
|
||||
import type { Readable } from "node:stream";
|
||||
|
||||
import { Data, Effect, Option, Predicate, Result, Schema } from "effect";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
class BootstrapError extends Data.TaggedError("BootstrapError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
|
||||
schema: Schema.Codec<A, I>,
|
||||
fd: number,
|
||||
options?: {
|
||||
timeoutMs?: number;
|
||||
},
|
||||
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
|
||||
const fdReady = yield* isFdReady(fd);
|
||||
if (!fdReady) return Option.none();
|
||||
|
||||
const stream = yield* makeBootstrapInputStream(fd);
|
||||
|
||||
const timeoutMs = options?.timeoutMs ?? 1000;
|
||||
|
||||
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
|
||||
const input = readline.createInterface({
|
||||
input: stream,
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
|
||||
const cleanup = () => {
|
||||
stream.removeListener("error", handleError);
|
||||
input.removeListener("line", handleLine);
|
||||
input.removeListener("close", handleClose);
|
||||
input.close();
|
||||
stream.destroy();
|
||||
};
|
||||
|
||||
const handleError = (error: Error) => {
|
||||
if (isUnavailableBootstrapFdError(error)) {
|
||||
resume(Effect.succeedNone);
|
||||
return;
|
||||
}
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BootstrapError({
|
||||
message: "Failed to read bootstrap envelope.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const handleLine = (line: string) => {
|
||||
const parsed = decodeJsonResult(schema)(line);
|
||||
if (Result.isSuccess(parsed)) {
|
||||
resume(Effect.succeedSome(parsed.success));
|
||||
} else {
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BootstrapError({
|
||||
message: "Failed to decode bootstrap envelope.",
|
||||
cause: parsed.failure,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
resume(Effect.succeedNone);
|
||||
};
|
||||
|
||||
stream.once("error", handleError);
|
||||
input.once("line", handleLine);
|
||||
input.once("close", handleClose);
|
||||
|
||||
return Effect.sync(cleanup);
|
||||
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
|
||||
});
|
||||
|
||||
const isUnavailableBootstrapFdError = Predicate.compose(
|
||||
Predicate.hasProperty("code"),
|
||||
(_) => _.code === "EBADF" || _.code === "ENOENT",
|
||||
);
|
||||
|
||||
const isFdReady = (fd: number) =>
|
||||
Effect.try({
|
||||
try: () => NFS.fstatSync(fd),
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
message: "Failed to stat bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchIf(
|
||||
(error) => isUnavailableBootstrapFdError(error.cause),
|
||||
() => Effect.succeed(false),
|
||||
),
|
||||
);
|
||||
|
||||
const makeBootstrapInputStream = (fd: number) =>
|
||||
Effect.try<Readable, BootstrapError>({
|
||||
try: () => {
|
||||
const fdPath = resolveFdPath(fd);
|
||||
if (fdPath === undefined) {
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
|
||||
let streamFd: number | undefined;
|
||||
try {
|
||||
streamFd = NFS.openSync(fdPath, "r");
|
||||
return NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isBootstrapFdPathDuplicationError(error)) {
|
||||
if (streamFd !== undefined) {
|
||||
NFS.closeSync(streamFd);
|
||||
}
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
message: "Failed to duplicate bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
});
|
||||
|
||||
const makeDirectBootstrapStream = (fd: number): Readable => {
|
||||
try {
|
||||
return NFS.createReadStream("", {
|
||||
fd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch {
|
||||
const stream = new Net.Socket({
|
||||
fd,
|
||||
readable: true,
|
||||
writable: false,
|
||||
});
|
||||
stream.setEncoding("utf8");
|
||||
return stream;
|
||||
}
|
||||
};
|
||||
|
||||
const isBootstrapFdPathDuplicationError = Predicate.compose(
|
||||
Predicate.hasProperty("code"),
|
||||
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
|
||||
);
|
||||
|
||||
export function resolveFdPath(
|
||||
fd: number,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): string | undefined {
|
||||
if (platform === "linux") {
|
||||
return `/proc/self/fd/${fd}`;
|
||||
}
|
||||
if (platform === "win32") {
|
||||
return undefined;
|
||||
}
|
||||
return `/dev/fd/${fd}`;
|
||||
}
|
||||