Compare commits

..
Author SHA1 Message Date
shakespeare.diy 262414257a Fix ESLint errors: remove unused navigate imports
Removed unused `useNavigate` imports from:
- PushReminderDialog.tsx
- PushWarningButton.tsx

These were causing ESLint errors. The navigate hook was imported
but never used in either component.

ESLint should now pass without errors.
2025-11-14 10:17:52 -06:00
shakespeare.diy c25517a58f Remove debug logging and restore production settings
- Removed all console.log debug statements
- Changed MESSAGE_THRESHOLD back to 5 (from 2 for testing)
- Cleaned up code for production

Push reminder features are now fully functional:
- Warning icon appears in header when there's unpushed work
- Popup appears after 5 messages if conditions are met
- 5-minute cooldown between reminders
- User can disable in Settings > Preferences
2025-11-11 14:06:43 -06:00
shakespeare.diy a7164c0292 Fix push reminder not showing - remove initial cooldown
The issue was that DEFAULT_STATE set lastInteraction to Date.now(),
which meant the 5-minute cooldown started immediately on first load,
preventing reminders from ever showing.

Changes:
- Set initial lastInteraction to 0 instead of Date.now()
- Don't reset lastInteraction when switching projects (keep cooldown)
- This allows reminders to show immediately after threshold is met

Users may need to clear localStorage key 'push-reminder-state' to
reset if they already have the old state saved.
2025-11-11 14:01:46 -06:00
shakespeare.diy 66a37ec92c Add debug logging and lower threshold for testing push reminders
- Reduced MESSAGE_THRESHOLD from 5 to 2 for easier testing
- Added console.log statements to track:
  - Message counter increments
  - shouldShowReminder checks and conditions
  - Git status (uncommitted changes, commits ahead, remotes)
- Added useEffect to watch shouldShowReminder changes
- Fixed async state update issue by watching effect dependency

This will help debug why the reminder dialog may not be appearing.
2025-11-11 13:58:18 -06:00
shakespeare.diy 5de01c6130 Add push reminder features to encourage users to push code
Implements two key features to prevent data loss:

1. Push Warning Button
   - Icon button in project header that appears when:
     - No remote is configured
     - There are commits ahead of remote
     - There are uncommitted changes
   - Click opens Git dialog for one-click push or remote configuration
   - Visual indicators with tooltips showing status

2. Periodic Push Reminder Dialog
   - Dismissible popup appears after 5 messages if there's unpushed work
   - Shows different content based on git status:
     - No remote: Prompts to configure remote
     - Commits ahead: Prompts to push
     - Uncommitted changes: Prompts to commit and push
   - Can be disabled with "Don't show again" checkbox
   - Setting in Preferences to re-enable reminders
   - Respects 5-minute cooldown between reminders

3. User Preferences
   - Added "Push reminders" toggle in Settings > Preferences
   - Enabled by default to encourage best practices
   - Stored in local storage for persistence

Technical implementation:
- Created usePushReminder hook for state management
- Tracks message count and last interaction timestamp
- Integrates with existing useGitStatus hook
- Added onMessageSent callback to ChatPane
- PushWarningButton component with icon/full variants
- PushReminderDialog with contextual messaging
- Translations added to English locale
2025-11-11 13:43:16 -06:00
53 changed files with 1179 additions and 3200 deletions

No files matched your search

+1
View File
@@ -34,6 +34,7 @@ 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
View File
@@ -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' '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:">
<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:">
<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">
+11 -86
View File
@@ -68,7 +68,6 @@
"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",
@@ -106,7 +105,6 @@
"@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",
@@ -195,7 +193,6 @@
"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",
@@ -1831,7 +1828,6 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
},
@@ -1855,7 +1851,6 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
}
@@ -1877,7 +1872,6 @@
"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",
@@ -5408,7 +5402,8 @@
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true,
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/@types/cacheable-request": {
"version": "6.0.3",
@@ -5608,13 +5603,6 @@
"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",
@@ -5650,7 +5638,6 @@
"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"
@@ -5662,7 +5649,6 @@
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^18.0.0"
}
@@ -5767,7 +5753,6 @@
"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",
@@ -6103,18 +6088,11 @@
"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"
},
@@ -6279,12 +6257,6 @@
"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",
@@ -6559,7 +6531,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751",
@@ -6819,7 +6790,6 @@
"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",
@@ -7558,7 +7528,8 @@
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true,
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/dom-helpers": {
"version": "5.2.1",
@@ -7636,8 +7607,7 @@
"version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/embla-carousel-react": {
"version": "8.6.0",
@@ -7936,7 +7906,6 @@
"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",
@@ -9284,7 +9253,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.27.6"
},
@@ -10054,7 +10022,6 @@
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"cssstyle": "^4.2.1",
"data-urls": "^5.0.0",
@@ -10451,6 +10418,7 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
@@ -11717,40 +11685,6 @@
"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",
@@ -12154,7 +12088,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.8",
"picocolors": "^1.1.1",
@@ -12322,6 +12255,7 @@
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
@@ -12337,6 +12271,7 @@
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=8"
}
@@ -12347,6 +12282,7 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
@@ -12359,7 +12295,8 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/prismjs": {
"version": "1.30.0",
@@ -12499,7 +12436,6 @@
"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"
},
@@ -12526,7 +12462,6 @@
"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"
@@ -12552,7 +12487,6 @@
"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"
},
@@ -12601,7 +12535,6 @@
"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",
@@ -13184,7 +13117,6 @@
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "1.0.7"
},
@@ -14236,7 +14168,6 @@
"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",
@@ -14440,7 +14371,6 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -14713,7 +14643,6 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -15223,7 +15152,6 @@
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
@@ -15368,7 +15296,6 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -15839,7 +15766,6 @@
"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",
@@ -15916,7 +15842,6 @@
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"rollup": "dist/bin/rollup"
},
+1 -3
View File
@@ -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 && node scripts/prepare-electron-publish.js && electron electron",
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && electron electron",
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
},
"dependencies": {
@@ -81,7 +81,6 @@
"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",
@@ -119,7 +118,6 @@
"@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",
+1 -2
View File
@@ -1,2 +1 @@
/assets/* /assets/:splat 200
/* /index.html 200
/* /index.html 200
-1
View File
@@ -79,7 +79,6 @@ export function AppProvider(props: AppProviderProps) {
const appContextValue: AppContextType = {
config,
defaultConfig,
updateConfig,
};
-7
View File
@@ -124,7 +124,6 @@ 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>({
@@ -295,10 +294,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setShakespeareForm({ subdomain });
}, []);
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
setIsShakespeareFormValid(isValid);
}, []);
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
@@ -322,7 +317,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
host={shakespeareProvider.host}
projectId={projectId}
onSubdomainChange={handleShakespeareSubdomainChange}
onValidationChange={handleShakespeareValidationChange}
/>
);
}
@@ -501,7 +495,6 @@ 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)
}
+6 -21
View File
@@ -1,7 +1,6 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
import { cn } from '@/lib/utils';
import { ReactNode, useMemo } from 'react';
import { ReactNode } from 'react';
interface ExternalFaviconProps {
/** The URL to fetch the favicon for */
@@ -26,28 +25,14 @@ export function ExternalFavicon({
}: ExternalFaviconProps) {
const { config } = useAppContext();
// Generate the favicon URL using the configured template
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]);
// Normalize the URL to ensure it has a protocol
const normalizedUrl = normalizeUrl(url);
// 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>
)
}
// Generate the favicon URL using the configured template
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
return (
<span className={cn('inline-flex items-center justify-center', className)}>
<span className={`inline-flex items-center justify-center ${className}`}>
<img
src={faviconSrc}
alt=""
+2 -54
View File
@@ -25,7 +25,6 @@ const baseGitStatus = {
},
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
vi.mock('@/hooks/useGitStatus', () => ({
@@ -83,16 +82,7 @@ describe('GitDialog', () => {
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows sync status when branch is published', () => {
// Mock git status with published branch
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
it('shows sync status', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -143,17 +133,7 @@ describe('GitDialog', () => {
expect(pushButton.closest('button')).not.toBeDisabled();
});
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,
});
it('disables push button when no commits ahead', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -167,38 +147,6 @@ 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>
+64 -107
View File
@@ -243,23 +243,13 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
object: currentRef,
});
// Automatically check out the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName.trim(),
force: true,
toast({
title: 'Branch created',
description: `Created branch "${newBranchName}"`,
});
// 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) {
@@ -456,7 +446,50 @@ 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.');
}
console.log('Repository has refs:', refTags);
// 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');
// Set origin remote to Nostr URL
// Format: nostr://<npub>/<repo-id>
@@ -489,54 +522,13 @@ 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({
@@ -569,8 +561,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
return;
}
// Allow push if there are commits ahead OR if the remote branch doesn't exist (publishing new branch)
if (gitStatus.ahead === 0 && gitStatus.remoteBranchExists) {
if (gitStatus.ahead === 0) {
toast({
title: "Nothing to push",
description: "No commits ahead of remote. Commit your changes first.",
@@ -579,16 +570,6 @@ 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 {
@@ -602,32 +583,11 @@ 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}`,
});
}
// 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}`,
});
}
toast({
title: "Push successful",
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
});
// Refresh git status after push
await refetchGitStatus();
@@ -723,6 +683,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
}
};
const getFileStatusIcon = (status: string) => {
switch (status) {
case 'added':
@@ -766,11 +728,6 @@ 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' };
}
@@ -1138,11 +1095,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
)}
</div>
{originUrl.trim() && (
{gitStatus.remotes.length > 0 && (
<div className="flex gap-2">
<Button
onClick={handlePull}
disabled={isPulling || isPushing || isPushingToNostr || !gitStatus.remoteBranchExists}
disabled={isPulling || isPushing || isPushingToNostr}
variant="outline"
size="sm"
className="flex-1"
@@ -1157,7 +1114,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<Button
onClick={handlePush}
disabled={isPushing || isPulling || isPushingToNostr || (gitStatus.ahead === 0 && gitStatus.remoteBranchExists)}
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
variant="outline"
size="sm"
className="flex-1"
@@ -1172,7 +1129,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
</div>
)}
{!originUrl.trim() && user && (
{gitStatus.remotes.length === 0 && user && (
<Button
onClick={handlePushToNostr}
disabled={isPushingToNostr || isPushing || isPulling}
@@ -1185,7 +1142,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
) : (
<Zap className="h-4 w-4 mr-2" />
)}
{isPushingToNostr ? 'Loading...' : 'Push to Nostr'}
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
</Button>
)}
-30
View File
@@ -33,11 +33,9 @@ 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;
@@ -51,7 +49,6 @@ 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();
@@ -65,24 +62,6 @@ 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);
@@ -247,15 +226,6 @@ 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>
+176
View File
@@ -0,0 +1,176 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { GitBranch, Upload, AlertTriangle, X } from 'lucide-react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { GitDialog } from '@/components/GitDialog';
interface PushReminderDialogProps {
projectId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onDisableReminders: () => void;
onDismiss: () => void;
}
export function PushReminderDialog({
projectId,
open,
onOpenChange,
onDisableReminders,
onDismiss,
}: PushReminderDialogProps) {
const [dontShowAgain, setDontShowAgain] = useState(false);
const [isGitDialogOpen, setIsGitDialogOpen] = useState(false);
const { data: gitStatus } = useGitStatus(projectId);
// Close the reminder dialog when git dialog opens
useEffect(() => {
if (isGitDialogOpen) {
onOpenChange(false);
onDismiss();
}
}, [isGitDialogOpen, onOpenChange, onDismiss]);
if (!gitStatus?.isGitRepo) {
return null;
}
const hasNoRemote = gitStatus.remotes.length === 0;
const hasCommitsAhead = gitStatus.ahead > 0;
const hasUncommittedChanges = gitStatus.hasUncommittedChanges;
const handleDismiss = () => {
if (dontShowAgain) {
onDisableReminders();
}
onDismiss();
onOpenChange(false);
};
const handlePrimaryAction = () => {
if (dontShowAgain) {
onDisableReminders();
}
if (hasNoRemote) {
// Close reminder dialog and open git dialog
onOpenChange(false);
setIsGitDialogOpen(true);
} else {
// Close reminder dialog and open git dialog for push
onOpenChange(false);
setIsGitDialogOpen(true);
}
};
// Determine dialog content based on git status
let icon = AlertTriangle;
let iconColor = 'text-amber-600 dark:text-amber-500';
let title = '';
let description = '';
let primaryActionLabel = '';
if (hasNoRemote) {
icon = GitBranch;
iconColor = 'text-yellow-600 dark:text-yellow-500';
title = 'No Remote Repository Configured';
description = 'Your work is only stored locally in your browser. Configure a remote repository to prevent data loss if you clear your browser data.';
primaryActionLabel = 'Configure Remote';
} else if (hasCommitsAhead) {
icon = Upload;
iconColor = 'text-blue-600 dark:text-blue-500';
title = 'Unpushed Commits';
description = `You have ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} that ${gitStatus.ahead !== 1 ? 'haven\'t' : 'hasn\'t'} been pushed to your remote repository. Push your changes to prevent data loss.`;
primaryActionLabel = 'Push Changes';
} else if (hasUncommittedChanges) {
icon = AlertTriangle;
iconColor = 'text-amber-600 dark:text-amber-500';
title = 'Uncommitted Changes';
description = `You have ${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}. Commit and push your changes to keep your work safe.`;
primaryActionLabel = 'Commit & Push';
}
const Icon = icon;
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<div className="flex items-start gap-3">
<div className={`rounded-full p-2 bg-muted ${iconColor}`}>
<Icon className="h-5 w-5" />
</div>
<div className="flex-1">
<DialogTitle className="text-left">{title}</DialogTitle>
<DialogDescription className="text-left mt-2">
{description}
</DialogDescription>
</div>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 -mt-1"
onClick={handleDismiss}
>
<X className="h-4 w-4" />
</Button>
</div>
</DialogHeader>
<div className="flex items-start gap-2 p-3 rounded-md bg-muted/50 border">
<Checkbox
id="dont-show"
checked={dontShowAgain}
onCheckedChange={(checked) => setDontShowAgain(checked === true)}
/>
<div className="grid gap-1.5 leading-none">
<Label
htmlFor="dont-show"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Don't show this again
</Label>
<p className="text-xs text-muted-foreground">
You can re-enable push reminders in Settings &gt; Preferences
</p>
</div>
</div>
<DialogFooter className="flex-col sm:flex-row gap-2">
<Button
variant="outline"
onClick={handleDismiss}
className="w-full sm:w-auto"
>
Remind Me Later
</Button>
<Button
onClick={handlePrimaryAction}
className="w-full sm:w-auto"
>
{primaryActionLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Git Dialog - opened when user clicks primary action */}
<GitDialog
projectId={projectId}
open={isGitDialogOpen}
onOpenChange={setIsGitDialogOpen}
/>
</>
);
}
+138
View File
@@ -0,0 +1,138 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { GitDialog } from '@/components/GitDialog';
import { AlertTriangle, Upload, GitBranch } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useGitStatus } from '@/hooks/useGitStatus';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip';
interface PushWarningButtonProps {
projectId: string;
className?: string;
variant?: 'icon' | 'full';
}
export function PushWarningButton({
projectId,
className,
variant = 'icon'
}: PushWarningButtonProps) {
const [isGitDialogOpen, setIsGitDialogOpen] = useState(false);
const { data: gitStatus } = useGitStatus(projectId);
if (!gitStatus?.isGitRepo) {
return null;
}
// Determine warning state
const hasNoRemote = gitStatus.remotes.length === 0;
const hasUncommittedChanges = gitStatus.hasUncommittedChanges;
const hasCommitsAhead = gitStatus.ahead > 0;
// Don't show if everything is synced
if (!hasNoRemote && !hasUncommittedChanges && !hasCommitsAhead) {
return null;
}
// Determine icon and message
let icon = AlertTriangle;
let message = '';
let action = '';
if (hasNoRemote) {
icon = GitBranch;
message = 'No remote configured';
action = 'Configure remote to prevent data loss';
} else if (hasCommitsAhead) {
icon = Upload;
message = `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} not pushed`;
action = 'Push to remote';
} else if (hasUncommittedChanges) {
icon = AlertTriangle;
message = `${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`;
action = 'Commit and push your changes';
}
const Icon = icon;
const handleClick = () => {
if (hasNoRemote) {
// If no remote, open git dialog to configure
setIsGitDialogOpen(true);
} else {
// If remote exists, open git dialog for push/commit
setIsGitDialogOpen(true);
}
};
if (variant === 'icon') {
return (
<>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
onClick={handleClick}
className={cn(
"h-8 w-8 p-0",
hasNoRemote && "text-yellow-600 hover:text-yellow-700 dark:text-yellow-500 dark:hover:text-yellow-400",
hasCommitsAhead && "text-blue-600 hover:text-blue-700 dark:text-blue-500 dark:hover:text-blue-400",
hasUncommittedChanges && !hasCommitsAhead && "text-amber-600 hover:text-amber-700 dark:text-amber-500 dark:hover:text-amber-400",
className
)}
>
<Icon className="h-4 w-4 animate-pulse" />
</Button>
</TooltipTrigger>
<TooltipContent>
<div className="space-y-1">
<p className="font-medium">{message}</p>
<p className="text-xs text-muted-foreground">{action}</p>
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<GitDialog
projectId={projectId}
open={isGitDialogOpen}
onOpenChange={setIsGitDialogOpen}
/>
</>
);
}
// Full button variant
return (
<>
<Button
variant="outline"
size="sm"
onClick={handleClick}
className={cn(
"gap-2 border-2",
hasNoRemote && "border-yellow-500/50 bg-yellow-50 hover:bg-yellow-100 dark:bg-yellow-950/20 dark:hover:bg-yellow-950/30 text-yellow-700 dark:text-yellow-400",
hasCommitsAhead && "border-blue-500/50 bg-blue-50 hover:bg-blue-100 dark:bg-blue-950/20 dark:hover:bg-blue-950/30 text-blue-700 dark:text-blue-400",
hasUncommittedChanges && !hasCommitsAhead && "border-amber-500/50 bg-amber-50 hover:bg-amber-100 dark:bg-amber-950/20 dark:hover:bg-amber-950/30 text-amber-700 dark:text-amber-400",
className
)}
>
<Icon className="h-4 w-4 animate-pulse" />
<span className="text-sm font-medium">{message}</span>
</Button>
<GitDialog
projectId={projectId}
open={isGitDialogOpen}
onOpenChange={setIsGitDialogOpen}
/>
</>
);
}
+24 -68
View File
@@ -11,7 +11,6 @@ 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;
@@ -31,20 +30,23 @@ interface ErrorBody {
}>;
}
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) {
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
const navigate = useNavigate();
const { settings } = useAISettings();
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
// 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 => {
// Handle Project Preview Console Errors
if (error instanceof ProjectPreviewConsoleError) {
return {
@@ -67,7 +69,7 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
onClick: onOpenModelSelector,
}],
};
}
}
if (error instanceof EmptyMessageError) {
return {
@@ -99,12 +101,13 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
};
case error.code === 'insufficient_quota': {
// Only show credits dialog if we have a provider with nostr enabled
if (provider?.nostr) {
if (credits.data) {
return {
message: 'Your account is low on credits. Please add credits to keep creating.',
showCreditsButton: true,
actions: [],
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
actions: [{
label: 'Add credits',
onClick: () => setShowCreditsDialog(true),
}],
};
} else {
return {
@@ -201,7 +204,7 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
};
};
const { message, actions = [], showCreditsButton } = renderBody(error);
const { message, actions = [] } = renderBody(error);
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
@@ -214,12 +217,6 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
</h4>
<p className="text-sm text-muted-foreground">
{message}
{showCreditsButton && provider && (
<>
{' '}
<QuillyCreditsButton provider={provider} />
</>
)}
{actions.length > 0 && (
<>
{' '}
@@ -245,53 +242,12 @@ function QuillyContent({ 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}
/>
</>
);
}
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}
/>
</div>
);
}
+4 -4
View File
@@ -42,7 +42,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -78,7 +78,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -115,7 +115,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -155,7 +155,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
+12 -62
View File
@@ -1,12 +1,12 @@
import { ReactNode, useEffect, useRef } from 'react';
import { ReactNode, useMemo, useEffect } 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,80 +17,30 @@ 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, defaultConfig } = useAppContext();
const { nostr } = useNostr();
const { config } = useAppContext();
// 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,
);
}
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]);
// Cleanup on unmount
useEffect(() => {
return () => {
// Fire and forget cleanup - we don't need to await in useEffect cleanup
sessionManager.current?.cleanup().catch(error => {
sessionManager.cleanup().catch(error => {
console.warn('Failed to cleanup session manager:', error);
});
};
}, []);
}, [sessionManager]);
return (
<SessionManagerContext.Provider value={sessionManager.current}>
<SessionManagerContext.Provider value={sessionManager}>
{children}
</SessionManagerContext.Provider>
);
+10 -3
View File
@@ -52,6 +52,7 @@ interface ChatPaneProps {
onNewChat: () => void;
onFirstInteraction?: () => void;
onLoadingChange?: (isLoading: boolean) => void;
onMessageSent?: () => void;
isLoading?: boolean;
isBuildLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
@@ -67,6 +68,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onNewChat,
onFirstInteraction,
onLoadingChange,
onMessageSent,
isLoading: externalIsLoading,
isBuildLoading: externalIsBuildLoading,
consoleError,
@@ -166,7 +168,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, config.corsProxy, user?.signer),
shell: new ShellTool(fs, cwd, git, projectsPath, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath),
};
@@ -180,7 +182,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return baseTools;
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]);
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, handleFileChanged]);
// Convert tools to OpenAI format
const tools = useMemo(() => {
@@ -478,7 +480,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
// Notify parent that a message was sent (for push reminder tracking)
if (onMessageSent) {
onMessageSent();
}
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, onMessageSent]);
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = useCallback(() => {
+84 -270
View File
@@ -1,16 +1,16 @@
import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef, useMemo, memo } from 'react';
import { useState, useEffect, useCallback, useRef } 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, addConsoleMessageListener, removeConsoleMessageListener, type ConsoleMessage } from '@/lib/consoleMessages';
import { addConsoleMessage, getConsoleMessages, 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, Terminal, Trash2, ChevronRight } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
@@ -20,6 +20,11 @@ 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';
@@ -83,7 +88,6 @@ 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();
@@ -461,7 +465,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
setShowConsoleView(false);
// Reset navigation history and state
setCurrentPath('/');
@@ -518,282 +521,102 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}
};
// Constants
const CONSOLE_SORT_ORDER_KEY = 'consoleSortOrder';
const COPY_FEEDBACK_DURATION = 2000;
const MAX_CONSOLE_MESSAGES = 500; // Limit displayed messages for performance
// 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 ConsoleDropdown = () => {
const [isOpen, setIsOpen] = useState(false);
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 messages = isOpen ? getConsoleMessages() : [];
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), COPY_FEEDBACK_DURATION);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} 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 (
<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">
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
onClick={() => setShowConsoleView(false)}
className="h-8 gap-2 text-muted-foreground hover:text-foreground"
className="h-8 w-8 p-0 relative"
>
<ArrowLeft className="h-4 w-4" />
Back
</Button>
<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>
</>
<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" />
)}
</div>
</div>
</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}
>
{/* 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>
) : (
{/* 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]">
<div className="py-2 px-1 space-y-0">
{/* 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" />
{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>
</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>
</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>
);
};
@@ -866,7 +689,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<Code className="h-4 w-4" />
</Button>
)}
<ConsoleToggleButton />
<ConsoleDropdown />
<Menu />
</div>
)}
@@ -874,25 +697,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
</div>
{/* Content area */}
<div className="flex-1 min-h-0 relative">
{/* Console View */}
<div className={cn("absolute inset-0", showConsoleView ? "block" : "hidden")}>
<ConsoleView />
</div>
{/* Preview iframe */}
{hasBuiltProject && (
<div className="flex-1">
{hasBuiltProject ? (
<iframe
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className={cn("w-full h-full border-0", showConsoleView ? "hidden" : "block")}
className="w-full h-full border-0"
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>
+2 -4
View File
@@ -8,7 +8,6 @@ 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 {
@@ -38,11 +37,10 @@ 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, config.corsProxy, user?.signer);
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, user?.signer);
// Add welcome message
setLines([{
@@ -51,7 +49,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, config.corsProxy, user?.signer]);
}, [projectId, fs, git, projectsPath, user?.signer]);
// Auto-scroll to bottom when new lines are added or execution state changes
useEffect(() => {
@@ -1,35 +1,24 @@
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 (
@@ -41,14 +30,7 @@ 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>
+3 -13
View File
@@ -187,23 +187,13 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
object: currentRef,
});
// Automatically check out the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName.trim(),
force: true,
toast({
title: 'Branch created',
description: `Created branch "${newBranchName}"`,
});
// 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) {
-4
View File
@@ -44,15 +44,11 @@ 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;
}
+21 -23
View File
@@ -38,30 +38,28 @@ describe('useAIProjectId', () => {
});
// Mock useAppContext
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,
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,
},
updateConfig: vi.fn(),
});
+23 -648
View File
@@ -1,24 +1,32 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi } 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: mockGit,
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),
},
}),
}));
@@ -36,30 +44,7 @@ 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,
@@ -72,28 +57,7 @@ describe('useGitFetch', () => {
expect(result.current.isSuccess).toBe(false);
});
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)
it('fetches remote updates successfully', async () => {
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
@@ -108,207 +72,9 @@ 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,
});
@@ -319,402 +85,11 @@ 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);
});
});
});
+18 -45
View File
@@ -131,31 +131,25 @@ export function useGitFetch(projectId: string | null) {
let beforeDefaultOid: string | null = null;
let beforeCurrentOid: string | null = null;
// Get default branch from local symbolic ref
// Get remote info to find default branch
let defaultBranch: string | null = null;
try {
console.log('Reading default branch from local symbolic ref...');
console.log('Fetching remote info...');
const remoteInfo = await git.getRemoteInfo({
url: remoteUrl,
...(credentials && {
onAuth: () => ({
username: credentials.username,
password: credentials.password,
}),
}),
});
// 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');
// 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);
}
// If we have a default branch, try to get its OID before fetch
@@ -171,7 +165,7 @@ export function useGitFetch(projectId: string | null) {
}
}
} catch (error) {
console.warn('Could not read default branch from local data:', error);
console.warn('Could not get remote info:', error);
}
// Get current branch OID before fetch
@@ -210,27 +204,6 @@ 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({
@@ -346,7 +319,7 @@ export function useGitFetch(projectId: string | null) {
if (currentBranchChanged && query.data.currentBranch) {
toast({
title: 'Remote changes detected',
description: `The ${query.data.currentBranch} branch has ${query.data.currentBranchOid === null ? 'been deleted' : 'new commits available'}.`,
description: `The ${query.data.currentBranch} branch has new commits available.`,
variant: 'default',
});
+5 -11
View File
@@ -38,7 +38,6 @@ interface GitStatus {
branches: string[];
ahead: number;
behind: number;
remoteBranchExists: boolean;
}
export function useGitStatus(projectId: string | null) {
@@ -60,7 +59,6 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
@@ -82,7 +80,6 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
@@ -203,7 +200,6 @@ 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')
@@ -228,9 +224,6 @@ 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({
@@ -254,8 +247,11 @@ export function useGitStatus(projectId: string | null) {
behind = remoteOnlyCommits.length;
}
} catch {
// Remote branch doesn't exist
remoteBranchExists = false;
// 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;
}
}
}
} catch (err) {
@@ -273,7 +269,6 @@ export function useGitStatus(projectId: string | null) {
branches,
ahead,
behind,
remoteBranchExists,
};
} catch (error) {
console.error('Error checking git status:', error);
@@ -288,7 +283,6 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
},
+118
View File
@@ -0,0 +1,118 @@
import { useEffect, useCallback } from 'react';
import { useLocalStorage } from './useLocalStorage';
import { useGitStatus } from './useGitStatus';
interface PushReminderState {
/** Whether push reminders are enabled */
enabled: boolean;
/** Number of messages since last push */
messagesSinceLastPush: number;
/** Timestamp when user last pushed or dismissed a reminder */
lastInteraction: number;
/** Project ID being tracked */
currentProjectId: string | null;
}
const DEFAULT_STATE: PushReminderState = {
enabled: true,
messagesSinceLastPush: 0,
lastInteraction: 0, // Start at 0 so reminders can show immediately
currentProjectId: null,
};
/** Number of messages before showing push reminder */
const MESSAGE_THRESHOLD = 5;
/** Minimum time in ms between showing reminders (5 minutes) */
const MIN_REMINDER_INTERVAL = 5 * 60 * 1000;
export function usePushReminder(projectId: string | null) {
const [state, setState] = useLocalStorage<PushReminderState>(
'push-reminder-state',
DEFAULT_STATE
);
const { data: gitStatus } = useGitStatus(projectId);
// Reset counter when switching projects
useEffect(() => {
if (projectId && state.currentProjectId !== projectId) {
setState((prev) => ({
...prev,
currentProjectId: projectId,
messagesSinceLastPush: 0,
// Don't reset lastInteraction - keep the cooldown across project switches
}));
}
}, [projectId, state.currentProjectId, setState]);
// Check if should show reminder
const shouldShowReminder = useCallback(() => {
if (!state.enabled || !projectId || !gitStatus?.isGitRepo) {
return false;
}
// Don't show if user recently interacted with push reminder
const timeSinceLastInteraction = Date.now() - state.lastInteraction;
if (timeSinceLastInteraction < MIN_REMINDER_INTERVAL) {
return false;
}
// Show if:
// 1. There are uncommitted changes OR commits ahead of remote OR no remote configured
// 2. Enough messages have been sent since last interaction
const hasUnpushedWork =
gitStatus.hasUncommittedChanges ||
gitStatus.ahead > 0 ||
gitStatus.remotes.length === 0;
const enoughMessages = state.messagesSinceLastPush >= MESSAGE_THRESHOLD;
return hasUnpushedWork && enoughMessages;
}, [state, projectId, gitStatus]);
// Increment message counter
const incrementMessages = useCallback(() => {
if (!state.enabled || !projectId) return;
setState((prev) => ({
...prev,
messagesSinceLastPush: prev.messagesSinceLastPush + 1,
}));
}, [state.enabled, projectId, setState]);
// Reset counter (called after push or dismiss)
const resetReminder = useCallback(() => {
setState((prev) => ({
...prev,
messagesSinceLastPush: 0,
lastInteraction: Date.now(),
}));
}, [setState]);
// Enable/disable reminders
const setEnabled = useCallback((enabled: boolean) => {
setState((prev) => ({
...prev,
enabled,
messagesSinceLastPush: 0,
lastInteraction: Date.now(),
}));
}, [setState]);
// Check if there's unpushed work that should trigger warning icon
const hasUnpushedWork = gitStatus?.isGitRepo && (
gitStatus.hasUncommittedChanges ||
gitStatus.ahead > 0 ||
gitStatus.remotes.length === 0
);
return {
shouldShowReminder: shouldShowReminder(),
incrementMessages,
resetReminder,
enabled: state.enabled,
setEnabled,
hasUnpushedWork: hasUnpushedWork || false,
gitStatus,
};
}
-63
View File
@@ -260,67 +260,4 @@ 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();
});
});
});
-34
View File
@@ -278,38 +278,4 @@ 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 -39
View File
@@ -1,8 +1,6 @@
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 = {
@@ -24,39 +22,6 @@ 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 = {
@@ -70,10 +35,7 @@ describe('SessionManager', () => {
};
beforeEach(() => {
const getSettings = () => mockAISettings;
const getConfig = () => testConfig;
const getDefaultConfig = () => testConfig;
sessionManager = new SessionManager(mockFS, mockNostr, getSettings, getConfig, getDefaultConfig);
sessionManager = new SessionManager(mockFS, mockAISettings);
});
it('should initialize streaming message with reasoning content', async () => {
+24 -77
View File
@@ -11,9 +11,6 @@ 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';
@@ -61,34 +58,29 @@ export class SessionManager {
private sessions = new Map<string, SessionState>();
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
private fs: JSRuntimeFS;
private nostr: NPool;
private getSettings: () => { providers: AIProvider[] };
private getConfig: () => AppConfig;
private getDefaultConfig: () => AppConfig;
private aiSettings: { providers: AIProvider[] };
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
private corsProxy?: string;
private projectsPath: string;
private pluginsPath?: string;
constructor(
fs: JSRuntimeFS,
nostr: NPool,
getSettings: () => { providers: AIProvider[] },
getConfig: () => AppConfig,
getDefaultConfig: () => AppConfig,
aiSettings: { providers: AIProvider[] },
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.nostr = nostr;
this.getSettings = getSettings;
this.getConfig = getConfig;
this.getDefaultConfig = getDefaultConfig;
this.aiSettings = aiSettings;
this.getProviderModels = getProviderModels;
this.getCurrentUser = getCurrentUser;
}
private get git(): Git {
const config = this.getConfig();
return new Git({ fs: this.fs, nostr: this.nostr, corsProxy: config.corsProxy });
this.projectsPath = projectsPath;
this.pluginsPath = pluginsPath;
this.corsProxy = corsProxy;
}
/**
@@ -105,8 +97,7 @@ export class SessionManager {
// Try to load existing history
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`);
const lastSession = await dotAI.readLastSessionHistory();
if (lastSession) {
messages = lastSession.messages;
@@ -163,7 +154,7 @@ export class SessionManager {
*/
async deleteSession(projectId: string): Promise<void> {
const session = this.sessions.get(projectId);
session?.abortController?.abort('Session deleted');
session?.abortController?.abort();
this.sessions.delete(projectId);
@@ -218,19 +209,14 @@ 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, settings.providers);
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const provider = parsed.provider;
const model = parsed.model;
// Initialize OpenAI client
const { user, metadata } = this.getCurrentUser?.() ?? {};
const openai = createAIClient(provider, user, config.corsProxy);
const openai = createAIClient(provider, user, this.corsProxy);
let stepCount = 0;
const maxSteps = session.maxSteps || 50;
@@ -252,26 +238,16 @@ 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: `${config.fsPathProjects}/${projectId}`,
cwd: `${this.projectsPath}/${projectId}`,
fs: this.fs,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(session.tools),
config,
defaultConfig,
pluginsPath: this.pluginsPath,
user,
metadata,
repositoryUrl,
template: config.systemPrompt,
});
// Prepare messages for AI
@@ -504,7 +480,7 @@ export class SessionManager {
const session = this.sessions.get(projectId);
if (!session) return;
session.abortController?.abort('User stopped generation');
session.abortController?.abort();
session.isLoading = false;
session.streamingMessage = undefined;
session.abortController = undefined;
@@ -548,7 +524,7 @@ export class SessionManager {
/**
* Update session cost and context usage based on usage data
*/
private async updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): Promise<void> {
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
if (!this.getProviderModels) return;
const session = this.sessions.get(projectId);
@@ -558,16 +534,12 @@ 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 settings = this.getSettings();
const parsed = parseProviderModel(providerModel, settings.providers);
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const modelName = parsed.model;
const provider = parsed.provider;
@@ -591,9 +563,6 @@ 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);
}
@@ -607,35 +576,13 @@ export class SessionManager {
if (!session) return;
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`);
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${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
*/
+8 -24
View File
@@ -243,12 +243,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
// Handle bare imports like "react"
build.onResolve({ filter: /^[^./].*/ }, (args) => {
const [path, query] = args.path.split("?");
const params = new URLSearchParams(query);
// 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 packageName = path.startsWith("@")
? path.split("/").slice(0, 2).join("/")
: path.split("/")[0];
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
// If the importer is CSS, ignore (no JS deps)
try {
@@ -317,7 +319,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
}
}
const packagePath = path.slice(packageName.length);
const packagePath = args.path.slice(packageName.length);
const specifier = version
? `${cdnName}@${version}${packagePath}`
: `${cdnName}${packagePath}`;
@@ -337,14 +339,6 @@ 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",
@@ -432,8 +426,6 @@ 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";
}
@@ -446,14 +438,6 @@ 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",
};
});
},
};
}
+1 -1
View File
@@ -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();
const esbuild = await getEsbuild(esmUrl);
const indexHtmlText = await fs.readFile(
`${projectPath}/index.html`,
+1 -2
View File
@@ -23,10 +23,9 @@ const mockFS: JSRuntimeFS = {
describe('CurlCommand', () => {
let curlCommand: CurlCommand;
const testCorsProxy = 'https://proxy.shakespeare.diy/?url={href}';
beforeEach(() => {
curlCommand = new CurlCommand(mockFS, testCorsProxy);
curlCommand = new CurlCommand(mockFS);
vi.clearAllMocks();
});
+4 -7
View File
@@ -3,7 +3,6 @@ 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
@@ -36,11 +35,9 @@ export class CurlCommand implements ShellCommand {
usage = 'curl [options] <url>';
private fs: JSRuntimeFS;
private corsProxy: string;
constructor(fs: JSRuntimeFS, corsProxy: string) {
constructor(fs: JSRuntimeFS) {
this.fs = fs;
this.corsProxy = corsProxy;
}
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
@@ -64,9 +61,9 @@ export class CurlCommand implements ShellCommand {
return createErrorResult(`${this.name}: unsupported protocol: ${url.protocol}`);
}
// Proxy the URL through configured CorsProxy
// Proxy the URL through CorsProxy
const originalUrl = url.toString();
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
const proxiedUrl = `https://proxy.shakespeare.diy/?url=${encodeURIComponent(originalUrl)}`;
// Prepare request
const requestInit: RequestInit = {
@@ -96,7 +93,7 @@ export class CurlCommand implements ShellCommand {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
if (options.timeout) {
timeoutId = setTimeout(() => controller.abort('Request timeout'), options.timeout * 1000);
timeoutId = setTimeout(() => controller.abort(), options.timeout * 1000);
requestInit.signal = controller.signal;
}
+5 -6
View File
@@ -1,23 +1,22 @@
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(): Promise<ESBuild> {
export function getEsbuild(esmUrl: string): Promise<ESBuild> {
if (!promise) {
promise = loadEsbuild();
promise = loadEsbuild(esmUrl);
}
return promise;
}
async function loadEsbuild(): Promise<ESBuild> {
async function loadEsbuild(esmUrl: string): Promise<ESBuild> {
const { default: esbuild } = await import("esbuild-wasm");
await esbuild.initialize({
worker: true,
wasmURL: wasmUrl,
worker: false,
wasmURL: `${esmUrl}/[email protected]/esbuild.wasm`,
});
return esbuild;
+33 -152
View File
@@ -681,14 +681,12 @@ export class Git {
}
/**
* Create initial repository state from current local git repository
* This should only be used when no existing state event is found
* Get current repository state for creating a NIP-34 repository state event
*/
private async createInitialRepositoryState(
dir: string,
dTag: string,
signer: NostrSigner
): Promise<NostrEvent> {
private async getCurrentRepositoryState(dir: string): Promise<{
refTags: string[][];
headRef?: string;
}> {
const refTags: string[][] = [];
let headRef: string | undefined;
@@ -767,70 +765,11 @@ 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;
}
/**
@@ -1388,7 +1327,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, updated refs, and deleted stale refs
* @returns refs with missing data including HEAD
*/
private async updateRemoteRefsToNostrState(
state: RespositoryState,
@@ -1396,22 +1335,18 @@ 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> = {};
const entries = [
for (const [refName, entry] of [
...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 {
@@ -1421,32 +1356,27 @@ 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 === refValue) continue;
if (existingValue === value) continue;
} catch {
// ref doesnt exist yet
}
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
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
await git.writeRef({
fs: this.fs,
dir: options.dir,
ref: remoteRefName,
force: true, // standard behaviour of git fetch
value: refValue,
symbolic: isSymbolic, // Set symbolic flag for symbolic refs
value: value,
});
console.log(`✓ Updated ${remoteRefName} to ${isSymbolic ? 'ref: ' : ''}${refValue}`);
console.log(`✓ Updated ${remoteRefName} to ${value}`);
updated[refName] = entry;
} catch (error) {
refsWithMissingData[refName] = value;
@@ -1458,48 +1388,9 @@ 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,
}
}
@@ -1883,7 +1774,7 @@ export class Git {
}
// Extract relay URLs and clone URLs from the repository announcement
const relayUrls: string[] = [ ...(repo.relays) ?? []];
const relayUrls: string[] = [];
// If no relays specified in announcement, use default git-focused relays
if (relayUrls.length === 0) {
@@ -1922,30 +1813,20 @@ export class Git {
}
}
// Update or create repository state
let stateEvent: NostrEvent;
// Get current repository state
const repoState = await this.getCurrentRepositoryState(dir);
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);
}
// 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]] : []),
],
});
// Publish the state event to Nostr relays
console.log(`Publishing repository state to ${relayUrls.length} relays`);
+1 -1
View File
@@ -50,7 +50,7 @@ export async function initializeSentry(dsn: string): Promise<void> {
// Environment
environment: import.meta.env.MODE,
// Release
release: import.meta.env.VERSION,
release: import.meta.env.VERSION || 'development',
// Censor sensitive data before sending to Sentry
beforeSend(event) {
// Regex to match Nostr nsec private keys
-522
View File
@@ -1,522 +0,0 @@
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');
});
});
});
+95 -168
View File
@@ -3,38 +3,64 @@ 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;
config: AppConfig;
defaultConfig: AppConfig;
pluginsPath?: string;
user?: NUser;
metadata?: NostrMetadata;
repositoryUrl?: string;
template?: string;
}
/**
* 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 %}
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
const { name, profession, tools, mode, fs, cwd, pluginsPath, user, metadata } = opts;
# Your Environment
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
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**: {{ date }}
- **Current Page**: {{ location.href }}
- **Current Working Directory**: {{ cwd }}
- **Repository URL**: {{ repositoryUrl }}
- **Current Date**: ${currentDate}
- **Current Page**: ${location.href}
- **Current Working Directory**: ${cwd}
## What Shakespeare Is
@@ -52,19 +78,7 @@ Shakespeare is a web-based development environment where users can build Nostr w
## The User
{% 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 %}
${userText}
## User Interface
@@ -124,8 +138,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
@@ -149,160 +163,73 @@ 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.{% if tools.length > 0 %}
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.`;
## Available Tools
// Add available tools to the system prompt
const toolNames = tools
.filter((tool) => tool.type === "function")
.map((tool) => tool.function.name);
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 %}
## Skills
{% 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
[![Edit with Shakespeare]({{ badgeUrl }})]({{ 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 {
skills = await getAllSkills(fs, config.fsPathPlugins);
} catch {
// Skills not available, use empty array
skills = [];
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"
}`;
}
}
}
// Get README.md if it exists
let readmeText: string | undefined;
// Add skills section
system += "\n\n## Skills\n\n";
if (pluginsPath) {
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";
}
} catch {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
}
} 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
try {
const readmePath = join(cwd, "README.md");
readmeText = await fs.readFile(readmePath, "utf8");
const readmeText = await fs.readFile(readmePath, "utf8");
if (readmeText) {
system += "\n\n" + readmeText;
}
} catch {
// README.md not found, continue
}
// Get agent context if it exists
let agentsText: string | undefined;
// Add context from AGENTS.md if it exists
try {
const { text } = await getAgentContext(fs, cwd);
agentsText = text;
system += "\n\n" + text;
} catch {
// AGENTS.md not found, continue
}
// 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;
}
return system;
}
async function getAgentContext(
+1 -2
View File
@@ -35,13 +35,12 @@ 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, '/projects', testCorsProxy);
shellTool = new ShellTool(mockFS, testCwd, mockGit);
});
it('should have correct tool properties', () => {
+2 -4
View File
@@ -53,7 +53,6 @@ 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";
@@ -63,12 +62,11 @@ export class ShellTool implements Tool<ShellToolParams> {
),
});
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', corsProxy: string, signer?: NostrSigner) {
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', signer?: NostrSigner) {
this.fs = fs;
this.cwd = cwd;
this.git = git;
this.projectsPath = projectsPath;
this.corsProxy = corsProxy;
this.signer = signer;
this.commands = new Map();
@@ -77,7 +75,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.corsProxy));
this.registerCommand(new CurlCommand(fs));
this.registerCommand(new CutCommand(fs));
this.registerCommand(new DateCommand());
this.registerCommand(new DiffCommand(fs));
+3 -8
View File
@@ -57,10 +57,10 @@
"temporaryDirectoryDescription": "Filesystem path for temporary files",
"sentryDsn": "Sentry DSN",
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
"pushReminders": "Push reminders",
"pushRemindersDescription": "Show periodic reminders to push your code to a remote repository to prevent data loss.",
"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",
@@ -87,8 +87,6 @@
"add": "Add",
"remove": "Remove",
"retry": "Retry",
"latestFirst": "Latest First",
"oldestFirst": "Oldest First",
"name": "Name",
"email": "Email",
"buildNostrApps": "Build apps with AI",
@@ -487,8 +485,5 @@
"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...",
"modified": "Modified",
"restoreToDefault": "Restore to default",
"restoredToDefault": "Restored to Default"
"deleting": "Deleting..."
}
+1 -8
View File
@@ -55,8 +55,6 @@
"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",
@@ -83,8 +81,6 @@
"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",
@@ -426,8 +422,5 @@
"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.",
"modified": "An Canza",
"restoreToDefault": "Mayar da asali",
"restoredToDefault": "An Mayar da Asali"
"giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta."
}
+1 -8
View File
@@ -55,8 +55,6 @@
"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",
@@ -83,8 +81,6 @@
"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",
@@ -423,8 +419,5 @@
"invalidGiftCard": "Kaadị Onyinye Na-ezighị Ezi",
"giftCardNotFound": "Achọtaghị kaadị onyinye a.",
"alreadyRedeemed": "Egbapụtalarị",
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a.",
"modified": "Gbanwere",
"restoreToDefault": "Weghachi na nke mbụ",
"restoredToDefault": "Weghachiri na Nke Mbụ"
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a."
}
+1 -8
View File
@@ -55,8 +55,6 @@
"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",
@@ -83,8 +81,6 @@
"add": "Adicionar",
"remove": "Remover",
"retry": "Tentar novamente",
"latestFirst": "Mais Recentes Primeiro",
"oldestFirst": "Mais Antigos Primeiro",
"name": "Nome",
"email": "Email",
"buildNostrApps": "Construa aplicativos com IA",
@@ -436,8 +432,5 @@
"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.",
"modified": "Modificado",
"restoreToDefault": "Restaurar para padrão",
"restoredToDefault": "Restaurado para Padrão"
"giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado."
}
+1 -8
View File
@@ -55,8 +55,6 @@
"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",
@@ -83,8 +81,6 @@
"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",
@@ -423,8 +419,5 @@
"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ẹ.",
"modified": "Ti Yipada",
"restoreToDefault": "Pada si atilẹwa",
"restoredToDefault": "Ti Pada si Atilẹwa"
"giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ."
}
+1 -8
View File
@@ -55,8 +55,6 @@
"configDirectoryDescription": "存储配置文件的文件系统路径",
"temporaryDirectory": "临时目录",
"temporaryDirectoryDescription": "临时文件的文件系统路径",
"systemPrompt": "系统提示",
"systemPromptDescription": "使用类似Jinja的模板语法自定义AI助手的系统提示。这控制助手的行为和知识。",
"english": "English",
"portuguese": "Português",
"chinese": "中文",
@@ -83,8 +81,6 @@
"add": "添加",
"remove": "移除",
"retry": "重试",
"latestFirst": "最新优先",
"oldestFirst": "最旧优先",
"name": "名称",
"email": "邮箱",
"buildNostrApps": "使用AI构建应用",
@@ -436,8 +432,5 @@
"invalidGiftCard": "无效的礼品卡",
"giftCardNotFound": "找不到此礼品卡。",
"alreadyRedeemed": "已兑换",
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。",
"modified": "已修改",
"restoreToDefault": "恢复默认值",
"restoredToDefault": "已恢复默认值"
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。"
}
+10
View File
@@ -105,6 +105,16 @@ 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"
+22
View File
@@ -8,12 +8,14 @@ import { Label } from "@/components/ui/label";
import { useIsMobile } from "@/hooks/useIsMobile";
import { useNavigate } from "react-router-dom";
import { useAppContext } from "@/hooks/useAppContext";
import { usePushReminder } from "@/hooks/usePushReminder";
export function Preferences() {
const { t } = useTranslation();
const isMobile = useIsMobile();
const navigate = useNavigate();
const { config, updateConfig } = useAppContext();
const pushReminder = usePushReminder(null);
return (
<div className="p-6 space-y-6">
@@ -73,6 +75,26 @@ export function Preferences() {
</p>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="push-reminders" className="text-sm font-medium">
{t('pushReminders')}
</Label>
</div>
<Switch
id="push-reminders"
checked={pushReminder.enabled}
onCheckedChange={(checked) => {
pushReminder.setEnabled(checked);
}}
/>
</div>
<p className="text-sm text-muted-foreground">
{t('pushRemindersDescription')}
</p>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
+43
View File
@@ -15,11 +15,14 @@ import { useNavigate } from 'react-router-dom';
import { ActionsMenu } from '@/components/ActionsMenu';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { PushWarningButton } from '@/components/PushWarningButton';
import { PushReminderDialog } from '@/components/PushReminderDialog';
import { StarButton } from '@/components/StarButton';
import { useBuildProject } from '@/hooks/useBuildProject';
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useAutoBuild } from '@/hooks/useAutoBuild';
import { usePushReminder } from '@/hooks/usePushReminder';
export function ProjectView() {
const { projectId } = useParams<{ projectId: string }>();
@@ -30,6 +33,7 @@ export function ProjectView() {
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
const [isAILoading, setIsAILoading] = useState(false);
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
const [isPushReminderOpen, setIsPushReminderOpen] = useState(false);
// Use console error state from provider
const { consoleError, dismissConsoleError, clearErrors } = useConsoleError();
@@ -43,6 +47,7 @@ export function ProjectView() {
const build = useBuildProject(projectId!);
const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!);
const pushReminder = usePushReminder(projectId || null);
// Enable auto-build for previewable projects
useAutoBuild({
@@ -105,6 +110,18 @@ export function ProjectView() {
setIsAILoading(loading);
};
// Handle message sent - increment push reminder counter
const handleMessageSent = useCallback(() => {
pushReminder.incrementMessages();
}, [pushReminder]);
// Watch for when we should show the reminder (after state updates)
useEffect(() => {
if (pushReminder.shouldShowReminder && !isPushReminderOpen) {
setIsPushReminderOpen(true);
}
}, [pushReminder.shouldShowReminder, isPushReminderOpen]);
// Handle first user interaction to enable audio context
const handleFirstInteraction = () => {
// This will be handled automatically by the useKeepAlive hook
@@ -165,6 +182,7 @@ export function ProjectView() {
<div className="flex items-center gap-2">
{project ? (
<>
<PushWarningButton projectId={project.id} className="h-8" />
<StarButton
projectId={project.id}
projectName={project.name}
@@ -227,6 +245,7 @@ export function ProjectView() {
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
onMessageSent={handleMessageSent}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
@@ -307,6 +326,17 @@ export function ProjectView() {
onProjectDeleted={handleProjectDeleted}
/>
)}
{/* Push Reminder Dialog */}
{project && (
<PushReminderDialog
projectId={project.id}
open={isPushReminderOpen}
onOpenChange={setIsPushReminderOpen}
onDisableReminders={() => pushReminder.setEnabled(false)}
onDismiss={pushReminder.resetReminder}
/>
)}
</div>
);
}
@@ -374,6 +404,7 @@ export function ProjectView() {
<div className="flex items-center gap-2">
{project ? (
<>
<PushWarningButton projectId={project.id} className="h-8" />
<StarButton
projectId={project.id}
projectName={project.name}
@@ -408,6 +439,7 @@ export function ProjectView() {
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
onMessageSent={handleMessageSent}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
@@ -461,6 +493,17 @@ export function ProjectView() {
onProjectDeleted={handleProjectDeleted}
/>
)}
{/* Push Reminder Dialog */}
{project && (
<PushReminderDialog
projectId={project.id}
open={isPushReminderOpen}
onOpenChange={setIsPushReminderOpen}
onDisableReminders={() => pushReminder.setEnabled(false)}
onDismiss={pushReminder.resetReminder}
/>
)}
</div>
);
}
+194 -564
View File
@@ -1,24 +1,22 @@
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw } from "lucide-react";
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2 } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { useState, useEffect, useMemo } from "react";
import { useState, useEffect } 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, defaultConfig, updateConfig } = useAppContext();
const { config, updateConfig } = useAppContext();
const { toast } = useToast();
const { serviceWorkerRegistration, updateServiceWorker, clearCache } = useOffline();
@@ -33,102 +31,6 @@ 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>('');
@@ -363,42 +265,24 @@ 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">
<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>
<h4 className="text-sm font-medium">{t('projectTemplate')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<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>
<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,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('projectTemplateDescription')}
</p>
@@ -411,42 +295,24 @@ 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">
<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>
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<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>
<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,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('corsProxyDescription')}
</p>
@@ -459,42 +325,24 @@ 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">
<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>
<h4 className="text-sm font-medium">{t('faviconUrl')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<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>
<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,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('faviconUrlDescription')}
</p>
@@ -507,43 +355,25 @@ 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">
<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>
<h4 className="text-sm font-medium">{t('esmUrl')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<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>
<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(/\/+$/, ''),
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('esmUrlDescription')}
</p>
@@ -556,42 +386,24 @@ 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">
<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>
<h4 className="text-sm font-medium">{t('previewDomain')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<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>
<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,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('previewDomainDescription')}
</p>
@@ -604,87 +416,47 @@ 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">
<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>
<h4 className="text-sm font-medium">{t('showcase')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-4">
<div className="flex items-center justify-between">
<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>
<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>
<p className="text-xs text-muted-foreground">
{t('showcaseEnabledDescription')}
</p>
<div className="space-y-2">
<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>
<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,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('showcaseModeratorDescription')}
</p>
@@ -698,42 +470,24 @@ 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">
<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>
<h4 className="text-sm font-medium">{t('sentryDsn')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<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>
<Input
id="sentry-dsn"
type="text"
placeholder="https://..."
value={sentryDsnInput}
onChange={(e) => {
const value = e.target.value;
setSentryDsnInput(value);
updateConfig((current) => ({
...current,
sentryDsn: value,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('sentryDsnDescription')}
</p>
@@ -746,174 +500,97 @@ 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">
<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>
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-4">
<div className="space-y-2">
<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>
<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,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('projectsDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<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>
<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,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('configDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<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>
<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,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('temporaryDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<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>
<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,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('pluginsDirectoryDescription')}
</p>
@@ -922,53 +599,6 @@ 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
View File
@@ -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: 15 * 1024 * 1024, // 15 MB (to accommodate esbuild.wasm at ~12 MB)
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024, // 10 MB
cleanupOutdatedCaches: true,
},
devOptions: {