mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-04 16:13:34 +00:00
Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91ab79bb39 | ||
|
|
8f148e48c0 | ||
|
|
3e230d425f | ||
|
|
a6caf93e8b | ||
|
|
b55fd857e1 | ||
|
|
65c51e865a | ||
|
|
8ecf460140 | ||
|
|
8ee4efdee3 | ||
|
|
5ac5fcc212 | ||
|
|
58c24f615d | ||
|
|
d1cbcda5d5 | ||
|
|
c30ed35c67 | ||
|
|
dea364c2a6 | ||
|
|
eabba1ecec | ||
|
|
db02b9fb94 | ||
|
|
4d88823c2d | ||
|
|
933530a96c | ||
|
|
43f4e0d15d | ||
|
|
21e522cba7 | ||
|
|
d8bfa10b43 | ||
|
|
7a000a80f0 | ||
|
|
866155d907 | ||
|
|
72439d4ec9 | ||
|
|
51f079696a | ||
|
|
abe3368115 | ||
|
|
16d357364d | ||
|
|
2d505588c7 | ||
|
|
a9ab551ca2 | ||
|
|
075d6aba2d | ||
|
|
a1f571b2d8 | ||
|
|
d4eca86ec6 | ||
|
|
44a208aed5 | ||
|
|
ccc3613c83 | ||
|
|
fd309e0aab | ||
|
|
3d06e0cb57 | ||
|
|
dbf5cfe0a3 | ||
|
|
0b66f81bfc | ||
|
|
35a85c18bd | ||
|
|
465bef91e8 |
No files matched your search
@@ -34,7 +34,6 @@ Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The p
|
||||
Shakespeare is available on the following URLs:
|
||||
|
||||
- [shakespeare.diy](https://shakespeare.diy)
|
||||
- [shakespeare.soapbox.dev](https://shakespeare.soapbox.dev)
|
||||
- [shakespeare-diy.github.io](https://shakespeare-diy.github.io)
|
||||
- [shakespeare-b0b9c8.gitlab.io](https://shakespeare-b0b9c8.gitlab.io)
|
||||
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
|
||||
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
||||
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
|
||||
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
|
||||
<meta name="theme-color" content="#2b0037">
|
||||
|
||||
Generated
+86
-11
@@ -68,6 +68,7 @@
|
||||
"lucide-react": "^0.525.0",
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.30.0",
|
||||
@@ -105,6 +106,7 @@
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/nunjucks": "^3.2.6",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
@@ -193,6 +195,7 @@
|
||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
@@ -1828,6 +1831,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
@@ -1851,6 +1855,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
@@ -1872,6 +1877,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
@@ -5402,8 +5408,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
|
||||
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/cacheable-request": {
|
||||
"version": "6.0.3",
|
||||
@@ -5603,6 +5608,13 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/nunjucks": {
|
||||
"version": "3.2.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/nunjucks/-/nunjucks-3.2.6.tgz",
|
||||
"integrity": "sha512-pHiGtf83na1nCzliuAdq8GowYiXvH5l931xZ0YEHaLMNFgynpEqx+IPStlu7UaDkehfvl01e4x/9Tpwhy7Ue3w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/path-browserify": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/path-browserify/-/path-browserify-1.0.3.tgz",
|
||||
@@ -5638,6 +5650,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
|
||||
"integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.0.2"
|
||||
@@ -5649,6 +5662,7 @@
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.0.0"
|
||||
}
|
||||
@@ -5753,6 +5767,7 @@
|
||||
"integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.31.1",
|
||||
"@typescript-eslint/types": "8.31.1",
|
||||
@@ -6088,11 +6103,18 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/a-sync-waterfall": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/a-sync-waterfall/-/a-sync-waterfall-1.0.1.tgz",
|
||||
"integrity": "sha512-RYTOHHdWipFUliRFMCS4X2Yn2X8M87V/OpSqWzKKOGhzqyUxzyVmhHDH9sAvG+ZuQf/TAOFsLCpMw09I1ufUnA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.15.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -6257,6 +6279,12 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/asap": {
|
||||
"version": "2.0.6",
|
||||
"resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",
|
||||
"integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/assertion-error": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
|
||||
@@ -6531,6 +6559,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.8.19",
|
||||
"caniuse-lite": "^1.0.30001751",
|
||||
@@ -6790,6 +6819,7 @@
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"anymatch": "~3.1.2",
|
||||
"braces": "~3.0.2",
|
||||
@@ -7528,8 +7558,7 @@
|
||||
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
|
||||
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dom-helpers": {
|
||||
"version": "5.2.1",
|
||||
@@ -7607,7 +7636,8 @@
|
||||
"version": "8.6.0",
|
||||
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
|
||||
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/embla-carousel-react": {
|
||||
"version": "8.6.0",
|
||||
@@ -7906,6 +7936,7 @@
|
||||
"integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.2.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -9253,6 +9284,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.27.6"
|
||||
},
|
||||
@@ -10022,6 +10054,7 @@
|
||||
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"cssstyle": "^4.2.1",
|
||||
"data-urls": "^5.0.0",
|
||||
@@ -10418,7 +10451,6 @@
|
||||
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"lz-string": "bin/bin.js"
|
||||
}
|
||||
@@ -11685,6 +11717,40 @@
|
||||
"integrity": "sha512-78BTryCLcLYv96ONU8Ws3Q1JzjlAt+43pWQhIl86xZmWeegYCNLPml7yQ+gG3vR6V5h4XGj+TxO+SS5dsThQIA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nunjucks": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/nunjucks/-/nunjucks-3.2.4.tgz",
|
||||
"integrity": "sha512-26XRV6BhkgK0VOxfbU5cQI+ICFUtMLixv1noZn1tGU38kQH5A5nmmbk/O45xdyBhD1esk47nKrY0mvQpZIhRjQ==",
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"a-sync-waterfall": "^1.0.0",
|
||||
"asap": "^2.0.3",
|
||||
"commander": "^5.1.0"
|
||||
},
|
||||
"bin": {
|
||||
"nunjucks-precompile": "bin/precompile"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6.9.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"chokidar": "^3.3.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"chokidar": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/nunjucks/node_modules/commander": {
|
||||
"version": "5.1.0",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",
|
||||
"integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/nwsapi": {
|
||||
"version": "2.2.20",
|
||||
"resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.20.tgz",
|
||||
@@ -12088,6 +12154,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.8",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -12255,7 +12322,6 @@
|
||||
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1",
|
||||
"ansi-styles": "^5.0.0",
|
||||
@@ -12271,7 +12337,6 @@
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
@@ -12282,7 +12347,6 @@
|
||||
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
@@ -12295,8 +12359,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
|
||||
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/prismjs": {
|
||||
"version": "1.30.0",
|
||||
@@ -12436,6 +12499,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
@@ -12462,6 +12526,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
@@ -12487,6 +12552,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
|
||||
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
@@ -12535,6 +12601,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
|
||||
"integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/hast": "^3.0.0",
|
||||
"@types/mdast": "^4.0.0",
|
||||
@@ -13117,6 +13184,7 @@
|
||||
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "1.0.7"
|
||||
},
|
||||
@@ -14168,6 +14236,7 @@
|
||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
||||
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@alloc/quick-lru": "^5.2.0",
|
||||
"arg": "^5.0.2",
|
||||
@@ -14371,6 +14440,7 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -14643,6 +14713,7 @@
|
||||
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -15152,6 +15223,7 @@
|
||||
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.4",
|
||||
@@ -15296,6 +15368,7 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -15766,6 +15839,7 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -15842,6 +15916,7 @@
|
||||
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"rollup": "dist/bin/rollup"
|
||||
},
|
||||
|
||||
+3
-1
@@ -18,7 +18,7 @@
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"typecheck": "npm i --silent && tsc --noEmit",
|
||||
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
|
||||
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && electron electron",
|
||||
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
|
||||
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -81,6 +81,7 @@
|
||||
"lucide-react": "^0.525.0",
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.30.0",
|
||||
@@ -118,6 +119,7 @@
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/nunjucks": "^3.2.6",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
/* /index.html 200
|
||||
/assets/* /assets/:splat 200
|
||||
/* /index.html 200
|
||||
@@ -79,6 +79,7 @@ export function AppProvider(props: AppProviderProps) {
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
defaultConfig,
|
||||
updateConfig,
|
||||
};
|
||||
|
||||
|
||||
@@ -124,6 +124,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||
|
||||
// Provider-specific form data
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
@@ -294,6 +295,10 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
setShakespeareForm({ subdomain });
|
||||
}, []);
|
||||
|
||||
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
|
||||
setIsShakespeareFormValid(isValid);
|
||||
}, []);
|
||||
|
||||
const handleNsiteNsecChange = useCallback((nsec: string) => {
|
||||
setNsiteForm({ nsec });
|
||||
}, []);
|
||||
@@ -317,6 +322,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
host={shakespeareProvider.host}
|
||||
projectId={projectId}
|
||||
onSubdomainChange={handleShakespeareSubdomainChange}
|
||||
onValidationChange={handleShakespeareValidationChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -495,6 +501,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
!selectedProvider ||
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
|
||||
import { ReactNode } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ReactNode, useMemo } from 'react';
|
||||
|
||||
interface ExternalFaviconProps {
|
||||
/** The URL to fetch the favicon for */
|
||||
@@ -25,14 +26,28 @@ export function ExternalFavicon({
|
||||
}: ExternalFaviconProps) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
|
||||
// Generate the favicon URL using the configured template
|
||||
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
const faviconSrc = useMemo(() => {
|
||||
try {
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
return faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}, [url, config.faviconUrl]);
|
||||
|
||||
// If faviconSrc is not available, render the fallback directly
|
||||
if (!faviconSrc) {
|
||||
return (
|
||||
<span className={cn('inline-flex items-center justify-center', className)}>
|
||||
<span>{fallback}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center justify-center ${className}`}>
|
||||
<span className={cn('inline-flex items-center justify-center', className)}>
|
||||
<img
|
||||
src={faviconSrc}
|
||||
alt=""
|
||||
|
||||
@@ -25,6 +25,7 @@ const baseGitStatus = {
|
||||
},
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
@@ -82,7 +83,16 @@ describe('GitDialog', () => {
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows sync status', () => {
|
||||
it('shows sync status when branch is published', () => {
|
||||
// Mock git status with published branch
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
@@ -133,7 +143,17 @@ describe('GitDialog', () => {
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables push button when no commits ahead', () => {
|
||||
it('disables push button when no commits ahead and branch is published', () => {
|
||||
// Mock git status with published branch and no commits ahead
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
@@ -147,6 +167,38 @@ describe('GitDialog', () => {
|
||||
expect(pushButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables push and disables pull when branch is not published', () => {
|
||||
// Mock git status with unpublished branch (has commits but no remote branch)
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: false,
|
||||
totalCommits: 5,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Sync Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Branch not published')).toBeInTheDocument();
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
|
||||
const pullButton = screen.getByText('Pull');
|
||||
expect(pullButton).toBeInTheDocument();
|
||||
expect(pullButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('does not show credentials warning when credentials are configured', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
|
||||
+107
-64
@@ -243,13 +243,23 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
object: currentRef,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Branch created',
|
||||
description: `Created branch "${newBranchName}"`,
|
||||
// Automatically check out the new branch
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: newBranchName.trim(),
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Close the dialog before showing the toast
|
||||
setNewBranchName('');
|
||||
setIsCreateBranchDialogOpen(false);
|
||||
|
||||
// Show success toast indicating the branch was created and checked out
|
||||
toast({
|
||||
title: 'Branch created and checked out',
|
||||
description: `Switched to new branch "${newBranchName.trim()}"`,
|
||||
});
|
||||
|
||||
await loadBranches();
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
@@ -446,50 +456,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
throw new Error('Could not determine repository state. The repository might not have any commits or branches.');
|
||||
}
|
||||
|
||||
// Get HEAD reference
|
||||
let headRef: string | undefined;
|
||||
try {
|
||||
const currentBranch = await git.currentBranch({ dir: projectPath });
|
||||
if (currentBranch) {
|
||||
headRef = `ref: refs/heads/${currentBranch}`;
|
||||
console.log(`HEAD points to: ${headRef}`);
|
||||
} else {
|
||||
// HEAD is detached, use the commit ID directly
|
||||
const headValue = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
if (headValue) {
|
||||
headRef = headValue;
|
||||
console.log(`HEAD is detached at: ${headRef}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to resolve HEAD:', error);
|
||||
}
|
||||
|
||||
// Create repo state event (NIP-34 kind 30618)
|
||||
const stateEvent = {
|
||||
kind: 30618,
|
||||
content: '',
|
||||
tags: [
|
||||
['d', result.repoId],
|
||||
...refTags,
|
||||
...(headRef ? [['HEAD', headRef]] : []),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
|
||||
console.log('Creating repository state event:', stateEvent);
|
||||
|
||||
// Sign and publish the state event
|
||||
const signedStateEvent = await user.signer.signEvent(stateEvent);
|
||||
|
||||
// State events only go to the relays specified in the repo announcement
|
||||
console.log('Publishing repository state to relays:', result.relays);
|
||||
await nostr.event(signedStateEvent, { relays: result.relays });
|
||||
|
||||
console.log('Published repository state to Nostr relays');
|
||||
console.log('Repository has refs:', refTags);
|
||||
|
||||
// Set origin remote to Nostr URL
|
||||
// Format: nostr://<npub>/<repo-id>
|
||||
@@ -522,13 +489,54 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
console.log('Set nostr.repo config to:', result.naddr);
|
||||
|
||||
toast({
|
||||
title: 'Repository published to Nostr',
|
||||
description: 'Waiting for GRASP servers to update...',
|
||||
});
|
||||
|
||||
// Refresh git status to pick up the new remote
|
||||
await refetchGitStatus();
|
||||
|
||||
// Automatically push to the newly configured Nostr remote
|
||||
// Get the current branch fresh from git instead of using stale gitStatus
|
||||
console.log('Starting automatic push to Nostr...');
|
||||
|
||||
try {
|
||||
const currentBranch = await git.currentBranch({ dir: projectPath });
|
||||
console.log('Current branch:', currentBranch);
|
||||
|
||||
if (!currentBranch) {
|
||||
throw new Error('No current branch found');
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Repository published to Nostr',
|
||||
description: 'Pushing commits to ngit servers...',
|
||||
});
|
||||
|
||||
console.log('Calling git.push with:', { dir: projectPath, remote: 'origin', ref: currentBranch });
|
||||
|
||||
await git.push({
|
||||
dir: projectPath,
|
||||
remote: 'origin',
|
||||
ref: currentBranch,
|
||||
signer: user.signer,
|
||||
});
|
||||
|
||||
console.log('Push completed successfully');
|
||||
|
||||
toast({
|
||||
title: 'Push successful',
|
||||
description: 'Repository successfully pushed to Nostr',
|
||||
});
|
||||
|
||||
// Refresh git status after push
|
||||
await refetchGitStatus();
|
||||
} catch (pushError) {
|
||||
console.error('Push error:', pushError);
|
||||
const pushErrorMessage = pushError instanceof Error ? pushError.message : 'Unknown error occurred';
|
||||
toast({
|
||||
title: 'Automatic push failed',
|
||||
description: pushErrorMessage,
|
||||
variant: 'destructive',
|
||||
duration: Infinity,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
toast({
|
||||
@@ -561,7 +569,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return;
|
||||
}
|
||||
|
||||
if (gitStatus.ahead === 0) {
|
||||
// Allow push if there are commits ahead OR if the remote branch doesn't exist (publishing new branch)
|
||||
if (gitStatus.ahead === 0 && gitStatus.remoteBranchExists) {
|
||||
toast({
|
||||
title: "Nothing to push",
|
||||
description: "No commits ahead of remote. Commit your changes first.",
|
||||
@@ -570,6 +579,16 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure we have commits to push when publishing a new branch
|
||||
if (!gitStatus.remoteBranchExists && gitStatus.totalCommits === 0) {
|
||||
toast({
|
||||
title: "Cannot publish branch",
|
||||
description: "No commits to push. Commit your changes first.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPushing(true);
|
||||
|
||||
try {
|
||||
@@ -583,11 +602,32 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
signer: user?.signer, // For signing if pushing to Nostr
|
||||
});
|
||||
|
||||
// Set up upstream tracking if this is the first push for this branch
|
||||
if (!gitStatus.remoteBranchExists) {
|
||||
await git.setConfig({
|
||||
dir: projectPath,
|
||||
path: `branch.${gitStatus.currentBranch}.remote`,
|
||||
value: remote.name,
|
||||
});
|
||||
await git.setConfig({
|
||||
dir: projectPath,
|
||||
path: `branch.${gitStatus.currentBranch}.merge`,
|
||||
value: `refs/heads/${gitStatus.currentBranch}`,
|
||||
});
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Push successful",
|
||||
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
// Show different messages for publishing new branches vs pushing commits
|
||||
if (gitStatus.remoteBranchExists) {
|
||||
toast({
|
||||
title: "Push successful",
|
||||
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Branch published",
|
||||
description: `New branch published to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Refresh git status after push
|
||||
await refetchGitStatus();
|
||||
@@ -683,8 +723,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
const getFileStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
@@ -728,6 +766,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
// Check if remote branch doesn't exist
|
||||
if (!gitStatus.remoteBranchExists && gitStatus.currentBranch) {
|
||||
return { status: 'not-published', text: 'Branch not published', icon: AlertCircle, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
if (gitStatus.ahead > 0 && gitStatus.behind > 0) {
|
||||
return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' };
|
||||
}
|
||||
@@ -1095,11 +1138,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
)}
|
||||
</div>
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
{originUrl.trim() && (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePull}
|
||||
disabled={isPulling || isPushing || isPushingToNostr}
|
||||
disabled={isPulling || isPushing || isPushingToNostr || !gitStatus.remoteBranchExists}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
@@ -1114,7 +1157,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
<Button
|
||||
onClick={handlePush}
|
||||
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
|
||||
disabled={isPushing || isPulling || isPushingToNostr || (gitStatus.ahead === 0 && gitStatus.remoteBranchExists)}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
@@ -1129,7 +1172,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gitStatus.remotes.length === 0 && user && (
|
||||
{!originUrl.trim() && user && (
|
||||
<Button
|
||||
onClick={handlePushToNostr}
|
||||
disabled={isPushingToNostr || isPushing || isPulling}
|
||||
@@ -1142,7 +1185,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
) : (
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
|
||||
{isPushingToNostr ? 'Loading...' : 'Push to Nostr'}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
|
||||
@@ -33,9 +33,11 @@ import {
|
||||
Loader2,
|
||||
Trash2,
|
||||
Save,
|
||||
DollarSign,
|
||||
} from 'lucide-react';
|
||||
import JSZip from 'jszip';
|
||||
import { Separator } from './ui/separator';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
|
||||
interface ProjectDetailsDialogProps {
|
||||
project: Project;
|
||||
@@ -49,6 +51,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isRenaming, setIsRenaming] = useState(false);
|
||||
const [newProjectName, setNewProjectName] = useState(project.id);
|
||||
const [totalCost, setTotalCost] = useState<number | null>(null);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
@@ -62,6 +65,24 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
setIsRenaming(false);
|
||||
}, [project.id]);
|
||||
|
||||
// Load total project cost
|
||||
useEffect(() => {
|
||||
const loadCost = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
|
||||
const cost = await dotAI.readCost();
|
||||
setTotalCost(cost);
|
||||
} catch (error) {
|
||||
console.warn('Failed to load project cost:', error);
|
||||
setTotalCost(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (open) {
|
||||
loadCost();
|
||||
}
|
||||
}, [fs, projectsPath, project.id, open]);
|
||||
|
||||
const formatDistanceToNow = (date: Date) => {
|
||||
const now = new Date();
|
||||
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||
@@ -226,6 +247,15 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
<span>{formatDistanceToNow(project.lastModified)}</span>
|
||||
</div>
|
||||
|
||||
{/* Total Cost */}
|
||||
{totalCost !== null && totalCost > 0 && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<DollarSign className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Total Cost:</span>
|
||||
<span className="font-mono">${totalCost.toFixed(6)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="project-name">Project Name</Label>
|
||||
|
||||
+68
-24
@@ -11,6 +11,7 @@ import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { useState } from 'react';
|
||||
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
|
||||
import { EmptyMessageError } from '@/lib/errors/EmptyMessageError';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
export interface QuillyProps {
|
||||
error: Error;
|
||||
@@ -30,23 +31,20 @@ interface ErrorBody {
|
||||
}>;
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
interface QuillyContentProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onNewChat: () => void;
|
||||
onOpenModelSelector: () => void;
|
||||
onTryAgain?: () => void;
|
||||
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
|
||||
provider: AIProvider | undefined;
|
||||
}
|
||||
|
||||
function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, provider }: QuillyContentProps) {
|
||||
const navigate = useNavigate();
|
||||
const { settings } = useAISettings();
|
||||
|
||||
// Handle empty provider model gracefully
|
||||
let provider;
|
||||
try {
|
||||
provider = parseProviderModel(providerModel, settings.providers).provider;
|
||||
} catch {
|
||||
// If no valid provider model, use a default or undefined
|
||||
provider = undefined;
|
||||
}
|
||||
|
||||
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody => {
|
||||
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
|
||||
// Handle Project Preview Console Errors
|
||||
if (error instanceof ProjectPreviewConsoleError) {
|
||||
return {
|
||||
@@ -69,7 +67,7 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof EmptyMessageError) {
|
||||
return {
|
||||
@@ -101,13 +99,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
};
|
||||
|
||||
case error.code === 'insufficient_quota': {
|
||||
if (credits.data) {
|
||||
// Only show credits dialog if we have a provider with nostr enabled
|
||||
if (provider?.nostr) {
|
||||
return {
|
||||
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
|
||||
actions: [{
|
||||
label: 'Add credits',
|
||||
onClick: () => setShowCreditsDialog(true),
|
||||
}],
|
||||
message: 'Your account is low on credits. Please add credits to keep creating.',
|
||||
showCreditsButton: true,
|
||||
actions: [],
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
@@ -204,7 +201,7 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
};
|
||||
};
|
||||
|
||||
const { message, actions = [] } = renderBody(error);
|
||||
const { message, actions = [], showCreditsButton } = renderBody(error);
|
||||
|
||||
return (
|
||||
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
|
||||
@@ -217,6 +214,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{message}
|
||||
{showCreditsButton && provider && (
|
||||
<>
|
||||
{' '}
|
||||
<QuillyCreditsButton provider={provider} />
|
||||
</>
|
||||
)}
|
||||
{actions.length > 0 && (
|
||||
<>
|
||||
{' '}
|
||||
@@ -242,12 +245,53 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface QuillyCreditsButtonProps {
|
||||
provider: AIProvider;
|
||||
}
|
||||
|
||||
function QuillyCreditsButton({ provider }: QuillyCreditsButtonProps) {
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
const credits = useAICredits(provider);
|
||||
|
||||
return (
|
||||
<>
|
||||
<button className="text-primary underline" onClick={() => setShowCreditsDialog(true)}>
|
||||
{credits.data ? `Add credits (${credits.data.amount.toFixed(2)} remaining)` : 'Add credits'}
|
||||
</button>
|
||||
<CreditsDialog
|
||||
open={showCreditsDialog}
|
||||
onOpenChange={setShowCreditsDialog}
|
||||
provider={provider}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
const { settings } = useAISettings();
|
||||
|
||||
// Handle empty provider model gracefully
|
||||
let provider: AIProvider | undefined;
|
||||
try {
|
||||
provider = parseProviderModel(providerModel, settings.providers).provider;
|
||||
} catch {
|
||||
// If no valid provider model, use a default or undefined
|
||||
provider = undefined;
|
||||
}
|
||||
|
||||
return (
|
||||
<QuillyContent
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={onOpenModelSelector}
|
||||
onTryAgain={onTryAgain}
|
||||
onRequestConsoleErrorHelp={onRequestConsoleErrorHelp}
|
||||
provider={provider}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -42,7 +42,7 @@ describe('SentryProvider', () => {
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
@@ -78,7 +78,7 @@ describe('SentryProvider', () => {
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
@@ -115,7 +115,7 @@ describe('SentryProvider', () => {
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
@@ -155,7 +155,7 @@ describe('SentryProvider', () => {
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { ReactNode, useMemo, useEffect } from 'react';
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
|
||||
import { SessionManager } from '@/lib/SessionManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
interface SessionManagerProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -17,30 +17,80 @@ interface SessionManagerProviderProps {
|
||||
*/
|
||||
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { projectsPath, pluginsPath } = useFSPaths();
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
const { user, metadata } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const { config, defaultConfig } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
const sessionManager = useMemo(() => {
|
||||
const getProviderModels = () => models;
|
||||
const getCurrentUser = () => ({ user, metadata });
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath);
|
||||
}, [fs, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath]);
|
||||
// Create SessionManager instance only once
|
||||
const sessionManager = useRef<SessionManager | undefined>(undefined);
|
||||
|
||||
// Use refs so SessionManager always has the latest data
|
||||
const configRef = useRef(config);
|
||||
const defaultConfigRef = useRef(defaultConfig);
|
||||
const settingsRef = useRef(settings);
|
||||
const modelsRef = useRef(models);
|
||||
const userRef = useRef(user);
|
||||
const metadataRef = useRef(metadata);
|
||||
|
||||
// Update refs when values change
|
||||
useEffect(() => {
|
||||
configRef.current = config;
|
||||
}, [config]);
|
||||
|
||||
useEffect(() => {
|
||||
defaultConfigRef.current = defaultConfig;
|
||||
}, [defaultConfig]);
|
||||
|
||||
useEffect(() => {
|
||||
settingsRef.current = settings;
|
||||
}, [settings]);
|
||||
|
||||
useEffect(() => {
|
||||
modelsRef.current = models;
|
||||
}, [models]);
|
||||
|
||||
useEffect(() => {
|
||||
userRef.current = user;
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
metadataRef.current = metadata;
|
||||
}, [metadata]);
|
||||
|
||||
// Initialize SessionManager only once
|
||||
if (!sessionManager.current) {
|
||||
// Callbacks access refs to get latest values
|
||||
const getProviderModels = () => modelsRef.current;
|
||||
const getCurrentUser = () => ({ user: userRef.current, metadata: metadataRef.current });
|
||||
const getConfig = () => configRef.current;
|
||||
const getDefaultConfig = () => defaultConfigRef.current;
|
||||
const getSettings = () => settingsRef.current;
|
||||
|
||||
sessionManager.current = new SessionManager(
|
||||
fs,
|
||||
nostr,
|
||||
getSettings,
|
||||
getConfig,
|
||||
getDefaultConfig,
|
||||
getProviderModels,
|
||||
getCurrentUser,
|
||||
);
|
||||
}
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
// Fire and forget cleanup - we don't need to await in useEffect cleanup
|
||||
sessionManager.cleanup().catch(error => {
|
||||
sessionManager.current?.cleanup().catch(error => {
|
||||
console.warn('Failed to cleanup session manager:', error);
|
||||
});
|
||||
};
|
||||
}, [sessionManager]);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SessionManagerContext.Provider value={sessionManager}>
|
||||
<SessionManagerContext.Provider value={sessionManager.current}>
|
||||
{children}
|
||||
</SessionManagerContext.Provider>
|
||||
);
|
||||
|
||||
@@ -166,7 +166,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
nostr_publish_events: new NostrPublishEventsTool(),
|
||||
shell: new ShellTool(fs, cwd, git, projectsPath, user?.signer),
|
||||
shell: new ShellTool(fs, cwd, git, projectsPath, config.corsProxy, user?.signer),
|
||||
read_console_messages: new ReadConsoleMessagesTool(),
|
||||
skill: new SkillTool(fs, pluginsPath),
|
||||
};
|
||||
@@ -180,7 +180,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return baseTools;
|
||||
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, handleFileChanged]);
|
||||
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]);
|
||||
|
||||
// Convert tools to OpenAI format
|
||||
const tools = useMemo(() => {
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { encodeBase64 } from '@std/encoding/base64';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef, useMemo, memo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
|
||||
import { addConsoleMessage, getConsoleMessages, addConsoleMessageListener, removeConsoleMessageListener, type ConsoleMessage } from '@/lib/consoleMessages';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, Terminal, Trash2, ChevronRight } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
@@ -20,11 +20,6 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
@@ -88,6 +83,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const [showConsoleView, setShowConsoleView] = useState(false);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
@@ -465,6 +461,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
setFileContent('');
|
||||
setMobileCodeView('explorer');
|
||||
setDesktopCodeView('files');
|
||||
setShowConsoleView(false);
|
||||
|
||||
// Reset navigation history and state
|
||||
setCurrentPath('/');
|
||||
@@ -521,102 +518,282 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}
|
||||
};
|
||||
|
||||
const ConsoleDropdown = () => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
// Constants
|
||||
const CONSOLE_SORT_ORDER_KEY = 'consoleSortOrder';
|
||||
const COPY_FEEDBACK_DURATION = 2000;
|
||||
const MAX_CONSOLE_MESSAGES = 500; // Limit displayed messages for performance
|
||||
|
||||
const messages = isOpen ? getConsoleMessages() : [];
|
||||
// Helper function to get message level color
|
||||
const getMessageLevelColor = (level: ConsoleMessage['level']): string => {
|
||||
switch (level) {
|
||||
case 'error': return 'text-destructive';
|
||||
case 'warn': return 'text-warning';
|
||||
case 'info': return 'text-primary';
|
||||
default: return 'text-muted-foreground';
|
||||
}
|
||||
};
|
||||
|
||||
const ConsoleToggleButton = () => {
|
||||
return (
|
||||
<Button
|
||||
variant={showConsoleView ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 relative"
|
||||
onClick={() => setShowConsoleView(!showConsoleView)}
|
||||
title={showConsoleView ? "Show preview" : "Show console"}
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
{hasConsoleErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
// Individual console message component - memoized for performance
|
||||
const ConsoleMessage = memo(({ msg, index, copiedMessageIndex, onCopy }: {
|
||||
msg: ConsoleMessage;
|
||||
index: number;
|
||||
copiedMessageIndex: number | null;
|
||||
onCopy: (msg: ConsoleMessage, index: number) => void;
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onCopy(msg, index);
|
||||
}}
|
||||
>
|
||||
<div className={cn(
|
||||
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
|
||||
getMessageLevelColor(msg.level)
|
||||
)}>
|
||||
{msg.message}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onCopy(msg, index);
|
||||
}}
|
||||
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
|
||||
>
|
||||
{copiedMessageIndex === index ? (
|
||||
<Check className="h-2 w-2 text-success" />
|
||||
) : (
|
||||
<Copy className="h-2 w-2" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
ConsoleMessage.displayName = 'ConsoleMessage';
|
||||
|
||||
const ConsoleView = () => {
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
const [isInitialLoad, setIsInitialLoad] = useState(true);
|
||||
const [rawMessages, setRawMessages] = useState<ConsoleMessage[]>([]);
|
||||
const [totalMessageCount, setTotalMessageCount] = useState(0);
|
||||
|
||||
// Load sort order from localStorage, default to 'newest-first'
|
||||
const [sortOrder, setSortOrder] = useState<'newest-first' | 'oldest-first'>(() => {
|
||||
const saved = localStorage.getItem(CONSOLE_SORT_ORDER_KEY);
|
||||
return (saved === 'oldest-first' || saved === 'newest-first') ? saved : 'newest-first';
|
||||
});
|
||||
|
||||
// Save sort order to localStorage whenever it changes
|
||||
useEffect(() => {
|
||||
localStorage.setItem(CONSOLE_SORT_ORDER_KEY, sortOrder);
|
||||
}, [sortOrder]);
|
||||
|
||||
// Track rapid message bursts for intelligent batching
|
||||
const lastMessageTimeRef = useRef<number>(0);
|
||||
const pendingUpdateRef = useRef<number>();
|
||||
const messageCountSinceUpdateRef = useRef<number>(0);
|
||||
|
||||
// Update messages from the global store - optimized for immediate updates
|
||||
const updateMessages = useCallback(() => {
|
||||
const allMessages = getConsoleMessages();
|
||||
setTotalMessageCount(allMessages.length);
|
||||
|
||||
// Limit messages for performance (keep most recent)
|
||||
const limitedMessages = allMessages.length > MAX_CONSOLE_MESSAGES
|
||||
? allMessages.slice(-MAX_CONSOLE_MESSAGES)
|
||||
: allMessages;
|
||||
|
||||
setRawMessages(limitedMessages);
|
||||
setIsInitialLoad(false);
|
||||
messageCountSinceUpdateRef.current = 0;
|
||||
}, []);
|
||||
|
||||
// Smart update handler: immediate for single messages, batched for rapid bursts
|
||||
const handleMessageUpdate = useCallback(() => {
|
||||
const now = Date.now();
|
||||
const timeSinceLastMessage = now - lastMessageTimeRef.current;
|
||||
lastMessageTimeRef.current = now;
|
||||
messageCountSinceUpdateRef.current += 1;
|
||||
|
||||
// Detect rapid bursts: if we get more than 3 messages within 50ms, batch them
|
||||
const isRapidBurst = messageCountSinceUpdateRef.current > 3 && timeSinceLastMessage < 50;
|
||||
|
||||
// Clear any pending update
|
||||
if (pendingUpdateRef.current) {
|
||||
cancelAnimationFrame(pendingUpdateRef.current);
|
||||
pendingUpdateRef.current = undefined;
|
||||
}
|
||||
|
||||
if (isRapidBurst) {
|
||||
// Batch rapid updates using requestAnimationFrame for smooth rendering
|
||||
// This prevents UI blocking during loops that log many messages
|
||||
pendingUpdateRef.current = requestAnimationFrame(() => {
|
||||
updateMessages();
|
||||
});
|
||||
} else {
|
||||
// Immediate update for normal console.log calls (like browser console)
|
||||
// Single messages appear instantly, just like native browser console
|
||||
updateMessages();
|
||||
}
|
||||
}, [updateMessages]);
|
||||
|
||||
// Initial load and listener setup
|
||||
useEffect(() => {
|
||||
// Initial load - check if we have many messages
|
||||
const allMessages = getConsoleMessages();
|
||||
if (allMessages.length > 500) {
|
||||
setIsInitialLoad(true);
|
||||
// Use requestIdleCallback for non-blocking initial render, fallback to setTimeout
|
||||
const scheduleUpdate = () => {
|
||||
if ('requestIdleCallback' in window) {
|
||||
requestIdleCallback(() => {
|
||||
updateMessages();
|
||||
}, { timeout: 100 });
|
||||
} else {
|
||||
setTimeout(() => {
|
||||
updateMessages();
|
||||
}, 0);
|
||||
}
|
||||
};
|
||||
scheduleUpdate();
|
||||
} else {
|
||||
updateMessages();
|
||||
}
|
||||
|
||||
addConsoleMessageListener(handleMessageUpdate);
|
||||
return () => {
|
||||
removeConsoleMessageListener(handleMessageUpdate);
|
||||
if (pendingUpdateRef.current) {
|
||||
cancelAnimationFrame(pendingUpdateRef.current);
|
||||
}
|
||||
};
|
||||
}, [handleMessageUpdate, updateMessages]);
|
||||
|
||||
// Memoize sorted messages to avoid recalculation on every render
|
||||
const messages = useMemo(() => {
|
||||
if (sortOrder === 'newest-first') {
|
||||
// For newest-first, reverse the array (messages are stored oldest-first)
|
||||
return [...rawMessages].reverse();
|
||||
}
|
||||
return rawMessages;
|
||||
}, [rawMessages, sortOrder]);
|
||||
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(msg.message);
|
||||
setCopiedMessageIndex(index);
|
||||
setTimeout(() => setCopiedMessageIndex(null), 2000);
|
||||
setTimeout(() => setCopiedMessageIndex(null), COPY_FEEDBACK_DURATION);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy message to clipboard:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearMessages = () => {
|
||||
clearErrors();
|
||||
setCopiedMessageIndex(null);
|
||||
};
|
||||
|
||||
const messageCount = messages.length;
|
||||
const hasMoreMessages = rawMessages.length >= MAX_CONSOLE_MESSAGES;
|
||||
|
||||
return (
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<div className="h-full w-full flex flex-col bg-background">
|
||||
{/* Header */}
|
||||
<div className="h-12 flex-shrink-0 flex items-center justify-between px-4 border-b">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 relative"
|
||||
onClick={() => setShowConsoleView(false)}
|
||||
className="h-8 gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
{hasConsoleErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="end"
|
||||
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0"
|
||||
sideOffset={4}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{messageCount > 0 && (
|
||||
<>
|
||||
{hasMoreMessages && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Showing last {MAX_CONSOLE_MESSAGES.toLocaleString()} of {totalMessageCount.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setSortOrder(sortOrder === 'newest-first' ? 'oldest-first' : 'newest-first')}
|
||||
className="h-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{sortOrder === 'newest-first' ? t('latestFirst') : t('oldestFirst')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleClearMessages}
|
||||
className="h-8 w-8 p-0 text-destructive/80 hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Messages */}
|
||||
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
|
||||
{/* Messages */}
|
||||
<div className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none] bg-background text-foreground font-mono text-xs relative">
|
||||
{isInitialLoad ? (
|
||||
<div className="absolute inset-0 flex items-center justify-center z-10 bg-background">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-primary" />
|
||||
<span className="text-sm text-muted-foreground">Loading console messages...</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-2 px-1 space-y-0">
|
||||
{messageCount === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||
{/* Console prompt indicator - at top for newest-first, bottom for oldest-first */}
|
||||
{sortOrder === 'newest-first' && (
|
||||
<div className="py-0.5 px-1 flex items-center">
|
||||
<ChevronRight className="h-3 w-3 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{messages.map((msg, index) => (
|
||||
<ConsoleMessage
|
||||
key={`${index}-${msg.message.slice(0, 20)}`}
|
||||
msg={msg}
|
||||
index={index}
|
||||
copiedMessageIndex={copiedMessageIndex}
|
||||
onCopy={copyMessageToClipboard}
|
||||
/>
|
||||
))}
|
||||
{sortOrder === 'oldest-first' && (
|
||||
<div className="py-0.5 px-1 flex items-center">
|
||||
<ChevronRight className="h-3 w-3 text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
messages.map((msg, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
>
|
||||
<div className={cn(
|
||||
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
|
||||
msg.level === 'error' ? "text-destructive" :
|
||||
msg.level === 'warn' ? "text-warning" :
|
||||
msg.level === 'info' ? "text-primary" :
|
||||
"text-muted-foreground"
|
||||
)}>
|
||||
{msg.message}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
|
||||
>
|
||||
{copiedMessageIndex === index ? (
|
||||
<Check className="h-2 w-2 text-success" />
|
||||
) : (
|
||||
<Copy className="h-2 w-2" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
|
||||
>
|
||||
<X className="h-5 w-5 text-muted-foreground" />
|
||||
</button>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -689,7 +866,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<Code className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<ConsoleDropdown />
|
||||
<ConsoleToggleButton />
|
||||
<Menu />
|
||||
</div>
|
||||
)}
|
||||
@@ -697,16 +874,25 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
</div>
|
||||
|
||||
{/* Content area */}
|
||||
<div className="flex-1">
|
||||
{hasBuiltProject ? (
|
||||
<div className="flex-1 min-h-0 relative">
|
||||
{/* Console View */}
|
||||
<div className={cn("absolute inset-0", showConsoleView ? "block" : "hidden")}>
|
||||
<ConsoleView />
|
||||
</div>
|
||||
|
||||
{/* Preview iframe */}
|
||||
{hasBuiltProject && (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
className="w-full h-full border-0"
|
||||
className={cn("w-full h-full border-0", showConsoleView ? "hidden" : "block")}
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
/>
|
||||
) : (
|
||||
)}
|
||||
|
||||
{/* Build prompt */}
|
||||
{!hasBuiltProject && !showConsoleView && (
|
||||
<div className="h-full flex items-center justify-center bg-muted">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
||||
|
||||
interface TerminalProps {
|
||||
@@ -37,10 +38,11 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Initialize ShellTool
|
||||
useEffect(() => {
|
||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, user?.signer);
|
||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, config.corsProxy, user?.signer);
|
||||
|
||||
// Add welcome message
|
||||
setLines([{
|
||||
@@ -49,7 +51,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
}, [projectId, fs, git, projectsPath, user?.signer]);
|
||||
}, [projectId, fs, git, projectsPath, config.corsProxy, user?.signer]);
|
||||
|
||||
// Auto-scroll to bottom when new lines are added or execution state changes
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,24 +1,35 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
|
||||
interface ShakespeareDeployFormProps {
|
||||
host?: string;
|
||||
projectId: string;
|
||||
onSubdomainChange: (subdomain: string) => void;
|
||||
onValidationChange?: (isValid: boolean) => void;
|
||||
}
|
||||
|
||||
export function ShakespeareDeployForm({
|
||||
host = 'shakespeare.wtf',
|
||||
projectId,
|
||||
onSubdomainChange,
|
||||
onValidationChange,
|
||||
}: ShakespeareDeployFormProps) {
|
||||
const [subdomain, setSubdomain] = useState(projectId);
|
||||
|
||||
// Validate subdomain: no periods allowed (only single-level subdomains)
|
||||
const hasPeriod = subdomain.includes('.');
|
||||
const isValid = subdomain.trim() !== '' && !hasPeriod;
|
||||
|
||||
useEffect(() => {
|
||||
onSubdomainChange(subdomain);
|
||||
}, [subdomain, onSubdomainChange]);
|
||||
|
||||
useEffect(() => {
|
||||
onValidationChange?.(isValid);
|
||||
}, [isValid, onValidationChange]);
|
||||
|
||||
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
|
||||
|
||||
return (
|
||||
@@ -30,7 +41,14 @@ export function ShakespeareDeployForm({
|
||||
value={subdomain}
|
||||
onChange={(e) => setSubdomain(e.target.value)}
|
||||
placeholder={projectId}
|
||||
className={hasPeriod ? 'border-destructive' : ''}
|
||||
/>
|
||||
{hasPeriod && (
|
||||
<div className="flex items-start gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<span>Subdomain cannot contain periods. Use hyphens instead (e.g., "nostr-radar").</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Will deploy to: <span className="font-mono">{fullDomain}</span>
|
||||
</p>
|
||||
|
||||
@@ -187,13 +187,23 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
|
||||
object: currentRef,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Branch created',
|
||||
description: `Created branch "${newBranchName}"`,
|
||||
// Automatically check out the new branch
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: newBranchName.trim(),
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Close the dialog before showing the toast
|
||||
setNewBranchName('');
|
||||
setIsCreateDialogOpen(false);
|
||||
|
||||
// Show success toast indicating the branch was created and checked out
|
||||
toast({
|
||||
title: 'Branch created and checked out',
|
||||
description: `Switched to new branch "${newBranchName.trim()}"`,
|
||||
});
|
||||
|
||||
await loadBranches();
|
||||
onBranchChange?.();
|
||||
} catch (error) {
|
||||
|
||||
@@ -44,11 +44,15 @@ export interface AppConfig {
|
||||
sentryDsn: string;
|
||||
/** Whether the user has enabled Sentry error reporting */
|
||||
sentryEnabled: boolean;
|
||||
/** System prompt EJS template */
|
||||
systemPrompt?: string;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
/** Current application configuration */
|
||||
config: AppConfig;
|
||||
/** Default application configuration */
|
||||
defaultConfig: AppConfig;
|
||||
/** Update configuration using a callback that receives current config and returns new config */
|
||||
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
||||
}
|
||||
|
||||
@@ -38,28 +38,30 @@ describe('useAIProjectId', () => {
|
||||
});
|
||||
|
||||
// Mock useAppContext
|
||||
mockUseAppContext.mockReturnValue({
|
||||
config: {
|
||||
theme: 'dark',
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://github.com/example/template',
|
||||
esmUrl: 'https://esm.sh',
|
||||
corsProxy: 'https://proxy.example.com/{href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
const config = {
|
||||
theme: 'dark' as const,
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://github.com/example/template',
|
||||
esmUrl: 'https://esm.sh',
|
||||
corsProxy: 'https://proxy.example.com/{href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
mockUseAppContext.mockReturnValue({
|
||||
config,
|
||||
defaultConfig: config,
|
||||
updateConfig: vi.fn(),
|
||||
});
|
||||
|
||||
|
||||
+648
-23
@@ -1,32 +1,24 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useGitFetch } from './useGitFetch';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Create mocks that can be reconfigured per test
|
||||
const mockGit = {
|
||||
findRoot: vi.fn(),
|
||||
listRemotes: vi.fn(),
|
||||
currentBranch: vi.fn(),
|
||||
resolveRef: vi.fn(),
|
||||
fetch: vi.fn(),
|
||||
};
|
||||
|
||||
const mockToast = vi.fn();
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Mock the git operations
|
||||
vi.mock('./useGit', () => ({
|
||||
useGit: () => ({
|
||||
git: {
|
||||
findRoot: vi.fn().mockResolvedValue('/projects/test-project'),
|
||||
listRemotes: vi.fn().mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]),
|
||||
currentBranch: vi.fn().mockResolvedValue('main'),
|
||||
getRemoteInfo: vi.fn().mockResolvedValue({
|
||||
refs: {
|
||||
HEAD: {
|
||||
type: 'symref',
|
||||
target: 'refs/heads/main',
|
||||
},
|
||||
},
|
||||
}),
|
||||
resolveRef: vi.fn()
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current
|
||||
.mockResolvedValueOnce('abc123') // after default
|
||||
.mockResolvedValueOnce('abc123'), // after current
|
||||
fetch: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
git: mockGit,
|
||||
}),
|
||||
}));
|
||||
|
||||
@@ -44,7 +36,30 @@ vi.mock('./useFSPaths', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useToast', () => ({
|
||||
useToast: () => ({
|
||||
toast: mockToast,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock QueryClient to track invalidateQueries calls
|
||||
vi.mock('@tanstack/react-query', async () => {
|
||||
const actual = await vi.importActual('@tanstack/react-query');
|
||||
return {
|
||||
...actual,
|
||||
useQueryClient: () => ({
|
||||
invalidateQueries: mockInvalidateQueries,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
describe('useGitFetch', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockToast.mockClear();
|
||||
mockInvalidateQueries.mockClear();
|
||||
});
|
||||
|
||||
it('returns null state when projectId is null', async () => {
|
||||
const { result } = renderHook(() => useGitFetch(null), {
|
||||
wrapper: TestApp,
|
||||
@@ -57,7 +72,28 @@ describe('useGitFetch', () => {
|
||||
expect(result.current.isSuccess).toBe(false);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully', async () => {
|
||||
it('fetches remote updates successfully when default branch is checked out', async () => {
|
||||
// Setup mocks for default branch scenario
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef calls in order:
|
||||
// 1. Read symbolic ref for default branch (returns the ref path)
|
||||
// 2. Get default branch OID before fetch
|
||||
// 3. Get current branch OID before fetch
|
||||
// 4. Get default branch OID after fetch
|
||||
// 5. Get current branch OID after fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current (same as default)
|
||||
.mockResolvedValueOnce('abc123') // after default
|
||||
.mockResolvedValueOnce('abc123'); // after current (same as default)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
@@ -72,9 +108,207 @@ describe('useGitFetch', () => {
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
|
||||
// Verify fetch was called
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dir: '/projects/test-project',
|
||||
remote: 'origin',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully when non-default branch is checked out', async () => {
|
||||
// Setup mocks for non-default branch scenario
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef calls in order:
|
||||
// 1. Read symbolic ref for default branch (returns the ref path)
|
||||
// 2. Get default branch OID before fetch
|
||||
// 3. Get current branch OID before fetch
|
||||
// 4. Get default branch OID after fetch
|
||||
// 5. Get current branch OID after fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default (main)
|
||||
.mockResolvedValueOnce('def456') // before current (feature-branch)
|
||||
.mockResolvedValueOnce('abc123') // after default (main)
|
||||
.mockResolvedValueOnce('def456'); // after current (feature-branch)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
|
||||
// Verify fetch was called
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dir: '/projects/test-project',
|
||||
remote: 'origin',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('detects changes on default branch when checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on default branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current (same as default)
|
||||
.mockResolvedValueOnce('xyz789') // after default (changed!)
|
||||
.mockResolvedValueOnce('xyz789'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
hasChanges: true, // Changes detected on default branch
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on non-default branch when checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on non-default branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('abc123') // after default (no change)
|
||||
.mockResolvedValueOnce('xyz789'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on current branch
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on both default and non-default branches', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on both branches
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('new111') // after default (changed!)
|
||||
.mockResolvedValueOnce('new222'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on both branches
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on default branch when non-default branch is checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on default branch only
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('xyz789') // after default (changed!)
|
||||
.mockResolvedValueOnce('def456'); // after current (no change)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on default branch
|
||||
});
|
||||
});
|
||||
|
||||
it('can be manually refetched', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef for initial fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
@@ -85,11 +319,402 @@ describe('useGitFetch', () => {
|
||||
|
||||
const firstFetchTime = result.current.data?.fetchedAt;
|
||||
|
||||
// Setup mocks for refetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
// Manually trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data?.fetchedAt).toBeGreaterThanOrEqual(firstFetchTime || 0);
|
||||
});
|
||||
|
||||
// Verify fetch was called twice (initial + refetch)
|
||||
expect(mockGit.fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
describe('Toast Notifications', () => {
|
||||
it('shows toast when default branch changes (on default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789') // Changed!
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast when non-default branch changes (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on feature branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123') // main unchanged
|
||||
.mockResolvedValueOnce('xyz789'); // feature-branch changed!
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message for feature branch
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The feature-branch branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast when default branch changes (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on main branch only
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('xyz789') // main changed!
|
||||
.mockResolvedValueOnce('def456'); // feature-branch unchanged
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message for main branch
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows two toasts when both branches change (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on both branches
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('new111') // main changed!
|
||||
.mockResolvedValueOnce('new222'); // feature-branch changed!
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
// Verify both toast messages
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The feature-branch branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated twice (once per toast)
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('does not show toast on initial load', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch with changes detected in the fetch itself
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789') // Changed from before to after fetch
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Should report changes in data
|
||||
expect(result.current.data?.hasChanges).toBe(true);
|
||||
|
||||
// But no toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not show toast when no changes detected', async () => {
|
||||
// Setup mocks for initial fetch
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Setup for refetch with no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast should be shown
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Verify git status was not invalidated (filter out other queries like 'nostr')
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not show duplicate toast for same branch when default equals current', async () => {
|
||||
// Setup mocks for initial fetch
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Setup for refetch with changes (both default and current are 'main')
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789')
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Should only show one toast (for default branch), not two
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Should only invalidate once
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
+45
-18
@@ -131,25 +131,31 @@ export function useGitFetch(projectId: string | null) {
|
||||
let beforeDefaultOid: string | null = null;
|
||||
let beforeCurrentOid: string | null = null;
|
||||
|
||||
// Get remote info to find default branch
|
||||
// Get default branch from local symbolic ref
|
||||
let defaultBranch: string | null = null;
|
||||
try {
|
||||
console.log('Fetching remote info...');
|
||||
const remoteInfo = await git.getRemoteInfo({
|
||||
url: remoteUrl,
|
||||
...(credentials && {
|
||||
onAuth: () => ({
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
console.log('Reading default branch from local symbolic ref...');
|
||||
|
||||
// Extract default branch from symbolic ref
|
||||
if (remoteInfo.refs?.HEAD?.type === 'symref') {
|
||||
const symref = remoteInfo.refs.HEAD.target;
|
||||
defaultBranch = symref?.replace('refs/heads/', '') || null;
|
||||
console.log('Default branch from remote:', defaultBranch);
|
||||
// Read the symbolic ref file directly
|
||||
// The file contains something like: "ref: refs/remotes/origin/main"
|
||||
try {
|
||||
const symbolicRefContent = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `remotes/${remote.remote}/HEAD`,
|
||||
depth: 1,
|
||||
});
|
||||
// Remove "ref: " prefix and extract the branch name
|
||||
// Content looks like: "ref: refs/remotes/origin/main"
|
||||
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
|
||||
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
|
||||
if (match) {
|
||||
defaultBranch = match[1].trim();
|
||||
console.log('Default branch from local symbolic ref:', defaultBranch);
|
||||
} else {
|
||||
console.log('Could not get default branch from local symbolic ref value:', refValue);
|
||||
}
|
||||
} catch {
|
||||
console.log('No local symbolic ref found, will be set after fetch');
|
||||
}
|
||||
|
||||
// If we have a default branch, try to get its OID before fetch
|
||||
@@ -165,7 +171,7 @@ export function useGitFetch(projectId: string | null) {
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not get remote info:', error);
|
||||
console.warn('Could not read default branch from local data:', error);
|
||||
}
|
||||
|
||||
// Get current branch OID before fetch
|
||||
@@ -204,6 +210,27 @@ export function useGitFetch(projectId: string | null) {
|
||||
let afterDefaultOid: string | null = null;
|
||||
let afterCurrentOid: string | null = null;
|
||||
|
||||
// Re-read default branch from symbolic ref in case it was just created by fetch
|
||||
if (!defaultBranch) {
|
||||
try {
|
||||
const symbolicRefContent = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `remotes/${remote.remote}/HEAD`,
|
||||
depth: 1,
|
||||
});
|
||||
// Remove "ref: " prefix and extract the branch name
|
||||
// Content looks like: "ref: refs/remotes/origin/main"
|
||||
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
|
||||
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
|
||||
if (match) {
|
||||
defaultBranch = match[1].trim();
|
||||
console.log('Default branch from local symbolic ref:', defaultBranch);
|
||||
}
|
||||
} catch {
|
||||
console.log('No local symbolic ref found, will be set after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
afterDefaultOid = await git.resolveRef({
|
||||
@@ -319,7 +346,7 @@ export function useGitFetch(projectId: string | null) {
|
||||
if (currentBranchChanged && query.data.currentBranch) {
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${query.data.currentBranch} branch has new commits available.`,
|
||||
description: `The ${query.data.currentBranch} branch has ${query.data.currentBranchOid === null ? 'been deleted' : 'new commits available'}.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ interface GitStatus {
|
||||
branches: string[];
|
||||
ahead: number;
|
||||
behind: number;
|
||||
remoteBranchExists: boolean;
|
||||
}
|
||||
|
||||
export function useGitStatus(projectId: string | null) {
|
||||
@@ -59,6 +60,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,6 +82,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -200,6 +203,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
// Calculate ahead/behind
|
||||
let ahead = 0;
|
||||
let behind = 0;
|
||||
let remoteBranchExists = false;
|
||||
try {
|
||||
if (currentBranch && remotes.length > 0) {
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
@@ -224,6 +228,9 @@ export function useGitStatus(projectId: string | null) {
|
||||
ref: currentBranch,
|
||||
});
|
||||
|
||||
// Remote branch exists!
|
||||
remoteBranchExists = true;
|
||||
|
||||
if (remoteRef && localRef && remoteRef !== localRef) {
|
||||
// Get commits between local and remote
|
||||
const localCommits = await git.log({
|
||||
@@ -247,11 +254,8 @@ export function useGitStatus(projectId: string | null) {
|
||||
behind = remoteOnlyCommits.length;
|
||||
}
|
||||
} catch {
|
||||
// Remote branch might not exist or other issues
|
||||
// If we can't find remote branch, assume we're ahead if we have commits
|
||||
if (totalCommits > 0) {
|
||||
ahead = totalCommits;
|
||||
}
|
||||
// Remote branch doesn't exist
|
||||
remoteBranchExists = false;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -269,6 +273,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches,
|
||||
ahead,
|
||||
behind,
|
||||
remoteBranchExists,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking git status:', error);
|
||||
@@ -283,6 +288,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
@@ -260,4 +260,67 @@ invalid json line
|
||||
expect(sessionName1).not.toBe(sessionName2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readCost', () => {
|
||||
it('should return 0 when COST file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
const cost = await dotAI.readCost();
|
||||
expect(cost).toBe(0);
|
||||
});
|
||||
|
||||
it('should read and parse cost from COST file', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('0.123456\n');
|
||||
|
||||
const cost = await dotAI.readCost();
|
||||
expect(cost).toBe(0.123456);
|
||||
});
|
||||
|
||||
it('should return 0 for invalid cost value', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('invalid\n');
|
||||
|
||||
const cost = await dotAI.readCost();
|
||||
expect(cost).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle cost with whitespace', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(' 0.050000 \n');
|
||||
|
||||
const cost = await dotAI.readCost();
|
||||
expect(cost).toBe(0.05);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeCost', () => {
|
||||
it('should create shakespeare directory if it does not exist', async () => {
|
||||
await dotAI.writeCost(0.123456);
|
||||
|
||||
expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/shakespeare', { recursive: true });
|
||||
});
|
||||
|
||||
it('should write cost with 6 decimal places', async () => {
|
||||
await dotAI.writeCost(0.123456789);
|
||||
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/test-project/.git/shakespeare/COST',
|
||||
'0.123457\n'
|
||||
);
|
||||
});
|
||||
|
||||
it('should write zero cost correctly', async () => {
|
||||
await dotAI.writeCost(0);
|
||||
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/test-project/.git/shakespeare/COST',
|
||||
'0.000000\n'
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle write errors gracefully', async () => {
|
||||
vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Write failed'));
|
||||
|
||||
// Should not throw
|
||||
await expect(dotAI.writeCost(0.123456)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -278,4 +278,38 @@ export class DotAI {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the accumulated cost from .git/shakespeare/COST file
|
||||
* @returns The accumulated cost as a number, or 0 if the file doesn't exist
|
||||
*/
|
||||
async readCost(): Promise<number> {
|
||||
try {
|
||||
const costPath = join(this.workingDir, ".git", "shakespeare", "COST");
|
||||
const content = await this.fs.readFile(costPath, "utf8");
|
||||
const cost = parseFloat(content.trim());
|
||||
return isNaN(cost) ? 0 : cost;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the accumulated cost to .git/shakespeare/COST file
|
||||
* @param cost The accumulated cost in USD
|
||||
*/
|
||||
async writeCost(cost: number): Promise<void> {
|
||||
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
|
||||
const costPath = join(shakespeareDir, "COST");
|
||||
|
||||
try {
|
||||
// Ensure .git/shakespeare directory exists
|
||||
await this.fs.mkdir(shakespeareDir, { recursive: true });
|
||||
|
||||
// Write the cost with 6 decimal places for precision
|
||||
await this.fs.writeFile(costPath, cost.toFixed(6) + "\n");
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .git/shakespeare/COST file: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { SessionManager, type AIMessage } from './SessionManager';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import type { NPool } from '@nostrify/nostrify';
|
||||
import type { AppConfig } from '@/contexts/AppContext';
|
||||
|
||||
// Mock the filesystem
|
||||
const mockFS: JSRuntimeFS = {
|
||||
@@ -22,6 +24,39 @@ const mockFS: JSRuntimeFS = {
|
||||
realpath: vi.fn(),
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
// Mock NPool
|
||||
const mockNostr: NPool = {
|
||||
query: vi.fn(),
|
||||
req: vi.fn(),
|
||||
event: vi.fn(),
|
||||
} as unknown as NPool;
|
||||
|
||||
// Test configuration
|
||||
const testConfig: AppConfig = {
|
||||
theme: 'light',
|
||||
relayMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
|
||||
esmUrl: 'https://esm.shakespeare.diy',
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
language: 'en',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
|
||||
describe('SessionManager', () => {
|
||||
let sessionManager: SessionManager;
|
||||
const mockAISettings = {
|
||||
@@ -35,7 +70,10 @@ describe('SessionManager', () => {
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
sessionManager = new SessionManager(mockFS, mockAISettings);
|
||||
const getSettings = () => mockAISettings;
|
||||
const getConfig = () => testConfig;
|
||||
const getDefaultConfig = () => testConfig;
|
||||
sessionManager = new SessionManager(mockFS, mockNostr, getSettings, getConfig, getDefaultConfig);
|
||||
});
|
||||
|
||||
it('should initialize streaming message with reasoning content', async () => {
|
||||
|
||||
+77
-24
@@ -11,6 +11,9 @@ import { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { MalformedToolCallError } from './errors/MalformedToolCallError';
|
||||
import { EmptyMessageError } from './errors/EmptyMessageError';
|
||||
import { isEmptyMessage } from './isEmptyMessage';
|
||||
import { Git } from './git';
|
||||
import type { NPool } from '@nostrify/nostrify';
|
||||
import type { AppConfig } from '@/contexts/AppContext';
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
role: 'assistant';
|
||||
@@ -58,29 +61,34 @@ export class SessionManager {
|
||||
private sessions = new Map<string, SessionState>();
|
||||
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
|
||||
private fs: JSRuntimeFS;
|
||||
private aiSettings: { providers: AIProvider[] };
|
||||
private nostr: NPool;
|
||||
private getSettings: () => { providers: AIProvider[] };
|
||||
private getConfig: () => AppConfig;
|
||||
private getDefaultConfig: () => AppConfig;
|
||||
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
|
||||
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
|
||||
private corsProxy?: string;
|
||||
private projectsPath: string;
|
||||
private pluginsPath?: string;
|
||||
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
aiSettings: { providers: AIProvider[] },
|
||||
nostr: NPool,
|
||||
getSettings: () => { providers: AIProvider[] },
|
||||
getConfig: () => AppConfig,
|
||||
getDefaultConfig: () => AppConfig,
|
||||
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
|
||||
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
|
||||
corsProxy?: string,
|
||||
projectsPath = '/projects',
|
||||
pluginsPath?: string,
|
||||
) {
|
||||
this.fs = fs;
|
||||
this.aiSettings = aiSettings;
|
||||
this.nostr = nostr;
|
||||
this.getSettings = getSettings;
|
||||
this.getConfig = getConfig;
|
||||
this.getDefaultConfig = getDefaultConfig;
|
||||
this.getProviderModels = getProviderModels;
|
||||
this.getCurrentUser = getCurrentUser;
|
||||
this.projectsPath = projectsPath;
|
||||
this.pluginsPath = pluginsPath;
|
||||
this.corsProxy = corsProxy;
|
||||
}
|
||||
|
||||
private get git(): Git {
|
||||
const config = this.getConfig();
|
||||
return new Git({ fs: this.fs, nostr: this.nostr, corsProxy: config.corsProxy });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -97,7 +105,8 @@ export class SessionManager {
|
||||
|
||||
// Try to load existing history
|
||||
try {
|
||||
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`);
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
if (lastSession) {
|
||||
messages = lastSession.messages;
|
||||
@@ -154,7 +163,7 @@ export class SessionManager {
|
||||
*/
|
||||
async deleteSession(projectId: string): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
session?.abortController?.abort();
|
||||
session?.abortController?.abort('Session deleted');
|
||||
|
||||
this.sessions.delete(projectId);
|
||||
|
||||
@@ -209,14 +218,19 @@ export class SessionManager {
|
||||
this.emit('loadingChanged', projectId, true);
|
||||
|
||||
try {
|
||||
// Get latest config and settings
|
||||
const config = this.getConfig();
|
||||
const defaultConfig = this.getDefaultConfig();
|
||||
const settings = this.getSettings();
|
||||
|
||||
// Parse provider and model
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const parsed = parseProviderModel(providerModel, settings.providers);
|
||||
const provider = parsed.provider;
|
||||
const model = parsed.model;
|
||||
|
||||
// Initialize OpenAI client
|
||||
const { user, metadata } = this.getCurrentUser?.() ?? {};
|
||||
const openai = createAIClient(provider, user, this.corsProxy);
|
||||
const openai = createAIClient(provider, user, config.corsProxy);
|
||||
|
||||
let stepCount = 0;
|
||||
const maxSteps = session.maxSteps || 50;
|
||||
@@ -238,16 +252,26 @@ export class SessionManager {
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
// Get repository URL if available
|
||||
let repositoryUrl: string | undefined;
|
||||
try {
|
||||
const remoteUrl = await this.git.getRemoteURL(`${config.fsPathProjects}/${projectId}`, 'origin');
|
||||
repositoryUrl = remoteUrl || undefined;
|
||||
} catch {
|
||||
// No repository URL available
|
||||
}
|
||||
|
||||
const systemPrompt = await makeSystemPrompt({
|
||||
cwd: `${this.projectsPath}/${projectId}`,
|
||||
cwd: `${config.fsPathProjects}/${projectId}`,
|
||||
fs: this.fs,
|
||||
mode: "agent",
|
||||
name: "Shakespeare",
|
||||
profession: "software extraordinaire",
|
||||
tools: Object.values(session.tools),
|
||||
pluginsPath: this.pluginsPath,
|
||||
config,
|
||||
defaultConfig,
|
||||
user,
|
||||
metadata,
|
||||
repositoryUrl,
|
||||
template: config.systemPrompt,
|
||||
});
|
||||
|
||||
// Prepare messages for AI
|
||||
@@ -480,7 +504,7 @@ export class SessionManager {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
session.abortController?.abort();
|
||||
session.abortController?.abort('User stopped generation');
|
||||
session.isLoading = false;
|
||||
session.streamingMessage = undefined;
|
||||
session.abortController = undefined;
|
||||
@@ -524,7 +548,7 @@ export class SessionManager {
|
||||
/**
|
||||
* Update session cost and context usage based on usage data
|
||||
*/
|
||||
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
|
||||
private async updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): Promise<void> {
|
||||
if (!this.getProviderModels) return;
|
||||
|
||||
const session = this.sessions.get(projectId);
|
||||
@@ -534,12 +558,16 @@ export class SessionManager {
|
||||
if (typeof usage.cost === 'number') {
|
||||
session.totalCost = (session.totalCost || 0) + usage.cost;
|
||||
this.emit('costUpdated', projectId, session.totalCost);
|
||||
|
||||
// Accumulate cost to project total
|
||||
await this.accumulateProjectCost(projectId, usage.cost);
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, get the cost from the models endpoint
|
||||
try {
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const settings = this.getSettings();
|
||||
const parsed = parseProviderModel(providerModel, settings.providers);
|
||||
const modelName = parsed.model;
|
||||
const provider = parsed.provider;
|
||||
|
||||
@@ -563,6 +591,9 @@ export class SessionManager {
|
||||
// Update session total cost
|
||||
session.totalCost = (session.totalCost || 0) + requestCost;
|
||||
this.emit('costUpdated', projectId, session.totalCost);
|
||||
|
||||
// Accumulate cost to project total
|
||||
await this.accumulateProjectCost(projectId, requestCost);
|
||||
} catch (error) {
|
||||
console.warn('Failed to calculate session cost:', error);
|
||||
}
|
||||
@@ -576,13 +607,35 @@ export class SessionManager {
|
||||
if (!session) return;
|
||||
|
||||
try {
|
||||
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${session.projectId}`);
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`);
|
||||
await dotAI.setHistory(session.sessionName, session.messages);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save session history:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Accumulate request cost to the project's total cost file
|
||||
*/
|
||||
private async accumulateProjectCost(projectId: string, requestCost: number): Promise<void> {
|
||||
try {
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||
|
||||
// Read current project total
|
||||
const currentTotal = await dotAI.readCost();
|
||||
|
||||
// Add this request's cost
|
||||
const newTotal = currentTotal + requestCost;
|
||||
|
||||
// Write back the new total
|
||||
await dotAI.writeCost(newTotal);
|
||||
} catch (error) {
|
||||
console.warn('Failed to accumulate project cost:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simplified event system
|
||||
*/
|
||||
|
||||
@@ -243,14 +243,12 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
|
||||
// Handle bare imports like "react"
|
||||
build.onResolve({ filter: /^[^./].*/ }, (args) => {
|
||||
// HACK: https://github.com/esm-dev/esm.sh/issues/1217
|
||||
if (args.path === "yet-another-react-lightbox/styles.css") {
|
||||
args.path = "yet-another-react-lightbox/dist/styles.css";
|
||||
}
|
||||
const [path, query] = args.path.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
|
||||
const packageName = args.path.startsWith("@")
|
||||
? args.path.split("/").slice(0, 2).join("/")
|
||||
: args.path.split("/")[0];
|
||||
const packageName = path.startsWith("@")
|
||||
? path.split("/").slice(0, 2).join("/")
|
||||
: path.split("/")[0];
|
||||
|
||||
// If the importer is CSS, ignore (no JS deps)
|
||||
try {
|
||||
@@ -319,7 +317,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
const packagePath = args.path.slice(packageName.length);
|
||||
const packagePath = path.slice(packageName.length);
|
||||
const specifier = version
|
||||
? `${cdnName}@${version}${packagePath}`
|
||||
: `${cdnName}${packagePath}`;
|
||||
@@ -339,6 +337,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
};
|
||||
}
|
||||
|
||||
// https://vite.dev/guide/assets#explicit-url-imports
|
||||
if (params.has("url")) {
|
||||
return {
|
||||
path: urlStr,
|
||||
namespace: "esm-file-external",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
path: urlStr,
|
||||
namespace: "esm",
|
||||
@@ -426,6 +432,8 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
loader = "js";
|
||||
} else if (contentType === "text/css") {
|
||||
loader = "css";
|
||||
} else if (contentType === "application/wasm") {
|
||||
loader = "binary";
|
||||
} else {
|
||||
loader = "text";
|
||||
}
|
||||
@@ -438,6 +446,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
loader,
|
||||
};
|
||||
});
|
||||
|
||||
// Convert `?url` imports to URL strings pointing to the ESM CDN
|
||||
build.onLoad({ filter: /.*/, namespace: "esm-file-external" }, (args) => {
|
||||
return {
|
||||
contents: `export default ${JSON.stringify(args.path)};`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ async function bundle(
|
||||
options: BuildProjectOptions,
|
||||
): Promise<Record<string, Uint8Array>> {
|
||||
const { fs, projectPath, domParser, target = "esnext", esmUrl } = options;
|
||||
const esbuild = await getEsbuild(esmUrl);
|
||||
const esbuild = await getEsbuild();
|
||||
|
||||
const indexHtmlText = await fs.readFile(
|
||||
`${projectPath}/index.html`,
|
||||
|
||||
@@ -23,9 +23,10 @@ const mockFS: JSRuntimeFS = {
|
||||
|
||||
describe('CurlCommand', () => {
|
||||
let curlCommand: CurlCommand;
|
||||
const testCorsProxy = 'https://proxy.shakespeare.diy/?url={href}';
|
||||
|
||||
beforeEach(() => {
|
||||
curlCommand = new CurlCommand(mockFS);
|
||||
curlCommand = new CurlCommand(mockFS, testCorsProxy);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
import { isAbsolutePath, validateWritePath } from "../security";
|
||||
import { proxyUrl } from "../proxyUrl";
|
||||
|
||||
/**
|
||||
* Parsed curl options
|
||||
@@ -35,9 +36,11 @@ export class CurlCommand implements ShellCommand {
|
||||
usage = 'curl [options] <url>';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
private corsProxy: string;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
constructor(fs: JSRuntimeFS, corsProxy: string) {
|
||||
this.fs = fs;
|
||||
this.corsProxy = corsProxy;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
|
||||
@@ -61,9 +64,9 @@ export class CurlCommand implements ShellCommand {
|
||||
return createErrorResult(`${this.name}: unsupported protocol: ${url.protocol}`);
|
||||
}
|
||||
|
||||
// Proxy the URL through CorsProxy
|
||||
// Proxy the URL through configured CorsProxy
|
||||
const originalUrl = url.toString();
|
||||
const proxiedUrl = `https://proxy.shakespeare.diy/?url=${encodeURIComponent(originalUrl)}`;
|
||||
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
|
||||
|
||||
// Prepare request
|
||||
const requestInit: RequestInit = {
|
||||
@@ -93,7 +96,7 @@ export class CurlCommand implements ShellCommand {
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
if (options.timeout) {
|
||||
timeoutId = setTimeout(() => controller.abort(), options.timeout * 1000);
|
||||
timeoutId = setTimeout(() => controller.abort('Request timeout'), options.timeout * 1000);
|
||||
requestInit.signal = controller.signal;
|
||||
}
|
||||
|
||||
|
||||
+6
-5
@@ -1,22 +1,23 @@
|
||||
import type _ESBuild from "esbuild-wasm";
|
||||
import wasmUrl from "esbuild-wasm/esbuild.wasm?url";
|
||||
|
||||
type ESBuild = typeof _ESBuild;
|
||||
|
||||
let promise: Promise<ESBuild> | undefined;
|
||||
|
||||
export function getEsbuild(esmUrl: string): Promise<ESBuild> {
|
||||
export function getEsbuild(): Promise<ESBuild> {
|
||||
if (!promise) {
|
||||
promise = loadEsbuild(esmUrl);
|
||||
promise = loadEsbuild();
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function loadEsbuild(esmUrl: string): Promise<ESBuild> {
|
||||
async function loadEsbuild(): Promise<ESBuild> {
|
||||
const { default: esbuild } = await import("esbuild-wasm");
|
||||
|
||||
await esbuild.initialize({
|
||||
worker: false,
|
||||
wasmURL: `${esmUrl}/[email protected]/esbuild.wasm`,
|
||||
worker: true,
|
||||
wasmURL: wasmUrl,
|
||||
});
|
||||
|
||||
return esbuild;
|
||||
|
||||
+152
-33
@@ -681,12 +681,14 @@ export class Git {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current repository state for creating a NIP-34 repository state event
|
||||
* Create initial repository state from current local git repository
|
||||
* This should only be used when no existing state event is found
|
||||
*/
|
||||
private async getCurrentRepositoryState(dir: string): Promise<{
|
||||
refTags: string[][];
|
||||
headRef?: string;
|
||||
}> {
|
||||
private async createInitialRepositoryState(
|
||||
dir: string,
|
||||
dTag: string,
|
||||
signer: NostrSigner
|
||||
): Promise<NostrEvent> {
|
||||
const refTags: string[][] = [];
|
||||
let headRef: string | undefined;
|
||||
|
||||
@@ -765,11 +767,70 @@ export class Git {
|
||||
}
|
||||
|
||||
console.log(`Repository state: ${refTags.length} refs, HEAD=${headRef}`);
|
||||
return { refTags, headRef };
|
||||
} catch (error) {
|
||||
console.error('Failed to get repository state:', error);
|
||||
throw new Error(`Failed to get repository state: ${error}`);
|
||||
}
|
||||
|
||||
// Create and sign the state event
|
||||
return await signer.signEvent({
|
||||
kind: 30618,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
content: '',
|
||||
tags: [
|
||||
['d', dTag],
|
||||
...refTags,
|
||||
...(headRef ? [['HEAD', headRef]] : []),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply changes from a push operation to repository state and create updated event
|
||||
* Mutates the state object directly and returns the signed event
|
||||
*/
|
||||
private async applyPushAndUpdateStateEvent(
|
||||
state: RespositoryState,
|
||||
remoteRef: string,
|
||||
newCommit: string,
|
||||
signer: NostrSigner
|
||||
): Promise<NostrEvent> {
|
||||
const remoteRefName = remoteRef.startsWith('refs/') ? remoteRef : `refs/heads/${remoteRef}`;
|
||||
|
||||
// Update the ref
|
||||
state.refs[remoteRefName] = newCommit;
|
||||
|
||||
// Update head commit if this ref is HEAD
|
||||
if (state.HEAD === `ref: ${remoteRefName}`) {
|
||||
state.headCommit = newCommit;
|
||||
}
|
||||
|
||||
// Extract d tag from original event
|
||||
const dTag = state.event.tags.find(([name]) => name === 'd');
|
||||
if (!dTag || !dTag[1]) {
|
||||
throw new Error('Repository state event missing required d tag');
|
||||
}
|
||||
|
||||
const tags: string[][] = [['d', dTag[1]]];
|
||||
|
||||
// Add HEAD if set
|
||||
if (state.HEAD) {
|
||||
tags.push(['HEAD', state.HEAD]);
|
||||
}
|
||||
// Add all refs
|
||||
for (const [ref, commit] of Object.entries(state.refs)) {
|
||||
tags.push([ref, commit]);
|
||||
}
|
||||
|
||||
// Create and sign the updated event
|
||||
state.event = await signer.signEvent({
|
||||
kind: 30618,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
content: '',
|
||||
tags,
|
||||
});
|
||||
|
||||
return state.event;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1327,7 +1388,7 @@ export class Git {
|
||||
|
||||
/**
|
||||
* Update remote tracking refs to match the Nostr state if git data present locally
|
||||
* @returns refs with missing data including HEAD
|
||||
* @returns refs with missing data including HEAD, updated refs, and deleted stale refs
|
||||
*/
|
||||
private async updateRemoteRefsToNostrState(
|
||||
state: RespositoryState,
|
||||
@@ -1335,18 +1396,22 @@ export class Git {
|
||||
): Promise<{
|
||||
updated?: Record<string, string>,
|
||||
refsWithMissingData?: Record<string, string>,
|
||||
deleted?: string[],
|
||||
}> {
|
||||
// Get the remote name from options (passed from the fetch call)
|
||||
const remoteName = options.remote || 'origin';
|
||||
|
||||
const refsWithMissingData: Record<string, string> = {};
|
||||
const updated: Record<string, string> = {};
|
||||
for (const [refName, entry] of [
|
||||
const entries = [
|
||||
...Object.entries(state.refs),
|
||||
...(state.HEAD ? [["HEAD", state.HEAD]] : [])
|
||||
]) {
|
||||
];
|
||||
for (const [refName, entry] of entries) {
|
||||
// update symbolic ref to use remote ref
|
||||
const value = entry.startsWith("ref: ") ? `ref: ${this.localRefToRemoteRef(remoteName, entry.slice(5))}` : entry;
|
||||
const isSymbolic = value.startsWith("ref: ");
|
||||
const refValue = isSymbolic ? value.slice(5) : value; // Remove "ref: " prefix for symbolic refs
|
||||
try {
|
||||
// Check if we have this commit locally
|
||||
try {
|
||||
@@ -1356,27 +1421,32 @@ export class Git {
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
ref:remoteRefName,
|
||||
depth: 1, // Don't resolve symbolic refs, just get the raw value
|
||||
});
|
||||
// update correct ref
|
||||
if (existingValue === value) continue;
|
||||
if (existingValue === refValue) continue;
|
||||
} catch {
|
||||
// ref doesnt exist yet
|
||||
}
|
||||
if (!value.startsWith("ref: ")) await git.readCommit({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
// TODO handle and annotated tags
|
||||
oid: value,
|
||||
});
|
||||
// We have the commit, update the remote tracking ref
|
||||
if (!isSymbolic) {
|
||||
// For non-symbolic refs, verify we have the commit locally
|
||||
await git.readCommit({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
// TODO handle annotated tags
|
||||
oid: refValue,
|
||||
});
|
||||
}
|
||||
// We have the commit (or it's a symbolic ref), update the remote tracking ref
|
||||
await git.writeRef({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
ref: remoteRefName,
|
||||
force: true, // standard behaviour of git fetch
|
||||
value: value,
|
||||
value: refValue,
|
||||
symbolic: isSymbolic, // Set symbolic flag for symbolic refs
|
||||
});
|
||||
console.log(`✓ Updated ${remoteRefName} to ${value}`);
|
||||
console.log(`✓ Updated ${remoteRefName} to ${isSymbolic ? 'ref: ' : ''}${refValue}`);
|
||||
updated[refName] = entry;
|
||||
} catch (error) {
|
||||
refsWithMissingData[refName] = value;
|
||||
@@ -1388,9 +1458,48 @@ export class Git {
|
||||
}
|
||||
}
|
||||
|
||||
// Delete local remote refs that don't exist in Repository State
|
||||
const deleted: string[] = [];
|
||||
try {
|
||||
// Get all local remote tracking refs for this remote
|
||||
const localRemoteRefs = await git.listRefs({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
filepath: `refs/remotes/${remoteName}`
|
||||
});
|
||||
|
||||
// Build set of expected remote refs based on Repository State
|
||||
// This should match the same set of refs we iterated over above
|
||||
const expectedRemoteRefs = new Set<string>();
|
||||
for (const [refName] of entries) {
|
||||
expectedRemoteRefs.add(this.localRefToRemoteRef(remoteName, refName));
|
||||
}
|
||||
// Delete any local remote refs that don't exist in the Repository State
|
||||
for (const localRemoteRef of localRemoteRefs) {
|
||||
const fullRef = this.localRefToRemoteRef(remoteName, localRemoteRef);
|
||||
|
||||
if (!expectedRemoteRefs.has(fullRef)) {
|
||||
try {
|
||||
await git.deleteRef({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
ref: fullRef,
|
||||
});
|
||||
console.log(`✓ Deleted stale remote ref ${localRemoteRef}`);
|
||||
deleted.push(localRemoteRef);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to delete stale remote ref ${localRemoteRef}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to clean up stale remote refs:', error);
|
||||
}
|
||||
|
||||
return {
|
||||
refsWithMissingData: Object.keys(refsWithMissingData).length > 0 ? refsWithMissingData : undefined,
|
||||
updated: Object.keys(updated).length > 0 ? updated : undefined,
|
||||
deleted: deleted.length > 0 ? deleted : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1774,7 +1883,7 @@ export class Git {
|
||||
}
|
||||
|
||||
// Extract relay URLs and clone URLs from the repository announcement
|
||||
const relayUrls: string[] = [];
|
||||
const relayUrls: string[] = [ ...(repo.relays) ?? []];
|
||||
|
||||
// If no relays specified in announcement, use default git-focused relays
|
||||
if (relayUrls.length === 0) {
|
||||
@@ -1813,20 +1922,30 @@ export class Git {
|
||||
}
|
||||
}
|
||||
|
||||
// Get current repository state
|
||||
const repoState = await this.getCurrentRepositoryState(dir);
|
||||
// Update or create repository state
|
||||
let stateEvent: NostrEvent;
|
||||
|
||||
// Create repository state event (kind 30618)
|
||||
const stateEvent = await signer.signEvent({
|
||||
kind: 30618,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
content: '',
|
||||
tags: [
|
||||
['d', nostrURI.d], // Repository identifier
|
||||
...repoState.refTags,
|
||||
...(repoState.headRef ? [['HEAD', repoState.headRef]] : []),
|
||||
],
|
||||
});
|
||||
if (state) {
|
||||
// We have an existing state event - update it with the new ref
|
||||
|
||||
// Get the commit we're pushing
|
||||
let localCommit: string;
|
||||
try {
|
||||
localCommit = await git.resolveRef({
|
||||
fs: this.fs,
|
||||
dir,
|
||||
ref,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to resolve local ref ${ref}: ${error}`);
|
||||
}
|
||||
|
||||
// Apply push changes and create updated event
|
||||
stateEvent = await this.applyPushAndUpdateStateEvent(state, remoteRef, localCommit, signer);
|
||||
} else {
|
||||
// No existing state event - create initial state from repository
|
||||
stateEvent = await this.createInitialRepositoryState(dir, nostrURI.d, signer);
|
||||
}
|
||||
|
||||
// Publish the state event to Nostr relays
|
||||
console.log(`Publishing repository state to ${relayUrls.length} relays`);
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ export async function initializeSentry(dsn: string): Promise<void> {
|
||||
// Environment
|
||||
environment: import.meta.env.MODE,
|
||||
// Release
|
||||
release: import.meta.env.VERSION || 'development',
|
||||
release: import.meta.env.VERSION,
|
||||
// Censor sensitive data before sending to Sentry
|
||||
beforeSend(event) {
|
||||
// Regex to match Nostr nsec private keys
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { makeSystemPrompt, MakeSystemPromptOpts } from './system';
|
||||
import { JSRuntimeFS } from './JSRuntime';
|
||||
import { NUser } from '@nostrify/react/login';
|
||||
import { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import OpenAI from 'openai';
|
||||
|
||||
// Mock the plugins module
|
||||
vi.mock('./plugins', () => ({
|
||||
getAllSkills: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock path-browserify
|
||||
vi.mock('path-browserify', () => ({
|
||||
join: (...args: string[]) => args.join('/').replace(/\/+/g, '/'),
|
||||
}));
|
||||
|
||||
import { getAllSkills } from './plugins';
|
||||
|
||||
// Test configuration
|
||||
const testConfig: AppConfig = {
|
||||
theme: 'light',
|
||||
relayMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
|
||||
esmUrl: 'https://esm.shakespeare.diy',
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
language: 'en',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
|
||||
describe('makeSystemPrompt', () => {
|
||||
let mockFs: JSRuntimeFS;
|
||||
let baseOpts: MakeSystemPromptOpts;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock filesystem
|
||||
mockFs = {
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
exists: vi.fn(),
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
// Base options for tests
|
||||
baseOpts = {
|
||||
tools: [],
|
||||
mode: 'agent',
|
||||
fs: mockFs,
|
||||
cwd: '/projects/test-project',
|
||||
config: testConfig,
|
||||
defaultConfig: testConfig,
|
||||
};
|
||||
|
||||
// Mock getAllSkills to return empty array by default
|
||||
vi.mocked(getAllSkills).mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe('basic system prompt generation', () => {
|
||||
it('should generate a basic system prompt in agent mode', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('You are Shakespeare, an expert software extraordinaire');
|
||||
expect(result).toContain('Your goal is to work on the project in the current directory');
|
||||
expect(result).toContain('explore and understand the project structure');
|
||||
});
|
||||
|
||||
it('should generate a basic system prompt in init mode', async () => {
|
||||
const result = await makeSystemPrompt({ ...baseOpts, mode: 'init' });
|
||||
|
||||
expect(result).toContain('You are Shakespeare, an expert software extraordinaire');
|
||||
expect(result).toContain('The files in the current directory are a template');
|
||||
expect(result).toContain('transform this template into a working project');
|
||||
});
|
||||
|
||||
it('should include current date', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
const currentDate = new Date().toLocaleDateString('en-US', {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
});
|
||||
|
||||
expect(result).toContain(`**Current Date**: ${currentDate}`);
|
||||
});
|
||||
|
||||
it('should include current working directory', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('**Current Working Directory**: /projects/test-project');
|
||||
});
|
||||
});
|
||||
|
||||
describe('user information', () => {
|
||||
it('should include logged-out user message when no user is provided', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('The user is not logged in');
|
||||
expect(result).toContain('can log into Nostr by clicking the "Login" button');
|
||||
});
|
||||
|
||||
it('should include basic user information when user is provided', async () => {
|
||||
const user = new NUser(
|
||||
'extension',
|
||||
'abc123def456',
|
||||
{} as NUser['signer']
|
||||
);
|
||||
|
||||
const result = await makeSystemPrompt({ ...baseOpts, user });
|
||||
|
||||
expect(result).toContain('The user is logged into Nostr');
|
||||
expect(result).toContain('**Nostr pubkey (hex)**: abc123def456');
|
||||
expect(result).toContain('**Nostr npub**: npub1');
|
||||
});
|
||||
|
||||
it('should include user metadata when provided', async () => {
|
||||
const user = new NUser(
|
||||
'extension',
|
||||
'abc123def456',
|
||||
{} as NUser['signer']
|
||||
);
|
||||
|
||||
const metadata: NostrMetadata = {
|
||||
name: 'Alice',
|
||||
about: 'A passionate developer',
|
||||
website: 'https://alice.example.com',
|
||||
picture: 'https://alice.example.com/avatar.jpg',
|
||||
banner: 'https://alice.example.com/banner.jpg',
|
||||
nip05: '[email protected]',
|
||||
lud16: '[email protected]',
|
||||
};
|
||||
|
||||
const result = await makeSystemPrompt({ ...baseOpts, user, metadata });
|
||||
|
||||
expect(result).toContain('**Name**: Alice');
|
||||
expect(result).toContain('**About**: A passionate developer');
|
||||
expect(result).toContain('**Website**: https://alice.example.com');
|
||||
expect(result).toContain('**Avatar**: https://alice.example.com/avatar.jpg');
|
||||
expect(result).toContain('**Banner**: https://alice.example.com/banner.jpg');
|
||||
expect(result).toContain('**NIP-05**: [email protected]');
|
||||
expect(result).toContain('**Lightning Address**: [email protected]');
|
||||
});
|
||||
|
||||
it('should sanitize multiline about text', async () => {
|
||||
const user = new NUser(
|
||||
'extension',
|
||||
'abc123def456',
|
||||
{} as NUser['signer']
|
||||
);
|
||||
|
||||
const metadata: NostrMetadata = {
|
||||
about: 'Line 1\nLine 2\r\nLine 3',
|
||||
};
|
||||
|
||||
const result = await makeSystemPrompt({ ...baseOpts, user, metadata });
|
||||
|
||||
expect(result).toContain('**About**: Line 1 Line 2 Line 3');
|
||||
expect(result).not.toContain('\n**About**');
|
||||
});
|
||||
});
|
||||
|
||||
describe('tools section', () => {
|
||||
it('should not include tools section when no tools are provided', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).not.toContain('## Available Tools');
|
||||
});
|
||||
|
||||
it('should list available tools with descriptions', async () => {
|
||||
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'read_file',
|
||||
description: 'Read contents of a file',
|
||||
parameters: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'write_file',
|
||||
description: 'Write contents to a file',
|
||||
parameters: {},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const result = await makeSystemPrompt({ ...baseOpts, tools });
|
||||
|
||||
expect(result).toContain('## Available Tools');
|
||||
expect(result).toContain('**read_file**: Read contents of a file');
|
||||
expect(result).toContain('**write_file**: Write contents to a file');
|
||||
});
|
||||
|
||||
it('should handle tools without descriptions', async () => {
|
||||
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'some_tool',
|
||||
parameters: {},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const result = await makeSystemPrompt({ ...baseOpts, tools });
|
||||
|
||||
expect(result).toContain('**some_tool**: No description available');
|
||||
});
|
||||
});
|
||||
|
||||
describe('skills section', () => {
|
||||
it('should show no skills message when pluginsPath is not provided', async () => {
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
config: { ...testConfig, fsPathPlugins: '' },
|
||||
});
|
||||
|
||||
expect(result).toContain('## Skills');
|
||||
expect(result).toContain('No skills are currently configured');
|
||||
});
|
||||
|
||||
it('should show no skills message when getAllSkills returns empty array', async () => {
|
||||
vi.mocked(getAllSkills).mockResolvedValue([]);
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('No skills are currently configured');
|
||||
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins');
|
||||
});
|
||||
|
||||
it('should list available skills when they exist', async () => {
|
||||
vi.mocked(getAllSkills).mockResolvedValue([
|
||||
{
|
||||
name: 'create_component',
|
||||
description: 'Create a new React component',
|
||||
plugin: 'react-plugin',
|
||||
path: '/plugins/react-plugin/skills/create_component.md',
|
||||
},
|
||||
{
|
||||
name: 'setup_routing',
|
||||
description: 'Setup React Router',
|
||||
plugin: 'react-plugin',
|
||||
path: '/plugins/react-plugin/skills/setup_routing.md',
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('## Skills');
|
||||
expect(result).toContain('**create_component**: Create a new React component');
|
||||
expect(result).toContain('Plugin: react-plugin');
|
||||
expect(result).toContain('**setup_routing**: Setup React Router');
|
||||
expect(result).toContain('Skills MUST be used whenever applicable');
|
||||
});
|
||||
|
||||
it('should handle getAllSkills errors gracefully', async () => {
|
||||
vi.mocked(getAllSkills).mockRejectedValue(new Error('Plugin error'));
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('No skills are currently configured');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CORS proxy section', () => {
|
||||
it('should not include CORS proxy section when not provided', async () => {
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
config: { ...testConfig, corsProxy: '' },
|
||||
});
|
||||
|
||||
expect(result).not.toContain('## Working Around CORS Issues');
|
||||
});
|
||||
|
||||
it('should include CORS proxy information when provided', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('## Working Around CORS Issues');
|
||||
expect(result).toContain('**CORS Proxy URL Template**: `https://proxy.shakespeare.diy/?url={href}`');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Edit with Shakespeare section', () => {
|
||||
it('should show message when no repository URL is configured', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('## Edit with Shakespeare');
|
||||
expect(result).toContain('This project does not currently have a repository URL configured');
|
||||
});
|
||||
|
||||
it('should include badge code snippets when repository URL is provided', async () => {
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
repositoryUrl: 'https://github.com/user/repo.git',
|
||||
});
|
||||
|
||||
expect(result).toContain('## Edit with Shakespeare');
|
||||
expect(result).toContain('[![Edit with Shakespeare]');
|
||||
expect(result).toContain('/badge.svg');
|
||||
expect(result).toContain('/clone');
|
||||
// URL is encoded, so check for the encoded version
|
||||
expect(result).toContain('url=https%3A%2F%2Fgithub.com%2Fuser%2Frepo.git');
|
||||
});
|
||||
});
|
||||
|
||||
describe('README.md inclusion', () => {
|
||||
it('should include README.md content when it exists', async () => {
|
||||
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
|
||||
if (path === '/projects/test-project/README.md') {
|
||||
return '# My Project\n\nThis is a test project.';
|
||||
}
|
||||
throw new Error('File not found');
|
||||
});
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('# My Project');
|
||||
expect(result).toContain('This is a test project.');
|
||||
});
|
||||
|
||||
it('should continue when README.md does not exist', async () => {
|
||||
vi.mocked(mockFs.readFile).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result).not.toContain('# My Project');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AGENTS.md and context files inclusion', () => {
|
||||
it('should include AGENTS.md content when it exists', async () => {
|
||||
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
|
||||
if (path === '/projects/test-project/AGENTS.md') {
|
||||
return '# Agent Instructions\n\nFollow these guidelines.';
|
||||
}
|
||||
throw new Error('File not found');
|
||||
});
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('# Agent Instructions');
|
||||
expect(result).toContain('Follow these guidelines.');
|
||||
});
|
||||
|
||||
it('should try alternative context files in order', async () => {
|
||||
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
|
||||
if (path === '/projects/test-project/CONTEXT.md') {
|
||||
return '# Context File\n\nProject context.';
|
||||
}
|
||||
throw new Error('File not found');
|
||||
});
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('# Context File');
|
||||
expect(result).toContain('Project context.');
|
||||
});
|
||||
|
||||
it('should continue when no context files exist', async () => {
|
||||
vi.mocked(mockFs.readFile).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should try context files in correct order', async () => {
|
||||
const readFileCalls: string[] = [];
|
||||
|
||||
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
|
||||
readFileCalls.push(path);
|
||||
throw new Error('File not found');
|
||||
});
|
||||
|
||||
await makeSystemPrompt(baseOpts);
|
||||
|
||||
// Check that AGENTS.md is tried first
|
||||
expect(readFileCalls).toContain('/projects/test-project/AGENTS.md');
|
||||
});
|
||||
});
|
||||
|
||||
describe('complete system prompt structure', () => {
|
||||
it('should include all major sections', async () => {
|
||||
// Use a valid hex pubkey (64 characters)
|
||||
const validPubkey = '0'.repeat(64);
|
||||
const user = new NUser('extension', validPubkey, {} as NUser['signer']);
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
user,
|
||||
repositoryUrl: 'https://github.com/test/repo.git',
|
||||
});
|
||||
|
||||
expect(result).toContain('# Your Environment');
|
||||
expect(result).toContain('## What Shakespeare Is');
|
||||
expect(result).toContain('## The User');
|
||||
expect(result).toContain('## User Interface');
|
||||
expect(result).toContain('## User Actions');
|
||||
expect(result).toContain('## Virtual Filesystem Structure');
|
||||
expect(result).toContain('## Your Role');
|
||||
expect(result).toContain('## Skills');
|
||||
expect(result).toContain('## Working Around CORS Issues');
|
||||
expect(result).toContain('## Edit with Shakespeare');
|
||||
});
|
||||
|
||||
it('should include Shakespeare architecture information', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('Browser-Based Storage');
|
||||
expect(result).toContain('AI Provider Independence');
|
||||
expect(result).toContain('Shakespeare AI Credits');
|
||||
expect(result).toContain('Cross-Browser Access');
|
||||
expect(result).toContain('No Central Shakespeare Server');
|
||||
});
|
||||
|
||||
it('should include user interface description', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('**Homepage**');
|
||||
expect(result).toContain('**Project View**');
|
||||
expect(result).toContain('**Settings**');
|
||||
expect(result).toContain('**Left Pane**: AI chat interface');
|
||||
expect(result).toContain('**Right Pane**: Toggles between two views');
|
||||
});
|
||||
|
||||
it('should include virtual filesystem structure', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('/projects/');
|
||||
// The config/ and tmp/ paths are in a code block, so check for the exact format
|
||||
expect(result).toContain('├── config/');
|
||||
expect(result).toContain('└── tmp/');
|
||||
expect(result).toContain('Project Isolation');
|
||||
expect(result).toContain('Persistent Storage');
|
||||
});
|
||||
|
||||
it('should include role description with commit reminder', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('## Your Role');
|
||||
expect(result).toContain('Always commit your code changes');
|
||||
});
|
||||
});
|
||||
|
||||
describe('custom template support', () => {
|
||||
it('should render a custom template when provided', async () => {
|
||||
const customTemplate = `Hello Shakespeare! Current directory: {{ cwd }}`;
|
||||
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
template: customTemplate,
|
||||
});
|
||||
|
||||
expect(result).toContain('Hello Shakespeare!');
|
||||
expect(result).toContain('Current directory: /projects/test-project');
|
||||
expect(result).not.toContain('# Your Environment'); // Should not include default template content
|
||||
});
|
||||
|
||||
it('should support conditional logic in custom templates', async () => {
|
||||
const customTemplate = `{% if mode === 'init' %}Initializing...{% else %}Working on project{% endif %}`;
|
||||
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
mode: 'agent',
|
||||
template: customTemplate,
|
||||
});
|
||||
|
||||
expect(result).toContain('Working on project');
|
||||
expect(result).not.toContain('Initializing');
|
||||
});
|
||||
|
||||
it('should provide access to all context variables in custom templates', async () => {
|
||||
const user = new NUser(
|
||||
'extension',
|
||||
'abc123def456',
|
||||
{} as NUser['signer']
|
||||
);
|
||||
|
||||
const customTemplate = `User: {{ user.pubkey if user else 'none' }}
|
||||
CWD: {{ cwd }}
|
||||
Origin: {{ location.origin }}
|
||||
Skills: {{ skills.length }}`;
|
||||
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
user,
|
||||
template: customTemplate,
|
||||
});
|
||||
|
||||
expect(result).toContain('User: abc123def456');
|
||||
expect(result).toContain('CWD: /projects/test-project');
|
||||
expect(result).toContain('Origin: http://localhost:3000');
|
||||
expect(result).toContain('Skills: 0');
|
||||
});
|
||||
});
|
||||
});
|
||||
+164
-91
@@ -3,64 +3,38 @@ import { NostrMetadata } from "@nostrify/nostrify";
|
||||
import { join } from "path-browserify";
|
||||
import OpenAI from "openai";
|
||||
import { nip19 } from "nostr-tools";
|
||||
import nunjucks from "nunjucks";
|
||||
import { JSRuntimeFS } from "./JSRuntime";
|
||||
import { getAllSkills } from "./plugins";
|
||||
import type { AppConfig } from "@/contexts/AppContext";
|
||||
|
||||
export interface MakeSystemPromptOpts {
|
||||
name: string;
|
||||
profession: string;
|
||||
tools: OpenAI.Chat.Completions.ChatCompletionTool[];
|
||||
mode: "init" | "agent";
|
||||
fs: JSRuntimeFS;
|
||||
cwd: string;
|
||||
pluginsPath?: string;
|
||||
config: AppConfig;
|
||||
defaultConfig: AppConfig;
|
||||
user?: NUser;
|
||||
metadata?: NostrMetadata;
|
||||
repositoryUrl?: string;
|
||||
template?: string;
|
||||
}
|
||||
|
||||
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
|
||||
const { name, profession, tools, mode, fs, cwd, pluginsPath, user, metadata } = opts;
|
||||
/**
|
||||
* Default system prompt template.
|
||||
* This can be customized by users in Settings > System > System Prompt.
|
||||
*/
|
||||
export const defaultSystemPrompt = `{% if mode === "init" %}You are Shakespeare, an expert software extraordinaire. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.{% else %}You are Shakespeare, an expert software extraordinaire. Your goal is to work on the project in the current directory according to the user's request. First, explore and understand the project structure, examine the existing files, and understand the context before making any assumptions about what the user is asking for.{% endif %}
|
||||
|
||||
let system = mode === "init"
|
||||
? `You are ${name}, an expert ${profession}. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.`
|
||||
: `You are ${name}, an expert ${profession}. Your goal is to work on the project in the current directory according to the user's request. First, explore and understand the project structure, examine the existing files, and understand the context before making any assumptions about what the user is asking for.`;
|
||||
|
||||
// Add current date
|
||||
const currentDate = new Date().toLocaleDateString("en-US", {
|
||||
weekday: "long",
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
let userText: string;
|
||||
if (user) {
|
||||
userText = `The user is logged into Nostr with the following profile:
|
||||
|
||||
- **Nostr pubkey (hex)**: ${user.pubkey}
|
||||
- **Nostr npub**: ${nip19.npubEncode(user.pubkey)}`;
|
||||
|
||||
if (metadata?.name) userText += `\n- **Name**: ${metadata.name}`;
|
||||
if (metadata?.about) userText += `\n- **About**: ${metadata.about.replace(/[\r\n]+/g, ' ')}`;
|
||||
if (metadata?.website) userText += `\n- **Website**: ${metadata.website}`;
|
||||
if (metadata?.picture) userText += `\n- **Avatar**: ${metadata.picture}`;
|
||||
if (metadata?.banner) userText += `\n- **Banner**: ${metadata.banner}`;
|
||||
if (metadata?.nip05) userText += `\n- **NIP-05**: ${metadata.nip05}`;
|
||||
if (metadata?.lud16) userText += `\n- **Lightning Address**: ${metadata.lud16}`;
|
||||
|
||||
userText += `\n\nSince the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
} else {
|
||||
userText = `The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
}
|
||||
|
||||
// Add Your Environment section
|
||||
system += `\n\n# Your Environment
|
||||
# Your Environment
|
||||
|
||||
You are operating within **Shakespeare**, an AI-powered Nostr website builder that allows users to create custom Nostr applications through natural language conversation.
|
||||
|
||||
- **Current Date**: ${currentDate}
|
||||
- **Current Page**: ${location.href}
|
||||
- **Current Working Directory**: ${cwd}
|
||||
- **Current Date**: {{ date }}
|
||||
- **Current Page**: {{ location.href }}
|
||||
- **Current Working Directory**: {{ cwd }}
|
||||
- **Repository URL**: {{ repositoryUrl }}
|
||||
|
||||
## What Shakespeare Is
|
||||
|
||||
@@ -78,7 +52,19 @@ Shakespeare is a web-based development environment where users can build Nostr w
|
||||
|
||||
## The User
|
||||
|
||||
${userText}
|
||||
{% if user %}The user is logged into Nostr with the following profile:
|
||||
|
||||
- **Nostr pubkey (hex)**: {{ user.pubkey }}
|
||||
- **Nostr npub**: {{ user.npub }}{% if user.name %}
|
||||
- **Name**: {{ user.name }}{% endif %}{% if user.about %}
|
||||
- **About**: {{ user.about }}{% endif %}{% if user.website %}
|
||||
- **Website**: {{ user.website }}{% endif %}{% if user.picture %}
|
||||
- **Avatar**: {{ user.picture }}{% endif %}{% if user.banner %}
|
||||
- **Banner**: {{ user.banner }}{% endif %}{% if user.nip05 %}
|
||||
- **NIP-05**: {{ user.nip05 }}{% endif %}{% if user.lud16 %}
|
||||
- **Lightning Address**: {{ user.lud16 }}{% endif %}
|
||||
|
||||
Since the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.{% else %}The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.{% endif %}
|
||||
|
||||
## User Interface
|
||||
|
||||
@@ -138,8 +124,8 @@ Shakespeare operates on a browser-based virtual filesystem (VFS) that persists a
|
||||
├── config/ # Configuration files
|
||||
│ ├── ai.json # AI provider settings and API keys
|
||||
│ └── git.json # Git credentials and repository settings
|
||||
└── tmp/ # Temporary files and scratch space
|
||||
└── ... # Various temporary files and directories
|
||||
└── tmp/ # Temporary files and scratch space
|
||||
└── ... # Various temporary files and directories
|
||||
\`\`\`
|
||||
|
||||
### Key VFS Features
|
||||
@@ -163,73 +149,160 @@ As the AI assistant in Shakespeare, you help users by:
|
||||
|
||||
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.
|
||||
|
||||
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.`;
|
||||
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.{% if tools.length > 0 %}
|
||||
|
||||
// Add available tools to the system prompt
|
||||
const toolNames = tools
|
||||
.filter((tool) => tool.type === "function")
|
||||
.map((tool) => tool.function.name);
|
||||
## Available Tools
|
||||
|
||||
if (toolNames.length > 0) {
|
||||
system +=
|
||||
"\n\n## Available Tools\n\nYou have access to the following tools:\n";
|
||||
for (const tool of tools) {
|
||||
if (tool.type === "function") {
|
||||
system += `\n- **${tool.function.name}**: ${
|
||||
tool.function.description || "No description available"
|
||||
}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
You have access to the following tools:
|
||||
{% for tool in tools %}{% if tool.type === 'function' %}
|
||||
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% endif %}
|
||||
|
||||
// Add skills section
|
||||
system += "\n\n## Skills\n\n";
|
||||
## Skills
|
||||
|
||||
if (pluginsPath) {
|
||||
{% if skills and skills.length > 0 %}You have access to the following skills. **Skills MUST be used whenever applicable** by calling the \`skill\` tool with the skill name.
|
||||
|
||||
Available skills:
|
||||
{% for skill in skills %}
|
||||
- **{{ skill.name }}**: {{ skill.description }}
|
||||
- Plugin: {{ skill.plugin }}
|
||||
- Path: {{ skill.path }}
|
||||
{% endfor %}
|
||||
|
||||
**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.{% else %}No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.{% endif %}
|
||||
|
||||
Users can configure skills in Settings > AI ({{ location.origin }}/settings/ai) by adding plugins that contain skills.{% if config.corsProxy %}
|
||||
|
||||
## Working Around CORS Issues
|
||||
|
||||
If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching external APIs, use the configured CORS proxy:
|
||||
|
||||
**CORS Proxy URL Template**: \`{{ config.corsProxy }}\`
|
||||
|
||||
Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.{% endif %}
|
||||
|
||||
## Edit with Shakespeare
|
||||
|
||||
The "Edit with Shakespeare" button is a way that people can start editing any Shakespeare-compatible site with a single click. It can be added anywhere markdown or HTML is supported, including in READMEs, or within an app itself.{% if repositoryUrl %}
|
||||
|
||||
This project has a repository URL configured, so you can create an "Edit with Shakespeare" button using the following code snippets:
|
||||
|
||||
**Markdown:**
|
||||
\`\`\`markdown
|
||||
[]({{ editUrl }})
|
||||
\`\`\`
|
||||
|
||||
**HTML/JSX/TSX:**
|
||||
\`\`\`jsx
|
||||
<a href="{{ editUrl }}" target="_blank">
|
||||
<img src="{{ badgeUrl }}" alt="Edit with Shakespeare" />
|
||||
</a>
|
||||
\`\`\`
|
||||
|
||||
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %}
|
||||
|
||||
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if readmeText %}
|
||||
|
||||
{{ readmeText }}{% endif %}{% if agentsText %}
|
||||
|
||||
{{ agentsText }}{% endif %}`;
|
||||
|
||||
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
|
||||
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template } = opts;
|
||||
|
||||
// Add current date
|
||||
const date = new Date().toLocaleDateString("en-US", {
|
||||
weekday: "long",
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
// Get skills
|
||||
let skills: Array<{ name: string; description: string; plugin: string; path: string }> = [];
|
||||
if (config.fsPathPlugins) {
|
||||
try {
|
||||
const skills = await getAllSkills(fs, pluginsPath);
|
||||
|
||||
if (skills.length > 0) {
|
||||
system += "You have access to the following skills. **Skills MUST be used whenever applicable** by calling the `skill` tool with the skill name.\n\n";
|
||||
system += "Available skills:\n\n";
|
||||
|
||||
for (const skill of skills) {
|
||||
system += `- **${skill.name}**: ${skill.description}\n - Plugin: ${skill.plugin}\n - Path: ${skill.path}\n`;
|
||||
}
|
||||
|
||||
system += `\n**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.\n`;
|
||||
} else {
|
||||
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
|
||||
}
|
||||
skills = await getAllSkills(fs, config.fsPathPlugins);
|
||||
} catch {
|
||||
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
|
||||
// Skills not available, use empty array
|
||||
skills = [];
|
||||
}
|
||||
} else {
|
||||
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
|
||||
}
|
||||
|
||||
system += `\nUsers can configure skills in Settings > AI (${location.origin}/settings/ai) by adding plugins that contain skills.`;
|
||||
|
||||
// Add README.md if it exists
|
||||
// Get README.md if it exists
|
||||
let readmeText: string | undefined;
|
||||
try {
|
||||
const readmePath = join(cwd, "README.md");
|
||||
const readmeText = await fs.readFile(readmePath, "utf8");
|
||||
if (readmeText) {
|
||||
system += "\n\n" + readmeText;
|
||||
}
|
||||
readmeText = await fs.readFile(readmePath, "utf8");
|
||||
} catch {
|
||||
// README.md not found, continue
|
||||
}
|
||||
|
||||
// Add context from AGENTS.md if it exists
|
||||
// Get agent context if it exists
|
||||
let agentsText: string | undefined;
|
||||
try {
|
||||
const { text } = await getAgentContext(fs, cwd);
|
||||
system += "\n\n" + text;
|
||||
agentsText = text;
|
||||
} catch {
|
||||
// AGENTS.md not found, continue
|
||||
}
|
||||
|
||||
return system;
|
||||
// Build URLs for Edit with Shakespeare
|
||||
let badgeUrl: string | undefined;
|
||||
let editUrl: string | undefined;
|
||||
if (repositoryUrl) {
|
||||
badgeUrl = new URL('/badge.svg', location.origin).toString();
|
||||
const editUrlObj = new URL('/clone', location.origin);
|
||||
editUrlObj.searchParams.set('url', repositoryUrl);
|
||||
editUrl = editUrlObj.toString();
|
||||
}
|
||||
|
||||
// Build context object for template
|
||||
const context = {
|
||||
mode,
|
||||
date,
|
||||
cwd,
|
||||
repositoryUrl,
|
||||
config,
|
||||
defaultConfig,
|
||||
user: user
|
||||
? {
|
||||
...metadata,
|
||||
pubkey: user.pubkey,
|
||||
npub: nip19.npubEncode(user.pubkey),
|
||||
about: metadata?.about?.replace(/[\r\n]+/g, ' '),
|
||||
}
|
||||
: undefined,
|
||||
tools,
|
||||
skills,
|
||||
location: {
|
||||
href: location.href,
|
||||
origin: location.origin,
|
||||
pathname: location.pathname,
|
||||
port: location.port,
|
||||
hostname: location.hostname,
|
||||
protocol: location.protocol,
|
||||
search: location.search,
|
||||
hash: location.hash,
|
||||
},
|
||||
badgeUrl,
|
||||
editUrl,
|
||||
readmeText,
|
||||
agentsText,
|
||||
};
|
||||
|
||||
// Render the template with the context
|
||||
// Use the provided template, or fall back to the default
|
||||
const templateToRender = template || defaultSystemPrompt;
|
||||
|
||||
try {
|
||||
// Configure nunjucks environment
|
||||
const env = new nunjucks.Environment(null, { autoescape: false });
|
||||
return env.renderString(templateToRender, context);
|
||||
} catch (error) {
|
||||
console.error("Error rendering system prompt template:", error);
|
||||
// Return the template as-is if rendering fails
|
||||
return templateToRender;
|
||||
}
|
||||
}
|
||||
|
||||
async function getAgentContext(
|
||||
|
||||
@@ -35,12 +35,13 @@ describe('ShellTool', () => {
|
||||
let mockNostr: NPool;
|
||||
let shellTool: ShellTool;
|
||||
const testCwd = '/test/dir';
|
||||
const testCorsProxy = 'https://proxy.shakespeare.diy/?url={href}';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
mockNostr = createMockNostr();
|
||||
mockGit = new Git({ fs: mockFS, nostr: mockNostr });
|
||||
shellTool = new ShellTool(mockFS, testCwd, mockGit);
|
||||
shellTool = new ShellTool(mockFS, testCwd, mockGit, '/projects', testCorsProxy);
|
||||
});
|
||||
|
||||
it('should have correct tool properties', () => {
|
||||
|
||||
@@ -53,6 +53,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
private commands: Map<string, ShellCommand>;
|
||||
private projectsPath: string;
|
||||
private signer?: NostrSigner;
|
||||
private corsProxy: string;
|
||||
|
||||
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, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection with > and >> operators";
|
||||
|
||||
@@ -62,11 +63,12 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
),
|
||||
});
|
||||
|
||||
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', signer?: NostrSigner) {
|
||||
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', corsProxy: string, signer?: NostrSigner) {
|
||||
this.fs = fs;
|
||||
this.cwd = cwd;
|
||||
this.git = git;
|
||||
this.projectsPath = projectsPath;
|
||||
this.corsProxy = corsProxy;
|
||||
this.signer = signer;
|
||||
this.commands = new Map();
|
||||
|
||||
@@ -75,7 +77,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
this.registerCommand(new CdCommand(fs));
|
||||
this.registerCommand(new ClearCommand());
|
||||
this.registerCommand(new CpCommand(fs));
|
||||
this.registerCommand(new CurlCommand(fs));
|
||||
this.registerCommand(new CurlCommand(fs, this.corsProxy));
|
||||
this.registerCommand(new CutCommand(fs));
|
||||
this.registerCommand(new DateCommand());
|
||||
this.registerCommand(new DiffCommand(fs));
|
||||
|
||||
+8
-1
@@ -59,6 +59,8 @@
|
||||
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
|
||||
"shareErrorReports": "Share error reports",
|
||||
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
|
||||
"systemPrompt": "System Prompt",
|
||||
"systemPromptDescription": "Customize the AI assistant's system prompt using Jinja-like template syntax. This controls the assistant's behavior and knowledge.",
|
||||
"english": "English",
|
||||
"portuguese": "Portuguese",
|
||||
"chinese": "Chinese",
|
||||
@@ -85,6 +87,8 @@
|
||||
"add": "Add",
|
||||
"remove": "Remove",
|
||||
"retry": "Retry",
|
||||
"latestFirst": "Latest First",
|
||||
"oldestFirst": "Oldest First",
|
||||
"name": "Name",
|
||||
"email": "Email",
|
||||
"buildNostrApps": "Build apps with AI",
|
||||
@@ -483,5 +487,8 @@
|
||||
"configDirectoryDescription": "Directory where configuration files are stored in the virtual filesystem.",
|
||||
"temporaryDirectory": "Temporary Directory",
|
||||
"temporaryDirectoryDescription": "Directory for temporary files in the virtual filesystem.",
|
||||
"deleting": "Deleting..."
|
||||
"deleting": "Deleting...",
|
||||
"modified": "Modified",
|
||||
"restoreToDefault": "Restore to default",
|
||||
"restoredToDefault": "Restored to Default"
|
||||
}
|
||||
+8
-1
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "Hanyar tsarin fayil inda ake adana fayilolin saiti",
|
||||
"temporaryDirectory": "Kundin Wucin Gadi",
|
||||
"temporaryDirectoryDescription": "Hanyar tsarin fayil don fayilolin wucin gadi",
|
||||
"systemPrompt": "Tambarin Tsarin",
|
||||
"systemPromptDescription": "Keɓanta tambarin tsarin mataimaki na AI ta amfani da tsarin samfuri mai kama da Jinja. Wannan yana sarrafa ɗabi'a da ilimi na mataimaki.",
|
||||
"english": "Turanci",
|
||||
"portuguese": "Fotigis",
|
||||
"chinese": "Sinanci",
|
||||
@@ -81,6 +83,8 @@
|
||||
"add": "Ƙara",
|
||||
"remove": "Cire",
|
||||
"retry": "Sake gwadawa",
|
||||
"latestFirst": "Na Baya-bayan nan Da farko",
|
||||
"oldestFirst": "Na Dā Da farko",
|
||||
"name": "Suna",
|
||||
"email": "Imel",
|
||||
"buildNostrApps": "Gina aikace-aikace da AI",
|
||||
@@ -422,5 +426,8 @@
|
||||
"invalidGiftCard": "Katin Kyauta Ba Daidai Ba",
|
||||
"giftCardNotFound": "Ba a iya samun wannan katin kyauta.",
|
||||
"alreadyRedeemed": "An riga an Fanshi",
|
||||
"giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta."
|
||||
"giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta.",
|
||||
"modified": "An Canza",
|
||||
"restoreToDefault": "Mayar da asali",
|
||||
"restoredToDefault": "An Mayar da Asali"
|
||||
}
|
||||
+8
-1
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "Ụzọ sistemu faịlụ ebe echekwara faịlụ nhazi",
|
||||
"temporaryDirectory": "Ndekọ Nwa Oge",
|
||||
"temporaryDirectoryDescription": "Ụzọ sistemu faịlụ maka faịlụ nwa oge",
|
||||
"systemPrompt": "Ajụjụ Sistemu",
|
||||
"systemPromptDescription": "Hazie ajụjụ sistemu nke enyemaka AI site na iji syntax template yiri Jinja. Nke a na-achịkwa omume na ihe ọmụma nke enyemaka ahụ.",
|
||||
"english": "Bekee",
|
||||
"portuguese": "Portuguese",
|
||||
"chinese": "Chinese",
|
||||
@@ -81,6 +83,8 @@
|
||||
"add": "Tinye",
|
||||
"remove": "Wepụ",
|
||||
"retry": "Nwaa ọzọ",
|
||||
"latestFirst": "Nke Ọhụrụ Mbụ",
|
||||
"oldestFirst": "Nke Ochie Mbụ",
|
||||
"name": "Aha",
|
||||
"email": "Ozi-eletrọniki",
|
||||
"buildNostrApps": "Wuo ngwa na AI",
|
||||
@@ -419,5 +423,8 @@
|
||||
"invalidGiftCard": "Kaadị Onyinye Na-ezighị Ezi",
|
||||
"giftCardNotFound": "Achọtaghị kaadị onyinye a.",
|
||||
"alreadyRedeemed": "Egbapụtalarị",
|
||||
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a."
|
||||
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a.",
|
||||
"modified": "Gbanwere",
|
||||
"restoreToDefault": "Weghachi na nke mbụ",
|
||||
"restoredToDefault": "Weghachiri na Nke Mbụ"
|
||||
}
|
||||
+8
-1
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "Caminho do sistema de arquivos onde os arquivos de configuração são armazenados",
|
||||
"temporaryDirectory": "Diretório Temporário",
|
||||
"temporaryDirectoryDescription": "Caminho do sistema de arquivos para arquivos temporários",
|
||||
"systemPrompt": "Prompt do Sistema",
|
||||
"systemPromptDescription": "Personalize o prompt do sistema do assistente de IA usando sintaxe de template semelhante a Jinja. Isso controla o comportamento e conhecimento do assistente.",
|
||||
"english": "Inglês",
|
||||
"portuguese": "Português",
|
||||
"chinese": "Chinês",
|
||||
@@ -81,6 +83,8 @@
|
||||
"add": "Adicionar",
|
||||
"remove": "Remover",
|
||||
"retry": "Tentar novamente",
|
||||
"latestFirst": "Mais Recentes Primeiro",
|
||||
"oldestFirst": "Mais Antigos Primeiro",
|
||||
"name": "Nome",
|
||||
"email": "Email",
|
||||
"buildNostrApps": "Construa aplicativos com IA",
|
||||
@@ -432,5 +436,8 @@
|
||||
"invalidGiftCard": "Cartão Presente Inválido",
|
||||
"giftCardNotFound": "Este cartão presente não pôde ser encontrado.",
|
||||
"alreadyRedeemed": "Já Resgatado",
|
||||
"giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado."
|
||||
"giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado.",
|
||||
"modified": "Modificado",
|
||||
"restoreToDefault": "Restaurar para padrão",
|
||||
"restoredToDefault": "Restaurado para Padrão"
|
||||
}
|
||||
+8
-1
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "Ọna eto faili nibiti a tọju awọn faili iṣeto",
|
||||
"temporaryDirectory": "Itọsọna Igba diẹ",
|
||||
"temporaryDirectoryDescription": "Ọna eto faili fun awọn faili igba diẹ",
|
||||
"systemPrompt": "Ibeere Eto",
|
||||
"systemPromptDescription": "Ṣe adani ibeere eto oluranlọwọ AI nipa lilo sintasi awoṣe ti o jọ Jinja. Eyi n ṣakoso ihuwasi ati imọ oluranlọwọ naa.",
|
||||
"english": "Gẹẹsi",
|
||||
"portuguese": "Potogisi",
|
||||
"chinese": "Kannada",
|
||||
@@ -81,6 +83,8 @@
|
||||
"add": "Fi kun",
|
||||
"remove": "Yọ kuro",
|
||||
"retry": "Tun gbiyanju",
|
||||
"latestFirst": "Tuntun Akọkọ",
|
||||
"oldestFirst": "Atijọ Akọkọ",
|
||||
"name": "Orukọ",
|
||||
"email": "Imeeli",
|
||||
"buildNostrApps": "Kọ awọn ohun elo pẹlu AI",
|
||||
@@ -419,5 +423,8 @@
|
||||
"invalidGiftCard": "Kaadi Ẹbun Ti ko Tọ",
|
||||
"giftCardNotFound": "A ko le ri kaadi ẹbun yii.",
|
||||
"alreadyRedeemed": "Ti ra Tẹlẹ",
|
||||
"giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ."
|
||||
"giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ.",
|
||||
"modified": "Ti Yipada",
|
||||
"restoreToDefault": "Pada si atilẹwa",
|
||||
"restoredToDefault": "Ti Pada si Atilẹwa"
|
||||
}
|
||||
+8
-1
@@ -55,6 +55,8 @@
|
||||
"configDirectoryDescription": "存储配置文件的文件系统路径",
|
||||
"temporaryDirectory": "临时目录",
|
||||
"temporaryDirectoryDescription": "临时文件的文件系统路径",
|
||||
"systemPrompt": "系统提示",
|
||||
"systemPromptDescription": "使用类似Jinja的模板语法自定义AI助手的系统提示。这控制助手的行为和知识。",
|
||||
"english": "English",
|
||||
"portuguese": "Português",
|
||||
"chinese": "中文",
|
||||
@@ -81,6 +83,8 @@
|
||||
"add": "添加",
|
||||
"remove": "移除",
|
||||
"retry": "重试",
|
||||
"latestFirst": "最新优先",
|
||||
"oldestFirst": "最旧优先",
|
||||
"name": "名称",
|
||||
"email": "邮箱",
|
||||
"buildNostrApps": "使用AI构建应用",
|
||||
@@ -432,5 +436,8 @@
|
||||
"invalidGiftCard": "无效的礼品卡",
|
||||
"giftCardNotFound": "找不到此礼品卡。",
|
||||
"alreadyRedeemed": "已兑换",
|
||||
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。"
|
||||
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。",
|
||||
"modified": "已修改",
|
||||
"restoreToDefault": "恢复默认值",
|
||||
"restoredToDefault": "已恢复默认值"
|
||||
}
|
||||
@@ -105,16 +105,6 @@ export function AboutSettings() {
|
||||
<ExternalLink className="ml-auto h-4 w-4" />
|
||||
</a>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-10 flex items-center gap-2 justify-start"
|
||||
asChild
|
||||
>
|
||||
<a href="https://shakespeare.soapbox.dev" target="_blank" rel="noopener noreferrer">
|
||||
<span className="font-mono text-sm">shakespeare.soapbox.dev</span>
|
||||
<ExternalLink className="ml-auto h-4 w-4" />
|
||||
</a>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-10 flex items-center gap-2 justify-start"
|
||||
|
||||
+564
-194
@@ -1,22 +1,24 @@
|
||||
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2 } from "lucide-react";
|
||||
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw } from "lucide-react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { useIsMobile } from "@/hooks/useIsMobile";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
import { useOffline } from "@/hooks/useOffline";
|
||||
import { useToast } from "@/hooks/useToast";
|
||||
import { defaultSystemPrompt } from "@/lib/system";
|
||||
|
||||
export function SystemSettings() {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const { config, defaultConfig, updateConfig } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const { serviceWorkerRegistration, updateServiceWorker, clearCache } = useOffline();
|
||||
|
||||
@@ -31,6 +33,102 @@ export function SystemSettings() {
|
||||
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
|
||||
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
|
||||
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
|
||||
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
|
||||
|
||||
// Check which settings differ from defaults
|
||||
const isModified = useMemo(() => ({
|
||||
projectTemplate: config.projectTemplate !== defaultConfig.projectTemplate,
|
||||
esmUrl: config.esmUrl !== defaultConfig.esmUrl,
|
||||
corsProxy: config.corsProxy !== defaultConfig.corsProxy,
|
||||
faviconUrl: config.faviconUrl !== defaultConfig.faviconUrl,
|
||||
previewDomain: config.previewDomain !== defaultConfig.previewDomain,
|
||||
showcaseEnabled: config.showcaseEnabled !== defaultConfig.showcaseEnabled,
|
||||
showcaseModerator: config.showcaseModerator !== defaultConfig.showcaseModerator,
|
||||
fsPathProjects: config.fsPathProjects !== defaultConfig.fsPathProjects,
|
||||
fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig,
|
||||
fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp,
|
||||
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
|
||||
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
|
||||
systemPrompt: (config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
|
||||
}), [config, defaultConfig]);
|
||||
|
||||
// Restore functions
|
||||
const restoreProjectTemplate = () => {
|
||||
const defaultValue = defaultConfig.projectTemplate;
|
||||
setProjectTemplateInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, projectTemplate: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreEsmUrl = () => {
|
||||
const defaultValue = defaultConfig.esmUrl;
|
||||
setEsmUrlInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, esmUrl: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreCorsProxy = () => {
|
||||
const defaultValue = defaultConfig.corsProxy;
|
||||
setCorsProxyInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, corsProxy: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreFaviconUrl = () => {
|
||||
const defaultValue = defaultConfig.faviconUrl;
|
||||
setFaviconUrlInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, faviconUrl: defaultValue }));
|
||||
};
|
||||
|
||||
const restorePreviewDomain = () => {
|
||||
const defaultValue = defaultConfig.previewDomain;
|
||||
setPreviewDomainInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, previewDomain: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreShowcaseEnabled = () => {
|
||||
const defaultValue = defaultConfig.showcaseEnabled;
|
||||
updateConfig((current) => ({ ...current, showcaseEnabled: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreShowcaseModerator = () => {
|
||||
const defaultValue = defaultConfig.showcaseModerator;
|
||||
setShowcaseModeratorInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, showcaseModerator: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreFsPathProjects = () => {
|
||||
const defaultValue = defaultConfig.fsPathProjects;
|
||||
setFsPathProjectsInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, fsPathProjects: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreFsPathConfig = () => {
|
||||
const defaultValue = defaultConfig.fsPathConfig;
|
||||
setFsPathConfigInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, fsPathConfig: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreFsPathTmp = () => {
|
||||
const defaultValue = defaultConfig.fsPathTmp;
|
||||
setFsPathTmpInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, fsPathTmp: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreFsPathPlugins = () => {
|
||||
const defaultValue = defaultConfig.fsPathPlugins;
|
||||
setFsPathPluginsInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, fsPathPlugins: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreSentryDsn = () => {
|
||||
const defaultValue = defaultConfig.sentryDsn;
|
||||
setSentryDsnInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, sentryDsn: defaultValue }));
|
||||
};
|
||||
|
||||
const restoreSystemPrompt = () => {
|
||||
const defaultValue = defaultSystemPrompt;
|
||||
setSystemPromptInput(defaultValue);
|
||||
updateConfig((current) => ({ ...current, systemPrompt: defaultValue }));
|
||||
};
|
||||
|
||||
// Service Worker state
|
||||
const [swState, setSwState] = useState<string>('');
|
||||
@@ -265,24 +363,42 @@ export function SystemSettings() {
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="project-template" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<h4 className="text-sm font-medium">{t('projectTemplate')}</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('projectTemplate')}</h4>
|
||||
{isModified.projectTemplate && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-2">
|
||||
<Input
|
||||
id="project-template"
|
||||
type="url"
|
||||
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
|
||||
value={projectTemplateInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setProjectTemplateInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
projectTemplate: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="project-template"
|
||||
type="url"
|
||||
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
|
||||
value={projectTemplateInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setProjectTemplateInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
projectTemplate: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.projectTemplate && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreProjectTemplate}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('projectTemplateDescription')}
|
||||
</p>
|
||||
@@ -295,24 +411,42 @@ export function SystemSettings() {
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="cors-proxy" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
|
||||
{isModified.corsProxy && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-2">
|
||||
<Input
|
||||
id="cors-proxy"
|
||||
type="url"
|
||||
placeholder="https://proxy.shakespeare.diy/?url={href}"
|
||||
value={corsProxyInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setCorsProxyInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
corsProxy: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="cors-proxy"
|
||||
type="url"
|
||||
placeholder="https://proxy.shakespeare.diy/?url={href}"
|
||||
value={corsProxyInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setCorsProxyInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
corsProxy: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.corsProxy && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreCorsProxy}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('corsProxyDescription')}
|
||||
</p>
|
||||
@@ -325,24 +459,42 @@ export function SystemSettings() {
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="favicon-url" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<h4 className="text-sm font-medium">{t('faviconUrl')}</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('faviconUrl')}</h4>
|
||||
{isModified.faviconUrl && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-2">
|
||||
<Input
|
||||
id="favicon-url"
|
||||
type="url"
|
||||
placeholder="https://favicon.shakespeare.diy/?url={href}"
|
||||
value={faviconUrlInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFaviconUrlInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
faviconUrl: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="favicon-url"
|
||||
type="url"
|
||||
placeholder="https://favicon.shakespeare.diy/?url={href}"
|
||||
value={faviconUrlInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFaviconUrlInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
faviconUrl: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.faviconUrl && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreFaviconUrl}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('faviconUrlDescription')}
|
||||
</p>
|
||||
@@ -355,25 +507,43 @@ export function SystemSettings() {
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="esm-url" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<h4 className="text-sm font-medium">{t('esmUrl')}</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('esmUrl')}</h4>
|
||||
{isModified.esmUrl && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-2">
|
||||
<Input
|
||||
id="esm-url"
|
||||
type="url"
|
||||
placeholder="https://esm.sh"
|
||||
value={esmUrlInput}
|
||||
onChange={(e) => {
|
||||
// Strip trailing slash on save.
|
||||
const value = e.target.value;
|
||||
setEsmUrlInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
esmUrl: value.replace(/\/+$/, ''),
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="esm-url"
|
||||
type="url"
|
||||
placeholder="https://esm.sh"
|
||||
value={esmUrlInput}
|
||||
onChange={(e) => {
|
||||
// Strip trailing slash on save.
|
||||
const value = e.target.value;
|
||||
setEsmUrlInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
esmUrl: value.replace(/\/+$/, ''),
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.esmUrl && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreEsmUrl}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('esmUrlDescription')}
|
||||
</p>
|
||||
@@ -386,24 +556,42 @@ export function SystemSettings() {
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="preview-domain" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<h4 className="text-sm font-medium">{t('previewDomain')}</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('previewDomain')}</h4>
|
||||
{isModified.previewDomain && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-2">
|
||||
<Input
|
||||
id="preview-domain"
|
||||
type="text"
|
||||
placeholder="local-shakespeare.dev"
|
||||
value={previewDomainInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setPreviewDomainInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
previewDomain: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="preview-domain"
|
||||
type="text"
|
||||
placeholder="local-shakespeare.dev"
|
||||
value={previewDomainInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setPreviewDomainInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
previewDomain: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.previewDomain && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restorePreviewDomain}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('previewDomainDescription')}
|
||||
</p>
|
||||
@@ -416,47 +604,87 @@ export function SystemSettings() {
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="showcase" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<h4 className="text-sm font-medium">{t('showcase')}</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('showcase')}</h4>
|
||||
{(isModified.showcaseEnabled || isModified.showcaseModerator) && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="showcase-enabled" className="text-sm font-medium">
|
||||
{t('showcaseEnabled')}
|
||||
</Label>
|
||||
<Switch
|
||||
id="showcase-enabled"
|
||||
checked={config.showcaseEnabled}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
showcaseEnabled: checked,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="showcase-enabled" className="text-sm font-medium">
|
||||
{t('showcaseEnabled')}
|
||||
</Label>
|
||||
{isModified.showcaseEnabled && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="showcase-enabled"
|
||||
checked={config.showcaseEnabled}
|
||||
onCheckedChange={(checked) => {
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
showcaseEnabled: checked,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
{isModified.showcaseEnabled && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreShowcaseEnabled}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('showcaseEnabledDescription')}
|
||||
</p>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="showcase-moderator" className="text-sm font-medium">
|
||||
{t('showcaseModerator')}
|
||||
</Label>
|
||||
<Input
|
||||
id="showcase-moderator"
|
||||
type="text"
|
||||
placeholder="npub1..."
|
||||
value={showcaseModeratorInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setShowcaseModeratorInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
showcaseModerator: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="showcase-moderator" className="text-sm font-medium">
|
||||
{t('showcaseModerator')}
|
||||
</Label>
|
||||
{isModified.showcaseModerator && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="showcase-moderator"
|
||||
type="text"
|
||||
placeholder="npub1..."
|
||||
value={showcaseModeratorInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setShowcaseModeratorInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
showcaseModerator: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.showcaseModerator && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreShowcaseModerator}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('showcaseModeratorDescription')}
|
||||
</p>
|
||||
@@ -470,24 +698,42 @@ export function SystemSettings() {
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="sentry-dsn" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<h4 className="text-sm font-medium">{t('sentryDsn')}</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('sentryDsn')}</h4>
|
||||
{isModified.sentryDsn && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-2">
|
||||
<Input
|
||||
id="sentry-dsn"
|
||||
type="text"
|
||||
placeholder="https://..."
|
||||
value={sentryDsnInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setSentryDsnInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
sentryDsn: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="sentry-dsn"
|
||||
type="text"
|
||||
placeholder="https://..."
|
||||
value={sentryDsnInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setSentryDsnInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
sentryDsn: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.sentryDsn && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreSentryDsn}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('sentryDsnDescription')}
|
||||
</p>
|
||||
@@ -500,97 +746,174 @@ export function SystemSettings() {
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="filesystem-paths" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
|
||||
{(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins) && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
|
||||
{t('projectsDirectory')}
|
||||
</Label>
|
||||
<Input
|
||||
id="fs-path-projects"
|
||||
type="text"
|
||||
placeholder="/projects"
|
||||
value={fsPathProjectsInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFsPathProjectsInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
fsPathProjects: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
|
||||
{t('projectsDirectory')}
|
||||
</Label>
|
||||
{isModified.fsPathProjects && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="fs-path-projects"
|
||||
type="text"
|
||||
placeholder="/projects"
|
||||
value={fsPathProjectsInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFsPathProjectsInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
fsPathProjects: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.fsPathProjects && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreFsPathProjects}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('projectsDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="fs-path-config" className="text-sm font-medium">
|
||||
{t('configDirectory')}
|
||||
</Label>
|
||||
<Input
|
||||
id="fs-path-config"
|
||||
type="text"
|
||||
placeholder="/config"
|
||||
value={fsPathConfigInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFsPathConfigInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
fsPathConfig: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="fs-path-config" className="text-sm font-medium">
|
||||
{t('configDirectory')}
|
||||
</Label>
|
||||
{isModified.fsPathConfig && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="fs-path-config"
|
||||
type="text"
|
||||
placeholder="/config"
|
||||
value={fsPathConfigInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFsPathConfigInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
fsPathConfig: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.fsPathConfig && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreFsPathConfig}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('configDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="fs-path-tmp" className="text-sm font-medium">
|
||||
{t('temporaryDirectory')}
|
||||
</Label>
|
||||
<Input
|
||||
id="fs-path-tmp"
|
||||
type="text"
|
||||
placeholder="/tmp"
|
||||
value={fsPathTmpInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFsPathTmpInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
fsPathTmp: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="fs-path-tmp" className="text-sm font-medium">
|
||||
{t('temporaryDirectory')}
|
||||
</Label>
|
||||
{isModified.fsPathTmp && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="fs-path-tmp"
|
||||
type="text"
|
||||
placeholder="/tmp"
|
||||
value={fsPathTmpInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFsPathTmpInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
fsPathTmp: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.fsPathTmp && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreFsPathTmp}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('temporaryDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="fs-path-plugins" className="text-sm font-medium">
|
||||
{t('pluginsDirectory')}
|
||||
</Label>
|
||||
<Input
|
||||
id="fs-path-plugins"
|
||||
type="text"
|
||||
placeholder="/plugins"
|
||||
value={fsPathPluginsInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFsPathPluginsInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
fsPathPlugins: value,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="fs-path-plugins" className="text-sm font-medium">
|
||||
{t('pluginsDirectory')}
|
||||
</Label>
|
||||
{isModified.fsPathPlugins && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="fs-path-plugins"
|
||||
type="text"
|
||||
placeholder="/plugins"
|
||||
value={fsPathPluginsInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFsPathPluginsInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
fsPathPlugins: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
{isModified.fsPathPlugins && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={restoreFsPathPlugins}
|
||||
title={t('restoreToDefault')}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('pluginsDirectoryDescription')}
|
||||
</p>
|
||||
@@ -599,6 +922,53 @@ export function SystemSettings() {
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* System Prompt Configuration */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="system-prompt" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium">{t('systemPrompt')}</h4>
|
||||
{isModified.systemPrompt && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-2">
|
||||
<div className="flex gap-2 flex-col">
|
||||
<Textarea
|
||||
id="system-prompt"
|
||||
placeholder="Enter EJS template..."
|
||||
value={systemPromptInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setSystemPromptInput(value);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
systemPrompt: value,
|
||||
}));
|
||||
}}
|
||||
className="flex-1 font-mono text-xs min-h-[400px]"
|
||||
/>
|
||||
{isModified.systemPrompt && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={restoreSystemPrompt}
|
||||
className="w-full"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4 mr-2" />
|
||||
{t('restoreToDefault')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('systemPromptDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ export default defineConfig(() => ({
|
||||
manifest: false, // Use existing manifest.webmanifest from public folder
|
||||
workbox: {
|
||||
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
|
||||
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024, // 10 MB
|
||||
maximumFileSizeToCacheInBytes: 15 * 1024 * 1024, // 15 MB (to accommodate esbuild.wasm at ~12 MB)
|
||||
cleanupOutdatedCaches: true,
|
||||
},
|
||||
devOptions: {
|
||||
|
||||
Reference in new issue
Block a user