Compare commits

..
147 Commits
Author SHA1 Message Date
MK Fain e23c843ef9 Fix GlobalChatProvider parseProviderModel usage
The parseProviderModel function returns { model, provider } but the code
was trying to destructure { providerId, modelId }. Fixed to correctly
use the actual return values and pass the required providers array
parameter to the function.
2025-12-03 20:10:18 -06:00
MK Fain 0c4de2e2c0 Fix global chat issues and move chat system prompt setting
1. Fixed user message not appearing in global chat
2. Made project chat and global chat remember separate models
   - Added separate localStorage storage for global chat model
   - Project chat continues to use recentlyUsedModels from AISettings
   - Global chat now stores its model independently
3. Moved Chat System Prompt setting from Preferences to System Settings
4. Removed chat pop-out functionality
   - Removed isPoppedOut state from GlobalChatContext
   - Removed handlePopOut function from GlobalChatPane
   - Removed pop-out button from desktop chat header
   - Removed isPoppedOut check from FloatingChatButton
2025-12-03 20:03:53 -06:00
MK Fain 477d055797 Improve unread message indicator for floating chat
- Add hasUnread state to track whether user has seen new messages
- Mark messages as read when chat is opened
- Mark as unread when assistant responds while chat is closed
- Change indicator from message count to simple dot for cleaner UX
2025-12-03 19:50:10 -06:00
MK Fain 15c8040e35 Fix: Move FloatingChatButton and GlobalChatPane inside Router
The ModelSelector component uses useNavigate which requires Router context.
Move the floating chat components from App.tsx into AppRouter.tsx where
they have access to the BrowserRouter/HashRouter context.
2025-12-03 19:47:29 -06:00
MK Fain 68702abc41 Add floating global chat feature
- Add GlobalChatContext, GlobalChatProvider for managing chat state
- Create FloatingChatButton component with unread message indicator
- Create GlobalChatPane with desktop (floating panel) and mobile (full screen) views
- Features include:
  - Streaming AI responses with markdown rendering
  - Auto context trimming when messages exceed ~50k tokens
  - Easy text copy from messages (hover to reveal copy button)
  - Pop-out to separate window
  - Minimize/dismiss functionality
  - Clear chat history
  - Mobile-optimized full-screen drawer
- Add settings in Preferences page:
  - Enable/disable floating chat button
  - Customize chat system prompt
- Add translations for all supported languages (en, pt, zh, ha, yo, ig)
- Integrate with existing AI provider configuration
2025-12-03 19:44:12 -06:00
Alex Gleason f41d70442a Prevent the Nostr settings dialog from refreshing 2025-12-03 17:06:29 -06:00
Alex Gleason 6f94aaa45e Allow editing t-tags on Nostr repos 2025-12-03 16:40:01 -06:00
Alex Gleason a2ffc7bf9c Display provider favicon in Add Provider dialog 2025-12-03 12:49:45 -06:00
Alex Gleason 4bc223e5af Revert "Merge branch 'text-chats' into 'main'"
This reverts commit 7badd0113f, reversing
changes made to 02dcd5cbe8.
2025-12-03 12:01:53 -06:00
Alex Gleason 2179c8fdce Revert "Don't display toast on own chat page"
This reverts commit 00b476085d.
2025-12-03 12:00:09 -06:00
Alex Gleason 00b476085d Don't display toast on own chat page 2025-12-03 02:47:11 -06:00
Alex Gleason 7badd0113f Merge branch 'text-chats' into 'main'
Text chats

See merge request soapbox-pub/shakespeare!79
2025-12-03 08:40:15 +00:00
Alex Gleason b3f47d41cb Don't use flexible sidebar in ChatView 2025-12-03 02:36:40 -06:00
Alex Gleason 8cf2b8a9d4 Display spinner for text chats 2025-12-03 02:31:13 -06:00
Alex Gleason f8743e3c63 Fix chat autostart 2025-12-03 02:25:28 -06:00
Alex Gleason ca0ae22cd3 Add start_project tool to text chats 2025-12-03 02:00:47 -06:00
Alex Gleason 01df64fce0 No useless escape 2025-12-03 01:53:05 -06:00
Alex Gleason 300fd26268 Add max width to text chats 2025-12-03 01:51:29 -06:00
Alex Gleason 0c42af082a Improve Chat Not Found design 2025-12-03 01:41:10 -06:00
Alex Gleason 4f552334b2 Allow deleting a chat 2025-12-03 01:40:28 -06:00
Alex Gleason bb9245118c Refresh sidebar when starting new chat, allow more characters in chat title 2025-12-03 01:33:34 -06:00
Alex Gleason 2c42efd4e1 Skip somethings for chats idk 2025-12-03 01:27:37 -06:00
Alex Gleason d3187d8c77 Improve chats icon 2025-12-03 01:11:39 -06:00
Alex Gleason ab039d2fb7 Text chats 2025-12-03 01:05:00 -06:00
Alex Gleason 02dcd5cbe8 Add Git Identity icon 2025-12-03 00:37:22 -06:00
Alex Gleason 69d8dfa9cd Add asterisks near required fields in Settings forms 2025-12-03 00:33:05 -06:00
Alex Gleason 43ad67b048 Add icons to Settings pages 2025-12-03 00:25:12 -06:00
Alex Gleason 5d1e2ddea0 Add "Vibed with Shakespeare" to system prompt 2025-12-02 20:29:53 -06:00
Alex Gleason e83ff56722 Fix CreditsDialog padding 2025-12-02 13:39:59 -06:00
Alex Gleason 56d9bca5c7 Increment the generated project id instead of falling back to untitled 2025-12-01 23:47:06 -06:00
Alex Gleason 89244d88e5 Fix updating templates 2025-12-01 23:34:06 -06:00
Alex Gleason 2096d526c4 Load skills from project dir in addition to plugins 2025-12-01 23:19:02 -06:00
Alex Gleason 367a6834eb typecheck fixes 2025-12-01 21:06:47 -06:00
Alex Gleason 9ede6bbd21 Provider name is a required field - backfill it when parsing config 2025-12-01 20:51:38 -06:00
Alex Gleason c1ad18bab7 Display nice model name in ModeleSelector if it's available 2025-12-01 17:52:18 -06:00
Alex Gleason 0e27c4d394 Display provider favicons instead of fullId in ModelSelector 2025-12-01 17:32:41 -06:00
Alex Gleason cd77a8edd5 Add background color to Nostr accounts in settings 2025-12-01 17:22:23 -06:00
Alex Gleason e05baee1f4 Allow setting AI Provider display name 2025-12-01 17:19:34 -06:00
Alex Gleason efbfd19f10 Started with -> Vibing with 2025-12-01 16:46:14 -06:00
Alex Gleason f256de7ab3 Improve icons in About Shakespeare page 2025-12-01 16:42:13 -06:00
Alex Gleason 5d65638f32 Improve icons in AI settings 2025-12-01 16:37:34 -06:00
Alex Gleason 2e65e1ee6c Improve design of Nostr settings 2025-12-01 16:32:30 -06:00
Alex Gleason dfc372e1d4 Preferences design improvements 2025-12-01 16:26:19 -06:00
Alex Gleason e8c3406e55 Add icons to all accordions in System settings 2025-12-01 16:21:00 -06:00
Alex Gleason 0a191be435 Let the system prompt be managed on the AI settings page 2025-12-01 16:12:21 -06:00
Alex Gleason 40062b6b92 Add Advanced section to bottom of AI Settings 2025-12-01 16:02:06 -06:00
Alex Gleason 6540ab28e6 Improve project templates description 2025-12-01 15:41:30 -06:00
Alex Gleason 93ae204e5e Improve design of mobile settings navigation 2025-12-01 15:38:12 -06:00
Alex Gleason 2c9e8abf5d Let project templates be re-ordered and reset to default 2025-12-01 15:36:06 -06:00
Alex Gleason b47f715362 Remove unnecessary empty states from AI settings sub-sections 2025-12-01 15:24:39 -06:00
Alex Gleason eadb628094 Fix linter issues 2025-12-01 15:21:23 -06:00
Alex Gleason db05223c68 Move project templates to AI settings 2025-12-01 15:18:34 -06:00
Alex Gleason 0a20d736ab Small system prompt tweaks 2025-12-01 15:08:29 -06:00
Alex Gleason fe0becb2c8 Expose templates to the system prompt 2025-12-01 14:59:24 -06:00
Alex Gleason 6941710a3d Clarify that mkstack should be chosen when the assistant isn't sure 2025-12-01 14:37:30 -06:00
Alex Gleason b67417115c Display template used to start project at top of messages history 2025-12-01 14:36:58 -06:00
Alex Gleason 23ad0a9d35 Remember the chosen project template 2025-12-01 14:26:58 -06:00
Alex Gleason 7112591aa3 Use textarea for template description 2025-12-01 14:05:46 -06:00
Alex Gleason 8a65c76197 Add nutstack and luvstack 2025-12-01 13:57:30 -06:00
Alex Gleason 009142b854 Allow multiple project templates to be configured 2025-12-01 13:20:25 -06:00
Alex Gleason f0c1784288 Clone from Nostr URL 2025-11-28 21:32:46 -06:00
Alex Gleason 94b4dcbda6 Filter out invalid repos 2025-11-28 21:29:23 -06:00
Alex Gleason c49e8811af Show follows repositories in Clone tab 2025-11-28 21:25:55 -06:00
Alex Gleason 37c72391a0 Projects Sidebar improvements 2025-11-28 21:16:41 -06:00
Alex Gleason 6c92b2dc4d Shrink down settings navigation again 2025-11-28 21:14:37 -06:00
Alex Gleason 676655ef66 Improve hover state of select 2025-11-28 21:01:01 -06:00
Alex Gleason 27f9435be9 Add foreground to many elements in settings 2025-11-28 20:58:31 -06:00
Alex Gleason 32656a8f5c Improve Settings Items hover states 2025-11-28 20:21:23 -06:00
Alex Gleason bd9a276275 Let PWA update nag be dismissed 2025-11-28 20:14:56 -06:00
Alex Gleason 7fa4330249 Remove Nostr pigeonholing from system prompt 2025-11-28 20:08:53 -06:00
Alex Gleason b5c2c79feb Remove pointless buttons from RepositoryCard 2025-11-28 20:05:42 -06:00
Alex Gleason f3a3d31977 Add a list of your own ngit repos to clone on the import page 2025-11-28 20:03:06 -06:00
Alex Gleason 68eee82c92 Make everything a bit rounder 2025-11-28 15:10:49 -06:00
Alex Gleason cd006889c8 Add search to projects sidebar 2025-11-28 15:02:37 -06:00
Alex Gleason d23778547f Clean up unused settings i18n strings 2025-11-28 14:42:14 -06:00
Alex Gleason 627a43309c Improve mobile settings design 2025-11-28 14:33:33 -06:00
Alex Gleason 07d594a373 Settings design improvements 2025-11-28 14:28:36 -06:00
DanConwayDev 5b8cb25675 Revert "Checkout branch with "force" so it updates the tree"
This reverts commit d13bc84232.

proceed with caution on this as i dont know what you were fixing
with this change
2025-11-28 11:34:19 -06:00
DanConwayDev 89de28cb0c fix: recovered for detached HEAD
git_commit tool was showing a false positive when in reality no
commits were changed. there are also other issues in the UI whilst
in this state. eg. current branch doesn't show, cannot push or pull,
or 'push to nostr' or github or other remote.

warning this must be done in combination with reverting
d13bc84232 or the user will lose all
uncomitted changes
2025-11-28 11:34:19 -06:00
Alex Gleason c5e5cafb77 Add "Try again" action to Quilly fallback 2025-11-26 12:05:33 -06:00
Alex Gleason 926e63bb81 Poll the Lightning invoice screen for payment 2025-11-25 17:36:42 -06:00
Alex Gleason c768f5fbe6 Don't parse URLs in user messages as images 2025-11-24 13:15:59 -06:00
Alex Gleason 2db50808d5 Fix input clipping on Nostr settings dialog 2025-11-23 23:03:38 -06:00
Alex Gleason b7a55f7fd7 Merge branch 'parseImageURLs' into 'main'
Recognize Image URLs

See merge request soapbox-pub/shakespeare!71
2025-11-23 17:57:24 +00:00
Alex Gleason 7fb9d765be Improve image retry logic 2025-11-23 11:54:26 -06:00
Alex Gleason 1f570a0d8f Merge remote-tracking branch 'origin/main' into parseImageURLs 2025-11-23 11:30:50 -06:00
Alex Gleason d2a8ee36f7 Don't upload images to Blossom 2025-11-23 11:30:34 -06:00
Alex Gleason f148bee88b Simplify Settings titles 2025-11-23 11:05:04 -06:00
Alex Gleason 199043e4bc Add Terminal to System Settings 2025-11-23 11:02:07 -06:00
Alex Gleason 4f73d99f64 Cache project template to VFS for faster clones 2025-11-23 10:42:07 -06:00
Alex Gleason 3050e93555 Fix return type of git.fetch method, ensure defaultBranch is returned 2025-11-23 10:14:21 -06:00
Alex Gleason fcc2b9902a Fix cwd in git commands 2025-11-23 10:13:51 -06:00
Alex Gleason 30ead01178 Support custom headers in MCP servers 2025-11-22 00:46:41 -06:00
Alex Gleason 393ed3ebca Fix linter issues 2025-11-21 22:07:08 -06:00
Alex Gleason 870b7ffb93 Improve MCP Servers design 2025-11-21 22:02:49 -06:00
Alex Gleason e2f816b6c1 Add MCP support 2025-11-21 20:14:38 -06:00
Alex Gleason c22332a7ce Fix prompt template 2025-11-21 12:03:08 -06:00
Alex Gleason 8199ca5a18 Reset button in System Settings should clear value instead of just setting to default 2025-11-21 12:00:35 -06:00
Alex Gleason dc549e64bd readmeText -> README, agentsText -> AGENTS 2025-11-21 11:52:16 -06:00
lemonknowsall e88b8c90d9 prevent image loading and add image-off logo for code preview 2025-11-16 17:44:17 -08:00
lemonknowsall 766aea14b9 add VFS only retry for models that don't accept images 2025-11-16 11:32:04 -08:00
lemonknowsall 653a7c0f0c add images to both VFS and API, update ChatPane UI 2025-11-15 20:43:35 -08:00
lemonknowsall 42637458c9 pass image to agent, render image in chat 2025-11-15 20:43:35 -08:00
Alex Gleason a6caf93e8b Display "Push to Nostr" when origin URL is empty 2025-11-14 21:19:01 -06:00
Alex Gleason b55fd857e1 Treat Vite ?url imports as external ESM CDN links 2025-11-14 13:20:46 -06:00
Alex Gleason 65c51e865a Treat wasm import as binary, remove nonstandard import attribute on esbuild.wasm 2025-11-14 12:39:52 -06:00
Alex Gleason 8ecf460140 Don't redirect /assets/* in netlify redirects file 2025-11-13 22:11:32 -06:00
Alex Gleason 8ee4efdee3 Remove outdated soapbox.dev mirror 2025-11-13 21:23:12 -06:00
Alex Gleason 5ac5fcc212 systemPromptDescription: EJS -> Jinja-like 2025-11-13 20:07:08 -06:00
Alex Gleason 58c24f615d Swap out eta for nunjucks 2025-11-13 19:49:15 -06:00
Alex Gleason d1cbcda5d5 Minor simplifications to system prompt template 2025-11-13 19:27:45 -06:00
Alex Gleason c30ed35c67 Fix eta CSP issue, disable autoTrim 2025-11-13 19:20:53 -06:00
Alex Gleason dea364c2a6 Use esbuild worker, emit wasm file in build 2025-11-13 18:50:46 -06:00
Alex Gleason eabba1ecec Expose full config and defaultConfig to systemPrompt template 2025-11-13 18:12:45 -06:00
Alex Gleason db02b9fb94 Let system prompt be configurable in System Settings (EJS template) 2025-11-13 17:36:04 -06:00
DanConwayDev 4d88823c2d Improve toast message for new branch push 2025-11-13 16:41:48 -06:00
Alex Gleason 933530a96c Add Edit with Shakespeare scaling note to system prompt 2025-11-13 16:40:51 -06:00
DanConwayDev 43f4e0d15d Auto-switch to newly crated branch 2025-11-13 16:22:50 -06:00
DanConwayDev 21e522cba7 Fix git fetch handle deteled refs 2025-11-13 16:11:39 -06:00
Alex Gleason d8bfa10b43 Indicate non-default System Settings, allow clicking to restore to default 2025-11-13 16:10:19 -06:00
Alex Gleason 7a000a80f0 Add system prompt test 2025-11-13 15:55:52 -06:00
Alex Gleason 866155d907 Add "Edit with Shakespeare" info to system prompt 2025-11-13 15:39:18 -06:00
Alex Gleason 72439d4ec9 Merge branch 'fix/periods-in-name-break-deployment' into 'main'
fix/periods-in-name-break-deployment

See merge request soapbox-pub/shakespeare!70
2025-11-13 04:03:25 +00:00
sam 51f079696a detect and block deployment when the target contains periods 2025-11-13 10:53:52 +07:00
Alex Gleason abe3368115 Add error handling to favicon URL 2025-11-12 14:34:46 -06:00
Alex Gleason 16d357364d Add abort reasons to abort controllers 2025-11-12 14:24:41 -06:00
Alex Gleason 2d505588c7 Refactor Quilly to fix conditional hook usage 2025-11-12 14:01:46 -06:00
Alex Gleason a9ab551ca2 Sentry remove unnecessary mode fallback 2025-11-12 13:51:04 -06:00
DanConwayDev 075d6aba2d Fix git fetch default branch identification
calling remote via getRemoteInfo is not needed and results in null
for nostr remotes.

default branch is used here to trigger git fetch toast notifications

improved test coverage to test whether toast mis-fire when there is
no update
2025-11-12 13:42:18 -06:00
DanConwayDev a1f571b2d8 Fix git push publish state to repo relays
instead of hardcoded default
2025-11-12 13:40:06 -06:00
DanConwayDev d4eca86ec6 Fix retain prior state during git push to nostr remote
otherwise git push to a feature branch removes all other branches
including main and sets HEAD to feature branch.
2025-11-12 13:39:31 -06:00
DanConwayDev 44a208aed5 Fix don't unwrap symrefs in nostr remote
this was causing `refs/remotes/origin/HEAD` to be a commit id rather
than a symbolic reference like in the nostr state event
2025-11-12 13:38:51 -06:00
DanConwayDev ccc3613c83 Fix git status when branch not published
instead using status 'X commits ahead' it says 'Branch not published' and disables pull disabled.
2025-11-12 13:38:20 -06:00
Alex Gleason fd309e0aab Merge branch 'pr/fix-npm-run-electron(8edc8583)' 2025-11-12 13:36:27 -06:00
Alex Gleason 3d06e0cb57 Accumulate and persist total project cost and display in Project Details dialog 2025-11-12 12:09:42 -06:00
Alex Gleason dbf5cfe0a3 Make curl virtual command use configured corsProxy instead of hardcoded 2025-11-12 11:10:30 -06:00
Alex Gleason 0b66f81bfc Make "Push to Nostr" actually push without requiring another click to "Push" 2025-11-12 11:02:01 -06:00
Alex Gleason 35a85c18bd Add CORS proxy to system prompt 2025-11-11 18:03:21 -06:00
Alex Gleason e116f7e9ec Fix typecheck issues 2025-11-10 09:55:34 -06:00
Alex Gleason cbf18d482d Fix failing tests 2025-11-10 09:42:27 -06:00
DanConwayDev d11a52992e Fix grasp server sync during automatic fetch
Ensure grasp servers stay synchronized with Nostr state events during
the periodic fetch (every 60 seconds). This prevents a critical UX issue
where the Nostr remote appears up-to-date but grasp servers have stale
refs, making the repository uncloneable.

This can occur when a state event is successfully published to Nostr
relays but an error prevents the corresponding git refs from being
pushed to grasp servers. By validating and syncing during fetch, we
ensure at least one grasp server has the correct refs that match the
Nostr state, maintaining repository accessibility.
2025-11-10 09:11:05 -06:00
DanConwayDev 056f2a0b5f Add automatic Git fetch with change detection and toast notifications
- Implement useGitFetch hook with 60-second polling
- Add toast notifications for remote changes detection
- Update GitDialog to show fetch status and manual refresh
- Add comprehensive tests for useGitFetch
- Update AGENTS.md documentation
- abstract simple time ago data function
2025-11-10 09:11:05 -06:00
DanConwayDev 50897e1164 fix: fetch Nostr remote refs into remote tracking refs instead of local refs
Previously, git fetch for Nostr remotes was directly updating local refs
(refs/heads/*), which incorrectly merged remote changes into the working
tree. Now properly fetches into remote tracking refs (refs/remotes/origin/*)
following standard Git behavior, allowing users to inspect and merge changes
manually.

When no Nostr state event is found, now only fetches from the first priority
clone URL instead of trying all URLs. This prevents potential sync issues
where different servers might have divergent histories, which would create
non-fast-forward conflicts that would revert on the next fetch from the
primary server.
2025-11-10 09:11:05 -06:00
DanConwayDev db001beeb5 Refactor to use parsed repo and state events
move abstract logic in git method extractRepositoryState to a
pure function parseRepositoryState with typed interface for
future reusability.

pass around parsed event instead of NostrEvent.
2025-11-10 09:11:05 -06:00
DanConwayDev 301b0d526b Refactor to abstract repo announcement parsing 2025-11-10 09:11:05 -06:00
Alex Gleason c474cd5c6c Fix linter issues 2025-11-06 14:33:10 -06:00
DanConwayDev 465bef91e8 fix npm run electron by generating package.json
The electron package.json needs to exist for this command to succeed.
If `prepare-electron-publish.js` has never been run then it hasn't been generated yet. Solution, run that everytime.
2025-11-03 11:35:20 +00:00
176 changed files with 12541 additions and 3397 deletions

No files matched your search

+2
View File
@@ -91,6 +91,7 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
- **LightningFSAdapter**: Adapts LightningFS to the unified JSRuntimeFS interface
- **GitCommitTool**: AI tool for automated commits with staging and validation
- **useGitStatus Hook**: Real-time Git status monitoring (updates every 5 seconds)
- **useGitFetch Hook**: Automatic remote fetch with change detection (updates every 60 seconds, shows toast notifications)
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
#### Core Features
@@ -219,6 +220,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useGitSettings`: Manage Git credentials and repository settings
- `useSessionManager`: Access session management for AI chat sessions
- `useGitStatus`: Real-time Git repository status monitoring
- `useGitFetch`: Automatic remote fetch with change detection and toast notifications
- `useProjects`: Project management and CRUD operations
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
- `useTheme`: Theme management
-1
View File
@@ -34,7 +34,6 @@ Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The p
Shakespeare is available on the following URLs:
- [shakespeare.diy](https://shakespeare.diy)
- [shakespeare.soapbox.dev](https://shakespeare.soapbox.dev)
- [shakespeare-diy.github.io](https://shakespeare-diy.github.io)
- [shakespeare-b0b9c8.gitlab.io](https://shakespeare-b0b9c8.gitlab.io)
+1 -1
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' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
<meta name="theme-color" content="#2b0037">
+712 -10
View File
File diff suppressed because it is too large. Load diff
+4 -1
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 && electron electron",
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
},
"dependencies": {
@@ -29,6 +29,7 @@
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^3.9.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.47.1",
"@nostrify/react": "^0.2.17",
@@ -81,6 +82,7 @@
"lucide-react": "^0.525.0",
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
@@ -118,6 +120,7 @@
"@testing-library/user-event": "^14.6.1",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/nunjucks": "^3.2.6",
"@types/path-browserify": "^1.0.3",
"@types/prismjs": "^1.26.5",
"@types/qrcode": "^1.5.5",
+2 -1
View File
@@ -1 +1,2 @@
/* /index.html 200
/assets/* /assets/:splat 200
/* /index.html 200
+35 -11
View File
@@ -28,6 +28,7 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { GlobalChatProvider } from '@/components/GlobalChatProvider';
import AppRouter from './AppRouter';
@@ -48,7 +49,7 @@ const queryClient = new QueryClient({
});
// Get OS-specific default paths for Electron
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string } {
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } {
if (!globalThis.electron) {
// Browser defaults - use virtual filesystem paths
return {
@@ -56,6 +57,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
fsPathConfig: "/config",
fsPathTmp: "/tmp",
fsPathPlugins: "/plugins",
fsPathTemplates: "/templates",
};
}
@@ -70,6 +72,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
fsPathConfig: "~/AppData/Local/shakespeare",
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
fsPathTemplates: "~/AppData/Local/shakespeare/templates",
};
} else if (platform.includes('mac')) {
// macOS
@@ -78,6 +81,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
fsPathConfig: "~/Library/Application Support/shakespeare",
fsPathTmp: "/tmp/shakespeare",
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
fsPathTemplates: "~/Library/Application Support/shakespeare/templates",
};
} else {
// Linux and other Unix-like systems
@@ -86,6 +90,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
fsPathConfig: "~/.config/shakespeare",
fsPathTmp: "/tmp/shakespeare",
fsPathPlugins: "~/.config/shakespeare/plugins",
fsPathTemplates: "~/.config/shakespeare/templates",
};
}
}
@@ -102,7 +107,23 @@ const defaultConfig: AppConfig = {
],
updatedAt: 0,
},
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
templates: [
{
name: "MKStack",
description: "Build Nostr clients with React. This is the default template that you should choose in the majority of cases. It ships with complete Nostr integration out of the box, enabling a variety of use-cases from social media to blogging to AI-powered apps. If you're not sure which template to choose, choose this one.",
url: "https://gitlab.com/soapbox-pub/mkstack.git",
},
{
name: "Nutstack",
description: "This is a variant of MKStack extended to support Cashu integration. Choose this template only if the user has indicated they require Cashu integration.",
url: "https://gitlab.com/lemonknowsall/nutstack.git",
},
{
name: "Luvstack",
description: "Barebones React template. Choose this to build mockups or demo sites that don't require Nostr functionality. Only choose this if the user has indicated they want to create a demo or mockup site, as it cannot support any sort of backend functionality or remote storage. It might also work for simple PWAs.",
url: "https://gitlab.com/soapbox-pub/luvstack.git",
}
],
esmUrl: "https://esm.sh",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
@@ -114,6 +135,7 @@ const defaultConfig: AppConfig = {
fsPathConfig: electronPaths.fsPathConfig,
fsPathTmp: electronPaths.fsPathTmp,
fsPathPlugins: electronPaths.fsPathPlugins,
fsPathTemplates: electronPaths.fsPathTemplates,
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
sentryEnabled: true,
};
@@ -156,15 +178,17 @@ export function App() {
<GitSettingsProvider>
<DeploySettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
<GlobalChatProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</GlobalChatProvider>
</SessionManagerProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
+5
View File
@@ -2,6 +2,8 @@ import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import { URLFragmentHandler } from "./components/URLFragmentHandler";
import { FloatingChatButton } from "./components/FloatingChatButton";
import { GlobalChatPane } from "./components/GlobalChatPane";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
@@ -56,6 +58,9 @@ export function AppRouter() {
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
{/* Global floating chat - available on all pages */}
<FloatingChatButton />
<GlobalChatPane />
</Router>
);
}
+80 -7
View File
@@ -7,6 +7,8 @@ import { UserMessage } from '@/components/UserMessage';
import OpenAI from 'openai';
import { useTheme } from '@/hooks/useTheme';
import { isEmptyMessage } from '@/lib/isEmptyMessage';
import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
import * as DialogPrimitive from '@radix-ui/react-dialog';
// Type guard to check if message has reasoning content
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
@@ -26,6 +28,7 @@ export const AIMessageItem = memo(({
}: AIMessageItemProps) => {
const [isToolExpanded, setIsToolExpanded] = useState(false);
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
const { displayTheme } = useTheme();
// Get content to display
@@ -295,20 +298,90 @@ export const AIMessageItem = memo(({
// Regular rendering for non-tool messages
if (message.role === 'user') {
// User messages: right-aligned bubble without avatar/name
// Extract text and image parts from message content
const contentArray = Array.isArray(message.content) ? message.content : null;
const textParts = contentArray
? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
: [];
const userContent = typeof message.content === 'string'
? message.content
: Array.isArray(message.content)
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
: textParts.length > 0
? textParts.map(part => part.text).join('\n')
: '';
// Extract image URLs from content array
const imageUrls = contentArray
? contentArray
.filter(part => part.type === 'image_url')
.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url)
: [];
return (
<div className="flex justify-end py-6">
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
<div className="text-sm break-words">
<UserMessage content={userContent} />
<>
<div className="flex justify-end py-6">
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
<div className="text-sm break-words space-y-2">
{/* Render text content and attachments first */}
{userContent && <UserMessage content={userContent} />}
{/* Render images after text and attachments */}
{imageUrls.length > 0 && (
<div className="space-y-2">
{imageUrls.map((url, index) => (
<div
key={index}
className="rounded-lg overflow-hidden border border-border cursor-pointer hover:opacity-90 transition-opacity"
onClick={() => setExpandedImageUrl(url)}
>
<img
src={url}
alt={`User uploaded image ${index + 1}`}
className="max-w-full h-auto max-h-96 object-contain"
loading="lazy"
onError={(e) => {
// Fallback if image fails to load
const target = e.target as HTMLImageElement;
target.style.display = 'none';
const fallback = document.createElement('div');
fallback.className = 'p-2 text-xs text-muted-foreground bg-muted rounded';
fallback.textContent = `Image failed to load: ${url}`;
target.parentElement?.appendChild(fallback);
}}
/>
</div>
))}
</div>
)}
</div>
</div>
</div>
</div>
{/* Image expansion dialog */}
<Dialog open={!!expandedImageUrl} onOpenChange={(open) => !open && setExpandedImageUrl(null)}>
<DialogPortal>
<DialogOverlay className="bg-black/95" />
<DialogPrimitive.Content
className={cn(
"fixed left-[50%] top-[50%] z-50 max-w-[95vw] max-h-[95vh] translate-x-[-50%] translate-y-[-50%] p-0 bg-transparent border-0 shadow-none",
"data-[state=open]:animate-in data-[state=closed]:animate-out",
"data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
)}
onPointerDownOutside={() => setExpandedImageUrl(null)}
onEscapeKeyDown={() => setExpandedImageUrl(null)}
>
{expandedImageUrl && (
<div className="relative flex items-center justify-center">
<img
src={expandedImageUrl}
alt="Expanded image"
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
/>
</div>
)}
</DialogPrimitive.Content>
</DialogPortal>
</Dialog>
</>
);
}
@@ -125,6 +125,7 @@ describe('AISettingsProvider', () => {
providers: [
{
id: 'openrouter',
name: 'OpenRouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'test-key'
}
@@ -173,6 +174,7 @@ describe('AISettingsProvider', () => {
providers: [
{
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key'
}
+25 -1
View File
@@ -1,6 +1,6 @@
import { useQueryClient } from '@tanstack/react-query';
import { ReactNode, useState, useEffect } from 'react';
import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext';
import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, type AISettingsContextType } from '@/contexts/AISettingsContext';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readAISettings, writeAISettings } from '@/lib/configUtils';
@@ -12,6 +12,7 @@ interface AISettingsProviderProps {
const DEFAULT_SETTINGS: AISettings = {
providers: [],
recentlyUsedModels: [],
mcpServers: {},
};
export function AISettingsProvider({ children }: AISettingsProviderProps) {
@@ -128,6 +129,27 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
});
};
const setMCPServer = (name: string, server: MCPServer) => {
setSettings(prev => ({
...prev,
mcpServers: {
...(prev.mcpServers || {}),
[name]: server,
},
}));
};
const removeMCPServer = (name: string) => {
setSettings(prev => {
const newMCPServers = { ...(prev.mcpServers || {}) };
delete newMCPServers[name];
return {
...prev,
mcpServers: newMCPServers,
};
});
};
const isConfigured = settings.providers.length > 0;
const contextValue: AISettingsContextType = {
@@ -137,6 +159,8 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
removeProvider,
setProviders,
addRecentlyUsedModel,
setMCPServer,
removeMCPServer,
isConfigured,
};
+10 -1
View File
@@ -5,7 +5,7 @@ import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { useAICredits } from '@/hooks/useAICredits';
import { getShakespeareProvider } from '@/lib/aiProviderPresets';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
interface Act1DialogProps {
open: boolean;
@@ -14,6 +14,15 @@ interface Act1DialogProps {
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
// Helper function to get the Shakespeare provider preset
function getShakespeareProvider(): PresetProvider {
const shakespeare = AI_PROVIDER_PRESETS.find(preset => preset.id === "shakespeare");
if (!shakespeare) {
throw new Error("Shakespeare provider preset not found");
}
return shakespeare;
}
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
const [step, setStep] = useState<DialogStep>('welcome');
const { data: creditsData } = useAICredits(getShakespeareProvider());
@@ -8,6 +8,7 @@ import type { AIProvider } from '@/contexts/AISettingsContext';
describe('AddProviderDialog', () => {
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'sk-test-key-123',
};
@@ -92,6 +93,7 @@ describe('AddProviderDialog', () => {
// Use a provider that exists in presets
const openrouterProvider: AIProvider = {
id: 'openrouter',
name: 'OpenRouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'sk-test-123',
};
@@ -114,6 +116,7 @@ describe('AddProviderDialog', () => {
const onOpenChange = vi.fn();
const customProvider: AIProvider = {
id: 'my-custom-provider',
name: 'My Custom Provider',
baseURL: 'https://api.custom.com/v1',
};
+6 -1
View File
@@ -5,6 +5,7 @@ import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { useAISettings } from '@/hooks/useAISettings';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import type { AIProvider } from '@/contexts/AISettingsContext';
interface AddProviderDialogProps {
@@ -156,7 +157,11 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
// New provider
<div className="space-y-6">
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
<Sparkles className="h-8 w-8 text-primary" />
<ExternalFavicon
url={provider.baseURL}
size={32}
fallback={<Sparkles className="h-8 w-8 text-primary" />}
/>
</div>
<div className="text-center space-y-2">
<h2 className="text-2xl font-bold">{providerName}</h2>
+2 -2
View File
@@ -99,7 +99,7 @@ export function AppLayout({
onClick={() => setIsSidebarVisible(false)}
/>
{/* Sidebar - positioned above the backdrop */}
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={(project) => {
@@ -123,7 +123,7 @@ export function AppLayout({
<div className="min-h-screen flex bg-background">
{/* Fixed Sidebar - show if showSidebar is true and sidebar is visible */}
{showSidebar && isSidebarVisible && (
<div className="w-80 border-r bg-sidebar transition-all duration-300">
<div className="w-72 border-r bg-sidebar transition-all duration-300">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={handleProjectSelect}
+11 -1
View File
@@ -22,11 +22,18 @@ const RelayMetadataSchema = z.object({
updatedAt: z.number(),
}) satisfies z.ZodType<RelayMetadata>;
// Zod schema for ProjectTemplate
const ProjectTemplateSchema = z.object({
name: z.string().min(1),
description: z.string().min(1),
url: z.string().url(),
});
// Zod schema for AppConfig validation
const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayMetadata: RelayMetadataSchema,
projectTemplate: z.string().url(),
templates: z.array(ProjectTemplateSchema),
esmUrl: z.string().url(),
corsProxy: z.string().url(),
faviconUrl: z.string().url(),
@@ -39,6 +46,7 @@ const AppConfigSchema = z.object({
fsPathConfig: z.string().min(1),
fsPathTmp: z.string().min(1),
fsPathPlugins: z.string().min(1),
fsPathTemplates: z.string().min(1),
sentryDsn: z.string(),
sentryEnabled: z.boolean(),
}) satisfies z.ZodType<AppConfig>;
@@ -76,9 +84,11 @@ export function AppProvider(props: AppProviderProps) {
config.fsPathProjects = expandPath(config.fsPathProjects);
config.fsPathTmp = expandPath(config.fsPathTmp);
config.fsPathPlugins = expandPath(config.fsPathPlugins);
config.fsPathTemplates = expandPath(config.fsPathTemplates);
const appContextValue: AppContextType = {
config,
defaultConfig,
updateConfig,
};
+1
View File
@@ -17,6 +17,7 @@ global.fetch = vi.fn();
const mockProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
+1
View File
@@ -9,6 +9,7 @@ global.fetch = vi.fn();
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
+148 -35
View File
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import QRCode from 'qrcode';
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft, Gift, Plus, History, DollarSign, Printer, Download } from 'lucide-react';
@@ -85,17 +85,33 @@ const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
interface LightningPaymentProps {
invoice: string;
amount: number;
paymentId: string;
provider: AIProvider;
onClose: () => void;
onPaymentCompleted: () => void;
}
function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPaymentCompleted }: LightningPaymentProps) {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { config } = useAppContext();
const queryClient = useQueryClient();
const [qrDataUrl, setQrDataUrl] = useState<string>('');
const [isWebLNAvailable, setIsWebLNAvailable] = useState(false);
const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false);
const [showCopiedTooltip, setShowCopiedTooltip] = useState(false);
const [paymentCompleted, setPaymentCompleted] = useState(false);
const { toast } = useToast();
const formatCurrency = useCallback((amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
}, []);
useEffect(() => {
// Generate QR code
QRCode.toDataURL(invoice, {
@@ -113,6 +129,98 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window);
}, [invoice]);
// Poll payment status
useEffect(() => {
// Don't poll if payment already completed
if (paymentCompleted) return;
let intervalId: NodeJS.Timeout | null = null;
const pollPaymentStatus = async () => {
// Double-check in case state updated during async operation
if (paymentCompleted) return;
try {
const ai = createAIClient(provider, user, config.corsProxy);
const payment = await ai.get(`/credits/payments/${paymentId}`) as Payment;
if (payment.status === 'completed') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
// Update credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Update payments list
queryClient.invalidateQueries({
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Show toast
toast({
title: t('paymentCompleted'),
description: t('creditsAddedToAccount', { amount: formatCurrency(payment.amount) }),
});
// Close dialog immediately
onPaymentCompleted();
} else if (payment.status === 'failed') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
toast({
title: t('paymentFailed'),
description: t('paymentFailed'),
variant: 'destructive',
});
} else if (payment.status === 'expired') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
toast({
title: t('paymentExpired'),
description: t('paymentExpiredMessage'),
variant: 'destructive',
});
}
} catch (error) {
console.error('Failed to poll payment status:', error);
}
};
// Poll immediately on mount
pollPaymentStatus();
// Then poll every 3 seconds
intervalId = setInterval(pollPaymentStatus, 3000);
return () => {
if (intervalId) {
clearInterval(intervalId);
}
};
}, [paymentId, provider, user, config.corsProxy, queryClient, toast, t, onPaymentCompleted, formatCurrency, paymentCompleted]);
const handleWebLNPay = async () => {
if (!window.webln) return;
@@ -145,15 +253,6 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
setTimeout(() => setShowCopiedTooltip(false), 2000);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
return (
<div className="space-y-4">
<div className="text-center">
@@ -223,6 +322,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
const [amount, setAmount] = useState<number>(10);
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
const [lightningPaymentId, setLightningPaymentId] = useState<string | null>(null);
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
const [giftcardAmount, setGiftcardAmount] = useState<number>(10);
const [giftcardQuantity, setGiftcardQuantity] = useState<number>(1);
@@ -301,6 +401,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
} else if (payment.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(payment.url);
setLightningPaymentId(payment.id);
}
// Refresh payments list
@@ -486,6 +587,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
} else if (paymentPreview.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(paymentPreview.url);
setLightningPaymentId(paymentPreview.id);
}
// Refresh payments list
@@ -882,27 +984,37 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</DialogHeader>
{/* Lightning Payment Interface */}
{lightningInvoice ? (
{lightningInvoice && lightningPaymentId ? (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<LightningPayment
invoice={lightningInvoice}
amount={amount}
onClose={() => setLightningInvoice(null)}
paymentId={lightningPaymentId}
provider={provider}
onClose={() => {
setLightningInvoice(null);
setLightningPaymentId(null);
}}
onPaymentCompleted={() => {
// Close the lightning payment view immediately
setLightningInvoice(null);
setLightningPaymentId(null);
}}
/>
</div>
) : (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<Accordion type="multiple" defaultValue={["add"]} className="w-full">
<Accordion type="multiple" defaultValue={["add"]} className="w-full space-y-2">
{/* Buy Credits Accordion */}
<AccordionItem value="add">
<AccordionTrigger className="hover:no-underline">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<DollarSign className="h-4 w-4" />
<DollarSign className="h-4 w-4 text-muted-foreground" />
{t('buyCredits')}
</div>
</AccordionTrigger>
<AccordionContent>
<div className="space-y-3 pt-2">
<AccordionContent className="px-4">
<div className="space-y-3 pt-2 pb-3">
<div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">{t('amountUSD')}</Label>
<div className="space-y-3">
@@ -986,14 +1098,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Transaction History Accordion */}
<AccordionItem value="history">
<AccordionTrigger className="hover:no-underline">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<History className="h-4 w-4" />
<History className="h-4 w-4 text-muted-foreground" />
{t('recentTransactions')}
</div>
</AccordionTrigger>
<AccordionContent>
<div className="pt-2">
<AccordionContent className="px-4">
<div className="pt-2 pb-3">
{isLoadingPayments ? (
<div className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
@@ -1054,6 +1166,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
setLightningPaymentId(payment.id);
} else {
window.open(payment.url, '_blank');
}
@@ -1077,14 +1190,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Redeem Gift Card Accordion */}
<AccordionItem value="redeem">
<AccordionTrigger className="hover:no-underline">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<Plus className="h-4 w-4 text-muted-foreground" />
{t('redeemGiftCard')}
</div>
</AccordionTrigger>
<AccordionContent>
<div className="space-y-3 pt-2">
<AccordionContent className="px-4">
<div className="space-y-3 pt-2 pb-3">
<div className="flex gap-2">
<Input
id="redeem-code"
@@ -1109,14 +1222,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Create Gift Card Accordion */}
<AccordionItem value="create">
<AccordionTrigger className="hover:no-underline">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<Gift className="h-4 w-4" />
<Gift className="h-4 w-4 text-muted-foreground" />
{t('createGiftCard')}
</div>
</AccordionTrigger>
<AccordionContent>
<div className="space-y-3 pt-2">
<AccordionContent className="px-4">
<div className="space-y-3 pt-2 pb-3">
<div className="grid grid-cols-2 gap-2">
<div className="space-y-2">
<Label htmlFor="giftcard-amount" className="text-xs text-muted-foreground">{t('amountUSD')}</Label>
@@ -1172,15 +1285,15 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</AccordionItem>
{/* Your Gift Cards Accordion */}
<AccordionItem value="list" className="border-b-0">
<AccordionTrigger className="hover:no-underline">
<AccordionItem value="list">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
<CreditCard className="h-4 w-4 text-muted-foreground" />
{t('yourGiftCards')}
</div>
</AccordionTrigger>
<AccordionContent className="pb-0">
<div className="pt-2 space-y-3">
<AccordionContent className="px-4">
<div className="pt-2 pb-3 space-y-3">
{giftcards && giftcards.filter(gc => !gc.redeemed).length > 0 && (
<div className="grid grid-cols-2 gap-2">
<Button
+7
View File
@@ -124,6 +124,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
const [isDeploying, setIsDeploying] = useState(false);
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
const [error, setError] = useState<string | null>(null);
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
// Provider-specific form data
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
@@ -294,6 +295,10 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setShakespeareForm({ subdomain });
}, []);
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
setIsShakespeareFormValid(isValid);
}, []);
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
@@ -317,6 +322,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
host={shakespeareProvider.host}
projectId={projectId}
onSubdomainChange={handleShakespeareSubdomainChange}
onValidationChange={handleShakespeareValidationChange}
/>
);
}
@@ -495,6 +501,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
!selectedProvider ||
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
}
+21 -6
View File
@@ -1,6 +1,7 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
import { ReactNode } from 'react';
import { cn } from '@/lib/utils';
import { ReactNode, useMemo } from 'react';
interface ExternalFaviconProps {
/** The URL to fetch the favicon for */
@@ -25,14 +26,28 @@ export function ExternalFavicon({
}: ExternalFaviconProps) {
const { config } = useAppContext();
// Normalize the URL to ensure it has a protocol
const normalizedUrl = normalizeUrl(url);
// Generate the favicon URL using the configured template
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
const faviconSrc = useMemo(() => {
try {
// Normalize the URL to ensure it has a protocol
const normalizedUrl = normalizeUrl(url);
return faviconUrl(config.faviconUrl, normalizedUrl);
} catch {
return;
}
}, [url, config.faviconUrl]);
// If faviconSrc is not available, render the fallback directly
if (!faviconSrc) {
return (
<span className={cn('inline-flex items-center justify-center', className)}>
<span>{fallback}</span>
</span>
)
}
return (
<span className={`inline-flex items-center justify-center ${className}`}>
<span className={cn('inline-flex items-center justify-center', className)}>
<img
src={faviconSrc}
alt=""
+36
View File
@@ -0,0 +1,36 @@
import { MessageCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useGlobalChat } from '@/hooks/useGlobalChat';
import { useAppContext } from '@/hooks/useAppContext';
import { cn } from '@/lib/utils';
export function FloatingChatButton() {
const { isOpen, setIsOpen, hasUnread } = useGlobalChat();
const { config } = useAppContext();
// Don't render if disabled in settings
if (config.globalChatEnabled === false) {
return null;
}
return (
<Button
onClick={() => setIsOpen(!isOpen)}
size="lg"
className={cn(
'fixed bottom-6 right-6 z-40 h-14 w-14 rounded-full shadow-lg',
'bg-primary hover:bg-primary/90 text-primary-foreground',
'transition-all duration-200 hover:scale-105',
'flex items-center justify-center p-0',
isOpen && 'ring-2 ring-ring ring-offset-2'
)}
aria-label={isOpen ? 'Close chat' : 'Open chat'}
>
<MessageCircle className="h-6 w-6" />
{/* Unread indicator - small dot when there are unread messages */}
{!isOpen && hasUnread && (
<span className="absolute top-0 right-0 h-3 w-3 rounded-full bg-destructive ring-2 ring-background" />
)}
</Button>
);
}
+1
View File
@@ -164,6 +164,7 @@ export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: Gift
const providerConfig = {
id: matchingPreset.id,
name: matchingPreset.name,
baseURL: matchingPreset.baseURL,
nostr: matchingPreset.nostr || undefined,
};
+54 -2
View File
@@ -25,6 +25,7 @@ const baseGitStatus = {
},
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
vi.mock('@/hooks/useGitStatus', () => ({
@@ -82,7 +83,16 @@ describe('GitDialog', () => {
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows sync status', () => {
it('shows sync status when branch is published', () => {
// Mock git status with published branch
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -133,7 +143,17 @@ describe('GitDialog', () => {
expect(pushButton.closest('button')).not.toBeDisabled();
});
it('disables push button when no commits ahead', () => {
it('disables push button when no commits ahead and branch is published', () => {
// Mock git status with published branch and no commits ahead
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 0,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -147,6 +167,38 @@ describe('GitDialog', () => {
expect(pushButton.closest('button')).toBeDisabled();
});
it('enables push and disables pull when branch is not published', () => {
// Mock git status with unpublished branch (has commits but no remote branch)
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 0,
remoteBranchExists: false,
totalCommits: 5,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Sync Status')).toBeInTheDocument();
expect(screen.getByText('Branch not published')).toBeInTheDocument();
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
expect(pushButton.closest('button')).not.toBeDisabled();
const pullButton = screen.getByText('Pull');
expect(pullButton).toBeInTheDocument();
expect(pullButton.closest('button')).toBeDisabled();
});
it('does not show credentials warning when credentials are configured', () => {
render(
<TestApp>
+159 -66
View File
@@ -47,6 +47,7 @@ import {
GitPullRequest,
ExternalLink,
Copy,
RefreshCw,
} from 'lucide-react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGitSettings } from '@/hooks/useGitSettings';
@@ -56,6 +57,7 @@ import { useToast } from '@/hooks/useToast';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react';
import { usePullRequests } from '@/hooks/usePullRequests';
import { useGitFetch } from '@/hooks/useGitFetch';
import { cn } from '@/lib/utils';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { nip19 } from 'nostr-tools';
@@ -63,6 +65,22 @@ import { GitManagementDialog } from '@/components/git/GitManagementDialog';
import { MergeDialog } from '@/components/git/MergeDialog';
import { PullRequestDialog } from '@/components/git/PullRequestDialog';
import { AnnounceRepositoryDialog, type AnnounceRepositoryResult } from '@/components/git/AnnounceRepositoryDialog';
import { formatRelativeTime } from '@/lib/utils';
// Helper function to format fetch timestamp with special "fetched" prefix
function formatFetchTime(date: Date | number): string {
const timestamp = typeof date === 'number' ? date : date.getTime();
const now = Date.now();
const diffMs = now - timestamp;
// Less than 20 seconds - use special "fetched just now" message
if (diffMs < 20 * 1000) {
return 'fetched just now';
}
// Otherwise use the standard relative time formatter
return formatRelativeTime(timestamp);
}
interface GitDialogProps {
projectId: string;
@@ -89,6 +107,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
const [isCreatingBranch, setIsCreatingBranch] = useState(false);
const [newBranchName, setNewBranchName] = useState('');
const [isCreateBranchDialogOpen, setIsCreateBranchDialogOpen] = useState(false);
const [, setUpdateTrigger] = useState(0);
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
const { settings } = useGitSettings();
@@ -98,9 +117,19 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { data: pullRequests, isLoading: isLoadingPRs } = usePullRequests(originUrl);
const { data: gitFetchData, isFetching: isFetchingRemote, refetch: refetchRemote } = useGitFetch(projectId);
const projectPath = `${projectsPath}/${projectId}`;
// Update the "last fetched" timestamp display every 10 seconds
useEffect(() => {
const interval = setInterval(() => {
setUpdateTrigger(prev => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
// Initialize origin URL from git status and load nostr.repo config
useEffect(() => {
const loadGitConfig = async () => {
@@ -153,7 +182,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
await git.checkout({
dir: projectPath,
ref: branchName,
force: true,
});
toast({
@@ -214,13 +242,23 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
object: currentRef,
});
toast({
title: 'Branch created',
description: `Created branch "${newBranchName}"`,
// Automatically check out the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName.trim(),
force: true,
});
// Close the dialog before showing the toast
setNewBranchName('');
setIsCreateBranchDialogOpen(false);
// Show success toast indicating the branch was created and checked out
toast({
title: 'Branch created and checked out',
description: `Switched to new branch "${newBranchName.trim()}"`,
});
await loadBranches();
await refetchGitStatus();
} catch (error) {
@@ -417,50 +455,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
throw new Error('Could not determine repository state. The repository might not have any commits or branches.');
}
// Get HEAD reference
let headRef: string | undefined;
try {
const currentBranch = await git.currentBranch({ dir: projectPath });
if (currentBranch) {
headRef = `ref: refs/heads/${currentBranch}`;
console.log(`HEAD points to: ${headRef}`);
} else {
// HEAD is detached, use the commit ID directly
const headValue = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
if (headValue) {
headRef = headValue;
console.log(`HEAD is detached at: ${headRef}`);
}
}
} catch (error) {
console.warn('Failed to resolve HEAD:', error);
}
// Create repo state event (NIP-34 kind 30618)
const stateEvent = {
kind: 30618,
content: '',
tags: [
['d', result.repoId],
...refTags,
...(headRef ? [['HEAD', headRef]] : []),
],
created_at: Math.floor(Date.now() / 1000),
};
console.log('Creating repository state event:', stateEvent);
// Sign and publish the state event
const signedStateEvent = await user.signer.signEvent(stateEvent);
// State events only go to the relays specified in the repo announcement
console.log('Publishing repository state to relays:', result.relays);
await nostr.event(signedStateEvent, { relays: result.relays });
console.log('Published repository state to Nostr relays');
console.log('Repository has refs:', refTags);
// Set origin remote to Nostr URL
// Format: nostr://<npub>/<repo-id>
@@ -493,13 +488,54 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
console.log('Set nostr.repo config to:', result.naddr);
toast({
title: 'Repository published to Nostr',
description: 'Waiting for GRASP servers to update...',
});
// Refresh git status to pick up the new remote
await refetchGitStatus();
// Automatically push to the newly configured Nostr remote
// Get the current branch fresh from git instead of using stale gitStatus
console.log('Starting automatic push to Nostr...');
try {
const currentBranch = await git.currentBranch({ dir: projectPath });
console.log('Current branch:', currentBranch);
if (!currentBranch) {
throw new Error('No current branch found');
}
toast({
title: 'Repository published to Nostr',
description: 'Pushing commits to ngit servers...',
});
console.log('Calling git.push with:', { dir: projectPath, remote: 'origin', ref: currentBranch });
await git.push({
dir: projectPath,
remote: 'origin',
ref: currentBranch,
signer: user.signer,
});
console.log('Push completed successfully');
toast({
title: 'Push successful',
description: 'Repository successfully pushed to Nostr',
});
// Refresh git status after push
await refetchGitStatus();
} catch (pushError) {
console.error('Push error:', pushError);
const pushErrorMessage = pushError instanceof Error ? pushError.message : 'Unknown error occurred';
toast({
title: 'Automatic push failed',
description: pushErrorMessage,
variant: 'destructive',
duration: Infinity,
});
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
toast({
@@ -532,7 +568,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
return;
}
if (gitStatus.ahead === 0) {
// Allow push if there are commits ahead OR if the remote branch doesn't exist (publishing new branch)
if (gitStatus.ahead === 0 && gitStatus.remoteBranchExists) {
toast({
title: "Nothing to push",
description: "No commits ahead of remote. Commit your changes first.",
@@ -541,6 +578,16 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
return;
}
// Ensure we have commits to push when publishing a new branch
if (!gitStatus.remoteBranchExists && gitStatus.totalCommits === 0) {
toast({
title: "Cannot publish branch",
description: "No commits to push. Commit your changes first.",
variant: "destructive",
});
return;
}
setIsPushing(true);
try {
@@ -554,11 +601,32 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
signer: user?.signer, // For signing if pushing to Nostr
});
// Set up upstream tracking if this is the first push for this branch
if (!gitStatus.remoteBranchExists) {
await git.setConfig({
dir: projectPath,
path: `branch.${gitStatus.currentBranch}.remote`,
value: remote.name,
});
await git.setConfig({
dir: projectPath,
path: `branch.${gitStatus.currentBranch}.merge`,
value: `refs/heads/${gitStatus.currentBranch}`,
});
}
toast({
title: "Push successful",
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
});
// Show different messages for publishing new branches vs pushing commits
if (gitStatus.remoteBranchExists) {
toast({
title: "Push successful",
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
});
} else {
toast({
title: "Branch published",
description: `New branch published to ${remote.name}/${gitStatus.currentBranch}`,
});
}
// Refresh git status after push
await refetchGitStatus();
@@ -654,8 +722,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
}
};
const getFileStatusIcon = (status: string) => {
switch (status) {
case 'added':
@@ -699,6 +765,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' };
}
// Check if remote branch doesn't exist
if (!gitStatus.remoteBranchExists && gitStatus.currentBranch) {
return { status: 'not-published', text: 'Branch not published', icon: AlertCircle, color: 'text-yellow-600' };
}
if (gitStatus.ahead > 0 && gitStatus.behind > 0) {
return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' };
}
@@ -1041,13 +1112,36 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<span className={cn("text-sm font-medium", syncStatus.color)}>
{syncStatus.text}
</span>
{/* Last Fetched Info - inline with sync status */}
{gitStatus.remotes.length > 0 && gitFetchData?.fetchedAt && (
<>
<span className="text-xs text-muted-foreground">
· {formatFetchTime(gitFetchData.fetchedAt)}
</span>
<Button
variant="ghost"
size="sm"
onClick={() => refetchRemote()}
disabled={isFetchingRemote}
className="h-5 w-5 p-0 -ml-1 hover:bg-transparent"
title="Refresh remote status"
>
{isFetchingRemote ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<RefreshCw className="h-3 w-3 hover:text-foreground transition-colors" />
)}
</Button>
</>
)}
</div>
{gitStatus.remotes.length > 0 && (
{originUrl.trim() && (
<div className="flex gap-2">
<Button
onClick={handlePull}
disabled={isPulling || isPushing || isPushingToNostr}
disabled={isPulling || isPushing || isPushingToNostr || !gitStatus.remoteBranchExists}
variant="outline"
size="sm"
className="flex-1"
@@ -1062,7 +1156,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<Button
onClick={handlePush}
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
disabled={isPushing || isPulling || isPushingToNostr || (gitStatus.ahead === 0 && gitStatus.remoteBranchExists)}
variant="outline"
size="sm"
className="flex-1"
@@ -1077,7 +1171,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
</div>
)}
{gitStatus.remotes.length === 0 && user && (
{!originUrl.trim() && user && (
<Button
onClick={handlePushToNostr}
disabled={isPushingToNostr || isPushing || isPulling}
@@ -1090,7 +1184,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
) : (
<Zap className="h-4 w-4 mr-2" />
)}
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
{isPushingToNostr ? 'Loading...' : 'Push to Nostr'}
</Button>
)}
@@ -1194,7 +1288,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
await git.checkout({
dir: projectPath,
ref: pr.sourceBranch,
force: true,
});
await refetchGitStatus();
toast({
+410
View File
@@ -0,0 +1,410 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { X, Minimize2, Trash2, Copy, Check, ChevronDown, ArrowUp, Square, Loader2 } from 'lucide-react';
import { Streamdown } from 'streamdown';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { ModelSelector } from '@/components/ModelSelector';
import { useGlobalChat } from '@/hooks/useGlobalChat';
import { useAppContext } from '@/hooks/useAppContext';
import { useAISettings } from '@/hooks/useAISettings';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';
import type { GlobalChatMessage } from '@/contexts/GlobalChatContext';
// Message component with copy functionality
function ChatMessage({ message }: { message: GlobalChatMessage }) {
const [copied, setCopied] = useState(false);
const { displayTheme } = useTheme();
const isUser = message.role === 'user';
const handleCopy = useCallback(async () => {
try {
await navigator.clipboard.writeText(message.content);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error('Failed to copy:', error);
}
}, [message.content]);
return (
<div
className={cn(
'group relative flex',
isUser ? 'justify-end' : 'justify-start'
)}
>
<div
className={cn(
'relative max-w-[85%] rounded-2xl px-4 py-2.5',
isUser
? 'bg-primary text-primary-foreground rounded-br-md'
: 'bg-muted rounded-bl-md'
)}
>
{isUser ? (
<p className="text-sm whitespace-pre-wrap break-words">{message.content}</p>
) : (
<div className="text-sm break-words">
<Streamdown
className="size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 prose prose-sm dark:prose-invert max-w-none"
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{message.content || '...'}
</Streamdown>
</div>
)}
{/* Copy button - shows on hover */}
<button
onClick={handleCopy}
className={cn(
'absolute -bottom-1 opacity-0 group-hover:opacity-100 transition-opacity',
'p-1 rounded bg-background/80 hover:bg-background shadow-sm border',
isUser ? 'right-0 translate-y-full' : 'left-0 translate-y-full'
)}
aria-label="Copy message"
>
{copied ? (
<Check className="h-3 w-3 text-green-500" />
) : (
<Copy className="h-3 w-3 text-muted-foreground" />
)}
</button>
</div>
</div>
);
}
export function GlobalChatPane() {
const { t } = useTranslation();
const {
messages,
isOpen,
isLoading,
sendMessage,
stopGeneration,
clearMessages,
setIsOpen,
providerModel,
setProviderModel,
} = useGlobalChat();
const { config } = useAppContext();
const { settings } = useAISettings();
const isMobile = useIsMobile();
const [input, setInput] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Initialize provider model from settings if not set
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
setProviderModel(settings.recentlyUsedModels[0]);
}
}, [providerModel, settings.recentlyUsedModels, setProviderModel]);
// Auto-scroll to bottom when new messages arrive
useEffect(() => {
if (scrollAreaRef.current) {
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;
if (isNearBottom || messages.length <= 1) {
container.scrollTop = container.scrollHeight;
}
}
}, [messages]);
// Handle scroll to show/hide scroll-to-bottom button
const handleScroll = useCallback(() => {
if (scrollAreaRef.current) {
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;
setShowScrollToBottom(!isNearBottom && messages.length > 0);
}
}, [messages.length]);
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, []);
const handleSend = useCallback(async () => {
if (!input.trim() || isLoading || !providerModel) return;
const messageContent = input.trim();
setInput('');
await sendMessage(messageContent, providerModel);
// Focus back on textarea
textareaRef.current?.focus();
}, [input, isLoading, providerModel, sendMessage]);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !isMobile) {
e.preventDefault();
handleSend();
}
}, [handleSend, isMobile]);
// Don't render if disabled or not open
if (config.globalChatEnabled === false || !isOpen) {
return null;
}
const hasProviders = settings.providers.length > 0;
// Mobile: Full screen drawer from bottom
if (isMobile) {
return (
<div className="fixed inset-0 z-50 bg-background flex flex-col animate-in slide-in-from-bottom duration-300">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<h2 className="font-semibold text-lg">{t('globalChat')}</h2>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={clearMessages}
>
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('clearChat')}</TooltipContent>
</Tooltip>
)}
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => setIsOpen(false)}
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Messages */}
<div
ref={scrollAreaRef}
className="flex-1 overflow-y-auto p-4 space-y-4"
onScroll={handleScroll}
>
{messages.length === 0 ? (
<div className="flex-1 flex items-center justify-center text-center text-muted-foreground px-8 py-12">
<div>
<p className="text-lg font-medium mb-2">{t('globalChatWelcome')}</p>
<p className="text-sm">{t('globalChatDescription')}</p>
</div>
</div>
) : (
messages.map((message) => (
<ChatMessage key={message.id} message={message} />
))
)}
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
<div className="flex justify-start">
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</div>
)}
</div>
{/* Scroll to bottom button */}
{showScrollToBottom && (
<Button
onClick={scrollToBottom}
size="sm"
variant="secondary"
className="absolute bottom-32 left-1/2 -translate-x-1/2 rounded-full shadow-lg"
>
<ChevronDown className="h-4 w-4" />
</Button>
)}
{/* Input */}
<div className="p-4 border-t bg-background space-y-3 pb-safe">
<div className="flex gap-2">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
className="flex-1"
disabled={isLoading}
placeholder={t('chooseModel')}
/>
</div>
<div className="flex gap-2 items-end">
<Textarea
ref={textareaRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
// Auto-resize
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
onKeyDown={handleKeyDown}
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
disabled={!hasProviders || isLoading}
className="resize-none min-h-[44px] max-h-32"
rows={1}
/>
{isLoading ? (
<Button onClick={stopGeneration} size="icon" variant="destructive" className="h-11 w-11 shrink-0">
<Square className="h-4 w-4" />
</Button>
) : (
<Button
onClick={handleSend}
size="icon"
disabled={!input.trim() || !providerModel || !hasProviders}
className="h-11 w-11 shrink-0"
>
<ArrowUp className="h-4 w-4" />
</Button>
)}
</div>
</div>
</div>
);
}
// Desktop: Floating panel
return (
<div className="fixed bottom-24 right-6 z-50 w-96 max-w-[calc(100vw-3rem)] bg-background border rounded-2xl shadow-2xl flex flex-col animate-in fade-in slide-in-from-bottom-4 duration-300">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b">
<h2 className="font-semibold">{t('globalChat')}</h2>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={clearMessages}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('clearChat')}</TooltipContent>
</Tooltip>
)}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => setIsOpen(false)}
>
<Minimize2 className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('minimizeChat')}</TooltipContent>
</Tooltip>
</div>
</div>
{/* Messages */}
<div
ref={scrollAreaRef}
className="flex-1 overflow-y-auto p-4 space-y-4 max-h-96 min-h-48"
onScroll={handleScroll}
>
{messages.length === 0 ? (
<div className="flex items-center justify-center text-center text-muted-foreground px-4 py-8">
<div>
<p className="font-medium mb-1">{t('globalChatWelcome')}</p>
<p className="text-xs">{t('globalChatDescription')}</p>
</div>
</div>
) : (
messages.map((message) => (
<ChatMessage key={message.id} message={message} />
))
)}
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
<div className="flex justify-start">
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</div>
)}
</div>
{/* Scroll to bottom button */}
{showScrollToBottom && (
<div className="absolute bottom-36 left-1/2 -translate-x-1/2">
<Button
onClick={scrollToBottom}
size="sm"
variant="secondary"
className="h-7 w-7 rounded-full shadow-lg p-0"
>
<ChevronDown className="h-3.5 w-3.5" />
</Button>
</div>
)}
{/* Input */}
<div className="p-3 border-t space-y-2">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
className="w-full"
disabled={isLoading}
placeholder={t('chooseModel')}
/>
<div className="flex gap-2 items-end">
<Textarea
ref={textareaRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
// Auto-resize
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 96) + 'px';
}}
onKeyDown={handleKeyDown}
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
disabled={!hasProviders || isLoading}
className="resize-none min-h-[40px] max-h-24 text-sm"
rows={1}
/>
{isLoading ? (
<Button onClick={stopGeneration} size="icon" variant="destructive" className="h-10 w-10 shrink-0">
<Square className="h-4 w-4" />
</Button>
) : (
<Button
onClick={handleSend}
size="icon"
disabled={!input.trim() || !providerModel || !hasProviders}
className="h-10 w-10 shrink-0"
>
<ArrowUp className="h-4 w-4" />
</Button>
)}
</div>
</div>
</div>
);
}
+211
View File
@@ -0,0 +1,211 @@
import { useState, useCallback, useRef, type ReactNode } from 'react';
import OpenAI from 'openai';
import { GlobalChatContext, type GlobalChatMessage } from '@/contexts/GlobalChatContext';
import { useAISettings } from '@/hooks/useAISettings';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { createAIClient } from '@/lib/ai-client';
// Maximum context size in characters (approximately 50k tokens worth)
// This leaves room for the system prompt and response
const MAX_CONTEXT_CHARS = 150000;
// Default system prompt for global chat
const DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT = `You are a helpful AI assistant. You're here to have a friendly conversation and help answer questions on any topic.
Keep your responses concise but informative. Be friendly and conversational.`;
interface GlobalChatProviderProps {
children: ReactNode;
}
export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
const [messages, setMessages] = useState<GlobalChatMessage[]>([]);
const [isOpen, setIsOpenInternal] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [hasUnread, setHasUnread] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null);
const isOpenRef = useRef(false);
// Separate model storage for global chat (independent from project chat)
const [globalChatModel, setGlobalChatModel] = useLocalStorage<string>('shakespeare-global-chat-model', '');
const { settings } = useAISettings();
const { config } = useAppContext();
const { user } = useCurrentUser();
// When opening the chat, mark messages as read
const setIsOpen = useCallback((open: boolean) => {
isOpenRef.current = open;
setIsOpenInternal(open);
if (open) {
setHasUnread(false);
}
}, []);
// Trim messages from the top when context gets too long
const trimMessages = useCallback((msgs: GlobalChatMessage[]): GlobalChatMessage[] => {
let totalChars = msgs.reduce((sum, msg) => sum + msg.content.length, 0);
if (totalChars <= MAX_CONTEXT_CHARS) {
return msgs;
}
// Remove messages from the beginning until we're under the limit
const trimmedMessages = [...msgs];
while (trimmedMessages.length > 1 && totalChars > MAX_CONTEXT_CHARS) {
const removed = trimmedMessages.shift();
if (removed) {
totalChars -= removed.content.length;
}
}
return trimmedMessages;
}, []);
const sendMessage = useCallback(async (content: string, providerModelString: string) => {
if (!content.trim() || isLoading) return;
// Parse provider and model
const { model: modelId, provider } = parseProviderModel(providerModelString, settings.providers);
if (!provider) {
console.error('Provider not found');
return;
}
// Create user message
const userMessage: GlobalChatMessage = {
id: crypto.randomUUID(),
role: 'user',
content: content.trim(),
timestamp: Date.now(),
};
// Add user message and trim if necessary
setMessages(prev => trimMessages([...prev, userMessage]));
setIsLoading(true);
// Create abort controller for this request
abortControllerRef.current = new AbortController();
try {
// Create AI client
const client = createAIClient(provider, config.corsProxy, user?.signer);
// Build messages for API
const systemPrompt = config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT;
const apiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
...messages.map(msg => ({
role: msg.role as 'user' | 'assistant',
content: msg.content,
})),
{ role: 'user', content: content.trim() },
];
// Create assistant message placeholder
const assistantMessage: GlobalChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: '',
timestamp: Date.now(),
};
setMessages(prev => [...prev, assistantMessage]);
// Stream the response
const stream = await client.chat.completions.create({
model: modelId,
messages: apiMessages,
stream: true,
}, {
signal: abortControllerRef.current.signal,
});
let fullContent = '';
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content || '';
fullContent += delta;
// Update the assistant message with streamed content
setMessages(prev => {
const updated = [...prev];
const lastMessage = updated[updated.length - 1];
if (lastMessage && lastMessage.role === 'assistant') {
lastMessage.content = fullContent;
}
return updated;
});
}
// Final trim after response is complete
setMessages(prev => trimMessages(prev));
// Mark as unread if chat is closed
if (!isOpenRef.current) {
setHasUnread(true);
}
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
// User stopped generation, keep partial response
return;
}
console.error('Global chat error:', error);
// Add error message
const errorMessage: GlobalChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}`,
timestamp: Date.now(),
};
setMessages(prev => {
// Remove empty assistant message if exists
const filtered = prev.filter(m => m.role !== 'assistant' || m.content.trim());
return [...filtered, errorMessage];
});
} finally {
setIsLoading(false);
abortControllerRef.current = null;
}
}, [config.corsProxy, config.globalChatSystemPrompt, isLoading, messages, settings.providers, trimMessages, user?.signer]);
const stopGeneration = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
setIsLoading(false);
}
}, []);
const clearMessages = useCallback(() => {
setMessages([]);
}, []);
return (
<GlobalChatContext.Provider
value={{
messages,
isOpen,
isLoading,
hasUnread,
providerModel: globalChatModel,
setProviderModel: setGlobalChatModel,
sendMessage,
stopGeneration,
clearMessages,
setIsOpen,
}}
>
{children}
</GlobalChatContext.Provider>
);
}
+1
View File
@@ -21,6 +21,7 @@ const { CreditsDialog } = await import('./CreditsDialog');
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
+338
View File
@@ -0,0 +1,338 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Server, Trash2, Check, Plus, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useAISettings } from '@/hooks/useAISettings';
import { useToast } from '@/hooks/useToast';
import { useMCPServerStatus } from '@/hooks/useMCPServerStatus';
import type { MCPServer } from '@/contexts/AISettingsContext';
import { cn } from '@/lib/utils';
function MCPConnectionStatus({ server }: { server: MCPServer }) {
const status = useMCPServerStatus(server);
return (
<div className="flex items-center gap-1.5 ml-auto mr-2">
<div
className={cn(
'h-2 w-2 rounded-full',
status === 'connected' && 'bg-green-500',
status === 'offline' && 'bg-red-500',
status === 'checking' && 'bg-yellow-500 animate-pulse'
)}
/>
<span className="text-xs text-muted-foreground capitalize">
{status}
</span>
</div>
);
}
interface HeadersEditorProps {
headers: Record<string, string> | undefined;
onChange: (headers: Record<string, string> | undefined) => void;
}
function HeadersEditor({ headers, onChange }: HeadersEditorProps) {
const { t } = useTranslation();
const [newHeaderName, setNewHeaderName] = useState('');
const [newHeaderValue, setNewHeaderValue] = useState('');
const headerEntries = Object.entries(headers || {});
const handleAddHeader = () => {
if (!newHeaderName.trim() || !newHeaderValue.trim()) return;
const updatedHeaders = {
...(headers || {}),
[newHeaderName.trim()]: newHeaderValue.trim(),
};
onChange(updatedHeaders);
setNewHeaderName('');
setNewHeaderValue('');
};
const handleRemoveHeader = (name: string) => {
const updatedHeaders = { ...(headers || {}) };
delete updatedHeaders[name];
// If no headers left, set to undefined
onChange(Object.keys(updatedHeaders).length > 0 ? updatedHeaders : undefined);
};
const handleUpdateHeader = (oldName: string, newName: string, newValue: string) => {
const updatedHeaders = { ...(headers || {}) };
delete updatedHeaders[oldName];
updatedHeaders[newName] = newValue;
onChange(updatedHeaders);
};
return (
<div className="space-y-3">
<Label>{t('mcpServerHeaders')}</Label>
<p className="text-xs text-muted-foreground">
{t('mcpServerHeadersDescription')}
</p>
{/* Existing Headers */}
{headerEntries.length > 0 && (
<div className="space-y-2">
{headerEntries.map(([name, value]) => (
<div key={name} className="flex gap-2">
<Input
value={name}
onChange={(e) => handleUpdateHeader(name, e.target.value, value)}
placeholder="Header name"
className="flex-1"
/>
<Input
value={value}
onChange={(e) => handleUpdateHeader(name, name, e.target.value)}
placeholder="Header value"
className="flex-1"
/>
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveHeader(name)}
className="shrink-0"
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
)}
{/* Add New Header */}
<div className="flex gap-2">
<Input
value={newHeaderName}
onChange={(e) => setNewHeaderName(e.target.value)}
placeholder="Header name (e.g., Authorization)"
className="flex-1"
/>
<Input
value={newHeaderValue}
onChange={(e) => setNewHeaderValue(e.target.value)}
placeholder="Header value"
className="flex-1"
/>
<Button
variant="outline"
size="icon"
onClick={handleAddHeader}
disabled={!newHeaderName.trim() || !newHeaderValue.trim()}
className="shrink-0"
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
);
}
export function MCPServersSection() {
const { t } = useTranslation();
const { settings, setMCPServer, removeMCPServer } = useAISettings();
const { toast } = useToast();
const [serverName, setServerName] = useState('');
const [serverUrl, setServerUrl] = useState('');
const [serverHeaders, setServerHeaders] = useState<Record<string, string> | undefined>(undefined);
const [serverType] = useState<'streamable-http'>('streamable-http'); // Only streamable-http is supported
const mcpServers = settings.mcpServers || {};
const serverEntries = Object.entries(mcpServers);
const handleAddServer = () => {
if (!serverName.trim() || !serverUrl.trim()) return;
if (mcpServers[serverName.trim()]) {
toast({
title: t('error'),
description: t('mcpServerAddFailed'),
variant: 'destructive',
});
return;
}
const newServer: MCPServer = {
type: serverType,
url: serverUrl.trim(),
headers: serverHeaders,
};
setMCPServer(serverName.trim(), newServer);
toast({
title: t('mcpServerAdded'),
description: t('mcpServerAddedDescription', { name: serverName.trim() }),
});
setServerName('');
setServerUrl('');
setServerHeaders(undefined);
};
const handleRemoveServer = (name: string) => {
removeMCPServer(name);
toast({
title: t('mcpServerDeleted'),
description: t('mcpServerDeletedDescription', { name }),
});
};
return (
<div className="space-y-4">
{/* MCP Servers Header */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<Server className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('mcpServers')}</h3>
</div>
<p className="text-sm text-muted-foreground">
{t('mcpServersDescription')}
</p>
</div>
{/* Configured MCP Servers List */}
{serverEntries.length > 0 && (
<div className="space-y-2">
{serverEntries.map(([name, server]) => (
<Accordion key={name} type="single" collapsible className="w-full">
<AccordionItem value={name} className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2 w-full mr-3">
<Server size={16} className="text-muted-foreground" />
<span className="font-medium">{name}</span>
<MCPConnectionStatus server={server} />
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`${name}-type`}>
{t('mcpServerType')} <span className="text-destructive">*</span>
</Label>
<Select value={server.type} disabled>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor={`${name}-url`}>
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id={`${name}-url`}
value={server.url}
onChange={(e) => setMCPServer(name, { ...server, url: e.target.value })}
placeholder="https://example.com/mcp"
/>
</div>
<HeadersEditor
headers={server.headers}
onChange={(headers) => setMCPServer(name, { ...server, headers })}
/>
<Button
variant="destructive"
size="sm"
onClick={() => handleRemoveServer(name)}
>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</Button>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
))}
</div>
)}
{/* Add New MCP Server */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-server">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<span className="text-sm font-medium">{t('addMcpServer')}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<p className="text-sm text-muted-foreground">
{t('mcpServerDescription')}
</p>
<div className="grid gap-2">
<Label htmlFor="new-server-name">
{t('mcpServerName')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-server-name"
placeholder="e.g., my-mcp-server"
value={serverName}
onChange={(e) => setServerName(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-type">
{t('mcpServerType')} <span className="text-destructive">*</span>
</Label>
<Select value={serverType} disabled>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Only Streamable HTTP transport is currently supported
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-url">
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-server-url"
placeholder="https://example.com/mcp"
value={serverUrl}
onChange={(e) => setServerUrl(e.target.value)}
/>
</div>
<HeadersEditor
headers={serverHeaders}
onChange={setServerHeaders}
/>
<Button
onClick={handleAddServer}
disabled={!serverName.trim() || !serverUrl.trim() || !!mcpServers[serverName.trim()]}
className="gap-2 w-full"
>
<Check className="h-4 w-4" />
{t('add')}
</Button>
{mcpServers[serverName.trim()] && (
<p className="text-sm text-destructive">
A server with this name already exists
</p>
)}
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
);
}
+47 -15
View File
@@ -42,14 +42,15 @@ describe('ModelSelector', () => {
vi.clearAllMocks();
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] },
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
mockUseProviderModels.mockReturnValue({
@@ -80,13 +81,22 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
settings: {
providers: [
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
],
recentlyUsedModels,
mcpServers: {},
},
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
@@ -102,7 +112,7 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider2')).toBeInTheDocument();
expect(screen.getByText('Provider 2')).toBeInTheDocument();
});
// Recently used section should NOT be visible
@@ -111,8 +121,8 @@ describe('ModelSelector', () => {
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 should still show with model3
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
// provider2 should still show with model3 (just the model ID, not the full ID)
expect(screen.getByText('model3')).toBeInTheDocument();
});
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
@@ -133,13 +143,23 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
settings: {
providers: [
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
{ id: 'provider3', name: 'Provider 3', baseURL: 'https://api.provider3.com' },
],
recentlyUsedModels,
mcpServers: {},
},
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
@@ -155,7 +175,7 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
expect(screen.getByText('Provider 1')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
@@ -182,13 +202,23 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
settings: {
providers: [
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
{ id: 'provider3', name: 'Provider 3', baseURL: 'https://api.provider3.com' },
],
recentlyUsedModels,
mcpServers: {},
},
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
@@ -204,7 +234,7 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider2')).toBeInTheDocument();
expect(screen.getByText('Provider 2')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
@@ -213,10 +243,10 @@ describe('ModelSelector', () => {
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 and provider3 should still show
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
expect(screen.getByText('provider2/model4')).toBeInTheDocument();
expect(screen.getByText('provider3/model5')).toBeInTheDocument();
// provider2 and provider3 should still show (just the model IDs, not full IDs)
expect(screen.getByText('model3')).toBeInTheDocument();
expect(screen.getByText('model4')).toBeInTheDocument();
expect(screen.getByText('model5')).toBeInTheDocument();
});
it('hides recently used section when no recently used models exist', async () => {
@@ -233,13 +263,15 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] }, // No recently used models
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, // No recently used models
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
+106 -31
View File
@@ -1,7 +1,7 @@
import { useState, useMemo, useEffect, memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert, Bot } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
@@ -12,6 +12,7 @@ import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useIsMobile } from '@/hooks/useIsMobile';
import { ModelPricing } from '@/components/ModelPricing';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { cn } from '@/lib/utils';
interface ModelSelectorProps {
@@ -72,6 +73,33 @@ export const ModelSelector = memo(function ModelSelector({
return groups;
}, [models, recentlyUsedSet]);
// Get provider display name and baseURL for a given provider ID
const getProviderInfo = useMemo(() => {
return (providerId: string) => {
const provider = settings.providers.find(p => p.id === providerId);
return {
displayName: provider ? provider.name : providerId,
baseURL: provider?.baseURL,
};
};
}, [settings.providers]);
// Get display info for the selected model
const selectedModelDisplay = useMemo(() => {
if (!value) return null;
const providerId = value.split('/')[0];
const modelId = value.split('/').slice(1).join('/') || value;
const providerInfo = getProviderInfo(providerId);
const modelData = models.find(m => m.fullId === value);
const displayName = modelData?.name || modelId;
return {
displayName,
baseURL: providerInfo.baseURL,
};
}, [value, getProviderInfo, models]);
// Determine if we should show the "Recently Used" section
const shouldShowRecentlyUsed = useMemo(() => {
// If no recently used models, don't show the section
@@ -278,13 +306,31 @@ export const ModelSelector = memo(function ModelSelector({
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-0.5 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0 max-w-[280px]"
"h-8 p-0 gap-1 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0 max-w-[280px]"
)}
disabled={disabled}
>
<span className="truncate">
{value || placeholder || defaultPlaceholder}
</span>
{selectedModelDisplay ? (
<>
{selectedModelDisplay.baseURL ? (
<ExternalFavicon
url={selectedModelDisplay.baseURL}
size={16}
fallback={<Bot size={16} />}
className="flex-shrink-0"
/>
) : (
<Bot size={16} className="flex-shrink-0" />
)}
<span className="truncate">
{selectedModelDisplay.displayName}
</span>
</>
) : (
<span className="truncate">
{placeholder || defaultPlaceholder}
</span>
)}
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
@@ -305,6 +351,11 @@ export const ModelSelector = memo(function ModelSelector({
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((modelId) => {
const modelData = models.find(m => m.fullId === modelId);
const providerId = modelId.split('/')[0];
const providerInfo = getProviderInfo(providerId);
const displayModelId = modelId.split('/').slice(1).join('/') || modelId;
const displayName = modelData?.name || displayModelId;
return (
<CommandItem
key={modelId}
@@ -318,7 +369,17 @@ export const ModelSelector = memo(function ModelSelector({
value === modelId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate flex-1">{modelId}</span>
{providerInfo.baseURL ? (
<ExternalFavicon
url={providerInfo.baseURL}
size={16}
fallback={<Bot size={16} />}
className="mr-2 flex-shrink-0"
/>
) : (
<Bot size={16} className="mr-2 flex-shrink-0" />
)}
<span className="truncate flex-1">{displayName}</span>
{modelData?.pricing && (
<ModelPricing pricing={modelData.pricing} className="ml-2" />
)}
@@ -367,32 +428,46 @@ export const ModelSelector = memo(function ModelSelector({
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
{!isLoading && Object.entries(modelsByProvider).map(([providerId, providerModels]) => {
const providerInfo = getProviderInfo(providerId);
return (
<div key={providerId}>
<CommandSeparator />
<CommandGroup heading={providerInfo.displayName}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
{providerInfo.baseURL ? (
<ExternalFavicon
url={providerInfo.baseURL}
size={16}
fallback={<Bot size={16} />}
className="mr-2 flex-shrink-0"
/>
) : (
<Bot size={16} className="mr-2 flex-shrink-0" />
)}
/>
<span className="truncate flex-1">{model.fullId}</span>
{model.pricing && (
<ModelPricing pricing={model.pricing} className="ml-2" />
)}
</CommandItem>
))}
</CommandGroup>
</div>
))}
<span className="truncate flex-1">{model.name || model.id}</span>
{model.pricing && (
<ModelPricing pricing={model.pricing} className="ml-2" />
)}
</CommandItem>
))}
</CommandGroup>
</div>
);
})}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
@@ -17,6 +17,7 @@ const mockUseAICredits = vi.mocked(useAICredits);
describe('OnboardingCreditsBadge', () => {
const mockProvider = {
id: 'shakespeare',
name: 'Shakespeare',
baseURL: 'https://ai.shakespeare.diy/v1',
nostr: true,
};
+8 -3
View File
@@ -23,6 +23,7 @@ import { ExternalFavicon } from '@/components/ExternalFavicon';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
import { cn } from '@/lib/utils';
import { LoginArea } from '@/components/auth/LoginArea';
import { AIProvider } from '@/contexts/AISettingsContext';
interface OnboardingDialogProps {
open: boolean;
@@ -57,10 +58,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
selectedProvider && selectedProvider.nostr && user
? {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr,
}
: { id: '', baseURL: '', nostr: undefined }
: { id: '', name: '', baseURL: '', nostr: undefined }
);
// Filter models to only show selected provider models
@@ -122,8 +124,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}
// Add selected provider to their config
const providerConfig = {
const providerConfig: AIProvider = {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
@@ -151,8 +154,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}
// Add selected provider to their config
const providerConfig = {
const providerConfig: AIProvider = {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
};
@@ -726,6 +730,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}}
provider={{
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
+27 -11
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { useRegisterSW } from 'virtual:pwa-register/react';
import { Sparkles } from 'lucide-react';
import { Sparkles, X } from 'lucide-react';
/**
* Component that prompts users to update when a new service worker is available
@@ -52,22 +52,38 @@ export function PWAUpdatePrompt() {
updateServiceWorker(true);
};
const handleDismiss = (e: React.MouseEvent) => {
e.stopPropagation();
setShowPrompt(false);
};
if (!showPrompt) {
return null;
}
return (
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 md:top-4 md:right-4 md:bottom-auto md:left-auto md:translate-x-0 z-50 animate-in slide-in-from-bottom-4 md:slide-in-from-top-4 duration-500 max-w-full">
<button
onClick={handleUpdate}
disabled={isUpdating}
className="group relative flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate"
>
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
</span>
</button>
<div className="relative group">
<button
onClick={handleUpdate}
disabled={isUpdating}
className={`relative flex items-center gap-2 px-4 py-2.5 ${!isUpdating ? 'pr-10' : ''} bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate`}
>
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
</span>
</button>
{!isUpdating && (
<button
onClick={handleDismiss}
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 rounded-full hover:bg-amber-200 dark:hover:bg-amber-800 transition-colors duration-200"
aria-label="Dismiss update notification"
>
<X className="h-4 w-4 text-amber-700 dark:text-amber-300" />
</button>
)}
</div>
</div>
);
}
+10 -28
View File
@@ -5,15 +5,14 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Separator } from '@/components/ui/separator';
import { usePlugins } from '@/hooks/usePlugins';
import { usePluginGitInfo } from '@/hooks/usePluginGitInfo';
import { useToast } from '@/hooks/useToast';
import { Alert, AlertDescription } from '@/components/ui/alert';
export function PluginsSection() {
const { t } = useTranslation();
const { toast } = useToast();
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin, getPluginGitInfo } = usePlugins();
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin } = usePlugins();
const [gitUrl, setGitUrl] = useState('');
const handleAddPlugin = async () => {
@@ -78,9 +77,6 @@ export function PluginsSection() {
return (
<div className="space-y-4">
{/* Divider */}
<Separator className="my-6" />
{/* Plugins Header */}
<div className="space-y-2">
<div className="flex items-center gap-2">
@@ -93,7 +89,7 @@ export function PluginsSection() {
</div>
{/* Configured Plugins List */}
{plugins.length > 0 ? (
{plugins.length > 0 && (
<div className="space-y-2">
{plugins.map((pluginName) => {
const pluginSkills = skillsByPlugin[pluginName] || [];
@@ -108,21 +104,14 @@ export function PluginsSection() {
isDeleting={isDeleting}
onSync={handleSyncPlugin}
onDelete={handleDeletePlugin}
getPluginGitInfo={getPluginGitInfo}
/>;
})}
</div>
) : (
<Alert>
<AlertDescription className="text-sm">
{t('noPluginsConfigured')}
</AlertDescription>
</Alert>
)}
{/* Add Plugin Section */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-plugin" className="border rounded-lg">
<AccordionItem value="add-plugin">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
@@ -132,7 +121,9 @@ export function PluginsSection() {
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="plugin-git-url">{t('gitRepositoryUrl')}</Label>
<Label htmlFor="plugin-git-url">
{t('gitRepositoryUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="plugin-git-url"
placeholder="https://github.com/user/plugin.git"
@@ -180,19 +171,18 @@ interface PluginItemProps {
isDeleting: boolean;
onSync: (pluginName: string) => void;
onDelete: (pluginName: string) => void;
getPluginGitInfo: (pluginName: string) => { data: { commitHash: string; commitDate: Date; commitMessage: string } | null | undefined; isLoading: boolean };
}
function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, onDelete, getPluginGitInfo }: PluginItemProps) {
function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, onDelete }: PluginItemProps) {
const { t } = useTranslation();
const { data: gitInfo } = getPluginGitInfo(pluginName);
const { data: gitInfo } = usePluginGitInfo(pluginName);
return (
<Accordion type="single" collapsible className="w-full">
<AccordionItem value={pluginName} className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Puzzle className="h-4 w-4 text-primary" />
<Puzzle className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{pluginName}</span>
{pluginSkills.length > 0 && (
<span className="text-xs text-muted-foreground">
@@ -225,14 +215,6 @@ function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, o
</div>
)}
{pluginSkills.length === 0 && (
<Alert>
<AlertDescription className="text-xs">
{t('noSkillsFound')}
</AlertDescription>
</Alert>
)}
{/* Plugin Actions and Git Info */}
<div className="space-y-2 pt-2">
{gitInfo && (
+57
View File
@@ -33,9 +33,13 @@ import {
Loader2,
Trash2,
Save,
DollarSign,
ExternalLink,
FileCode,
} from 'lucide-react';
import JSZip from 'jszip';
import { Separator } from './ui/separator';
import { DotAI } from '@/lib/DotAI';
interface ProjectDetailsDialogProps {
project: Project;
@@ -49,6 +53,8 @@ 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 [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const { toast } = useToast();
const { fs } = useFS();
const { projectsPath } = useFSPaths();
@@ -62,6 +68,31 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
setIsRenaming(false);
}, [project.id]);
// Load total project cost and template info
useEffect(() => {
const loadProjectData = async () => {
try {
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
// Load cost
const cost = await dotAI.readCost();
setTotalCost(cost);
// Load template info
const template = await dotAI.readTemplate();
setTemplateInfo(template);
} catch (error) {
console.warn('Failed to load project data:', error);
setTotalCost(null);
setTemplateInfo(null);
}
};
if (open) {
loadProjectData();
}
}, [fs, projectsPath, project.id, open]);
const formatDistanceToNow = (date: Date) => {
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
@@ -226,6 +257,32 @@ 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>
)}
{/* Template Info */}
{templateInfo && (
<div className="flex items-center gap-2 text-sm">
<FileCode className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Template:</span>
<a
href={templateInfo.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-primary hover:underline"
>
{templateInfo.name}
<ExternalLink className="h-3 w-3" />
</a>
</div>
)}
{/* Project Name */}
<div className="space-y-2">
<Label htmlFor="project-name">Project Name</Label>
+41 -6
View File
@@ -1,9 +1,10 @@
import React, { useEffect } from 'react';
import React, { useEffect, useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Input } from '@/components/ui/input';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
@@ -93,10 +94,24 @@ export function ProjectSidebar({
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const [searchQuery, setSearchQuery] = useState('');
const isMobile = useIsMobile();
const navigate = useNavigate();
// Fast in-memory search filtering
const filteredProjects = useMemo(() => {
if (!searchQuery.trim()) {
return projects;
}
const query = searchQuery.toLowerCase();
return projects.filter(project =>
project.id.toLowerCase().includes(query) ||
project.name.toLowerCase().includes(query)
);
}, [projects, searchQuery]);
// Custom navigate function that closes sidebar on mobile
const navigateAndClose = (path: string) => {
navigate(path);
@@ -166,12 +181,12 @@ export function ProjectSidebar({
<div className="flex-1 overflow-y-auto">
<div className="p-2">
<div className="mb-2">
<div className="mb-2 space-y-3">
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
<div className="flex">
<button
onClick={handleNewProject}
className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
className="flex-1 flex items-center justify-center px-3 py-2.5 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
>
<Plus className="h-4 w-4 mr-2" />
{t('newProject')}
@@ -179,7 +194,7 @@ export function ProjectSidebar({
<div className="w-px bg-white/20" />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="px-2 py-2 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
<button className="px-3 py-2.5 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
<ChevronDown className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
@@ -195,6 +210,20 @@ export function ProjectSidebar({
</DropdownMenu>
</div>
</div>
{/* Search Input */}
{projects.length > 0 && (
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
<Input
type="text"
placeholder={t('searchProjects')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9 text-sm bg-sidebar-accent/50 border-sidebar-border focus-visible:ring-primary/50"
/>
</div>
)}
</div>
{isLoading ? (
@@ -214,9 +243,15 @@ export function ProjectSidebar({
<p className="text-sm">{t('noProjectsYet')}</p>
<p className="text-xs">{t('createFirstProject')}</p>
</div>
) : filteredProjects.length === 0 ? (
<div className="text-center p-6 text-muted-foreground">
<Search className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">{t('noProjectsFound')}</p>
<p className="text-xs">{t('tryDifferentSearch')}</p>
</div>
) : (
<div className="space-y-1">
{projects.map((project) => (
{filteredProjects.map((project) => (
<ProjectItem
key={project.id}
project={project}
+357
View File
@@ -0,0 +1,357 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FileCode2, Trash2, Plus, GripVertical, RotateCcw } from 'lucide-react';
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
type DragEndEvent,
} from '@dnd-kit/core';
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import {
useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
interface ProjectTemplate {
name: string;
description: string;
url: string;
}
interface SortableTemplateItemProps {
template: ProjectTemplate;
index: number;
onRemove: (index: number) => void;
onUpdate: (index: number, template: ProjectTemplate) => void;
showDragHandle: boolean;
isOnlyTemplate: boolean;
}
function SortableTemplateItem({
template,
index,
onRemove,
onUpdate,
showDragHandle,
isOnlyTemplate,
}: SortableTemplateItemProps) {
const { t } = useTranslation();
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: `template-${index}` });
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<AccordionItem
ref={setNodeRef}
style={style}
value={`template-${index}`}
className="border rounded-lg"
>
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2 w-full mr-3">
{showDragHandle && (
<div
{...attributes}
{...listeners}
className="cursor-grab active:cursor-grabbing p-1 -ml-1 text-muted-foreground hover:text-foreground"
>
<GripVertical className="h-4 w-4" />
</div>
)}
<FileCode2 size={16} className="text-muted-foreground" />
<span className="font-medium">{template.name}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`template-name-${index}`}>
{t('templateName')} <span className="text-destructive">*</span>
</Label>
<Input
id={`template-name-${index}`}
placeholder="MKStack"
value={template.name}
onChange={(e) => onUpdate(index, { ...template, name: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`template-description-${index}`}>
{t('templateDescription')} <span className="text-destructive">*</span>
</Label>
<Textarea
id={`template-description-${index}`}
placeholder="Build Nostr clients with React."
value={template.description}
onChange={(e) => onUpdate(index, { ...template, description: e.target.value })}
className="min-h-[80px]"
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`template-url-${index}`}>
{t('templateGitUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id={`template-url-${index}`}
type="url"
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
value={template.url}
onChange={(e) => onUpdate(index, { ...template, url: e.target.value })}
/>
</div>
<Button
variant="destructive"
size="sm"
onClick={() => onRemove(index)}
disabled={isOnlyTemplate}
title={isOnlyTemplate ? t('atLeastOneTemplateRequired') : t('delete')}
>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</Button>
</div>
</AccordionContent>
</AccordionItem>
);
}
export function ProjectTemplatesSection() {
const { t } = useTranslation();
const { config, defaultConfig, updateConfig } = useAppContext();
const { toast } = useToast();
const [newTemplateName, setNewTemplateName] = useState('');
const [newTemplateDescription, setNewTemplateDescription] = useState('');
const [newTemplateUrl, setNewTemplateUrl] = useState('');
const templates = config.templates || [];
const defaultTemplates = defaultConfig.templates || [];
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
// Check if current templates match the default configuration
const templatesMatchDefault = JSON.stringify(templates) === JSON.stringify(defaultTemplates);
const handleAddTemplate = () => {
if (!newTemplateName.trim() || !newTemplateDescription.trim() || !newTemplateUrl.trim()) {
return;
}
const newTemplate: ProjectTemplate = {
name: newTemplateName.trim(),
description: newTemplateDescription.trim(),
url: newTemplateUrl.trim(),
};
updateConfig((current) => ({
...current,
templates: [...(current.templates || []), newTemplate],
}));
toast({
title: t('templateAdded'),
description: t('templateAddedDescription', { name: newTemplateName.trim() }),
});
setNewTemplateName('');
setNewTemplateDescription('');
setNewTemplateUrl('');
};
const handleRemoveTemplate = (index: number) => {
const templateName = templates[index]?.name || 'template';
const newTemplates = templates.filter((_, i) => i !== index);
updateConfig((current) => ({
...current,
templates: newTemplates,
}));
toast({
title: t('templateDeleted'),
description: t('templateDeletedDescription', { name: templateName }),
});
};
const handleUpdateTemplate = (index: number, updatedTemplate: ProjectTemplate) => {
const newTemplates = [...templates];
newTemplates[index] = updatedTemplate;
updateConfig((current) => ({
...current,
templates: newTemplates,
}));
};
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (active.id !== over?.id) {
const oldIndex = parseInt(active.id.toString().replace('template-', ''));
const newIndex = parseInt(over?.id.toString().replace('template-', '') || '0');
if (!isNaN(oldIndex) && !isNaN(newIndex) && oldIndex !== newIndex) {
const newTemplates = arrayMove(templates, oldIndex, newIndex);
updateConfig((current) => ({
...current,
templates: newTemplates,
}));
}
}
};
const handleResetToDefaults = () => {
// Remove the templates from local config so defaults take precedence
updateConfig((current) => {
const { templates: _, ...rest } = current;
return rest;
});
};
return (
<div className="space-y-4">
{/* Project Templates Header */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<FileCode2 className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('projectTemplates')}</h3>
{!templatesMatchDefault && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
{!templatesMatchDefault && (
<button
onClick={handleResetToDefaults}
title={t('restoreToDefault')}
className="ml-auto p-1 text-muted-foreground hover:text-foreground"
>
<RotateCcw className="h-4 w-4" />
</button>
)}
</div>
<p className="text-sm text-muted-foreground">
{t('projectTemplatesDescription')}
</p>
</div>
{/* Configured Templates List */}
{templates.length > 0 && (
<div className="space-y-2">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={templates.map((_, index) => `template-${index}`)}
strategy={verticalListSortingStrategy}
>
<Accordion type="multiple" className="w-full space-y-2">
{templates.map((template, index) => (
<SortableTemplateItem
key={index}
template={template}
index={index}
onRemove={handleRemoveTemplate}
onUpdate={handleUpdateTemplate}
showDragHandle={templates.length > 1}
isOnlyTemplate={templates.length === 1}
/>
))}
</Accordion>
</SortableContext>
</DndContext>
</div>
)}
{/* Add New Template */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-template">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<span className="text-sm font-medium">{t('addProjectTemplate')}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="new-template-name">
{t('templateName')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-template-name"
placeholder="MKStack"
value={newTemplateName}
onChange={(e) => setNewTemplateName(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-template-description">
{t('templateDescription')} <span className="text-destructive">*</span>
</Label>
<Textarea
id="new-template-description"
placeholder="Build Nostr clients with React."
value={newTemplateDescription}
onChange={(e) => setNewTemplateDescription(e.target.value)}
className="min-h-[80px]"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-template-url">
{t('templateGitUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-template-url"
type="url"
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
value={newTemplateUrl}
onChange={(e) => setNewTemplateUrl(e.target.value)}
/>
</div>
<Button
onClick={handleAddTemplate}
disabled={!newTemplateName.trim() || !newTemplateDescription.trim() || !newTemplateUrl.trim()}
className="gap-2 w-full"
>
<Plus className="h-4 w-4" />
{t('add')}
</Button>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
);
}
+75 -25
View File
@@ -11,6 +11,7 @@ import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { useState } from 'react';
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
import { EmptyMessageError } from '@/lib/errors/EmptyMessageError';
import { AIProvider } from '@/contexts/AISettingsContext';
export interface QuillyProps {
error: Error;
@@ -30,23 +31,20 @@ interface ErrorBody {
}>;
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
interface QuillyContentProps {
error: Error;
onDismiss: () => void;
onNewChat: () => void;
onOpenModelSelector: () => void;
onTryAgain?: () => void;
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
provider: AIProvider | undefined;
}
function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, provider }: QuillyContentProps) {
const navigate = useNavigate();
const { settings } = useAISettings();
// Handle empty provider model gracefully
let provider;
try {
provider = parseProviderModel(providerModel, settings.providers).provider;
} catch {
// If no valid provider model, use a default or undefined
provider = undefined;
}
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody => {
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
// Handle Project Preview Console Errors
if (error instanceof ProjectPreviewConsoleError) {
return {
@@ -69,7 +67,7 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
onClick: onOpenModelSelector,
}],
};
}
}
if (error instanceof EmptyMessageError) {
return {
@@ -101,13 +99,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
};
case error.code === 'insufficient_quota': {
if (credits.data) {
// Only show credits dialog if we have a provider with nostr enabled
if (provider?.nostr) {
return {
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
actions: [{
label: 'Add credits',
onClick: () => setShowCreditsDialog(true),
}],
message: 'Your account is low on credits. Please add credits to keep creating.',
showCreditsButton: true,
actions: [],
};
} else {
return {
@@ -200,11 +197,17 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
message: error.message
? `AI service error: ${error.message}`
: 'Sorry, I encountered an unexpected error. Please try again.',
actions: [],
actions: onTryAgain ? [{
label: 'Try again',
onClick: () => {
onTryAgain();
onDismiss();
},
}] : [],
};
};
const { message, actions = [] } = renderBody(error);
const { message, actions = [], showCreditsButton } = renderBody(error);
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
@@ -217,6 +220,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
</h4>
<p className="text-sm text-muted-foreground">
{message}
{showCreditsButton && provider && (
<>
{' '}
<QuillyCreditsButton provider={provider} />
</>
)}
{actions.length > 0 && (
<>
{' '}
@@ -242,12 +251,53 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
<X className="h-4 w-4" />
</Button>
</div>
</div>
);
}
interface QuillyCreditsButtonProps {
provider: AIProvider;
}
function QuillyCreditsButton({ provider }: QuillyCreditsButtonProps) {
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const credits = useAICredits(provider);
return (
<>
<button className="text-primary underline" onClick={() => setShowCreditsDialog(true)}>
{credits.data ? `Add credits (${credits.data.amount.toFixed(2)} remaining)` : 'Add credits'}
</button>
<CreditsDialog
open={showCreditsDialog}
onOpenChange={setShowCreditsDialog}
provider={provider}
/>
</div>
</>
);
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
const { settings } = useAISettings();
// Handle empty provider model gracefully
let provider: AIProvider | undefined;
try {
provider = parseProviderModel(providerModel, settings.providers).provider;
} catch {
// If no valid provider model, use a default or undefined
provider = undefined;
}
return (
<QuillyContent
error={error}
onDismiss={onDismiss}
onNewChat={onNewChat}
onOpenModelSelector={onOpenModelSelector}
onTryAgain={onTryAgain}
onRequestConsoleErrorHelp={onRequestConsoleErrorHelp}
provider={provider}
/>
);
}
+99
View File
@@ -0,0 +1,99 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitBranch } from 'lucide-react';
import type { Repository } from '@/hooks/useUserRepositories';
import { useAuthor } from '@/hooks/useAuthor';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { genUserName } from '@/lib/genUserName';
import { useNavigate } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
interface RepositoryCardProps {
repo: Repository;
}
export function RepositoryCard({ repo }: RepositoryCardProps) {
const { data: authorData } = useAuthor(repo.pubkey);
const navigate = useNavigate();
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
const profileImage = authorData?.metadata?.picture;
// Construct Nostr clone URL
const nostrCloneUrl = `nostr://${nip19.npubEncode(repo.pubkey)}/${repo.repoId}`;
const handleClone = () => {
// Navigate to clone page with Nostr URL parameter
navigate(`/clone?url=${encodeURIComponent(nostrCloneUrl)}`);
};
return (
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow cursor-pointer" onClick={handleClone}>
<CardContent className="p-6 flex flex-col flex-1">
{/* Header with name and author */}
<div className="mb-4">
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
{repo.name}
</h3>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Avatar className="h-4 w-4">
{profileImage && (
<AvatarImage src={profileImage} alt={displayName} />
)}
<AvatarFallback className="text-[8px]">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span className="truncate">{displayName}</span>
</div>
</div>
{/* Description */}
{repo.description && (
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
{repo.description}
</p>
)}
{/* Tags */}
{repo.repoTags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-4">
{repo.repoTags.slice(0, 3).map((tag, index) => (
<Badge key={index} variant="secondary" className="text-xs">
{tag}
</Badge>
))}
{repo.repoTags.length > 3 && (
<Badge variant="secondary" className="text-xs">
+{repo.repoTags.length - 3}
</Badge>
)}
</div>
)}
{/* Personal fork badge */}
{repo.isPersonalFork && (
<div className="mb-4">
<Badge variant="outline" className="text-xs">
Personal Fork
</Badge>
</div>
)}
{/* Actions */}
<div className="mt-auto">
<Button
size="sm"
className="w-full"
onClick={handleClone}
>
<GitBranch className="h-4 w-4 mr-2" />
Clone
</Button>
</div>
</CardContent>
</Card>
);
}
+12 -8
View File
@@ -27,7 +27,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://test.git',
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
@@ -39,10 +39,11 @@ describe('SentryProvider', () => {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -63,7 +64,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://test.git',
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
@@ -75,10 +76,11 @@ describe('SentryProvider', () => {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -100,7 +102,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://test.git',
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
@@ -112,10 +114,11 @@ describe('SentryProvider', () => {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -140,7 +143,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://test.git',
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
@@ -152,10 +155,11 @@ describe('SentryProvider', () => {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
+62 -12
View File
@@ -1,12 +1,12 @@
import { ReactNode, useMemo, useEffect } from 'react';
import { ReactNode, useEffect, useRef } from 'react';
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
import { SessionManager } from '@/lib/SessionManager';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
interface SessionManagerProviderProps {
children: ReactNode;
@@ -17,30 +17,80 @@ interface SessionManagerProviderProps {
*/
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
const { fs } = useFS();
const { projectsPath, pluginsPath } = useFSPaths();
const { settings } = useAISettings();
const { models } = useProviderModels();
const { user, metadata } = useCurrentUser();
const { config } = useAppContext();
const { config, defaultConfig } = useAppContext();
const { nostr } = useNostr();
const sessionManager = useMemo(() => {
const getProviderModels = () => models;
const getCurrentUser = () => ({ user, metadata });
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath);
}, [fs, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath]);
// Create SessionManager instance only once
const sessionManager = useRef<SessionManager | undefined>(undefined);
// Use refs so SessionManager always has the latest data
const configRef = useRef(config);
const defaultConfigRef = useRef(defaultConfig);
const settingsRef = useRef(settings);
const modelsRef = useRef(models);
const userRef = useRef(user);
const metadataRef = useRef(metadata);
// Update refs when values change
useEffect(() => {
configRef.current = config;
}, [config]);
useEffect(() => {
defaultConfigRef.current = defaultConfig;
}, [defaultConfig]);
useEffect(() => {
settingsRef.current = settings;
}, [settings]);
useEffect(() => {
modelsRef.current = models;
}, [models]);
useEffect(() => {
userRef.current = user;
}, [user]);
useEffect(() => {
metadataRef.current = metadata;
}, [metadata]);
// Initialize SessionManager only once
if (!sessionManager.current) {
// Callbacks access refs to get latest values
const getProviderModels = () => modelsRef.current;
const getCurrentUser = () => ({ user: userRef.current, metadata: metadataRef.current });
const getConfig = () => configRef.current;
const getDefaultConfig = () => defaultConfigRef.current;
const getSettings = () => settingsRef.current;
sessionManager.current = new SessionManager(
fs,
nostr,
getSettings,
getConfig,
getDefaultConfig,
getProviderModels,
getCurrentUser,
);
}
// Cleanup on unmount
useEffect(() => {
return () => {
// Fire and forget cleanup - we don't need to await in useEffect cleanup
sessionManager.cleanup().catch(error => {
sessionManager.current?.cleanup().catch(error => {
console.warn('Failed to cleanup session manager:', error);
});
};
}, [sessionManager]);
}, []);
return (
<SessionManagerContext.Provider value={sessionManager}>
<SessionManagerContext.Provider value={sessionManager.current}>
{children}
</SessionManagerContext.Provider>
);
+57
View File
@@ -0,0 +1,57 @@
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface SettingsItemProps {
icon: React.ComponentType<{ className?: string }>;
title: string;
onClick: () => void;
isActive?: boolean;
className?: string;
}
export function SettingsItem({
icon: Icon,
title,
onClick,
isActive = false,
className,
}: SettingsItemProps) {
return (
<button
onClick={onClick}
className={cn(
'group w-full text-left p-2 rounded-lg transition-all duration-200 border',
{
'bg-primary/10 border-primary/20 shadow-sm': isActive,
'border-transparent hover:bg-muted/60 hover:shadow-sm': !isActive,
},
className
)}
>
<div className="flex items-center gap-2.5">
<div className="rounded-md transition-all duration-200">
<Icon className={cn('h-4 w-4 flex-shrink-0 transition-colors duration-200', {
'text-primary': isActive,
'text-muted-foreground group-hover:text-foreground': !isActive,
})} />
</div>
<div className="flex-1 min-w-0">
<div className={cn('text-sm font-medium transition-colors duration-200', {
'text-primary': isActive,
'text-foreground': !isActive,
})}>
{title}
</div>
</div>
<ChevronRight className={cn(
'h-4 w-4 flex-shrink-0 transition-all duration-200',
'opacity-0 -translate-x-1 group-hover:opacity-100 group-hover:translate-x-0',
{
'text-primary opacity-60': isActive,
'text-muted-foreground': !isActive,
}
)} />
</div>
</button>
);
}
+43
View File
@@ -0,0 +1,43 @@
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface SettingsItemMobileProps {
icon: React.ComponentType<{ className?: string }>;
title: string;
onClick: () => void;
isFirst?: boolean;
isLast?: boolean;
}
export function SettingsItemMobile({
icon: Icon,
title,
onClick,
isFirst = false,
isLast = false,
}: SettingsItemMobileProps) {
return (
<button
onClick={onClick}
className={cn(
'w-full text-left px-4 py-3.5 bg-card text-card-foreground transition-colors active:bg-muted/50',
'flex items-center gap-3',
'border-b border-border last:border-b-0',
{
'rounded-t-xl': isFirst,
'rounded-b-xl': isLast,
}
)}
>
<div className="flex items-center justify-center w-7 h-7 rounded-lg bg-primary/10">
<Icon className="h-4 w-4 text-primary flex-shrink-0" />
</div>
<div className="flex-1 min-w-0">
<div className="text-base">
{title}
</div>
</div>
<ChevronRight className="h-5 w-5 text-muted-foreground/50 flex-shrink-0" />
</button>
);
}
+31 -36
View File
@@ -8,8 +8,8 @@ import { ProjectSidebar } from '@/components/ProjectSidebar';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useIsMobile } from '@/hooks/useIsMobile';
import { type Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import { getSettingsItems } from '@/lib/settingsItems';
import { getSettingsCategories } from '@/lib/settingsItems';
import { SettingsItem } from '@/components/SettingsItem';
export function SettingsLayout() {
const { t } = useTranslation();
@@ -60,9 +60,11 @@ export function SettingsLayout() {
};
// Get current settings page
const settingsItems = getSettingsItems(t);
const settingsCategories = getSettingsCategories(t);
const currentPath = location.pathname;
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
const currentSettingsId = settingsCategories
.flatMap(category => category.items)
.find(item => item.href === currentPath)?.id;
if (isMobile) {
return (
@@ -89,7 +91,7 @@ export function SettingsLayout() {
className="absolute inset-0"
onClick={() => setIsSidebarVisible(false)}
/>
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={null}
onSelectProject={(project) => {
@@ -112,7 +114,7 @@ export function SettingsLayout() {
<div className="h-screen flex bg-background overflow-hidden">
{/* Left Column - Projects Sidebar (optionally hidden) */}
{isSidebarVisible && (
<div className="w-80 border-r bg-sidebar flex-shrink-0">
<div className="w-72 border-r bg-sidebar flex-shrink-0">
<ProjectSidebar
selectedProject={null}
onSelectProject={handleProjectSelect}
@@ -123,7 +125,7 @@ export function SettingsLayout() {
)}
{/* Middle Column - Settings Navigation */}
<div className="w-96 border-r bg-background flex flex-col flex-shrink-0">
<div className="w-72 border-r bg-background flex flex-col flex-shrink-0">
{/* Header with toggle button */}
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
<div className="flex items-center gap-3">
@@ -146,36 +148,29 @@ export function SettingsLayout() {
{/* Settings Navigation - Scrollable */}
<ScrollArea className="flex-1">
<div className="p-4">
<div className="space-y-2">
{settingsItems.map((item) => {
const Icon = item.icon;
const isActive = currentSettingsId === item.id;
<div className="p-4 space-y-6">
{settingsCategories.map((category) => (
<div key={category.id}>
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-2">
{category.title}
</h3>
<div className="space-y-1">
{category.items.map((item) => {
const isActive = currentSettingsId === item.id;
return (
<button
key={item.id}
onClick={() => navigate(item.href)}
className={cn('w-full text-left p-3 rounded-lg transition-colors border border-transparent', {
'bg-primary/10 border border-primary/20': isActive,
'hover:bg-muted/50': !isActive,
})}
>
<div className="flex items-start gap-3">
<Icon className={`h-5 w-5 mt-0.5 ${isActive ? 'text-primary' : 'text-muted-foreground'}`} />
<div className="flex-1 min-w-0">
<div className={`font-medium ${isActive ? 'text-primary' : 'text-foreground'}`}>
{item.title}
</div>
<div className="text-sm text-muted-foreground mt-0.5">
{item.description}
</div>
</div>
</div>
</button>
);
})}
</div>
return (
<SettingsItem
key={item.id}
icon={item.icon}
title={item.title}
onClick={() => navigate(item.href)}
isActive={isActive}
/>
);
})}
</div>
</div>
))}
</div>
</ScrollArea>
</div>
+108 -49
View File
@@ -14,6 +14,7 @@ import { useAppContext } from '@/hooks/useAppContext';
import { useAIChat } from '@/hooks/useAIChat';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useMCPTools } from '@/hooks/useMCPTools';
import { AIMessageItem } from '@/components/AIMessageItem';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
@@ -35,15 +36,17 @@ import { ShellTool } from '@/lib/tools/ShellTool';
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
import { SkillTool } from '@/lib/tools/SkillTool';
import { createMCPTools } from '@/lib/tools/MCPTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { DotAI } from '@/lib/DotAI';
// Clean interfaces now handled by proper hooks
@@ -86,6 +89,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
// Determine which error to show - console error takes priority over AI errors
const displayError = consoleError || aiError;
@@ -148,8 +153,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
sessionManager.emit('fileChanged', projectId, filePath);
}, [sessionManager, projectId]);
const customTools = useMemo(() => {
const baseTools = {
// Fetch MCP tools
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
// Separate built-in tools from MCP tools for clarity
const builtInTools = useMemo(() => {
const tools: Record<string, Tool<unknown>> = {
git_commit: new GitCommitTool(fs, cwd, git),
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
@@ -166,30 +175,42 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_read_nips_index: new NostrReadNipsIndexTool(),
nostr_generate_kind: new NostrGenerateKindTool(),
nostr_publish_events: new NostrPublishEventsTool(),
shell: new ShellTool(fs, cwd, git, projectsPath, user?.signer),
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath),
skill: new SkillTool(fs, pluginsPath, cwd),
};
// Add deploy tool only if user is logged in
if (user && user.signer) {
return {
...baseTools,
deploy_project: new DeployProjectTool(fs, cwd, user.signer, projectId),
};
tools.deploy_project = new DeployProjectTool(fs, cwd, user.signer, projectId);
}
return baseTools;
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, handleFileChanged]);
return tools;
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]);
// Convert tools to OpenAI format
// MCP tools wrapped for execution
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
// Combined tool executors (for SessionManager to call)
const customTools = useMemo(() => ({
...builtInTools,
...mcpToolWrappers,
}), [builtInTools, mcpToolWrappers]);
// Convert tools to OpenAI format for AI provider
const tools = useMemo(() => {
const result: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
for (const [name, tool] of Object.entries(customTools)) {
// Convert built-in tools to OpenAI format
for (const [name, tool] of Object.entries(builtInTools)) {
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
}
// Add MCP tools (already in OpenAI format from useMCPTools)
Object.assign(result, mcpOpenAITools);
return result;
}, [customTools]);
}, [builtInTools, mcpOpenAITools]);
// Keep-alive functionality to prevent tab throttling during AI processing
const { updateMetadata } = useKeepAlive({
@@ -234,6 +255,52 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onAIError,
});
// Check if we should show the template info banner
useEffect(() => {
const checkTemplateInfo = async () => {
try {
// Only check if we have at least 1 message
if (messages.length === 0) {
setShowTemplateInfo(false);
return;
}
const projectCwd = `${projectsPath}/${projectId}`;
const dotAI = new DotAI(fs, projectCwd);
// Check if template.json exists
const template = await dotAI.readTemplate();
if (!template) {
setShowTemplateInfo(false);
return;
}
// Check if exactly 1 history file exists
const historyDirExists = await dotAI.historyDirExists();
if (!historyDirExists) {
setShowTemplateInfo(false);
return;
}
const historyDir = `${projectCwd}/.git/ai/history`;
const files = await fs.readdir(historyDir);
const historyFiles = files.filter(file => file.endsWith('.jsonl'));
if (historyFiles.length === 1) {
setTemplateInfo(template);
setShowTemplateInfo(true);
} else {
setShowTemplateInfo(false);
}
} catch (error) {
console.warn('Failed to check template info:', error);
setShowTemplateInfo(false);
}
};
checkTemplateInfo();
}, [fs, projectsPath, projectId, messages.length]);
// Handle console error help requests
const handleConsoleErrorHelp = useCallback(async () => {
const tool = new ReadConsoleMessagesTool();
@@ -438,45 +505,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const modelToUse = providerModel.trim();
// Build message content as text parts
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
// Add user input as text part if present
if (input.trim()) {
contentParts.push({
type: 'text',
text: input.trim()
});
}
// Process attached files and add as separate text parts
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
const savedPath = await saveFileToTmp(fs, file, tmpPath);
return `Added file: ${savedPath}`;
} catch (error) {
console.error('Failed to save file:', error);
return `Failed to save file: ${file.name}`;
}
});
const fileResults = await Promise.all(filePromises);
// Add each file as a separate text part
fileResults.forEach(fileResult => {
contentParts.push({
type: 'text',
text: fileResult
});
});
}
// Build message content from input and attached files
// Images are converted to base64-encoded data URLs
const messageContent = await buildMessageContent(
input,
attachedFiles,
fs,
tmpPath
);
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
// 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]);
@@ -511,6 +551,25 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
<div className="p-4 space-y-4">
{/* Template info banner - shown when conditions are met */}
{showTemplateInfo && templateInfo && (
<div className="flex items-center gap-3 text-xs text-muted-foreground uppercase tracking-wide">
<div className="flex-1 h-px bg-border" />
<span>
Vibing with{' '}
<a
href={templateInfo.url}
target="_blank"
rel="noopener noreferrer"
className="hover:text-foreground transition-colors"
>
{templateInfo.name}
</a>
</span>
<div className="flex-1 h-px bg-border" />
</div>
)}
{/* Empty state when no messages and not loading */}
{messages.length === 0 && !streamingMessage && !isLoading && (
<div className="flex-1 flex items-center justify-center min-h-[400px]">
+33 -23
View File
@@ -3,9 +3,10 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Save, Loader2 } from 'lucide-react';
import { Save, Loader2, ImageOff } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useGitStatus } from '@/hooks/useGitStatus';
import { isMediaFile } from '@/lib/fileUtils';
interface FileEditorProps {
filePath: string;
@@ -93,6 +94,7 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
// Get git status for the current file
const currentFileGitStatus = getFileGitStatus(filePath);
const gitStatusClasses = getGitStatusClasses(currentFileGitStatus);
const isMedia = isMediaFile(filePath);
return (
<div className="h-full flex flex-col">
@@ -100,32 +102,36 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
<div className="flex items-center justify-between">
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
<div className="flex items-center space-x-1 sm:space-x-2">
{hasChanges && (
{hasChanges && !isMedia && (
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">{t('unsavedChanges')}</span>
)}
<Button
onClick={handleSave}
disabled={!hasChanges || isSaving || isLoading}
size="sm"
className="focus-ring"
>
{isSaving ? (
<>
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
<span className="hidden sm:inline">{t('saving')}</span>
</>
) : (
<>
<Save className="sm:mr-2 h-4 w-4" />
<span className="hidden sm:inline">{t('save')}</span>
</>
)}
</Button>
{!isMedia && (
<Button
onClick={handleSave}
disabled={!hasChanges || isSaving || isLoading}
size="sm"
className="focus-ring"
>
{isSaving ? (
<>
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
<span className="hidden sm:inline">{t('saving')}</span>
</>
) : (
<>
<Save className="sm:mr-2 h-4 w-4" />
<span className="hidden sm:inline">{t('save')}</span>
</>
)}
</Button>
)}
</div>
</div>
<div className="text-xs text-muted-foreground mt-1">
{t('languageLabel')}: {getLanguageFromPath(filePath)}
</div>
{!isMedia && (
<div className="text-xs text-muted-foreground mt-1">
{t('languageLabel')}: {getLanguageFromPath(filePath)}
</div>
)}
</CardHeader>
<CardContent className="flex-1 p-0">
@@ -133,6 +139,10 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
<div className="flex items-center justify-center h-full">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
) : isMedia ? (
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
<ImageOff className="h-16 w-16 text-muted-foreground" />
</div>
) : (
<Textarea
value={editedContent}
+10 -2
View File
@@ -32,6 +32,7 @@ import { DeployDialog } from '@/components/DeployDialog';
import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
import { useAppContext } from '@/hooks/useAppContext';
import { isMediaFile } from '@/lib/fileUtils';
interface PreviewPaneProps {
projectId: string;
@@ -130,6 +131,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
const loadFileContent = useCallback(async (filePath: string) => {
// Skip loading media files - they can't be edited as text
if (isMediaFile(filePath)) {
setFileContent('');
setIsLoading(false);
return;
}
setIsLoading(true);
try {
const content = await projectsManager.readFile(projectId, filePath);
@@ -793,7 +801,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
</h3>
</div>
<div className="flex-1 min-h-0">
<TerminalComponent projectId={projectId} />
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
</div>
</>
) : (
@@ -887,7 +895,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<div className="flex-1 flex min-h-0">
{desktopCodeView === 'terminal' ? (
<div className="flex-1">
<TerminalComponent projectId={projectId} />
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
</div>
) : (
<>
+9 -11
View File
@@ -5,13 +5,13 @@ import { Copy } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ShellTool } from '@/lib/tools/ShellTool';
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 {
projectId: string;
cwd: string;
className?: string;
}
@@ -22,7 +22,7 @@ interface TerminalLine {
timestamp: Date;
}
export function Terminal({ projectId, className }: TerminalProps) {
export function Terminal({ cwd, className }: TerminalProps) {
const [lines, setLines] = useState<TerminalLine[]>([]);
const [currentInput, setCurrentInput] = useState('');
const [isExecuting, setIsExecuting] = useState(false);
@@ -34,13 +34,13 @@ export function Terminal({ projectId, className }: TerminalProps) {
const shellToolRef = useRef<ShellTool | null>(null);
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const { git } = useGit();
const { user } = useCurrentUser();
const { config } = useAppContext();
// Initialize ShellTool
useEffect(() => {
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, user?.signer);
shellToolRef.current = new ShellTool(fs, cwd, git, config.corsProxy, user?.signer);
// Add welcome message
setLines([{
@@ -49,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, user?.signer]);
}, [cwd, fs, git, config.corsProxy, user?.signer]);
// Auto-scroll to bottom when new lines are added or execution state changes
useEffect(() => {
@@ -106,10 +106,8 @@ export function Terminal({ projectId, className }: TerminalProps) {
// Check if running in Electron - use real shell
if (window.electron?.shell) {
// Use the full path (with ~ if present) - Electron will expand it
const fullCwd = `${projectsPath}/${projectId}`;
const result = await window.electron.shell.exec(command, fullCwd);
// Use the provided cwd (Electron will expand ~ if present)
const result = await window.electron.shell.exec(command, cwd);
// Format output
let output = '';
@@ -157,7 +155,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
} finally {
setIsExecuting(false);
}
}, [addLine, commandHistory, projectId, projectsPath]);
}, [addLine, commandHistory, cwd]);
const handleSubmit = useCallback((e: React.FormEvent) => {
e.preventDefault();
+1 -1
View File
@@ -6,7 +6,7 @@ import { Terminal } from './Terminal';
export function TerminalTest() {
return (
<div className="h-[500px] w-full">
<Terminal projectId="test" />
<Terminal cwd="/projects/test" />
</div>
);
}
+7
View File
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { AddProviderDialog } from '@/components/AddProviderDialog';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
/**
* Component that handles URL fragments for adding AI providers
@@ -30,9 +31,15 @@ export function URLFragmentHandler() {
return;
}
// Get name from URL params or derive from presets or id
const nameParam = params.get('name');
const preset = AI_PROVIDER_PRESETS.find(p => p.id === id);
const name = nameParam || preset?.name || id;
// Build the provider object
const provider: AIProvider = {
id,
name,
baseURL,
};
+5 -2
View File
@@ -16,8 +16,11 @@ describe('UserMessage', () => {
render(<UserMessage content={content} />);
// When using string content, it should still work but won't separate file attachments
expect(screen.getByText(content)).toBeInTheDocument();
// When using string content, it should parse and separate file attachments
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
expect(screen.getByText('test.txt')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
});
it('renders file attachment badges for single file with text parts', () => {
+58 -25
View File
@@ -1,4 +1,4 @@
import { FileText, File } from 'lucide-react';
import { Paperclip } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import type OpenAI from 'openai';
@@ -18,21 +18,60 @@ export function UserMessage({ content }: UserMessageProps) {
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
// Regular expression to match "Added file: /tmp/<filename>" patterns
const filePattern = /^Added file: (\/tmp\/[^\s\n]+)$/;
// Matches the pattern anywhere in the text
const filePattern = /Added file:\s*(\/tmp\/[^\s\n]+)/g;
// Process each content part and categorize as text or file
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
contentParts.forEach(part => {
const text = part.text.trim();
const match = text.match(filePattern);
// Find all file patterns in this text part
const fileMatches: Array<{ filepath: string; index: number; length: number }> = [];
let match;
filePattern.lastIndex = 0; // Reset regex
while ((match = filePattern.exec(text)) !== null) {
fileMatches.push({
filepath: match[1], // "/tmp/filename.txt"
index: match.index,
length: match[0].length
});
}
if (match) {
// This is a file attachment
const filepath = match[1]; // "/tmp/filename.txt"
processedParts.push({ type: 'file', content: text, filepath });
if (fileMatches.length > 0) {
// Split text around file patterns and process each segment
let lastIndex = 0;
fileMatches.forEach((fileMatch) => {
// Add text before the file pattern
if (fileMatch.index > lastIndex) {
const textBefore = text.substring(lastIndex, fileMatch.index).trim();
if (textBefore) {
processedParts.push({ type: 'text', content: textBefore });
}
}
// Add the file attachment badge (without showing "Added file:" text)
processedParts.push({
type: 'file',
content: '', // Empty - badge will show filename only
filepath: fileMatch.filepath
});
lastIndex = fileMatch.index + fileMatch.length;
});
// Add remaining text after the last file pattern
if (lastIndex < text.length) {
const textAfter = text.substring(lastIndex).trim();
if (textAfter) {
processedParts.push({ type: 'text', content: textAfter });
}
}
} else if (text) {
// This is regular text content
// No file patterns found, treat as regular text
processedParts.push({ type: 'text', content: text });
}
});
@@ -42,19 +81,6 @@ export function UserMessage({ content }: UserMessageProps) {
return null;
}
const getFileIcon = (filename: string) => {
const extension = filename.split('.').pop()?.toLowerCase();
// Return FileText icon for text-like files, File icon for others
const textExtensions = ['txt', 'md', 'json', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'xml', 'yml', 'yaml'];
if (extension && textExtensions.includes(extension)) {
return <FileText className="h-3 w-3" />;
}
return <File className="h-3 w-3" />;
};
const getFileName = (filepath: string) => {
return filepath.split('/').pop() || filepath;
};
@@ -63,18 +89,25 @@ export function UserMessage({ content }: UserMessageProps) {
<div className="space-y-2">
{processedParts.map((part, index) => {
if (part.type === 'text') {
// Only render text if it has content
if (!part.content.trim()) return null;
return (
<div key={index} className="whitespace-pre-wrap">
{part.content}
</div>
);
} else {
// Render file attachment badge (no "Added file:" text)
const filename = getFileName(part.filepath!);
return (
<div key={index} className="flex items-center gap-2">
<Badge variant="secondary" className="flex items-center gap-1.5 px-2 py-1">
{getFileIcon(filename)}
<span className="text-xs font-medium">{filename}</span>
<div key={index} className="flex items-center gap-2 max-w-full min-w-0">
<Badge variant="secondary" className="inline-flex items-center gap-1.5 px-2 py-1 max-w-full">
<span className="flex-shrink-0">
<Paperclip className="h-3 w-3" />
</span>
<span className="text-xs font-medium truncate min-w-0" title={filename}>
{filename}
</span>
</Badge>
</div>
);
+1 -18
View File
@@ -10,6 +10,7 @@ import { useFSPaths } from '@/hooks/useFSPaths';
import { useFS } from '@/hooks/useFS';
import { useToast } from '@/hooks/useToast';
import { useGitStatus } from '@/hooks/useGitStatus';
import { formatRelativeTime } from '@/lib/utils';
interface GitCommit {
oid: string;
@@ -336,24 +337,6 @@ ${commitsToRevert.map(c => {
}
}, [isOpen, loadGitHistory]);
const formatRelativeTime = (timestamp: number) => {
const now = Date.now();
const commitTime = timestamp * 1000;
const diffMs = now - commitTime;
const diffMinutes = Math.floor(diffMs / (1000 * 60));
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffMinutes < 60) {
return `${diffMinutes} minutes ago`;
} else if (diffHours < 24) {
return `${diffHours} hours ago`;
} else {
return `${diffDays} days ago`;
}
};
const getCommitMessageLines = (message: string) => {
const lines = message.split('\n').filter(line => line.trim() !== '');
return {
@@ -1,24 +1,35 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { AlertCircle } from 'lucide-react';
interface ShakespeareDeployFormProps {
host?: string;
projectId: string;
onSubdomainChange: (subdomain: string) => void;
onValidationChange?: (isValid: boolean) => void;
}
export function ShakespeareDeployForm({
host = 'shakespeare.wtf',
projectId,
onSubdomainChange,
onValidationChange,
}: ShakespeareDeployFormProps) {
const [subdomain, setSubdomain] = useState(projectId);
// Validate subdomain: no periods allowed (only single-level subdomains)
const hasPeriod = subdomain.includes('.');
const isValid = subdomain.trim() !== '' && !hasPeriod;
useEffect(() => {
onSubdomainChange(subdomain);
}, [subdomain, onSubdomainChange]);
useEffect(() => {
onValidationChange?.(isValid);
}, [isValid, onValidationChange]);
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
return (
@@ -30,7 +41,14 @@ export function ShakespeareDeployForm({
value={subdomain}
onChange={(e) => setSubdomain(e.target.value)}
placeholder={projectId}
className={hasPeriod ? 'border-destructive' : ''}
/>
{hasPeriod && (
<div className="flex items-start gap-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
<span>Subdomain cannot contain periods. Use hyphens instead (e.g., "nostr-radar").</span>
</div>
)}
<p className="text-xs text-muted-foreground">
Will deploy to: <span className="font-mono">{fullDomain}</span>
</p>
+88 -41
View File
@@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { TagInput } from '@/components/ui/tag-input';
import {
Dialog,
DialogContent,
@@ -33,12 +34,15 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@/hooks/useNostr';
import { useToast } from '@/hooks/useToast';
import { useAppContext } from '@/hooks/useAppContext';
import { useFS } from '@/hooks/useFS';
import { DotAI } from '@/lib/DotAI';
import { nip19 } from 'nostr-tools';
import {
createRepositoryAnnouncementEvent,
createRepositoryNaddr,
validateRepositoryAnnouncementData,
validateRepositoryId,
parseRepositoryAnnouncement,
} from '@/lib/announceRepository';
export interface AnnounceRepositoryResult {
@@ -74,6 +78,7 @@ export function AnnounceRepositoryDialog({
const [webUrls, setWebUrls] = useState<string[]>([]);
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
const [relays, setRelays] = useState<string[]>([]);
const [tTags, setTTags] = useState<string[]>([]);
const [earliestCommit, setEarliestCommit] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -88,6 +93,7 @@ export function AnnounceRepositoryDialog({
const { nostr } = useNostr();
const { toast } = useToast();
const { config } = useAppContext();
const { fs } = useFS();
const projectPath = `${projectsPath}/${projectId}`;
@@ -145,37 +151,57 @@ export function AnnounceRepositoryDialog({
.join(' ');
setName(defaultName);
// Only prepopulate if the arrays are empty (user hasn't made changes yet)
if (cloneUrls.length === 0 && relays.length === 0) {
// Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr)
if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) {
// Clone URLs: https://{server}/{npub}/{repo-id}.git
const npub = nip19.npubEncode(user.pubkey);
const cloneUrls = config.ngitServers.map(server =>
`https://${server}/${npub}/${defaultRepoId}.git`
);
setCloneUrls(cloneUrls);
// Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr)
if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) {
// Clone URLs: https://{server}/{npub}/{repo-id}.git
const npub = nip19.npubEncode(user.pubkey);
const cloneUrls = config.ngitServers.map(server =>
`https://${server}/${npub}/${defaultRepoId}.git`
);
setCloneUrls(cloneUrls);
// Relay URLs: wss://{server}
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
setRelays(relayUrls);
} else {
// Fallback to write relays if no ngitServers configured
const writeRelays = config.relayMetadata.relays
.filter(r => r.write)
.map(r => r.url);
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
}
// Relay URLs: wss://{server}
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
setRelays(relayUrls);
} else {
// Fallback to write relays if no ngitServers configured
const writeRelays = config.relayMetadata.relays
.filter(r => r.write)
.map(r => r.url);
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
}
// Prepopulate t-tags
const defaultTTags: string[] = ['shakespeare'];
// Try to read template.json to get template name
try {
const dotAI = new DotAI(fs, projectPath);
const template = await dotAI.readTemplate();
if (template?.name) {
// Convert template name to lowercase and add as t-tag
const templateTag = template.name.toLowerCase();
if (!defaultTTags.includes(templateTag)) {
defaultTTags.push(templateTag);
}
}
} catch (error) {
console.warn('Failed to read template for t-tags:', error);
}
setTTags(defaultTTags);
// Get earliest commit
await getEarliestCommit();
}, [projectId, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length]);
}, [projectId, projectPath, fs, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit]);
// Load existing repository data if editing
// Load existing repository data if editing, or prepopulate fields for new repos
useEffect(() => {
// Only run when dialog opens
if (!isOpen || isPrepopulated) return;
const loadExistingRepo = async () => {
if (!editNaddr || !isOpen) return;
if (!editNaddr) return;
try {
// Decode the naddr to get repository coordinates
@@ -209,21 +235,23 @@ export function AnnounceRepositoryDialog({
// Use the most recent event
const event = events.sort((a, b) => b.created_at - a.created_at)[0];
// Parse tags to populate form fields
const nameTag = event.tags.find(([name]) => name === 'name');
const descriptionTag = event.tags.find(([name]) => name === 'description');
const webTag = event.tags.find(([name]) => name === 'web');
const cloneTag = event.tags.find(([name]) => name === 'clone');
const relaysTag = event.tags.find(([name]) => name === 'relays');
const eucTag = event.tags.find(([name, , marker]) => name === 'r' && marker === 'euc');
// Parse the NIP-34 repository announcement
const parsed = parseRepositoryAnnouncement(event);
setRepoId(identifier);
setName(nameTag?.[1] || '');
setDescription(descriptionTag?.[1] || '');
setWebUrls(webTag ? webTag.slice(1) : []);
setCloneUrls(cloneTag ? cloneTag.slice(1) : []);
setRelays(relaysTag ? relaysTag.slice(1) : []);
setEarliestCommit(eucTag?.[1] || '');
setRepoId(parsed.identifier);
setName(parsed.name || '');
setDescription(parsed.description || '');
setWebUrls(parsed.webUrls);
setCloneUrls(parsed.httpsCloneUrls);
setRelays(parsed.relays);
setEarliestCommit(parsed.earliestCommit || '');
// Extract t-tags from the event
const extractedTTags = parsed.event.tags
.filter(([name]) => name === 't')
.map(([, value]) => value)
.filter((value): value is string => !!value);
setTTags(extractedTTags);
setIsPrepopulated(true);
} catch (error) {
@@ -236,13 +264,13 @@ export function AnnounceRepositoryDialog({
}
};
if (isOpen && editNaddr) {
if (editNaddr) {
loadExistingRepo();
} else if (isOpen && !isPrepopulated) {
} else {
prepopulateFields();
setIsPrepopulated(true);
}
}, [isOpen, isPrepopulated, prepopulateFields, editNaddr, nostr, config.relayMetadata, toast]);
}, [isOpen, isPrepopulated, editNaddr, nostr, config.relayMetadata, toast, prepopulateFields]);
const addWebUrl = () => {
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
@@ -317,6 +345,7 @@ export function AnnounceRepositoryDialog({
webUrls,
cloneUrls,
relays,
tTags,
earliestCommit,
});
@@ -389,6 +418,7 @@ export function AnnounceRepositoryDialog({
setWebUrls([]);
setCloneUrls([]);
setRelays(['wss://relay.nostr.band']);
setTTags([]);
setEarliestCommit('');
setError(null);
setNewWebUrl('');
@@ -414,7 +444,7 @@ export function AnnounceRepositoryDialog({
</DialogHeader>
<ScrollArea className="max-h-[60vh]">
<div className="space-y-6 pr-4">
<div className="space-y-6 p-1 pr-4">
{/* Error alert */}
{error && (
<Alert variant="destructive">
@@ -640,6 +670,23 @@ export function AnnounceRepositoryDialog({
</p>
</div>
{/* Category Tags (t-tags) */}
<div className="space-y-2">
<Label htmlFor="category-tags">Category Tags</Label>
<TagInput
id="category-tags"
value={tTags}
onChange={setTTags}
placeholder="e.g., nostr, social, web"
disabled={isCreating}
transformTag={(tag) => tag.trim().toLowerCase()}
allowDuplicates={false}
/>
<p className="text-xs text-muted-foreground">
Tags for categorizing your repository. Press space or comma to add a tag.
</p>
</div>
{/* Earliest Commit */}
<div className="space-y-2">
<Label htmlFor="earliest-commit">Earliest Unique Commit</Label>
+13 -4
View File
@@ -187,13 +187,23 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
object: currentRef,
});
toast({
title: 'Branch created',
description: `Created branch "${newBranchName}"`,
// Automatically check out the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName.trim(),
force: true,
});
// Close the dialog before showing the toast
setNewBranchName('');
setIsCreateDialogOpen(false);
// Show success toast indicating the branch was created and checked out
toast({
title: 'Branch created and checked out',
description: `Switched to new branch "${newBranchName.trim()}"`,
});
await loadBranches();
onBranchChange?.();
} catch (error) {
@@ -213,7 +223,6 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
await git.checkout({
dir: projectPath,
ref: branchName,
force: true,
});
toast({
+8 -8
View File
@@ -39,6 +39,7 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@/hooks/useNostr';
import { useAppContext } from '@/hooks/useAppContext';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
import { nip19 } from 'nostr-tools';
import type { GitCredential } from '@/contexts/GitSettingsContext';
@@ -717,21 +718,20 @@ export function PullRequestDialog({
const repoEvent = repoEvents[0];
console.log('Found repository announcement event:', repoEvent);
// Parse the NIP-34 repository announcement
const repoAnn = parseRepositoryAnnouncement(repoEvent);
// Get earliest unique commit from repository announcement
const eucTag = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc');
if (eucTag) {
earliestUniqueCommit = eucTag[1];
if (repoAnn.earliestCommit) {
earliestUniqueCommit = repoAnn.earliestCommit;
console.log('Found earliest unique commit:', earliestUniqueCommit);
} else {
console.warn('No euc tag found in repository announcement');
}
// Get relay hints from repository announcement
// Per NIP-34, all relays are in a single tag: ["relays", "wss://...", "wss://...", ...]
const relayTag = repoEvent.tags.find((t: string[]) => t[0] === 'relays');
if (relayTag && relayTag.length > 1) {
// Extract all relay URLs from the tag (skip the first element which is "relays")
publishRelays = relayTag.slice(1);
if (repoAnn.relays.length > 0) {
publishRelays = repoAnn.relays;
console.log('Publishing to repository relays:', publishRelays);
} else {
console.log('No relay hints in repository announcement, using configured relay');
+1 -1
View File
@@ -12,7 +12,7 @@ const AccordionItem = React.forwardRef<
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border-b", className)}
className={cn("border rounded-lg bg-card text-card-foreground shadow-sm", className)}
{...props}
/>
))
+1 -1
View File
@@ -11,7 +11,7 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
"peer h-4 w-4 shrink-0 rounded-xs border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
+1 -1
View File
@@ -17,7 +17,7 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:bg-border/20 dark:hover:bg-border/50 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
+256
View File
@@ -0,0 +1,256 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { TagInput } from './tag-input';
describe('TagInput', () => {
it('renders with placeholder when no tags', () => {
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
expect(input).toBeInTheDocument();
});
it('displays existing tags', () => {
const onChange = vi.fn();
render(
<TagInput
value={['tag1', 'tag2', 'tag3']}
onChange={onChange}
/>
);
expect(screen.getByText('tag1')).toBeInTheDocument();
expect(screen.getByText('tag2')).toBeInTheDocument();
expect(screen.getByText('tag3')).toBeInTheDocument();
});
it('adds tag on space key', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, 'newtag ');
expect(onChange).toHaveBeenCalledWith(['newtag']);
});
it('adds tag on comma key', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, 'newtag,');
expect(onChange).toHaveBeenCalledWith(['newtag']);
});
it('adds tag on Enter key', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, 'newtag{Enter}');
expect(onChange).toHaveBeenCalledWith(['newtag']);
});
it('removes last tag on Backspace when input is empty', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={['tag1', 'tag2']}
onChange={onChange}
/>
);
const input = screen.getByRole('textbox');
await user.click(input);
await user.keyboard('{Backspace}');
expect(onChange).toHaveBeenCalledWith(['tag1']);
});
it('removes tag when clicking X button', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={['tag1', 'tag2', 'tag3']}
onChange={onChange}
/>
);
const removeButtons = screen.getAllByRole('button');
await user.click(removeButtons[1]); // Remove tag2
expect(onChange).toHaveBeenCalledWith(['tag1', 'tag3']);
});
it('transforms tags using transformTag function', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
transformTag={(tag) => tag.toUpperCase()}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, 'lowercase ');
expect(onChange).toHaveBeenCalledWith(['LOWERCASE']);
});
it('prevents duplicate tags by default', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={['existing']}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByRole('textbox');
await user.type(input, 'existing ');
expect(onChange).not.toHaveBeenCalled();
});
it('allows duplicate tags when allowDuplicates is true', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={['existing']}
onChange={onChange}
allowDuplicates={true}
placeholder="Add tags..."
/>
);
const input = screen.getByRole('textbox');
await user.type(input, 'existing ');
expect(onChange).toHaveBeenCalledWith(['existing', 'existing']);
});
it('validates tags using validateTag function', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
validateTag={(tag) => tag.length >= 3}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
// Try adding tag that's too short
await user.type(input, 'ab ');
expect(onChange).not.toHaveBeenCalled();
// Add valid tag
await user.type(input, 'valid ');
expect(onChange).toHaveBeenCalledWith(['valid']);
});
it('does not add empty tags', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, ' '); // Just spaces
expect(onChange).not.toHaveBeenCalled();
});
it('focuses input when container is clicked', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const { container } = render(
<TagInput
value={['tag1']}
onChange={onChange}
/>
);
const inputContainer = container.querySelector('div');
if (inputContainer) {
await user.click(inputContainer);
}
const input = screen.getByRole('textbox');
expect(input).toHaveFocus();
});
it('is disabled when disabled prop is true', () => {
const onChange = vi.fn();
render(
<TagInput
value={['tag1']}
onChange={onChange}
disabled={true}
/>
);
const input = screen.getByRole('textbox');
expect(input).toBeDisabled();
});
});
+172
View File
@@ -0,0 +1,172 @@
import * as React from 'react';
import { X } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
export interface TagInputProps
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'> {
value: string[];
onChange: (tags: string[]) => void;
/** Character(s) that trigger tag creation. Default: [' ', ','] */
delimiters?: string[];
/** Transform tag before adding (e.g., toLowerCase). Default: (tag) => tag.trim() */
transformTag?: (tag: string) => string;
/** Validate tag before adding. Return false to reject. */
validateTag?: (tag: string) => boolean;
/** Allow duplicate tags. Default: false */
allowDuplicates?: boolean;
}
export const TagInput = React.forwardRef<HTMLInputElement, TagInputProps>(
(
{
className,
value = [],
onChange,
delimiters = [' ', ','],
transformTag = (tag) => tag.trim(),
validateTag,
allowDuplicates = false,
disabled,
placeholder,
...props
},
ref
) => {
const [inputValue, setInputValue] = React.useState('');
const inputRef = React.useRef<HTMLInputElement>(null);
const containerRef = React.useRef<HTMLDivElement>(null);
// Combine external ref with internal ref
React.useImperativeHandle(ref, () => inputRef.current!);
const addTag = (tag: string) => {
const transformed = transformTag(tag);
if (!transformed) return;
// Check for duplicates if not allowed
if (!allowDuplicates && value.includes(transformed)) {
setInputValue('');
return;
}
// Validate if validator provided
if (validateTag && !validateTag(transformed)) {
setInputValue('');
return;
}
onChange([...value, transformed]);
setInputValue('');
};
const removeTag = (index: number) => {
onChange(value.filter((_, i) => i !== index));
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
// Handle delimiters (space, comma, etc.)
if (delimiters.includes(e.key)) {
e.preventDefault();
if (inputValue.trim()) {
addTag(inputValue);
}
return;
}
// Handle Enter key
if (e.key === 'Enter') {
e.preventDefault();
if (inputValue.trim()) {
addTag(inputValue);
}
return;
}
// Handle Backspace - delete last tag if input is empty
if (e.key === 'Backspace' && !inputValue && value.length > 0) {
e.preventDefault();
removeTag(value.length - 1);
return;
}
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
// Check if any delimiter was typed
const hasDelimiter = delimiters.some(delimiter => newValue.includes(delimiter));
if (hasDelimiter) {
// Extract the part before the delimiter
const parts = newValue.split(new RegExp(`[${delimiters.map(d => d === ' ' ? '\\s' : d).join('')}]`));
const tagToAdd = parts[0];
if (tagToAdd.trim()) {
addTag(tagToAdd);
}
} else {
setInputValue(newValue);
}
};
const handleContainerClick = () => {
inputRef.current?.focus();
};
return (
<div
ref={containerRef}
className={cn(
'flex min-h-10 w-full flex-wrap gap-1.5 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background',
'focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2',
disabled && 'cursor-not-allowed opacity-50',
className
)}
onClick={handleContainerClick}
>
{/* Render tags */}
{value.map((tag, index) => (
<Badge
key={index}
variant="secondary"
className="gap-1 pr-1.5 pl-2.5 py-0.5 h-6"
>
<span>{tag}</span>
<button
type="button"
className="ml-1 rounded-sm hover:bg-secondary-foreground/20 focus:outline-none focus:ring-1 focus:ring-ring"
onClick={(e) => {
e.stopPropagation();
removeTag(index);
}}
disabled={disabled}
>
<X className="h-3 w-3" />
<span className="sr-only">Remove {tag}</span>
</button>
</Badge>
))}
{/* Input field */}
<input
ref={inputRef}
type="text"
value={inputValue}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
disabled={disabled}
placeholder={value.length === 0 ? placeholder : undefined}
className={cn(
'flex-1 min-w-[120px] bg-transparent outline-none placeholder:text-muted-foreground',
'disabled:cursor-not-allowed'
)}
{...props}
/>
</div>
);
}
);
TagInput.displayName = 'TagInput';
+14
View File
@@ -2,15 +2,27 @@ import { createContext } from 'react';
export interface AIProvider {
id: string;
name: string;
baseURL: string;
apiKey?: string;
nostr?: boolean;
proxy?: boolean;
}
export interface MCPServer {
type: 'streamable-http';
url: string;
headers?: Record<string, string>;
}
export interface MCPServers {
[key: string]: MCPServer;
}
export interface AISettings {
providers: AIProvider[];
recentlyUsedModels: string[];
mcpServers?: MCPServers;
}
export interface AISettingsContextType {
@@ -20,6 +32,8 @@ export interface AISettingsContextType {
removeProvider: (id: string) => void;
setProviders: (providers: AIProvider[]) => void;
addRecentlyUsedModel: (modelId: string) => void;
setMCPServer: (name: string, server: MCPServer) => void;
removeMCPServer: (name: string) => void;
isConfigured: boolean;
}
+21 -2
View File
@@ -9,13 +9,22 @@ export interface RelayMetadata {
updatedAt: number;
}
export interface ProjectTemplate {
/** Template name */
name: string;
/** Template description */
description: string;
/** Git repository URL */
url: string;
}
export interface AppConfig {
/** Current theme */
theme: Theme;
/** NIP-65 relay list metadata */
relayMetadata: RelayMetadata;
/** Git repository URL to use as project template */
projectTemplate: string;
/** Available project templates */
templates: ProjectTemplate[];
/** ESM CDN URL for package imports */
esmUrl: string;
/** HTTP proxy used to bypass CORS for AI and Git operations */
@@ -40,15 +49,25 @@ export interface AppConfig {
fsPathTmp: string;
/** VFS path for plugins directory */
fsPathPlugins: string;
/** VFS path for templates directory */
fsPathTemplates: string;
/** Sentry DSN for error reporting (empty string = disabled) */
sentryDsn: string;
/** Whether the user has enabled Sentry error reporting */
sentryEnabled: boolean;
/** System prompt EJS template */
systemPrompt?: string;
/** Whether the global floating chat is enabled */
globalChatEnabled?: boolean;
/** Custom system prompt for global chat */
globalChatSystemPrompt?: 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;
}
+23
View File
@@ -0,0 +1,23 @@
import { createContext } from 'react';
export interface GlobalChatMessage {
id: string;
role: 'user' | 'assistant';
content: string;
timestamp: number;
}
export interface GlobalChatContextType {
messages: GlobalChatMessage[];
isOpen: boolean;
isLoading: boolean;
hasUnread: boolean;
providerModel: string;
setProviderModel: (model: string) => void;
sendMessage: (content: string, providerModel: string) => Promise<void>;
stopGeneration: () => void;
clearMessages: () => void;
setIsOpen: (open: boolean) => void;
}
export const GlobalChatContext = createContext<GlobalChatContextType | undefined>(undefined);
+4 -1
View File
@@ -114,7 +114,10 @@ export function useAIChat({
}, [projectId]);
// Actions
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
const sendMessage = useCallback(async (
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
providerModel: string
) => {
try {
await initSession();
await sessionManager.sendMessage(projectId, content, providerModel);
-501
View File
@@ -1,501 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useAIProjectId } from './useAIProjectId';
import { useAISettings } from './useAISettings';
import { useCurrentUser } from './useCurrentUser';
import { useAppContext } from './useAppContext';
import { useProjectsManager } from './useProjectsManager';
import { createAIClient } from '@/lib/ai-client';
import { parseProviderModel } from '@/lib/parseProviderModel';
import type { ProjectsManager } from '@/lib/ProjectsManager';
// Mock the hooks and dependencies
vi.mock('./useAISettings');
vi.mock('./useCurrentUser');
vi.mock('./useAppContext');
vi.mock('./useProjectsManager');
vi.mock('@/lib/ai-client');
vi.mock('@/lib/parseProviderModel');
describe('useAIProjectId', () => {
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseCurrentUser = vi.mocked(useCurrentUser);
const mockUseAppContext = vi.mocked(useAppContext);
const mockUseProjectsManager = vi.mocked(useProjectsManager);
const mockCreateAIClient = vi.mocked(createAIClient);
const mockParseProviderModel = vi.mocked(parseProviderModel);
beforeEach(() => {
vi.clearAllMocks();
// Mock fetch globally
global.fetch = vi.fn();
// Mock useCurrentUser to return undefined user by default
mockUseCurrentUser.mockReturnValue({
user: undefined,
users: [],
});
// Mock useAppContext
mockUseAppContext.mockReturnValue({
config: {
theme: 'dark',
relayMetadata: {
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://github.com/example/template',
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
sentryDsn: '',
sentryEnabled: false,
},
updateConfig: vi.fn(),
});
// Mock useProjectsManager
const mockProjectsManager = {
getProject: vi.fn().mockResolvedValue(null),
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
// Mock parseProviderModel
mockParseProviderModel.mockReturnValue({
provider: { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
model: 'gpt-4',
});
// Mock createAIClient
const mockCompletion = {
choices: [{ message: { content: 'test-project-name' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
});
it('should return not configured when AI settings are not configured', () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
expect(result.current.isConfigured).toBe(false);
expect(result.current.isLoading).toBe(false);
});
it('should throw error when trying to generate ID without configuration', async () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
await expect(result.current.generateProjectId('openai/gpt-4', 'test prompt')).rejects.toThrow(
'AI settings not configured'
);
});
it('should throw error when prompt is empty', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
await expect(result.current.generateProjectId('openai/gpt-4', '')).rejects.toThrow(
'Prompt cannot be empty'
);
});
it('should have configured status when providers are available', () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
expect(result.current.isConfigured).toBe(true);
expect(result.current.isLoading).toBe(false);
});
it('should successfully generate project ID', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('test-project-name');
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
]);
expect(mockCreateAIClient).toHaveBeenCalledWith(
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
undefined,
'https://proxy.example.com/{href}'
);
});
it('should fallback to untitled when project exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI response - returns a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'existing-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValueOnce(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - first call returns project (exists), second returns null (untitled is available)
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'existing-project', name: 'Existing Project', path: '/projects/existing-project', lastModified: new Date() })
.mockResolvedValueOnce(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(2);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'existing-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled-1 when untitled exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'taken-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - taken-project exists, untitled exists, untitled-1 is available
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
.mockResolvedValueOnce(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled-1');
expect(mockGetProject).toHaveBeenCalledTimes(3);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled when AI generates too long name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return a very long project name (over 50 characters)
const mockCompletion = {
choices: [{ message: { content: 'this-is-a-very-long-project-name-that-exceeds-the-maximum-allowed-length-limit' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - untitled is available
const mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(1);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled when AI generates invalid name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return an invalid project name (doesn't match regex)
const mockCompletion = {
choices: [{ message: { content: 'Invalid Project Name!' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - untitled is available
const mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(1);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled-2 when untitled and untitled-1 exist', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'taken-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - taken-project exists, untitled exists, untitled-1 exists, untitled-2 is available
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled-1', name: 'Untitled 1', path: '/projects/untitled-1', lastModified: new Date() })
.mockResolvedValueOnce(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled-2');
expect(mockGetProject).toHaveBeenCalledTimes(4);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
expect(mockGetProject).toHaveBeenNthCalledWith(4, 'untitled-2');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should handle loading state correctly', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
expect(result.current.isLoading).toBe(false);
const promise = result.current.generateProjectId('openai/gpt-4', 'Test prompt');
await waitFor(() => {
expect(result.current.isLoading).toBe(false); // Should be false after completion
});
await promise;
});
});
-96
View File
@@ -1,96 +0,0 @@
import { useState, useCallback } from 'react';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { createAIClient } from '@/lib/ai-client';
import { parseProviderModel } from '@/lib/parseProviderModel';
interface UseAIProjectIdOptions {
onError?: (error: string) => void;
}
export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
const [isLoading, setIsLoading] = useState(false);
const { settings, isConfigured } = useAISettings();
const { user } = useCurrentUser();
const { config } = useAppContext();
const projectsManager = useProjectsManager();
const generateProjectId = useCallback(async (providerModel: string, prompt: string): Promise<string> => {
if (!isConfigured) {
throw new Error('AI settings not configured');
}
if (!prompt.trim()) {
throw new Error('Prompt cannot be empty');
}
setIsLoading(true);
try {
// Initialize OpenAI client
const { model, provider } = parseProviderModel(providerModel, settings.providers);
const openai = createAIClient(provider, user, config.corsProxy);
const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`;
const messages = [
{ role: 'system' as const, content: systemPrompt },
{ role: 'user' as const, content: prompt }
];
// Try once to generate a project name
const completion = await openai.chat.completions.create({
model,
messages,
temperature: 1,
});
const projectId = completion.choices[0]?.message?.content?.trim();
if (!projectId) {
throw new Error('Failed to generate project name');
}
// Validate the generated ID directly (no conversion)
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (projectId.length <= 50 && validIdRegex.test(projectId)) {
// Check if project exists
const existingProject = await projectsManager.getProject(projectId);
if (existingProject === null) {
// Valid and unique project ID
return projectId;
}
}
// If we reach here, either the regex failed or the project already exists
// Fall back to "untitled" with number suffixes
let fallbackId = 'untitled';
let counter = 1;
// Check if base "untitled" exists
let existingProject = await projectsManager.getProject(fallbackId);
// Keep incrementing until we find an available name
while (existingProject !== null) {
fallbackId = `untitled-${counter}`;
existingProject = await projectsManager.getProject(fallbackId);
counter++;
}
return fallbackId;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
onError?.(errorMessage);
throw error;
} finally {
setIsLoading(false);
}
}, [isConfigured, settings, onError, user, projectsManager, config.corsProxy]);
return {
generateProjectId,
isLoading,
isConfigured
};
}
+43
View File
@@ -0,0 +1,43 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
/**
* Hook to get the user's contact list (kind 3 follow list)
* Returns an array of pubkeys that the user follows
*/
export function useContacts(userPubkey?: string) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'contacts', userPubkey],
queryFn: async (): Promise<string[]> => {
if (!userPubkey) {
return [];
}
// Get the user's contact list (kind 3)
const events = await nostr.query([{
kinds: [3],
authors: [userPubkey],
limit: 1,
}], { signal: AbortSignal.timeout(3000) });
if (events.length === 0) {
return [];
}
// Get the most recent contact list event
const contactList = events.sort((a, b) => b.created_at - a.created_at)[0];
// Extract pubkeys from 'p' tags
const followedPubkeys = contactList.tags
.filter(tag => tag[0] === 'p' && tag[1])
.map(tag => tag[1]);
return followedPubkeys;
},
enabled: !!userPubkey,
staleTime: 60000, // 1 minute
refetchInterval: 300000, // 5 minutes
});
}
+2
View File
@@ -17,5 +17,7 @@ export function useFSPaths() {
tmpPath: config.fsPathTmp,
/** Plugins directory path (default: /plugins) */
pluginsPath: config.fsPathPlugins,
/** Templates directory path (default: /templates) */
templatesPath: config.fsPathTemplates,
};
}
+92
View File
@@ -0,0 +1,92 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
import type { Repository } from './useUserRepositories';
// Kind 30617 for repository announcements (NIP-34)
const REPOSITORY_KIND = 30617;
/**
* Hook to get repositories from a list of followed users
*/
export function useFollowedRepositories(followedPubkeys: string[] = []) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'followed-repositories', followedPubkeys.sort().join(',')],
queryFn: async (): Promise<Repository[]> => {
if (followedPubkeys.length === 0) {
return [];
}
// Get all repository announcements from followed users
const events = await nostr.query([{
kinds: [REPOSITORY_KIND],
authors: followedPubkeys,
limit: 500, // Increased limit to get more repos from follows
}], { signal: AbortSignal.timeout(5000) });
// Process repository events
const repositories: Repository[] = [];
const repoMap = new Map<string, NostrEvent>();
// Group by author+d-tag to get latest version of each repo
for (const event of events) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const key = `${event.pubkey}:${dTag}`;
const existing = repoMap.get(key);
if (!existing || event.created_at > existing.created_at) {
repoMap.set(key, event);
}
}
// Convert to Repository objects
for (const [, event] of repoMap) {
try {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
// Filter out invalid repositories without clone URLs
if (cloneUrls.length === 0) {
console.warn('Skipping repository without clone URLs:', dTag);
continue;
}
repositories.push({
...event,
repoId: dTag,
name,
description,
webUrls,
cloneUrls,
relays,
maintainers,
repoTags,
earliestUniqueCommit,
isPersonalFork,
});
} catch (error) {
console.warn('Failed to parse repository:', error);
}
}
// Sort by created_at (newest first)
return repositories.sort((a, b) => b.created_at - a.created_at);
},
enabled: followedPubkeys.length > 0,
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
+503
View File
@@ -0,0 +1,503 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useGenerateProjectInfo } from './useGenerateProjectInfo';
import { useAISettings } from './useAISettings';
import { useCurrentUser } from './useCurrentUser';
import { useAppContext } from './useAppContext';
import { useProjectsManager } from './useProjectsManager';
import { createAIClient } from '@/lib/ai-client';
import { parseProviderModel } from '@/lib/parseProviderModel';
import type { ProjectsManager } from '@/lib/ProjectsManager';
import type { ProjectTemplate } from '@/contexts/AppContext';
// Mock the hooks and dependencies
vi.mock('./useAISettings');
vi.mock('./useCurrentUser');
vi.mock('./useAppContext');
vi.mock('./useProjectsManager');
vi.mock('@/lib/ai-client');
vi.mock('@/lib/parseProviderModel');
describe('useGenerateProjectInfo', () => {
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseCurrentUser = vi.mocked(useCurrentUser);
const mockUseAppContext = vi.mocked(useAppContext);
const mockUseProjectsManager = vi.mocked(useProjectsManager);
const mockCreateAIClient = vi.mocked(createAIClient);
const mockParseProviderModel = vi.mocked(parseProviderModel);
const defaultTemplates: ProjectTemplate[] = [
{
name: "MKStack",
description: "Build Nostr clients with React.",
url: "https://gitlab.com/soapbox-pub/mkstack.git"
},
{
name: "VanillaJS",
description: "Simple vanilla JavaScript template.",
url: "https://github.com/example/vanilla-template.git"
}
];
let mockGetProject: ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.clearAllMocks();
// Mock fetch globally
global.fetch = vi.fn();
// Mock useCurrentUser to return undefined user by default
mockUseCurrentUser.mockReturnValue({
user: undefined,
users: [],
});
// Mock useAppContext
const config = {
theme: 'dark' as const,
relayMetadata: {
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
updatedAt: 0,
},
templates: defaultTemplates,
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',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
mockUseAppContext.mockReturnValue({
config,
defaultConfig: config,
updateConfig: vi.fn(),
});
// Mock useProjectsManager
mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
// Mock parseProviderModel
mockParseProviderModel.mockReturnValue({
provider: { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
model: 'gpt-4',
});
// Mock createAIClient
const mockCompletion = {
choices: [{
message: {
tool_calls: [{
type: 'function' as const,
function: {
name: 'create_project',
arguments: JSON.stringify({
project_name: 'test-project-name',
template_url: 'https://gitlab.com/soapbox-pub/mkstack.git'
})
}
}]
}
}]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
});
it('should return not configured when AI settings are not configured', () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
expect(result.current.isConfigured).toBe(false);
expect(result.current.isLoading).toBe(false);
});
it('should throw error when trying to generate without configuration', async () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
await expect(result.current.generateProjectInfo('openai/gpt-4', 'test prompt')).rejects.toThrow(
'AI settings not configured'
);
});
it('should throw error when prompt is empty', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
await expect(result.current.generateProjectInfo('openai/gpt-4', '')).rejects.toThrow(
'Prompt cannot be empty'
);
});
it('should throw error when no templates are configured', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock config with no templates
const config = {
theme: 'dark' as const,
relayMetadata: {
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
updatedAt: 0,
},
templates: [],
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',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
mockUseAppContext.mockReturnValue({
config,
defaultConfig: config,
updateConfig: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
await expect(result.current.generateProjectInfo('openai/gpt-4', 'test prompt')).rejects.toThrow(
'No templates configured'
);
});
it('should successfully generate project info with template selection', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'A social media app for developers');
expect(projectInfo).toEqual({
projectId: 'test-project-name',
template: {
name: 'MKStack',
description: 'Build Nostr clients with React.',
url: 'https://gitlab.com/soapbox-pub/mkstack.git'
}
});
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
]);
expect(mockCreateAIClient).toHaveBeenCalledWith(
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
undefined,
'https://proxy.example.com/{href}'
);
});
it('should fallback to first template when AI selects invalid template URL', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock AI to return invalid template URL
const mockCompletion = {
choices: [{
message: {
tool_calls: [{
type: 'function' as const,
function: {
name: 'create_project',
arguments: JSON.stringify({
project_name: 'test-project',
template_url: 'https://invalid-url.com/template.git'
})
}
}]
}
}]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(projectInfo.projectId).toBe('untitled');
});
it('should increment AI-generated ID when project already exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Reset and override the mock to return project on first call, null on second
mockGetProject.mockReset();
mockGetProject
.mockResolvedValueOnce({ id: 'test-project-name', name: 'Test Project', path: '/projects/test-project-name', lastModified: new Date() })
.mockResolvedValue(null);
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
expect(projectInfo.projectId).toBe('test-project-name-1');
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(mockGetProject).toHaveBeenCalledTimes(2);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1');
});
it('should increment multiple times when necessary', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Reset and override the mock - base and -1 exist, -2 is available
mockGetProject.mockReset();
mockGetProject
.mockResolvedValueOnce({ id: 'test-project-name', name: 'Test Project', path: '/projects/test-project-name', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'test-project-name-1', name: 'Test Project 1', path: '/projects/test-project-name-1', lastModified: new Date() })
.mockResolvedValue(null);
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
expect(projectInfo.projectId).toBe('test-project-name-2');
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(mockGetProject).toHaveBeenCalledTimes(3);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'test-project-name-2');
});
it('should handle loading state correctly', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
expect(result.current.isLoading).toBe(false);
const promise = result.current.generateProjectInfo('openai/gpt-4', 'Test prompt');
await waitFor(() => {
expect(result.current.isLoading).toBe(false); // Should be false after completion
});
await promise;
});
it('should select second template when AI chooses it', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock AI to select the second template
const mockCompletion = {
choices: [{
message: {
tool_calls: [{
type: 'function' as const,
function: {
name: 'create_project',
arguments: JSON.stringify({
project_name: 'vanilla-app',
template_url: 'https://github.com/example/vanilla-template.git'
})
}
}]
}
}]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'A simple vanilla JS app');
expect(projectInfo).toEqual({
projectId: 'vanilla-app',
template: {
name: 'VanillaJS',
description: 'Simple vanilla JavaScript template.',
url: 'https://github.com/example/vanilla-template.git'
}
});
});
});
+187
View File
@@ -0,0 +1,187 @@
import { useState, useCallback } from 'react';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { createAIClient } from '@/lib/ai-client';
import { parseProviderModel } from '@/lib/parseProviderModel';
import type { ChatCompletionMessageParam, ChatCompletionTool } from 'openai/resources/chat/completions';
interface UseGenerateProjectInfoOptions {
onError?: (error: string) => void;
}
interface ProjectInfo {
projectId: string;
template: {
name: string;
description: string;
url: string;
};
}
export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOptions = {}) {
const [isLoading, setIsLoading] = useState(false);
const { settings, isConfigured } = useAISettings();
const { user } = useCurrentUser();
const { config } = useAppContext();
const projectsManager = useProjectsManager();
// Helper function to generate incremented project name
// Note: This assumes the baseId already exists (caller has verified this)
const generateIncrementedId = useCallback(async (baseId: string, template: { url: string; name: string; description: string }, baseExists: boolean = true): Promise<ProjectInfo> => {
// If base doesn't exist, just use it
if (!baseExists) {
const existingProject = await projectsManager.getProject(baseId);
if (existingProject === null) {
return {
projectId: baseId,
template,
};
}
}
// Start incrementing from -1
let counter = 1;
let fallbackId = `${baseId}-${counter}`;
let existingProject = await projectsManager.getProject(fallbackId);
// Keep incrementing until we find an available name
while (existingProject !== null) {
counter++;
fallbackId = `${baseId}-${counter}`;
existingProject = await projectsManager.getProject(fallbackId);
}
return {
projectId: fallbackId,
template,
};
}, [projectsManager]);
const generateProjectInfo = useCallback(async (providerModel: string, prompt: string): Promise<ProjectInfo> => {
if (!isConfigured) {
throw new Error('AI settings not configured');
}
if (!prompt.trim()) {
throw new Error('Prompt cannot be empty');
}
if (config.templates.length === 0) {
throw new Error('No templates configured');
}
setIsLoading(true);
try {
// Initialize OpenAI client
const { model, provider } = parseProviderModel(providerModel, settings.providers);
const openai = createAIClient(provider, user, config.corsProxy);
// Create project creation tool
const createProjectTool: ChatCompletionTool = {
type: 'function',
function: {
name: 'create_project',
description: 'Create a new project by choosing a name and selecting the most appropriate template. You must call this tool to create the project.',
parameters: {
type: 'object',
properties: {
project_name: {
type: 'string',
description: 'A short, unique, and memorable name for the project. Should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens.',
},
template_url: {
type: 'string',
description: `The Git URL of the selected template. Must be one of: ${config.templates.map(t => t.url).join(', ')}`,
enum: config.templates.map(t => t.url),
},
},
required: ['project_name', 'template_url'],
},
},
};
const systemPrompt = `You are a product expert helping users create new projects. Given the user's project description, you must:
1. Generate a short, unique, and memorable name for their product or brand. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.
2. Select the most appropriate template from the available options:
${config.templates.map(t => ` - ${t.name}: ${t.description} (${t.url})`).join('\n')}
You MUST call the create_project tool with your choices.`;
const messages: ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: prompt }
];
// Call AI with tool
const completion = await openai.chat.completions.create({
model,
messages,
tools: [createProjectTool],
tool_choice: { type: 'function', function: { name: 'create_project' } },
temperature: 1,
});
const toolCall = completion.choices[0]?.message?.tool_calls?.[0];
if (!toolCall || toolCall.type !== 'function' || toolCall.function.name !== 'create_project') {
throw new Error('AI failed to create the project');
}
const args = JSON.parse(toolCall.function.arguments);
const templateUrl = args.template_url as string;
const projectId = args.project_name as string;
// Validate template URL
const selectedTemplate = config.templates.find(t => t.url === templateUrl);
if (!selectedTemplate) {
// Fallback to first template if invalid URL selected
console.warn(`Invalid template URL selected: ${templateUrl}, falling back to first template`);
return await generateIncrementedId('untitled', config.templates[0], false);
}
// Validate the generated project ID
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (projectId && projectId.length <= 50 && validIdRegex.test(projectId)) {
// Check if project exists
const existingProject = await projectsManager.getProject(projectId);
if (existingProject === null) {
// Valid and unique project ID
return {
projectId,
template: selectedTemplate,
};
}
// Project already exists - increment the AI-generated ID (baseExists = true)
return await generateIncrementedId(projectId, selectedTemplate, true);
}
// If we reach here, the regex failed - fall back to "untitled" with number suffixes
return await generateIncrementedId('untitled', selectedTemplate, false);
} catch (error) {
// On any error, fall back to first template with untitled name
console.error('Error generating project info:', error);
if (config.templates.length === 0) {
const errorMessage = 'No templates configured';
onError?.(errorMessage);
throw new Error(errorMessage);
}
return await generateIncrementedId('untitled', config.templates[0], false);
} finally {
setIsLoading(false);
}
}, [isConfigured, settings, onError, user, projectsManager, config.corsProxy, config.templates, generateIncrementedId]);
return {
generateProjectInfo,
isLoading,
isConfigured
};
}
+2 -1
View File
@@ -37,7 +37,7 @@ function createWrapper(corsProxy: string) {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: 'https://gitlab.com/soapbox-pub/mkstack.git' }],
esmUrl: 'https://esm.test',
corsProxy,
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
@@ -49,6 +49,7 @@ function createWrapper(corsProxy: string) {
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
+720
View File
@@ -0,0 +1,720 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useGitFetch } from './useGitFetch';
import { TestApp } from '@/test/TestApp';
// Create mocks that can be reconfigured per test
const mockGit = {
findRoot: vi.fn(),
listRemotes: vi.fn(),
currentBranch: vi.fn(),
resolveRef: vi.fn(),
fetch: vi.fn(),
};
const mockToast = vi.fn();
const mockInvalidateQueries = vi.fn();
// Mock the git operations
vi.mock('./useGit', () => ({
useGit: () => ({
git: mockGit,
}),
}));
vi.mock('./useGitSettings', () => ({
useGitSettings: () => ({
settings: {
credentials: [],
},
}),
}));
vi.mock('./useFSPaths', () => ({
useFSPaths: () => ({
projectsPath: '/projects',
}),
}));
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,
});
// When projectId is null, the query is disabled and won't fetch
// So we just check the initial state
expect(result.current.data).toBeUndefined();
expect(result.current.isLoading).toBe(false);
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)
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',
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,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
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);
});
});
});
+362
View File
@@ -0,0 +1,362 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useGit } from './useGit';
import { useFSPaths } from './useFSPaths';
import { useGitSettings } from './useGitSettings';
import { useToast } from './useToast';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { useEffect, useRef } from 'react';
interface FetchResult {
defaultBranch: string | null;
defaultBranchOid: string | null;
currentBranch: string | null;
currentBranchOid: string | null;
fetchedAt: number;
hasChanges: boolean;
remoteUrl: string | null;
}
/**
* Hook to fetch updates from remote repository and detect changes.
* Polls every 60 seconds and shows toast notifications when changes are detected.
*
* @param projectId - The project ID to fetch for
* @returns Query result with manual refetch capability
*/
export function useGitFetch(projectId: string | null) {
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { settings } = useGitSettings();
const { toast } = useToast();
const queryClient = useQueryClient();
// Track previous state to detect changes
const previousStateRef = useRef<{
defaultBranchOid: string | null;
currentBranchOid: string | null;
} | null>(null);
const query = useQuery({
queryKey: ['git-fetch', projectId],
queryFn: async (): Promise<FetchResult> => {
console.log('=== GIT FETCH STARTING ===');
console.log('Project ID:', projectId);
if (!projectId) {
console.log('No project ID, returning empty result');
return {
defaultBranch: null,
defaultBranchOid: null,
currentBranch: null,
currentBranchOid: null,
fetchedAt: Date.now(),
hasChanges: false,
remoteUrl: null,
};
}
try {
const cwd = `${projectsPath}/${projectId}`;
console.log('Working directory:', cwd);
// Check if we're in a git repository
try {
await git.findRoot({ filepath: cwd });
console.log('Git repository found');
} catch {
console.log('Not a git repository');
return {
defaultBranch: null,
defaultBranchOid: null,
currentBranch: null,
currentBranchOid: null,
fetchedAt: Date.now(),
hasChanges: false,
remoteUrl: null,
};
}
// Get remotes
const remotes = await git.listRemotes({ dir: cwd });
console.log('Remotes found:', remotes);
if (remotes.length === 0) {
console.log('No remotes configured');
return {
defaultBranch: null,
defaultBranchOid: null,
currentBranch: null,
currentBranchOid: null,
fetchedAt: Date.now(),
hasChanges: false,
remoteUrl: null,
};
}
const remote = remotes[0]; // Use first remote (usually 'origin')
const remoteUrl = remote.url || null;
console.log('Using remote:', remote.remote, 'URL:', remoteUrl);
if (!remoteUrl) {
console.log('No remote URL found');
return {
defaultBranch: null,
defaultBranchOid: null,
currentBranch: null,
currentBranchOid: null,
fetchedAt: Date.now(),
hasChanges: false,
remoteUrl: null,
};
}
// Get credentials for authentication
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
console.log('Credentials found:', !!credentials);
// Get current branch before fetch
let currentBranch: string | null = null;
try {
const branch = await git.currentBranch({
dir: cwd,
fullname: false,
});
currentBranch = (branch && branch.trim() !== '') ? branch : null;
console.log('Current branch:', currentBranch);
} catch (error) {
console.warn('Could not get current branch:', error);
}
// Store OIDs before fetch
let beforeDefaultOid: string | null = null;
let beforeCurrentOid: string | null = null;
// Get default branch from local symbolic ref
let defaultBranch: string | null = null;
try {
console.log('Reading default branch from local symbolic ref...');
// Read the symbolic ref file directly
// The file contains something like: "ref: refs/remotes/origin/main"
try {
const symbolicRefContent = await git.resolveRef({
dir: cwd,
ref: `remotes/${remote.remote}/HEAD`,
depth: 1,
});
// Remove "ref: " prefix and extract the branch name
// Content looks like: "ref: refs/remotes/origin/main"
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
if (match) {
defaultBranch = match[1].trim();
console.log('Default branch from local symbolic ref:', defaultBranch);
} else {
console.log('Could not get default branch from local symbolic ref value:', refValue);
}
} catch {
console.log('No local symbolic ref found, will be set after fetch');
}
// If we have a default branch, try to get its OID before fetch
if (defaultBranch) {
try {
beforeDefaultOid = await git.resolveRef({
dir: cwd,
ref: `${remote.remote}/${defaultBranch}`,
});
console.log('Default branch OID before fetch:', beforeDefaultOid);
} catch {
console.log('Remote default branch not in local repo yet');
}
}
} catch (error) {
console.warn('Could not read default branch from local data:', error);
}
// Get current branch OID before fetch
if (currentBranch) {
try {
beforeCurrentOid = await git.resolveRef({
dir: cwd,
ref: `${remote.remote}/${currentBranch}`,
});
console.log('Current branch OID before fetch:', beforeCurrentOid);
} catch {
console.log('Remote current branch not in local repo yet');
}
}
// Perform fetch
try {
console.log('Fetching from remote...');
await git.fetch({
dir: cwd,
remote: remote.remote,
...(credentials && {
onAuth: () => ({
username: credentials.username,
password: credentials.password,
}),
}),
});
console.log('Fetch completed successfully');
} catch (error) {
console.error('Failed to fetch from remote:', error);
throw error;
}
// Get OIDs after fetch
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({
dir: cwd,
ref: `${remote.remote}/${defaultBranch}`,
});
console.log('Default branch OID after fetch:', afterDefaultOid);
} catch {
console.log('Could not resolve default branch after fetch');
}
}
if (currentBranch) {
try {
afterCurrentOid = await git.resolveRef({
dir: cwd,
ref: `${remote.remote}/${currentBranch}`,
});
console.log('Current branch OID after fetch:', afterCurrentOid);
} catch {
console.log('Could not resolve current branch after fetch');
}
}
// Detect changes
const defaultBranchChanged = beforeDefaultOid !== null &&
afterDefaultOid !== null &&
beforeDefaultOid !== afterDefaultOid;
const currentBranchChanged = beforeCurrentOid !== null &&
afterCurrentOid !== null &&
beforeCurrentOid !== afterCurrentOid &&
currentBranch !== defaultBranch; // Don't double-report if they're the same
const hasChanges = defaultBranchChanged || currentBranchChanged;
console.log('Changes detected:', {
defaultBranchChanged,
currentBranchChanged,
hasChanges,
});
const result = {
defaultBranch,
defaultBranchOid: afterDefaultOid,
currentBranch,
currentBranchOid: afterCurrentOid,
fetchedAt: Date.now(),
hasChanges,
remoteUrl,
};
console.log('=== GIT FETCH COMPLETE ===');
console.log('Result:', result);
return result;
} catch (error) {
console.error('Error fetching from remote:', error);
throw error;
}
},
enabled: !!projectId,
refetchInterval: 60000, // Fetch every 60 seconds
staleTime: 30000, // Consider data stale after 30 seconds
retry: 1, // Only retry once on failure
});
// Show toast notifications when changes are detected
useEffect(() => {
if (!query.data || !query.isSuccess) {
return;
}
const currentState = {
defaultBranchOid: query.data.defaultBranchOid,
currentBranchOid: query.data.currentBranchOid,
};
// Skip on first load
if (previousStateRef.current === null) {
previousStateRef.current = currentState;
return;
}
const prevState = previousStateRef.current;
// Detect default branch changes
const defaultBranchChanged =
prevState.defaultBranchOid !== null &&
currentState.defaultBranchOid !== null &&
prevState.defaultBranchOid !== currentState.defaultBranchOid;
// Detect current branch changes
const currentBranchChanged =
prevState.currentBranchOid !== null &&
currentState.currentBranchOid !== null &&
prevState.currentBranchOid !== currentState.currentBranchOid &&
query.data.currentBranch !== query.data.defaultBranch;
// Show toast for default branch changes
if (defaultBranchChanged && query.data.defaultBranch) {
toast({
title: 'Remote changes detected',
description: `The ${query.data.defaultBranch} branch has new commits available.`,
variant: 'default',
});
// Invalidate git status to show new ahead/behind counts
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
}
// Show toast for current branch changes (if different from default)
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'}.`,
variant: 'default',
});
// Invalidate git status to show new ahead/behind counts
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
}
// Update previous state
previousStateRef.current = currentState;
}, [query.data, query.isSuccess, toast, queryClient, projectId]);
return query;
}
+11 -5
View File
@@ -38,6 +38,7 @@ interface GitStatus {
branches: string[];
ahead: number;
behind: number;
remoteBranchExists: boolean;
}
export function useGitStatus(projectId: string | null) {
@@ -59,6 +60,7 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
@@ -80,6 +82,7 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
@@ -200,6 +203,7 @@ export function useGitStatus(projectId: string | null) {
// Calculate ahead/behind
let ahead = 0;
let behind = 0;
let remoteBranchExists = false;
try {
if (currentBranch && remotes.length > 0) {
const remote = remotes[0]; // Use first remote (usually 'origin')
@@ -224,6 +228,9 @@ export function useGitStatus(projectId: string | null) {
ref: currentBranch,
});
// Remote branch exists!
remoteBranchExists = true;
if (remoteRef && localRef && remoteRef !== localRef) {
// Get commits between local and remote
const localCommits = await git.log({
@@ -247,11 +254,8 @@ export function useGitStatus(projectId: string | null) {
behind = remoteOnlyCommits.length;
}
} catch {
// Remote branch might not exist or other issues
// If we can't find remote branch, assume we're ahead if we have commits
if (totalCommits > 0) {
ahead = totalCommits;
}
// Remote branch doesn't exist
remoteBranchExists = false;
}
}
} catch (err) {
@@ -269,6 +273,7 @@ export function useGitStatus(projectId: string | null) {
branches,
ahead,
behind,
remoteBranchExists,
};
} catch (error) {
console.error('Error checking git status:', error);
@@ -283,6 +288,7 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
},
+10
View File
@@ -0,0 +1,10 @@
import { useContext } from 'react';
import { GlobalChatContext, type GlobalChatContextType } from '@/contexts/GlobalChatContext';
export function useGlobalChat(): GlobalChatContextType {
const context = useContext(GlobalChatContext);
if (!context) {
throw new Error('useGlobalChat must be used within a GlobalChatProvider');
}
return context;
}
+45
View File
@@ -0,0 +1,45 @@
import { useEffect, useState } from 'react';
import { MCPClient } from '@/lib/MCPClient';
import type { MCPServer } from '@/contexts/AISettingsContext';
/**
* Hook to check the connection status of an MCP server.
* Returns 'connected', 'offline', or 'checking'.
*/
export function useMCPServerStatus(server: MCPServer): 'connected' | 'offline' | 'checking' {
const [status, setStatus] = useState<'connected' | 'offline' | 'checking'>('checking');
useEffect(() => {
let cancelled = false;
async function checkConnection() {
setStatus('checking');
try {
const client = new MCPClient(server);
await client.connect();
// Try to list tools to verify the connection is working
await client.listTools();
await client.close();
if (!cancelled) {
setStatus('connected');
}
} catch {
if (!cancelled) {
setStatus('offline');
}
}
}
checkConnection();
return () => {
cancelled = true;
};
}, [server]); // Re-check when server config changes
return status;
}
+39
View File
@@ -0,0 +1,39 @@
import { useQuery } from '@tanstack/react-query';
import { useAISettings } from './useAISettings';
import { discoverMCPTools } from '@/lib/MCPClient';
import type OpenAI from 'openai';
import type { MCPClient } from '@/lib/MCPClient';
interface UseMCPToolsResult {
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
clients: Record<string, MCPClient>;
isLoading: boolean;
error: Error | null;
}
/**
* Hook to discover and manage MCP tools from configured servers.
*/
export function useMCPTools(): UseMCPToolsResult {
const { settings } = useAISettings();
const mcpServers = settings.mcpServers || {};
const { data, isLoading, error } = useQuery({
queryKey: ['mcp-tools', mcpServers],
queryFn: async () => {
if (Object.keys(mcpServers).length === 0) {
return { tools: {}, clients: {} };
}
return await discoverMCPTools(mcpServers);
},
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
retry: 1,
});
return {
tools: data?.tools || {},
clients: data?.clients || {},
isLoading,
error: error as Error | null,
};
}
+20
View File
@@ -0,0 +1,20 @@
import { useQuery } from '@tanstack/react-query';
import { useFS } from './useFS';
import { useFSPaths } from './useFSPaths';
import { getPluginGitInfo } from '@/lib/plugins';
/**
* Hook to get git info for a specific plugin
*/
export function usePluginGitInfo(pluginName: string) {
const { fs } = useFS();
const { pluginsPath } = useFSPaths();
return useQuery({
queryKey: ['plugin-git-info', pluginsPath, pluginName],
queryFn: async () => {
return await getPluginGitInfo(fs, pluginsPath, pluginName);
},
enabled: !!pluginName,
});
}
+7 -14
View File
@@ -1,7 +1,7 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useFS } from './useFS';
import { useFSPaths } from './useFSPaths';
import { getPlugins, getAllSkills, deletePlugin as deletePluginFn, getPluginGitInfo, type PluginGitInfo } from '@/lib/plugins';
import { getPlugins, getPluginSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { useGit } from './useGit';
import { join } from 'path-browserify';
@@ -22,11 +22,11 @@ export function usePlugins() {
},
});
// Query to get all skills
// Query to get all plugin skills (not including project skills)
const skillsQuery = useQuery({
queryKey: ['skills', pluginsPath],
queryFn: async () => {
return await getAllSkills(fs, pluginsPath);
return await getPluginSkills(fs, pluginsPath);
},
});
@@ -91,6 +91,10 @@ export function usePlugins() {
dir: pluginDir,
singleBranch: true,
fastForward: true,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
return pluginName;
@@ -115,16 +119,6 @@ export function usePlugins() {
},
});
// Function to get git info for a specific plugin
const getPluginGitInfoQuery = (pluginName: string) => {
return useQuery({
queryKey: ['plugin-git-info', pluginsPath, pluginName],
queryFn: async () => {
return await getPluginGitInfo(fs, pluginsPath, pluginName);
},
});
};
return {
plugins: pluginsQuery.data || [],
isLoadingPlugins: pluginsQuery.isLoading,
@@ -133,6 +127,5 @@ export function usePlugins() {
clonePlugin,
syncPlugin,
deletePlugin,
getPluginGitInfo: getPluginGitInfoQuery,
};
}
+3 -3
View File
@@ -11,11 +11,11 @@ import { useGit } from './useGit';
export function useProjectsManager() {
const { fs } = useFS();
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { projectsPath, templatesPath } = useFSPaths();
const projectsManager = useMemo(() => {
return new ProjectsManager({ fs, git, projectsPath });
}, [fs, git, projectsPath]);
return new ProjectsManager({ fs, git, projectsPath, templatesPath });
}, [fs, git, projectsPath, templatesPath]);
return projectsManager;
}
+96
View File
@@ -0,0 +1,96 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
// Kind 30617 for repository announcements (NIP-34)
const REPOSITORY_KIND = 30617;
export interface Repository extends NostrEvent {
repoId: string;
name: string;
description: string;
webUrls: string[];
cloneUrls: string[];
relays: string[];
maintainers: string[];
repoTags: string[];
earliestUniqueCommit?: string;
isPersonalFork: boolean;
}
export function useUserRepositories(userPubkey?: string) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'user-repositories', userPubkey],
queryFn: async (): Promise<Repository[]> => {
if (!userPubkey) {
return [];
}
// Get all repository announcements for this user
const events = await nostr.query([{
kinds: [REPOSITORY_KIND],
authors: [userPubkey],
limit: 100,
}], { signal: AbortSignal.timeout(3000) });
// Process repository events
const repositories: Repository[] = [];
const repoMap = new Map<string, NostrEvent>();
// Group by d-tag (repo-id) to get latest version
for (const event of events) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const existing = repoMap.get(dTag);
if (!existing || event.created_at > existing.created_at) {
repoMap.set(dTag, event);
}
}
// Convert to Repository objects
for (const [dTag, event] of repoMap) {
try {
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
// Filter out invalid repositories without clone URLs
if (cloneUrls.length === 0) {
console.warn('Skipping repository without clone URLs:', dTag);
continue;
}
repositories.push({
...event,
repoId: dTag,
name,
description,
webUrls,
cloneUrls,
relays,
maintainers,
repoTags,
earliestUniqueCommit,
isPersonalFork,
});
} catch (error) {
console.warn('Failed to parse repository:', error);
}
}
return repositories;
},
enabled: !!userPubkey,
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
+1 -1
View File
@@ -37,7 +37,7 @@
--input: 220 13% 91%;
--ring: 271 81% 56%;
--radius: 0.375rem;
--radius: 0.75rem;
/* Sidebar colors - Enhanced purple theme */
--sidebar-background: 271 81% 96%;
+63
View File
@@ -260,4 +260,67 @@ invalid json line
expect(sessionName1).not.toBe(sessionName2);
});
});
describe('readCost', () => {
it('should return 0 when COST file does not exist', async () => {
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
const cost = await dotAI.readCost();
expect(cost).toBe(0);
});
it('should read and parse cost from COST file', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue('0.123456\n');
const cost = await dotAI.readCost();
expect(cost).toBe(0.123456);
});
it('should return 0 for invalid cost value', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue('invalid\n');
const cost = await dotAI.readCost();
expect(cost).toBe(0);
});
it('should handle cost with whitespace', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue(' 0.050000 \n');
const cost = await dotAI.readCost();
expect(cost).toBe(0.05);
});
});
describe('writeCost', () => {
it('should create shakespeare directory if it does not exist', async () => {
await dotAI.writeCost(0.123456);
expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/shakespeare', { recursive: true });
});
it('should write cost with 6 decimal places', async () => {
await dotAI.writeCost(0.123456789);
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.git/shakespeare/COST',
'0.123457\n'
);
});
it('should write zero cost correctly', async () => {
await dotAI.writeCost(0);
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.git/shakespeare/COST',
'0.000000\n'
);
});
it('should handle write errors gracefully', async () => {
vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Write failed'));
// Should not throw
await expect(dotAI.writeCost(0.123456)).resolves.toBeUndefined();
});
});
});
+80
View File
@@ -278,4 +278,84 @@ 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}`);
}
}
/**
* Read template metadata from .git/shakespeare/template.json file
* @returns Template metadata object or null if not found or invalid
*/
async readTemplate(): Promise<{ name: string; description: string; url: string } | null> {
try {
const templatePath = join(this.workingDir, ".git", "shakespeare", "template.json");
const content = await this.fs.readFile(templatePath, "utf8");
const template = JSON.parse(content);
// Validate that required fields exist
if (template && typeof template.name === 'string' &&
typeof template.description === 'string' &&
typeof template.url === 'string') {
return {
name: template.name,
description: template.description,
url: template.url,
};
}
return null;
} catch {
return null;
}
}
/**
* Write template metadata to .git/shakespeare/template.json file
* @param template Template metadata with name, description, and url
*/
async writeTemplate(template: { name: string; description: string; url: string }): Promise<void> {
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
const templatePath = join(shakespeareDir, "template.json");
try {
// Ensure .git/shakespeare directory exists
await this.fs.mkdir(shakespeareDir, { recursive: true });
// Write the template metadata as formatted JSON
await this.fs.writeFile(templatePath, JSON.stringify(template, null, 2) + "\n");
} catch (error) {
console.warn(`Failed to write .git/shakespeare/template.json file: ${error}`);
}
}
}
+167
View File
@@ -0,0 +1,167 @@
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import type { MCPServer } from '@/contexts/AISettingsContext';
import type OpenAI from 'openai';
/**
* MCP (Model Context Protocol) Client for discovering and executing tools from MCP servers.
* Uses the official @modelcontextprotocol/sdk library.
*/
export class MCPClient {
private client: Client;
private transport: StreamableHTTPClientTransport;
private connected = false;
constructor(server: MCPServer) {
// Create the client
this.client = new Client({
name: 'shakespeare',
version: '1.0.0',
}, {
capabilities: {}
});
// Create HTTP transport with optional custom headers
this.transport = new StreamableHTTPClientTransport(new URL(server.url), {
requestInit: server.headers ? {
headers: server.headers,
} : undefined,
});
}
/**
* Connect to the MCP server.
*/
async connect(): Promise<void> {
if (this.connected) return;
await this.client.connect(this.transport);
this.connected = true;
}
/**
* List all available tools from the MCP server.
*/
async listTools(): Promise<Array<{
name: string;
description?: string;
inputSchema: {
type: 'object';
properties?: Record<string, object>;
required?: string[];
};
}>> {
await this.connect();
const result = await this.client.listTools();
return result.tools;
}
/**
* Call a tool on the MCP server.
*/
async callTool(name: string, args: Record<string, unknown>): Promise<string> {
await this.connect();
const result = await this.client.callTool({
name,
arguments: args,
});
const content = Array.isArray(result.content) ? result.content : [];
if (result.isError) {
const errorText = content
.filter((c): c is { type: 'text'; text: string } => c.type === 'text')
.map(c => c.text)
.join('\n');
throw new Error(`MCP tool error: ${errorText}`);
}
// Concatenate all text content from the response
return content
.filter((c): c is { type: 'text'; text: string } => c.type === 'text')
.map(c => c.text)
.join('\n');
}
/**
* Close the connection to the MCP server.
*/
async close(): Promise<void> {
if (!this.connected) return;
await this.client.close();
this.connected = false;
}
/**
* Convert MCP tools to OpenAI tool format.
*/
static toOpenAITools(mcpTools: Array<{
name: string;
description?: string;
inputSchema: {
type: 'object';
properties?: Record<string, object>;
required?: string[];
};
}>): Record<string, OpenAI.Chat.Completions.ChatCompletionTool> {
const tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
for (const tool of mcpTools) {
tools[tool.name] = {
type: 'function',
function: {
name: tool.name,
description: tool.description || '',
parameters: tool.inputSchema as Record<string, unknown>,
},
} as OpenAI.Chat.Completions.ChatCompletionTool;
}
return tools;
}
}
/**
* Discover tools from all configured MCP servers.
*/
export async function discoverMCPTools(
mcpServers: Record<string, MCPServer>
): Promise<{
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
clients: Record<string, MCPClient>;
}> {
const allTools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
const clients: Record<string, MCPClient> = {};
for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
try {
const client = new MCPClient(serverConfig);
const mcpTools = await client.listTools();
const openAITools = MCPClient.toOpenAITools(mcpTools);
// Store tools with server prefix to avoid name collisions
for (const [toolName, tool] of Object.entries(openAITools)) {
const prefixedName = `${serverName}__${toolName}`;
const functionTool = tool as OpenAI.Chat.Completions.ChatCompletionTool & {
function: { name: string; description: string; parameters: Record<string, unknown> }
};
allTools[prefixedName] = {
type: 'function',
function: {
...functionTool.function,
name: prefixedName,
description: `[${serverName}] ${functionTool.function.description}`,
},
} as OpenAI.Chat.Completions.ChatCompletionTool;
clients[prefixedName] = client;
}
} catch (error) {
console.error(`Failed to discover tools from MCP server "${serverName}":`, error);
}
}
return { tools: allTools, clients };
}
+1 -1
View File
@@ -219,7 +219,7 @@ describe('ProjectsManager', () => {
fs = new MockFS() as unknown as JSRuntimeFS;
nostr = createMockNostr();
git = new Git({ fs, nostr });
projectsManager = new ProjectsManager({ fs, git });
projectsManager = new ProjectsManager({ fs, git, projectsPath: '/projects', templatesPath: '/templates' });
});
describe('getProjects', () => {
+268 -40
View File
@@ -3,6 +3,7 @@ import JSZip from 'jszip';
import { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { ensurePersistentStorage } from '@/lib/persistentStorage';
import { DotAI } from '@/lib/DotAI';
// Polyfill Buffer for browser
if (typeof window !== 'undefined') {
@@ -20,18 +21,22 @@ export interface ProjectsManagerOptions {
fs: JSRuntimeFS;
git: Git;
/** Projects directory path (default: /projects) */
projectsPath?: string;
projectsPath: string;
/** Templates directory path (default: /templates) */
templatesPath: string;
}
export class ProjectsManager {
fs: JSRuntimeFS;
git: Git;
dir: string;
templatesDir: string;
constructor(options: ProjectsManagerOptions) {
this.fs = options.fs;
this.git = options.git;
this.dir = options.projectsPath || '/projects';
this.dir = options.projectsPath;
this.templatesDir = options.templatesPath;
}
async init() {
@@ -40,58 +45,281 @@ export class ProjectsManager {
} catch {
// Directory might already exist
}
try {
await this.fs.mkdir(this.templatesDir);
} catch {
// Directory might already exist
}
}
async createProject(name: string, templateUrl: string, customId?: string): Promise<Project> {
const project = await this.cloneProject(name, templateUrl, customId, { depth: 1 });
/**
* Ensure a template is cached locally and up-to-date.
* Returns the path to the cached template.
*
* @param templateUrl - Git repository URL of the template
* @param onUpdateError - Optional callback when template update fails (non-critical)
* @returns Path to the cached template directory
*/
async updateTemplate(templateUrl: string, onUpdateError?: (error: Error) => void): Promise<string> {
// Generate a safe directory name from the template URL
const templateName = this.getTemplateNameFromUrl(templateUrl);
const templatePath = `${this.templatesDir}/${templateName}`;
// Delete README.md if it exists
try {
await this.fs.unlink(`${project.path}/README.md`);
// Check if template already exists
await this.fs.stat(templatePath);
// Template exists, try to update it with force pull
try {
await this.forcePullTemplate(templatePath);
} catch (updateError) {
// Update failed, but we can continue with the existing template
console.warn(`Failed to update template at ${templatePath}:`, updateError);
if (onUpdateError) {
onUpdateError(updateError instanceof Error ? updateError : new Error(String(updateError)));
}
}
} catch {
// README.md might not exist, ignore error
}
// Template doesn't exist, clone it shallowly
await this.fs.mkdir(templatePath, { recursive: true });
// Delete .git directory and reinitialize
try {
await this.deleteDirectory(`${project.path}/.git`);
} catch {
// .git directory might not exist, ignore error
}
// Initialize new git repository
await this.git.init({
dir: project.path,
defaultBranch: 'main',
});
// Add all files to git
const files = await this.getAllFiles(project.path);
for (const file of files) {
// Skip .git directory
if (!file.startsWith('.git/')) {
await this.git.add({
dir: project.path,
filepath: file,
try {
await this.git.clone({
dir: templatePath,
url: templateUrl,
singleBranch: true,
depth: 1,
});
} catch (cloneError) {
// Clean up on clone failure
try {
await this.deleteDirectory(templatePath);
} catch {
// Ignore cleanup errors
}
throw cloneError;
}
}
// Make initial commit
await this.git.commit({
dir: project.path,
message: 'New project created with Shakespeare',
return templatePath;
}
/**
* Force pull the template repository to match remote, discarding any local changes.
* This ensures the template is always up-to-date with the remote.
*
* Since templates are cloned with depth=1 (shallow), we can't use merge because
* isomorphic-git can't verify the commit history. Instead, we fetch and directly
* checkout the remote branch, which is safe since we always want templates to
* exactly match the remote.
*/
private async forcePullTemplate(templatePath: string): Promise<void> {
// Fetch the latest changes from remote (shallow fetch for efficiency)
const fetchResult = await this.git.fetch({
dir: templatePath,
singleBranch: true,
depth: 1,
});
// Automatically request persistent storage after project creation
try {
await ensurePersistentStorage();
} catch (error) {
// Don't fail project creation if persistent storage request fails
console.warn('Failed to request persistent storage after project creation:', error);
// Get the current branch name (e.g., "refs/heads/main")
const branchRef = fetchResult.defaultBranch;
if (!branchRef) {
throw new Error('Could not determine current branch');
}
return project;
// Extract just the branch name (e.g., "main" from "refs/heads/main")
const branchName = branchRef.replace(/^refs\/heads\//, '');
// Get the remote ref OID
// The fetch stores it as refs/remotes/origin/{branchName}, not refs/remotes/origin/refs/heads/{branchName}
const remoteRef = `refs/remotes/origin/${branchName}`;
const remoteOid = await this.git.resolveRef({
dir: templatePath,
ref: remoteRef,
});
// Update the local branch ref to point to the remote commit
await this.git.writeRef({
dir: templatePath,
ref: branchRef, // Use the full ref like "refs/heads/main"
value: remoteOid,
force: true,
});
// Directly checkout the remote commit to update working directory
// This bypasses merge entirely and just makes the working directory
// match the remote commit exactly. Safe for templates.
// Using force: true to overwrite any local changes
await this.git.checkout({
dir: templatePath,
ref: remoteOid,
force: true,
});
}
/**
* Generate a safe directory name from a template URL
*/
private getTemplateNameFromUrl(url: string): string {
// Extract a meaningful name from the URL
// e.g., "https://gitlab.com/soapbox-pub/mkstack.git" -> "mkstack"
// e.g., "nostr://[email protected]/shakespeare.diy/mkstack" -> "mkstack"
let name = url;
// Remove .git suffix if present
name = name.replace(/\.git$/, '');
// Remove trailing slash
name = name.replace(/\/$/, '');
// Extract the last part of the path
const parts = name.split('/');
name = parts[parts.length - 1] || '';
// Sanitize the name to be filesystem-safe
name = name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
if (!name) {
throw new Error(`Could not derive template name from URL: ${url}`);
}
return name;
}
/**
* Copy a directory recursively from source to destination
*/
private async copyDirectory(sourcePath: string, destPath: string): Promise<void> {
// Ensure destination directory exists
await this.fs.mkdir(destPath, { recursive: true });
const entries = await this.fs.readdir(sourcePath);
for (const entry of entries) {
// Skip .git directory
if (entry === '.git') continue;
const sourceFullPath = `${sourcePath}/${entry}`;
const destFullPath = `${destPath}/${entry}`;
try {
const stat = await this.fs.lstat(sourceFullPath);
if (stat.isDirectory()) {
// Recursively copy subdirectories
await this.copyDirectory(sourceFullPath, destFullPath);
} else if (stat.isFile()) {
// Copy file
const content = await this.fs.readFile(sourceFullPath);
await this.fs.writeFile(destFullPath, content);
}
} catch (error) {
console.warn(`Failed to copy ${sourceFullPath}:`, error);
// Continue copying other files
}
}
}
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void, templateMetadata?: { name: string; description: string }): Promise<Project> {
const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID
if (customId && await this.projectExists(id)) {
throw new Error(`Project with ID "${id}" already exists`);
}
const projectPath = `${this.dir}/${id}`;
// Ensure template is cached and up-to-date
const templatePath = await this.updateTemplate(templateUrl, onTemplateUpdateError);
// Create project directory
await this.fs.mkdir(projectPath, { recursive: true });
try {
// Copy template to project directory (excluding .git)
await this.copyDirectory(templatePath, projectPath);
// Delete README.md if it exists
try {
await this.fs.unlink(`${projectPath}/README.md`);
} catch {
// README.md might not exist, ignore error
}
// Initialize new git repository
await this.git.init({
dir: projectPath,
defaultBranch: 'main',
});
// Save template metadata to .git/shakespeare/template.json if provided
if (templateMetadata) {
try {
const dotAI = new DotAI(this.fs, projectPath);
await dotAI.writeTemplate({
name: templateMetadata.name,
description: templateMetadata.description,
url: templateUrl,
});
} catch (error) {
// Don't fail project creation if template metadata save fails
console.warn('Failed to save template metadata:', error);
}
}
// Add all files to git
const files = await this.getAllFiles(projectPath);
for (const file of files) {
// Skip .git directory
if (!file.startsWith('.git/')) {
await this.git.add({
dir: projectPath,
filepath: file,
});
}
}
// Make initial commit
await this.git.commit({
dir: projectPath,
message: 'New project created with Shakespeare',
});
// Get filesystem stats for timestamps
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Automatically request persistent storage after project creation
try {
await ensurePersistentStorage();
} catch (error) {
// Don't fail project creation if persistent storage request fails
console.warn('Failed to request persistent storage after project creation:', error);
}
return {
id,
name: this.formatProjectName(id),
path: projectPath,
lastModified: timestamp,
};
} catch (error) {
// Clean up the directory that was created if project creation fails
try {
await this.deleteDirectory(projectPath);
} catch (cleanupError) {
// Log cleanup error but don't mask the original error
console.warn('Failed to clean up directory after project creation failure:', cleanupError);
}
// Re-throw the original error
throw error;
}
}
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
+62 -1
View File
@@ -1,6 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { SessionManager, type AIMessage } from './SessionManager';
import type { JSRuntimeFS } from './JSRuntime';
import type { NPool } from '@nostrify/nostrify';
import type { AppConfig } from '@/contexts/AppContext';
// Mock the filesystem
const mockFS: JSRuntimeFS = {
@@ -22,12 +24,47 @@ 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,
},
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: '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',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
describe('SessionManager', () => {
let sessionManager: SessionManager;
const mockAISettings = {
providers: [
{
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com',
apiKey: 'test-key'
}
@@ -35,7 +72,10 @@ describe('SessionManager', () => {
};
beforeEach(() => {
sessionManager = new SessionManager(mockFS, mockAISettings);
const getSettings = () => mockAISettings;
const getConfig = () => testConfig;
const getDefaultConfig = () => testConfig;
sessionManager = new SessionManager(mockFS, mockNostr, getSettings, getConfig, getDefaultConfig);
});
it('should initialize streaming message with reasoning content', async () => {
@@ -117,4 +157,25 @@ describe('SessionManager', () => {
expect(updatedSession?.messages).toHaveLength(1); // Only the user message
expect(updatedSession?.messages[0].role).toBe('user');
});
it('should track when images are not supported and strip them on subsequent requests', async () => {
const projectId = 'test-project';
const tools = {};
const customTools = {};
// Load a session
const session = await sessionManager.loadSession(projectId, tools, customTools);
// Initially, images should not be marked as unsupported
expect(session.imagesNotSupported).toBeUndefined();
// Simulate marking images as not supported (this would happen after an API error)
session.imagesNotSupported = true;
// Verify the flag is set
expect(session.imagesNotSupported).toBe(true);
// On subsequent requests, the SessionManager should proactively strip images
// This prevents retrying with images on every message/tool call
});
});
+209 -31
View File
@@ -11,6 +11,9 @@ import { NostrMetadata } from '@nostrify/nostrify';
import { MalformedToolCallError } from './errors/MalformedToolCallError';
import { EmptyMessageError } from './errors/EmptyMessageError';
import { isEmptyMessage } from './isEmptyMessage';
import { Git } from './git';
import type { NPool } from '@nostrify/nostrify';
import type { AppConfig } from '@/contexts/AppContext';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
role: 'assistant';
@@ -37,6 +40,7 @@ export interface SessionState {
abortController?: AbortController;
totalCost?: number; // Total cost in USD for this session
lastInputTokens?: number; // Input tokens from the last AI request
imagesNotSupported?: boolean; // Track if this session's model doesn't support images
}
export interface SessionManagerEvents {
@@ -58,29 +62,34 @@ export class SessionManager {
private sessions = new Map<string, SessionState>();
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
private fs: JSRuntimeFS;
private aiSettings: { providers: AIProvider[] };
private nostr: NPool;
private getSettings: () => { providers: AIProvider[] };
private getConfig: () => AppConfig;
private getDefaultConfig: () => AppConfig;
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
private corsProxy?: string;
private projectsPath: string;
private pluginsPath?: string;
constructor(
fs: JSRuntimeFS,
aiSettings: { providers: AIProvider[] },
nostr: NPool,
getSettings: () => { providers: AIProvider[] },
getConfig: () => AppConfig,
getDefaultConfig: () => AppConfig,
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
corsProxy?: string,
projectsPath = '/projects',
pluginsPath?: string,
) {
this.fs = fs;
this.aiSettings = aiSettings;
this.nostr = nostr;
this.getSettings = getSettings;
this.getConfig = getConfig;
this.getDefaultConfig = getDefaultConfig;
this.getProviderModels = getProviderModels;
this.getCurrentUser = getCurrentUser;
this.projectsPath = projectsPath;
this.pluginsPath = pluginsPath;
this.corsProxy = corsProxy;
}
private get git(): Git {
const config = this.getConfig();
return new Git({ fs: this.fs, nostr: this.nostr, corsProxy: config.corsProxy });
}
/**
@@ -97,7 +106,8 @@ export class SessionManager {
// Try to load existing history
try {
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`);
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
const lastSession = await dotAI.readLastSessionHistory();
if (lastSession) {
messages = lastSession.messages;
@@ -154,7 +164,7 @@ export class SessionManager {
*/
async deleteSession(projectId: string): Promise<void> {
const session = this.sessions.get(projectId);
session?.abortController?.abort();
session?.abortController?.abort('Session deleted');
this.sessions.delete(projectId);
@@ -178,7 +188,11 @@ export class SessionManager {
/**
* Send a message and start AI generation
*/
async sendMessage(projectId: string, content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string): Promise<void> {
async sendMessage(
projectId: string,
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
providerModel: string
): Promise<void> {
const session = this.sessions.get(projectId);
if (!session || session.isLoading) return;
@@ -209,14 +223,19 @@ export class SessionManager {
this.emit('loadingChanged', projectId, true);
try {
// Get latest config and settings
const config = this.getConfig();
const defaultConfig = this.getDefaultConfig();
const settings = this.getSettings();
// Parse provider and model
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const parsed = parseProviderModel(providerModel, settings.providers);
const provider = parsed.provider;
const model = parsed.model;
// Initialize OpenAI client
const { user, metadata } = this.getCurrentUser?.() ?? {};
const openai = createAIClient(provider, user, this.corsProxy);
const openai = createAIClient(provider, user, config.corsProxy);
let stepCount = 0;
const maxSteps = session.maxSteps || 50;
@@ -238,22 +257,106 @@ 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
}
// Get project template metadata if available
let projectTemplate: { name: string; description: string; url: string } | undefined;
try {
const dotai = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
const template = await dotai.readTemplate();
projectTemplate = template || undefined;
} catch {
// Template metadata not available
}
const systemPrompt = await makeSystemPrompt({
cwd: `${this.projectsPath}/${projectId}`,
cwd: `${config.fsPathProjects}/${projectId}`,
fs: this.fs,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(session.tools),
pluginsPath: this.pluginsPath,
config,
defaultConfig,
user,
metadata,
repositoryUrl,
template: config.systemPrompt,
projectTemplate,
});
// Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG)
const filterSupportedImages = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
return msgs.map(msg => {
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
const filteredContent = msg.content.filter(part => {
if (part.type !== 'image_url') return true;
const imagePart = part as OpenAI.Chat.Completions.ChatCompletionContentPartImage;
const url = imagePart.image_url.url.toLowerCase();
// Keep only JPG/JPEG/PNG images
// Check file extension or data URL MIME type
return /\.(jpg|jpeg|png)(\?|$)/.test(url) ||
url.startsWith('data:image/jpeg') ||
url.startsWith('data:image/png') ||
url.startsWith('data:image/jpg');
});
return {
...msg,
content: filteredContent
};
}
return msg;
});
};
// Helper function to strip all image_url parts but keep text parts (including VFS paths)
const stripImageUrls = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
return msgs.map(msg => {
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
// Keep only text parts (this includes "Added file: /tmp/..." paths)
const textParts = msg.content.filter(part => part.type === 'text');
// If we had images, convert to string content (or empty if no text)
if (textParts.length > 0) {
return {
...msg,
content: textParts.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartText).text).join('\n')
};
}
// If no text parts, return empty string
return {
...msg,
content: ''
};
}
return msg;
});
};
// Prepare messages for AI
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = (systemPrompt
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages;
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
// Filter out unsupported image formats (keep only JPG/JPEG/PNG for API)
// This ensures the UI shows all image types, but API only receives supported formats
messages = filterSupportedImages(messages);
// If this session has already determined images aren't supported, strip them proactively
if (session.imagesNotSupported) {
messages = stripImageUrls(messages);
}
// Prepare completion options
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
@@ -266,11 +369,56 @@ export class SessionManager {
},
};
// Generate streaming response
const stream = await openai.chat.completions.create(completionOptions, {
signal: session.abortController?.signal
// Check if messages contain any images (for retry logic)
const hasImages = messages.some(msg => {
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
return msg.content.some(part => part.type === 'image_url');
}
return false;
});
// Generate streaming response with retry logic for models that don't support images
let stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>;
let retriedWithoutImages = false;
try {
stream = await openai.chat.completions.create(completionOptions, {
signal: session.abortController?.signal
});
} catch (error) {
// Check if this might be an image-related error and we have images to strip
const errorObj = error as Record<string, unknown>;
const errorStatus = typeof errorObj?.status === 'number' ? errorObj.status : undefined;
const isPotentialImageError = errorStatus === 400 || errorStatus === 404 || errorStatus === 500;
if (isPotentialImageError && hasImages && !retriedWithoutImages) {
console.warn('API call failed, retrying without image_url parts (keeping VFS paths):', error);
retriedWithoutImages = true;
// Strip image_url parts but keep text parts (including VFS paths)
const messagesWithoutImages = stripImageUrls(messages);
// Update completion options with stripped messages
const retryOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
...completionOptions,
messages: messagesWithoutImages
};
// Retry the API call - if this succeeds, we know images were the problem
stream = await openai.chat.completions.create(retryOptions, {
signal: session.abortController?.signal
});
// SUCCESS: The retry without images worked, so this model doesn't support images
// Mark this session as not supporting images to avoid future retries
session.imagesNotSupported = true;
console.log('Retry without images succeeded - marking this session as not supporting images');
} else {
// Re-throw if not a potential image error or already retried
throw error;
}
}
let accumulatedContent = '';
let accumulatedReasoningContent = '';
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
@@ -480,7 +628,7 @@ export class SessionManager {
const session = this.sessions.get(projectId);
if (!session) return;
session.abortController?.abort();
session.abortController?.abort('User stopped generation');
session.isLoading = false;
session.streamingMessage = undefined;
session.abortController = undefined;
@@ -524,7 +672,7 @@ export class SessionManager {
/**
* Update session cost and context usage based on usage data
*/
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
private async updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): Promise<void> {
if (!this.getProviderModels) return;
const session = this.sessions.get(projectId);
@@ -534,12 +682,16 @@ export class SessionManager {
if (typeof usage.cost === 'number') {
session.totalCost = (session.totalCost || 0) + usage.cost;
this.emit('costUpdated', projectId, session.totalCost);
// Accumulate cost to project total
await this.accumulateProjectCost(projectId, usage.cost);
return;
}
// Otherwise, get the cost from the models endpoint
try {
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const settings = this.getSettings();
const parsed = parseProviderModel(providerModel, settings.providers);
const modelName = parsed.model;
const provider = parsed.provider;
@@ -563,6 +715,9 @@ export class SessionManager {
// Update session total cost
session.totalCost = (session.totalCost || 0) + requestCost;
this.emit('costUpdated', projectId, session.totalCost);
// Accumulate cost to project total
await this.accumulateProjectCost(projectId, requestCost);
} catch (error) {
console.warn('Failed to calculate session cost:', error);
}
@@ -576,13 +731,36 @@ export class SessionManager {
if (!session) return;
try {
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${session.projectId}`);
await dotAI.setHistory(session.sessionName, session.messages);
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`);
// Cast to ChatCompletionMessageParam[] - user messages with image arrays are valid
await dotAI.setHistory(session.sessionName, session.messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[]);
} 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
*/
+5 -13
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { AI_PROVIDER_PRESETS, getPresetProvider, getShakespeareProvider } from './aiProviderPresets';
import { AI_PROVIDER_PRESETS } from './aiProviderPresets';
describe('AI Provider Presets', () => {
it('should export preset providers array', () => {
@@ -22,20 +22,12 @@ describe('AI Provider Presets', () => {
});
it('should get preset provider by id', () => {
const openai = getPresetProvider('openai');
const openai = AI_PROVIDER_PRESETS.find(p => p.id === 'openai');
expect(openai).toBeDefined();
expect(openai?.name).toBe('OpenAI');
const nonExistent = getPresetProvider('non-existent');
expect(nonExistent).toBeUndefined();
});
it('should get Shakespeare provider', () => {
const shakespeare = getShakespeareProvider();
expect(shakespeare).toBeDefined();
expect(shakespeare.id).toBe('shakespeare');
expect(shakespeare.name).toBe('Shakespeare AI');
expect(shakespeare.nostr).toBe(true);
const nonExistent = AI_PROVIDER_PRESETS.find(p => p.id === 'non-existent');
expect(nonExistent).toBeUndefined();
});
it('should have valid preset structure', () => {
@@ -47,7 +39,7 @@ describe('AI Provider Presets', () => {
expect(preset.baseURL).toBeDefined();
expect(typeof preset.baseURL).toBe('string');
expect(preset.baseURL).toMatch(/^https?:\/\//);
// Optional fields
if (preset.apiKeysURL) {
expect(typeof preset.apiKeysURL).toBe('string');
+1 -15
View File
@@ -89,18 +89,4 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://vercel.com/legal/terms",
proxy: true,
},
];
// Helper function to get a specific preset by ID
export function getPresetProvider(id: string): PresetProvider | undefined {
return AI_PROVIDER_PRESETS.find(preset => preset.id === id);
}
// Helper function to get the Shakespeare provider preset
export function getShakespeareProvider(): PresetProvider {
const shakespeare = getPresetProvider("shakespeare");
if (!shakespeare) {
throw new Error("Shakespeare provider preset not found");
}
return shakespeare;
}
];
+440
View File
@@ -0,0 +1,440 @@
import { describe, it, expect } from 'vitest';
import { parseRepositoryAnnouncement } from './announceRepository';
import type { NostrEvent } from '@nostrify/nostrify';
// Valid test npub for GRASP URL testing
const TEST_NPUB = 'npub1cmzxsdtwlu5m42vmqrkkcx50pc7anr5754ncmn380gmf4gcjsgms7vk7pj';
describe('parseRepositoryAnnouncement', () => {
// Helper to create a mock repository announcement event
const createMockEvent = (tags: string[][]): NostrEvent => ({
id: 'test-id',
pubkey: 'test-pubkey',
kind: 30617,
content: '',
tags,
created_at: Math.floor(Date.now() / 1000),
sig: 'test-sig',
});
it('should throw error for non-30617 events', () => {
const event = createMockEvent([]);
event.kind = 1;
expect(() => parseRepositoryAnnouncement(event)).toThrow('Expected kind 30617, got 1');
});
it('should parse basic repository fields', () => {
const event = createMockEvent([
['d', 'my-repo'],
['name', 'My Repository'],
['description', 'A test repository'],
['clone', 'https://github.com/user/repo.git'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.identifier).toBe('my-repo');
expect(result.name).toBe('My Repository');
expect(result.description).toBe('A test repository');
expect(result.httpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
});
it('should handle missing optional fields', () => {
const event = createMockEvent([
['d', 'minimal-repo'],
['clone', 'https://example.com/repo.git'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.identifier).toBe('minimal-repo');
expect(result.name).toBeUndefined();
expect(result.description).toBeUndefined();
expect(result.earliestCommit).toBeUndefined();
expect(result.maintainers).toEqual([]);
});
it('should parse multiple values in single tag (NIP-34 format)', () => {
const event = createMockEvent([
['d', 'repo'],
['web', 'https://example.com', 'https://mirror.example.com'],
['clone', 'https://github.com/user/repo.git', 'https://gitlab.com/user/repo.git'],
['relays', 'wss://relay1.com', 'wss://relay2.com'],
['maintainers', 'pubkey1', 'pubkey2', 'pubkey3'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.webUrls).toEqual(['https://example.com', 'https://mirror.example.com']);
expect(result.httpsCloneUrls).toEqual([
'https://github.com/user/repo.git',
'https://gitlab.com/user/repo.git',
]);
expect(result.relays).toEqual(['wss://relay1.com', 'wss://relay2.com']);
expect(result.maintainers).toEqual(['pubkey1', 'pubkey2', 'pubkey3']);
});
it('should parse multiple separate tags (backward compatibility)', () => {
const event = createMockEvent([
['d', 'repo'],
['clone', 'https://github.com/user/repo.git'],
['clone', 'https://gitlab.com/user/repo.git'],
['relays', 'wss://relay1.com'],
['relays', 'wss://relay2.com'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.httpsCloneUrls).toEqual([
'https://github.com/user/repo.git',
'https://gitlab.com/user/repo.git',
]);
expect(result.relays).toEqual(['wss://relay1.com', 'wss://relay2.com']);
});
it('should extract earliest unique commit (euc)', () => {
const event = createMockEvent([
['d', 'repo'],
['clone', 'https://example.com/repo.git'],
['r', 'abc123def456', 'euc'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.earliestCommit).toBe('abc123def456');
});
it('should ignore r tags without euc marker', () => {
const event = createMockEvent([
['d', 'repo'],
['clone', 'https://example.com/repo.git'],
['r', 'abc123def456'],
['r', 'other-value', 'other-marker'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.earliestCommit).toBeUndefined();
});
describe('graspServers - GRASP server detection', () => {
it('should identify GRASP servers from clone and relays tags (NIP-34 format)', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/'],
]);
const parsed = parseRepositoryAnnouncement(event);
expect(parsed.graspServers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
expect(parsed.graspServers).toHaveLength(2);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should identify GRASP servers from clone and relays tags (multiple tags format)', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://git.shakespeare.diy/'],
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://relay.ngit.dev/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
expect(servers).toHaveLength(2);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should require both clone and relays tags to identify GRASP server', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
// Missing relays tag for git.shakespeare.diy
['relays', 'wss://relay.ngit.dev/'],
// Missing clone tag for relay.ngit.dev
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual([]);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([`https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`]);
});
it('should validate npub pattern in clone URLs', () => {
const event = createMockEvent([
['clone', 'https://git.shakespeare.diy/invalid-npub/myrepo.git'],
['relays', 'wss://git.shakespeare.diy/'],
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://relay.ngit.dev/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(['relay.ngit.dev']);
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://git.shakespeare.diy/invalid-npub/myrepo.git']);
});
it('should require .git extension in clone URLs', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo`],
['relays', 'wss://git.shakespeare.diy/'],
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://relay.ngit.dev/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(['relay.ngit.dev']);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([`https://git.shakespeare.diy/${TEST_NPUB}/myrepo`]);
});
it('should handle multiple clone URLs for same server', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo1.git`],
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo2.git`],
['relays', 'wss://git.shakespeare.diy/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(['git.shakespeare.diy']);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should reject http:// clone URLs and only accept https://', () => {
const event = createMockEvent([
['clone', `http://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://git.shakespeare.diy/'],
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://relay.ngit.dev/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
// Only https://relay.ngit.dev should be identified as GRASP server
expect(servers).toEqual(['relay.ngit.dev']);
expect(servers).toHaveLength(1);
// http:// URL should not be included in httpsCloneUrls at all
expect(parsed.httpsCloneUrls).toEqual([`https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`]);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should handle ws and wss protocols', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
['relays', 'ws://git.shakespeare.diy/'],
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://relay.ngit.dev/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
expect(servers).toHaveLength(2);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should ignore non-GRASP clone URLs (separate tags)', () => {
const event = createMockEvent([
['clone', 'https://github.com/user/repo.git'],
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://git.shakespeare.diy/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(['git.shakespeare.diy']);
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
});
it('should ignore non-GRASP clone URLs (mixed in single tag)', () => {
const event = createMockEvent([
['clone', 'https://github.com/user/repo.git', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, 'https://gitlab.com/user/repo.git'],
['relays', 'wss://git.shakespeare.diy/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(['git.shakespeare.diy']);
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git', 'https://gitlab.com/user/repo.git']);
});
it('should return empty array when no GRASP servers found', () => {
const event = createMockEvent([
['clone', 'https://github.com/user/repo.git'],
['relays', 'wss://relay.nostr.band/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual([]);
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
});
it('should handle invalid URLs gracefully', () => {
const event = createMockEvent([
['clone', 'not-a-valid-url'],
['relays', 'also-invalid'],
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://git.shakespeare.diy/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(['git.shakespeare.diy']);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should handle paths with subdirectories after npub', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/org/myrepo.git`],
['relays', 'wss://git.shakespeare.diy/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(['git.shakespeare.diy']);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should handle empty tags array', () => {
const event = createMockEvent([]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual([]);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should handle tags with empty values', () => {
const event = createMockEvent([
['clone', ''],
['relays', ''],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual([]);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should handle clone URLs with trailing slashes', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`],
['relays', 'wss://git.shakespeare.diy/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(['git.shakespeare.diy']);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should handle relay URLs without trailing slashes', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://git.shakespeare.diy'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(['git.shakespeare.diy']);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
it('should handle mixed trailing slashes in clone and relay URLs', () => {
const event = createMockEvent([
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev/'],
]);
const parsed = parseRepositoryAnnouncement(event);
const servers = parsed.graspServers;
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
expect(servers).toHaveLength(2);
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
});
});
it('should filter out invalid URLs', () => {
const event = createMockEvent([
['d', 'repo'],
['clone', 'https://valid.com/repo.git', 'not-a-url', 'ftp://invalid.com/repo.git'],
['relays', 'wss://valid.com', 'not-a-url', 'http://invalid.com'],
['web', 'https://valid.com', 'not-a-url'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.httpsCloneUrls).toEqual(['https://valid.com/repo.git']);
expect(result.relays).toEqual(['wss://valid.com']);
expect(result.webUrls).toEqual(['https://valid.com', 'not-a-url']); // web URLs are not validated
});
it('should preserve raw event', () => {
const event = createMockEvent([
['d', 'repo'],
['clone', 'https://example.com/repo.git'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.event).toBe(event);
expect(result.event.id).toBe('test-id');
expect(result.event.pubkey).toBe('test-pubkey');
});
it('should handle empty identifier gracefully', () => {
const event = createMockEvent([
['clone', 'https://example.com/repo.git'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.identifier).toBe('');
});
it('should handle empty arrays for missing multi-value tags', () => {
const event = createMockEvent([
['d', 'repo'],
['clone', 'https://example.com/repo.git'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.webUrls).toEqual([]);
expect(result.relays).toEqual([]);
expect(result.maintainers).toEqual([]);
expect(result.graspServers).toEqual([]);
expect(result.nonGraspRelays).toEqual([]);
});
it('should accept both ws and wss protocols for relays', () => {
const event = createMockEvent([
['d', 'repo'],
['clone', 'https://example.com/repo.git'],
['relays', 'ws://insecure.example.com', 'wss://secure.example.com'],
]);
const result = parseRepositoryAnnouncement(event);
expect(result.relays).toEqual([
'ws://insecure.example.com',
'wss://secure.example.com',
]);
});
it('should only accept https:// protocol for clone URLs (reject http://)', () => {
const event = createMockEvent([
['d', 'repo'],
['clone', 'http://insecure.example.com/repo.git', 'https://secure.example.com/repo.git'],
]);
const result = parseRepositoryAnnouncement(event);
// Only https:// URL should be included
expect(result.httpsCloneUrls).toEqual([
'https://secure.example.com/repo.git',
]);
});
});
+219
View File
@@ -1,4 +1,5 @@
import type { EventTemplate } from 'nostr-tools';
import type { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
export interface RepositoryAnnouncementData {
@@ -14,10 +15,42 @@ export interface RepositoryAnnouncementData {
cloneUrls: string[];
/** Relays for patch submissions */
relays?: string[];
/** Category tags for the repository */
tTags?: string[];
/** Earliest unique commit (root commit) */
earliestCommit?: string;
}
/**
* Parsed NIP-34 repository announcement with categorized data
*/
export interface RepositoryAnnouncement {
/** Repository identifier (d tag) */
identifier: string;
/** Human-readable name */
name?: string;
/** Description of the repository */
description?: string;
/** Web URLs where repository can be browsed */
webUrls: string[];
/** All clone URLs (https) - to support http we would need to store graspServers with ws|wss:// prefix */
httpsCloneUrls: string[];
/** valid ws:// or wss:// Repository relay URLs*/
relays: string[];
/** Earliest unique commit (root commit SHA) */
earliestCommit?: string;
/** Maintainer public keys */
maintainers: string[];
/** GRASP servers (hostname only) - servers that appear in both clone and relays with valid pattern */
graspServers: string[];
/** Clone URLs that are NOT GRASP servers */
nonGraspHttpsCloneUrls: string[];
/** Relay URLs that are NOT GRASP servers */
nonGraspRelays: string[];
/** Raw event for advanced use */
event: NostrEvent;
}
/**
* Creates a NIP-34 repository announcement event (kind 30617)
*
@@ -64,6 +97,14 @@ export function createRepositoryAnnouncementEvent(
}
}
// Add t-tags for categorization (each as a separate tag for relay-level filtering)
if (data.tTags && data.tTags.length > 0) {
const trimmedTags = data.tTags.map(tag => tag.trim().toLowerCase()).filter(tag => tag);
for (const tag of trimmedTags) {
tags.push(['t', tag]);
}
}
// Add earliest unique commit (euc) for repository identification
if (data.earliestCommit?.trim()) {
tags.push(['r', data.earliestCommit.trim(), 'euc']);
@@ -150,3 +191,181 @@ export function validateRepositoryAnnouncementData(
throw new Error('At least one clone URL is required');
}
}
/**
* Parses a NIP-34 repository announcement event (kind 30617) into a structured format.
*
* This function extracts all relevant data from the event tags and categorizes servers
* into GRASP and non-GRASP categories. GRASP servers are identified by matching:
* - clone tag contains URL(s) matching: [http|https]://<hostname>/<valid-npub>/<repo>.git
* - relays tag contains URL(s) matching: [ws|wss]://<hostname>
*
* @param event - A kind 30617 repository announcement event
* @returns Parsed repository data with categorized servers
* @throws Error if event is not kind 30617
*
* @example
* ```typescript
* const repo = parseRepositoryAnnouncement(event);
* console.log(repo.identifier); // "my-repo"
* console.log(repo.graspServers); // ["git.example.com"]
* console.log(repo.nonGraspCloneUrls); // ["https://github.com/user/repo.git"]
* ```
*/
export function parseRepositoryAnnouncement(event: NostrEvent): RepositoryAnnouncement {
if (event.kind !== 30617) {
throw new Error(`Expected kind 30617, got ${event.kind}`);
}
// Extract basic fields
const identifier = event.tags.find(([name]) => name === 'd')?.[1] || '';
const name = event.tags.find(([name]) => name === 'name')?.[1];
const description = event.tags.find(([name]) => name === 'description')?.[1];
// Extract multi-value tags
const webUrls: string[] = [];
const httpsCloneUrls: string[] = [];
const relays: string[] = [];
const maintainers: string[] = [];
let earliestCommit: string | undefined;
// Track servers for GRASP detection
const validCloneServers = new Set<string>(); // Servers with valid GRASP clone URLs
const relayServers = new Set<string>(); // Servers in relays tags
const cloneUrlsByServer = new Map<string, string[]>(); // Map hostname -> clone URLs
const relayUrlsByServer = new Map<string, string[]>(); // Map hostname -> relay URLs
for (const [name, ...values] of event.tags) {
switch (name) {
case 'web':
// All values after tag name are web URLs
for (const value of values) {
if (value) {
webUrls.push(value);
}
}
break;
case 'clone':
// All values after tag name are clone URLs
// Also track which ones match GRASP pattern
for (const value of values) {
if (value) {
try {
const url = new URL(value);
// Only accept https:// URLs (reject http://)
if (url.protocol === 'https:') {
httpsCloneUrls.push(value); // Use original value to preserve exact format
// Check if this matches GRASP pattern: https://<hostname>/<npub>/<repo>.git
if ((value.endsWith('.git/') || value.endsWith('.git')) && value.includes('/npub1')) {
// Extract and validate the npub using nip19.decode
// Match npub1 followed by alphanumeric chars, ending at /
const npubMatch = value.match(/\/npub1([a-z0-9]+)\//);
if (npubMatch) {
const npub = `npub1${npubMatch[1]}`;
try {
const decoded = nip19.decode(npub);
if (decoded.type === 'npub') {
// Valid GRASP clone URL
validCloneServers.add(url.hostname);
if (!cloneUrlsByServer.has(url.hostname)) {
cloneUrlsByServer.set(url.hostname, []);
}
cloneUrlsByServer.get(url.hostname)!.push(value);
}
} catch {
// Invalid npub, not a GRASP server
}
}
}
}
} catch {
// Invalid URL, skip
}
}
}
break;
case 'relays':
// All values after tag name are relay URLs
for (const value of values) {
if (value) {
try {
const url = new URL(value);
if (url.protocol === 'ws:' || url.protocol === 'wss:') {
relays.push(value); // Use original value to preserve exact format
relayServers.add(url.hostname);
if (!relayUrlsByServer.has(url.hostname)) {
relayUrlsByServer.set(url.hostname, []);
}
relayUrlsByServer.get(url.hostname)!.push(value);
}
} catch {
// Invalid URL, skip
}
}
}
break;
case 'maintainers':
// All values after tag name are maintainer pubkeys
for (const value of values) {
if (value) {
maintainers.push(value);
}
}
break;
case 'r':
// Check for earliest unique commit marker
if (values.length >= 2 && values[1] === 'euc') {
earliestCommit = values[0];
}
break;
}
}
// Identify GRASP servers: must appear in BOTH clone (with valid pattern) and relays
const graspServers = [...validCloneServers].filter(server =>
relayServers.has(server)
);
// Categorize clone URLs
const nonGraspHttpsCloneUrls = httpsCloneUrls.filter(url => {
try {
const hostname = new URL(url).hostname;
return !graspServers.includes(hostname);
} catch {
return true; // Invalid URLs go to non-GRASP
}
});
// Categorize relay URLs
const nonGraspRelays = relays.filter(url => {
try {
const hostname = new URL(url).hostname;
return !graspServers.includes(hostname);
} catch {
return true; // Invalid URLs go to non-GRASP
}
});
return {
identifier,
name,
description,
webUrls,
httpsCloneUrls,
relays,
earliestCommit,
maintainers,
graspServers,
nonGraspHttpsCloneUrls,
nonGraspRelays,
event,
};
}
+24 -8
View File
@@ -243,14 +243,12 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
// Handle bare imports like "react"
build.onResolve({ filter: /^[^./].*/ }, (args) => {
// HACK: https://github.com/esm-dev/esm.sh/issues/1217
if (args.path === "yet-another-react-lightbox/styles.css") {
args.path = "yet-another-react-lightbox/dist/styles.css";
}
const [path, query] = args.path.split("?");
const params = new URLSearchParams(query);
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
const packageName = path.startsWith("@")
? path.split("/").slice(0, 2).join("/")
: path.split("/")[0];
// If the importer is CSS, ignore (no JS deps)
try {
@@ -319,7 +317,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
}
}
const packagePath = args.path.slice(packageName.length);
const packagePath = path.slice(packageName.length);
const specifier = version
? `${cdnName}@${version}${packagePath}`
: `${cdnName}${packagePath}`;
@@ -339,6 +337,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
};
}
// https://vite.dev/guide/assets#explicit-url-imports
if (params.has("url")) {
return {
path: urlStr,
namespace: "esm-file-external",
};
}
return {
path: urlStr,
namespace: "esm",
@@ -426,6 +432,8 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
loader = "js";
} else if (contentType === "text/css") {
loader = "css";
} else if (contentType === "application/wasm") {
loader = "binary";
} else {
loader = "text";
}
@@ -438,6 +446,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
loader,
};
});
// Convert `?url` imports to URL strings pointing to the ESM CDN
build.onLoad({ filter: /.*/, namespace: "esm-file-external" }, (args) => {
return {
contents: `export default ${JSON.stringify(args.path)};`,
loader: "js",
};
});
},
};
}
+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(esmUrl);
const esbuild = await getEsbuild();
const indexHtmlText = await fs.readFile(
`${projectPath}/index.html`,
+95
View File
@@ -0,0 +1,95 @@
import type OpenAI from 'openai';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { saveFileToTmp } from './fileUtils';
import { fileToUrl } from './imageUtils';
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
/**
* Builds message content from text input and attached files.
*
* - All image formats are included in the message content for UI display
* - SessionManager filters to only pass JPG/JPEG/PNG to the OpenAI API
* - All files are saved to VFS and get a text part with the path
* - Images are converted to base64-encoded data URLs for API consumption
*
* Returns content as either a string (for simple text) or an array of content parts.
*
* @param input - User text input
* @param attachedFiles - Array of files to attach
* @param fs - Filesystem instance for saving files
* @param tmpPath - Temporary directory path for file storage
* @returns Promise resolving to message content (string or array of content parts)
*/
export async function buildMessageContent(
input: string,
attachedFiles: File[],
fs: JSRuntimeFS,
tmpPath = '/tmp'
): Promise<string | ContentPart[]> {
const contentParts: ContentPart[] = [];
// Add user input as text part if present
if (input.trim()) {
contentParts.push({
type: 'text',
text: input.trim()
});
}
// Process attached files: save to VFS and add image_url for UI display (all image types)
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
// Save file to VFS (always do this)
const savedPath = await saveFileToTmp(fs, file, tmpPath);
// Always add text part with VFS path
const textPart: ContentPart = {
type: 'text',
text: `Added file: ${savedPath}`
};
// For all image types, also add as image_url for UI display with base64 encoding
const isImage = file.type.startsWith('image/');
if (isImage) {
try {
const imageUrl = await fileToUrl(file);
// Return both parts: image_url for UI display and text for VFS path
return [textPart, {
type: 'image_url' as const,
image_url: { url: imageUrl }
}];
} catch (error) {
// If URL conversion fails, just use text part
console.warn('Failed to convert image to base64, using text part only:', error);
}
}
return [textPart];
} catch (error) {
console.error('Failed to save file:', error);
return [{
type: 'text' as const,
text: `Failed to save file: ${file.name}`
}];
}
});
const fileResults = await Promise.all(filePromises);
// Flatten the results (each file can return multiple parts)
for (const parts of fileResults) {
contentParts.push(...parts);
}
}
// Return as string if single text part, otherwise return array
if (contentParts.length === 1 && contentParts[0].type === 'text') {
return contentParts[0].text;
}
// Return array for multiple parts or if contains image URLs
return contentParts;
}
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more