Merge console messaging systems - resolve conflicts between parallel console log implementations

- Unified the global console message system with local state passing
- Maintained backward compatibility for external systems
- Added proper synchronization between global and local console states
- Resolved conflicts in PreviewPane.tsx and ProjectView.tsx
- Both console messaging systems now co-exist peacefully
This commit is contained in:
Chad Curtis committed 2025-09-24 16:30:50 +00:00
commit 662f95d35d
43 files changed
+2477 -307

No files matched your search

+114
View File
@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="500px" height="500px" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd" xmlns:xlink="http://www.w3.org/1999/xlink">
<g><path style="opacity:0.004" fill="#fefffe" d="M 1.5,10.5 C 2.83333,11.1667 2.83333,11.1667 1.5,10.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 287.5,14.5 C 288.833,15.1667 288.833,15.1667 287.5,14.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 393.5,19.5 C 394.833,20.1667 394.833,20.1667 393.5,19.5 Z"/></g>
<g><path style="opacity:0.067" fill="#d8d5d1" d="M 257.5,33.5 C 252.167,33.5 246.833,33.5 241.5,33.5C 246.567,32.8118 251.733,32.1451 257,31.5C 257.464,32.0944 257.631,32.7611 257.5,33.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 304.5,37.5 C 305.833,38.1667 305.833,38.1667 304.5,37.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 199.5,52.5 C 198.833,51.1667 198.833,51.1667 199.5,52.5 Z"/></g>
<g><path style="opacity:1" fill="#272422" d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z"/></g>
<g><path style="opacity:0.435" fill="#9b9895" d="M 195.5,57.5 C 195.573,59.0269 194.906,60.0269 193.5,60.5C 193.427,58.9731 194.094,57.9731 195.5,57.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 404.5,60.5 C 405.833,61.1667 405.833,61.1667 404.5,60.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 92.5,61.5 C 93.8333,62.1667 93.8333,62.1667 92.5,61.5 Z"/></g>
<g><path style="opacity:1" fill="#1c1a18" d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 448.5,63.5 C 449.833,64.1667 449.833,64.1667 448.5,63.5 Z"/></g>
<g><path style="opacity:0.141" fill="#b0abaa" d="M 291.5,64.5 C 293.104,65.287 293.771,66.6203 293.5,68.5C 292.326,67.4863 291.66,66.153 291.5,64.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 426.5,69.5 C 427.833,70.1667 427.833,70.1667 426.5,69.5 Z"/></g>
<g><path style="opacity:0.09" fill="#c3bbb9" d="M 187.5,70.5 C 187.573,72.0269 186.906,73.0269 185.5,73.5C 185.427,71.9731 186.094,70.9731 187.5,70.5 Z"/></g>
<g><path style="opacity:0.824" fill="#726e69" d="M 312.5,71.5 C 314.729,74.3538 316.062,77.6871 316.5,81.5C 315.043,79.7582 313.876,77.7582 313,75.5C 312.51,74.2068 312.343,72.8734 312.5,71.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 487.5,76.5 C 488.833,77.1667 488.833,77.1667 487.5,76.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 387.5,78.5 C 388.833,79.1667 388.833,79.1667 387.5,78.5 Z"/></g>
<g><path style="opacity:1" fill="#1e1d1b" d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 20.5,86.5 C 21.8333,87.1667 21.8333,87.1667 20.5,86.5 Z"/></g>
<g><path style="opacity:0.792" fill="#97938f" d="M 272.5,96.5 C 275.189,97.1894 276.856,98.856 277.5,101.5C 275.451,100.118 273.785,98.4516 272.5,96.5 Z"/></g>
<g><path style="opacity:1" fill="#23201e" d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z"/></g>
<g><path style="opacity:0.004" fill="#d7d2ce" d="M 269.5,104.5 C 270.5,104.833 271.167,105.5 271.5,106.5C 270.167,106.5 269.5,105.833 269.5,104.5 Z"/></g>
<g><path style="opacity:1" fill="#242220" d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z"/></g>
<g><path style="opacity:1" fill="#272422" d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z"/></g>
<g><path style="opacity:0.137" fill="#a59b96" d="M 163.5,112.5 C 163.573,114.027 162.906,115.027 161.5,115.5C 161.427,113.973 162.094,112.973 163.5,112.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 89.5,117.5 C 90.8333,118.167 90.8333,118.167 89.5,117.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 437.5,118.5 C 438.833,119.167 438.833,119.167 437.5,118.5 Z"/></g>
<g><path style="opacity:0.992" fill="#72716a" d="M 216.5,118.5 C 216.167,120.833 214.833,122.167 212.5,122.5C 213.09,121.234 213.59,119.901 214,118.5C 214.77,119.598 215.603,119.598 216.5,118.5 Z"/></g>
<g><path style="opacity:0.098" fill="#bfb8b7" d="M 339.5,117.5 C 340.906,117.973 341.573,118.973 341.5,120.5C 340.094,120.027 339.427,119.027 339.5,117.5 Z"/></g>
<g><path style="opacity:0.508" fill="#7f7a74" d="M 203.5,121.5 C 206.43,122.299 209.43,122.632 212.5,122.5C 210.034,123.634 207.367,123.801 204.5,123C 203.944,122.617 203.611,122.117 203.5,121.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 408.5,124.5 C 409.833,125.167 409.833,125.167 408.5,124.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 424.5,133.5 C 425.833,134.167 425.833,134.167 424.5,133.5 Z"/></g>
<g><path style="opacity:0.333" fill="#9e9894" d="M 344.5,127.5 C 345.954,130.718 346.621,134.218 346.5,138C 346.496,140.361 346.163,142.527 345.5,144.5C 345.553,138.804 345.22,133.138 344.5,127.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 140.5,135.5 C 141.833,136.167 141.833,136.167 140.5,135.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 53.5,137.5 C 54.8333,138.167 54.8333,138.167 53.5,137.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 353.5,140.5 C 354.833,141.167 354.833,141.167 353.5,140.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 493.5,141.5 C 494.833,142.167 494.833,142.167 493.5,141.5 Z"/></g>
<g><path style="opacity:0.455" fill="#918f8b" d="M 243.5,143.5 C 242.135,145.794 240.135,147.461 237.5,148.5C 239.385,146.947 240.385,144.947 240.5,142.5C 241.791,142.263 242.791,142.596 243.5,143.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 437.5,153.5 C 438.833,154.167 438.833,154.167 437.5,153.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 438.5,183.5 C 439.833,184.167 439.833,184.167 438.5,183.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 446.5,183.5 C 447.833,184.167 447.833,184.167 446.5,183.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 123.5,185.5 C 124.833,186.167 124.833,186.167 123.5,185.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 129.5,186.5 C 130.833,187.167 130.833,187.167 129.5,186.5 Z"/></g>
<g><path style="opacity:0.839" fill="#756a67" d="M 333.5,187.5 C 333.346,189.97 332.346,191.97 330.5,193.5C 330.455,190.923 331.455,188.923 333.5,187.5 Z"/></g>
<g><path style="opacity:1" fill="#262321" d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 26.5,198.5 C 27.8333,199.167 27.8333,199.167 26.5,198.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 413.5,204.5 C 414.833,205.167 414.833,205.167 413.5,204.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 74.5,209.5 C 75.8333,210.167 75.8333,210.167 74.5,209.5 Z"/></g>
<g><path style="opacity:0.965" fill="#272422" d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z"/></g>
<g><path style="opacity:0.129" fill="#b5b4af" d="M 206.5,184.5 C 207.906,184.973 208.573,185.973 208.5,187.5C 207.094,187.027 206.427,186.027 206.5,184.5 Z"/></g>
<g><path style="opacity:1" fill="#35312f" d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z"/></g>
<g><path style="opacity:1" fill="#171513" d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z"/></g>
<g><path style="opacity:1" fill="#413d38" d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z"/></g>
<g><path style="opacity:0.098" fill="#cecbc4" d="M 177.5,212.5 C 181.151,211.835 184.985,211.501 189,211.5C 195.725,211.4 202.225,212.066 208.5,213.5C 198.183,212.774 187.85,212.44 177.5,212.5 Z"/></g>
<g><path style="opacity:0.149" fill="#adaaa7" d="M 150.5,210.5 C 150.573,212.027 149.906,213.027 148.5,213.5C 148.427,211.973 149.094,210.973 150.5,210.5 Z"/></g>
<g><path style="opacity:0.122" fill="#c4b9b8" d="M 217.5,211.5 C 217.5,212.167 217.5,212.833 217.5,213.5C 215.833,214.833 214.167,214.833 212.5,213.5C 214.554,213.635 216.221,212.968 217.5,211.5 Z"/></g>
<g><path style="opacity:1" fill="#181614" d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z"/></g>
<g><path style="opacity:0.047" fill="#e0dfd7" d="M 198.5,219.5 C 198.5,219.833 198.5,220.167 198.5,220.5C 195.287,220.19 192.287,220.523 189.5,221.5C 188.957,221.44 188.624,221.107 188.5,220.5C 191.768,219.513 195.102,219.18 198.5,219.5 Z"/></g>
<g><path style="opacity:0.592" fill="#7d7976" d="M 299.5,222.5 C 298.833,224.167 298.167,225.833 297.5,227.5C 296.833,227.5 296.167,227.5 295.5,227.5C 296.124,225.246 297.457,223.579 299.5,222.5 Z"/></g>
<g><path style="opacity:0.592" fill="#94908e" d="M 189.5,221.5 C 190.377,223.728 191.71,225.728 193.5,227.5C 190.224,226.878 188.891,224.878 189.5,221.5 Z"/></g>
<g><path style="opacity:0.247" fill="#837f7a" d="M 201.5,225.5 C 201.423,226.75 200.756,227.583 199.5,228C 197.288,228.789 195.288,228.622 193.5,227.5C 196.421,227.717 199.087,227.051 201.5,225.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 32.5,229.5 C 33.8333,230.167 33.8333,230.167 32.5,229.5 Z"/></g>
<g><path style="opacity:1" fill="#252421" d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 490.5,245.5 C 491.833,246.167 491.833,246.167 490.5,245.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 230.5,246.5 C 231.833,247.167 231.833,247.167 230.5,246.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 223.5,250.5 C 224.833,251.167 224.833,251.167 223.5,250.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 485.5,254.5 C 486.833,255.167 486.833,255.167 485.5,254.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 411.5,255.5 C 412.833,256.167 412.833,256.167 411.5,255.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 144.5,270.5 C 145.833,271.167 145.833,271.167 144.5,270.5 Z"/></g>
<g><path style="opacity:1" fill="#22201e" d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z"/></g>
<g><path style="opacity:0.184" fill="#a6a29e" d="M 278.5,242.5 C 280.027,242.427 281.027,243.094 281.5,244.5C 279.973,244.573 278.973,243.906 278.5,242.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 257.5,237.5 C 258.833,238.167 258.833,238.167 257.5,237.5 Z"/></g>
<g><path style="opacity:0.247" fill="#aca7a5" d="M 295.5,227.5 C 295.573,229.027 294.906,230.027 293.5,230.5C 293.427,228.973 294.094,227.973 295.5,227.5 Z"/></g>
<g><path style="opacity:0.306" fill="#7f7772" d="M 244.5,228.5 C 246.167,228.5 247.833,228.5 249.5,228.5C 249.598,230.553 248.931,232.22 247.5,233.5C 247.33,232.178 247.663,231.011 248.5,230C 246.942,229.79 245.609,229.29 244.5,228.5 Z"/></g>
<g><path style="opacity:0.114" fill="#bcb6b2" d="M 213.5,222.5 C 212.523,225.287 212.19,228.287 212.5,231.5C 211.833,231.5 211.5,231.167 211.5,230.5C 211.183,227.428 211.516,224.428 212.5,221.5C 213.107,221.624 213.44,221.957 213.5,222.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 202.5,272.5 C 203.833,273.167 203.833,273.167 202.5,272.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 32.5,280.5 C 33.8333,281.167 33.8333,281.167 32.5,280.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 255.5,283.5 C 256.833,284.167 256.833,284.167 255.5,283.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 239.5,290.5 C 240.833,291.167 240.833,291.167 239.5,290.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 110.5,295.5 C 111.833,296.167 111.833,296.167 110.5,295.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 405.5,295.5 C 406.833,296.167 406.833,296.167 405.5,295.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 330.5,302.5 C 331.833,303.167 331.833,303.167 330.5,302.5 Z"/></g>
<g><path style="opacity:0.342" fill="#837e7a" d="M 172.5,220.5 C 172.5,220.167 172.5,219.833 172.5,219.5C 175.167,219.5 177.833,219.5 180.5,219.5C 180.5,273.833 180.5,328.167 180.5,382.5C 179.501,328.669 179.168,274.669 179.5,220.5C 177.167,220.5 174.833,220.5 172.5,220.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 394.5,307.5 C 395.833,308.167 395.833,308.167 394.5,307.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 406.5,308.5 C 407.833,309.167 407.833,309.167 406.5,308.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 63.5,320.5 C 64.8333,321.167 64.8333,321.167 63.5,320.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 105.5,321.5 C 106.833,322.167 106.833,322.167 105.5,321.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 400.5,323.5 C 401.833,324.167 401.833,324.167 400.5,323.5 Z"/></g>
<g><path style="opacity:0.224" fill="#6b6662" d="M 200.5,235.5 C 198.735,236.461 196.735,236.795 194.5,236.5C 194.185,286.857 194.518,337.19 195.5,387.5C 194.732,386.737 194.232,385.737 194,384.5C 193.5,334.834 193.333,285.168 193.5,235.5C 195.833,235.5 198.167,235.5 200.5,235.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 492.5,372.5 C 493.833,373.167 493.833,373.167 492.5,372.5 Z"/></g>
<g><path style="opacity:1" fill="#706d68" d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z"/></g>
<g><path style="opacity:0.471" fill="#89837d" d="M 262.5,374.5 C 260.321,375.926 257.821,376.592 255,376.5C 253.293,376.492 251.793,376.158 250.5,375.5C 254.534,375.495 258.534,375.162 262.5,374.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 308.5,385.5 C 309.833,386.167 309.833,386.167 308.5,385.5 Z"/></g>
<g><path style="opacity:0.039" fill="#cdc9c7" d="M 308.5,397.5 C 308.573,399.027 307.906,400.027 306.5,400.5C 306.427,398.973 307.094,397.973 308.5,397.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 384.5,401.5 C 385.833,402.167 385.833,402.167 384.5,401.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 130.5,431.5 C 131.833,432.167 131.833,432.167 130.5,431.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 129.5,437.5 C 130.833,438.167 130.833,438.167 129.5,437.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 172.5,437.5 C 173.833,438.167 173.833,438.167 172.5,437.5 Z"/></g>
<g><path style="opacity:0.998" fill="#1f1d1b" d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z"/></g>
<g><path style="opacity:0.755" fill="#706a67" d="M 266.5,434.5 C 266.082,435.222 265.416,435.722 264.5,436C 258.984,436.817 253.65,436.651 248.5,435.5C 254.545,435.697 260.545,435.363 266.5,434.5 Z"/></g>
<g><path style="opacity:0.165" fill="#a6a19f" d="M 276.5,445.5 C 275.22,446.931 273.553,447.598 271.5,447.5C 272.78,446.069 274.447,445.402 276.5,445.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 496.5,448.5 C 497.833,449.167 497.833,449.167 496.5,448.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 485.5,449.5 C 486.833,450.167 486.833,450.167 485.5,449.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 295.5,468.5 C 296.833,469.167 296.833,469.167 295.5,468.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 31.5,477.5 C 32.8333,478.167 32.8333,478.167 31.5,477.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 78.5,478.5 C 79.8333,479.167 79.8333,479.167 78.5,478.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 135.5,485.5 C 136.833,486.167 136.833,486.167 135.5,485.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 67.5,492.5 C 68.8333,493.167 68.8333,493.167 67.5,492.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 11.5,495.5 C 12.8333,496.167 12.8333,496.167 11.5,495.5 Z"/></g>
</svg>

After

Width:  |  Height:  |  Size: 29 KiB

+15 -3
View File
@@ -11,6 +11,7 @@ import {
MoreHorizontal,
MessageSquarePlus,
History,
Folder,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
@@ -19,6 +20,7 @@ interface ActionsMenuProps {
projectId: string;
projectName: string;
onNewChat: () => void;
onProjectDetails?: () => void;
isLoading?: boolean;
isBuildLoading?: boolean;
disabled?: boolean;
@@ -29,6 +31,7 @@ export function ActionsMenu({
projectId,
projectName: _projectName,
onNewChat,
onProjectDetails,
isLoading = false,
isBuildLoading = false,
disabled = false,
@@ -65,6 +68,15 @@ export function ActionsMenu({
New Chat
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitHistoryOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<History className="h-4 w-4" />
Rollback
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitDialogOpen(true)}
disabled={isAnyLoading}
@@ -75,12 +87,12 @@ export function ActionsMenu({
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitHistoryOpen(true)}
onClick={onProjectDetails}
disabled={isAnyLoading}
className="gap-2"
>
<History className="h-4 w-4" />
Rollback
<Folder className="h-4 w-4" />
Project Details
</DropdownMenuItem>
+6 -16
View File
@@ -3,7 +3,6 @@ import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsBadge } from './CreditsBadge';
// Mock the useAICredits hook
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: () => ({
@@ -16,7 +15,8 @@ vi.mock('@/hooks/useAICredits', () => ({
// Mock the fetch function
global.fetch = vi.fn();
const mockConnection = {
const mockProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
@@ -25,10 +25,7 @@ describe('CreditsBadge', () => {
it('renders the credits amount', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
<CreditsBadge provider={mockProvider} />
</TestApp>
);
@@ -41,8 +38,7 @@ describe('CreditsBadge', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
onOpenDialog={mockCallback}
/>
</TestApp>
@@ -57,10 +53,7 @@ describe('CreditsBadge', () => {
it('has proper styling for clickable badge', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
<CreditsBadge provider={mockProvider} />
</TestApp>
);
@@ -72,10 +65,7 @@ describe('CreditsBadge', () => {
it('does not render dialog directly', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
<CreditsBadge provider={mockProvider} />
</TestApp>
);
+4 -8
View File
@@ -1,13 +1,9 @@
import { Badge } from '@/components/ui/badge';
import { AIProvider } from '@/contexts/AISettingsContext';
import { useAICredits } from '@/hooks/useAICredits';
interface CreditsBadgeProps {
providerId: string;
connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
};
provider: AIProvider;
className?: string;
onOpenDialog?: () => void;
}
@@ -15,8 +11,8 @@ interface CreditsBadgeProps {
/**
* Displays a clickable credits badge showing the remaining credits for an AI provider
*/
export function CreditsBadge({ providerId, connection, className, onOpenDialog }: CreditsBadgeProps) {
const { data: credits, isLoading, error } = useAICredits(providerId, connection);
export function CreditsBadge({ provider, className, onOpenDialog }: CreditsBadgeProps) {
const { data: credits, isLoading, error } = useAICredits(provider);
// Don't render anything if there's an error (provider doesn't support credits endpoint)
if (error || isLoading) {
+10 -14
View File
@@ -2,14 +2,16 @@ import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsDialog } from './CreditsDialog';
import type { AIProvider } from '@/contexts/AISettingsContext';
// Mock the fetch function
global.fetch = vi.fn();
const mockConnection = {
const mockProvider: AIProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
};
describe('CreditsDialog', () => {
@@ -19,8 +21,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -36,8 +37,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={false}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -51,8 +51,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -67,8 +66,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -89,8 +87,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={false}
onOpenChange={mockCallback}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -101,8 +98,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={true}
onOpenChange={mockCallback}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
+12 -15
View File
@@ -13,15 +13,12 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { useToast } from '@/hooks/useToast';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { AIProvider } from '@/contexts/AISettingsContext';
interface CreditsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
providerId: string;
connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
};
provider: AIProvider;
}
interface Payment {
@@ -184,7 +181,7 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
);
}
export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) {
export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogProps) {
const { user } = useCurrentUser();
const { toast } = useToast();
const queryClient = useQueryClient();
@@ -196,9 +193,9 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Query for payment history
const { data: payments, isLoading: isLoadingPayments } = useQuery({
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
queryFn: async (): Promise<Payment[]> => {
const ai = createAIClient(connection, user);
const ai = createAIClient(provider, user);
const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse;
return data.data;
},
@@ -210,7 +207,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Mutation for adding credits
const addCreditsMutation = useMutation({
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
const ai = createAIClient(connection, user);
const ai = createAIClient(provider, user);
return await ai.post('/credits/add', {
body: request,
}) as Payment;
@@ -230,12 +227,12 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Refresh payments list
queryClient.invalidateQueries({
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Refresh credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
},
onError: (error: Error) => {
@@ -251,7 +248,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Mutation for checking payment status
const checkPaymentMutation = useMutation({
mutationFn: async (paymentId: string): Promise<Payment> => {
const ai = createAIClient(connection, user);
const ai = createAIClient(provider, user);
return await ai.get(`/credits/payments/${paymentId}`) as Payment;
},
onMutate: async (paymentId: string) => {
@@ -268,7 +265,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Update the specific payment in the cache instead of refetching
queryClient.setQueryData<Payment[]>(
['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
(oldPayments) => {
if (!oldPayments) return oldPayments;
return oldPayments.map(payment =>
@@ -280,7 +277,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// If payment completed, refresh credits balance
if (updatedPayment.status === 'completed') {
queryClient.invalidateQueries({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
toast({
title: 'Payment completed!',
+7 -7
View File
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import type { AIProvider } from '@/contexts/AISettingsContext';
// Mock QRCode
vi.mock('qrcode', () => ({
@@ -18,9 +19,11 @@ const mockWebLN = {
// We need to import the component after mocking
const { CreditsDialog } = await import('./CreditsDialog');
const mockConnection = {
const mockProvider: AIProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
};
describe('Lightning Payment', () => {
@@ -39,8 +42,7 @@ describe('Lightning Payment', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -61,8 +63,7 @@ describe('Lightning Payment', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -77,8 +78,7 @@ describe('Lightning Payment', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
+27 -18
View File
@@ -17,6 +17,8 @@ interface ModelSelectorProps {
className?: string;
disabled?: boolean;
placeholder?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function ModelSelector({
@@ -25,9 +27,16 @@ export function ModelSelector({
className,
disabled = false,
placeholder,
open: controlledOpen,
onOpenChange: setControlledOpen,
}: ModelSelectorProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
// Use controlled state if provided, otherwise use local state
const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen;
const setOpen = setControlledOpen || setUncontrolledOpen;
const [isCustomInput, setIsCustomInput] = useState(false);
const [customValue, setCustomValue] = useState('');
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
@@ -140,23 +149,23 @@ export function ModelSelector({
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
className
)}
disabled={disabled}
>
<span className="w-full truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
className
)}
disabled={disabled}
>
<span className="w-full truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-96 p-0" align="end">
<Command>
{isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
+1 -2
View File
@@ -334,8 +334,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
handleCreditsDialogClose();
}
}}
providerId="shakespeare"
connection={SHAKESPEARE_PROVIDER}
provider={SHAKESPEARE_PROVIDER}
/>
)}
</>
@@ -1,4 +1,5 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { type Project } from '@/lib/ProjectsManager';
import {
Dialog,
@@ -18,6 +19,8 @@ import {
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { useProjectsManager } from '@/hooks/useProjectsManager';
@@ -28,23 +31,34 @@ import {
Download,
Loader2,
Trash2,
Save,
} from 'lucide-react';
import JSZip from 'jszip';
import { Separator } from './ui/separator';
interface ProjectInfoDialogProps {
interface ProjectDetailsDialogProps {
project: Project;
open: boolean;
onOpenChange: (open: boolean) => void;
onProjectDeleted?: () => void;
}
export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectInfoDialogProps) {
export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectDetailsDialogProps) {
const [isExporting, setIsExporting] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isRenaming, setIsRenaming] = useState(false);
const [newProjectName, setNewProjectName] = useState(project.id);
const { toast } = useToast();
const { fs } = useFS();
const projectsManager = useProjectsManager();
const navigate = useNavigate();
const queryClient = useQueryClient();
// Reset state when project changes
useEffect(() => {
setNewProjectName(project.id);
setIsRenaming(false);
}, [project.id]);
const formatDistanceToNow = (date: Date) => {
const now = new Date();
@@ -58,11 +72,49 @@ export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDelete
return `${Math.floor(diffInSeconds / 31536000)} years ago`;
};
const handleSaveProject = async () => {
if (!newProjectName.trim() || newProjectName === project.id) {
setNewProjectName(project.id);
return;
}
setIsRenaming(true);
try {
await projectsManager.renameProject(project.id, newProjectName);
// Invalidate the projects query to update the sidebar
await queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: "Project renamed",
description: `Project renamed from "${project.id}" to "${newProjectName}".`,
});
// Close the dialog first
onOpenChange(false);
// Navigate to the new URL
navigate(`/project/${newProjectName}`);
} catch (error) {
toast({
title: "Failed to rename project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
setNewProjectName(project.id); // Reset to original name
} finally {
setIsRenaming(false);
}
};
const handleDeleteProject = async () => {
setIsDeleting(true);
try {
await projectsManager.deleteProject(project.id);
// Invalidate the projects query to update the sidebar
await queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: "Project deleted",
description: `"${project.name}" has been permanently deleted.`,
@@ -172,10 +224,46 @@ export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDelete
<span>{formatDistanceToNow(project.lastModified)}</span>
</div>
{/* Project Name */}
<div className="space-y-2">
<Label htmlFor="project-name">Project Name</Label>
<div className="flex items-center gap-2">
<Input
id="project-name"
value={newProjectName}
onChange={(e) => setNewProjectName(e.target.value)}
disabled={isRenaming}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleSaveProject();
} else if (e.key === 'Escape') {
setNewProjectName(project.id);
}
}}
className="flex-1"
placeholder="Enter project name"
/>
<Button
size="sm"
onClick={handleSaveProject}
disabled={isRenaming || !newProjectName.trim() || newProjectName === project.id}
className="h-10"
>
{isRenaming ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Save className="h-4 w-4" />
)}
</Button>
</div>
</div>
<Separator />
{/* Export Project Button */}
<Button
onClick={handleExportProject}
disabled={isExporting || isDeleting}
disabled={isExporting || isDeleting || isRenaming}
className="w-full gap-2"
variant="outline"
>
@@ -193,7 +281,7 @@ export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDelete
<Button
variant="destructive"
className="w-full gap-2"
disabled={isExporting || isDeleting}
disabled={isExporting || isDeleting || isRenaming}
>
<Trash2 className="h-4 w-4" />
Delete Project
+3 -3
View File
@@ -17,13 +17,13 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps
const { fs } = useFS();
const { settings } = useAISettings();
const { models } = useProviderModels();
const { user } = useCurrentUser();
const { user, metadata } = useCurrentUser();
const sessionManager = useMemo(() => {
const getProviderModels = () => models;
const getCurrentUser = () => user;
const getCurrentUser = () => ({ user, metadata });
return new SessionManager(fs, settings, getProviderModels, getCurrentUser);
}, [fs, settings, models, user]);
}, [fs, settings, models, user, metadata]);
// Cleanup on unmount
useEffect(() => {
+152 -61
View File
@@ -7,7 +7,8 @@ import { Skeleton } from '@/components/ui/skeleton';
import { CircularProgress } from '@/components/ui/circular-progress';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { Square, Loader2, ChevronDown, ArrowUp, X } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -38,9 +39,55 @@ import { ConsoleMessage } from '@/types/console';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { makeSystemPrompt } from '@/lib/system';
import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection';
import { QuillySVG } from '@/components/ui/QuillySVG';
function ChatIntervention({
message,
onDismiss,
action,
}: {
message: string;
onDismiss: () => void;
action?: { label: string; onClick: () => void };
}) {
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
<div className="flex items-start gap-2">
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
<div className="flex-1 min-w-0">
<div className="space-y-1">
<h4 className="font-semibold text-primary">
Pardon the interruption
</h4>
<p className="text-sm text-muted-foreground">
{message}
{' '}
{action && (
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
)}
</p>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={onDismiss}
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
);
}
// Clean interfaces now handled by proper hooks
interface ChatPaneProps {
projectId: string;
@@ -69,11 +116,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}, ref) => {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [systemPrompt, setSystemPrompt] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
const [showOnboarding, setShowOnboarding] = useState(false);
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
@@ -83,6 +130,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Initialize with first recently used model if available, otherwise empty
return settings.recentlyUsedModels?.[0] || '';
});
// State to control model selector dropdown
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
@@ -93,7 +142,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
const { git } = useGit();
const { user, metadata } = useCurrentUser();
const { user } = useCurrentUser();
const { models } = useProviderModels();
// Initialize AI chat with tools
@@ -158,19 +207,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
updateMetadata(title, description);
}, [updateMetadata]);
useEffect(() => {
makeSystemPrompt({
cwd,
fs,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(tools),
user,
metadata,
}).then(setSystemPrompt)
}, [fs, cwd, tools, user, metadata]);
const {
messages,
streamingMessage,
@@ -185,7 +221,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
projectId,
tools,
customTools,
systemPrompt,
onUpdateMetadata,
});
@@ -210,6 +245,32 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [internalIsLoading, onLoadingChange]);
// Function to scroll to bottom
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, []);
// Function to open model selector dropdown
const openModelSelector = useCallback(() => {
setIsModelSelectorOpen(true);
}, []);
// Function to suggest error fix
// Clean alert hooks with proper interfaces
const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector);
const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading);
// Scroll to bottom when alerts appear
useEffect(() => {
if (aiModelAlert.hasError || consoleAlert.hasError) {
setTimeout(() => {
scrollToBottom();
}, 50);
}
}, [aiModelAlert.hasError, consoleAlert.hasError, scrollToBottom]);
// Check for autostart parameter and trigger AI generation
useEffect(() => {
const autostart = searchParams.get('autostart');
@@ -238,14 +299,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
// Function to scroll to bottom
const scrollToBottom = () => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
};
// Simple scroll event listener
useEffect(() => {
const container = scrollAreaRef.current;
@@ -280,7 +333,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
}
}
}, [messages, streamingMessage, isLoading]);
@@ -295,7 +347,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
return () => clearTimeout(timer);
}
}, [projectId, scrolledProjects]);
}, [projectId, scrolledProjects, scrollToBottom]);
const handleFileSelect = (file: File) => {
setAttachedFiles(prev => [...prev, file]);
@@ -348,8 +400,17 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
setAttachedFiles(prev => [...prev, ...files]);
};
const handleSend = async () => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading || !providerModel.trim()) return;
const send = useCallback(async (input: string, attachedFiles: File[]) => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
// If AI is not configured, show onboarding dialog
if (!isConfigured) {
setShowOnboarding(true);
return;
}
// If configured but no model selected, don't proceed
if (!providerModel.trim()) return;
const modelToUse = providerModel.trim();
@@ -399,9 +460,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
await sendMessage(messageContent, modelToUse);
} catch (error) {
console.error('AI chat error:', error);
// Error handling is done in the useAIChat hook
// Error handling is done in the useAIChat hook and SessionManager
}
};
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
const handleSend = useCallback(async () => {
await send(input, attachedFiles);
}, [input, attachedFiles, send]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
@@ -439,6 +504,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
};
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = () => {
if (!isConfigured) {
setShowOnboarding(true);
}
if (onFirstInteraction) {
onFirstInteraction();
}
};
// Handle first user interaction to enable audio context
const handleFirstInteraction = () => {
// This will be handled automatically by the useKeepAlive hook
@@ -455,28 +530,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}), [internalStartNewSession]);
if (!isConfigured) {
return (
<div className="h-full flex flex-col">
<div className="flex-1 flex items-center justify-center bg-gradient-to-br from-primary/5 to-accent/5">
<div className="text-center space-y-4 max-w-md mx-auto p-6">
<div className="text-4xl mb-4">🤖</div>
<div>
<h3 className="text-lg font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('aiNotConfigured')}</h3>
<p className="text-sm text-muted-foreground mb-4">
{t('configureAI')}
</p>
<p className="text-sm text-muted-foreground">
{t('useMenuForAI')}
</p>
</div>
</div>
</div>
</div>
);
}
const suggestErrorFix = useCallback(async (errorMessage: string) => {
await send(errorMessage, attachedFiles);
}, [send, attachedFiles]);
return (
<div className="h-full flex flex-col relative">
@@ -557,6 +613,28 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
</div>
)}
{/* AI Model Alert */}
{aiModelAlert.hasError && (
<ChatIntervention
message={aiModelAlert.errorMessage || ''}
onDismiss={aiModelAlert.dismiss}
action={aiModelAlert.action}
/>
)}
{/* Console Error Alert */}
{consoleAlert.hasError && (
<ChatIntervention
message={`Console ${consoleAlert.errorCount === 1 ? 'error' : 'errors'} detected in your app. Would you like me to help fix ${consoleAlert.errorCount === 1 ? 'it' : 'them'}?`}
onDismiss={consoleAlert.dismiss}
action={{
label: `Fix ${consoleAlert.errorCount === 1 ? 'error' : 'errors'}`,
onClick: () => suggestErrorFix(consoleAlert.errorSummary || '')
}}
/>
)}
</div>
</div>
@@ -577,9 +655,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="border-t p-4">
{/* Chat Input Container */}
<div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${
isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
@@ -590,10 +667,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={handleFirstInteraction}
placeholder={providerModel.trim() ? t('askToAddFeatures') : t('selectModelFirst')}
onFocus={handleTextareaFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || !providerModel.trim()}
disabled={isLoading || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
@@ -666,6 +749,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
className="w-full"
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={setIsModelSelectorOpen}
/>
</div>
@@ -684,7 +769,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={(!input.trim() && attachedFiles.length === 0) || !providerModel.trim()}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
@@ -695,6 +780,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
</div>
</div>
{/* Onboarding Dialog */}
<OnboardingDialog
open={showOnboarding}
onOpenChange={setShowOnboarding}
/>
</div>
);
});
+73 -11
View File
@@ -3,6 +3,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { useConsoleMessages, addConsoleMessage, clearConsoleMessages, type ConsoleMessage } from '@/hooks/useConsoleMessages';
import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
@@ -29,6 +30,7 @@ import { ConsoleMessage } from '@/types/console';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
import { DeployDialog } from '@/components/DeployDialog';
import { useSearchParams } from 'react-router-dom';
// Get iframe domain from environment variable
const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev';
@@ -97,7 +99,7 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
// Use external state if provided, otherwise use internal state
@@ -107,15 +109,39 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const projectsManager = useProjectsManager();
const { messages: consoleMessages } = useConsoleMessages();
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
const handleBuildProject = () => {
const [searchParams, setSearchParams] = useSearchParams();
const [shouldBuild, setShouldBuild] = useState(false);
const handleBuildProject = useCallback(() => {
buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
});
};
}, [buildProject]);
// Handle "build" URL parameter on initial load
useEffect(() => {
if (searchParams.has('build')) {
setShouldBuild(true);
// Remove the build parameter from URL
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('build');
setSearchParams(newSearchParams, { replace: true });
}
}, [searchParams, setSearchParams]);
// Build automatically if "build" parameter was present
useEffect(() => {
if (shouldBuild && isPreviewable && !isBuildLoading) {
setShouldBuild(false);
handleBuildProject();
}
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
const loadFileContent = useCallback(async (filePath: string) => {
setIsLoading(true);
@@ -255,17 +281,23 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr
normalizedLevel = params.level as ConsoleMessage['level'];
}
const newConsoleMessage: ConsoleMessage = {
id: Date.now(),
level: normalizedLevel,
message: params.message,
};
// Add to global console messages
addConsoleMessage(normalizedLevel, params.message);
setConsoleMessages(prev => [...prev, newConsoleMessage]);
// Also update local state if provided (for external systems)
if (setConsoleMessages !== setInternalConsoleMessages) {
const newMessage: ConsoleMessage = {
id: Date.now() + Math.random(),
level: normalizedLevel,
message: params.message,
timestamp: Date.now(),
};
setConsoleMessages(prev => [...prev, newMessage]);
}
// Log to parent console for debugging with appropriate level
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
}, [setConsoleMessages]);
}, [setConsoleMessages, setInternalConsoleMessages]);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
@@ -397,6 +429,13 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr
}
}, [selectedFile, loadFileContent]);
// Reset selected file when projectId changes
useEffect(() => {
setSelectedFile(null);
setFileContent('');
setMobileCodeView('explorer');
}, [projectId]);
useEffect(() => {
checkForBuiltProject();
}, [checkForBuiltProject]);
@@ -438,7 +477,30 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr
const [isOpen, setIsOpen] = useState(false);
const copiedMessageRef = useRef<number | null>(null);
const [_, setCopyUpdate] = useState(0);
const getLevelColor = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return 'text-red-500';
case 'warn': return 'text-yellow-500';
case 'info': return 'text-blue-500';
case 'debug': return 'text-gray-500';
default: return 'text-gray-400';
}
};
const getLevelIcon = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return '!';
case 'warn': return '⚠';
case 'info': return 'ℹ';
case 'debug': return '🔍';
default: return '•';
}
};
const clearConsole = () => {
clearConsoleMessages();
};
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
try {
await navigator.clipboard.writeText(msg.message);
+174 -12
View File
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
@@ -7,6 +8,7 @@ import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp }
import { useGit } from '@/hooks/useGit';
import { useFS } from '@/hooks/useFS';
import { useToast } from '@/hooks/useToast';
import { useGitStatus } from '@/hooks/useGitStatus';
interface GitCommit {
oid: string;
@@ -45,6 +47,8 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
const { fs } = useFS();
const { git } = useGit();
const { toast } = useToast();
const navigate = useNavigate();
const { data: gitStatus } = useGitStatus(projectId);
const loadGitHistory = useCallback(async () => {
setIsLoading(true);
@@ -213,8 +217,9 @@ ${commitsToRevert.map(c => {
description: `Reverted ${commitsToRevert.length} commit(s) back to ${targetCommit.oid.substring(0, 7)}`,
});
// Reload the git history to show the new commit
await loadGitHistory();
// Close the dialog and navigate to project page with build query parameter
setIsOpen(false);
navigate(`/project/${projectId}?build`);
} catch (err) {
console.error('Failed to rollback:', err);
@@ -226,7 +231,106 @@ ${commitsToRevert.map(c => {
} finally {
setIsRollingBack(null);
}
}, [git, fs, projectId, toast, loadGitHistory]);
}, [git, fs, projectId, toast, navigate, setIsOpen]);
const resetToHead = useCallback(async () => {
if (!fs) return;
setIsRollingBack('HEAD');
try {
const projectPath = `/projects/${projectId}`;
// Get the current HEAD commit
const headCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
// Get all files from HEAD
const headFiles = await git.listFiles({
dir: projectPath,
ref: 'HEAD',
});
// Get current files in working directory
const currentFiles = await git.listFiles({
dir: projectPath,
});
// Remove files that don't exist in HEAD (equivalent to git clean -fd for tracked files)
for (const filepath of currentFiles) {
if (!headFiles.includes(filepath)) {
try {
await fs.unlink(`${projectPath}/${filepath}`);
} catch (err) {
console.warn(`Could not remove ${filepath}:`, err);
}
}
}
// Reset all files to HEAD state (equivalent to git reset --hard HEAD)
for (const filepath of headFiles) {
try {
const { blob } = await git.readBlob({
dir: projectPath,
oid: headCommit,
filepath,
});
// Ensure directory exists
const dirPath = filepath.split('/').slice(0, -1).join('/');
if (dirPath) {
await fs.mkdir(`${projectPath}/${dirPath}`, { recursive: true });
}
// Write the file
await fs.writeFile(`${projectPath}/${filepath}`, blob);
} catch (err) {
console.error(`Failed to reset ${filepath}:`, err);
}
}
// Remove untracked files and directories (equivalent to git clean -fd)
// Get git status to find untracked files
const status = await git.statusMatrix({
dir: projectPath,
});
const untrackedFiles = status
.filter(([, headStatus, workdirStatus, stageStatus]) =>
headStatus === 0 && workdirStatus === 1 && stageStatus === 0
)
.map(([filepath]) => filepath);
for (const filepath of untrackedFiles) {
try {
await fs.unlink(`${projectPath}/${filepath}`);
} catch (err) {
console.warn(`Could not remove untracked file ${filepath}:`, err);
}
}
toast({
title: "Reset successful",
description: "All changes have been discarded and working directory reset to HEAD",
});
// Close the dialog and navigate to project page with build query parameter
setIsOpen(false);
navigate(`/project/${projectId}?build`);
} catch (err) {
console.error('Failed to reset:', err);
toast({
title: "Reset failed",
description: err instanceof Error ? err.message : 'Failed to reset to HEAD',
variant: "destructive",
});
} finally {
setIsRollingBack(null);
}
}, [git, fs, projectId, toast, navigate, setIsOpen]);
useEffect(() => {
if (isOpen) {
@@ -372,15 +476,73 @@ ${commitsToRevert.map(c => {
<div className="flex items-center gap-2 shrink-0">
{index === 0 ? (
// Show "Current" for the most recent commit
<Button
variant="outline"
size="sm"
className="h-7 px-2 text-xs gap-1 cursor-default"
disabled
>
Current
</Button>
// Show "Current" or "Rollback" for the most recent commit
gitStatus?.hasUncommittedChanges ? (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="outline"
size="sm"
className="h-7 px-2 text-xs gap-1 hover:bg-destructive/10 hover:border-destructive/20 hover:text-destructive"
disabled={isRollingBack !== null}
>
<RotateCcw className="h-3 w-3" />
Rollback
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Discard All Changes
</AlertDialogTitle>
<AlertDialogDescription className="space-y-2">
<p>
This will discard all unstaged changes and reset your working directory to the current commit:
</p>
<div className="bg-muted p-3 rounded-md text-sm">
<div className="font-medium break-words">{firstLine}</div>
<div className="text-muted-foreground text-xs mt-1">
{commit.oid.substring(0, 7)} • {formatRelativeTime(commit.commit.author.timestamp)}
</div>
</div>
<p className="text-sm">
This action cannot be undone.
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={resetToHead}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={isRollingBack !== null}
>
{isRollingBack === 'HEAD' ? (
<>
<div className="h-3 w-3 animate-spin rounded-full border border-current border-t-transparent mr-1" />
Discarding...
</>
) : (
<>
<RotateCcw className="h-3 w-3 mr-1" />
Discard Changes
</>
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
) : (
<Button
variant="outline"
size="sm"
className="h-7 px-2 text-xs gap-1 cursor-default"
disabled
>
Current
</Button>
)
) : (
// Show rollback button for older commits
<AlertDialog>
+63
View File
@@ -0,0 +1,63 @@
import React from 'react';
interface QuillySVGProps extends React.SVGProps<SVGSVGElement> {
className?: string;
fillColor?: string;
}
export function QuillySVG({ className = "w-4 h-4", fillColor = "currentColor", ...props }: QuillySVGProps) {
return (
<svg
className={className}
viewBox="140 30 220 420"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
{/* Main quill head/top part */}
<path fill={fillColor} d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z" />
{/* Main quill feather/plume part */}
<path fill={fillColor} d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z" />
{/* Body/torso part */}
<path fill={fillColor} d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z" />
{/* Additional body details */}
<path fill={fillColor} d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z" />
{/* Eyes */}
<path fill={fillColor} d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z" />
<path fill={fillColor} d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z" />
{/* Extended body details */}
<path fill={fillColor} d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z" />
{/* Main body section */}
<path fill={fillColor} d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z" />
{/* Additional body details */}
<path fill={fillColor} d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z" />
{/* Body shading */}
<path fill={fillColor} d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z" />
{/* More body shading */}
<path fill={fillColor} d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z" />
{/* Lower body/legs area */}
<path fill={fillColor} d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z" />
{/* Extended body section */}
<path fill={fillColor} d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z" />
{/* Additional details */}
<path fill={fillColor} d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z" />
{/* Final details */}
<path fill={fillColor} d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z" />
{/* Bottom section */}
<path fill={fillColor} d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z" />
</svg>
);
}
+2 -2
View File
@@ -14,7 +14,7 @@ const ToastViewport = React.forwardRef<
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[480px]",
className
)}
{...props}
@@ -41,7 +41,7 @@ const toastVariants = cva(
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
+2 -4
View File
@@ -10,7 +10,6 @@ interface UseAIChatSessionOptions {
projectId: string;
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools?: Record<string, Tool<unknown>>;
systemPrompt?: string;
maxSteps?: number;
onUpdateMetadata?: (title: string, description: string) => void;
}
@@ -30,7 +29,6 @@ export function useAIChat({
projectId,
tools = {},
customTools = {},
systemPrompt,
maxSteps = 50,
onUpdateMetadata
}: UseAIChatSessionOptions) {
@@ -46,14 +44,14 @@ export function useAIChat({
const initSession = useCallback(async () => {
// Load or update session
const session = await sessionManager.loadSession(projectId, tools, customTools, systemPrompt, maxSteps);
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
// Initialize individual state variables from existing session
setMessages([...session.messages]);
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
setIsLoading(session.isLoading);
setTotalCost(session.totalCost || 0);
setLastInputTokens(session.lastInputTokens || 0);
}, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps]);
}, [sessionManager, projectId, tools, customTools, maxSteps]);
// Initialize session
useEffect(() => {
+5 -7
View File
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
import { z } from 'zod';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { AIProvider } from '@/contexts/AISettingsContext';
// Zod schemas for the two possible response formats
const creditsResponseV1Schema = z.object({
@@ -31,18 +32,14 @@ export interface CreditsResponse {
* @param connection - The AI connection configuration
* @returns Query result with credits information
*/
export function useAICredits(providerId: string, connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
}) {
export function useAICredits(provider: AIProvider) {
const { user } = useCurrentUser();
return useQuery({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
queryFn: async (): Promise<CreditsResponse> => {
try {
const ai = createAIClient(connection, user);
const ai = createAIClient(provider, user);
const data = await ai.get('/credits');
// Validate and normalize the response
@@ -68,5 +65,6 @@ export function useAICredits(providerId: string, connection: {
retry: false, // Don't retry as not all providers support this endpoint
refetchOnWindowFocus: false,
staleTime: 5 * 60 * 1000, // 5 minutes
enabled: provider.id === 'shakespeare' && !!user,
});
}
+12 -13
View File
@@ -42,9 +42,8 @@ describe('useAIProjectId', () => {
// Mock parseProviderModel
mockParseProviderModel.mockReturnValue({
provider: 'openai',
provider: { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
model: 'gpt-4',
connection: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
});
// Mock createAIClient
@@ -86,7 +85,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -110,7 +109,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -134,7 +133,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -157,7 +156,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -170,7 +169,7 @@ describe('useAIProjectId', () => {
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
]);
expect(mockCreateAIClient).toHaveBeenCalledWith(
{ apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
undefined
);
});
@@ -188,7 +187,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -241,7 +240,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -296,7 +295,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -346,7 +345,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -396,7 +395,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -453,7 +452,7 @@ describe('useAIProjectId', () => {
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
+2 -2
View File
@@ -28,8 +28,8 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
try {
// Initialize OpenAI client
const { model, connection } = parseProviderModel(providerModel, settings.providers);
const openai = createAIClient(connection, user);
const { model, provider } = parseProviderModel(providerModel, settings.providers);
const openai = createAIClient(provider, user);
const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`;
+79
View File
@@ -0,0 +1,79 @@
import { useState, useCallback, useEffect } from 'react';
export interface ConsoleMessage {
id: number;
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
timestamp: number;
}
// Global state for console messages
let globalConsoleMessages: ConsoleMessage[] = [];
const listeners: Set<(messages: ConsoleMessage[]) => void> = new Set();
const notifyListeners = () => {
listeners.forEach(listener => listener([...globalConsoleMessages]));
};
export const useConsoleMessages = () => {
const [messages, setMessages] = useState<ConsoleMessage[]>(globalConsoleMessages);
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
const newMessage: ConsoleMessage = {
id: Date.now() + Math.random(), // Ensure uniqueness
level,
message,
timestamp: Date.now(),
};
globalConsoleMessages = [...globalConsoleMessages, newMessage];
notifyListeners();
}, []);
const clearMessages = useCallback(() => {
globalConsoleMessages = [];
notifyListeners();
}, []);
const getErrorsSince = useCallback((timestamp: number) => {
return globalConsoleMessages.filter(
msg => msg.level === 'error' && msg.timestamp > timestamp
);
}, []);
// Subscribe to global state changes
useEffect(() => {
const listener = (newMessages: ConsoleMessage[]) => {
setMessages(newMessages);
};
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}, []);
return {
messages,
addMessage,
clearMessages,
getErrorsSince,
};
};
// Export functions for external use (like PreviewPane)
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
const newMessage: ConsoleMessage = {
id: Date.now() + Math.random(),
level,
message,
timestamp: Date.now(),
};
globalConsoleMessages = [...globalConsoleMessages, newMessage];
notifyListeners();
};
export const clearConsoleMessages = () => {
globalConsoleMessages = [];
notifyListeners();
};
+153
View File
@@ -0,0 +1,153 @@
import { useState, useCallback, useMemo } from 'react';
import type { AIMessage } from '@/lib/SessionManager';
import { useConsoleMessages } from './useConsoleMessages';
export interface ConsoleErrorAlert {
hasError: boolean;
errorSummary: string | null;
errorCount: number;
dismiss: () => void;
}
export const useConsoleErrorAlert = (
aiMessages: AIMessage[],
isBuilding?: boolean,
isLoading?: boolean
): ConsoleErrorAlert => {
const { messages } = useConsoleMessages();
const [dismissedErrorSummary, setDismissedErrorSummary] = useState<string>('');
const { hasError, errorSummary, errorCount } = useMemo(() => {
// Don't show alerts while building or AI is working
if (isBuilding || isLoading) {
return { hasError: false, errorSummary: null, errorCount: 0 };
}
// Find the timestamp of the last AI assistant message
// Since AIMessage doesn't have timestamps, we'll use a different approach:
// Only show errors if there are any errors at all and no recent user activity
const lastMessage = aiMessages[aiMessages.length - 1];
const isLastMessageFromAssistant = lastMessage?.role === 'assistant';
// Only show console errors if the last message was from assistant (AI just responded)
if (!isLastMessageFromAssistant) {
return { hasError: false, errorSummary: null, errorCount: 0 };
}
// Get recent errors (last 10 seconds worth to catch errors from recent AI actions)
const recentTimeThreshold = Date.now() - (10 * 1000); // 10 seconds ago
const recentErrors = messages.filter(msg =>
msg.level === 'error' &&
msg.timestamp > recentTimeThreshold
);
if (recentErrors.length === 0) {
return { hasError: false, errorSummary: null, errorCount: 0 };
}
// Just return the raw error messages, no formatting
const summary = recentErrors.slice(-3).map(e => e.message).join('\n');
return {
hasError: dismissedErrorSummary !== summary,
errorSummary: summary,
errorCount: recentErrors.length
};
}, [messages, dismissedErrorSummary, aiMessages, isBuilding, isLoading]);
const dismiss = useCallback(() => {
if (errorSummary) {
setDismissedErrorSummary(errorSummary);
}
}, [errorSummary]);
return {
hasError,
errorSummary,
errorCount,
dismiss
};
};
export interface AIModelErrorAlert {
hasError: boolean;
errorMessage: string | null;
errorType: 'warn' | 'error' | null;
action?: { label: string; onClick: () => void };
dismiss: () => void;
}
export const useAIModelErrorAlert = (
messages: AIMessage[],
onNewChat?: () => void,
onChangeModel?: () => void
): AIModelErrorAlert => {
const [dismissedAlertKey, setDismissedAlertKey] = useState<string>('');
const { hasError, errorMessage, errorType, action } = useMemo(() => {
const lastMessage = messages[messages.length - 1];
// Only show AI model alerts if the last message is from the assistant
// This ensures we don't show stale alerts when user continues the conversation
if (!lastMessage || lastMessage.role !== 'assistant') {
return { hasError: false, errorMessage: null, errorType: null, action: undefined };
}
const content = typeof lastMessage.content === 'string' ? lastMessage.content : '';
// Define error patterns with actions
const errorPatterns = [
{
test: (content: string) => /AI service error: 422/.test(content) || /Provider returned error/.test(content),
type: 'error' as const,
message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.',
action: onChangeModel ? { label: 'Change model', onClick: onChangeModel } : undefined
},
{
test: (content: string) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content),
type: 'warn' as const,
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
action: onNewChat ? { label: 'New chat', onClick: onNewChat } : undefined
},
{
test: (content: string) => /rate limit/i.test(content) || /too many requests/i.test(content),
type: 'warn' as const,
message: 'You\'re sending requests too quickly. Please wait a moment before trying again.'
}
];
for (const pattern of errorPatterns) {
if (pattern.test(content)) {
const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
const alertKey = `${pattern.message}_${messageContent.slice(0, 50)}_${Date.now()}`;
return {
hasError: dismissedAlertKey !== alertKey,
errorMessage: pattern.message,
errorType: pattern.type,
action: pattern.action,
alertKey
};
}
}
return { hasError: false, errorMessage: null, errorType: null, action: undefined };
}, [messages, dismissedAlertKey, onNewChat, onChangeModel]);
const dismiss = useCallback(() => {
const lastMessage = messages[messages.length - 1];
if (errorMessage && lastMessage) {
const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
const alertKey = `${errorMessage}_${messageContent.slice(0, 50)}_${Date.now()}`;
setDismissedAlertKey(alertKey);
}
}, [errorMessage, messages]);
return {
hasError,
errorMessage,
errorType,
action,
dismiss
};
};
+1 -1
View File
@@ -72,7 +72,7 @@ export function useGitHubOAuth() {
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: window.location.origin + '/oauth/github',
scope: 'repo',
scope: 'repo workflow',
state: state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
+6 -7
View File
@@ -45,9 +45,8 @@ export function useProviderModels(): ModelFetchResult {
// Fetch models from each configured provider in parallel
const providerPromises = settings.providers.map(async (provider) => {
const { id: providerKey, ...connection } = provider;
try {
const openai = createAIClient(connection, user);
const openai = createAIClient(provider, user);
// Fetch models with timeout
try {
@@ -59,8 +58,8 @@ export function useProviderModels(): ModelFetchResult {
const providerModels = response.data.map((model) => {
const providerModel: ProviderModel = {
id: model.id,
provider: providerKey,
fullId: `${providerKey}/${model.id}`,
provider: provider.id,
fullId: `${provider.id}/${model.id}`,
};
if ('name' in model && typeof model.name === 'string') {
@@ -95,16 +94,16 @@ export function useProviderModels(): ModelFetchResult {
return providerModels;
} catch (fetchError) {
if (fetchError instanceof Error && fetchError.name === 'AbortError') {
errors.push(`${providerKey}: Request timeout`);
errors.push(`${provider.id}: Request timeout`);
} else {
throw fetchError;
}
return [];
}
} catch (providerError) {
console.warn(`Failed to fetch models from ${providerKey}:`, providerError);
console.warn(`Failed to fetch models from ${provider.id}:`, providerError);
errors.push(
`${providerKey}: ${
`${provider.id}: ${
providerError instanceof Error ? providerError.message : 'Unknown error'
}`
);
+122 -1
View File
@@ -59,7 +59,7 @@ class MockFS implements JSRuntimeFS {
error.code = 'ENOENT';
throw error;
}
const entries: string[] = [];
// Find subdirectories
@@ -125,6 +125,63 @@ class MockFS implements JSRuntimeFS {
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
// Handle both files and directories
if (this.files.has(oldPath)) {
const content = this.files.get(oldPath);
this.files.delete(oldPath);
this.files.set(newPath, content!);
}
if (this.dirs.has(oldPath)) {
this.dirs.delete(oldPath);
this.dirs.add(newPath);
// Also move all subdirectories and files
const itemsToMove: Array<{ oldPath: string; newPath: string; isDir: boolean }> = [];
// Collect directories to move
for (const dir of this.dirs) {
if (dir.startsWith(oldPath + '/')) {
const relativePath = dir.slice(oldPath.length);
itemsToMove.push({
oldPath: dir,
newPath: newPath + relativePath,
isDir: true
});
}
}
// Collect files to move
for (const file of this.files.keys()) {
if (file.startsWith(oldPath + '/')) {
const relativePath = file.slice(oldPath.length);
itemsToMove.push({
oldPath: file,
newPath: newPath + relativePath,
isDir: false
});
}
}
// Move all items
for (const item of itemsToMove) {
if (item.isDir) {
this.dirs.delete(item.oldPath);
this.dirs.add(item.newPath);
} else {
const content = this.files.get(item.oldPath);
this.files.delete(item.oldPath);
this.files.set(item.newPath, content!);
}
}
}
}
async lstat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean; mtimeMs?: number }> {
return this.stat(path);
}
}
describe('ProjectsManager', () => {
@@ -211,4 +268,68 @@ describe('ProjectsManager', () => {
expect(project).toBeNull();
});
});
describe('renameProject', () => {
it('should rename a project directory', async () => {
await projectsManager.init();
// Create a project
await fs.mkdir('/projects/old-name');
await fs.writeFile('/projects/old-name/package.json', '{}');
// Verify the project exists
const originalProject = await projectsManager.getProject('old-name');
expect(originalProject).not.toBeNull();
// Rename the project
const renamedProject = await projectsManager.renameProject('old-name', 'new-name');
// Verify the renamed project
expect(renamedProject.id).toBe('new-name');
expect(renamedProject.name).toBe('new-name');
expect(renamedProject.path).toBe('/projects/new-name');
// Verify old project no longer exists
const oldProject = await projectsManager.getProject('old-name');
expect(oldProject).toBeNull();
// Verify new project exists
const newProject = await projectsManager.getProject('new-name');
expect(newProject).not.toBeNull();
expect(newProject?.id).toBe('new-name');
});
it('should throw error when old project does not exist', async () => {
await projectsManager.init();
await expect(projectsManager.renameProject('non-existent', 'new-name'))
.rejects.toThrow('Project with ID "non-existent" does not exist');
});
it('should throw error when new project name already exists', async () => {
await projectsManager.init();
// Create two projects
await fs.mkdir('/projects/project-1');
await fs.mkdir('/projects/project-2');
await expect(projectsManager.renameProject('project-1', 'project-2'))
.rejects.toThrow('Project with ID "project-2" already exists');
});
it('should validate and normalize project names', async () => {
await projectsManager.init();
// Create a project
await fs.mkdir('/projects/old-name');
// Try to rename with invalid characters
await expect(projectsManager.renameProject('old-name', 'New Name With Spaces'))
.rejects.toThrow('Project name must contain only lowercase letters, numbers, and hyphens');
// Try to rename with empty name
await expect(projectsManager.renameProject('old-name', ''))
.rejects.toThrow('Project name cannot be empty');
});
});
});
+44
View File
@@ -264,6 +264,50 @@ export class ProjectsManager {
await this.deleteDirectory(projectPath);
}
async renameProject(oldId: string, newId: string): Promise<Project> {
// Validate that the old project exists
const oldProject = await this.getProject(oldId);
if (!oldProject) {
throw new Error(`Project with ID "${oldId}" does not exist`);
}
// Validate that the new ID doesn't already exist
if (await this.projectExists(newId)) {
throw new Error(`Project with ID "${newId}" already exists`);
}
// Validate the new ID format (same rules as generateUniqueProjectId)
const validatedNewId = newId
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
if (validatedNewId !== newId) {
throw new Error(`Project name must contain only lowercase letters, numbers, and hyphens`);
}
if (!validatedNewId) {
throw new Error(`Project name cannot be empty`);
}
const oldPath = `${this.dir}/${oldId}`;
const newPath = `${this.dir}/${newId}`;
// Rename the directory
await this.fs.rename(oldPath, newPath);
// Return the updated project object
const stats = await this.fs.stat(newPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
return {
id: newId,
name: this.formatProjectName(newId),
path: newPath,
lastModified: timestamp,
};
}
private async deleteDirectory(dirPath: string): Promise<void> {
const files = await this.fs.readdir(dirPath);
+47 -19
View File
@@ -6,6 +6,8 @@ import { createAIClient } from './ai-client';
import type { Tool } from './tools/Tool';
import type { NUser } from '@nostrify/react/login';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { makeSystemPrompt } from './system';
import { NostrMetadata } from '@nostrify/nostrify';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
role: 'assistant';
@@ -18,7 +20,6 @@ export interface SessionState {
projectId: string;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools: Record<string, Tool<unknown>>;
systemPrompt?: string;
maxSteps?: number;
messages: AIMessage[];
streamingMessage?: {
@@ -55,13 +56,13 @@ export class SessionManager {
private fs: JSRuntimeFS;
private aiSettings: { providers: AIProvider[] };
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getCurrentUser?: () => NUser | undefined;
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
constructor(
fs: JSRuntimeFS,
aiSettings: { providers: AIProvider[] },
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getCurrentUser?: () => NUser | undefined
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
) {
this.fs = fs;
this.aiSettings = aiSettings;
@@ -76,7 +77,6 @@ export class SessionManager {
projectId: string,
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>,
customTools: Record<string, Tool<unknown>>,
systemPrompt?: string,
maxSteps?: number
): Promise<SessionState> {
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
@@ -98,7 +98,6 @@ export class SessionManager {
projectId,
tools,
customTools,
systemPrompt,
maxSteps,
isLoading: false,
lastActivity: new Date(),
@@ -114,7 +113,6 @@ export class SessionManager {
session.tools = tools;
session.customTools = customTools;
session.systemPrompt = systemPrompt;
session.maxSteps = maxSteps;
this.sessions.set(projectId, session);
@@ -203,12 +201,12 @@ export class SessionManager {
try {
// Parse provider and model
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const connectionConfig = parsed.connection;
const modelName = parsed.model;
const provider = parsed.provider;
const model = parsed.model;
// Initialize OpenAI client
const currentUser = this.getCurrentUser?.();
const openai = createAIClient(connectionConfig, currentUser);
const { user, metadata } = this.getCurrentUser?.() ?? {};
const openai = createAIClient(provider, user);
let stepCount = 0;
const maxSteps = session.maxSteps || 50;
@@ -230,14 +228,25 @@ export class SessionManager {
tool_calls: undefined
};
const systemPrompt = await makeSystemPrompt({
cwd: `/projects/${projectId}`,
fs: this.fs,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(session.tools),
user,
metadata,
});
// Prepare messages for AI
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = session.systemPrompt
? [{ role: 'system', content: session.systemPrompt }, ...session.messages]
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages;
// Prepare completion options
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
model: modelName,
model,
messages,
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined,
@@ -258,7 +267,7 @@ export class SessionManager {
let finishReason: string | null = null;
// Process the stream
let usage: { prompt_tokens: number; completion_tokens: number } | undefined;
let usage: { prompt_tokens: number; completion_tokens: number; cost?: number } | undefined;
for await (const chunk of stream) {
// Check if session was cancelled
if (!session.isLoading) break;
@@ -319,13 +328,25 @@ export class SessionManager {
// Capture usage data if available (some providers include it in the final chunk)
if (chunk.usage) {
const cost = 'cost' in chunk.usage && typeof chunk.usage.cost === 'number'
? chunk.usage.cost
: undefined;
usage = {
prompt_tokens: chunk.usage.prompt_tokens || 0,
completion_tokens: chunk.usage.completion_tokens || 0
completion_tokens: chunk.usage.completion_tokens || 0,
cost,
};
}
}
// Fix tool calls with empty arguments
for (const toolCall of accumulatedToolCalls) {
if (toolCall.type === 'function') {
toolCall.function.arguments = toolCall.function.arguments || '{}';
}
}
// Create final assistant message
const assistantMessage: AIMessage = {
role: 'assistant',
@@ -461,20 +482,28 @@ export class SessionManager {
/**
* Update session cost and context usage based on usage data
*/
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void {
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
if (!this.getProviderModels) return;
const session = this.sessions.get(projectId);
if (!session) return;
// If provider gives direct cost, use it
if (typeof usage.cost === 'number') {
session.totalCost = (session.totalCost || 0) + usage.cost;
this.emit('costUpdated', projectId, session.totalCost);
return;
}
// Otherwise, get the cost from the models endpoint
try {
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const modelName = parsed.model;
const providerName = parsed.provider;
const provider = parsed.provider;
// Find the model in provider models to get pricing and context length
const models = this.getProviderModels();
const model = models.find(m => m.id === modelName && m.provider === providerName);
const model = models.find(m => m.id === modelName && m.provider === provider.id);
// Update input tokens for context usage tracking
session.lastInputTokens = usage.prompt_tokens;
@@ -491,7 +520,6 @@ export class SessionManager {
// Update session total cost
session.totalCost = (session.totalCost || 0) + requestCost;
this.emit('costUpdated', projectId, session.totalCost);
} catch (error) {
console.warn('Failed to calculate session cost:', error);
+30 -11
View File
@@ -1,33 +1,52 @@
import OpenAI from 'openai';
import { NIP98Client } from '@nostrify/nostrify';
import type { NUser } from '@nostrify/react/login';
import type { AIProvider } from '@/contexts/AISettingsContext';
/**
* Create an OpenAI client instance with the appropriate configuration.
* If the connection requires Nostr authentication (NIP-98), it will use
* the NIP98Client for authenticated requests.
*/
export function createAIClient(connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
}, user?: NUser): OpenAI {
export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
baseURL: connection.baseURL,
apiKey: connection.apiKey ?? '',
baseURL: provider.baseURL,
apiKey: provider.apiKey ?? '',
dangerouslyAllowBrowser: true,
defaultHeaders: {
// https://openrouter.ai/docs/app-attribution
'HTTP-Referer': 'https://shakespeare.diy',
'X-Title': 'Shakespeare',
},
};
let openai: OpenAI;
// If Nostr authentication is required and we have a user, use NIP-98
if (connection.nostr && user?.signer) {
if (provider.nostr && user?.signer) {
const nip98Client = new NIP98Client({ signer: user.signer });
return new OpenAI({
openai = new OpenAI({
...baseConfig,
fetch: (input, init) => nip98Client.fetch(input, init),
});
} else {
// Standard OpenAI client
openai = new OpenAI(baseConfig);
}
// Standard OpenAI client
return new OpenAI(baseConfig);
const createCompletion: typeof openai.chat.completions.create
= openai.chat.completions.create.bind(openai.chat.completions);
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
// OpenRouter usage accounting
// https://openrouter.ai/docs/use-cases/usage-accounting
if (provider.id === 'openrouter') {
(body as { usage?: { include?: boolean } }).usage = { include: true };
}
return createCompletion(body, options);
}) as typeof createCompletion;
return openai;
}
+229
View File
@@ -0,0 +1,229 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { HexdumpCommand } from './hexdump';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
unlink: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
readlink: vi.fn(),
symlink: vi.fn(),
});
describe('HexdumpCommand', () => {
let mockFS: JSRuntimeFS;
let command: HexdumpCommand;
const testCwd = '/test/dir';
beforeEach(() => {
mockFS = createMockFS();
command = new HexdumpCommand(mockFS);
});
it('should have correct name and description', () => {
expect(command.name).toBe('hexdump');
expect(command.description).toBe('Display file contents in hexadecimal format');
expect(command.usage).toBe('hexdump [-C] [-n length] [-s skip] [file...]');
});
it('should show error when no file is specified', async () => {
const result = await command.execute([], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('missing file operand');
});
it('should show error for non-existent file', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await command.execute(['nonexistent.txt'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No such file or directory');
});
it('should show error for directory', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
const result = await command.execute(['testdir'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Is a directory');
});
it('should display hexdump in default format', async () => {
const content = 'Hello, World!\n';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('0000000');
expect(result.stdout).toContain('000000e'); // Final offset
});
it('should display hexdump in canonical format with -C', async () => {
const content = 'Hello, World!\n';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['-C', 'test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000000');
expect(result.stdout).toContain('|Hello, World!');
expect(result.stdout).toContain('|'); // Should have ASCII representation
});
it('should handle -n length option', async () => {
const content = 'Hello, World!\nThis is a longer line.';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['-C', '-n', '5', 'test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('|Hello|');
expect(result.stdout).not.toContain('World');
});
it('should handle -s skip option', async () => {
const content = 'Hello, World!\n';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['-C', '-s', '7', 'test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000007');
expect(result.stdout).toContain('|World!');
expect(result.stdout).not.toContain('Hello');
});
it('should handle -n and -s together', async () => {
const content = 'Hello, World!\n';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['-C', '-s', '7', '-n', '5', 'test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000007');
expect(result.stdout).toContain('|World|');
expect(result.stdout).not.toContain('Hello');
expect(result.stdout).not.toContain('!');
});
it('should show error for invalid -n value', async () => {
const result = await command.execute(['-n', 'invalid'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('invalid length');
});
it('should show error for invalid -s value', async () => {
const result = await command.execute(['-s', 'invalid'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('invalid skip offset');
});
it('should show error for missing -n argument', async () => {
const result = await command.execute(['-n'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('option requires an argument -- n');
});
it('should show error for missing -s argument', async () => {
const result = await command.execute(['-s'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('option requires an argument -- s');
});
it('should show error for invalid option', async () => {
const result = await command.execute(['-x'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('invalid option -- x');
});
it('should handle multiple files', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce(Buffer.from('ABC'))
.mockResolvedValueOnce(Buffer.from('XYZ'));
const result = await command.execute(['-C', 'file1.txt', 'file2.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('==> file1.txt <==');
expect(result.stdout).toContain('==> file2.txt <==');
expect(result.stdout).toContain('|ABC|');
expect(result.stdout).toContain('|XYZ|');
});
it('should handle piped input', async () => {
const input = 'Hello, World!';
const result = await command.execute(['-C'], testCwd, input);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000000');
expect(result.stdout).toContain('|Hello, World!|');
});
it('should handle binary data correctly', async () => {
// Create binary data with non-printable characters
const binaryData = Buffer.from([0x00, 0x01, 0x02, 0x7F, 0x80, 0xFF, 0x41, 0x42, 0x43]);
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(binaryData);
const result = await command.execute(['-C', 'binary.dat'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000000');
expect(result.stdout).toContain('00 01 02 7f 80 ff 41 42 43');
expect(result.stdout).toContain('|......ABC|'); // Non-printable chars shown as dots
});
it('should handle empty file', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(''));
const result = await command.execute(['-C', 'empty.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe(''); // No output for empty file
});
it('should handle skip beyond file length', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('Hi'));
const result = await command.execute(['-C', '-s', '10', 'short.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe(''); // No output since skip is beyond file
});
});
+272
View File
@@ -0,0 +1,272 @@
import { join } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'hexdump' command
* Display file contents in hexadecimal format
*/
export class HexdumpCommand implements ShellCommand {
name = 'hexdump';
description = 'Display file contents in hexadecimal format';
usage = 'hexdump [-C] [-n length] [-s skip] [file...]';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
// Parse command line options
const options = this.parseOptions(args);
if (options.error) {
return createErrorResult(options.error);
}
// If input is provided (from pipe), process it
if (input !== undefined) {
const buffer = Buffer.from(input, 'utf8');
const output = this.formatHexdump(buffer, options);
return createSuccessResult(output);
}
// If no files specified, show usage
if (options.files.length === 0) {
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
}
try {
const outputs: string[] = [];
for (const filePath of options.files) {
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
// It's an absolute path - use it directly
absolutePath = filePath;
} else {
// It's a relative path - resolve it relative to the current working directory
absolutePath = join(cwd, filePath);
}
// Check if path exists and is a file
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
// Read file content as binary
const content = await this.fs.readFile(absolutePath);
const buffer = Buffer.from(content);
// Format the hexdump
const hexOutput = this.formatHexdump(buffer, options);
// Add filename header if multiple files
if (options.files.length > 1) {
outputs.push(`==> ${filePath} <==`);
outputs.push(hexOutput);
} else {
outputs.push(hexOutput);
}
} catch (error) {
// Handle file not found or permission errors
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${filePath}: Unknown error`);
}
}
}
const result = outputs.join('\n');
return createSuccessResult(result);
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Parse command line options
*/
private parseOptions(args: string[]): {
canonical: boolean;
length?: number;
skip: number;
files: string[];
error?: string;
} {
const options = {
canonical: false,
length: undefined as number | undefined,
skip: 0,
files: [] as string[],
};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-C') {
options.canonical = true;
} else if (arg === '-n') {
// Next argument should be the length
if (i + 1 >= args.length) {
return { ...options, error: `${this.name}: option requires an argument -- n` };
}
const lengthStr = args[++i];
const length = parseInt(lengthStr, 10);
if (isNaN(length) || length < 0) {
return { ...options, error: `${this.name}: invalid length: ${lengthStr}` };
}
options.length = length;
} else if (arg === '-s') {
// Next argument should be the skip offset
if (i + 1 >= args.length) {
return { ...options, error: `${this.name}: option requires an argument -- s` };
}
const skipStr = args[++i];
const skip = parseInt(skipStr, 10);
if (isNaN(skip) || skip < 0) {
return { ...options, error: `${this.name}: invalid skip offset: ${skipStr}` };
}
options.skip = skip;
} else if (arg.startsWith('-')) {
return { ...options, error: `${this.name}: invalid option -- ${arg.slice(1)}` };
} else {
// It's a filename
options.files.push(arg);
}
}
return options;
}
/**
* Format buffer content as hexdump
*/
private formatHexdump(buffer: Buffer, options: {
canonical: boolean;
length?: number;
skip: number;
}): string {
const lines: string[] = [];
const bytesPerLine = 16;
// Apply skip offset
const startOffset = options.skip;
if (startOffset >= buffer.length) {
return ''; // Nothing to display
}
// Apply length limit
let endOffset = buffer.length;
if (options.length !== undefined) {
endOffset = Math.min(startOffset + options.length, buffer.length);
}
for (let offset = startOffset; offset < endOffset; offset += bytesPerLine) {
const lineEnd = Math.min(offset + bytesPerLine, endOffset);
const lineBytes = buffer.subarray(offset, lineEnd);
if (options.canonical) {
// Canonical format (-C): address, hex bytes, ASCII
lines.push(this.formatCanonicalLine(offset, lineBytes));
} else {
// Default format: address followed by 16-bit words in hex
lines.push(this.formatDefaultLine(offset, lineBytes));
}
}
// Add final offset line if we have data
if (endOffset > startOffset) {
const finalOffset = endOffset;
lines.push(this.formatOffsetLine(finalOffset));
}
return lines.join('\n');
}
/**
* Format a line in canonical format (-C option)
*/
private formatCanonicalLine(offset: number, bytes: Buffer): string {
const addressStr = offset.toString(16).padStart(8, '0');
// Format hex bytes (2 groups of 8 bytes each)
const group1: string[] = [];
const group2: string[] = [];
for (let i = 0; i < 16; i++) {
const hexByte = i < bytes.length
? bytes[i].toString(16).padStart(2, '0')
: ' ';
if (i < 8) {
group1.push(hexByte);
} else {
group2.push(hexByte);
}
}
const hexStr = group1.join(' ') + ' ' + group2.join(' ');
// Format ASCII representation
let asciiStr = '';
for (let i = 0; i < bytes.length; i++) {
const byte = bytes[i];
if (byte >= 32 && byte <= 126) {
// Printable ASCII character
asciiStr += String.fromCharCode(byte);
} else {
// Non-printable character
asciiStr += '.';
}
}
return `${addressStr} ${hexStr} |${asciiStr}|`;
}
/**
* Format a line in default format
*/
private formatDefaultLine(offset: number, bytes: Buffer): string {
const addressStr = offset.toString(16).padStart(7, '0');
// Group bytes into 16-bit words (little-endian)
const words: string[] = [];
for (let i = 0; i < bytes.length; i += 2) {
if (i + 1 < bytes.length) {
// Full 16-bit word (little-endian)
const word = (bytes[i + 1] << 8) | bytes[i];
words.push(word.toString(16).padStart(4, '0'));
} else {
// Partial word (only one byte)
const word = bytes[i];
words.push(word.toString(16).padStart(2, '0') + ' ');
}
}
return `${addressStr} ${words.join(' ')}`;
}
/**
* Format the final offset line
*/
private formatOffsetLine(offset: number): string {
return offset.toString(16).padStart(7, '0');
}
}
+3 -1
View File
@@ -13,6 +13,7 @@ export { FindCommand } from './find';
export { GitCommand } from './git';
export { GrepCommand } from './grep';
export { HeadCommand } from './head';
export { HexdumpCommand } from './hexdump';
export { LsCommand } from './ls';
export { MkdirCommand } from './mkdir';
export { MvCommand } from './mv';
@@ -25,4 +26,5 @@ export { TrCommand } from './tr';
export { UniqCommand } from './uniq';
export { WcCommand } from './wc';
export { WhoamiCommand } from './whoami';
export { WhichCommand } from './which';
export { WhichCommand } from './which';
export { UnzipCommand } from './unzip';
+303
View File
@@ -0,0 +1,303 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import JSZip from 'jszip';
import { UnzipCommand } from './unzip';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
unlink: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
readlink: vi.fn(),
symlink: vi.fn(),
});
describe('UnzipCommand', () => {
let mockFS: JSRuntimeFS;
let command: UnzipCommand;
beforeEach(() => {
mockFS = createMockFS();
command = new UnzipCommand(mockFS);
});
const createTestZip = async (files: Record<string, string | Uint8Array>): Promise<Uint8Array> => {
const zip = new JSZip();
for (const [path, content] of Object.entries(files)) {
if (path.endsWith('/')) {
zip.folder(path.slice(0, -1));
} else {
zip.file(path, content);
}
}
return zip.generateAsync({ type: 'uint8array' });
};
it('should show usage when no arguments provided', async () => {
const result = await command.execute([], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('missing archive operand');
expect(result.stderr).toContain('Usage:');
});
it('should show error for invalid options', async () => {
const result = await command.execute(['-x', 'test.zip'], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("invalid option '-x'");
});
it('should show error for non-existent archive', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await command.execute(['nonexistent.zip'], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No such file or directory');
});
it('should show error when trying to unzip a directory', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
const result = await command.execute(['testdir'], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Is a directory');
});
it('should list archive contents with -l option', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World',
'dir1/': '',
'dir1/file2.txt': 'Test content'
});
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
const result = await command.execute(['-l', 'test.zip'], '/home');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Archive: test.zip');
expect(result.stdout).toContain('file1.txt');
expect(result.stdout).toContain('dir1/');
expect(result.stdout).toContain('dir1/file2.txt');
});
it('should extract files to current directory', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
// Mock file operations - keep it simple
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await command.execute(['test.zip'], '/home');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Archive: test.zip');
expect(result.stdout).toContain('inflating: file1.txt');
// Verify writeFile was called for extracted files
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
});
it('should handle command line options correctly', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
// Test -d option
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await command.execute(['-d', 'extract', 'test.zip'], '/home');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('inflating: file1.txt');
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/extract/file1.txt', expect.any(Uint8Array));
});
it('should handle overwrite option', async () => {
const zipData = await createTestZip({
'file1.txt': 'New content'
});
// Mock file exists scenario
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
// Without -o option, should fail
const resultWithoutOverwrite = await command.execute(['test.zip'], '/home');
expect(resultWithoutOverwrite.exitCode).toBe(1);
expect(resultWithoutOverwrite.stderr).toContain('File exists (use -o to overwrite)');
// Reset mocks
vi.clearAllMocks();
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
// With -o option, should succeed
const resultWithOverwrite = await command.execute(['-o', 'test.zip'], '/home');
expect(resultWithOverwrite.exitCode).toBe(0);
expect(resultWithOverwrite.stdout).toContain('inflating: file1.txt');
});
it('should prevent extraction outside allowed directories', async () => {
// Since JSZip normalizes paths during creation, we'll test the security logic
// by mocking the internal zip.files object to simulate a malicious ZIP
const zipData = await createTestZip({
'normal.txt': 'safe content'
});
// Mock the zip loading to return a ZIP with malicious paths
const originalLoadAsync = JSZip.loadAsync;
vi.spyOn(JSZip, 'loadAsync').mockImplementation(async () => {
const zip = new JSZip();
// Simulate malicious ZIP file entries that would escape the directory
(zip as unknown as { files: Record<string, { name: string; dir: boolean; async: () => Promise<Uint8Array> }> }).files = {
'../../../etc/passwd': {
name: '../../../etc/passwd',
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])),
},
'../../outside.txt': {
name: '../../outside.txt',
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])),
},
'normal.txt': {
name: 'normal.txt',
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])),
}
};
return zip;
});
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await command.execute(['test.zip'], '/home/user');
// Should return error because some files were skipped
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Path is outside allowed directories');
expect(result.stderr).toContain('../../../etc/passwd');
expect(result.stderr).toContain('../../outside.txt');
// Should only extract the safe file
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/user/normal.txt', expect.any(Uint8Array));
expect(mockFS.writeFile).toHaveBeenCalledTimes(1);
// Restore the original method
JSZip.loadAsync = originalLoadAsync;
});
it('should allow extraction to /tmp directory', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockRejectedValueOnce(new Error('ENOENT')) // extraction dir doesn't exist
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
const result = await command.execute(['-d', '/tmp', 'test.zip'], '/home/user');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('inflating: file1.txt');
expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/file1.txt', expect.any(Uint8Array));
});
it('should reject extraction directory outside allowed paths', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
// Mock that the archive exists and provide zip data
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
const result = await command.execute(['-d', '/etc', 'test.zip'], '/home/user');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("extraction directory '/etc' is outside allowed paths");
});
it('should support quiet mode with -q flag', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World',
'dir1/': '',
'dir1/file2.txt': 'Test content'
});
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
const result = await command.execute(['-q', 'test.zip'], '/home');
expect(result.exitCode).toBe(0);
// In quiet mode, should not show archive header or extraction messages
expect(result.stdout).toBe('');
// But files should still be extracted
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/dir1/file2.txt', expect.any(Uint8Array));
});
});
+220
View File
@@ -0,0 +1,220 @@
import { join, dirname, normalize } from "path-browserify";
import JSZip from "jszip";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'unzip' command
* Extract files from ZIP archives
*/
export class UnzipCommand implements ShellCommand {
name = 'unzip';
description = 'Extract files from ZIP archives';
usage = 'unzip [-d directory] [-o] [-l] [-q] archive.zip';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing archive operand\nUsage: ${this.usage}`);
}
let archivePath = '';
let extractDir = cwd;
let overwrite = false;
let listOnly = false;
let quiet = false;
// Parse command line options
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-d' && i + 1 < args.length) {
// Extract to specific directory
extractDir = args[i + 1];
i++; // Skip next argument
} else if (arg === '-o') {
// Overwrite existing files
overwrite = true;
} else if (arg === '-l') {
// List archive contents only
listOnly = true;
} else if (arg === '-q') {
// Quiet mode - suppress output
quiet = true;
} else if (arg.startsWith('-')) {
return createErrorResult(`${this.name}: invalid option '${arg}'\nUsage: ${this.usage}`);
} else {
// This should be the archive path
archivePath = arg;
}
}
if (!archivePath) {
return createErrorResult(`${this.name}: no archive specified\nUsage: ${this.usage}`);
}
try {
// Resolve archive path
let absoluteArchivePath: string;
if (archivePath.startsWith('/') || archivePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(archivePath)) {
absoluteArchivePath = archivePath;
} else {
absoluteArchivePath = join(cwd, archivePath);
}
// Check if archive exists
try {
const stats = await this.fs.stat(absoluteArchivePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${archivePath}: Is a directory`);
}
} catch {
return createErrorResult(`${this.name}: ${archivePath}: No such file or directory`);
}
// Read the ZIP file
const zipData = await this.fs.readFile(absoluteArchivePath);
const zip = await JSZip.loadAsync(zipData);
// Resolve extraction directory
let absoluteExtractDir: string;
if (extractDir.startsWith('/') || extractDir.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(extractDir)) {
absoluteExtractDir = extractDir;
} else {
absoluteExtractDir = join(cwd, extractDir);
}
// Security check: ensure extraction directory is within allowed paths
if (!this.isPathAllowed(absoluteExtractDir, cwd)) {
return createErrorResult(`${this.name}: extraction directory '${extractDir}' is outside allowed paths (cwd or /tmp)`);
}
if (listOnly) {
// List contents only
const entries: string[] = [];
zip.forEach((relativePath, file) => {
const date = file.date || new Date();
const type = file.dir ? 'd' : '-';
const sizeStr = file.dir ? '0' : '?';
entries.push(`${type}rw-r--r-- 1 user user ${sizeStr.padStart(8)} ${date.toISOString().slice(0, 19).replace('T', ' ')} ${relativePath}`);
});
return createSuccessResult(`Archive: ${archivePath}\n${entries.join('\n')}`);
}
// Create extraction directory if it doesn't exist
try {
await this.fs.stat(absoluteExtractDir);
} catch {
await this.fs.mkdir(absoluteExtractDir, { recursive: true });
}
const extractedFiles: string[] = [];
const errors: string[] = [];
// Extract all files
for (const [relativePath, file] of Object.entries(zip.files)) {
const extractPath = join(absoluteExtractDir, relativePath);
// Security check: ensure each file path is within allowed directories
if (!this.isPathAllowed(extractPath, cwd)) {
errors.push(`${this.name}: ${relativePath}: Path is outside allowed directories (skipped for security)`);
continue;
}
try {
if (file.dir) {
// Create directory
await this.fs.mkdir(extractPath, { recursive: true });
if (!quiet) {
extractedFiles.push(` creating: ${relativePath}`);
}
} else {
// Check if file exists and handle overwrite
if (!overwrite) {
try {
await this.fs.stat(extractPath);
errors.push(`${this.name}: ${relativePath}: File exists (use -o to overwrite)`);
continue;
} catch {
// File doesn't exist, proceed with extraction
}
}
// Create parent directories if needed
const parentDir = dirname(extractPath);
try {
await this.fs.stat(parentDir);
} catch {
await this.fs.mkdir(parentDir, { recursive: true });
}
// Extract file content
const content = await file.async('uint8array');
await this.fs.writeFile(extractPath, content);
if (!quiet) {
extractedFiles.push(` inflating: ${relativePath}`);
}
}
} catch (error) {
errors.push(`${this.name}: ${relativePath}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
let output = '';
if (!quiet) {
output = `Archive: ${archivePath}\n`;
if (extractedFiles.length > 0) {
output += extractedFiles.join('\n');
}
}
if (errors.length > 0) {
if (!quiet && extractedFiles.length > 0) {
output += '\n';
}
return createErrorResult(output + '\n' + errors.join('\n'));
}
return createSuccessResult(output);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('corrupted') || error.message.includes('invalid')) {
return createErrorResult(`${this.name}: ${archivePath}: Archive is corrupted or invalid`);
} else {
return createErrorResult(`${this.name}: ${archivePath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${archivePath}: Unknown error`);
}
}
}
/**
* Check if a path is within allowed extraction directories (cwd or /tmp and their subdirectories)
*/
private isPathAllowed(extractPath: string, cwd: string): boolean {
// Normalize the paths without using resolve() since we're in browser environment
const normalizedPath = normalize(extractPath);
const normalizedCwd = normalize(cwd);
const tmpPath = '/tmp';
// Ensure paths are absolute for comparison
const absolutePath = normalizedPath.startsWith('/') ? normalizedPath : normalize(join(normalizedCwd, normalizedPath));
const absoluteCwd = normalizedCwd.startsWith('/') ? normalizedCwd : '/' + normalizedCwd;
// Check if path is within cwd or /tmp
return absolutePath.startsWith(absoluteCwd + '/') ||
absolutePath === absoluteCwd ||
absolutePath.startsWith(tmpPath + '/') ||
absolutePath === tmpPath;
}
}
+20 -12
View File
@@ -98,8 +98,6 @@ const resources = {
getHelp: '🔧 Get help with debugging and optimization',
buildDeploy: '🚀 Build and deploy your project',
aiNotConfigured: 'AI Assistant Not Configured',
configureAI: 'Please configure your AI settings to start building with AI assistance.',
useMenuForAI: 'Use the menu in the top bar to access AI Settings.',
askToAddFeatures: 'Ask me to add features, edit files, or build your project...',
selectModelFirst: 'Please select a model to start chatting...',
sendMessage: 'Send message',
@@ -256,6 +254,11 @@ const resources = {
recentlyUsed: 'Recently Used',
errorLoadingModels: 'Error Loading Models',
// API Authentication Errors
apiAuthenticationFailed: 'API Authentication Failed',
invalidApiKey: 'Invalid API key for {{provider}}. Please check your API key in Settings.',
checkApiKeySettings: 'Check API Key Settings',
// Context and Cost
contextUsage: 'Context usage: {{tokens}} / {{total}} tokens ({{percentage}}%)',
totalCostSession: 'Total cost for this chat session',
@@ -394,8 +397,6 @@ const resources = {
getHelp: '🔧 Obtenha ajuda com depuração e otimização',
buildDeploy: '🚀 Construa e implante seu projeto',
aiNotConfigured: 'Assistente de IA Não Configurado',
configureAI: 'Configure suas configurações de IA para começar a construir com assistência de IA.',
useMenuForAI: 'Use o menu na barra superior para acessar as Configurações de IA.',
askToAddFeatures: 'Peça para adicionar recursos, editar arquivos ou construir seu projeto...',
selectModelFirst: 'Selecione um modelo para começar a conversar...',
sendMessage: 'Enviar mensagem',
@@ -552,6 +553,11 @@ const resources = {
recentlyUsed: 'Usados Recentemente',
errorLoadingModels: 'Erro ao Carregar Modelos',
// API Authentication Errors
apiAuthenticationFailed: 'Falha na Autenticação da API',
invalidApiKey: 'Chave de API inválida para {{provider}}. Verifique sua chave de API nas Configurações.',
checkApiKeySettings: 'Verificar Configurações da Chave de API',
// Context and Cost
contextUsage: 'Uso de contexto: {{tokens}} / {{total}} tokens ({{percentage}}%)',
totalCostSession: 'Custo total para esta sessão de chat',
@@ -690,8 +696,6 @@ const resources = {
getHelp: '🔧 获得调试和优化帮助',
buildDeploy: '🚀 构建和部署您的项目',
aiNotConfigured: 'AI助手未配置',
configureAI: '请配置您的AI设置以开始使用AI助手构建。',
useMenuForAI: '使用顶部栏中的菜单访问AI设置。',
askToAddFeatures: '请我添加功能、编辑文件或构建您的项目...',
selectModelFirst: '请先选择一个模型开始聊天...',
sendMessage: '发送消息',
@@ -848,6 +852,11 @@ const resources = {
recentlyUsed: '最近使用',
errorLoadingModels: '加载模型时出错',
// API Authentication Errors
apiAuthenticationFailed: 'API身份验证失败',
invalidApiKey: '{{provider}}的API密钥无效。请在设置中检查您的API密钥。',
checkApiKeySettings: '检查API密钥设置',
// Context and Cost
contextUsage: '上下文使用:{{tokens}} / {{total}} 令牌 ({{percentage}}%)',
totalCostSession: '此聊天会话的总费用',
@@ -986,8 +995,6 @@ const resources = {
getHelp: '🔧 Sami taimako da gyara kuskure da haɓakawa',
buildDeploy: '🚀 Gina da tura aikinku',
aiNotConfigured: 'Mataimakin AI Ba a Saita ba',
configureAI: 'Da fatan za a saita saitunan AI don farawa ginawa da taimakon AI.',
useMenuForAI: 'Yi amfani da menu a saman mashigi don shiga Saitunan AI.',
askToAddFeatures: 'Roƙe ni in ƙara fasaloli, gyara fayiloli, ko gina aikinku...',
selectModelFirst: 'Da fatan za a zaɓi samfuri don farawa hira...',
sendMessage: 'Aika saƙo',
@@ -1144,6 +1151,11 @@ const resources = {
recentlyUsed: 'An yi amfani da su kwanan nan',
errorLoadingModels: 'Kuskure wajen Lodin Samfura',
// API Authentication Errors
apiAuthenticationFailed: 'Gazawar Tabbatarwar API',
invalidApiKey: 'Maɓallin API na {{provider}} ba daidai ba ne. Da fatan za a duba maɓallin API a cikin Saitunan.',
checkApiKeySettings: 'Duba Saitunan Maɓallin API',
// Context and Cost
contextUsage: 'Amfanin mahallin: {{tokens}} / {{total}} alamomi ({{percentage}}%)',
totalCostSession: 'Jimlar farashi don wannan zaman hira',
@@ -1282,8 +1294,6 @@ const resources = {
getHelp: '🔧 Gba iranlọwọ pẹlu atunṣe ati imudara',
buildDeploy: '🚀 Kọ ati gbe iṣẹ akanṣe rẹ lọ',
aiNotConfigured: 'Oluranlọwọ AI Ko Tunto',
configureAI: 'Jọwọ tunto awọn eto AI rẹ lati bẹrẹ kikọ pẹlu iranlọwọ AI.',
useMenuForAI: 'Lo akojọ aṣayan ni oke ọpa lati wọle si Awọn eto AI.',
askToAddFeatures: 'Beere mi lati fi awọn ẹya kun, ṣatunkọ awọn faili, tabi kọ iṣẹ akanṣe rẹ...',
selectModelFirst: 'Jọwọ yan awoṣe lati bẹrẹ ibaraẹnisọrọ...',
sendMessage: 'Fi ifiranṣẹ ranṣẹ',
@@ -1578,8 +1588,6 @@ const resources = {
getHelp: '🔧 Nweta enyemaka na debugging na optimization',
buildDeploy: '🚀 Wuo ma bufee ọrụ gị',
aiNotConfigured: 'Onye Enyemaka AI Ahazighị',
configureAI: 'Biko hazie ntọala AI gị iji malite iwu na enyemaka AI.',
useMenuForAI: 'Jiri menu dị n\'elu okporo iji nweta Ntọala AI.',
askToAddFeatures: 'Rịọ m ka m tinye atụmatụ, dezie faịlụ, ma ọ bụ wuo ọrụ gị...',
selectModelFirst: 'Biko họrọ ụdịdị iji malite ikwu okwu...',
sendMessage: 'Ziga ozi',
+6 -6
View File
@@ -29,9 +29,9 @@ describe('parseProviderModel', () => {
it('should parse simple provider/model format', () => {
const result = parseProviderModel('openai/gpt-4o', mockProviders);
expect(result.provider).toBe('openai');
expect(result.model).toBe('gpt-4o');
expect(result.connection).toEqual({
expect(result.provider).toEqual({
id: 'openai',
baseURL: mockProviders[0].baseURL,
apiKey: mockProviders[0].apiKey,
nostr: mockProviders[0].nostr,
@@ -41,9 +41,9 @@ describe('parseProviderModel', () => {
it('should parse complex model names with slashes', () => {
const result = parseProviderModel('openrouter/anthropic/claude-sonnet-4', mockProviders);
expect(result.provider).toBe('openrouter');
expect(result.model).toBe('anthropic/claude-sonnet-4');
expect(result.connection).toEqual({
expect(result.provider).toEqual({
id: 'openrouter',
baseURL: mockProviders[1].baseURL,
apiKey: mockProviders[1].apiKey,
nostr: mockProviders[1].nostr,
@@ -53,9 +53,9 @@ describe('parseProviderModel', () => {
it('should handle model names with multiple slashes', () => {
const result = parseProviderModel('openrouter/meta/llama-3.1-405b-instruct', mockProviders);
expect(result.provider).toBe('openrouter');
expect(result.model).toBe('meta/llama-3.1-405b-instruct');
expect(result.connection).toEqual({
expect(result.provider).toEqual({
id: 'openrouter',
baseURL: mockProviders[1].baseURL,
apiKey: mockProviders[1].apiKey,
nostr: mockProviders[1].nostr,
+7 -17
View File
@@ -1,13 +1,8 @@
import type { AIProvider } from '@/contexts/AISettingsContext';
export interface ParsedProviderModel {
provider: string;
model: string;
connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
};
provider: AIProvider;
}
/**
@@ -25,25 +20,20 @@ export function parseProviderModel(
throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")');
}
const provider = providerModelString.substring(0, firstSlashIndex);
const providerId = providerModelString.substring(0, firstSlashIndex);
const model = providerModelString.substring(firstSlashIndex + 1);
if (!provider || !model) {
if (!providerId || !model) {
throw new Error('Invalid format. Both provider and model must be specified');
}
const providerObj = providers.find(p => p.id === provider);
if (!providerObj) {
throw new Error(`Provider "${provider}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`);
const provider = providers.find(p => p.id === providerId);
if (!provider) {
throw new Error(`Provider "${providerId}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`);
}
return {
provider,
model,
connection: {
baseURL: providerObj.baseURL,
apiKey: providerObj.apiKey,
nostr: providerObj.nostr,
},
provider,
};
}
+1 -1
View File
@@ -44,7 +44,7 @@ describe('ShellTool', () => {
});
it('should have correct tool properties', () => {
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators');
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators');
expect(shellTool.inputSchema).toBeDefined();
});
+5 -1
View File
@@ -18,6 +18,7 @@ import {
GitCommand,
GrepCommand,
HeadCommand,
HexdumpCommand,
LsCommand,
MkdirCommand,
MvCommand,
@@ -28,6 +29,7 @@ import {
TouchCommand,
TrCommand,
UniqCommand,
UnzipCommand,
WcCommand,
WhoamiCommand,
WhichCommand
@@ -46,7 +48,7 @@ export class ShellTool implements Tool<ShellToolParams> {
private git: Git;
private commands: Map<string, ShellCommand>;
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators";
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators";
readonly inputSchema = z.object({
command: z.string().describe(
@@ -75,6 +77,7 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new GitCommand({ git: this.git, fs, cwd: this.cwd }));
this.registerCommand(new GrepCommand(fs));
this.registerCommand(new HeadCommand(fs));
this.registerCommand(new HexdumpCommand(fs));
this.registerCommand(new LsCommand(fs));
this.registerCommand(new MkdirCommand(fs));
this.registerCommand(new MvCommand(fs));
@@ -85,6 +88,7 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new TouchCommand(fs));
this.registerCommand(new TrCommand(fs));
this.registerCommand(new UniqCommand(fs));
this.registerCommand(new UnzipCommand(fs));
this.registerCommand(new WcCommand(fs));
this.registerCommand(new WhoamiCommand());
+2 -4
View File
@@ -144,8 +144,7 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
</div>
<div className="flex items-center gap-2">
<CreditsBadge
providerId={provider.id}
connection={{ baseURL: provider.baseURL, apiKey: provider.apiKey, nostr: provider.nostr }}
provider={provider}
onOpenDialog={() => onOpenCreditsDialog(provider.id)}
/>
<Button
@@ -547,8 +546,7 @@ export function AISettings() {
handleCloseCreditsDialog();
}
}}
providerId={activeCreditsDialog}
connection={{ baseURL: provider.baseURL, apiKey: provider.apiKey, nostr: provider.nostr }}
provider={provider}
/>
);
})()}
+6 -4
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { AppLayout } from '@/components/AppLayout';
@@ -19,6 +19,7 @@ export default function Clone() {
const [searchParams] = useSearchParams();
const projectsManager = useProjectsManager();
const { toast } = useToast();
const autoCloneInitiatedRef = useRef(false);
useSeoMeta({
title: `${t('importRepository')} - Shakespeare`,
@@ -115,8 +116,8 @@ export default function Clone() {
description: successDescription,
});
// Navigate to the new project
navigate(`/project/${project.id}`);
// Navigate to the new project with build parameter
navigate(`/project/${project.id}?build`);
} catch (error) {
console.error('Failed to clone repository:', error);
@@ -160,9 +161,10 @@ export default function Clone() {
// Initialize repoUrl from URL parameters and auto-import if URL is provided
useEffect(() => {
const urlParam = searchParams.get('url');
if (urlParam) {
if (urlParam && !autoCloneInitiatedRef.current) {
const decodedUrl = decodeURIComponent(urlParam);
setRepoUrl(decodedUrl);
autoCloneInitiatedRef.current = true;
// Automatically start the clone process with the URL directly
handleClone(decodedUrl);
+84 -7
View File
@@ -7,15 +7,20 @@ import { useFS } from '@/hooks/useFS';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useAISettings } from '@/hooks/useAISettings';
import { useToast } from '@/hooks/useToast';
import { AppLayout } from '@/components/AppLayout';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { DotAI } from '@/lib/DotAI';
import { parseProviderModel } from '@/lib/parseProviderModel';
import type { AIMessage } from '@/lib/SessionManager';
import { saveFileToTmp } from '@/lib/fileUtils';
import type OpenAI from 'openai';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ModelSelector } from '@/components/ModelSelector';
import { FileAttachment } from '@/components/ui/file-attachment';
import { ToastAction } from '@/components/ui/toast';
import { Plus } from 'lucide-react';
import { useSeoMeta } from '@unhead/react';
@@ -30,6 +35,7 @@ export default function Index() {
const { fs } = useFS();
const { generateProjectId, isLoading: isGeneratingId } = useAIProjectId();
const { settings, addRecentlyUsedModel } = useAISettings();
const { toast } = useToast();
const [providerModel, setProviderModel] = useState(() => {
// Initialize with first recently used model if available, otherwise empty
return settings.recentlyUsedModels?.[0] || '';
@@ -41,6 +47,41 @@ export default function Index() {
// Check if any providers are configured
const hasProvidersConfigured = settings.providers.length > 0;
// Check for API key failures and show appropriate toast
const checkForKeyFailure = (error: unknown): boolean => {
// Check for authentication errors
// Note: useAIProjectId re-throws OpenAI errors as generic Error objects
const isAuthError = error instanceof Error && error.message === '401 No auth credentials found';
if (isAuthError) {
// Get provider name inline
let providerName = 'Provider';
try {
const { provider } = parseProviderModel(providerModel, settings.providers);
providerName = provider.id.charAt(0).toUpperCase() + provider.id.slice(1);
} catch {
// Keep default 'Provider'
}
toast({
title: t('apiAuthenticationFailed'),
description: t('invalidApiKey', { provider: providerName }),
variant: 'destructive',
action: (
<ToastAction
altText={t('checkApiKeySettings')}
onClick={() => navigate('/settings/ai')}
>
{t('checkApiKeySettings')}
</ToastAction>
),
});
}
return isAuthError;
};
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
setProviderModel(settings.recentlyUsedModels[0]);
@@ -164,13 +205,48 @@ export default function Index() {
// Create project with AI-generated ID
const project = await projectsManager.createProject(prompt.trim(), projectId);
// Build message content as text parts (same as ChatPane)
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
// Add user input as text part if present
if (prompt.trim()) {
contentParts.push({
type: 'text',
text: prompt.trim()
});
}
// Process attached files and add as separate text parts
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
const savedPath = await saveFileToTmp(fs, file);
return `Added file: ${savedPath}`;
} catch (error) {
console.error('Failed to save file:', error);
return `Failed to save file: ${file.name}`;
}
});
const fileResults = await Promise.all(filePromises);
// Add each file as a separate text part
fileResults.forEach(fileResult => {
contentParts.push({
type: 'text',
text: fileResult
});
});
}
// Store the initial message in chat history using DotAI
const dotAI = new DotAI(fs, `/projects/${project.id}`);
const sessionName = DotAI.generateSessionName();
// Create initial message with content parts
// Create initial message with content parts (same format as ChatPane)
const initialMessage: AIMessage = {
role: 'user',
content: prompt.trim()
content: contentParts.length === 1 ? contentParts[0].text : contentParts
};
await dotAI.setHistory(sessionName, [initialMessage]);
@@ -180,11 +256,13 @@ export default function Index() {
// Navigate to the project with autostart parameter and model
const searchParams = new URLSearchParams({
autostart: 'true',
build: 'true',
...(providerModel.trim() && { model: providerModel.trim() })
});
navigate(`/project/${project.id}?${searchParams.toString()}`);
} catch (error) {
console.error('Failed to create project:', error);
checkForKeyFailure(error);
} finally {
setIsCreating(false);
}
@@ -209,9 +287,8 @@ export default function Index() {
<div className="mb-8 md:mb-12">
{/* Chat Input Container - matching the ChatPane style */}
<div
className={`relative rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${
isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
className={`relative rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
@@ -222,8 +299,8 @@ export default function Index() {
!hasProvidersConfigured
? t('examplePrompt')
: !providerModel.trim()
? t('selectModelToDescribe')
: t('examplePrompt')
? t('selectModelToDescribe')
: t('examplePrompt')
}
value={prompt}
onChange={handlePromptChange}
+33 -12
View File
@@ -6,7 +6,7 @@ import { useProjectsManager } from '@/hooks/useProjectsManager';
import { ChatPane, type ChatPaneRef } from '@/components/Shakespeare/ChatPane';
import { PreviewPane } from '@/components/Shakespeare/PreviewPane';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { ProjectInfoDialog } from '@/components/ProjectInfoDialog';
import { ProjectDetailsDialog } from '@/components/ProjectDetailsDialog';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
@@ -21,6 +21,7 @@ import { StarButton } from '@/components/StarButton';
import { useBuildProject } from '@/hooks/useBuildProject';
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
import { ConsoleMessage } from '@/types/console';
import { useConsoleMessages, clearConsoleMessages } from '@/hooks/useConsoleMessages';
export function ProjectView() {
const { projectId } = useParams<{ projectId: string }>();
@@ -30,7 +31,7 @@ export function ProjectView() {
const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview');
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
const [isAILoading, setIsAILoading] = useState(false);
const [isProjectInfoOpen, setIsProjectInfoOpen] = useState(false);
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
const [consoleMessages, setConsoleMessages] = useState<ConsoleMessage[]>([]);
const projectsManager = useProjectsManager();
const chatPaneRef = useRef<ChatPaneRef>(null);
@@ -64,6 +65,8 @@ export function ProjectView() {
setProject(projectData);
// Clear console messages when switching projects
setConsoleMessages([]);
// Also clear global console messages
clearConsoleMessages();
} catch (error) {
console.error('Failed to load project:', error);
} finally {
@@ -75,6 +78,22 @@ export function ProjectView() {
loadProject();
}, [loadProject]);
// Sync console messages with global state
const { messages: globalMessages } = useConsoleMessages();
useEffect(() => {
setConsoleMessages(globalMessages);
}, [globalMessages]);
// Reset view state when projectId changes
useEffect(() => {
if (projectId) {
// Reset to preview tab if the new project is previewable, otherwise code
setActiveTab(isPreviewable ? 'preview' : 'code');
// Reset mobile view to chat when switching projects
setMobileView('chat');
}
}, [projectId, isPreviewable]);
// Switch away from preview mode if project is not previewable
useEffect(() => {
if (mobileView === 'preview' && !isPreviewable) {
@@ -156,7 +175,7 @@ export function ProjectView() {
<Button
variant="ghost"
className="block p-0 h-auto text-sm font-semibold truncate hover:bg-transparent hover:text-primary"
onClick={() => setIsProjectInfoOpen(true)}
onClick={() => setIsProjectDetailsOpen(true)}
>
{project.name}
</Button>
@@ -178,6 +197,7 @@ export function ProjectView() {
projectId={project.id}
projectName={project.name}
onNewChat={handleNewChat}
onProjectDetails={() => setIsProjectDetailsOpen(true)}
isLoading={isAILoading}
isBuildLoading={build.isPending}
onFirstInteraction={handleFirstInteraction}
@@ -303,12 +323,12 @@ export function ProjectView() {
</div>
</div>
{/* Project Info Dialog */}
{/* Project Details Dialog */}
{project && (
<ProjectInfoDialog
<ProjectDetailsDialog
project={project}
open={isProjectInfoOpen}
onOpenChange={setIsProjectInfoOpen}
open={isProjectDetailsOpen}
onOpenChange={setIsProjectDetailsOpen}
onProjectDeleted={handleProjectDeleted}
/>
)}
@@ -365,7 +385,7 @@ export function ProjectView() {
<Button
variant="ghost"
className="block p-0 h-auto font-semibold text-lg truncate hover:bg-transparent hover:text-primary"
onClick={() => setIsProjectInfoOpen(true)}
onClick={() => setIsProjectDetailsOpen(true)}
>
{project.name}
</Button>
@@ -388,6 +408,7 @@ export function ProjectView() {
projectId={project.id}
projectName={project.name}
onNewChat={handleNewChat}
onProjectDetails={() => setIsProjectDetailsOpen(true)}
isLoading={isAILoading}
isBuildLoading={build.isPending}
onFirstInteraction={handleFirstInteraction}
@@ -460,12 +481,12 @@ export function ProjectView() {
</div>
</div>
{/* Project Info Dialog */}
{/* Project Details Dialog */}
{project && (
<ProjectInfoDialog
<ProjectDetailsDialog
project={project}
open={isProjectInfoOpen}
onOpenChange={setIsProjectInfoOpen}
open={isProjectDetailsOpen}
onOpenChange={setIsProjectDetailsOpen}
onProjectDeleted={handleProjectDeleted}
/>
)}