Compare commits

..
Author SHA1 Message Date
lemonknowsall 2f1b3e6b7e update language mapping 2026-01-12 19:38:16 -08:00
lemonknowsall 749d173cf4 remove redundant timestamp function 2026-01-12 19:27:28 -08:00
lemonknowsall a7b45b5068 update repo card design and add clickable tags 2026-01-11 23:33:02 -08:00
lemonknowsall d26d1051f1 update default zap message 2026-01-11 23:33:02 -08:00
lemonknowsall d99a9e1c46 fix illegal invocation error on fetch 2026-01-11 23:33:02 -08:00
lemonknowsall 8be2ef7b22 improve explore page and search performance 2026-01-11 23:33:01 -08:00
lemonknowsall 75a0d637ce center clone page content 2026-01-11 23:33:01 -08:00
lemonknowsall a84ba7385b explore follows as default 2026-01-11 23:33:01 -08:00
lemonknowsall 2fdd9e6a49 split explore from clone 2026-01-11 23:33:01 -08:00
lemonknowsall 67a77419df add NWC settings page for zaps 2026-01-11 23:33:01 -08:00
lemonknowsall 4676738a14 add OG images, pretty event viewer 2026-01-11 23:33:01 -08:00
lemonknowsall 444dfbc5dd add web tag on deploy 2026-01-11 23:33:01 -08:00
Alex Gleason 5d075e02ab npm audit fix 2026-01-11 13:18:05 -06:00
Alex Gleason 6edc623c13 Add cache-control to last 2 non-system messages 2026-01-10 16:16:58 -06:00
Alex Gleason 027cd819f8 Add OpenCode Zen as a preset AI provider 2026-01-09 16:22:58 -06:00
Alex Gleason ef55e80c35 Add opencode.json with Nostr MCP server 2026-01-09 16:09:55 -06:00
Alex Gleason 3666aac2a1 Clone the messages list instead of mutating them 2026-01-08 01:17:46 -06:00
Alex Gleason f58f75ae8b Add OpenRouter prompt caching hack for Anthropic models 2026-01-08 01:03:05 -06:00
Alex Gleason 22885e0978 Fix z-index of GitSync warning popover 2026-01-07 20:09:07 -06:00
Alex Gleason a988238bb4 Add Continue button to GitSync warning popover 2026-01-07 19:31:39 -06:00
Alex Gleason 11197139f9 Add back totalCommits check 2026-01-07 19:23:51 -06:00
Alex Gleason 9ccad00888 Reset state of GitSyncButton when navigating between projects 2026-01-07 19:18:34 -06:00
Alex Gleason 32ff6570cf Add GitSyncButton popover nag 2026-01-07 19:15:55 -06:00
Alex Gleason 80bb72ef79 Only delete origin header in proxy 2026-01-04 15:56:18 -06:00
Alex Gleason e45f167d2b Drop browser-specific headers from CORS proxy service 2026-01-04 14:35:01 -06:00
Alex Gleason 7e755916c0 Clean up System Settings 2026-01-04 13:06:35 -06:00
Alex Gleason 5915b96d98 Use ExternalInput in OnboardingDialog 2026-01-04 12:53:09 -06:00
Alex Gleason b327607be3 AddProviderDialog -> AddDeployProviderDialog, refactor GitHub OAuth to be less hardcoded 2026-01-04 12:44:27 -06:00
Alex Gleason e23b5031ee Remove favicons from OAuth connect buttons 2026-01-04 12:39:04 -06:00
Alex Gleason 104a08c75a Add OpenRouter OAuth 2026-01-04 12:36:15 -06:00
Alex Gleason ddc23e3800 Fix favicon service hostname logic 2026-01-04 12:10:00 -06:00
Alex Gleason a1959369c5 Don't emit unnecessary streamingUpdate events 2026-01-04 00:46:45 -06:00
Alex Gleason 6c4c1dab3b Fix tool_calls index logic 2026-01-04 00:35:10 -06:00
Alex Gleason 45edc6a777 Lemon keeps adding "peer": true to my package-lock.json for some reason 2026-01-03 19:23:23 -06:00
Alex Gleason 2cde8b5105 Merge branch 'main' of gitlab.com:soapbox-pub/shakespeare 2026-01-03 19:10:49 -06:00
Alex Gleason d2a84fa00d Strip API subdomains in ExternalFavicon to reduce reliance on Shakespeare's favicon service 2026-01-03 19:09:52 -06:00
Alex Gleason 1915e6044f Deployment providers refactoring 2026-01-03 18:49:54 -06:00
Alex Gleason 4f7525bf0a Merge branch 'lightningFees' into 'main'
Add Lightning Fees

See merge request soapbox-pub/shakespeare!93
2026-01-03 23:23:54 +00:00
Alex Gleason cb3fb88a75 Fix tests 2026-01-02 19:41:06 -06:00
Alex Gleason 7d0cd03da9 og:image generation note 2026-01-02 16:50:53 -06:00
Alex Gleason dd3946d6de Fix provider name in Shared Provider Dialog 2026-01-02 16:43:15 -06:00
Alex Gleason 24e70712d8 Revert "Capture session data with Sentry TypeError in SessionManager"
This reverts commit 6a11b5ea05.
2026-01-02 14:59:07 -06:00
Alex Gleason 6a11b5ea05 Capture session data with Sentry TypeError in SessionManager 2026-01-02 14:40:41 -06:00
Alex Gleason 85ac92db96 Log unexpected TypeErrors to Sentry for investigation 2026-01-02 14:02:55 -06:00
lemonknowsall 4cbce6be63 show placeholder when clearing field 2026-01-02 09:53:02 -08:00
lemonknowsall 87de7c79ff add debouncing on typed input 2026-01-02 09:45:39 -08:00
lemonknowsall a96e028bb5 include fees with lightning payments 2026-01-02 09:35:04 -08:00
Alex Gleason b9e5a2f3c2 Fix Lightning payment flow 2026-01-02 10:22:51 -06:00
Alex Gleason f6b3b3a5ea Remove Luvstack 2026-01-02 02:24:48 -06:00
Alex Gleason 88ba38d21a Claude Gateway favicon 2026-01-01 20:55:02 -06:00
Alex Gleason f8b7ad4689 Adjust Luvstack language a tad 2026-01-01 16:36:47 -06:00
Alex Gleason f4a3953d4d Remove Electron functionality 2026-01-01 16:36:35 -06:00
Alex Gleason 16cb47832e Make the ProjectView buttons more clickable on mobile 2025-12-31 13:22:59 -06:00
Alex Gleason 6839f50a48 Fix type errors and tests 2025-12-31 10:25:27 -06:00
Alex Gleason 638b2dd1b8 git log enhancements 2025-12-30 23:34:49 -06:00
Alex Gleason 93c23cb2b6 AI Settings system prompt font size 2025-12-30 22:20:06 -06:00
Alex Gleason a69d96533e Settings inputs bg visual consistency 2025-12-30 22:17:04 -06:00
Alex Gleason 87db8d7101 Fix dialog buttons gaps 2025-12-30 22:10:04 -06:00
Alex Gleason 47820048dc Decrease max width of all Settings pages 2025-12-30 22:07:33 -06:00
Alex Gleason 26945e3b84 typecheck fix 2025-12-30 22:03:57 -06:00
Alex Gleason 38ffe02185 drag-and-drop all the things 2025-12-30 22:00:49 -06:00
Alex Gleason 0192d307c5 drag-and-drop deployment providers 2025-12-30 21:56:21 -06:00
Alex Gleason fa495f876e Deployment before Nostr / add separator in Git Settings 2025-12-30 21:19:44 -06:00
Alex Gleason c6caeed31d Fix defaultig to Credits tab 2025-12-30 21:18:34 -06:00
Alex Gleason 9941078da1 Don't display cents in CreditsBadge 2025-12-30 21:14:00 -06:00
Alex Gleason ef67b9b166 Combine CreditsDialog into AIProviderConfigDialog 2025-12-30 21:11:48 -06:00
Alex Gleason a0d3c4fbd0 Redesign "Git Identity" in Git Settings 2025-12-30 20:43:40 -06:00
Alex Gleason 55cc3c61d5 Update settings pages loading skeletons 2025-12-30 20:36:13 -06:00
Alex Gleason 2acc0191ad Fix type errors 2025-12-30 20:32:50 -06:00
Alex Gleason 5a43a1ea61 Remove separator from Settings pages 2025-12-30 20:23:57 -06:00
Alex Gleason 48d357549a Move "Add Custom" to presets instead of configured 2025-12-30 20:19:17 -06:00
Alex Gleason 4cbff7c8dd Use ProviderTile's for all settings pages 2025-12-30 20:14:51 -06:00
Alex Gleason fa1a8781dc Redesign Deploy Settings into tile icons 2025-12-30 20:01:28 -06:00
Alex Gleason fefa97cb21 Add indicator check to GitSyncButton 2025-12-30 14:41:02 -06:00
Alex Gleason 55ea749c31 Sync after rollback 2025-12-30 12:54:29 -06:00
Alex Gleason 1120d6e574 Add isomorphic-git cache to rollback dialog 2025-12-30 12:49:29 -06:00
Alex Gleason 8fe872e015 Add isomorphic-git cache support
https://isomorphic-git.org/docs/en/cache
2025-12-30 12:40:03 -06:00
Alex Gleason 88def1264d Fix "mode" parameter in system prompt 2025-12-30 12:19:10 -06:00
Alex Gleason e0241a3250 Skip fetch when autosync is enabled (pull will fetch) 2025-12-29 23:21:26 -06:00
Alex Gleason fc9bd3ef02 Add useNostrRepo hook 2025-12-29 22:14:30 -06:00
Alex Gleason 69a49af983 Add NostrRepoEditDialog 2025-12-29 18:54:07 -06:00
Alex Gleason 0a17b575d0 Sync less often 2025-12-29 18:20:31 -06:00
Alex Gleason dff3497ba6 Set up 'shakespeare.autosync' config for non-forked repositories 2025-12-29 18:08:32 -06:00
Alex Gleason 02cc069ff8 Move git sync operations directly into GitSyncProvider 2025-12-29 17:57:16 -06:00
Alex Gleason b7081ea64a BranchSwitcher: display branch name even on mobile 2025-12-29 17:44:39 -06:00
Alex Gleason eb7071789c Allow typing into the chat textarea while a project is generating (just can't submit) 2025-12-29 17:39:59 -06:00
Alex Gleason e4e37c01f4 Don't sync git while project is generating 2025-12-29 17:34:18 -06:00
Alex Gleason 6c5ac6adee Improve git sync button spinner blue color 2025-12-29 17:17:09 -06:00
Alex Gleason a752b22138 Let me configure Nostr repo name 2025-12-29 17:15:31 -06:00
Alex Gleason db64cb3047 Refetch autosync after creating git repo 2025-12-29 17:05:10 -06:00
Alex Gleason f9d398091b Add spinner to GitSyncButton 2025-12-29 17:02:14 -06:00
Alex Gleason ffa65212bc Hold errors in GitSyncProvider 2025-12-29 16:43:47 -06:00
Alex Gleason f9febcce1e Don't sign new state events if they match the old one, after all 2025-12-29 16:30:15 -06:00
Alex Gleason 71f3a08325 Load autosync state at the top level to prevent jarring toggle shifts 2025-12-29 16:25:11 -06:00
Alex Gleason 1e13ed8f36 Add unified git sync state so state is shared across components 2025-12-29 16:10:09 -06:00
Alex Gleason 758e3ab261 Add git autosync functionality 2025-12-29 16:00:23 -06:00
Alex Gleason 0ee88f5968 Increase Nostr push timeouts 2025-12-28 23:55:40 -06:00
Alex Gleason d8e46732b3 Nostr git improve error reporting for push 2025-12-28 23:38:22 -06:00
Alex Gleason 5691954dc8 Add detailed error messaging to "Failed to push to any clone URLs" 2025-12-28 23:20:23 -06:00
Alex Gleason 03e867c33a Fix nostrClone and nostrPull 2025-12-28 22:52:32 -06:00
Alex Gleason e5087e5ad6 Remove httpNoProxy 2025-12-28 18:22:12 -06:00
Alex Gleason 74c0be9d5d Move branch selector into Code section 2025-12-28 18:00:01 -06:00
Alex Gleason 1c54a889ce Add git branch switcher 2025-12-28 17:51:37 -06:00
Alex Gleason 41f4a53b1f Display "Resume" button when there's no finish button / only throw EmptyMessageError when finish_reason is not "stop" 2025-12-28 17:02:03 -06:00
Alex Gleason 44dfd25a84 Save last finish_reason, display a "Resume" button 2025-12-28 16:49:51 -06:00
Alex Gleason dc0144a477 Let git proxy origins be configurable 2025-12-28 16:26:21 -06:00
Alex Gleason b60d11186b Git proxy origins are configured separately from git credentials 2025-12-28 16:19:52 -06:00
Alex Gleason f5036b8b56 Checkout branch name, not commit oid 2025-12-28 15:50:57 -06:00
Alex Gleason 243853b6c8 Update template without depth: 1 2025-12-28 15:09:12 -06:00
Alex Gleason d314655a7b Simplify Nostr Clone, require HEAD tag in state event, improve HEAD detection in push 2025-12-26 14:32:27 -06:00
Alex Gleason b3f5219062 Fetching from each clone URL sequentially is actually faster and more efficient 2025-12-26 14:24:10 -06:00
Alex Gleason 4216d9864c Add the Rollback menu to SyncStep 2025-12-26 01:06:04 -06:00
Alex Gleason 85ee7c40f5 Preserve HEAD from past repo state / set refs to match repo state on clone 2025-12-26 01:01:27 -06:00
Alex Gleason b863009c47 Remove ANSI color functionality from virtual terminal 2025-12-26 00:30:59 -06:00
Alex Gleason 2743d42b55 Add export and delete buttons back to ProjectDetailsDialog, remove export from title menu 2025-12-26 00:23:52 -06:00
Alex Gleason 6542b55823 Remove toast on favorite/unfavorite 2025-12-26 00:11:47 -06:00
Alex Gleason d1b5a26839 Correctly extract HEAD ref in getNostrRemoteInfo 2025-12-26 00:00:35 -06:00
Alex Gleason 393eef282b git fix state event refs 2025-12-25 23:33:11 -06:00
Alex Gleason 118fb6cf2f git class bugfixes 2025-12-25 23:20:01 -06:00
Alex Gleason adcd87cb64 Add Nostr clone test 2025-12-25 23:01:58 -06:00
Alex Gleason 54c89f03c7 Add mock git http server 2025-12-25 22:45:17 -06:00
Alex Gleason dd726c1766 Git: accept custom fetch 2025-12-25 22:44:16 -06:00
Alex Gleason 3b332c6ade Fix useGit test 2025-12-25 22:17:23 -06:00
Alex Gleason 4e68ee57d6 Move MockFS to a separate file (with its own tests) 2025-12-25 22:06:19 -06:00
Alex Gleason 9987cfca6d git basic test setup 2025-12-25 21:39:10 -06:00
Alex Gleason 84cf0ff23a Reimplement nostrPush (also not sure about it) 2025-12-25 20:18:02 -06:00
Alex Gleason 0138c3a17f Implement nostrPull (not sure about it) 2025-12-25 20:05:18 -06:00
Alex Gleason a606c1237d Reimplement nostrClone (simple version) 2025-12-25 18:30:21 -06:00
Alex Gleason 6d001daf8a Implement getNostrRemoteInfo simple version 2025-12-25 18:04:33 -06:00
Alex Gleason e2c4da5300 Reiplement nostrFetch simple version 2025-12-25 17:38:33 -06:00
Alex Gleason b2afa2bc3e Merge remote-tracking branch 'origin/main' into nuke-ngit 2025-12-25 14:42:24 -06:00
Alex Gleason 739b0d50e0 Move External button to the right of Copy button 2025-12-25 06:26:48 -06:00
Alex Gleason 0139d7c2dd Chat history loading skeleton in ChatPane 2025-12-25 06:11:14 -06:00
Alex Gleason 6407523df4 Loading icon on chat tab 2025-12-25 06:06:56 -06:00
Alex Gleason 932db9107d Display text labels near Preview Pane icons 2025-12-25 05:50:16 -06:00
Alex Gleason 1d5b3b1ca7 Nuke the current ngit implementation 2025-12-25 01:27:22 -06:00
Alex Gleason 598447b89f Fix tests 2025-12-25 01:20:59 -06:00
Alex Gleason e13c3c0077 AddProviderDialog -> AddSharedProviderDialog 2025-12-25 01:16:58 -06:00
Alex Gleason 6a74120ddd Fix useGitFetch with no remote 2025-12-25 00:42:15 -06:00
Alex Gleason 5ef848b45e Include user relays in repo announcement event 2025-12-25 00:34:46 -06:00
Alex Gleason 83fec3f6d6 Invalidate git status after every git action 2025-12-25 00:23:13 -06:00
Alex Gleason 0fa4d3a199 Fix onAuth binding to this 2025-12-25 00:20:18 -06:00
Alex Gleason 39652a85ca Fix tests 2025-12-25 00:14:22 -06:00
Alex Gleason 2f2957435a Query must return something in useGitFetch 2025-12-25 00:14:09 -06:00
Alex Gleason 1804436565 Fix advancing step in GitSyncSteps 2025-12-25 00:09:33 -06:00
Alex Gleason 2cc61bd6df Don't use corsProxy for Nostr git 2025-12-25 00:04:29 -06:00
Alex Gleason 4546098df7 Add git proxy config 2025-12-24 23:44:54 -06:00
Alex Gleason e288660d3e Fix tests 2025-12-24 21:49:23 -06:00
Alex Gleason e599f76787 Add back a simple useGitFetch hook 2025-12-24 21:38:57 -06:00
Alex Gleason a9c1922e51 Include relay host in Nostr URIs when possible 2025-12-24 20:46:55 -06:00
Alex Gleason 1f87c68c4f Display yellow indicator dots above push and pull buttons when changes need to be synced 2025-12-24 20:20:48 -06:00
Alex Gleason cfb7242e2b Make the Sync button display loading indicators for Push and Pull 2025-12-24 20:16:01 -06:00
Alex Gleason 6a12e1f4f4 npm i baseline-browser-mapping@latest -D 2025-12-24 20:10:57 -06:00
Alex Gleason 9eb068c2ad SyncStep: loading spinner on pull and push buttons 2025-12-24 20:09:40 -06:00
Alex Gleason 977c40f85b Make Sync button a Collapsible instead of a Dropdown 2025-12-24 20:05:55 -06:00
Alex Gleason f8ed988042 Fix dialog footer gap 2025-12-24 20:02:04 -06:00
Alex Gleason ad92e655cc Fix dialog text being centered on mobile 2025-12-24 19:59:21 -06:00
Alex Gleason 53c8f16dec Fix list item styles in force push/pull dialogs 2025-12-24 19:55:15 -06:00
Alex Gleason a74db2cdd0 Simplify indicator logic in GitSyncButton 2025-12-24 19:52:20 -06:00
Alex Gleason 7428a23c8d Display remote changes message in SyncStep 2025-12-24 19:44:30 -06:00
Alex Gleason f2e34ed9af Display dot indicator where there are unsynced changes 2025-12-24 19:34:18 -06:00
Alex Gleason 12433320b6 Display git provider favicon in SyncStep 2025-12-24 19:20:34 -06:00
Alex Gleason d2fd29ed86 Remove unnecessary dynamic imports 2025-12-24 19:13:30 -06:00
Alex Gleason bc0eec3839 Capture git http error to Sentry 2025-12-24 19:09:01 -06:00
Alex Gleason ddc59a74ff Render InitSuccess above others 2025-12-24 19:00:18 -06:00
Alex Gleason 5f054a9a4a Pass a parsed remoteUrl down into GitSyncSteps to simplify conditionals 2025-12-24 18:58:51 -06:00
Alex Gleason 21df7fe3dd Link to git credentials in case of 401, improve Force Push text 2025-12-24 18:05:44 -06:00
Alex Gleason 99764670ef Don't dismiss error just because Force Pull button was clicked 2025-12-24 17:53:59 -06:00
Alex Gleason 2948a3b4d4 Remove AlertTriangle from error text 2025-12-24 17:44:43 -06:00
Alex Gleason 46affcbdcc Add "Force Push" functionality 2025-12-24 17:44:13 -06:00
Alex Gleason dcdee5b875 Add hover states to DeployButton and GitSyncButton 2025-12-24 17:29:53 -06:00
Alex Gleason c1427d45dc Fix DropdownMenuItem gap in SyncStep 2025-12-24 17:27:29 -06:00
Alex Gleason fba7d680f2 Switch ForcePullDialog to use a regular Dialog 2025-12-24 17:21:02 -06:00
Alex Gleason fe72549e2d Improve ForcePullDialog language 2025-12-24 17:15:16 -06:00
Alex Gleason 5c8d9b3aaa Refactor ForcePullDialog into a separate component 2025-12-24 16:57:56 -06:00
Alex Gleason 2dc22cc40b Add SyncStepError component 2025-12-24 16:54:34 -06:00
Alex Gleason 1fadd80adc Add better error handling to SyncStep 2025-12-24 16:52:16 -06:00
Alex Gleason 49f535827c SyncStep: save full Error object in the state 2025-12-24 16:30:22 -06:00
Alex Gleason 2df6887591 GitSync: dismiss error 2025-12-24 16:27:51 -06:00
Alex Gleason 1c28587bdf Put Push and Pull side-by-side 2025-12-24 16:21:37 -06:00
Alex Gleason 56f2715f79 Unmuted deploy / gitsync button when respective popover is open 2025-12-24 16:08:34 -06:00
Alex Gleason 1424663b43 DeployPopover -> DeployButton, remove deploy barrel export 2025-12-24 16:06:39 -06:00
Alex Gleason 91ae86bbde SyncStep: DRY, improve display of unknown git URLs 2025-12-24 15:57:10 -06:00
Alex Gleason 0dbe51fd88 Add separate pull and push actions to sync 2025-12-24 15:49:55 -06:00
Alex Gleason 1ffd2d06cf SettingsPageLayout 2025-12-23 20:01:02 -06:00
Alex Gleason db807d52d8 Mobile layout improvements 2025-12-23 18:41:48 -06:00
Alex Gleason 95eea4230d Add build project button back to the UI 2025-12-23 14:12:31 -06:00
Alex Gleason 80400ef159 Improve consistency between Deploy and Git popovers 2025-12-23 09:04:26 -06:00
Alex Gleason a8796e6197 Fix lint errors for the 50th time 2025-12-23 08:58:20 -06:00
Alex Gleason 028d22c7c9 DeployPopover 2025-12-23 08:13:29 -06:00
Alex Gleason 9fe97c0b61 Refactor ConfigureRepoStep to eliminate code duplication
- Move GRASP server URL generation before the if/else branches
- Move validation before the if/else branches
- Move 5-second wait after both branches
- Reduces code duplication by ~50 lines while maintaining identical functionality
2025-12-23 07:37:11 -06:00
Alex Gleason f7fc018ae2 Update existing repo announcements with current GRASP servers
- When an existing NIP-34 repository announcement is found, extract all metadata (name, description, web URLs, t-tags, earliest commit)
- Update the announcement with current GRASP server clone URLs and relays from config
- Publish the updated event to keep repository announcements in sync with GRASP configuration
- Remove invalid onProjectDeleted prop from ProjectDetailsDialog usage (prop was removed in previous refactor)
2025-12-23 07:31:33 -06:00
Alex Gleason 8174db459f Fix repo announcement event creation 2025-12-23 07:28:13 -06:00
Alex Gleason 45dd2507fa Fix linting errors 2025-12-23 06:22:36 -06:00
Alex Gleason 0b19ac4f09 Move deploy button to title bar, favorite button into title menu 2025-12-23 05:24:01 -06:00
Alex Gleason 5460a2e766 Fix disconnect query invalidation 2025-12-23 04:22:35 -06:00
Alex Gleason 9d32a13971 Only display the git sync indicator if there are at least 2 commits 2025-12-23 03:31:55 -06:00
Alex Gleason 706ec3642e Improve copy 2025-12-23 03:23:03 -06:00
Alex Gleason 3465b97c13 Abstract and reuse detectFork logic 2025-12-23 03:13:17 -06:00
Alex Gleason c9d1509481 Detect fork by credentials 2025-12-23 03:10:15 -06:00
Alex Gleason 31fc4d61c5 Pass "fork" for Nostr URIs in Clone page 2025-12-23 02:46:22 -06:00
Alex Gleason 956dfb5099 Clone non-owned Nostr repos to "upstream" remote 2025-12-23 02:01:28 -06:00
Alex Gleason 8b8958f7c8 Refactor ProjectsManager.cloneProject to accept an options object 2025-12-23 01:45:12 -06:00
Alex Gleason b99c20c7f7 Make RepositoryCard clone repo directly 2025-12-23 01:22:37 -06:00
Alex Gleason b82b4539d9 Let ngitWebUrl be configurable 2025-12-23 01:21:56 -06:00
Alex Gleason 43190b7a35 Small refactor in ConfigureRepoStep 2025-12-23 01:03:40 -06:00
Alex Gleason e98fc617a1 Open git link externally 2025-12-23 01:02:50 -06:00
Alex Gleason 46a89a67d9 Add NostrURI class 2025-12-23 00:57:18 -06:00
Alex Gleason c84acfdcaa Implement ngit push 2025-12-23 00:28:23 -06:00
Alex Gleason b79b7f04db Add disconnect icon to remove the origin remote 2025-12-22 23:09:34 -06:00
Alex Gleason 6739fea580 Pass signer into Git constructor 2025-12-22 22:46:19 -06:00
Alex Gleason 34db584772 Pass onAuth and author into all the things 2025-12-22 22:37:36 -06:00
Alex Gleason 05d18ae788 normalizeUrl belongs in a separate utils file 2025-12-22 22:26:45 -06:00
Alex Gleason ac8fe4108a GitHub favicon hack 2025-12-22 22:26:05 -06:00
Alex Gleason 3eae1bda4a Add sync feedback 2025-12-22 21:38:22 -06:00
Alex Gleason 4fdb881075 Replace Pull / Push with Sync button 2025-12-22 21:24:50 -06:00
Alex Gleason 3eb156e983 Pass onAuth into the git constructor instead of to push method 2025-12-22 21:16:18 -06:00
Alex Gleason a915b9121f Disable open autofocus in GitSyncButton 2025-12-22 21:00:27 -06:00
Alex Gleason 91313764aa Don't pass author into git functions - use values from config 2025-12-22 20:56:41 -06:00
Alex Gleason 6a7ec8413a Clean up configure repo UI 2025-12-22 20:17:00 -06:00
Alex Gleason 4f49c8efb4 Remove unnecessary onRefetchStatus props 2025-12-22 20:11:21 -06:00
Alex Gleason bd97dda7ab Fix state issue with remote being added 2025-12-22 20:08:02 -06:00
Alex Gleason ab879c9023 Break git-sync up into steps 2025-12-22 19:41:55 -06:00
Alex Gleason 062e2e41bc Don't close GitSync menu after success 2025-12-22 19:28:21 -06:00
Alex Gleason a415a7c5bc Be less tolerant of broken grasp server lists 2025-12-22 19:20:46 -06:00
Alex Gleason f5010518e2 Copy copy button height 2025-12-22 18:26:02 -06:00
Alex Gleason aa1f456a36 Don't show sync indicator until after git information has loaded 2025-12-22 18:22:07 -06:00
Alex Gleason 117cc2ee1e Improve design of git success state 2025-12-22 18:20:34 -06:00
Alex Gleason 50c9645e3a Fix "Add" button height in git settings provider presets 2025-12-22 18:12:36 -06:00
Alex Gleason 8224589dbe CloudUpload icon for GitSyncButton 2025-12-22 18:09:23 -06:00
Alex Gleason 11f670871c Merge remote-tracking branch 'origin/main' into git-redo 2025-12-22 18:08:53 -06:00
Alex Gleason 581f6406dc Small favicon service refactor 2025-12-22 18:08:12 -06:00
Alex Gleason ba02d7bf33 Add rudimentary Git Sync button 2025-12-22 17:14:18 -06:00
Alex Gleason d72729f379 Remove all the git menus 2025-12-22 15:47:31 -06:00
Alex Gleason 8eeea7b188 Remove unnecessary remote add (other place) 2025-12-22 14:01:46 -06:00
Alex Gleason 95dead2c79 Small whitespace fix 2025-12-22 13:58:40 -06:00
Alex Gleason afa21c7507 Remove unnecessary temp remote 2025-12-22 13:58:01 -06:00
Alex Gleason d82df433de Upgrade nostrify 2025-12-22 13:28:00 -06:00
Alex Gleason 5a55c09a67 Merge branch 'pr/fix-git-fetch-toast-missfire(1141d542)' 2025-12-22 13:01:13 -06:00
Alex Gleason c14419640a DeployDialog provider chicklets 2025-12-21 07:52:05 -06:00
Alex Gleason 94cdf2c9a4 Prevent the chat UI from freezing when AI isn't configured 2025-12-21 06:36:52 -06:00
Alex Gleason 1405d0a760 AI service errors take precedence over console errors in Quilly 2025-12-21 04:46:34 -06:00
Alex Gleason a957338afd Revert "Fix happy-dom vuln"
This reverts commit 94d62b254d.
2025-12-21 04:11:22 -06:00
Alex Gleason d1cdcb0fd9 Fix attachment rendering 2025-12-21 03:41:25 -06:00
Alex Gleason 94d62b254d Fix happy-dom vuln 2025-12-21 02:27:50 -06:00
Alex Gleason 112a042bc5 npm audit fix 2025-12-21 01:46:22 -06:00
Alex Gleason c53233d5d8 npm i 2025-12-21 01:45:40 -06:00
Alex Gleason 5d7ae56e2d Merge branch 'moreApps' into 'main'
Add Remaining Apps to 'More Apps' Section

See merge request soapbox-pub/shakespeare!77
2025-12-21 07:45:00 +00:00
Alex Gleason 0689f1cbf7 Remove DeployProjectTool for now 2025-12-21 01:11:15 -06:00
Alex Gleason 91130cbd89 Fix grasp tests 2025-12-21 01:06:11 -06:00
Alex Gleason 8b9d87b5d5 Sync user grasp servers 2025-12-21 00:55:51 -06:00
Alex Gleason ead95a4d03 Fix origin type errors 2025-12-21 00:17:52 -06:00
Alex Gleason fcc305788d Use origin instead of protocol, host for git credentials 2025-12-21 00:08:56 -06:00
Alex Gleason 9c2f4f9eb6 Add id and name to GitCredentials 2025-12-20 23:54:00 -06:00
Alex Gleason 6dfedaa97e Use stable key for deploy settings, too 2025-12-20 23:34:10 -06:00
Alex Gleason 8ed98a9d73 Let me rearrange git credentials 2025-12-20 23:23:38 -06:00
Alex Gleason 0377761fc6 Add loading skeletons to settings pages 2025-12-20 23:14:41 -06:00
Alex Gleason fbdcd01b38 Refactor git credentials to be an array instead of an object 2025-12-20 22:49:07 -06:00
Alex Gleason 07807ea1bf Fix PreviewPane style issue 2025-12-20 22:46:20 -06:00
Alex Gleason 31b26e40a8 Merge branch 'main' of nostr://npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/relay.ngit.dev/shakespeare 2025-12-20 21:37:49 -06:00
Alex Gleason 42b697643f Fix Add button height in git settings 2025-12-20 21:25:59 -06:00
Alex Gleason 97038ec809 Fix Add button height in git settings 2025-12-20 21:21:09 -06:00
Alex Gleason e644d7127c Mute the title chevron a little 2025-12-20 21:09:46 -06:00
Alex Gleason 3d3d35be40 First user message is always interpreted as plain text 2025-12-20 20:55:54 -06:00
Alex Gleason d4dc0d54c4 Fix UserMessage test 2025-12-20 20:51:41 -06:00
Alex Gleason 246b23167b Also display ModelSelector skeleton if providers are loading 2025-12-20 20:48:18 -06:00
Alex Gleason 88c6b80484 Make "Added File:" match stricter 2025-12-20 20:43:53 -06:00
Alex Gleason 8fc7c0bb60 ChatInput is also disabled while settings are loading 2025-12-20 20:36:19 -06:00
Alex Gleason 155707436c Improve AI config loading display 2025-12-20 20:32:43 -06:00
Alex Gleason b59dbc9ba8 Attach button style improvements 2025-12-20 20:25:28 -06:00
Alex Gleason 2f8055abfa Expose AI configuration loading state 2025-12-20 20:23:18 -06:00
Alex Gleason 763cf87749 Improve display of ExternalInput on Safari 2025-12-20 20:13:29 -06:00
Alex Gleason 97b334da8e Refactor ExternalInput 2025-12-20 19:43:31 -06:00
Alex Gleason 8af3618793 Improve loading of Project Details dialog 2025-12-20 19:12:18 -06:00
Alex Gleason 8c7c2694c4 Add device toggle to preview bar 2025-12-20 18:57:16 -06:00
Alex Gleason f3d2f40c13 Avoid text-primary in thumb navigation 2025-12-20 18:35:29 -06:00
Alex Gleason 2347770d46 Remove useless .mobile-nav-button 2025-12-20 18:29:00 -06:00
Alex Gleason a5f89d20ae Make project title open the menu instead of the extra menu button 2025-12-20 18:20:30 -06:00
Alex Gleason eb17feadea Remove unused goBack / goForward verbs 2025-12-20 17:51:40 -06:00
Alex Gleason 7a252e0037 Merge branch 'fullscreenPreview' into 'main'
Fullscreen Preview

See merge request soapbox-pub/shakespeare!87
2025-12-20 22:50:35 +00:00
Alex Gleason 7b9310c6ac Shrink default chat area a tad 2025-12-20 16:47:14 -06:00
Alex Gleason e012c74b41 Change preview fullscreen icon 2025-12-20 16:42:15 -06:00
Alex Gleason 6cccf6e2d9 Highlight the active navigation 2025-12-20 16:38:51 -06:00
Alex Gleason 45038c9b96 Allow easy navigating in address bar 2025-12-20 16:24:23 -06:00
Alex Gleason b74259f5f7 Browser input style improvements 2025-12-20 15:55:48 -06:00
Alex Gleason 7322b0ff41 Move refresh button into browser address bar, move fullscreen to the left 2025-12-20 14:43:19 -06:00
Alex Gleason af09c9aa79 Merge branch 'searchProjectImports' into 'main'
Add My Projects/Follows Import Search

See merge request soapbox-pub/shakespeare!86
2025-12-20 20:24:32 +00:00
Alex Gleason 179a59c58c Merge branch 'pasteImage' into 'main'
bugfix: add paste image functionality to main index page

See merge request soapbox-pub/shakespeare!85
2025-12-20 20:17:27 +00:00
Alex Gleason 5a456c9957 refactor: move paste image handling to Textarea component
- Add onPasteImage prop to Textarea component
- Remove createPasteHandler utility function from utils.ts
- Update Index.tsx and ChatInput.tsx to use onPasteImage prop
- onPaste takes precedence over onPasteImage when both are provided
2025-12-20 14:13:15 -06:00
lemonknowsall 7478be317c add full-screen preview mode 2025-12-19 20:19:03 -08:00
lemonknowsall 54a2b807d8 increase search input sizing 2025-12-15 15:59:30 -08:00
lemonknowsall a8e6d51f9f add nostr repo search 2025-12-15 15:59:30 -08:00
Alex Gleason 27dec36a3f Improve empty deploy dialog 2025-12-14 08:12:05 -06:00
lemonknowsall 6e03767f62 bugfix: add paste image functionality to main index page 2025-12-12 17:54:18 -08:00
lemonknowsall 421c3f2b2b add remaining apps to 'More Apps' section 2025-12-11 21:22:51 -08:00
Alex Gleason 2f50b2611c Expose deployedUrl to system prompt 2025-12-09 20:23:27 -06:00
Alex Gleason 6bbee282be Add deployed URL to deploy config, parse the config with zod 2025-12-09 20:16:09 -06:00
Alex Gleason dd0f105c87 Preserve subdomain in Shakespeare Deploy 2025-12-09 19:58:18 -06:00
Alex Gleason 83b20c88f0 Don't nag git updates so much 2025-12-09 19:42:00 -06:00
Alex Gleason 52863b808b Improve Quilly offline text 2025-12-09 13:45:26 -06:00
Alex Gleason 0fb4bcf375 Fix exhaustive-deps issue in VFSImage 2025-12-09 13:31:55 -06:00
Alex Gleason 8f66e44162 Improve APIConnectionError in Quilly 2025-12-09 13:29:51 -06:00
Alex Gleason 4e231844a5 Hide image preview when it has an error in ToolCallDisplay 2025-12-09 12:47:43 -06:00
Alex Gleason 3a546880f8 Fix lightbox for portrait images 2025-12-09 01:49:39 -06:00
Alex Gleason 4106bc77b3 Chat models default to png 2025-12-09 01:24:14 -06:00
Alex Gleason 77f29c12af Wait a few seconds for GRASP servers to update after creating the repo announcement event 2025-12-09 01:21:44 -06:00
Alex Gleason d8806d1ee4 Prefer high compression, jpeg/webp images 2025-12-09 01:17:15 -06:00
Alex Gleason 3592aff575 Accept additional parameters into generate_image tool 2025-12-09 00:45:13 -06:00
Alex Gleason 62b1a19f2d Expose imageModel to system prompt 2025-12-09 00:33:54 -06:00
Alex Gleason d8bf0d0432 Make ToolCallDisplay aware of tool failure 2025-12-08 15:59:36 -06:00
Alex Gleason c03e630d66 Add special rendering for missing tools 2025-12-08 15:41:34 -06:00
Alex Gleason 73ccd7cb73 Accumulate tool cost to project total 2025-12-08 15:32:14 -06:00
Alex Gleason a9b22e2381 Return cost information from GenerateImageTool 2025-12-08 15:24:14 -06:00
Alex Gleason f7b2d754e9 Tool result refactor (return an object instead of a string) 2025-12-08 15:13:34 -06:00
Alex Gleason 9c86ced552 Remove unused import 2025-12-08 14:45:11 -06:00
Alex Gleason 631cd98a1b Fix image generation skeleton 2025-12-08 14:41:41 -06:00
Alex Gleason 48cbc46d9b Create unified ToolCallDisplay component 2025-12-08 14:32:11 -06:00
Alex Gleason 5fab750222 Clicking outside the lightbox closes it 2025-12-08 14:10:58 -06:00
Alex Gleason de3fb92304 Split out ImageLightBox into a separate component 2025-12-08 14:07:29 -06:00
Alex Gleason ed426b0eab Generated image lightbox 2025-12-08 14:04:32 -06:00
Alex Gleason 2eda6749ce Fix system prompt test 2025-12-08 14:01:04 -06:00
Alex Gleason 3f0d49ceb3 Render image below tool 2025-12-08 13:53:37 -06:00
Alex Gleason f42ca5897a Expose model and provider to system prompt 2025-12-08 13:44:01 -06:00
Alex Gleason 3b44deb26f Memoize image model filters 2025-12-08 13:20:06 -06:00
Alex Gleason b2266581ad Fix model filtering in available models tool 2025-12-08 13:17:14 -06:00
Alex Gleason 147a620a0f Mark definite image generation models 2025-12-08 13:08:11 -06:00
Alex Gleason 25d065f112 Filter out non-image models with a callback 2025-12-08 12:59:24 -06:00
Alex Gleason 9181124467 Filter out non-chat models from ModelSelector 2025-12-08 00:49:52 -06:00
Alex Gleason 465364ffc0 Support the model "type" property 2025-12-07 23:56:56 -06:00
Alex Gleason 0b076d2114 Refactor image generation tool 2025-12-07 23:40:29 -06:00
Alex Gleason e1028e9f5e Prefer specific image models if they're available 2025-12-07 23:23:46 -06:00
Alex Gleason 1f850bc8a2 Filter out non-text models in OnboardingModal 2025-12-07 22:34:08 -06:00
Alex Gleason 8aa04464db Greatly simplify image generation config tools 2025-12-07 22:20:05 -06:00
Alex Gleason db2739cb77 Improve failed image generation request UX 2025-12-07 22:05:16 -06:00
Alex Gleason 60a4f77364 Add tools to configure an image model, add image model to system prompt 2025-12-07 21:44:28 -06:00
Alex Gleason 0d524f7c36 Revert "Use currently-selected model to generate images if it supports image output modality"
This reverts commit c2ccc3e60b.
2025-12-07 20:52:38 -06:00
Alex Gleason 6455b1d933 Fix tests 2025-12-07 20:37:50 -06:00
Alex Gleason d35b6601c5 npx eslint --fix 2025-12-07 20:17:23 -06:00
Alex Gleason fefd589187 Don't completely remove the tmpDir; ensure it exists before saving a generated image to it 2025-12-07 20:02:01 -06:00
Alex Gleason 38450a4793 Handle both b64_json and url data from image generations API 2025-12-07 19:53:18 -06:00
Alex Gleason 1f15dc7380 Fix modalities test 2025-12-07 19:43:44 -06:00
Alex Gleason 084b1e4d72 Remove "Generated: " 2025-12-07 17:20:12 -06:00
Alex Gleason 49300ed7b0 We only care about output modalities 2025-12-07 17:17:20 -06:00
Alex Gleason c2ccc3e60b Use currently-selected model to generate images if it supports image output modality 2025-12-07 16:46:02 -06:00
Alex Gleason d97bf1e2aa Use API model info to decide how to generate image instead of hardcoding provider ID 2025-12-07 16:40:10 -06:00
Alex Gleason 67a2290b89 Filter image models by modalities, if provided 2025-12-07 16:15:36 -06:00
Alex Gleason b9bc22eaf0 Improve image generation loading state 2025-12-07 15:25:55 -06:00
Alex Gleason 21341304b8 Improve tool calling i18n 2025-12-07 15:15:55 -06:00
Alex Gleason 799aaa5696 Fix streaming message rendering, add state for awaiting tool response 2025-12-07 15:09:38 -06:00
Alex Gleason 32892c8840 ngit: if there's no repo state event, clone from the best ngit server 2025-12-07 03:55:34 -06:00
Alex Gleason 8b1f2e381c Move imageModel to VFS 2025-12-07 03:04:02 -06:00
Alex Gleason 16b49e82bb Image generation reset icon to X 2025-12-07 02:46:52 -06:00
Alex Gleason 6885e2beec Fix generate_image tool, fix rendering of image from VFS 2025-12-07 02:43:29 -06:00
Alex Gleason b8638ac13a Add generate_image tool 2025-12-07 02:01:02 -06:00
Alex Gleason ff51fa2f77 Remove fake Typecheck tool 2025-12-07 00:26:43 -06:00
Alex Gleason 8b193c3a33 Merge branch 'iframeForm' into 'main'
Allow form submission in preview iframe

See merge request soapbox-pub/shakespeare!83
2025-12-07 01:39:59 +00:00
Alex Gleason 6ba82b5e4a Tag ErrorBoundaries as fatal in Sentry 2025-12-06 15:44:31 -06:00
Chad Curtis 8bad3cfc81 Allow form submission in iframes 2025-12-06 20:33:01 +00:00
Alex Gleason 3f792defcc Fix scrolling inside of label selector 2025-12-05 17:57:14 -06:00
Alex Gleason 274f9715ba Merge branch 'folders' into 'main'
Add project labels feature

See merge request soapbox-pub/shakespeare!80
2025-12-05 23:32:03 +00:00
Alex Gleason bbee14b675 Create src/lib/labels.ts 2025-12-05 17:28:53 -06:00
Alex Gleason 048846865f Merge remote-tracking branch 'origin/main' into folders 2025-12-05 17:23:09 -06:00
Alex Gleason 87fb13c131 Project Details dialog folder icon color 2025-12-05 17:22:05 -06:00
Alex Gleason dea9288fd4 Access Manage Labels through label input 2025-12-05 17:21:05 -06:00
Alex Gleason 6899220f27 Remove labels from Preferences 2025-12-05 17:17:03 -06:00
Alex Gleason 16e1577dc9 Add Manage Labels to left sidebar, improve UX 2025-12-05 17:15:17 -06:00
Alex Gleason 487d3c378d Add uncategorized collapsable labels section 2025-12-05 17:08:00 -06:00
Alex Gleason 25c2da6dd5 Display project in each label group it belongs to 2025-12-05 16:53:22 -06:00
Alex Gleason 083ae9d82e Add labels chevron to projects sidebar 2025-12-05 16:50:33 -06:00
Alex Gleason c962e9632e Replace label dot and chevron with colored label icon 2025-12-05 16:45:46 -06:00
Alex Gleason 32f12f08c1 Fix star button alignment 2025-12-05 16:41:10 -06:00
Alex Gleason 5840a3ffe8 De-indent label headers, remove project count 2025-12-05 16:38:32 -06:00
Alex Gleason 15690f25e5 Replace "unlabeled" with a separator 2025-12-05 16:34:58 -06:00
Alex Gleason 26f02819b1 Use a random color instead of blue as the selected color for new labels 2025-12-05 16:26:23 -06:00
Alex Gleason bc976fd58e Let me create a label directly from the Project Details dialog 2025-12-05 16:24:41 -06:00
Alex Gleason 5bcaff0536 Improve design of labels input in Project Details dialog 2025-12-05 16:21:13 -06:00
Alex Gleason 8c5dd1f49c Remove labels preferences 2025-12-05 16:18:42 -06:00
Alex Gleason 096e703c20 Improve design of Manage Labels dialog 2025-12-05 16:06:03 -06:00
Alex Gleason e6c7cc4316 Remove "order" property from labels 2025-12-05 15:50:28 -06:00
Alex Gleason b13b96c8fb Merge branch 'selectorBug' into 'main'
bug fix: models disappear if list is small

See merge request soapbox-pub/shakespeare!82
2025-12-05 02:54:11 +00:00
lemonknowsall 7f378311ca bug fix: models disappear if list is small 2025-12-04 18:44:35 -08:00
Alex Gleason 720aba0ff7 Prewarm user's follow list, speed up discover plugins hook 2025-12-04 20:42:46 -06:00
Alex Gleason 67fc846ba3 Use stricter input validation in renderSpecialContent (remove type assertions) 2025-12-04 20:26:16 -06:00
Alex Gleason 9a288c38c7 Allow duplicating a project 2025-12-04 19:47:12 -06:00
Alex Gleason acadf07a68 Small plugins design tweaks 2025-12-04 18:09:49 -06:00
Alex Gleason 9005a2c38e Display plugins from people you follow 2025-12-04 18:06:13 -06:00
Alex Gleason 4c9e688009 Nostr plugin discovery 2025-12-04 17:56:35 -06:00
Alex Gleason 96b9088551 Fix text overflow issue with homepage textarea 2025-12-04 16:29:19 -06:00
Alex Gleason 7b84447f29 Simplify homepage textarea 2025-12-04 16:25:44 -06:00
Alex Gleason 2a39dcaf86 Emphasize the textarea on the homepage; position the showcase to peek from the bottom 2025-12-04 16:13:03 -06:00
Alex Gleason 2096c83b3c Let baseDomain be configured for Cloudflare and Deno Deploy 2025-12-04 00:17:11 -06:00
Alex Gleason bbb4a2534b Fix Deno Deploy so it works 2025-12-04 00:02:50 -06:00
Alex Gleason 5685c6f52f Fix Deno config in configUtils 2025-12-03 23:57:01 -06:00
Alex Gleason 12c4acf3d5 Add Deno Deploy adapter 2025-12-03 23:48:20 -06:00
Alex Gleason 77a648e77e Redesign inputs on other pages 2025-12-03 23:20:02 -06:00
Alex Gleason ff6932ecda Upload Cloudflare files in parallel 2025-12-03 23:11:15 -06:00
Alex Gleason 74b5f60df8 Improve Get Key inputs 2025-12-03 23:02:50 -06:00
Alex Gleason 6c4bd9bd7c Deploy to Cloudflare Workers instead of Cloudflare Pages 2025-12-03 22:57:12 -06:00
Alex Gleason 45061bfbb9 Merge remote-tracking branch 'origin/main' into cf 2025-12-03 22:05:31 -06:00
Alex Gleason 6ce25ad2a1 Add the missing headers to the OPTIONS response 2025-12-03 22:05:05 -06:00
Alex Gleason 1f896b2ab5 Merge remote-tracking branch 'origin/main' into cf 2025-12-03 22:04:33 -06:00
Alex Gleason ed7f60692d Allow PUT and PATCH through CORS proxy 2025-12-03 21:58:02 -06:00
Alex Gleason cc8a02a564 Fix Cloudflare config persistence 2025-12-03 21:21:30 -06:00
Alex Gleason 9017c5c382 Fix Cloudflare deploy 2025-12-03 20:53:04 -06:00
Alex Gleason 3f3ac26c65 Fix account ID URL 2025-12-03 20:28:33 -06:00
Alex Gleason fef40abcae Improve input external link hover style 2025-12-03 20:09:47 -06:00
Alex Gleason b345145ad3 Improve design of "Get Key" inputs 2025-12-03 20:02:50 -06:00
Alex Gleason 46db6542aa Add Cloudflare deployment provider 2025-12-03 19:37:36 -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
MK Fain 18d088660f Show labels settings always, disabled until labels exist
- Project Labels section now always visible in Preferences
- Toggle switches are grayed out and disabled when no labels exist
- Added helper text "Create a label to enable these settings"
- Users can still click "Manage Labels" to create their first label
- Added translations for new helper text in all 6 languages
2025-12-03 13:49:16 -06:00
MK Fain 7e7ef35ff6 Add drag-and-drop reordering for labels in manage dialog
- Implemented using @dnd-kit/core and @dnd-kit/sortable
- Grip handle now functional for reordering labels
- Supports both pointer and keyboard interactions
- Reorder persists via reorderLabels() in useLabels hook
2025-12-03 13:43:22 -06:00
MK Fain 63d23f5510 Add project labels feature similar to Gmail labels
Features:
- Create and manage labels with customizable colors (18 color options)
- Assign multiple labels to projects via Project Details dialog
- Display settings in Preferences (only shown when labels exist):
  - Colored folder icons: Show project folder icons in label color
  - Group by label: Organize sidebar projects into collapsible groups
- Labels work alongside existing favorites (starred) system:
  - Favorites still sort to top within label groups
  - Star indicator remains visible in all display modes
- Collapsible label groups in sidebar (state persists)
- Unlabeled projects shown at bottom when grouping is enabled
- No UI changes for users without labels (settings hidden until first label)

Technical:
- useLabels hook: Manage labels CRUD and display settings
- useProjectLabels hook: Manage project-label assignments
- LabelSelector component: Assign labels to projects
- LabelsManageDialog: Create, edit, delete labels
- Full i18n support for EN, PT, ZH, HA, YO, IG
2025-12-03 13:25:35 -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
DanConwayDev 77a1a17c06 Fix git fetch toast missfire
toast trigger was comparing state with the previous fetch rather than the
local state we gather just before the fetch
2025-11-13 07:34:45 +00:00
299 changed files with 26395 additions and 23283 deletions

No files matched your search

+5 -17
View File
@@ -33,16 +33,14 @@ This architecture allows Shakespeare to provide a full development environment e
Shakespeare provides AI agents with specialized tools for project development (note: these are different from the tools available during Shakespeare's own development). These tools are defined in `src/lib/tools/`:
- **ShellTool**: Execute shell commands (virtual in browser, real OS shell in Electron)
- **ShellTool**: Execute shell commands in the virtual browser environment
- **TextEditorViewTool**: Read file contents and view directory structures
- **TextEditorWriteTool**: Create or overwrite files with new content
- **TextEditorStrReplaceTool**: Replace strings in files
- **BuildProjectTool**: Build and compile projects
- **TypecheckTool**: Run TypeScript type checking
- **NpmAddPackageTool**: Add npm packages to projects
- **NpmRemovePackageTool**: Remove npm packages from projects
- **GitCommitTool**: Commit changes to Git repositories
- **DeployProjectTool**: Deploy projects to hosting platforms
- **ReadWebpageTool**: Fetch and read web pages
- **NostrReadNipTool**: Read Nostr protocol NIP documents
- **NostrReadKindTool**: Read Nostr event kind documentation
@@ -55,7 +53,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
#### Shell Commands
**In Browser Mode:**
Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations.
**Available Commands:**
@@ -64,16 +61,6 @@ Shakespeare provides a comprehensive set of shell commands that are JavaScript r
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
**In Electron Mode:**
When running in Electron, the ShellTool automatically uses the **real OS terminal** instead of the virtual terminal. This means:
- **All OS commands available**: Not limited to built-in commands
- **Native shell features**: Pipes, redirection, environment variables work natively
- **Package managers**: `npm`, `yarn`, `pnpm` work directly
- **Build tools**: `vite`, `webpack`, `tsc`, etc. available
- **System utilities**: Full access to OS commands
The ShellTool detects the environment automatically and uses the appropriate execution method.
#### Security
AI filesystem access through tools (including shell commands via ShellTool) has path restrictions to ensure safe operation:
@@ -91,7 +78,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)
- **useGitFetch Hook**: Automatic remote fetch
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
#### Core Features
@@ -220,7 +207,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
- `useGitFetch`: Automatic remote fetch
- `useProjects`: Project management and CRUD operations
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
- `useTheme`: Theme management
@@ -241,7 +228,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
- `/src/lib/tools/`: AI tool implementations for project development
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
- Project tools: `BuildProjectTool`, `TypecheckTool`, `DeployProjectTool`
- Project tools: `BuildProjectTool`
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
- Git integration: `GitCommitTool`
- Shell access: `ShellTool`
@@ -1301,6 +1288,7 @@ When users specify color schemes:
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
- **Use `hover:bg-muted` for hover states on clickable cards/buttons** - provides subtle, accessible feedback without overpowering the design (avoid `hover:bg-accent` or `hover:bg-secondary` which can be too strong)
## Writing Tests vs Running Tests
+42 -2
View File
@@ -15,6 +15,7 @@ The OAuth system consists of three main components:
- **GitHub** - Git repository hosting (with PKCE support)
- **Netlify** - Static site deployment
- **Vercel** - Static site deployment
- **OpenRouter** - AI model routing (with PKCE support)
## File Structure
@@ -24,11 +25,13 @@ src/
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
│ └── useVercelOAuth.ts # Vercel-specific configuration
│ ├── useVercelOAuth.ts # Vercel-specific configuration
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
├── pages/
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
│ └── VercelOAuth.tsx # Vercel OAuth callback page
│ ├── VercelOAuth.tsx # Vercel OAuth callback page
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
└── AppRouter.tsx # Routes for OAuth callbacks
```
@@ -190,6 +193,7 @@ const config: OAuthConfig = {
- ✅ GitHub - Supports PKCE (enabled)
- ❌ Netlify - Doesn't support PKCE (disabled)
- ❌ Vercel - Doesn't support PKCE (disabled)
- ✅ OpenRouter - Requires PKCE (enabled)
### Scope Parameter
@@ -199,6 +203,42 @@ The `scope` parameter is optional in the OAuth configuration. Some providers (li
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
- ❌ Netlify - No scope parameter (permissions set in app settings)
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
- ❌ OpenRouter - No scope parameter (uses PKCE for authorization)
### OpenRouter Custom OAuth Implementation
OpenRouter uses a custom OAuth flow that differs from the standard OAuth 2.0 specification. Instead of using the generic `useOAuth` hook, it has a dedicated `useOpenRouterOAuth` hook with the following key differences:
1. **No Client Credentials**: OpenRouter doesn't require client ID or client secret - it uses PKCE only
2. **Authorization URL**: Uses `callback_url` parameter instead of `redirect_uri`
3. **Token Exchange**: Posts to `/api/v1/auth/keys` with a simplified request body
4. **Response Format**: Returns `{ key }` instead of standard `{ access_token }`
5. **PKCE Required**: Must use PKCE with S256 code challenge method
6. **No User Info**: Doesn't provide a user info endpoint after authentication
7. **No Environment Variables**: No configuration needed - works out of the box
**Authorization URL Format:**
```
https://openrouter.ai/auth?callback_url=<REDIRECT_URI>&code_challenge=<CHALLENGE>&code_challenge_method=S256
```
**Token Exchange Request:**
```json
{
"code": "<CODE_FROM_QUERY_PARAM>",
"code_verifier": "<CODE_VERIFIER>",
"code_challenge_method": "S256"
}
```
**Token Exchange Response:**
```json
{
"key": "sk-or-v1-..."
}
```
This custom implementation is fully contained in `useOpenRouterOAuth.ts` and doesn't rely on the generic OAuth hook. Unlike other providers, OpenRouter's OAuth doesn't require any environment variables or application registration - it works immediately without configuration.
## Adding a New OAuth Provider
+1 -5
View File
@@ -174,9 +174,6 @@ When called, it:
Plugins are stored in the configured plugins directory:
- **Browser**: `/plugins` (IndexedDB via LightningFS)
- **Electron (Windows)**: `~/AppData/Local/shakespeare/plugins`
- **Electron (macOS)**: `~/Library/Application Support/shakespeare/plugins`
- **Electron (Linux)**: `~/.config/shakespeare/plugins`
## System Prompt Integration
@@ -250,8 +247,7 @@ When designing web interfaces, follow these principles:
Configure in **Settings > System > Filesystem Paths**:
- Default browser: `/plugins`
- Default Electron: OS-specific (see Storage section)
- Default: `/plugins`
- Custom: Any absolute path
Changes take effect immediately.
-5
View File
@@ -1,5 +0,0 @@
package.json
package-lock.json
README.md
node_modules/
dist/
-582
View File
@@ -1,582 +0,0 @@
# Shakespeare Electron - Complete Guide
This guide provides comprehensive documentation for developing, building, and troubleshooting the Shakespeare Electron desktop application.
## Table of Contents
1. [Filesystem Architecture](#filesystem-architecture)
2. [Terminal Integration](#terminal-integration)
3. [Development Workflow](#development-workflow)
4. [Building for Distribution](#building-for-distribution)
5. [Troubleshooting](#troubleshooting)
---
## Filesystem Architecture
### Overview
The Electron version uses your local OS filesystem at `~/shakespeare` instead of IndexedDB, providing direct file access and unlimited storage.
### Path Resolution
All paths are relative to `~/shakespeare`:
- `/projects/my-app/` → `~/shakespeare/projects/my-app/`
- `/tmp/upload.txt` → `~/shakespeare/tmp/upload.txt`
- `/config/ai.json` → `~/shakespeare/config/ai.json`
### Implementation
**Automatic Adapter Selection** (`src/App.tsx`):
```typescript
const fs = window.electron?.isElectron
? new NodeFSAdapter() // Real filesystem
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
```
**IPC Communication Flow:**
1. **Renderer** (`NodeFSAdapter.ts`) - Calls `window.electron.fs.*` methods
2. **Preload** (`preload.js`) - Exposes API via `contextBridge`
3. **Main** (`main.js`) - Handles IPC with `ipcMain.handle()`, performs filesystem operations
### Supported Operations
All standard filesystem operations are supported:
- **Files**: `readFile`, `writeFile`, `unlink`, `rename`
- **Directories**: `readdir`, `mkdir`, `rmdir`
- **Metadata**: `stat`, `lstat`
- **Symlinks**: `readlink`, `symlink`
### Benefits
✅ **No storage limits** - Only limited by disk space
✅ **Direct access** - Use any editor, file manager, or Git client
✅ **Easy backup** - Standard backup tools work
✅ **Better performance** - Faster for large projects
✅ **Data portability** - Copy projects between machines
### Data Migration
**Browser to Electron:**
1. Export project as ZIP from browser
2. Import ZIP in Electron version
**Electron to Browser:**
1. Export project as ZIP from Electron
2. Import ZIP in browser version
---
## Terminal Integration
### Overview
The Electron version uses the **real OS terminal** instead of the virtual terminal, providing access to all system commands.
### Architecture
**ShellTool Detection** (`src/lib/tools/ShellTool.ts`):
```typescript
if (window.electron?.shell) {
// Use real OS shell
const result = await window.electron.shell.exec(command, workingDir);
} else {
// Use virtual command system
const result = await executeCommand(command, workingDir, fs);
}
```
**Shell Execution** (`electron/main.js`):
- Uses `child_process.spawn()` to execute commands
- Windows: Uses `cmd.exe`
- macOS/Linux: Uses `/bin/sh`
- Executes in project directory: `~/shakespeare/projects/{projectId}`
### Features
**All OS Commands Available:**
```bash
# Package managers
$ npm install
$ yarn add lodash
$ pnpm update
# Build tools
$ vite build
$ webpack --config webpack.config.js
$ tsc --noEmit
# Git operations
$ git commit -m "Update"
$ git push origin main
# System utilities
$ grep -r "TODO" src/
$ curl https://api.example.com
$ python script.py
```
**Native Shell Features:**
- Pipes: `ls | grep ".ts$"`
- Redirection: `echo "test" > file.txt`
- Environment variables: `$PATH`, `$HOME`
- Command chaining: `npm install && npm run build`
### ANSI Code Stripping
Output from shell commands is cleaned for AI consumption:
- Color codes removed (e.g., `\u001b[31m`)
- Cursor control sequences stripped
- Text formatting removed (bold, italic)
- Newlines preserved
**Example:**
```
Input: \u001b[1m\u001b[32madded 142 packages\u001b[39m\u001b[22m in 3s
Output: added 142 packages in 3s
```
Terminal UI still shows colored output for users.
### Platform Support
| Platform | Shell | Notes |
|----------|-------|-------|
| macOS | `/bin/sh` | All Unix commands available |
| Linux | `/bin/sh` | Standard Linux utilities |
| Windows | `cmd.exe` | Windows commands, consider Git Bash for Unix tools |
### Security
- Commands run with user permissions (no sudo/elevation)
- Working directory sandboxed to `~/shakespeare`
- Environment variables inherited from Electron process
---
## Development Workflow
### Running in Development Mode
```bash
npm run electron:dev
```
This will:
1. Start Vite dev server on http://localhost:5173
2. Wait for server to be ready
3. Launch Electron with hot reload
4. Open DevTools automatically
### Testing Shell Execution
Use the provided test script to verify shell functionality:
```bash
# Start Electron in dev mode
npm run electron:dev
# Open DevTools (View > Toggle Developer Tools)
# Paste contents of electron/test-terminal.js into console
```
The test script verifies:
- Basic command execution
- File listing
- Node.js version check
- Error handling
- Working directory
### Debugging
**Renderer Process:**
- DevTools open automatically in dev mode
- Or press `Cmd+Option+I` (macOS) / `Ctrl+Shift+I` (Windows/Linux)
**Main Process:**
```bash
# Enable verbose logging
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
```
**Check Configuration:**
```bash
node electron/test-config.js
```
### File Watching
In development mode:
- Vite provides hot module replacement
- Changes to React components reload instantly
- Electron process restarts on main.js changes (via `nodemon` in the script)
---
## Building for Distribution
### Prerequisites
- Node.js 18+ installed
- All dependencies installed: `npm install`
- Web build completed: `npm run build`
### Build Commands
**Current Platform:**
```bash
npm run electron:build
```
**Specific Platforms:**
```bash
npm run electron:build:mac # macOS (DMG + ZIP)
npm run electron:build:win # Windows (NSIS + Portable)
npm run electron:build:linux # Linux (AppImage, DEB, RPM)
npm run electron:build:all # All platforms
```
### Build Output
```
electron-dist/
├── mac/
│ ├── Shakespeare.app # macOS application bundle
│ ├── Shakespeare.dmg # DMG installer
│ └── Shakespeare-mac.zip # ZIP archive
├── win-unpacked/
│ └── Shakespeare.exe # Windows executable
├── Shakespeare Setup.exe # NSIS installer
├── Shakespeare Portable.exe # Portable executable
├── shakespeare-*.AppImage # Linux AppImage
├── shakespeare_*.deb # Debian package
└── shakespeare-*.rpm # RPM package
```
### Platform-Specific Notes
**macOS:**
- Builds for Intel (x64) and Apple Silicon (arm64)
- Code signing optional for development
- For distribution: Requires Apple Developer account
**Windows:**
- Builds for x64 and ARM64
- No code signing required for development
- For distribution: EV certificate recommended for SmartScreen
**Linux:**
- Builds for x64 and ARM64
- AppImage requires FUSE: `sudo apt-get install fuse`
- DEB/RPM packages can be installed with package managers
### Cross-Platform Limitations
- **macOS builds require macOS** (for code signing)
- Windows/Linux can be built from any platform
- Use GitHub Actions or CI/CD for multi-platform builds
### Code Signing
**Development (Disable Signing):**
Edit `electron/builder.config.js`:
```javascript
mac: {
identity: null, // Disable code signing
}
```
**Production (macOS):**
1. Obtain Apple Developer account
2. Create certificates in Xcode
3. Configure signing in builder.config.js
4. See: https://www.electron.build/code-signing
**Production (Windows):**
1. Obtain EV code signing certificate
2. Configure in builder.config.js
3. Builds reputation with SmartScreen over time
---
## Troubleshooting
### Development Issues
#### Port 5173 Already in Use
**Solution:**
```bash
# Find and kill the process
lsof -i :5173 # macOS/Linux
netstat -ano | findstr :5173 # Windows
# Or change the port in vite.config.ts
export default defineConfig({
server: { port: 5174 },
});
```
#### Blank Screen on Launch
**Browser Mode:**
1. Check Vite server is running: http://localhost:5173
2. Check Electron console for errors
3. Verify URL in `electron/main.js` matches Vite server
4. Clear cache: Delete `node_modules/.vite`
**Production Build:**
1. Ensure `base: './'` is set in `vite.config.ts`
2. Check `dist/` directory contains all files
3. Look for "Failed to load resource" errors in console
4. Verify file:// protocol is used in loadURL
#### Assets Fail to Load: "net::ERR_FILE_NOT_FOUND"
**Problem:** CSS/JS fail to load with `file:///assets/npm/...` errors
**Solution:** Add to `vite.config.ts`:
```typescript
export default defineConfig(() => ({
base: './', // Required for Electron
// ... rest of config
}))
```
Then rebuild: `npm run build`
#### 404 Error: Page Not Found
**Problem:** App shows "404: Oops! Page not found" on launch
**Solution:** Verify `HashRouter` is used in Electron.
Check `src/AppRouter.tsx`:
```typescript
const Router = window.electron?.isElectron ? HashRouter : BrowserRouter;
```
Rebuild: `npm run build && npm run electron:build`
#### Service Worker Errors
**Solution:** Service workers don't work with `file://` protocol.
Check `src/main.tsx`:
```typescript
if ('serviceWorker' in navigator && !window.electron?.isElectron) {
// Only register in web environment
}
```
#### CSP Font Errors
**Solution:** Update CSP in `index.html`:
```html
<meta http-equiv="content-security-policy"
content="... font-src 'self' data:; ...">
```
#### Broken SVG Images
**Problem:** Logo/SVG files show as broken
**Solution:** Import SVG files properly:
```typescript
// ❌ Wrong
<img src="/shakespeare.svg" alt="Logo" />
// ✅ Correct
import logo from '/shakespeare.svg?url';
<img src={logo} alt="Logo" />
```
#### Preload Script ESM Errors
**Solution:** Requires `sandbox: false` in webPreferences.
Check `electron/main.js`:
```javascript
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true, // Still enabled
sandbox: false, // Disabled for ESM
webSecurity: true,
}
```
### Build Issues
#### Build Fails with "Cannot find module"
**Solutions:**
1. Install dependencies: `npm install`
2. Clear and reinstall: `rm -rf node_modules package-lock.json && npm install`
3. Build web first: `npm run build`
4. Verify `dist/` exists
5. Check config: `node electron/test-config.js`
#### Icons Not Appearing
**Solution:** Should work automatically with `public/shakespeare-512x512.png`.
If not:
1. Verify PNG exists
2. Check build output for icon errors
3. Try: `npm run electron:icons` (requires ImageMagick)
4. Check paths in `electron/builder.config.js`
#### Code Signing Errors (macOS)
**Development:** Disable signing:
```javascript
mac: {
identity: null,
}
```
**Production:** Requires Apple Developer account and certificates.
#### App Won't Launch After Build
**Solutions:**
1. Check console/terminal for errors
2. Try unpacked version first
3. macOS: Check Security & Privacy settings
4. Windows: Check Windows Defender logs
5. Verify `dist/` contains valid files
### Runtime Issues
#### App Crashes on Startup
**Solutions:**
1. Check crash logs:
- macOS: `~/Library/Logs/Shakespeare/`
- Windows: `%APPDATA%\Shakespeare\logs\`
- Linux: `~/.config/Shakespeare/logs/`
2. Run from terminal to see errors
3. Test web build in browser first
#### Shell Execution Error: "spawn /bin/sh ENOENT"
**Problem:** Terminal commands fail with spawn error
**Root Cause:** Working directory doesn't exist
**Solution:** Should be fixed - main.js creates directories automatically.
**Debug:**
1. Open DevTools
2. Check console for "Shell exec in directory: ..."
3. Verify directory exists: `ls -la ~/shakespeare/projects/`
4. Manually create if needed: `mkdir -p ~/shakespeare/projects`
#### External Links Not Opening
**Solution:** Should open in default browser automatically.
Check `electron/main.js` has:
```javascript
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
```
### Platform-Specific Issues
#### macOS: "App is damaged and can't be opened"
**Solutions:**
1. Development: `xattr -cr /path/to/Shakespeare.app`
2. Distribution: Requires code signing
3. Users: Right-click → Open (instead of double-click)
#### Windows: "Windows protected your PC"
**Solutions:**
1. Testing: Click "More info" → "Run anyway"
2. Distribution: Requires EV code signing
3. Build reputation over time
#### Linux: "Permission denied"
**Solutions:**
1. Make executable: `chmod +x Shakespeare*.AppImage`
2. Install FUSE: `sudo apt-get install fuse`
3. Try DEB/RPM package instead
### Performance Issues
#### App Feels Slow
**Solutions:**
1. Close DevTools
2. Check system resources
3. Use production build
4. Disable hardware acceleration in `main.js`:
```javascript
app.disableHardwareAcceleration();
```
#### High Memory Usage
**Solutions:**
1. Normal for Chromium-based apps
2. Close unused projects
3. Restart app periodically
4. Check for memory leaks in web code
---
## Getting Help
If issues persist:
1. **Check existing issues:** https://gitlab.com/soapbox-pub/shakespeare/-/issues
2. **Create new issue** with:
- OS and version
- Electron version: `npm list electron`
- Steps to reproduce
- Error messages/logs
- Screenshots
3. **Community support:** Check project README for links
## Useful Commands
**Complete rebuild:**
```bash
rm -rf node_modules dist electron-dist package-lock.json
npm install
npm run build
npm run electron:build
```
**Check versions:**
```bash
npm list electron
node --version
npm --version
```
**Verbose logging:**
```bash
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
```
**Check build contents:**
```bash
npm run electron:build -- --dir
ls -la electron-dist/[platform]-unpacked/
```
## Additional Resources
- [Electron Documentation](https://www.electronjs.org/docs)
- [electron-builder Documentation](https://www.electron.build/)
- [Electron Security](https://www.electronjs.org/docs/latest/tutorial/security)
- [Debugging Electron](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process)
- [Shakespeare Main Docs](../README.md)
-22
View File
@@ -1,22 +0,0 @@
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import electron from 'electron';
const __dirname = dirname(fileURLToPath(import.meta.url));
const appPath = join(__dirname, '..');
const child = spawn(electron, [appPath], {
stdio: 'inherit',
windowsHide: false,
});
child.on('close', code => process.exit(code ?? 0));
child.on('error', err => {
console.error('Failed to launch Electron:', err);
process.exit(1);
});
process.on('SIGINT', () => child.kill('SIGINT'));
process.on('SIGTERM', () => child.kill('SIGTERM'));
-99
View File
@@ -1,99 +0,0 @@
/**
* TypeScript definitions for the Electron API exposed to the renderer process.
*
* Add this to your tsconfig.json include array to use these types:
* "include": ["src", "electron/electron.d.ts"]
*/
interface DirectoryEntry {
name: string;
isDirectory: boolean;
isFile: boolean;
}
interface StatResult {
isDirectory: boolean;
isFile: boolean;
isBlockDevice: boolean;
isCharacterDevice: boolean;
isSymbolicLink: boolean;
isFIFO: boolean;
isSocket: boolean;
size: number;
mtimeMs: number;
ctimeMs: number;
atimeMs: number;
// Timestamps (serialized as numbers for IPC)
mtime: number;
ctime: number;
atime: number;
}
interface ElectronFSAPI {
readFile(path: string, encoding?: string): Promise<string | number[]>;
writeFile(path: string, data: string | number[], encoding?: string): Promise<void>;
readdir(path: string, withFileTypes?: boolean): Promise<string[] | DirectoryEntry[]>;
mkdir(path: string, recursive?: boolean): Promise<void>;
stat(path: string): Promise<StatResult>;
lstat(path: string): Promise<StatResult>;
unlink(path: string): Promise<void>;
rmdir(path: string): Promise<void>;
rename(oldPath: string, newPath: string): Promise<void>;
readlink(path: string): Promise<string>;
symlink(target: string, path: string): Promise<void>;
}
interface ShellExecResult {
stdout: string;
stderr: string;
exitCode: number;
}
interface ElectronShellAPI {
/**
* Execute a shell command on the host OS.
* @param command - The command to execute
* @param cwd - Working directory (relative to ~/shakespeare)
* @returns Promise with stdout, stderr, and exit code
*/
exec(command: string, cwd?: string): Promise<ShellExecResult>;
}
interface ElectronAPI {
/**
* Get the user's home directory path.
*/
homedir: string;
/**
* Get the current platform.
* @returns 'darwin' | 'win32' | 'linux'
*/
platform(): Promise<string>;
/**
* Get the application version from package.json.
* @returns Version string (e.g., "1.0.0")
*/
version(): Promise<string>;
/**
* Filesystem API for accessing the local OS filesystem.
* All paths are relative to ~/shakespeare directory.
*/
fs: ElectronFSAPI;
/**
* Shell API for executing real shell commands on the host OS.
* All paths in commands are relative to ~/shakespeare directory.
*/
shell: ElectronShellAPI;
}
interface Window {
/**
* Electron API exposed via preload script.
* Only available when running in Electron.
*/
electron?: ElectronAPI;
}
-532
View File
@@ -1,532 +0,0 @@
import { app, BrowserWindow, ipcMain, shell, Menu, protocol } from 'electron';
import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
import os from 'os';
// ESM equivalent of __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let mainWindow;
function createWindow() {
// Remove the default menu (File, Edit, View, etc.)
Menu.setApplicationMenu(null);
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
sandbox: false, // Disabled to support ESM in preload
webSecurity: true,
},
icon: path.join(__dirname, 'dist/shakespeare-512x512.png'),
title: 'Shakespeare',
backgroundColor: '#ffffff',
});
// Enable DevTools keyboard shortcut (Ctrl+Shift+I / Cmd+Option+I)
mainWindow.webContents.on('before-input-event', (event, input) => {
// Check for Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac)
if (input.control && input.shift && input.key.toLowerCase() === 'i') {
mainWindow.webContents.toggleDevTools();
event.preventDefault();
}
// Also support F12
if (input.key === 'F12') {
mainWindow.webContents.toggleDevTools();
event.preventDefault();
}
});
// Load the app
if (process.env.ELECTRON_DEV) {
// Development mode - load from Vite dev server
console.log('Loading from Vite dev server: http://localhost:5173');
mainWindow.loadURL('http://localhost:5173');
mainWindow.webContents.openDevTools();
} else {
// Production mode - load from custom protocol
// This allows absolute paths like /shakespeare.svg to work naturally
console.log('Loading from app:// protocol: app://./index.html');
mainWindow.loadURL('app://./index.html');
}
// Log any load errors
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
console.error('Failed to load:', validatedURL, errorCode, errorDescription);
});
// Log successful load
mainWindow.webContents.on('did-finish-load', () => {
console.log('Successfully loaded app');
});
// Handle window close
mainWindow.on('closed', () => {
mainWindow = null;
});
}
// Register custom protocol scheme before app is ready (required for privileges)
if (!process.env.ELECTRON_DEV) {
protocol.registerSchemesAsPrivileged([
{
scheme: 'app',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: false,
},
},
]);
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.whenReady().then(async () => {
// Register the app:// protocol to serve files from dist/
// This allows absolute paths (/) to work naturally without base: './'
if (!process.env.ELECTRON_DEV) {
protocol.registerFileProtocol('app', (request, callback) => {
// Remove 'app://' prefix and normalize path
let filePath = request.url.replace('app://', '');
// Remove trailing slashes
filePath = filePath.replace(/\/+$/, '');
// Handle root path
if (filePath === '' || filePath === '/') {
filePath = 'index.html';
}
// Remove leading slash if present
if (filePath.startsWith('/')) {
filePath = filePath.substring(1);
}
// Resolve to dist directory
const fullPath = path.join(__dirname, 'dist', filePath);
console.log('Protocol handler:', request.url, '->', fullPath);
callback({ path: fullPath });
});
}
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
// Quit when all windows are closed, except on macOS.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// Handle app-level events
app.on('web-contents-created', (event, contents) => {
// Security: Prevent navigation to external sites
contents.on('will-navigate', (event, navigationUrl) => {
const parsedUrl = new URL(navigationUrl);
// Allow navigation within the app
if (parsedUrl.origin === 'http://localhost:5173' ||
parsedUrl.protocol === 'file:') {
return;
}
// Block all other navigation
event.preventDefault();
});
// Security: Prevent opening new windows
contents.setWindowOpenHandler(({ url }) => {
// Open external links in the default browser
shell.openExternal(url);
return { action: 'deny' };
});
});
// IPC handlers can be added here if needed for future Electron-specific features
// For example: file system access, native dialogs, etc.
// Example: Handle getting app version
ipcMain.handle('get-app-version', () => {
return app.getVersion();
});
// Example: Handle getting platform
ipcMain.handle('get-platform', () => {
return process.platform;
});
// Helper function to expand tilde (~) in paths
function expandTilde(filepath) {
if (filepath.startsWith('~/') || filepath === '~') {
return path.join(os.homedir(), filepath.slice(1));
}
return filepath;
}
// Filesystem IPC handlers
ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
if (!filePath) {
const err = new Error('Failed to read file: path is required');
err.code = 'EINVAL';
// Don't log - empty paths are expected from isomorphic-git's ref resolution
throw err;
}
try {
const fullPath = expandTilde(filePath);
const data = await fs.readFile(fullPath, encoding ? { encoding } : undefined);
// If no encoding, convert Buffer to array for IPC serialization
return encoding ? data : Array.from(data);
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
// Serialize the error code as a regular property so it survives IPC
const err = new Error(`Failed to read file ${filePath}: ${error.message}`);
// Copy enumerable properties including code
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
// Don't log ENOENT errors - these are expected for git packed objects and missing refs
// Only log unexpected errors
if (error.code !== 'ENOENT' && error.code !== 'EINVAL') {
console.error(err);
}
throw err;
}
});
ipcMain.handle('fs:writeFile', async (event, filePath, data, encoding) => {
if (!filePath) {
const err = new Error('Failed to write file: path is required');
err.code = 'EINVAL';
throw err;
}
try {
const fullPath = expandTilde(filePath);
// Ensure parent directory exists
await fs.mkdir(path.dirname(fullPath), { recursive: true });
// Convert array back to Buffer if needed
const dataToWrite = Array.isArray(data) ? Buffer.from(data) : data;
await fs.writeFile(fullPath, dataToWrite, encoding ? { encoding } : undefined);
} catch (error) {
const err = new Error(`Failed to write file ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
try {
const fullPath = expandTilde(dirPath);
const entries = await fs.readdir(fullPath, { withFileTypes: !!withFileTypes });
if (withFileTypes) {
// Convert Dirent objects to plain objects for IPC
return entries.map(entry => ({
name: entry.name,
isDirectory: entry.isDirectory(),
isFile: entry.isFile(),
}));
}
return entries;
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
// Only log non-ENOTDIR errors (ENOTDIR is expected when checking if a file is a directory)
if (error.code !== 'ENOTDIR') {
console.error(err);
}
throw err;
}
});
ipcMain.handle('fs:mkdir', async (event, dirPath, recursive) => {
try {
const fullPath = expandTilde(dirPath);
await fs.mkdir(fullPath, { recursive: !!recursive });
} catch (error) {
const err = new Error(`Failed to create directory ${dirPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:stat', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
const stats = await fs.stat(fullPath);
const now = Date.now();
return {
isDirectory: stats.isDirectory(),
isFile: stats.isFile(),
isBlockDevice: stats.isBlockDevice(),
isCharacterDevice: stats.isCharacterDevice(),
isSymbolicLink: stats.isSymbolicLink(),
isFIFO: stats.isFIFO(),
isSocket: stats.isSocket(),
size: stats.size,
mtimeMs: stats.mtimeMs ?? now,
ctimeMs: stats.ctimeMs ?? now,
atimeMs: stats.atimeMs ?? now,
// Date objects need to be serialized as timestamps for IPC
// Use optional chaining and fallback to now to prevent valueOf errors
mtime: stats.mtime?.getTime() ?? now,
ctime: stats.ctime?.getTime() ?? now,
atime: stats.atime?.getTime() ?? now,
};
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:lstat', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
const stats = await fs.lstat(fullPath);
const now = Date.now();
return {
isDirectory: stats.isDirectory(),
isFile: stats.isFile(),
isBlockDevice: stats.isBlockDevice(),
isCharacterDevice: stats.isCharacterDevice(),
isSymbolicLink: stats.isSymbolicLink(),
isFIFO: stats.isFIFO(),
isSocket: stats.isSocket(),
size: stats.size,
mtimeMs: stats.mtimeMs ?? now,
ctimeMs: stats.ctimeMs ?? now,
atimeMs: stats.atimeMs ?? now,
// Date objects need to be serialized as timestamps for IPC
// Use optional chaining and fallback to now to prevent valueOf errors
mtime: stats.mtime?.getTime() ?? now,
ctime: stats.ctime?.getTime() ?? now,
atime: stats.atime?.getTime() ?? now,
};
} catch (error) {
const err = new Error(`Failed to lstat ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:unlink', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
await fs.unlink(fullPath);
} catch (error) {
const err = new Error(`Failed to unlink ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:rmdir', async (event, dirPath) => {
try {
const fullPath = expandTilde(dirPath);
await fs.rmdir(fullPath);
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
const err = new Error(`Failed to remove directory ${dirPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:rename', async (event, oldPath, newPath) => {
try {
const fullOldPath = expandTilde(oldPath);
const fullNewPath = expandTilde(newPath);
// Ensure parent directory of new path exists
await fs.mkdir(path.dirname(fullNewPath), { recursive: true });
await fs.rename(fullOldPath, fullNewPath);
} catch (error) {
const err = new Error(`Failed to rename ${oldPath} to ${newPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:readlink', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
return await fs.readlink(fullPath);
} catch (error) {
const err = new Error(`Failed to read link ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:symlink', async (event, target, filePath) => {
try {
const fullPath = expandTilde(filePath);
// Ensure parent directory exists
await fs.mkdir(path.dirname(fullPath), { recursive: true });
await fs.symlink(target, fullPath);
} catch (error) {
const err = new Error(`Failed to create symlink ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
// Shell execution handler
ipcMain.handle('shell:exec', async (event, command, cwd) => {
return new Promise(async (resolve, reject) => {
try {
// Determine the shell and command execution method based on platform
const isWindows = process.platform === 'win32';
const shellCmd = isWindows ? 'cmd.exe' : '/bin/sh';
const shellArgs = isWindows ? ['/c', command] : ['-c', command];
// Expand tilde in working directory if provided, otherwise use home directory
const workingDir = cwd ? expandTilde(cwd) : os.homedir();
// Ensure the working directory exists before spawning
try {
await fs.mkdir(workingDir, { recursive: true });
console.log(`Shell exec in directory: ${workingDir}`);
console.log(`Command: ${command}`);
} catch (mkdirError) {
console.warn(`Failed to create directory ${workingDir}:`, mkdirError.message);
// Continue anyway - directory might already exist
}
const child = spawn(shellCmd, shellArgs, {
cwd: workingDir,
env: { ...process.env },
shell: false, // We're already using the shell
});
let stdout = '';
let stderr = '';
child.stdout?.on('data', (data) => {
stdout += data.toString();
});
child.stderr?.on('data', (data) => {
stderr += data.toString();
});
child.on('error', (error) => {
console.error('Shell execution error:', error);
console.error('Working directory:', workingDir);
console.error('Shell command:', shellCmd);
console.error('Shell args:', shellArgs);
reject(new Error(`Failed to execute command: ${error.message} (cwd: ${workingDir})`));
});
child.on('close', (code) => {
resolve({
stdout,
stderr,
exitCode: code ?? 0,
});
});
} catch (error) {
console.error('Shell setup error:', error);
reject(new Error(`Failed to setup shell execution: ${error.message}`));
}
});
});
-35
View File
@@ -1,35 +0,0 @@
import { contextBridge, ipcRenderer } from 'electron';
import os from 'node:os';
// Expose protected methods that allow the renderer process to use
// ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld('electron', {
// Get the home directory
homedir: os.homedir(),
// Platform information
platform: () => ipcRenderer.invoke('get-platform'),
// App version
version: () => ipcRenderer.invoke('get-app-version'),
// Filesystem API - paths support tilde (~) expansion for home directory
fs: {
readFile: (path, encoding) => ipcRenderer.invoke('fs:readFile', path, encoding),
writeFile: (path, data, encoding) => ipcRenderer.invoke('fs:writeFile', path, data, encoding),
readdir: (path, withFileTypes) => ipcRenderer.invoke('fs:readdir', path, withFileTypes),
mkdir: (path, recursive) => ipcRenderer.invoke('fs:mkdir', path, recursive),
stat: (path) => ipcRenderer.invoke('fs:stat', path),
lstat: (path) => ipcRenderer.invoke('fs:lstat', path),
unlink: (path) => ipcRenderer.invoke('fs:unlink', path),
rmdir: (path) => ipcRenderer.invoke('fs:rmdir', path),
rename: (oldPath, newPath) => ipcRenderer.invoke('fs:rename', oldPath, newPath),
readlink: (path) => ipcRenderer.invoke('fs:readlink', path),
symlink: (target, path) => ipcRenderer.invoke('fs:symlink', target, path),
},
// Shell API - execute real shell commands
shell: {
exec: (command, cwd) => ipcRenderer.invoke('shell:exec', command, cwd),
},
});
+9
View File
@@ -0,0 +1,9 @@
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"nostr": {
"type": "local",
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
}
}
}
+205 -703
View File
File diff suppressed because it is too large. Load diff
+4 -7
View File
@@ -17,9 +17,7 @@
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"typecheck": "npm i --silent && tsc --noEmit",
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
@@ -31,8 +29,8 @@
"@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",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -79,7 +77,7 @@
"isomorphic-git": "^1.32.1",
"jsonc-parser": "^3.3.1",
"jszip": "^3.10.1",
"lucide-react": "^0.525.0",
"lucide-react": "^0.562.0",
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
@@ -130,7 +128,6 @@
"@types/uri-templates": "^0.1.34",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"electron": "^39.0.0",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
-78
View File
@@ -1,78 +0,0 @@
#!/usr/bin/env node
import { readFileSync, writeFileSync, copyFileSync, rmSync, cpSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = join(__dirname, '..');
const electronDir = join(rootDir, 'electron');
const distDir = join(rootDir, 'dist');
const electronDistDir = join(electronDir, 'dist');
// Read root package.json
const rootPackage = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf-8'));
// Generate CalVer version (YYYY.MM.DDHHMM) in UTC
const now = new Date();
const year = now.getUTCFullYear();
const month = String(now.getUTCMonth() + 1).padStart(2, '0');
const day = String(now.getUTCDate()).padStart(2, '0');
const hour = String(now.getUTCHours()).padStart(2, '0');
const minute = String(now.getUTCMinutes()).padStart(2, '0');
const version = `${year}.${month}.${day}${hour}${minute}`;
// Get electron version from root devDependencies
const electronVersion = rootPackage.devDependencies.electron;
// Remove old electron/dist and copy new one
console.log('Removing old electron/dist...');
rmSync(electronDistDir, { recursive: true, force: true });
console.log('Copying dist to electron/dist...');
cpSync(distDir, electronDistDir, { recursive: true });
// Create electron package.json
const electronPackage = {
name: rootPackage.name,
description: rootPackage.description,
homepage: rootPackage.homepage,
license: rootPackage.license,
version: version,
type: "module",
main: "main.js",
bin: {
shakespeare: "./bin/shakespeare.js"
},
files: [
"bin/",
"dist/",
"main.js",
"package.json",
"preload.js",
"LICENSE",
"README.md"
],
author: rootPackage.author,
repository: rootPackage.repository,
dependencies: {
electron: electronVersion
}
};
// Write electron package.json
writeFileSync(
join(electronDir, 'package.json'),
JSON.stringify(electronPackage, null, 2) + '\n',
'utf-8'
);
// Copy README.md to electron directory
copyFileSync(
join(rootDir, 'README.md'),
join(electronDir, 'README.md')
);
console.log(`✓ Generated electron/package.json with version ${version}`);
console.log('✓ Copied README.md to electron/');
+23 -15
View File
@@ -23,24 +23,32 @@ export default {
} catch {
return new Response('Invalid url parameter', { status: 400 });
}
// AI-provider-specific hacks
let hostname = url.hostname;
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
hostname = 'ollama.com';
} else if (url.host === 'generativelanguage.googleapis.com') {
hostname = 'gemini.google.com';
} else if (url.host === 'api.z.ai') {
hostname = 'docs.z.ai';
}
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
hostname = hostname.replace(/^(ai\.|api\.)/, '');
return fetchFavicon(hostname);
},
};
// GitHub hack: neutral color for light/dark mode
if (hostname === 'github.com') {
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
return new Response(svg.replaceAll('#24292E', '#808080'), {
headers: { 'Content-Type': 'image/svg+xml' },
});
}
// AI-provider-specific hacks
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
hostname = 'ollama.com';
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
hostname = 'claude.ai';
} else if (url.host === 'generativelanguage.googleapis.com') {
hostname = 'gemini.google.com';
} else if (url.host === 'z.ai') {
hostname = 'docs.z.ai';
}
function fetchFavicon(hostname: string): Promise<Response> {
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
}
// Fetch the favicon from DuckDuckGo's service
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
},
};
@@ -160,16 +160,6 @@ consistent handling of both text and binary data across the messaging protocol.
**Parameters:** None
**Result:** None (notification only)
#### `goBack`
**Purpose:** Navigate back in the iframe's history
**Parameters:** None
**Result:** None (notification only)
#### `goForward`
**Purpose:** Navigate forward in the iframe's history
**Parameters:** None
**Result:** None (notification only)
#### `updateNavigationState`
**Purpose:** Update parent about iframe's current navigation state
**Parameters:**
@@ -193,12 +193,6 @@ class NavigationHandler {
case "refresh":
this.handleRefresh();
break;
case "goBack":
this.handleGoBack();
break;
case "goForward":
this.handleGoForward();
break;
}
}
});
@@ -286,14 +280,6 @@ class NavigationHandler {
window.location.reload();
}
handleGoBack() {
window.history.back();
}
handleGoForward() {
window.history.forward();
}
updateNavigationState() {
// Use tracked semantic path, fallback to current location if needed
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
+9 -8
View File
@@ -12,16 +12,17 @@ export default {
return new Response(null, {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Allow-Headers": "*", // Or specify specific headers
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
"access-control-allow-headers": "*", // Or specify specific headers
"access-control-max-age": "86400", // Cache preflight for 24 hours
}
});
}
const headers = new Headers(request.headers);
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
headers.set('user-agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
headers.delete('origin');
const targetResponse = await fetch(target, {
method: request.method,
@@ -31,9 +32,9 @@ export default {
const response = new Response(targetResponse.body, targetResponse);
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS");
response.headers.set("Access-Control-Allow-Headers", "*");
response.headers.set("access-control-allow-origin", "*");
response.headers.set("access-control-allow-methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
response.headers.set("access-control-allow-headers", "*");
return response;
}
+69 -79
View File
@@ -21,13 +21,14 @@ import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider';
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
import { GitSyncProvider } from '@/components/GitSyncProvider';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { ElectronFSAdapter } from '@/lib/ElectronFSAdapter';
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { NWCProvider } from '@/contexts/NWCContext';
import AppRouter from './AppRouter';
@@ -47,55 +48,6 @@ const queryClient = new QueryClient({
},
});
// Get OS-specific default paths for Electron
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } {
if (!globalThis.electron) {
// Browser defaults - use virtual filesystem paths
return {
fsPathProjects: "/projects",
fsPathConfig: "/config",
fsPathTmp: "/tmp",
fsPathPlugins: "/plugins",
fsPathTemplates: "/templates",
};
}
// Electron defaults - use OS-specific paths
// Note: The ~ will be expanded by the Electron main process
const platform = navigator.platform.toLowerCase();
if (platform.includes('win')) {
// Windows
return {
fsPathProjects: "~/Documents/Projects",
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
return {
fsPathProjects: "~/Projects",
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
return {
fsPathProjects: "~/Projects",
fsPathConfig: "~/.config/shakespeare",
fsPathTmp: "/tmp/shakespeare",
fsPathPlugins: "~/.config/shakespeare/plugins",
fsPathTemplates: "~/.config/shakespeare/templates",
};
}
}
const electronPaths = getElectronDefaultPaths();
const defaultConfig: AppConfig = {
theme: "system",
relayMetadata: {
@@ -106,39 +58,73 @@ const defaultConfig: AppConfig = {
],
updatedAt: 0,
},
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
graspMetadata: {
relays: [
{ url: 'wss://git.shakespeare.diy/' },
{ url: 'wss://relay.ngit.dev/' },
],
updatedAt: 0,
},
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",
},
],
esmUrl: "https://esm.sh",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
gitProxyOrigins: ["https://github.com", "https://gitlab.com"],
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
ngitWebUrl: "https://nostrhub.io/{naddr}",
previewDomain: "local-shakespeare.dev",
showcaseEnabled: true,
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
fsPathProjects: electronPaths.fsPathProjects,
fsPathConfig: electronPaths.fsPathConfig,
fsPathTmp: electronPaths.fsPathTmp,
fsPathPlugins: electronPaths.fsPathPlugins,
fsPathTemplates: electronPaths.fsPathTemplates,
fsPathProjects: "/projects",
fsPathConfig: "/config",
fsPathTmp: "/tmp",
fsPathPlugins: "/plugins",
fsPathTemplates: "/templates",
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
sentryEnabled: true,
};
// Initialize filesystem adapter based on environment
// In Electron, use Electron filesystem at ~/shakespeare
// In browser, use LightningFS (IndexedDB-backed virtual filesystem)
const fs = globalThis.electron
? new ElectronFSAdapter()
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
// Initialize filesystem adapter
// Use LightningFS (IndexedDB-backed virtual filesystem)
const fs = new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
// Component to handle filesystem cleanup on startup
// Automatically removes files older than 1 hour from tmp directory
// Component to handle filesystem initialization and cleanup on startup
// Ensures tmp directory exists and removes files older than 1 hour
function FSCleanupHandler() {
const { config } = useAppContext();
useEffect(() => {
// Run cleanup on application startup to remove stale temporary files
// This helps prevent the VFS from accumulating old files over time
cleanupTmpDirectory(fs, config.fsPathTmp).catch(console.error);
// Ensure tmp directory exists before cleanup
const initializeAndCleanup = async () => {
try {
// Create tmp directory if it doesn't exist
try {
await fs.stat(config.fsPathTmp);
} catch {
// Directory doesn't exist, create it
await fs.mkdir(config.fsPathTmp);
console.log(`Created ${config.fsPathTmp} directory`);
}
// Run cleanup to remove stale temporary files
// This helps prevent the VFS from accumulating old files over time
await cleanupTmpDirectory(fs, config.fsPathTmp);
} catch (error) {
console.error(`Error during filesystem initialization:`, error);
}
};
initializeAndCleanup();
}, [config.fsPathTmp]);
return null;
@@ -157,23 +143,27 @@ export function App() {
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<NWCProvider>
<AISettingsProvider>
<GitSettingsProvider>
<DeploySettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
<GitSyncProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</GitSyncProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleErrorProvider>
+6
View File
@@ -5,12 +5,14 @@ import { URLFragmentHandler } from "./components/URLFragmentHandler";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
import Explore from "./pages/Explore";
import Settings from "./pages/Settings";
import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DeploySettings from "./pages/DeploySettings";
import WalletSettings from "./pages/WalletSettings";
import SystemSettings from "./pages/SystemSettings";
import StorageSettings from "./pages/StorageSettings";
import AboutSettings from "./pages/AboutSettings";
@@ -18,6 +20,7 @@ import AboutSettings from "./pages/AboutSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import NetlifyOAuth from "./pages/NetlifyOAuth";
import VercelOAuth from "./pages/VercelOAuth";
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -36,9 +39,11 @@ export function AppRouter() {
<Route path="/" element={<Index />} />
<Route path="/giftcard" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/explore" element={<Explore />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
@@ -46,6 +51,7 @@ export function AppRouter() {
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="deploy" element={<DeploySettings />} />
<Route path="wallet" element={<WalletSettings />} />
<Route path="system" element={<SystemSettings />} />
<Route path="storage" element={<StorageSettings />} />
<Route path="about" element={<AboutSettings />} />
+29 -266
View File
@@ -1,14 +1,14 @@
import { memo, useState } from 'react';
import { Streamdown } from 'streamdown';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs, Send, Puzzle } from 'lucide-react';
import { Lightbulb, Loader2 } from 'lucide-react';
import type { AIMessage } from '@/lib/SessionManager';
import { cn } from '@/lib/utils';
import { UserMessage } from '@/components/UserMessage';
import { ImageLightbox } from '@/components/ImageLightbox';
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
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,7 +26,6 @@ export const AIMessageItem = memo(({
isCurrentlyLoading = false,
toolCall,
}: AIMessageItemProps) => {
const [isToolExpanded, setIsToolExpanded] = useState(false);
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
const { displayTheme } = useTheme();
@@ -50,162 +49,11 @@ export const AIMessageItem = memo(({
return '';
};
// Get tool info including icon and title
const getToolInfo = () => {
if (message.role === 'tool' && toolCall) {
if (toolCall.type === 'function') {
const toolName = toolCall.function.name;
let args;
try {
args = JSON.parse(toolCall.function.arguments);
} catch {
args = {};
}
// Generate icons and titles based on tool name and arguments
switch (toolName) {
case 'shell':
return {
icon: Terminal,
title: args.command ? args.command : 'Shell Command'
};
case 'text_editor_view': {
const title = args.path
? (args.start_line || args.end_line
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
: `Viewed ${args.path}`)
: 'Viewed File';
return { icon: Eye, title };
}
case 'text_editor_write':
return {
icon: FileText,
title: args.path ? `Wrote ${args.path}` : 'Wrote File'
};
case 'text_editor_str_replace':
return {
icon: Edit,
title: args.path ? `Edited ${args.path}` : 'Edited File'
};
case 'npm_add_package': {
const installTitle = args.name
? (args.dev ? `Installed ${args.name} (dev)` : `Installed ${args.name}`)
: 'Installed Package';
return { icon: Package, title: installTitle };
}
case 'npm_remove_package':
return {
icon: PackageMinus,
title: args.name ? `Removed ${args.name}` : 'Removed Package'
};
case 'git_commit':
return {
icon: GitCommit,
title: args.message ? `Committed: ${args.message}` : 'Committed Changes'
};
case 'build_project':
return {
icon: Package,
title: 'Built Project'
};
case 'nostr_read_nip':
return {
icon: BookOpen,
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP'
};
case 'nostr_fetch_event':
return {
icon: Download,
title: args.identifier ? `Fetched ${args.identifier.slice(0, 16)}...` : 'Fetched Event'
};
case 'nostr_read_kind':
return {
icon: Hash,
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind'
};
case 'nostr_read_tag':
return {
icon: Tag,
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag'
};
case 'nostr_read_protocol':
return {
icon: Network,
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol'
};
case 'nostr_read_nips_index':
return {
icon: List,
title: 'Read NIPs Index'
};
case 'nostr_generate_kind':
return {
icon: Plus,
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind'
};
case 'nostr_publish_events': {
const eventCount = args.events?.length || 0;
return {
icon: Send,
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event'
};
}
case 'deploy_project':
return {
icon: Globe,
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project'
};
case 'typecheck':
return {
icon: CheckCircle,
title: 'TypeScript'
};
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console'
};
case 'skill':
return {
icon: Puzzle,
title: args.name ? `Skill: ${args.name}` : 'Skill'
};
default:
return {
icon: Wrench,
title: toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
};
}
}
}
// Fallback to extracting from content
if (message.role === 'tool') {
const content = getContent();
const lines = content.split('\n');
const firstLine = lines[0];
if (firstLine && firstLine.length < 100) {
return {
icon: Wrench,
title: firstLine.replace(/^(Error |Tool |Executing |Result: )/i, '').trim()
};
}
return { icon: Wrench, title: 'Tool Result' };
}
return { icon: Wrench, title: 'Tool' };
};
// Special rendering for tool messages
if (message.role === 'tool') {
const content = getContent();
const toolInfo = getToolInfo();
const IconComponent = toolInfo.icon;
// Get tool call arguments for special rendering
// Get tool call arguments
let toolArgs: Record<string, unknown> = {};
let toolName = '';
if (toolCall?.type === 'function') {
@@ -217,81 +65,13 @@ export const AIMessageItem = memo(({
}
}
// Special rendering for tools
const renderSpecialContent = () => {
if (toolName === 'text_editor_write' && toolArgs.file_text) {
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{toolArgs.file_text as string}
</div>
</div>
);
}
if (toolName === 'text_editor_str_replace' && toolArgs.old_str && toolArgs.new_str) {
const oldLines = (toolArgs.old_str as string).split('\n');
const newLines = (toolArgs.new_str as string).split('\n');
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
<div className="space-y-1">
{/* Old content (removed) */}
<div className="space-y-0">
{oldLines.map((line, index) => (
<div key={`old-${index}`} className="flex">
<span className="text-red-500 select-none mr-2">-</span>
<span className="bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-300 flex-1 whitespace-pre-wrap break-words">
{line}
</span>
</div>
))}
</div>
{/* New content (added) */}
<div className="space-y-0">
{newLines.map((line, index) => (
<div key={`new-${index}`} className="flex">
<span className="text-green-500 select-none mr-2">+</span>
<span className="bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-300 flex-1 whitespace-pre-wrap break-words">
{line}
</span>
</div>
))}
</div>
</div>
</div>
);
}
// Default rendering for other tools
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{content}
</div>
</div>
);
};
// Regular tool message rendering
return (
<div className="-mt-2"> {/* -mt-2 to make it snug with the previous assistant message */}
<button
onClick={() => setIsToolExpanded(!isToolExpanded)}
className={cn(
"w-full flex items-center gap-2 px-2 py-1 text-xs",
"hover:bg-muted/30 rounded transition-colors duration-200"
)}
>
<IconComponent className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<span className="text-muted-foreground font-medium truncate flex-1 text-left">
{toolInfo.title}
</span>
</button>
{isToolExpanded && renderSpecialContent()}
</div>
<ToolCallDisplay
toolName={toolName}
toolArgs={toolArgs}
state="completed"
result={content}
/>
);
}
@@ -300,14 +80,6 @@ export const AIMessageItem = memo(({
// 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
: textParts.length > 0
? textParts.map(part => part.text).join('\n')
: '';
// Extract image URLs from content array
const imageUrls = contentArray
@@ -322,7 +94,7 @@ export const AIMessageItem = memo(({
<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} />}
<UserMessage content={message.content} />
{/* Render images after text and attachments */}
{imageUrls.length > 0 && (
<div className="space-y-2">
@@ -355,32 +127,11 @@ export const AIMessageItem = memo(({
</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>
{/* Image expansion lightbox */}
<ImageLightbox
imageUrl={expandedImageUrl}
onClose={() => setExpandedImageUrl(null)}
/>
</>
);
}
@@ -395,7 +146,7 @@ export const AIMessageItem = memo(({
}
// Assistant messages: left-aligned without avatar/name
return (
const assistantContent = (
<div className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm space-y-3">
@@ -453,6 +204,18 @@ export const AIMessageItem = memo(({
</div>
</div>
);
return (
<>
{assistantContent}
{/* Image expansion lightbox */}
<ImageLightbox
imageUrl={expandedImageUrl}
onClose={() => setExpandedImageUrl(null)}
/>
</>
);
});
AIMessageItem.displayName = 'AIMessageItem';
File diff suppressed because it is too large. Load diff
@@ -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'
}
+2
View File
@@ -151,6 +151,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
};
const isConfigured = settings.providers.length > 0;
const isLoading = !isInitialized;
const contextValue: AISettingsContextType = {
settings,
@@ -162,6 +163,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
setMCPServer,
removeMCPServer,
isConfigured,
isLoading,
};
return (
+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());
-136
View File
@@ -1,136 +0,0 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
GitBranch,
MoreHorizontal,
MessageSquarePlus,
History,
Folder,
Rocket,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
import { DeployDialog } from '@/components/DeployDialog';
interface ActionsMenuProps {
projectId: string;
projectName: string;
onNewChat: () => void;
onProjectDetails?: () => void;
isLoading?: boolean;
isBuildLoading?: boolean;
disabled?: boolean;
onFirstInteraction?: () => void;
}
export function ActionsMenu({
projectId,
projectName,
onNewChat,
onProjectDetails,
isLoading = false,
isBuildLoading = false,
disabled = false,
onFirstInteraction: _onFirstInteraction,
}: ActionsMenuProps) {
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [gitDialogOpen, setGitDialogOpen] = useState(false);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const isAnyLoading = isLoading || isBuildLoading;
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
disabled={disabled}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={onNewChat}
disabled={isLoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
New Chat
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitHistoryOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<History className="h-4 w-4" />
Rollback
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<GitBranch className="h-4 w-4" />
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
className="gap-2"
>
<Folder className="h-4 w-4" />
Project Details
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{/* Dialogs */}
<GitDialog
projectId={projectId}
open={gitDialogOpen}
onOpenChange={setGitDialogOpen}
/>
<GitHistoryDialog
projectId={projectId}
open={gitHistoryOpen}
onOpenChange={setGitHistoryOpen}
/>
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
</>
);
}
+219
View File
@@ -0,0 +1,219 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Bot, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { ExternalInput } from '@/components/ui/external-input';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { Link } from 'react-router-dom';
import type { PresetProvider } from '@/lib/aiProviderPresets';
interface OAuthHook {
isOAuthConfigured: boolean;
isLoading: boolean;
error: string | null;
initiateOAuth: () => void;
}
interface AddAIProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
preset: PresetProvider;
isLoggedIntoNostr: boolean;
oauthHook?: OAuthHook | null;
forceManualEntry?: boolean;
onSetForceManualEntry?: (force: boolean) => void;
onAdd: (apiKey: string) => void;
}
export function AddAIProviderDialog({
open,
onOpenChange,
preset,
isLoggedIntoNostr,
oauthHook,
forceManualEntry = false,
onSetForceManualEntry,
onAdd,
}: AddAIProviderDialogProps) {
const { t } = useTranslation();
const [apiKey, setApiKey] = useState('');
const [termsAgreed, setTermsAgreed] = useState(false);
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
const isOAuthLoading = oauthHook?.isLoading ?? false;
const oauthError = oauthHook?.error ?? null;
const handleAdd = () => {
onAdd(apiKey);
setApiKey('');
onOpenChange(false);
};
// Reset state when dialog closes
const handleOpenChange = (open: boolean) => {
if (!open) {
setApiKey('');
setTermsAgreed(false);
}
onOpenChange(open);
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.baseURL}
size={20}
fallback={<Bot size={20} />}
/>
<DialogTitle>{preset.name}</DialogTitle>
</div>
<DialogDescription>
Add {preset.name} as your AI provider
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
<Button asChild className="w-full">
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
) : isOAuthConfigured && !forceManualEntry ? (
// Show OAuth button if OAuth is configured and not forced to manual
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={() => oauthHook?.initiateOAuth()}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onSetForceManualEntry?.(true)}>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
</div>
) : (
<div className="space-y-3">
{!preset.nostr && preset.apiKeysURL && (
<ExternalInput
type="password"
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() && termsAgreed) {
handleAdd();
}
}}
url={preset.apiKeysURL}
urlTitle="Get Key"
/>
)}
{/* Terms of Service Agreement */}
<div className="flex items-center gap-1.5">
<Checkbox
id="agree-terms"
checked={termsAgreed}
onCheckedChange={(checked) => setTermsAgreed(checked === true)}
className="size-3 [&_svg]:size-3"
/>
<label
htmlFor="agree-terms"
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
{preset.tosURL ? (
<a
href={preset.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-muted-foreground underline hover:text-foreground hover:no-underline"
onClick={(e) => e.stopPropagation()}
>
{t('termsOfService')}
</a>
) : (
t('termsOfService')
)}
</label>
</div>
</div>
)}
</div>
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
</Button>
<Button
onClick={handleAdd}
disabled={
!termsAgreed ||
(!!preset.apiKeysURL && !apiKey.trim())
}
>
{t('add')}
</Button>
</DialogFooter>
)}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,218 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import type { AIProvider } from '@/contexts/AISettingsContext';
interface AddCustomAIProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onAdd: (provider: AIProvider) => void;
existingIds: string[];
}
// Helper function to generate ID from name
function generateIdFromName(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-') // Replace non-alphanumeric chars with hyphens
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
}
export function AddCustomAIProviderDialog({
open,
onOpenChange,
onAdd,
existingIds,
}: AddCustomAIProviderDialogProps) {
const { t } = useTranslation();
const [customProviderName, setCustomProviderName] = useState('');
const [customProviderId, setCustomProviderId] = useState('');
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
const [customProxy, setCustomProxy] = useState(false);
const handleAdd = () => {
if (!customProviderName.trim() || !customProviderId.trim() || !customBaseURL.trim()) return;
const provider: AIProvider = {
id: customProviderId.trim(),
name: customProviderName.trim(),
baseURL: customBaseURL.trim(),
};
if (customAuthMethod === 'api-key' && customApiKey.trim()) {
provider.apiKey = customApiKey.trim();
} else if (customAuthMethod === 'nostr') {
provider.nostr = true;
}
if (customProxy) {
provider.proxy = true;
}
onAdd(provider);
// Reset form
setCustomProviderName('');
setCustomProviderId('');
setCustomIdManuallyEdited(false);
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
setCustomProxy(false);
onOpenChange(false);
};
const isValid = customProviderName.trim() &&
customProviderId.trim() &&
customBaseURL.trim() &&
!existingIds.includes(customProviderId.trim());
const idExists = existingIds.includes(customProviderId.trim());
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{t('addCustomProvider')}</DialogTitle>
<DialogDescription>
Configure a custom AI provider with your own settings
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-2">
<Label htmlFor="custom-name">
{t('name')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-name"
placeholder="e.g., My Custom API"
value={customProviderName}
onChange={(e) => {
const newName = e.target.value;
setCustomProviderName(newName);
// Auto-generate ID from name if ID hasn't been manually edited
if (!customIdManuallyEdited) {
setCustomProviderId(generateIdFromName(newName));
}
}}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-id">
{t('id')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-id"
placeholder="e.g., my-custom-api"
value={customProviderId}
onChange={(e) => {
setCustomProviderId(e.target.value);
setCustomIdManuallyEdited(true);
}}
/>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-baseurl">
{t('baseUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-baseurl"
placeholder="https://api.example.com/v1"
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-auth">{t('authentication')}</Label>
<Select
value={customAuthMethod}
onValueChange={(value: 'api-key' | 'nostr') => {
setCustomAuthMethod(value);
if (value === 'nostr') {
setCustomApiKey(''); // Clear API key when switching to Nostr auth
}
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
</SelectContent>
</Select>
</div>
{customAuthMethod === 'api-key' && (
<div className="grid gap-2">
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
<PasswordInput
id="custom-apikey"
placeholder={t('enterApiKey') + ' (optional)'}
value={customApiKey}
onChange={(e) => setCustomApiKey(e.target.value)}
/>
</div>
)}
<div className="flex items-center gap-2">
<Checkbox
id="custom-proxy"
checked={customProxy}
onCheckedChange={(checked) => setCustomProxy(checked === true)}
/>
<Label htmlFor="custom-proxy" className="cursor-pointer">
{t('useCorsProxy')}
</Label>
</div>
{idExists && (
<p className="text-sm text-destructive">
{t('providerExists')}
</p>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
</Button>
<Button onClick={handleAdd} disabled={!isValid}>
<Check className="h-4 w-4 mr-2" />
{t('addCustomProviderButton')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,146 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
interface AddCustomGitCredentialDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onAdd: (credential: {
name: string;
origin: string;
username: string;
password: string;
}) => void;
existingOrigins: string[];
}
export function AddCustomGitCredentialDialog({
open,
onOpenChange,
onAdd,
existingOrigins,
}: AddCustomGitCredentialDialogProps) {
const { t } = useTranslation();
const [customName, setCustomName] = useState('');
const [customOrigin, setCustomOrigin] = useState('');
const [customUsername, setCustomUsername] = useState('');
const [customPassword, setCustomPassword] = useState('');
const handleAdd = () => {
if (!customName.trim() || !customOrigin.trim() || !customUsername.trim() || !customPassword.trim()) return;
onAdd({
name: customName.trim(),
origin: customOrigin.trim(),
username: customUsername.trim(),
password: customPassword.trim(),
});
// Reset form
setCustomName('');
setCustomOrigin('');
setCustomUsername('');
setCustomPassword('');
onOpenChange(false);
};
const isValid = customName.trim() &&
customOrigin.trim() &&
customUsername.trim() &&
customPassword.trim() &&
!existingOrigins.includes(customOrigin.trim());
const originExists = existingOrigins.includes(customOrigin.trim());
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>{t('addCustomProvider')}</DialogTitle>
<DialogDescription>
Configure a custom Git server with your credentials
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="grid gap-2">
<Label htmlFor="custom-name">
{t('name')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-name"
placeholder="My Git Server"
value={customName}
onChange={(e) => setCustomName(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-origin">
{t('origin')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-origin"
placeholder="https://git.example.com"
value={customOrigin}
onChange={(e) => setCustomOrigin(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-username">
{t('username')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-username"
placeholder="git"
value={customUsername}
onChange={(e) => setCustomUsername(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-password">
{t('password')} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-password"
placeholder={t('enterPassword')}
value={customPassword}
onChange={(e) => setCustomPassword(e.target.value)}
/>
</div>
{originExists && (
<p className="text-sm text-destructive">
{t('credentialsExist')}
</p>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
</Button>
<Button onClick={handleAdd} disabled={!isValid}>
<Check className="h-4 w-4 mr-2" />
{t('addCustomProviderButton')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+372
View File
@@ -0,0 +1,372 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import type {
ShakespeareDeployProvider,
NetlifyProvider,
VercelProvider,
NsiteProvider,
CloudflareProvider,
DenoDeployProvider,
} from '@/contexts/DeploySettingsContext';
// Type for provider without the 'id' field (will be generated)
type DeployProviderInput =
| Omit<ShakespeareDeployProvider, 'id'>
| Omit<NetlifyProvider, 'id'>
| Omit<VercelProvider, 'id'>
| Omit<NsiteProvider, 'id'>
| Omit<CloudflareProvider, 'id'>
| Omit<DenoDeployProvider, 'id'>;
interface AddCustomProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onAdd: (provider: DeployProviderInput) => void;
}
export function AddCustomProviderDialog({
open,
onOpenChange,
onAdd,
}: AddCustomProviderDialogProps) {
const { t } = useTranslation();
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAccountId, setCustomAccountId] = useState('');
const [customOrganizationId, setCustomOrganizationId] = useState('');
const [customBaseURL, setCustomBaseURL] = useState('');
const [customBaseDomain, setCustomBaseDomain] = useState('');
const [customHost, setCustomHost] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const [customGateway, setCustomGateway] = useState('');
const [customRelayUrls, setCustomRelayUrls] = useState('');
const [customBlossomServers, setCustomBlossomServers] = useState('');
const handleAdd = () => {
if (!customProviderType || !customName.trim()) return;
// Build provider object based on type
let provider: DeployProviderInput;
if (customProviderType === 'shakespeare') {
provider = {
type: 'shakespeare',
name: customName.trim(),
...(customHost?.trim() && { host: customHost.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'nsite') {
provider = {
type: 'nsite',
name: customName.trim(),
gateway: customGateway.trim() || 'nsite.lol',
relayUrls: customRelayUrls.trim()
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
: ['wss://relay.nostr.band'],
blossomServers: customBlossomServers.trim()
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
: ['https://blossom.primal.net/'],
};
} else if (customProviderType === 'netlify') {
if (!customApiKey.trim()) return;
provider = {
type: 'netlify',
name: customName.trim(),
apiKey: customApiKey.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'vercel') {
if (!customApiKey.trim()) return;
provider = {
type: 'vercel',
name: customName.trim(),
apiKey: customApiKey.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'cloudflare') {
if (!customApiKey.trim() || !customAccountId.trim()) return;
provider = {
type: 'cloudflare',
name: customName.trim(),
apiKey: customApiKey.trim(),
accountId: customAccountId.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'deno') {
if (!customApiKey.trim() || !customOrganizationId.trim()) return;
provider = {
type: 'deno',
name: customName.trim(),
apiKey: customApiKey.trim(),
organizationId: customOrganizationId.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
...(customProxy && { proxy: true }),
};
} else {
return; // Unknown type
}
onAdd(provider);
// Reset form
setCustomProviderType('');
setCustomName('');
setCustomApiKey('');
setCustomAccountId('');
setCustomOrganizationId('');
setCustomBaseURL('');
setCustomBaseDomain('');
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls('');
setCustomBlossomServers('');
onOpenChange(false);
};
const isValid = customProviderType && customName.trim() &&
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
(customApiKey.trim() &&
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
(customProviderType !== 'deno' || customOrganizationId.trim())));
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{t('addCustomProvider')}</DialogTitle>
<DialogDescription>
Configure a custom deployment provider with your own settings
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="grid gap-2">
<Label htmlFor="custom-provider-type">
{t('providerType')} <span className="text-destructive">*</span>
</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
setCustomAccountId('');
setCustomOrganizationId('');
setCustomBaseURL('');
setCustomBaseDomain('');
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls('');
setCustomBlossomServers('');
}}
>
<SelectTrigger>
<SelectValue placeholder={t('selectProviderType')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="shakespeare">Shakespeare Deploy</SelectItem>
<SelectItem value="nsite">nsite</SelectItem>
<SelectItem value="netlify">Netlify</SelectItem>
<SelectItem value="vercel">Vercel</SelectItem>
<SelectItem value="cloudflare">Cloudflare</SelectItem>
<SelectItem value="deno">Deno Deploy</SelectItem>
</SelectContent>
</Select>
</div>
{customProviderType && (
<>
<div className="grid gap-2">
<Label htmlFor="custom-name">
{t('providerName')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-name"
placeholder="e.g., My Production Deploy"
value={customName}
onChange={(e) => setCustomName(e.target.value)}
/>
</div>
{customProviderType === 'shakespeare' ? (
<>
<p className="text-sm text-muted-foreground">
{t('shakespeareDeployNostrAuth')}
</p>
<div className="grid gap-2">
<Label htmlFor="custom-host">Host (Optional)</Label>
<Input
id="custom-host"
placeholder="shakespeare.wtf"
value={customHost}
onChange={(e) => setCustomHost(e.target.value)}
/>
</div>
</>
) : customProviderType === 'nsite' ? (
<>
<p className="text-sm text-muted-foreground">
Deploy to Nostr as a static website. Uses kind 34128 events and Blossom file storage.
</p>
<div className="grid gap-2">
<Label htmlFor="custom-gateway">Gateway</Label>
<Input
id="custom-gateway"
placeholder="nsite.lol"
value={customGateway}
onChange={(e) => setCustomGateway(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-relays">Relay URLs (comma-separated)</Label>
<Input
id="custom-relays"
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
value={customRelayUrls}
onChange={(e) => setCustomRelayUrls(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-blossom">Blossom Servers (comma-separated)</Label>
<Input
id="custom-blossom"
placeholder="https://blossom.primal.net/"
value={customBlossomServers}
onChange={(e) => setCustomBlossomServers(e.target.value)}
/>
</div>
</>
) : (
<>
{customProviderType === 'cloudflare' && (
<div className="grid gap-2">
<Label htmlFor="custom-accountid">
Account ID <span className="text-destructive">*</span>
</Label>
<Input
id="custom-accountid"
placeholder="Enter Account ID"
value={customAccountId}
onChange={(e) => setCustomAccountId(e.target.value)}
/>
</div>
)}
{customProviderType === 'deno' && (
<div className="grid gap-2">
<Label htmlFor="custom-organizationid">
Organization ID <span className="text-destructive">*</span>
</Label>
<Input
id="custom-organizationid"
placeholder="Enter Organization ID"
value={customOrganizationId}
onChange={(e) => setCustomOrganizationId(e.target.value)}
/>
</div>
)}
<div className="grid gap-2">
<Label htmlFor="custom-apikey">
{customProviderType === 'netlify' ? 'Personal Access Token' :
customProviderType === 'cloudflare' ? 'API Token' :
customProviderType === 'deno' ? 'Access Token' :
'Access Token'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-apikey"
placeholder={t('enterApiKey')}
value={customApiKey}
onChange={(e) => setCustomApiKey(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-baseurl">Base URL (Optional)</Label>
<Input
id="custom-baseurl"
placeholder={
customProviderType === 'netlify'
? 'https://api.netlify.com/api/v1'
: customProviderType === 'vercel'
? 'https://api.vercel.com'
: customProviderType === 'deno'
? 'https://api.deno.com/v1'
: 'https://api.cloudflare.com/client/v4'
}
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
/>
</div>
{(customProviderType === 'cloudflare' || customProviderType === 'deno') && (
<div className="grid gap-2">
<Label htmlFor="custom-basedomain">Base Domain (Optional)</Label>
<Input
id="custom-basedomain"
placeholder={customProviderType === 'cloudflare' ? 'workers.dev' : 'deno.dev'}
value={customBaseDomain}
onChange={(e) => setCustomBaseDomain(e.target.value)}
/>
<p className="text-xs text-muted-foreground">
{customProviderType === 'cloudflare'
? 'The domain suffix for deployed workers (e.g., workers.dev)'
: 'The domain suffix for deployed projects (e.g., deno.dev)'}
</p>
</div>
)}
<div className="flex items-center space-x-2">
<Checkbox
id="custom-proxy"
checked={customProxy}
onCheckedChange={(checked) => setCustomProxy(checked === true)}
/>
<Label htmlFor="custom-proxy" className="text-sm font-normal cursor-pointer">
Use CORS Proxy
</Label>
</div>
</>
)}
</>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
</Button>
<Button onClick={handleAdd} disabled={!isValid}>
<Check className="h-4 w-4 mr-2" />
{t('add')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+220
View File
@@ -0,0 +1,220 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ExternalInput } from '@/components/ui/external-input';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { Link } from 'react-router-dom';
import type { PresetDeployProvider } from '@/lib/deploy/types';
interface OAuthHook {
isOAuthConfigured: boolean;
isLoading: boolean;
error: string | null;
initiateOAuth: () => void;
}
interface AddDeployProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
preset: PresetDeployProvider;
isLoggedIntoNostr: boolean;
oauthHook: OAuthHook | null;
forceManualEntry: boolean;
onSetForceManualEntry: (force: boolean) => void;
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
}
export function AddDeployProviderDialog({
open,
onOpenChange,
preset,
isLoggedIntoNostr,
oauthHook,
forceManualEntry,
onSetForceManualEntry,
onAdd,
}: AddDeployProviderDialogProps) {
const { t } = useTranslation();
const [apiKey, setApiKey] = useState('');
const [accountId, setAccountId] = useState('');
const [organizationId, setOrganizationId] = useState('');
const showNostrLoginRequired = preset.requiresNostr && !isLoggedIntoNostr;
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
const isOAuthLoading = oauthHook?.isLoading ?? false;
const oauthError = oauthHook?.error ?? null;
const handleAdd = () => {
onAdd(apiKey, accountId, organizationId);
setApiKey('');
setAccountId('');
setOrganizationId('');
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.baseURL}
size={20}
fallback={<Rocket size={20} />}
/>
<DialogTitle>{preset.name}</DialogTitle>
</div>
<DialogDescription>
{preset.description}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
<Button asChild className="w-full">
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
) : isOAuthConfigured && !forceManualEntry ? (
// Show OAuth button if OAuth is configured and not forced to manual
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={() => oauthHook?.initiateOAuth()}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
</div>
) : (
// Show manual token input
<div className="space-y-3">
{!preset.requiresNostr && preset.type !== 'nsite' && (
<>
{preset.type === 'cloudflare' && (
<ExternalInput
type="text"
placeholder={preset.accountIdLabel || 'Account ID'}
value={accountId}
onChange={(e) => setAccountId(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() && accountId.trim()) {
handleAdd();
}
}}
url={preset.accountIdURL}
urlTitle="Find ID"
/>
)}
{preset.type === 'deno' && (
<ExternalInput
type="text"
placeholder={preset.organizationIdLabel || 'Organization ID'}
value={organizationId}
onChange={(e) => setOrganizationId(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() && organizationId.trim()) {
handleAdd();
}
}}
url={preset.organizationIdURL}
urlTitle="Find ID"
/>
)}
<ExternalInput
type="password"
placeholder={preset.apiKeyLabel || t('enterApiKey')}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() &&
(preset.type !== 'cloudflare' || accountId.trim()) &&
(preset.type !== 'deno' || organizationId.trim())) {
handleAdd();
}
}}
url={preset.apiKeyURL}
urlTitle="Get Key"
/>
</>
)}
</div>
)}
</div>
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
</Button>
<Button
onClick={handleAdd}
disabled={
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !apiKey.trim()) ||
(preset.type === 'cloudflare' && !accountId.trim()) ||
(preset.type === 'deno' && !organizationId.trim())
}
>
{t('add')}
</Button>
</DialogFooter>
)}
</DialogContent>
</Dialog>
);
}
+162
View File
@@ -0,0 +1,162 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { GitBranch, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ExternalInput } from '@/components/ui/external-input';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ExternalFavicon } from '@/components/ExternalFavicon';
interface PresetProvider {
id: string;
name: string;
origin: string;
username: string;
tokenURL?: string;
}
interface OAuthHook {
initiateOAuth: () => void;
isLoading: boolean;
error: string | null;
isOAuthConfigured: boolean;
}
interface AddGitCredentialDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
preset: PresetProvider;
oauthHook: OAuthHook | null;
forceManualEntry: boolean;
onSetForceManualEntry: (force: boolean) => void;
onAdd: (token: string) => void;
}
export function AddGitCredentialDialog({
open,
onOpenChange,
preset,
oauthHook,
forceManualEntry,
onSetForceManualEntry,
onAdd,
}: AddGitCredentialDialogProps) {
const { t } = useTranslation();
const [token, setToken] = useState('');
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
const isOAuthLoading = oauthHook?.isLoading ?? false;
const oauthError = oauthHook?.error ?? null;
const handleAdd = () => {
onAdd(token);
setToken('');
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.origin}
size={20}
fallback={<GitBranch size={20} />}
/>
<DialogTitle>{preset.name}</DialogTitle>
</div>
<DialogDescription>
Add {preset.name} credentials for Git operations
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{isOAuthConfigured && !forceManualEntry ? (
// Show OAuth button if OAuth is configured and not forced to manual
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={() => oauthHook?.initiateOAuth()}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
Enter token manually
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
</div>
) : (
// Show manual token input
<ExternalInput
type="password"
placeholder={t('enterToken')}
value={token}
onChange={(e) => setToken(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && token.trim()) {
handleAdd();
}
}}
url={preset.tokenURL}
urlTitle="Get Token"
/>
)}
</div>
{!(isOAuthConfigured && !forceManualEntry) && (
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
</Button>
<Button onClick={handleAdd} disabled={!token.trim()}>
{t('add')}
</Button>
</DialogFooter>
)}
</DialogContent>
</Dialog>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { Plus } from 'lucide-react';
interface AddProviderTileProps {
onClick: () => void;
label?: string;
}
export function AddProviderTile({ onClick, label = 'Add Custom' }: AddProviderTileProps) {
return (
<button
onClick={onClick}
className="flex flex-col items-center justify-center gap-2 p-4 rounded-lg border border-dashed bg-card hover:bg-muted transition-colors text-center min-h-[100px]"
>
<Plus size={32} className="text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground overflow-hidden max-w-full text-ellipsis">
{label}
</span>
</button>
);
}
@@ -2,12 +2,13 @@ import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { TestApp } from '@/test/TestApp';
import { AddProviderDialog } from './AddProviderDialog';
import { AddSharedProviderDialog } from './AddSharedProviderDialog';
import type { AIProvider } from '@/contexts/AISettingsContext';
describe('AddProviderDialog', () => {
describe('AddSharedProviderDialog', () => {
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'sk-test-key-123',
};
@@ -17,7 +18,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
@@ -25,9 +26,9 @@ describe('AddProviderDialog', () => {
</TestApp>
);
// Provider name is used as the heading (fallback to id since it's not in presets)
expect(screen.getByRole('heading', { name: 'test-provider' })).toBeInTheDocument();
expect(screen.getByText(/Add test-provider to your configuration/i)).toBeInTheDocument();
// Provider name is displayed in the heading
expect(screen.getByRole('heading', { name: 'Test Provider' })).toBeInTheDocument();
expect(screen.getByText(/Add Test Provider to your configuration/i)).toBeInTheDocument();
});
it('shows add provider button for new provider', () => {
@@ -35,7 +36,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
@@ -54,7 +55,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
@@ -73,7 +74,7 @@ describe('AddProviderDialog', () => {
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
@@ -92,13 +93,14 @@ 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',
};
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={openrouterProvider}
@@ -110,16 +112,17 @@ describe('AddProviderDialog', () => {
expect(screen.getByText(/Add OpenRouter to your configuration/i)).toBeInTheDocument();
});
it('uses provider id as fallback name when not in presets', () => {
it('uses provider name when not in presets', () => {
const onOpenChange = vi.fn();
const customProvider: AIProvider = {
id: 'my-custom-provider',
name: 'My Custom Provider',
baseURL: 'https://api.custom.com/v1',
};
render(
<TestApp>
<AddProviderDialog
<AddSharedProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={customProvider}
@@ -127,7 +130,7 @@ describe('AddProviderDialog', () => {
</TestApp>
);
// Should use the id as the name since it's not in presets
expect(screen.getByText(/Add my-custom-provider to your configuration/i)).toBeInTheDocument();
// Should use the provider name even when not in presets
expect(screen.getByText(/Add My Custom Provider to your configuration/i)).toBeInTheDocument();
});
});
@@ -5,15 +5,16 @@ 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 {
interface AddSharedProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
provider: AIProvider;
}
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
export function AddSharedProviderDialog({ open, onOpenChange, provider }: AddSharedProviderDialogProps) {
const scrollableContentRef = useRef<HTMLDivElement>(null);
const [agreedToTerms, setAgreedToTerms] = useState(false);
@@ -31,7 +32,6 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
const preset = AI_PROVIDER_PRESETS.find(
p => p.id === provider.id && p.baseURL === provider.baseURL
);
const providerName = preset?.name || provider.id;
const handleAddProvider = () => {
setProvider(provider);
@@ -68,7 +68,7 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
<div className="space-y-2">
<h2 className="text-2xl font-bold">Already Configured</h2>
<p className="text-muted-foreground max-w-md mx-auto">
You already have {providerName} configured with the same settings.
You already have {provider.name} configured with the same settings.
</p>
</div>
<Button onClick={() => onOpenChange(false)} className="gap-2">
@@ -156,12 +156,16 @@ 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>
<h2 className="text-2xl font-bold">{provider.name}</h2>
<p className="text-muted-foreground max-w-md mx-auto">
Add {providerName} to your configuration?
Add {provider.name} to your configuration?
</p>
</div>
@@ -178,7 +182,7 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
htmlFor="agree-provider-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
I agree to {providerName}'s{' '}
I agree to {provider.name}'s{' '}
<a
href={preset.tosURL}
target="_blank"
+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}
+21 -24
View File
@@ -1,7 +1,7 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata, type GraspMetadata } from '@/contexts/AppContext';
import i18n from '@/lib/i18n';
interface AppProviderProps {
@@ -22,19 +22,36 @@ const RelayMetadataSchema = z.object({
updatedAt: z.number(),
}) satisfies z.ZodType<RelayMetadata>;
// Zod schema for GraspMetadata
const GraspMetadataSchema = z.object({
relays: z.array(z.object({
url: z.string().url(),
})),
updatedAt: z.number(),
}) satisfies z.ZodType<GraspMetadata>;
// 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(),
graspMetadata: GraspMetadataSchema,
templates: z.array(ProjectTemplateSchema),
esmUrl: z.string().url(),
corsProxy: z.string().url(),
gitProxyOrigins: z.array(z.string()),
faviconUrl: z.string().url(),
ngitWebUrl: z.string().url(),
previewDomain: z.string().min(1),
language: z.string(),
showcaseEnabled: z.boolean(),
showcaseModerator: z.string(),
ngitServers: z.array(z.string()),
fsPathProjects: z.string().min(1),
fsPathConfig: z.string().min(1),
fsPathTmp: z.string().min(1),
@@ -42,6 +59,7 @@ const AppConfigSchema = z.object({
fsPathTemplates: z.string().min(1),
sentryDsn: z.string(),
sentryEnabled: z.boolean(),
systemPrompt: z.string(),
}) satisfies z.ZodType<AppConfig>;
export function AppProvider(props: AppProviderProps) {
@@ -72,13 +90,6 @@ export function AppProvider(props: AppProviderProps) {
// Merge default config with stored config
const config = { ...defaultConfig, ...rawConfig };
// Expand filesystem paths
config.fsPathConfig = expandPath(config.fsPathConfig);
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,
@@ -146,18 +157,4 @@ function useApplyLanguage(language?: string): void {
useEffect(() => {
i18n.changeLanguage(language ?? navigator.language);
}, [language]);
}
/** Expand FS paths with the user's home directory, if available. */
function expandPath(path: string): string {
const homedir = window.electron?.homedir;
if (!homedir) {
return path;
} else if (path.startsWith('~/')) {
return homedir + path.slice(1);
} else if (path === '~') {
return homedir;
} else {
return path;
}
}
+210
View File
@@ -0,0 +1,210 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { BranchSwitcher } from './BranchSwitcher';
import { TestApp } from '@/test/TestApp';
// Mock hooks
vi.mock('@/hooks/useGitStatus', () => ({
useGitStatus: vi.fn(),
}));
vi.mock('@/hooks/useGit', () => ({
useGit: vi.fn(),
}));
vi.mock('@/hooks/useFSPaths', () => ({
useFSPaths: vi.fn(() => ({
projectsPath: '/projects',
})),
}));
vi.mock('@/hooks/useToast', () => ({
useToast: vi.fn(() => ({
toast: vi.fn(),
})),
}));
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGit } from '@/hooks/useGit';
describe('BranchSwitcher', () => {
const mockGit = {
checkout: vi.fn(),
branch: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
(useGit as ReturnType<typeof vi.fn>).mockReturnValue({ git: mockGit });
});
it('should not render when not in a git repository', () => {
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
data: {
isGitRepo: false,
currentBranch: null,
branches: [],
},
});
const { container } = render(
<TestApp>
<BranchSwitcher projectId="test-project" />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('should render branch switcher button when in a git repository', () => {
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
data: {
isGitRepo: true,
currentBranch: 'main',
branches: ['main', 'develop'],
hasUncommittedChanges: false,
},
});
render(
<TestApp>
<BranchSwitcher projectId="test-project" />
</TestApp>
);
expect(screen.getByRole('button')).toBeInTheDocument();
expect(screen.getByText('main')).toBeInTheDocument();
});
it('should show dropdown menu when clicked', async () => {
const user = userEvent.setup();
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
data: {
isGitRepo: true,
currentBranch: 'main',
branches: ['main', 'develop', 'feature/test'],
hasUncommittedChanges: false,
},
});
render(
<TestApp>
<BranchSwitcher projectId="test-project" />
</TestApp>
);
const button = screen.getByRole('button');
await user.click(button);
await waitFor(() => {
expect(screen.getByText('Switch Branch')).toBeInTheDocument();
expect(screen.getByText('develop')).toBeInTheDocument();
expect(screen.getByText('feature/test')).toBeInTheDocument();
expect(screen.getByText('Create new branch')).toBeInTheDocument();
});
});
it('should show current branch with checkmark', async () => {
const user = userEvent.setup();
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
data: {
isGitRepo: true,
currentBranch: 'main',
branches: ['main', 'develop'],
hasUncommittedChanges: false,
},
});
render(
<TestApp>
<BranchSwitcher projectId="test-project" />
</TestApp>
);
const button = screen.getByRole('button');
await user.click(button);
await waitFor(() => {
expect(screen.getByText('Switch Branch')).toBeInTheDocument();
expect(screen.getByText('develop')).toBeInTheDocument();
});
});
it('should open create branch dialog when clicking create new branch', async () => {
const user = userEvent.setup();
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
data: {
isGitRepo: true,
currentBranch: 'main',
branches: ['main'],
hasUncommittedChanges: false,
},
});
render(
<TestApp>
<BranchSwitcher projectId="test-project" />
</TestApp>
);
const button = screen.getByRole('button');
await user.click(button);
const createButton = await screen.findByText('Create new branch');
await user.click(createButton);
await waitFor(() => {
expect(screen.getByText('Create New Branch')).toBeInTheDocument();
expect(screen.getByPlaceholderText('feature/my-new-feature')).toBeInTheDocument();
});
});
it('should handle branch creation', async () => {
const user = userEvent.setup();
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
data: {
isGitRepo: true,
currentBranch: 'main',
branches: ['main'],
hasUncommittedChanges: false,
},
});
mockGit.branch.mockResolvedValue(undefined);
mockGit.checkout.mockResolvedValue(undefined);
render(
<TestApp>
<BranchSwitcher projectId="test-project" />
</TestApp>
);
// Open dropdown
const button = screen.getByRole('button');
await user.click(button);
// Click create new branch
const createButton = await screen.findByText('Create new branch');
await user.click(createButton);
// Enter branch name
const input = await screen.findByPlaceholderText('feature/my-new-feature');
await user.type(input, 'feature/new-branch');
// Click create button
const createBranchButton = screen.getByRole('button', { name: /Create Branch/i });
await user.click(createBranchButton);
await waitFor(() => {
expect(mockGit.branch).toHaveBeenCalledWith({
dir: '/projects/test-project',
ref: 'feature/new-branch',
});
expect(mockGit.checkout).toHaveBeenCalledWith({
dir: '/projects/test-project',
ref: 'feature/new-branch',
});
});
});
});
+274
View File
@@ -0,0 +1,274 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { GitBranch, Check, Plus, Loader2 } from 'lucide-react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
import { cn } from '@/lib/utils';
interface BranchSwitcherProps {
projectId: string;
className?: string;
}
export function BranchSwitcher({ projectId, className }: BranchSwitcherProps) {
const [isCreatingBranch, setIsCreatingBranch] = useState(false);
const [newBranchName, setNewBranchName] = useState('');
const [isSwitching, setIsSwitching] = useState(false);
const [isCreating, setIsCreating] = useState(false);
const { data: gitStatus } = useGitStatus(projectId);
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { toast } = useToast();
const queryClient = useQueryClient();
const handleSwitchBranch = async (branchName: string) => {
if (!gitStatus?.currentBranch || branchName === gitStatus.currentBranch) {
return;
}
// Check for uncommitted changes
if (gitStatus.hasUncommittedChanges) {
toast({
title: "Uncommitted changes",
description: "Please commit or discard your changes before switching branches.",
variant: "destructive",
});
return;
}
setIsSwitching(true);
try {
const projectPath = `${projectsPath}/${projectId}`;
await git.checkout({
dir: projectPath,
ref: branchName,
});
toast({
title: "Branch switched",
description: `Switched to branch "${branchName}"`,
});
// Invalidate git status to refresh the UI
await queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
} catch (error) {
console.error('Failed to switch branch:', error);
toast({
title: "Failed to switch branch",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsSwitching(false);
}
};
const handleCreateBranch = async () => {
if (!newBranchName.trim()) {
toast({
title: "Invalid branch name",
description: "Branch name cannot be empty",
variant: "destructive",
});
return;
}
// Validate branch name (basic validation)
if (!/^[a-zA-Z0-9_\-/.]+$/.test(newBranchName)) {
toast({
title: "Invalid branch name",
description: "Branch name can only contain letters, numbers, hyphens, underscores, slashes, and dots",
variant: "destructive",
});
return;
}
// Check if branch already exists
if (gitStatus?.branches.includes(newBranchName)) {
toast({
title: "Branch already exists",
description: `A branch named "${newBranchName}" already exists`,
variant: "destructive",
});
return;
}
setIsCreating(true);
try {
const projectPath = `${projectsPath}/${projectId}`;
// Create new branch
await git.branch({
dir: projectPath,
ref: newBranchName,
});
// Switch to the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName,
});
toast({
title: "Branch created",
description: `Created and switched to branch "${newBranchName}"`,
});
// Close dialog and reset state
setIsCreatingBranch(false);
setNewBranchName('');
// Invalidate git status to refresh the UI
await queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
} catch (error) {
console.error('Failed to create branch:', error);
toast({
title: "Failed to create branch",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsCreating(false);
}
};
// Don't show if not a git repo
if (!gitStatus?.isGitRepo) {
return null;
}
const currentBranch = gitStatus.currentBranch || 'main';
const branches = gitStatus.branches || [];
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
size="sm"
className={cn("gap-1 sm:gap-2 hover:bg-secondary/10 hover:border-secondary/20", className)}
disabled={isSwitching}
>
{isSwitching ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<GitBranch className="h-4 w-4" />
)}
<span className=" max-w-[120px] truncate">{currentBranch}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel>Switch Branch</DropdownMenuLabel>
<DropdownMenuSeparator />
{branches.length > 0 ? (
branches.map((branch) => (
<DropdownMenuItem
key={branch}
onClick={() => handleSwitchBranch(branch)}
disabled={branch === currentBranch || isSwitching}
className="cursor-pointer"
>
<div className="flex items-center justify-between w-full">
<span className="truncate">{branch}</span>
{branch === currentBranch && (
<Check className="h-4 w-4 ml-2 shrink-0 text-primary" />
)}
</div>
</DropdownMenuItem>
))
) : (
<DropdownMenuItem disabled>No branches found</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setIsCreatingBranch(true)}
disabled={isSwitching}
className="cursor-pointer"
>
<Plus className="h-4 w-4 mr-2" />
Create new branch
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Dialog open={isCreatingBranch} onOpenChange={setIsCreatingBranch}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Branch</DialogTitle>
<DialogDescription>
Create a new branch from the current branch "{currentBranch}".
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="branch-name">Branch name</Label>
<Input
id="branch-name"
placeholder="feature/my-new-feature"
value={newBranchName}
onChange={(e) => setNewBranchName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleCreateBranch();
}
}}
autoFocus
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => {
setIsCreatingBranch(false);
setNewBranchName('');
}}
disabled={isCreating}
>
Cancel
</Button>
<Button onClick={handleCreateBranch} disabled={isCreating}>
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Creating...
</>
) : (
<>
<GitBranch className="h-4 w-4 mr-2" />
Create Branch
</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
+5 -3
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',
};
@@ -29,7 +30,8 @@ describe('CreditsBadge', () => {
</TestApp>
);
expect(screen.getByText('$10.50')).toBeInTheDocument();
// Credits are formatted as whole dollars (10.50 rounds to $11)
expect(screen.getByText('$11')).toBeInTheDocument();
});
it('calls onOpenDialog when badge is clicked', () => {
@@ -44,7 +46,7 @@ describe('CreditsBadge', () => {
</TestApp>
);
const badge = screen.getByText('$10.50');
const badge = screen.getByText('$11');
fireEvent.click(badge);
expect(mockCallback).toHaveBeenCalled();
@@ -57,7 +59,7 @@ describe('CreditsBadge', () => {
</TestApp>
);
const badge = screen.getByText('$10.50');
const badge = screen.getByText('$11');
expect(badge).toHaveClass('cursor-pointer');
expect(badge).toHaveClass('hover:bg-secondary/80');
});
+2 -2
View File
@@ -28,8 +28,8 @@ export function CreditsBadge({ provider, className, onOpenDialog }: CreditsBadge
const formattedAmount = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(credits.amount);
return (
+75 -26
View File
@@ -1,43 +1,65 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsDialog } from './CreditsDialog';
import { AIProviderConfigDialog } from './AIProviderConfigDialog';
import type { AIProvider } from '@/contexts/AISettingsContext';
// Mock useAICredits to return credits data
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: () => ({
data: { amount: 10.50 },
error: null,
isLoading: false,
}),
}));
// Mock the fetch function
global.fetch = vi.fn();
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
};
describe('CreditsDialog', () => {
it('renders dialog when open', () => {
describe('AIProviderConfigDialog - Credits Tab', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders dialog when open with credits tab', async () => {
render(
<TestApp>
<CreditsDialog
<AIProviderConfigDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</TestApp>
);
expect(screen.getByText('Credits')).toBeInTheDocument();
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
// Wait for the dialog to render with tabs
await waitFor(() => {
expect(screen.getByRole('tab', { name: /credits/i })).toBeInTheDocument();
});
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
expect(screen.getByText('Recent Transactions')).toBeInTheDocument();
});
it('does not render when closed', () => {
render(
<TestApp>
<CreditsDialog
<AIProviderConfigDialog
open={false}
onOpenChange={() => {}}
provider={mockProvider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</TestApp>
);
@@ -45,49 +67,71 @@ describe('CreditsDialog', () => {
expect(screen.queryByText('Credits')).not.toBeInTheDocument();
});
it('shows payment method options', () => {
it('shows payment method options', async () => {
render(
<TestApp>
<CreditsDialog
<AIProviderConfigDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</TestApp>
);
expect(screen.getByText('Payment Method')).toBeInTheDocument();
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
// Wait for accordion to be available and click to expand
await waitFor(() => {
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
});
// The content is in an accordion that needs to be expanded
// Check for accordion trigger text instead
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
});
it('shows preset amount buttons', () => {
it('shows preset amount buttons', async () => {
render(
<TestApp>
<CreditsDialog
<AIProviderConfigDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</TestApp>
);
expect(screen.getByText('$5')).toBeInTheDocument();
expect(screen.getByText('$10')).toBeInTheDocument();
expect(screen.getByText('$25')).toBeInTheDocument();
expect(screen.getByText('$50')).toBeInTheDocument();
expect(screen.getByText('$100')).toBeInTheDocument();
// Wait for the Buy Credits accordion to be visible
await waitFor(() => {
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
});
// Click the accordion to expand it (accordions default to closed)
const buyCreditsButton = screen.getByText('Buy Credits');
buyCreditsButton.click();
// Now the preset buttons should be visible
await waitFor(() => {
expect(screen.getByText('$5')).toBeInTheDocument();
expect(screen.getByText('$10')).toBeInTheDocument();
expect(screen.getByText('$25')).toBeInTheDocument();
expect(screen.getByText('$50')).toBeInTheDocument();
expect(screen.getByText('$100')).toBeInTheDocument();
});
});
it('calls onDialogStateChange callback when dialog state changes', () => {
it('calls onDialogStateChange callback when dialog state changes', async () => {
const mockCallback = vi.fn();
const { rerender } = render(
<TestApp>
<CreditsDialog
<AIProviderConfigDialog
open={false}
onOpenChange={mockCallback}
provider={mockProvider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</TestApp>
);
@@ -95,14 +139,19 @@ describe('CreditsDialog', () => {
// Simulate opening the dialog
rerender(
<TestApp>
<CreditsDialog
<AIProviderConfigDialog
open={true}
onOpenChange={mockCallback}
provider={mockProvider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</TestApp>
);
expect(screen.getByText('Credits')).toBeInTheDocument();
// Wait for the Credits tab to appear
await waitFor(() => {
expect(screen.getByRole('tab', { name: /credits/i })).toBeInTheDocument();
});
});
});
File diff suppressed because it is too large. Load diff
+62
View File
@@ -0,0 +1,62 @@
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Loader2 } from 'lucide-react';
import type { ReactNode } from 'react';
interface DeleteProjectDialogProps {
projectName: string;
onDelete: () => void | Promise<void>;
isDeleting: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
trigger?: ReactNode;
}
export function DeleteProjectDialog({
projectName,
onDelete,
isDeleting,
open,
onOpenChange,
trigger,
}: DeleteProjectDialogProps) {
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
{trigger && <AlertDialogTrigger asChild>{trigger}</AlertDialogTrigger>}
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Project</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{projectName}"? This action cannot be undone and will permanently delete all project data including files.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={onDelete}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Deleting...
</>
) : (
'Delete Project'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
-529
View File
@@ -1,529 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
import { Link } from 'react-router-dom';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
/**
* Helper function to get provider URL for favicon
*/
function getProviderUrl(provider: DeployProvider): string | null {
switch (provider.type) {
case 'shakespeare':
if (provider.host) {
return `https://${provider.host}`;
}
return 'https://shakespeare.diy';
case 'netlify':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://netlify.com';
case 'vercel':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://vercel.com';
case 'nsite':
return null;
default:
return null;
}
}
/**
* Render provider icon using favicon or fallback
*/
function renderProviderIcon(provider: DeployProvider, size = 14) {
const url = getProviderUrl(provider);
if (url) {
return (
<ExternalFavicon
url={url}
size={size}
fallback={<Rocket size={size} />}
/>
);
}
return <Rocket size={size} />;
}
interface DeployDialogProps {
projectId: string;
projectName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
}
interface ShakespeareFormData {
subdomain: string;
}
interface NsiteFormData {
nsec: string;
}
interface NetlifyFormData {
siteId: string;
siteName: string;
}
interface VercelFormData {
projectName: string;
teamId: string;
}
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
const { user } = useCurrentUser();
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const { config } = useAppContext();
const { nostr } = useNostr();
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
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>({
subdomain: projectId,
});
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
nsec: '',
});
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
siteId: '',
siteName: '',
});
const [vercelForm, setVercelForm] = useState<VercelFormData>({
projectName: projectName || projectId,
teamId: '',
});
// Load project settings when dialog opens
useEffect(() => {
if (open) {
// First, try to use the currentProvider from project settings
if (projectSettings.currentProvider && settings.providers.some(p => p.id === projectSettings.currentProvider)) {
setSelectedProviderId(projectSettings.currentProvider);
} else {
// Otherwise, find the first configured provider in project settings
const providerIds = Object.keys(projectSettings.providers);
if (providerIds.length > 0) {
setSelectedProviderId(providerIds[0]);
}
}
}
}, [open, projectSettings, settings.providers]);
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
const handleDeploy = async () => {
if (!selectedProvider) return;
setIsDeploying(true);
setError(null);
setDeployResult(null);
try {
const projectPath = `${projectsPath}/${projectId}`;
let adapter: DeployAdapter;
if (selectedProvider.type === 'shakespeare') {
if (!user) {
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
}
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
adapter = new ShakespeareAdapter({
fs,
signer: user.signer,
host: shakespeareProvider.host,
subdomain: shakespeareForm.subdomain || undefined,
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'nsite') {
const nsiteProvider = selectedProvider as import('@/contexts/DeploySettingsContext').NsiteProvider;
if (!nsiteForm.nsec) {
throw new Error('Site private key (nsec) is required');
}
adapter = new NsiteAdapter({
fs,
nostr,
nsec: nsiteForm.nsec,
gateway: nsiteProvider.gateway,
relayUrls: nsiteProvider.relayUrls,
blossomServers: nsiteProvider.blossomServers,
});
} else if (selectedProvider.type === 'netlify') {
const netlifyProvider = selectedProvider as NetlifyProvider;
if (!netlifyProvider.apiKey) {
throw new Error('Netlify API key is required');
}
// If siteId is empty, we're creating a new site, so only pass siteName
// If siteId is set, we're updating an existing site
adapter = new NetlifyAdapter({
fs,
apiKey: netlifyProvider.apiKey,
baseURL: netlifyProvider.baseURL,
siteName: netlifyForm.siteId ? undefined : (netlifyForm.siteName || undefined),
siteId: netlifyForm.siteId || undefined,
corsProxy: netlifyProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'vercel') {
const vercelProvider = selectedProvider as VercelProvider;
if (!vercelProvider.apiKey) {
throw new Error('Vercel API key is required');
}
adapter = new VercelAdapter({
fs,
apiKey: vercelProvider.apiKey,
baseURL: vercelProvider.baseURL,
teamId: vercelForm.teamId || undefined,
projectName: vercelForm.projectName || undefined,
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
}
const result = await adapter.deploy({
projectId,
projectPath,
});
// Save project-specific settings (updateSettings now automatically sets currentProvider)
if (selectedProvider.type === 'shakespeare') {
await updateProjectSettings(selectedProviderId, {
type: 'shakespeare',
data: {
subdomain: shakespeareForm.subdomain || undefined,
},
});
} else if (selectedProvider.type === 'nsite') {
await updateProjectSettings(selectedProviderId, {
type: 'nsite',
data: {
nsec: nsiteForm.nsec,
},
});
} else if (selectedProvider.type === 'netlify') {
await updateProjectSettings(selectedProviderId, {
type: 'netlify',
data: {
siteId: result.metadata?.siteId as string | undefined,
},
});
} else if (selectedProvider.type === 'vercel') {
await updateProjectSettings(selectedProviderId, {
type: 'vercel',
data: {
teamId: vercelForm.teamId || undefined,
projectId: vercelForm.projectName || undefined,
},
});
}
setDeployResult(result);
} catch (err) {
setError(err instanceof Error ? err.message : 'Deployment failed');
} finally {
setIsDeploying(false);
}
};
const handleClose = () => {
setSelectedProviderId('');
setDeployResult(null);
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNsiteForm({ nsec: '' });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
onOpenChange(false);
};
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
setShakespeareForm({ subdomain });
}, []);
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
setIsShakespeareFormValid(isValid);
}, []);
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
setNetlifyForm({ siteId, siteName });
}, []);
const handleVercelConfigChange = useCallback((projectName: string, teamId: string) => {
setVercelForm({ projectName, teamId });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
if (selectedProvider.type === 'shakespeare') {
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
return (
<ShakespeareDeployForm
host={shakespeareProvider.host}
projectId={projectId}
onSubdomainChange={handleShakespeareSubdomainChange}
onValidationChange={handleShakespeareValidationChange}
/>
);
}
if (selectedProvider.type === 'nsite') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
return (
<NsiteDeployForm
gateway={selectedProvider.gateway}
savedNsec={savedNsec}
onNsecChange={handleNsiteNsecChange}
/>
);
}
if (selectedProvider.type === 'netlify') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedSiteId = savedConfig?.type === 'netlify' ? savedConfig.data.siteId : undefined;
return (
<NetlifyDeployForm
apiKey={selectedProvider.apiKey}
baseURL={selectedProvider.baseURL}
projectId={projectId}
projectName={projectName}
savedSiteId={savedSiteId}
onSiteChange={handleNetlifySiteChange}
corsProxy={selectedProvider.proxy ? config.corsProxy : undefined}
/>
);
}
if (selectedProvider.type === 'vercel') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedTeamId = savedConfig?.type === 'vercel' ? savedConfig.data.teamId : undefined;
const savedProjectName = savedConfig?.type === 'vercel' ? savedConfig.data.projectId : undefined;
return (
<VercelDeployForm
projectId={projectId}
projectName={projectName}
savedTeamId={savedTeamId}
savedProjectName={savedProjectName}
onConfigChange={handleVercelConfigChange}
/>
);
}
return null;
};
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Rocket className="h-5 w-5" />
Deploy Project
</DialogTitle>
<DialogDescription>
Deploy your project to a hosting platform
</DialogDescription>
</DialogHeader>
{deployResult ? (
<div className="space-y-4">
<Alert>
<Rocket className="h-4 w-4" />
<AlertDescription>
Your project has been successfully deployed!
</AlertDescription>
</Alert>
<div className="space-y-2">
<Label>Deployed URL</Label>
<div className="flex gap-2">
<Input
value={deployResult.url}
readOnly
className="flex-1"
/>
<Button
size="sm"
variant="outline"
onClick={() => window.open(deployResult.url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
</div>
</div>
) : (
<div className="space-y-4">
{settings.providers.length === 0 ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No deployment providers configured.{' '}
<Link
to="/settings/deploy"
className="underline hover:no-underline"
onClick={handleClose}
>
Configure deployment settings
</Link>
</AlertDescription>
</Alert>
) : (
<>
<div className="space-y-2">
<Label htmlFor="provider">Select Provider</Label>
<Select value={selectedProviderId} onValueChange={setSelectedProviderId}>
<SelectTrigger id="provider">
{selectedProvider ? (
<div className="flex items-center gap-2">
{renderProviderIcon(selectedProvider, 14)}
<span>{selectedProvider.name}</span>
</div>
) : (
<SelectValue placeholder="Choose a deployment provider..." />
)}
</SelectTrigger>
<SelectContent>
{settings.providers.map((provider) => (
<SelectItem key={provider.id} value={provider.id}>
<div className="flex items-center gap-2">
{renderProviderIcon(provider, 14)}
<span>{provider.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedProvider && renderProviderFields()}
{selectedProvider?.type === 'shakespeare' && !user && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline"
onClick={handleClose}
>
Go to Nostr Settings
</Link>
</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleClose}>
{t('cancel')}
</Button>
<Button
onClick={handleDeploy}
disabled={
!selectedProvider ||
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
}
>
{isDeploying ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Deploying...
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
Deploy
</>
)}
</Button>
</div>
</>
)}
</div>
)}
</DialogContent>
</Dialog>
);
}
+249
View File
@@ -0,0 +1,249 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Search, Download, Loader2, Check, Package, LogIn } from 'lucide-react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useDiscoverPlugins } from '@/hooks/useDiscoverPlugins';
import { usePlugins } from '@/hooks/usePlugins';
import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { genUserName } from '@/lib/genUserName';
import { Link } from 'react-router-dom';
import type { NostrMetadata } from '@nostrify/nostrify';
interface DiscoverPluginsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function DiscoverPluginsDialog({ open, onOpenChange }: DiscoverPluginsDialogProps) {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { data: plugins, isLoading } = useDiscoverPlugins();
const [searchQuery, setSearchQuery] = useState('');
// Filter plugins based on search query
const filteredPlugins = plugins?.filter((plugin) => {
const query = searchQuery.toLowerCase();
return (
plugin.name.toLowerCase().includes(query) ||
plugin.description.toLowerCase().includes(query) ||
plugin.id.toLowerCase().includes(query)
);
});
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-3xl max-h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Package className="h-5 w-5 text-primary" />
{t('discoverPlugins')}
</DialogTitle>
<DialogDescription>
{t('discoverPluginsDescription')}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 flex-1 min-h-0 flex flex-col">
{/* Search Input */}
<div className="relative flex-shrink-0">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder={t('searchPlugins')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9"
/>
</div>
{/* Plugins List */}
<div className="flex-1 overflow-y-auto space-y-3">
{!user && (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<LogIn className="h-12 w-12 mx-auto text-muted-foreground" />
<div className="space-y-2">
<h3 className="font-semibold">{t('loginRequired')}</h3>
<p className="text-sm text-muted-foreground">
{t('loginToDiscoverPlugins')}
</p>
</div>
<Button asChild className="w-full">
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
</CardContent>
</Card>
)}
{user && isLoading && (
<>
{[...Array(3)].map((_, i) => (
<Card key={i}>
<CardContent className="p-4 space-y-3">
<div className="flex items-start gap-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="flex-1 space-y-2">
<Skeleton className="h-5 w-48" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
</div>
</div>
</CardContent>
</Card>
))}
</>
)}
{user && !isLoading && filteredPlugins?.length === 0 && (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<Package className="h-12 w-12 mx-auto text-muted-foreground" />
<div className="space-y-2">
<h3 className="font-semibold">
{searchQuery ? t('noPluginsFound') : t('noPluginsFromNetwork')}
</h3>
<p className="text-sm text-muted-foreground">
{searchQuery
? t('tryDifferentSearch')
: t('noPluginsFromNetworkDescription')
}
</p>
</div>
</div>
</CardContent>
</Card>
)}
{user && !isLoading && filteredPlugins?.map((plugin) => (
<PluginCard key={`${plugin.author}-${plugin.id}`} plugin={plugin} />
))}
</div>
</div>
</DialogContent>
</Dialog>
);
}
interface PluginCardProps {
plugin: {
id: string;
name: string;
description: string;
cloneUrl?: string;
webUrl?: string;
author: string;
};
}
function PluginCard({ plugin }: PluginCardProps) {
const { t } = useTranslation();
const { toast } = useToast();
const author = useAuthor(plugin.author);
const { clonePlugin, plugins: installedPlugins } = usePlugins();
const metadata: NostrMetadata | undefined = author.data?.metadata;
const isInstalled = installedPlugins.includes(plugin.id);
const isInstalling = clonePlugin.isPending && clonePlugin.variables?.pluginName === plugin.id;
const handleInstall = async () => {
if (!plugin.cloneUrl) {
toast({
title: t('noCloneUrl'),
description: t('noCloneUrlDescription'),
variant: 'destructive',
});
return;
}
try {
await clonePlugin.mutateAsync({
gitUrl: plugin.cloneUrl,
pluginName: plugin.id,
});
toast({
title: t('pluginInstalled'),
description: t('pluginInstalledDescription', { name: plugin.name }),
});
} catch (error) {
toast({
title: t('pluginInstallFailed'),
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
});
}
};
const displayName = metadata?.name ?? genUserName(plugin.author);
const profileImage = metadata?.picture;
return (
<Card>
<CardContent className="p-4 space-y-3">
{/* Plugin Header with Author Info */}
<div className="flex items-start gap-3">
<Avatar className="h-10 w-10">
<AvatarImage src={profileImage} alt={displayName} />
<AvatarFallback>{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<h3 className="font-semibold text-base truncate">{plugin.name}</h3>
{isInstalled && (
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium bg-green-500/10 text-green-600 dark:text-green-400 rounded-full">
<Check className="h-3 w-3" />
{t('installed')}
</span>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('by')} {displayName}
</p>
</div>
</div>
{/* Plugin Description */}
{plugin.description && (
<p className="text-sm text-muted-foreground line-clamp-2">
{plugin.description}
</p>
)}
{/* Action Button */}
<Button
onClick={handleInstall}
disabled={isInstalled || isInstalling || !plugin.cloneUrl}
className="w-full"
size="sm"
>
{isInstalling ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{t('installing')}
</>
) : isInstalled ? (
<>
<Check className="h-4 w-4 mr-2" />
{t('installed')}
</>
) : (
<>
<Download className="h-4 w-4 mr-2" />
{t('install')}
</>
)}
</Button>
</CardContent>
</Card>
);
}
+66
View File
@@ -0,0 +1,66 @@
import { Bot, GripVertical } from 'lucide-react';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { ReactNode } from 'react';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
interface DraggableProviderTileProps {
id: string;
icon?: ReactNode;
iconUrl?: string | null;
name: string;
onClick: () => void;
badge?: ReactNode;
}
export function DraggableProviderTile({ id, icon, iconUrl, name, onClick, badge }: DraggableProviderTileProps) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<div ref={setNodeRef} style={style} className="relative group">
<button
onClick={onClick}
className="flex flex-col items-center justify-center gap-2 p-4 rounded-lg border bg-card hover:bg-muted transition-colors text-center h-[120px] w-full relative"
>
{iconUrl ? (
<ExternalFavicon
url={iconUrl}
size={32}
fallback={icon || <Bot size={32} />}
/>
) : (
icon || <Bot size={32} />
)}
<span className="text-sm font-medium line-clamp-2 overflow-hidden max-w-full text-ellipsis">
{name}
</span>
{badge && (
<div className="absolute top-0 right-0">
{badge}
</div>
)}
</button>
<div
{...attributes}
{...listeners}
className="absolute top-1 right-1 p-1 cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity bg-background/80 rounded hover:bg-muted"
title="Drag to reorder"
>
<GripVertical size={16} className="text-muted-foreground" />
</div>
</div>
);
}
@@ -0,0 +1,137 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DuplicateProjectDialog } from './DuplicateProjectDialog';
import { TestApp } from '@/test/TestApp';
// Mock the navigate function
const mockNavigate = vi.fn();
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useNavigate: () => mockNavigate,
};
});
describe('DuplicateProjectDialog', () => {
beforeEach(() => {
mockNavigate.mockClear();
});
it('renders dialog when open', () => {
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={() => {}}
/>
</TestApp>
);
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Duplicate Project' })).toBeInTheDocument();
expect(screen.getByText('Create a copy of this project with a new name')).toBeInTheDocument();
});
it('does not render dialog when closed', () => {
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={false}
onOpenChange={() => {}}
/>
</TestApp>
);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('shows default project name with -copy suffix', () => {
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={() => {}}
/>
</TestApp>
);
const input = screen.getByLabelText('New Project Name');
expect(input).toHaveValue('Test Project-copy');
});
it('allows changing the project name', async () => {
const user = userEvent.setup();
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={() => {}}
/>
</TestApp>
);
const input = screen.getByLabelText('New Project Name');
await user.clear(input);
await user.type(input, 'My New Project');
expect(input).toHaveValue('My New Project');
});
it('disables duplicate button when name is empty', async () => {
const user = userEvent.setup();
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={() => {}}
/>
</TestApp>
);
const input = screen.getByLabelText('New Project Name');
const duplicateButton = screen.getByRole('button', { name: /Duplicate Project/i });
// Clear the input
await user.clear(input);
// Button should be disabled when input is empty
expect(duplicateButton).toBeDisabled();
});
it('closes dialog when cancel button is clicked', async () => {
const user = userEvent.setup();
const onOpenChange = vi.fn();
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={onOpenChange}
/>
</TestApp>
);
const cancelButton = screen.getByRole('button', { name: /Cancel/i });
await user.click(cancelButton);
await waitFor(() => {
expect(onOpenChange).toHaveBeenCalledWith(false);
});
});
});
+119
View File
@@ -0,0 +1,119 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
interface DuplicateProjectDialogProps {
projectId: string;
projectName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function DuplicateProjectDialog({
projectId,
projectName,
open,
onOpenChange,
}: DuplicateProjectDialogProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const { toast } = useToast();
const projectsManager = useProjectsManager();
const queryClient = useQueryClient();
const [newName, setNewName] = useState(`${projectName}-copy`);
const [isLoading, setIsLoading] = useState(false);
const handleDuplicate = async () => {
if (!newName.trim()) {
return;
}
setIsLoading(true);
try {
const duplicatedProject = await projectsManager.duplicateProject(projectId, newName);
// Invalidate projects query to refresh the list
await queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: t('projectDuplicated'),
description: t('projectDuplicatedDescription'),
});
// Close dialog
onOpenChange(false);
// Navigate to the new project
navigate(`/project/${duplicatedProject.id}`);
} catch (error) {
console.error('Failed to duplicate project:', error);
toast({
title: t('failedToDuplicateProject'),
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>{t('duplicateProject')}</DialogTitle>
<DialogDescription>
{t('duplicateProjectDescription')}
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label htmlFor="new-name">{t('newProjectName')}</Label>
<Input
id="new-name"
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder={`${projectName}-copy`}
disabled={isLoading}
onKeyDown={(e) => {
if (e.key === 'Enter' && newName.trim()) {
handleDuplicate();
}
}}
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
>
{t('cancel')}
</Button>
<Button
onClick={handleDuplicate}
disabled={isLoading || !newName.trim()}
>
{isLoading ? t('duplicatingProject') : t('duplicateProject')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+4
View File
@@ -100,11 +100,15 @@ export function ErrorBoundary({
const Sentry = getSentryInstance();
if (Sentry) {
Sentry.captureException(error, {
level: 'fatal', // Mark as fatal/unhandled error (skull icon in Sentry UI)
contexts: {
react: {
componentStack: info.componentStack,
},
},
tags: {
errorBoundary: 'true', // Tag to easily filter these errors
},
});
}
}
+9 -4
View File
@@ -1,11 +1,11 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
import { faviconUrl } from '@/lib/faviconUrl';
import { cn } from '@/lib/utils';
import { ReactNode, useMemo } from 'react';
interface ExternalFaviconProps {
/** The URL to fetch the favicon for */
url: string;
url: string | URL | undefined;
/** Size of the favicon in pixels */
size?: number;
/** Fallback element to display if favicon fails to load */
@@ -28,10 +28,15 @@ export function ExternalFavicon({
// Generate the favicon URL using the configured template
const faviconSrc = useMemo(() => {
if (!url) return;
try {
const parsedUrl = new URL(url);
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.)/, '');
// Normalize the URL to ensure it has a protocol
const normalizedUrl = normalizeUrl(url);
return faviconUrl(config.faviconUrl, normalizedUrl);
return faviconUrl(config.faviconUrl, parsedUrl);
} catch {
return;
}
+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,
};
@@ -0,0 +1,144 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Trash2, GitBranch } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import type { GitCredential } from '@/contexts/GitSettingsContext';
import { ExternalFavicon } from '@/components/ExternalFavicon';
interface GitCredentialConfigDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
credential: GitCredential;
onUpdate: (credential: GitCredential) => void;
onRemove: () => void;
isCustom?: boolean;
}
export function GitCredentialConfigDialog({
open,
onOpenChange,
credential,
onUpdate,
onRemove,
isCustom = false,
}: GitCredentialConfigDialogProps) {
const { t } = useTranslation();
const [localCredential, setLocalCredential] = useState(credential);
// Reset local state when credential changes or dialog opens
useEffect(() => {
if (open) {
setLocalCredential(credential);
}
}, [credential, open]);
const handleSave = () => {
onUpdate(localCredential);
onOpenChange(false);
};
const handleDelete = () => {
onRemove();
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<div className="flex items-center gap-2">
<ExternalFavicon
url={localCredential.origin}
size={20}
fallback={<GitBranch size={20} />}
/>
<DialogTitle>{localCredential.name}</DialogTitle>
{isCustom && <Badge variant="outline">{t('custom')}</Badge>}
</div>
<DialogDescription>
Configure your Git credentials
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="grid gap-2">
<Label htmlFor="credential-name">
{t('name')} <span className="text-destructive">*</span>
</Label>
<Input
id="credential-name"
placeholder="GitHub"
value={localCredential.name}
onChange={(e) => setLocalCredential({ ...localCredential, name: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="credential-origin">
{t('origin')} <span className="text-destructive">*</span>
</Label>
<Input
id="credential-origin"
placeholder="https://github.com"
value={localCredential.origin}
onChange={(e) => setLocalCredential({ ...localCredential, origin: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="credential-username">
{t('username')} <span className="text-destructive">*</span>
</Label>
<Input
id="credential-username"
placeholder="git"
value={localCredential.username}
onChange={(e) => setLocalCredential({ ...localCredential, username: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="credential-password">
{t('password')} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="credential-password"
placeholder={t('enterPassword')}
value={localCredential.password}
onChange={(e) => setLocalCredential({ ...localCredential, password: e.target.value })}
/>
</div>
</div>
<DialogFooter className="gap-2">
<Button
variant="destructive"
onClick={handleDelete}
className="sm:mr-auto"
>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</Button>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
</Button>
<Button onClick={handleSave}>
{t('save')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
-245
View File
@@ -1,245 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { GitDialog } from './GitDialog';
// Mock the hooks
const mockRefetch = vi.fn();
const mockUseGitStatus = vi.fn();
const baseGitStatus = {
isGitRepo: true,
currentBranch: 'main',
hasUncommittedChanges: false,
changedFiles: [],
totalCommits: 5,
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
latestCommit: {
oid: 'abc123def456',
message: 'Initial commit',
author: {
name: 'Test User',
email: '[email protected]',
timestamp: Date.now() / 1000,
},
},
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
vi.mock('@/hooks/useGitStatus', () => ({
useGitStatus: () => mockUseGitStatus(),
}));
vi.mock('@/hooks/useFS', () => ({
useFS: vi.fn(() => ({
fs: {},
})),
}));
vi.mock('@/hooks/useToast', () => ({
useToast: vi.fn(() => ({
toast: vi.fn(),
})),
}));
const mockUseGitSettings = vi.fn();
vi.mock('@/hooks/useGitSettings', () => ({
useGitSettings: () => mockUseGitSettings(),
}));
describe('GitDialog', () => {
beforeEach(() => {
mockUseGitStatus.mockReturnValue({
data: baseGitStatus,
refetch: mockRefetch,
});
mockUseGitSettings.mockReturnValue({
settings: {
credentials: {
'https://github.com': {
username: 'git',
password: 'github-token',
},
},
},
});
});
it('renders git dialog without repository information section', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Repository')).toBeInTheDocument();
expect(screen.queryByText('Repository Information')).not.toBeInTheDocument();
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows sync status when branch is published', () => {
// Mock git status with published branch
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
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('Up to date')).toBeInTheDocument();
expect(screen.getByText('Pull')).toBeInTheDocument();
expect(screen.getByText('Push')).toBeInTheDocument();
});
it('shows clean working directory when no changes', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Working directory is clean')).toBeInTheDocument();
expect(screen.getByText('No uncommitted changes')).toBeInTheDocument();
});
it('enables push button when there are commits ahead', () => {
// Mock git status with commits ahead
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 2,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
expect(pushButton.closest('button')).not.toBeDisabled();
});
it('disables push button when no commits ahead and branch is published', () => {
// Mock git status with published branch and no commits ahead
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 0,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
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>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
// Should not show warning when credentials are configured
expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument();
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows credentials warning when no credentials are configured', () => {
// Mock git settings with no credentials and mock git status with an https remote
mockUseGitSettings.mockReturnValue({
settings: {
credentials: {},
},
});
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
// Should show warning when credentials are missing
expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument();
expect(screen.getByText('log in')).toBeInTheDocument();
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
});
File diff suppressed because it is too large. Load diff
+34 -18
View File
@@ -14,35 +14,49 @@ vi.mock('@/lib/configUtils', () => ({
// Test component that uses the hook
function TestComponent() {
const { settings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
const { settings, addCredential, removeCredential, setCredentials, isConfigured } = useGitSettings();
const handleAdd = () => {
const credential: GitCredential = {
id: crypto.randomUUID(),
name: 'GitHub',
origin: 'https://github.com',
username: 'git',
password: 'test-token',
};
addCredential('https://github.com', credential);
addCredential(credential);
};
const handleUpdate = () => {
updateCredential('https://github.com', { password: 'updated-token' });
const githubCred = settings.credentials.find(c => c.origin === 'https://github.com');
if (githubCred) {
const updatedCredentials = settings.credentials.map((cred) =>
cred.id === githubCred.id ? { ...cred, password: 'updated-token' } : cred
);
setCredentials(updatedCredentials);
}
};
const handleRemove = () => {
removeCredential('https://github.com');
const githubCred = settings.credentials.find(c => c.origin === 'https://github.com');
if (githubCred) {
removeCredential(githubCred.id);
}
};
const githubCred = settings.credentials.find(c => c.origin === 'https://github.com');
return (
<div>
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
<div data-testid="count">{settings.credentials.length}</div>
<button onClick={handleAdd}>Add GitHub</button>
<button onClick={handleUpdate}>Update GitHub</button>
<button onClick={handleRemove}>Remove GitHub</button>
{settings.credentials['https://github.com'] && (
{githubCred && (
<div data-testid="github-creds">
{settings.credentials['https://github.com'].username}:
{settings.credentials['https://github.com'].password}
{githubCred.username}:
{githubCred.password}
</div>
)}
</div>
@@ -67,8 +81,7 @@ describe('GitSettingsProvider', () => {
// Mock the read function to return default settings
const { readGitSettings } = await import('@/lib/configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
hostTokens: {},
credentials: [],
});
});
@@ -165,12 +178,13 @@ describe('GitSettingsProvider', () => {
expect(writeGitSettings).toHaveBeenCalledWith(
expect.anything(), // fs instance
expect.objectContaining({
credentials: {
'https://github.com': {
credentials: expect.arrayContaining([
expect.objectContaining({
origin: 'https://github.com',
username: 'git',
password: 'test-token',
}
}
})
])
}),
'/config' // configPath
);
@@ -179,13 +193,15 @@ describe('GitSettingsProvider', () => {
it('loads settings from VFS', async () => {
const settings = {
credentials: {
'https://gitlab.com': {
credentials: [
{
id: crypto.randomUUID(),
name: 'GitLab',
origin: 'https://gitlab.com',
username: 'git',
password: 'gitlab-token',
},
},
hostTokens: {},
],
};
const { readGitSettings } = await import('@/lib/configUtils');
+10 -59
View File
@@ -1,5 +1,5 @@
import { ReactNode, useState, useEffect } from 'react';
import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
@@ -9,8 +9,7 @@ interface GitSettingsProviderProps {
}
const DEFAULT_SETTINGS: GitSettings = {
credentials: {},
hostTokens: {},
credentials: [],
};
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
@@ -55,83 +54,35 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
setSettings(prev => ({ ...prev, ...newSettings }));
};
const addCredential = (origin: string, credential: GitCredential) => {
const addCredential = (credential: GitCredential) => {
setSettings(prev => ({
...prev,
credentials: {
...prev.credentials,
[origin]: credential,
},
credentials: [...prev.credentials, credential],
}));
};
const removeCredential = (origin: string) => {
setSettings(prev => {
const { [origin]: removed, ...rest } = prev.credentials;
return {
...prev,
credentials: rest,
};
});
};
const updateCredential = (origin: string, credential: Partial<GitCredential>) => {
const removeCredential = (id: string) => {
setSettings(prev => ({
...prev,
credentials: {
...prev.credentials,
[origin]: {
...prev.credentials[origin],
...credential,
},
},
credentials: prev.credentials.filter((cred) => cred.id !== id),
}));
};
const addHostToken = (host: string, token: GitHostToken) => {
const setCredentials = (credentials: GitCredential[]) => {
setSettings(prev => ({
...prev,
hostTokens: {
...prev.hostTokens,
[host]: token,
},
credentials,
}));
};
const removeHostToken = (host: string) => {
setSettings(prev => {
const { [host]: removed, ...rest } = prev.hostTokens;
return {
...prev,
hostTokens: rest,
};
});
};
const updateHostToken = (host: string, token: Partial<GitHostToken>) => {
setSettings(prev => ({
...prev,
hostTokens: {
...prev.hostTokens,
[host]: {
...prev.hostTokens[host],
...token,
},
},
}));
};
const isConfigured = Object.entries(settings.credentials).length > 0;
const isConfigured = settings.credentials.length > 0;
const contextValue: GitSettingsContextType = {
settings,
updateSettings,
addCredential,
removeCredential,
updateCredential,
addHostToken,
removeHostToken,
updateHostToken,
setCredentials,
isConfigured,
isInitialized,
};
+228
View File
@@ -0,0 +1,228 @@
import { useState, useCallback, ReactNode, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { GitSyncContext, GitOperation, GitSyncState, FetchResult } from '@/contexts/GitSyncContext';
import { useGit } from '@/hooks/useGit';
export function GitSyncProvider({ children }: { children: ReactNode }) {
const [syncStates, setSyncStates] = useState<Map<string, GitSyncState>>(new Map());
const queryClient = useQueryClient();
const { git } = useGit();
// Track active operations to prevent concurrent operations on the same directory
const activeOperations = useRef<Map<string, Promise<unknown>>>(new Map());
const startOperation = useCallback((dir: string, operation: GitOperation) => {
setSyncStates(prev => {
const next = new Map(prev);
// Clear any previous error when starting a new operation
next.set(dir, { dir, operation, isActive: true });
return next;
});
}, []);
const endOperation = useCallback((dir: string, error?: Error) => {
setSyncStates(prev => {
const next = new Map(prev);
if (error) {
// Keep the state with the error
const currentState = prev.get(dir);
if (currentState) {
next.set(dir, { ...currentState, isActive: false, error });
}
} else {
// Remove the state if no error
next.delete(dir);
}
return next;
});
}, []);
const setError = useCallback((dir: string, error: Error | null) => {
setSyncStates(prev => {
const next = new Map(prev);
const currentState = prev.get(dir);
if (error) {
// Set or update error
if (currentState) {
next.set(dir, { ...currentState, error });
} else {
// Create a new state with just the error (no active operation)
next.set(dir, { dir, operation: 'fetch', isActive: false, error });
}
} else {
// Clear error
if (currentState) {
const { error: _, ...stateWithoutError } = currentState;
if (stateWithoutError.isActive) {
next.set(dir, stateWithoutError);
} else {
// If not active and no error, remove the state entirely
next.delete(dir);
}
}
}
return next;
});
}, []);
const getState = useCallback((dir: string) => {
return syncStates.get(dir);
}, [syncStates]);
const getError = useCallback((dir: string) => {
return syncStates.get(dir)?.error;
}, [syncStates]);
// Helper to invalidate git status queries
const invalidateGitStatus = useCallback((dir: string) => {
const projectId = dir.split('/').pop();
if (projectId) {
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
}
}, [queryClient]);
// Helper to ensure only one operation runs at a time per directory
const withOperationLock = useCallback(async <T,>(
dir: string,
operation: GitOperation,
fn: () => Promise<T>
): Promise<T> => {
// Check if there's already an active operation for this directory
const existingOp = activeOperations.current.get(dir);
if (existingOp) {
// Wait for the existing operation to complete first
await existingOp.catch(() => {
// Ignore errors from previous operation
});
}
// Start the new operation
startOperation(dir, operation);
setError(dir, null);
const promise = fn()
.then(result => {
endOperation(dir);
activeOperations.current.delete(dir);
return result;
})
.catch(err => {
const error = err instanceof Error ? err : new Error(`${operation} failed`);
endOperation(dir, error);
setError(dir, error);
activeOperations.current.delete(dir);
throw error;
});
activeOperations.current.set(dir, promise);
return promise;
}, [startOperation, endOperation, setError]);
// Git operation: fetch
const fetch = useCallback(async (dir: string, remote = 'origin'): Promise<FetchResult> => {
return withOperationLock(dir, 'fetch', async () => {
const fetchResult = await git.fetch({ dir, remote });
invalidateGitStatus(dir);
return fetchResult;
});
}, [git, withOperationLock, invalidateGitStatus]);
// Git operation: pull
const pull = useCallback(async (dir: string, ref: string, _remote = 'origin'): Promise<void> => {
return withOperationLock(dir, 'pull', async () => {
await git.pull({ dir, ref, singleBranch: true });
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus]);
// Git operation: push
const push = useCallback(async (dir: string, ref: string, remote = 'origin', force = false): Promise<void> => {
return withOperationLock(dir, 'push', async () => {
await git.push({ dir, remote, ref, force });
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus]);
// Git operation: sync (pull then push)
const sync = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise<void> => {
return withOperationLock(dir, 'pull', async () => {
const cache = {};
// Pull first
await git.pull({ dir, ref, singleBranch: true, cache });
// Then push (update operation type)
startOperation(dir, 'push');
await git.push({ dir, remote, ref, cache });
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus, startOperation]);
// Git operation: force pull
const forcePull = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise<void> => {
return withOperationLock(dir, 'pull', async () => {
const cache = {};
// Step 1: Fetch latest changes from remote
await git.fetch({
dir,
remote,
ref,
singleBranch: true,
cache,
});
// Step 2: Get the remote commit SHA
const remoteRef = `refs/remotes/${remote}/${ref}`;
const remoteSha = await git.resolveRef({ dir, ref: remoteRef });
// Step 3: Force update the current branch to point to remote
await git.writeRef({
dir,
ref: `refs/heads/${ref}`,
value: remoteSha,
force: true,
});
// Step 4: Force checkout all files (overwrite local changes)
await git.checkout({
dir,
ref,
force: true,
cache,
});
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus]);
// Git operation: force push
const forcePush = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise<void> => {
return withOperationLock(dir, 'push', async () => {
await git.push({ dir, remote, ref, force: true });
invalidateGitStatus(dir);
});
}, [git, withOperationLock, invalidateGitStatus]);
return (
<GitSyncContext.Provider value={{
syncStates,
getState,
getError,
fetch,
pull,
push,
sync,
forcePull,
forcePush,
startOperation,
endOperation,
setError,
}}>
{children}
</GitSyncContext.Provider>
);
}
+223
View File
@@ -0,0 +1,223 @@
import { useState, useEffect } from 'react';
import { Plus, X, Server } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { toast } from '@/hooks/useToast';
export function GraspListManager() {
const { config, updateConfig } = useAppContext();
const { user } = useCurrentUser();
const { mutate: publishEvent } = useNostrPublish();
const [graspRelays, setGraspRelays] = useState<{ url: string }[]>(config.graspMetadata.relays);
const [newRelayUrl, setNewRelayUrl] = useState('');
// Sync local state with config when it changes (e.g., from NostrProvider sync)
useEffect(() => {
setGraspRelays(config.graspMetadata.relays);
}, [config.graspMetadata.relays]);
const normalizeRelayUrl = (url: string): string => {
url = url.trim();
try {
const parsed = new URL(url);
// Ensure it's a websocket URL
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
parsed.protocol = 'wss:';
}
// Ensure trailing slash
if (!parsed.pathname.endsWith('/')) {
parsed.pathname += '/';
}
return parsed.toString();
} catch {
// If parsing fails, try to construct a valid URL
try {
const withProtocol = url.startsWith('ws://') || url.startsWith('wss://')
? url
: `wss://${url}`;
const parsed = new URL(withProtocol);
if (!parsed.pathname.endsWith('/')) {
parsed.pathname += '/';
}
return parsed.toString();
} catch {
return url;
}
}
};
const isValidRelayUrl = (url: string): boolean => {
const trimmed = url.trim();
if (!trimmed) return false;
const normalized = normalizeRelayUrl(trimmed);
try {
const parsed = new URL(normalized);
return parsed.protocol === 'ws:' || parsed.protocol === 'wss:';
} catch {
return false;
}
};
const handleAddRelay = () => {
if (!isValidRelayUrl(newRelayUrl)) {
toast({
title: 'Invalid relay URL',
description: 'Please enter a valid websocket URL (e.g., wss://git.shakespeare.diy/)',
variant: 'destructive',
});
return;
}
const normalized = normalizeRelayUrl(newRelayUrl);
if (graspRelays.some(r => r.url === normalized)) {
toast({
title: 'Relay already exists',
description: 'This relay is already in your list',
variant: 'destructive',
});
return;
}
const newRelays = [...graspRelays, { url: normalized }];
setGraspRelays(newRelays);
setNewRelayUrl('');
saveRelays(newRelays);
};
const handleRemoveRelay = (url: string) => {
const newRelays = graspRelays.filter(r => r.url !== url);
setGraspRelays(newRelays);
saveRelays(newRelays);
};
const saveRelays = (newRelays: { url: string }[]) => {
const now = Math.floor(Date.now() / 1000);
// Update local config
updateConfig((current) => ({
...current,
graspMetadata: {
relays: newRelays,
updatedAt: now,
},
}));
// Publish to Nostr if user is logged in
if (user) {
publishNIP34GraspList(newRelays);
}
};
const publishNIP34GraspList = (relays: { url: string }[]) => {
const tags = relays.map(relay => ['g', relay.url]);
publishEvent(
{
kind: 10317,
content: '',
tags,
},
{
onSuccess: () => {
toast({
title: 'Grasp list published',
description: 'Your Nostr git server list has been published to your relays',
});
},
onError: (error) => {
console.error('Failed to publish grasp list:', error);
toast({
title: 'Publish failed',
description: 'Failed to publish your grasp server list',
variant: 'destructive',
});
},
}
);
};
const renderRelayUrl = (url: string): string => {
try {
const parsed = new URL(url);
if (parsed.pathname === '/') {
return parsed.host;
} else {
return parsed.host + parsed.pathname;
}
} catch {
return url;
}
};
return (
<div className="space-y-4">
{/* Relay List */}
<div className="space-y-2">
{graspRelays.map((relay) => (
<div
key={relay.url}
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
>
<Server className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
{renderRelayUrl(relay.url)}
</span>
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveRelay(relay.url)}
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
disabled={graspRelays.length <= 1}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
{/* Add Relay Form */}
<div className="flex gap-2">
<div className="flex-1">
<Label htmlFor="new-grasp-relay" className="sr-only">
Grasp Relay URL
</Label>
<Input
id="new-grasp-relay"
placeholder="wss://git.shakespeare.diy/"
value={newRelayUrl}
onChange={(e) => setNewRelayUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddRelay();
}
}}
/>
</div>
<Button
onClick={handleAddRelay}
disabled={!newRelayUrl.trim()}
variant="outline"
size="sm"
className="h-10 shrink-0"
>
<Plus className="h-4 w-4 mr-2" />
Add
</Button>
</div>
{!user && (
<p className="text-xs text-muted-foreground">
Log in to sync your grasp server list with Nostr
</p>
)}
</div>
);
}
+69
View File
@@ -0,0 +1,69 @@
import { X } from 'lucide-react';
import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { VFSImage } from '@/components/VFSImage';
import { cn } from '@/lib/utils';
interface ImageLightboxProps {
imageUrl: string | null;
onClose: () => void;
}
export function ImageLightbox({ imageUrl, onClose }: ImageLightboxProps) {
return (
<Dialog open={!!imageUrl} onOpenChange={(open) => !open && onClose()}>
<DialogPortal>
<DialogOverlay className="bg-black/95" />
<DialogPrimitive.Content
className={cn(
"fixed inset-0 z-50 flex items-center justify-center p-4 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"
)}
onEscapeKeyDown={onClose}
>
{imageUrl && (
<>
{/* Clickable background to close */}
<div
className="absolute inset-0 cursor-pointer z-[1]"
onClick={onClose}
aria-label="Close lightbox"
/>
{/* Close button */}
<button
onClick={onClose}
className="absolute top-4 right-4 z-[3] p-2 rounded-full bg-black/50 hover:bg-black/70 text-white transition-colors"
aria-label="Close"
>
<X className="h-6 w-6" />
</button>
{/* Image */}
<div
className="relative z-[2] flex items-center justify-center w-full h-full pointer-events-none"
onClick={(e) => e.stopPropagation()}
>
{imageUrl.startsWith('/') ? (
<VFSImage
path={imageUrl}
alt="Expanded image"
className="max-w-[calc(100vw-2rem)] max-h-[calc(100vh-2rem)] w-auto h-auto object-contain rounded-lg pointer-events-auto"
/>
) : (
<img
src={imageUrl}
alt="Expanded image"
className="max-w-[calc(100vw-2rem)] max-h-[calc(100vh-2rem)] w-auto h-auto object-contain rounded-lg pointer-events-auto"
/>
)}
</div>
</>
)}
</DialogPrimitive.Content>
</DialogPortal>
</Dialog>
);
}
+83
View File
@@ -0,0 +1,83 @@
import { useState, useEffect, useCallback } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { useAISettings } from '@/hooks/useAISettings';
import { ModelInput } from '@/components/ModelInput';
interface ImageModelDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function ImageModelDialog({ open, onOpenChange }: ImageModelDialogProps) {
const { settings, updateSettings } = useAISettings();
const [selectedModel, setSelectedModel] = useState(settings.imageModel || '');
// Update selected model when dialog opens or settings change
useEffect(() => {
if (open) {
setSelectedModel(settings.imageModel || '');
}
}, [open, settings.imageModel]);
const handleSave = () => {
updateSettings({ imageModel: selectedModel || undefined });
onOpenChange(false);
};
const imageModelFilter = useCallback((model: { type?: 'chat' | 'image'; modalities?: string[] }) => {
// Filter out models that are definitely NOT image models
// If type is "chat", exclude it
if (model.type === 'chat') {
return false;
}
// If modalities exist but don't include "image", exclude it
if (model.modalities && !model.modalities.includes('image')) {
return false;
}
// Otherwise include it (type is "image", modalities includes "image", or both are undefined)
return true;
}, []);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>Configure Image Model</DialogTitle>
<DialogDescription>
Select an AI model to use for image generation.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="image-model">Image Model</Label>
<ModelInput
value={selectedModel}
onChange={setSelectedModel}
className="flex-1"
modelFilter={imageModelFilter}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleSave}>
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+33 -11
View File
@@ -1,8 +1,17 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { render, screen, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import type { AIProvider } from '@/contexts/AISettingsContext';
// Mock useAICredits to return credits data
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: () => ({
data: { amount: 10.50 },
error: null,
isLoading: false,
}),
}));
// Mock QRCode
vi.mock('qrcode', () => ({
default: {
@@ -17,10 +26,11 @@ const mockWebLN = {
};
// We need to import the component after mocking
const { CreditsDialog } = await import('./CreditsDialog');
const { AIProviderConfigDialog } = await import('./AIProviderConfigDialog');
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
@@ -39,16 +49,20 @@ describe('Lightning Payment', () => {
it('shows QR code for Lightning payment', async () => {
render(
<TestApp>
<CreditsDialog
<AIProviderConfigDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
// Should show the Credits tab with Buy Credits accordion
await waitFor(() => {
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
});
});
it('shows WebLN button when available', async () => {
@@ -60,30 +74,38 @@ describe('Lightning Payment', () => {
render(
<TestApp>
<CreditsDialog
<AIProviderConfigDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
// Should show the Credits tab with Buy Credits accordion
await waitFor(() => {
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
});
});
it('displays copy invoice button', async () => {
render(
<TestApp>
<CreditsDialog
<AIProviderConfigDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Payment Method')).toBeInTheDocument();
// Should show the Credits tab with Buy Credits accordion
await waitFor(() => {
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
});
});
});
+18 -19
View File
@@ -6,8 +6,6 @@ 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 { Separator } from '@/components/ui/separator';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useAISettings } from '@/hooks/useAISettings';
import { useToast } from '@/hooks/useToast';
import { useMCPServerStatus } from '@/hooks/useMCPServerStatus';
@@ -192,9 +190,6 @@ export function MCPServersSection() {
return (
<div className="space-y-4">
{/* Divider */}
<Separator className="my-6" />
{/* MCP Servers Header */}
<div className="space-y-2">
<div className="flex items-center gap-2">
@@ -207,14 +202,14 @@ export function MCPServersSection() {
</div>
{/* Configured MCP Servers List */}
{serverEntries.length > 0 ? (
{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-primary" />
<Server size={16} className="text-muted-foreground" />
<span className="font-medium">{name}</span>
<MCPConnectionStatus server={server} />
</div>
@@ -222,7 +217,9 @@ export function MCPServersSection() {
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`${name}-type`}>{t('mcpServerType')}</Label>
<Label htmlFor={`${name}-type`}>
{t('mcpServerType')} <span className="text-destructive">*</span>
</Label>
<Select value={server.type} disabled>
<SelectTrigger>
<SelectValue />
@@ -233,7 +230,9 @@ export function MCPServersSection() {
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor={`${name}-url`}>{t('mcpServerUrl')}</Label>
<Label htmlFor={`${name}-url`}>
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id={`${name}-url`}
value={server.url}
@@ -259,17 +258,11 @@ export function MCPServersSection() {
</Accordion>
))}
</div>
) : (
<Alert>
<AlertDescription className="text-sm">
{t('noMcpServersConfigured')}
</AlertDescription>
</Alert>
)}
{/* Add New MCP Server */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-server" className="border rounded-lg">
<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" />
@@ -282,7 +275,9 @@ export function MCPServersSection() {
{t('mcpServerDescription')}
</p>
<div className="grid gap-2">
<Label htmlFor="new-server-name">{t('mcpServerName')}</Label>
<Label htmlFor="new-server-name">
{t('mcpServerName')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-server-name"
placeholder="e.g., my-mcp-server"
@@ -291,7 +286,9 @@ export function MCPServersSection() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-type">{t('mcpServerType')}</Label>
<Label htmlFor="new-server-type">
{t('mcpServerType')} <span className="text-destructive">*</span>
</Label>
<Select value={serverType} disabled>
<SelectTrigger>
<SelectValue />
@@ -305,7 +302,9 @@ export function MCPServersSection() {
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-url">{t('mcpServerUrl')}</Label>
<Label htmlFor="new-server-url">
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-server-url"
placeholder="https://example.com/mcp"
+84
View File
@@ -0,0 +1,84 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ModelInput } from './ModelInput';
// Mock the hooks
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: () => ({
settings: {
providers: [
{ id: 'test-provider', name: 'Test Provider', baseURL: 'https://api.test.com' }
]
}
})
}));
vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: () => ({
models: [
{
id: 'text-model',
name: 'Text Model',
provider: 'test-provider',
fullId: 'test-provider/text-model',
inputModalities: ['text'],
outputModalities: ['text']
},
{
id: 'image-model',
name: 'Image Model',
provider: 'test-provider',
fullId: 'test-provider/image-model',
inputModalities: ['text'],
outputModalities: ['image']
},
{
id: 'multimodal-model',
name: 'Multimodal Model',
provider: 'test-provider',
fullId: 'test-provider/multimodal-model',
inputModalities: ['text', 'image'],
outputModalities: ['text', 'image']
},
{
id: 'no-modalities-model',
name: 'No Modalities Model',
provider: 'test-provider',
fullId: 'test-provider/no-modalities-model'
}
],
isLoading: false,
error: null,
refetch: vi.fn()
})
}));
describe('ModelInput', () => {
it('renders without crashing', () => {
const onChange = vi.fn();
render(
<TestApp>
<ModelInput value="" onChange={onChange} />
</TestApp>
);
expect(screen.getByRole('combobox')).toBeInTheDocument();
});
it('accepts modelFilter prop', () => {
const onChange = vi.fn();
const modelFilter = (model: { modalities?: string[] }) => model.modalities?.includes('image') ?? false;
render(
<TestApp>
<ModelInput
value=""
onChange={onChange}
modelFilter={modelFilter}
/>
</TestApp>
);
expect(screen.getByRole('combobox')).toBeInTheDocument();
});
});
+185
View File
@@ -0,0 +1,185 @@
import { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Bot, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { cn } from '@/lib/utils';
interface ProviderModel {
id: string;
type?: "chat" | "image";
name?: string;
provider: string;
fullId: string;
description?: string;
contextLength?: number;
pricing?: {
prompt: unknown;
completion: unknown;
};
modalities?: string[];
}
interface ModelInputProps {
value: string;
onChange: (value: string) => void;
className?: string;
placeholder?: string;
modelFilter?: (model: ProviderModel) => boolean;
}
export function ModelInput({
value,
onChange,
className,
placeholder,
modelFilter,
}: ModelInputProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const { settings } = useAISettings();
const { models } = useProviderModels();
const defaultPlaceholder = 'Select a model...';
// Filter models using the provided filter function
const filteredModels = useMemo(() => {
if (modelFilter) {
return models.filter(modelFilter);
}
return models;
}, [models, modelFilter]);
// Group models by provider
const modelsByProvider = useMemo(() => {
const groups: Record<string, typeof filteredModels> = {};
for (const model of filteredModels) {
if (!groups[model.provider]) {
groups[model.provider] = [];
}
groups[model.provider].push(model);
}
return groups;
}, [filteredModels]);
// 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 = filteredModels.find(m => m.fullId === value);
const displayName = modelData?.name || modelId;
return {
displayName,
baseURL: providerInfo.baseURL,
};
}, [value, getProviderInfo, filteredModels]);
const handleSelect = (selectedValue: string) => {
onChange(selectedValue);
setOpen(false);
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className={cn(
"w-full justify-between font-normal h-10",
!value && "text-muted-foreground",
className
)}
>
{selectedModelDisplay ? (
<div className="flex items-center gap-2 min-w-0">
{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>
</div>
) : (
<span className="truncate">
{placeholder || defaultPlaceholder}
</span>
)}
<ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[400px] p-0" align="start">
<Command>
<CommandInput placeholder={t('searchModels')} className="h-9" />
<CommandList>
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
</div>
</CommandEmpty>
{/* Provider models */}
{Object.entries(modelsByProvider).map(([providerId, providerModels], index) => {
const providerInfo = getProviderInfo(providerId);
return (
<div key={providerId}>
{index > 0 && <CommandSeparator />}
<CommandGroup heading={providerInfo.displayName}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
{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.name || model.id}</span>
</CommandItem>
))}
</CommandGroup>
</div>
);
})}
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
+40 -29
View File
@@ -45,6 +45,7 @@ describe('ModelSelector', () => {
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
@@ -81,9 +82,17 @@ 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,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
@@ -105,18 +114,16 @@ 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
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
// provider1 should still be visible (models appear in both sections now)
expect(screen.getByText('provider1')).toBeInTheDocument();
expect(screen.getByText('model1')).toBeInTheDocument();
expect(screen.getByText('model2')).toBeInTheDocument();
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 should still show with model3
// provider2 should still show with model3 (just the model ID, not the full ID)
expect(screen.getByText('model3')).toBeInTheDocument();
});
@@ -138,9 +145,18 @@ 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,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
@@ -162,17 +178,11 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
// provider1 appears in both recently used and available sections
const provider1Elements = screen.queryAllByText('provider1');
expect(provider1Elements.length).toBeGreaterThan(0);
expect(screen.getByText('Provider 1')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
expect(screen.getByText('Recently Used')).toBeInTheDocument();
// provider1 should appear in both sections (recently used and available)
const provider1Elements = screen.queryAllByText('provider1');
expect(provider1Elements.length).toBeGreaterThanOrEqual(1);
});
it('shows recently used section when 5 or more models are available', async () => {
@@ -195,9 +205,18 @@ 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,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
@@ -219,25 +238,16 @@ 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
expect(screen.getByText('Recently Used')).toBeInTheDocument();
// provider1 should still be visible (models appear in both sections now)
// Use queryAllByText since provider1 appears as a heading in both sections
const provider1Elements = screen.queryAllByText('provider1');
expect(provider1Elements.length).toBeGreaterThanOrEqual(1);
// Models should be visible (display text is just the model name, not full ID)
// model1 and model2 appear in both recently used and available sections
const model1Elements = screen.queryAllByText('model1');
expect(model1Elements.length).toBeGreaterThanOrEqual(1);
const model2Elements = screen.queryAllByText('model2');
expect(model2Elements.length).toBeGreaterThanOrEqual(1);
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 and provider3 should still show (only in available section)
// 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();
@@ -260,6 +270,7 @@ describe('ModelSelector', () => {
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, // No recently used models
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
+172 -194
View File
@@ -1,11 +1,10 @@
import { useState, useMemo, useEffect, memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Decimal } from 'decimal.js';
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 { Dialog, DialogContent, DialogTrigger } from '@/components/ui/dialog';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
@@ -13,74 +12,9 @@ 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';
// Type for model (matches ProviderModel from useProviderModels)
type ModelType = {
id: string;
name?: string;
provider: string;
fullId: string;
description?: string;
contextLength?: number;
pricing?: {
prompt: Decimal;
completion: Decimal;
};
};
// Interface for grouped models by provider
interface ModelGroup {
provider: string;
models: ModelType[];
}
// Parse model ID into components (provider/company/model or provider/model)
function parseModelId(fullId: string) {
const parts = fullId.split('/');
return {
provider: parts[0] || '',
company: parts.length >= 3 ? parts[1] : null,
modelName: parts.length >= 3 ? parts.slice(2).join('/') : parts[1] || '',
};
}
// Group models by provider and sort
function groupModelsByProvider(models: ModelType[], excludeIds: Set<string>): ModelGroup[] {
const groups: Record<string, ModelType[]> = {};
// Group by provider
models.forEach(model => {
if (!excludeIds.has(model.fullId)) {
const { provider } = parseModelId(model.fullId);
if (!groups[provider]) groups[provider] = [];
groups[provider].push(model);
}
});
// Sort models within each group and convert to array
return Object.entries(groups)
.map(([provider, models]) => ({
provider,
models: models.sort((a, b) => {
const aParsed = parseModelId(a.fullId);
const bParsed = parseModelId(b.fullId);
// Sort by company, then model name
if (aParsed.company && bParsed.company) {
const diff = aParsed.company.localeCompare(bParsed.company);
if (diff !== 0) return diff;
}
return aParsed.modelName.localeCompare(bParsed.modelName);
}),
}))
.sort((a, b) => {
// Shakespeare first, then alphabetical
if (a.provider === 'shakespeare') return -1;
if (b.provider === 'shakespeare') return 1;
return a.provider.localeCompare(b.provider);
});
}
interface ModelSelectorProps {
value: string;
onChange: (value: string) => void;
@@ -91,46 +25,6 @@ interface ModelSelectorProps {
onOpenChange?: (open: boolean) => void;
}
// Render a model item in the list
const ModelItem = memo(({ model, currentValue, onSelect, valuePrefix = '' }: {
model: ModelType;
currentValue: string;
onSelect: (value: string) => void;
valuePrefix?: string;
}) => {
const parsed = parseModelId(model.fullId);
const displayText = parsed.company
? `${parsed.company}/${parsed.modelName}`
: parsed.modelName;
// Use prefix to make value unique (prevents both recently used and available from highlighting together)
const uniqueValue = valuePrefix ? `${valuePrefix}-${model.fullId}` : model.fullId;
return (
<CommandItem
key={model.fullId}
value={uniqueValue}
keywords={[model.fullId]}
onSelect={() => onSelect(model.fullId)}
className="cursor-pointer"
title={model.fullId}
>
<Check
className={cn(
"mr-2 h-4 w-4 shrink-0",
currentValue === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="flex-1 min-w-0 truncate">
{displayText}
</span>
{model.pricing && (
<ModelPricing pricing={model.pricing} className="ml-2 shrink-0" />
)}
</CommandItem>
);
});
export const ModelSelector = memo(function ModelSelector({
value,
onChange,
@@ -150,20 +44,22 @@ export const ModelSelector = memo(function ModelSelector({
const [isCustomInput, setIsCustomInput] = useState(false);
const [customValue, setCustomValue] = useState('');
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
const { models, isLoading, error, refetch } = useProviderModels();
const { settings, addRecentlyUsedModel, isConfigured, isLoading: isLoadingSettings } = useAISettings();
const { models: allModels, isLoading, error, refetch } = useProviderModels();
const navigate = useNavigate();
const isMobile = useIsMobile();
// Filter models to only include chat models (type is undefined or "chat")
const models = useMemo(() => {
return allModels.filter(model => model.type === undefined || model.type === 'chat');
}, [allModels]);
const defaultPlaceholder = t('selectOrEnterModel');
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
// Group models by provider (don't exclude recently used - they should appear in both sections)
const modelGroups = useMemo(
() => groupModelsByProvider(models, new Set()),
[models]
);
// Create a Set of recently used model IDs for efficient lookup
const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]);
// Determine if we should show the "Recently Used" section
const shouldShowRecentlyUsed = useMemo(() => {
@@ -188,14 +84,50 @@ export const ModelSelector = memo(function ModelSelector({
return !allRecentlyUsedAreAvailable;
}, [recentlyUsedModels, models]);
// Group recently used models (same structure as available models)
const recentlyUsedGroups = useMemo(() => {
if (!shouldShowRecentlyUsed) return [];
const recentModels = recentlyUsedModels
.map(id => models.find(m => m.fullId === id))
.filter((m): m is ModelType => m !== undefined);
return groupModelsByProvider(recentModels, new Set());
}, [recentlyUsedModels, models, shouldShowRecentlyUsed]);
// Group models by provider, excluding models that are in the recently used section
// (only exclude them if the recently used section is actually being shown)
const modelsByProvider = useMemo(() => {
const groups: Record<string, typeof models> = {};
for (const model of models) {
// Only skip models that are in recently used if we're showing the recently used section
if (shouldShowRecentlyUsed && recentlyUsedSet.has(model.fullId)) {
continue;
}
if (!groups[model.provider]) {
groups[model.provider] = [];
}
groups[model.provider].push(model);
}
return groups;
}, [models, recentlyUsedSet, shouldShowRecentlyUsed]);
// 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]);
// Check if the current model is free
const isCurrentModelFree = useMemo(() => {
@@ -373,44 +305,51 @@ export const ModelSelector = memo(function ModelSelector({
</TooltipContent>
</Tooltip>
)}
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
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}
disabled={disabled || isLoading || isLoadingSettings}
>
<span className="truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
{(isLoading || isLoadingSettings) ? (
<Skeleton className="h-4 w-32" />
) : 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>
)}
{(!isLoading && !isLoadingSettings) && (
<ChevronDown className="size-3 shrink-0 opacity-50" />
)}
</Button>
</DialogTrigger>
<DialogContent
className={cn(
"p-0 max-w-[90vw] sm:max-w-lg md:max-w-2xl",
"max-h-[85vh] overflow-hidden flex flex-col"
)}
onOpenAutoFocus={(e) => e.preventDefault()}
>
<Command
className="flex flex-col h-full overflow-hidden"
filter={(value, search, keywords) => {
// Substring search: match if search appears anywhere in value or keywords
const s = search.toLowerCase();
if (value.toLowerCase().includes(s)) return 1;
if (keywords?.some(k => typeof k === 'string' && k.toLowerCase().includes(s))) return 1;
return 0;
}}
>
</PopoverTrigger>
<PopoverContent className="p-0 w-80" align="end">
<Command>
{(isConfigured && models.length >= 5) && (
<CommandInput placeholder={t('searchModels')} className="h-9" autoFocus={false} />
<CommandInput placeholder={t('searchModels')} className="h-9" />
)}
<CommandList className="flex-1 overflow-y-auto overflow-x-hidden">
<CommandList>
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
@@ -418,31 +357,49 @@ export const ModelSelector = memo(function ModelSelector({
</div>
</CommandEmpty>
{/* Recently Used section */}
{shouldShowRecentlyUsed && (
<>
<CommandGroup heading={t('recentlyUsed')} />
{recentlyUsedGroups.map((group) => (
<CommandGroup key={`recent-${group.provider}`} heading={group.provider}>
{group.models.map((model) => (
<ModelItem
key={model.fullId}
model={model}
currentValue={value}
onSelect={handleSelect}
valuePrefix="recent"
<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}
value={modelId}
onSelect={() => handleSelect(modelId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === modelId ? "opacity-100" : "opacity-0"
)}
/>
))}
</CommandGroup>
))}
{modelGroups.length > 0 && <CommandSeparator />}
</>
{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" />
)}
</CommandItem>
);
})}
</CommandGroup>
)}
{/* Available Models section */}
{!isLoading && modelGroups.length > 0 && (
<CommandGroup heading={t('availableModels')} />
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
@@ -480,26 +437,47 @@ export const ModelSelector = memo(function ModelSelector({
</CommandGroup>
)}
{/* No models available state */}
{!isLoading && !error && !shouldShowRecentlyUsed && modelGroups.length === 0 && (
<div className="py-12 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
</div>
)}
{/* Provider models */}
{!isLoading && modelGroups.map((group) => (
<CommandGroup key={group.provider} heading={group.provider}>
{group.models.map((model) => (
<ModelItem
key={model.fullId}
model={model}
currentValue={value}
onSelect={handleSelect}
/>
))}
</CommandGroup>
))}
{!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.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 />
@@ -525,8 +503,8 @@ export const ModelSelector = memo(function ModelSelector({
</CommandGroup>
</CommandList>
</Command>
</DialogContent>
</Dialog>
</PopoverContent>
</Popover>
</div>
</TooltipProvider>
);
+1 -1
View File
@@ -19,7 +19,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config } = useAppContext();
const gitRelays = config.ngitServers.map(server => `wss://${server}/`);
const gitRelays = config.graspMetadata.relays.map(r => r.url);
const queryClient = useQueryClient();
// Create NPool instance only once
+249
View File
@@ -0,0 +1,249 @@
import { useState, useEffect } from 'react';
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 { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostrRepo } from '@/hooks/useNostrRepo';
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
import { nip19 } from 'nostr-tools';
interface NostrRepoEditDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
repoIdentifier: string;
onSuccess?: () => void;
}
// Helper function to convert kebab-case to Title Case
function kebabToTitleCase(str: string): string {
return str
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
export function NostrRepoEditDialog({
open,
onOpenChange,
repoIdentifier,
onSuccess,
}: NostrRepoEditDialogProps) {
const [repoName, setRepoName] = useState('');
const [description, setDescription] = useState('');
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const { user } = useCurrentUser();
const { mutateAsync: publishEvent } = useNostrPublish();
const { config } = useAppContext();
// Load existing repository data with react-query
const { data: existingEvent, isLoading } = useNostrRepo({
repoIdentifier,
});
// Update form fields when event data loads
useEffect(() => {
if (existingEvent) {
const name = existingEvent.tags.find(([tagName]) => tagName === 'name')?.[1] || kebabToTitleCase(repoIdentifier);
const desc = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1] || '';
setRepoName(name);
setDescription(desc);
} else if (!isLoading) {
// No existing event, use defaults
setRepoName(kebabToTitleCase(repoIdentifier));
setDescription('');
}
}, [existingEvent, isLoading, repoIdentifier]);
const handleSave = async () => {
if (!user || !existingEvent) {
setError('Repository not found');
return;
}
setIsSaving(true);
setError(null);
try {
// Extract existing data from the event
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
const webUrls = webTag ? webTag.slice(1) : undefined;
const tTags = existingEvent.tags
.filter(([tagName]) => tagName === 't')
.map(([, value]) => value);
const eucTag = existingEvent.tags.find(([tagName, , marker]) => tagName === 'r' && marker === 'euc');
const earliestCommit = eucTag?.[1];
// Get clone URLs and relays from existing event
const cloneTag = existingEvent.tags.find(([tagName]) => tagName === 'clone');
const cloneUrls = cloneTag ? cloneTag.slice(1) : [];
const relaysTag = existingEvent.tags.find(([tagName]) => tagName === 'relays');
const relays = relaysTag ? relaysTag.slice(1) : [];
// If no clone URLs or relays, regenerate from current GRASP servers
let finalCloneUrls = cloneUrls;
let finalRelays = relays;
if (cloneUrls.length === 0 || relays.length === 0) {
// Convert user's GRASP servers to clone URLs and relay URLs
const npub = nip19.npubEncode(user.pubkey);
const newCloneUrls = new Set<string>();
const newRelays = new Set<string>();
for (const graspRelay of config.graspMetadata.relays) {
try {
const relayUrl = new URL(graspRelay.url);
newRelays.add(relayUrl.href);
const cloneUrl = new URL(`/${npub}/${repoIdentifier}.git`, `https://${relayUrl.host}`);
newCloneUrls.add(cloneUrl.href);
} catch {
// fallthrough
}
}
for (const relay of config.relayMetadata.relays.filter(r => r.write)) {
try {
const relayUrl = new URL(relay.url);
newRelays.add(relayUrl.href);
} catch {
// fallthrough
}
}
finalCloneUrls = cloneUrls.length === 0 ? [...newCloneUrls] : cloneUrls;
finalRelays = relays.length === 0 ? [...newRelays] : relays;
}
// Create updated repository announcement event
const eventTemplate = createRepositoryAnnouncementEvent({
repoId: repoIdentifier,
name: repoName.trim() || undefined,
description: description.trim() || undefined,
webUrls,
cloneUrls: finalCloneUrls,
relays: finalRelays,
tTags: tTags.length > 0 ? tTags : undefined,
earliestCommit,
});
// Publish the updated event
await publishEvent(eventTemplate);
// Wait a moment for relays to process
await new Promise(resolve => setTimeout(resolve, 1000));
// Call success callback if provided
if (onSuccess) {
onSuccess();
}
// Close dialog
onOpenChange(false);
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to update repository';
setError(message);
} finally {
setIsSaving(false);
}
};
const handleRepoNameChange = (value: string) => {
setRepoName(value);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Edit Repository</DialogTitle>
<DialogDescription>
Update your repository announcement on Nostr.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{isLoading ? (
<>
<div className="space-y-2">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-10 w-full" />
</div>
<div className="space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-24 w-full" />
</div>
</>
) : (
<>
<div className="space-y-2">
<Label htmlFor="repo-name">Repo Name</Label>
<Input
id="repo-name"
placeholder="My Project"
value={repoName}
onChange={(e) => handleRepoNameChange(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
placeholder="A brief description of your project"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={4}
/>
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
)}
</>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isSaving || isLoading}
>
Cancel
</Button>
<Button
onClick={handleSave}
disabled={isSaving || isLoading || !existingEvent}
>
{isSaving ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2" />
Saving...
</>
) : (
'Save'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+45
View File
@@ -2,6 +2,7 @@ import { useEffect } from 'react';
import { useNostr } from '@nostrify/react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useContacts } from '@/hooks/useContacts';
/**
* NostrSync - Syncs user's Nostr data
@@ -9,12 +10,16 @@ import { useAppContext } from '@/hooks/useAppContext';
* This component runs globally to sync various Nostr data when the user logs in.
* Currently syncs:
* - NIP-65 relay list (kind 10002)
* - NIP-34 grasp server list (kind 10317)
*/
export function NostrSync() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { config, updateConfig } = useAppContext();
// Prewarm user's follow list
useContacts(user?.pubkey);
useEffect(() => {
if (!user) return;
@@ -58,5 +63,45 @@ export function NostrSync() {
syncRelaysFromNostr();
}, [user, config.relayMetadata.updatedAt, nostr, updateConfig]);
useEffect(() => {
if (!user) return;
const syncGraspServersFromNostr = async () => {
try {
const events = await nostr.query(
[{ kinds: [10317], authors: [user.pubkey], limit: 1 }],
{ signal: AbortSignal.timeout(5000) }
);
if (events.length > 0) {
const event = events[0];
// Only update if the event is newer than our stored data
if (event.created_at > config.graspMetadata.updatedAt) {
const fetchedRelays = event.tags
.filter(([name]) => name === 'g')
.map(([_, url]) => ({ url }))
.filter(relay => relay.url); // Filter out empty URLs
if (fetchedRelays.length > 0) {
console.log('Syncing grasp server list from Nostr:', fetchedRelays);
updateConfig((current) => ({
...current,
graspMetadata: {
relays: fetchedRelays,
updatedAt: event.created_at,
},
}));
}
}
}
} catch (error) {
console.error('Failed to sync grasp servers from Nostr:', error);
}
};
syncGraspServersFromNostr();
}, [user, config.graspMetadata.updatedAt, nostr, updateConfig]);
return null;
}
@@ -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,
};
+34 -31
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, useRef } from 'react';
import { generateSecretKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink, Search, Coins } from 'lucide-react';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, Search, Coins } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
@@ -9,13 +9,13 @@ import { Card, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { ExternalInput } from '@/components/ui/external-input';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useAICredits } from '@/hooks/useAICredits';
import { CreditsDialog } from '@/components/CreditsDialog';
import { AIProviderConfigDialog } from '@/components/AIProviderConfigDialog';
import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ModelPricing } from '@/components/ModelPricing';
@@ -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,15 +58,21 @@ 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
// Also filter to only show text models (modalities absent or includes "text")
const providerModels = selectedProvider
? models.filter(model => model.provider === selectedProvider.id)
? models.filter(model =>
model.provider === selectedProvider.id &&
model.type !== 'image' &&
(!model.modalities || model.modalities.includes('text'))
)
: [];
// Filter models by search query
@@ -122,8 +129,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 +159,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,
};
@@ -456,37 +465,28 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
{/* API Key Input Section */}
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
<div className="space-y-3 max-w-md mx-auto">
<div className="text-center">
<h3 className="text-lg font-semibold">
<h3 className="flex justify-center text-lg font-semibold gap-2">
<ExternalFavicon
url={selectedProvider.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<span>
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
</h3>
<p className="text-sm text-muted-foreground">
{selectedProvider.id === 'routstr' ? (
t('requiresCashuToken', { providerName: selectedProvider.name })
) : (
<>
{selectedProvider.name} {t('requiresAnApiKey')}{' '}
{selectedProvider.apiKeysURL ? (
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
{t('apiKey')}
<ExternalLink className="inline-block h-4 w-4 ml-1" />
</a>
) : (
t('apiKey')
)}
</>
)}
</p>
</div>
<PasswordInput
</span>
</h3>
<ExternalInput
type="password"
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
value={providerApiKey}
onChange={(e) => setProviderApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && providerApiKey.trim()) {
if (e.key === 'Enter' && providerApiKey.trim() && agreedToProviderTerms) {
handleContinueFromProviderSelection();
}
}}
url={selectedProvider.apiKeysURL}
urlTitle="Get Key"
/>
</div>
)}
@@ -717,7 +717,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
{/* Credits Dialog */}
{showCreditsDialog && selectedModel && selectedProvider && (
<CreditsDialog
<AIProviderConfigDialog
open={showCreditsDialog}
onOpenChange={(open) => {
if (!open) {
@@ -726,9 +726,12 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}}
provider={{
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
onUpdate={() => {}}
onRemove={() => {}}
/>
)}
</>
+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>
);
}
+29 -27
View File
@@ -1,21 +1,21 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Puzzle, Plus, Trash2, RefreshCw, Loader2, Check } from 'lucide-react';
import { Puzzle, Plus, Trash2, RefreshCw, Loader2, Check, Compass } from 'lucide-react';
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';
import { DiscoverPluginsDialog } from '@/components/DiscoverPluginsDialog';
export function PluginsSection() {
const { t } = useTranslation();
const { toast } = useToast();
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin } = usePlugins();
const [gitUrl, setGitUrl] = useState('');
const [showDiscoverDialog, setShowDiscoverDialog] = useState(false);
const handleAddPlugin = async () => {
if (!gitUrl.trim()) return;
@@ -79,14 +79,22 @@ 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">
<Puzzle className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('plugins')}</h3>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Puzzle className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('plugins')}</h3>
</div>
<Button
variant="outline"
size="sm"
onClick={() => setShowDiscoverDialog(true)}
className="gap-2"
>
<Compass className="h-4 w-4" />
{t('discoverPlugins')}
</Button>
</div>
<p className="text-sm text-muted-foreground">
{t('pluginsDescription')}
@@ -94,7 +102,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] || [];
@@ -112,17 +120,11 @@ export function PluginsSection() {
/>;
})}
</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 +134,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"
@@ -169,6 +173,12 @@ export function PluginsSection() {
</AccordionContent>
</AccordionItem>
</Accordion>
{/* Discover Plugins Dialog */}
<DiscoverPluginsDialog
open={showDiscoverDialog}
onOpenChange={setShowDiscoverDialog}
/>
</div>
);
}
@@ -191,7 +201,7 @@ function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, o
<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">
@@ -224,14 +234,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 && (
+75 -56
View File
@@ -7,17 +7,6 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -29,15 +18,21 @@ import { useNavigate } from 'react-router-dom';
import {
Calendar,
Folder,
Download,
Loader2,
Trash2,
Save,
DollarSign,
ExternalLink,
FileCode,
Download,
Trash2,
} from 'lucide-react';
import JSZip from 'jszip';
import { Skeleton } from './ui/skeleton';
import { Separator } from './ui/separator';
import { DotAI } from '@/lib/DotAI';
import { LabelSelector } from '@/components/labels/LabelSelector';
import { DeleteProjectDialog } from '@/components/DeleteProjectDialog';
import { cn } from '@/lib/utils';
import JSZip from 'jszip';
interface ProjectDetailsDialogProps {
project: Project;
@@ -47,11 +42,13 @@ interface ProjectDetailsDialogProps {
}
export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectDetailsDialogProps) {
const [isRenaming, setIsRenaming] = useState(false);
const [isExporting, setIsExporting] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isRenaming, setIsRenaming] = useState(false);
const [newProjectName, setNewProjectName] = useState(project.id);
const [totalCost, setTotalCost] = useState<number | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const { toast } = useToast();
const { fs } = useFS();
const { projectsPath } = useFSPaths();
@@ -65,21 +62,31 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
setIsRenaming(false);
}, [project.id]);
// Load total project cost
// Load total project cost and template info
useEffect(() => {
const loadCost = async () => {
const loadProjectData = async () => {
setIsLoading(true);
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 cost:', error);
console.warn('Failed to load project data:', error);
setTotalCost(null);
setTemplateInfo(null);
} finally {
setIsLoading(false);
}
};
if (open) {
loadCost();
loadProjectData();
}
}, [fs, projectsPath, project.id, open]);
@@ -234,7 +241,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Folder className="h-5 w-5" />
<Folder className="h-5 w-5 text-primary" />
{project.name}
</DialogTitle>
</DialogHeader>
@@ -248,13 +255,44 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
</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>
)}
<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>
{typeof totalCost === 'number' ? (
<span className="font-mono">${totalCost.toFixed(2)}</span>
) : (
isLoading ? (
<Skeleton className="h-4 w-16" />
) : (
<span>N/A</span>
)
)}
</div>
{/* Template Info */}
<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={cn("flex items-center gap-1", { "text-primary hover:underline": !!templateInfo })}
>
{templateInfo ? (
<>
<span>{templateInfo.name}</span>
<ExternalLink className="h-3 w-3" />
</>
) : (
isLoading ? (
<Skeleton className="h-4 w-24" />
) : (
<span>N/A</span>
)
)}
</a>
</div>
{/* Project Name */}
<div className="space-y-2">
@@ -290,6 +328,9 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
</div>
</div>
{/* Labels */}
<LabelSelector projectId={project.id} />
<Separator />
{/* Export Project Button */}
@@ -308,8 +349,11 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
</Button>
{/* Delete Project Button */}
<AlertDialog>
<AlertDialogTrigger asChild>
<DeleteProjectDialog
projectName={project.name}
onDelete={handleDeleteProject}
isDeleting={isDeleting}
trigger={
<Button
variant="destructive"
className="w-full gap-2"
@@ -318,33 +362,8 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
<Trash2 className="h-4 w-4" />
Delete Project
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Project</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{project.name}"? This action cannot be undone and will permanently delete all project data including files.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteProject}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Deleting...
</>
) : (
'Delete Project'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
}
/>
</div>
</DialogContent>
</Dialog>
+307 -13
View File
@@ -1,27 +1,40 @@
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, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders, Compass } 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 { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useLabels } from '@/hooks/useLabels';
import { getLabelColor } from '@/lib/labels';
import { useProjectLabels } from '@/hooks/useProjectLabels';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { LabelsManageDialog } from '@/components/labels/LabelsManageDialog';
interface ProjectItemProps {
project: Project;
isSelected: boolean;
onSelect: (project: Project) => void;
isFavorite?: boolean;
labelColor?: string;
}
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
const ProjectItem: React.FC<ProjectItemProps> = ({
project,
isSelected,
onSelect,
isFavorite,
labelColor,
}) => {
const navigate = useNavigate();
const { hasRunningSessions } = useProjectSessionStatus(project.id);
@@ -30,6 +43,15 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
navigate(`/project/${project.id}`);
};
// Determine folder icon color - always show colored icons when label exists
const getFolderColorClass = () => {
if (labelColor) {
const colorConfig = getLabelColor(labelColor as Parameters<typeof getLabelColor>[0]);
return colorConfig.text;
}
return 'text-primary';
};
return (
<div
className={cn(
@@ -47,7 +69,7 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
{hasRunningSessions ? (
<Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" />
) : (
<Folder className="h-4 w-4 text-primary" />
<Folder className={cn("h-4 w-4", getFolderColorClass())} />
)}
</div>
<div className="flex justify-between gap-2 flex-1 min-w-0">
@@ -59,10 +81,8 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
{/* Star indicator - only shown when favorited */}
{isFavorite && (
<div className="flex-shrink-0 relative -mr-1 pointer-events-none">
<div className="flex items-center justify-center">
<Star className="h-4 w-4 text-yellow-500 fill-current" />
</div>
<div className="flex-shrink-0 relative -mr-1 pointer-events-none flex items-center justify-center">
<Star className="h-4 w-4 text-yellow-500 fill-current" />
</div>
)}
</div>
@@ -74,6 +94,78 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
ProjectItem.displayName = 'ProjectItem';
/** Label group header component */
interface LabelGroupHeaderProps {
labelName: string;
labelColor: string;
isCollapsed: boolean;
onToggle: () => void;
projectCount?: number;
}
const LabelGroupHeader: React.FC<LabelGroupHeaderProps> = ({
labelName,
labelColor,
isCollapsed,
onToggle,
projectCount = 0,
}) => {
const colorConfig = getLabelColor(labelColor as Parameters<typeof getLabelColor>[0]);
return (
<button
onClick={onToggle}
className="w-full flex items-center gap-2 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
>
<Tag className={cn("h-3.5 w-3.5", colorConfig.text)} />
<span className="flex-1 text-left truncate">{labelName}</span>
{isCollapsed && projectCount > 0 && (
<span className="text-xs text-muted-foreground/70">
{projectCount}
</span>
)}
<ChevronRight className={cn(
"h-3.5 w-3.5 transition-transform duration-200",
!isCollapsed && "rotate-90"
)} />
</button>
);
};
/** Other projects group header component */
interface OtherProjectsGroupHeaderProps {
isCollapsed: boolean;
onToggle: () => void;
projectCount?: number;
}
const OtherProjectsGroupHeader: React.FC<OtherProjectsGroupHeaderProps> = ({
isCollapsed,
onToggle,
projectCount = 0,
}) => {
const { t } = useTranslation();
return (
<button
onClick={onToggle}
className="w-full flex items-center gap-2 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
>
<Folders className="h-3.5 w-3.5 text-primary" />
<span className="flex-1 text-left truncate">{t('otherProjects')}</span>
{isCollapsed && projectCount > 0 && (
<span className="text-xs text-muted-foreground/70">
{projectCount}
</span>
)}
<ChevronRight className={cn(
"h-3.5 w-3.5 transition-transform duration-200",
!isCollapsed && "rotate-90"
)} />
</button>
);
};
interface ProjectSidebarProps {
selectedProject: Project | null;
onSelectProject: (project: Project | null) => void;
@@ -93,10 +185,94 @@ export function ProjectSidebar({
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const [searchQuery, setSearchQuery] = useState('');
const [otherProjectsCollapsed, setOtherProjectsCollapsed] = useLocalStorage<boolean>('other-projects-collapsed', false);
const [labelsDialogOpen, setLabelsDialogOpen] = useState(false);
const { labels, toggleLabelCollapsed } = useLabels();
const { getProjectLabels, hasAnyLabels } = useProjectLabels();
const isMobile = useIsMobile();
const navigate = useNavigate();
// Always show grouped view when labels exist and projects have labels
const showGroupedView = labels.length > 0 && hasAnyLabels();
// 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]);
// Group projects by label for grouped view
const groupedProjects = useMemo(() => {
if (!showGroupedView) return null;
const groups: Map<string, Project[]> = new Map();
const unlabeled: Project[] = [];
// Initialize groups for each label in order
for (const label of labels) {
groups.set(label.id, []);
}
// Sort projects into groups
for (const project of filteredProjects) {
const projectLabelIds = getProjectLabels(project.id);
if (projectLabelIds.length === 0) {
unlabeled.push(project);
} else {
// Add project to each label group it belongs to
let addedToAnyGroup = false;
for (const labelId of projectLabelIds) {
const group = groups.get(labelId);
if (group) {
group.push(project);
addedToAnyGroup = true;
}
}
// If all labels were deleted, add to unlabeled
if (!addedToAnyGroup) {
unlabeled.push(project);
}
}
}
// Sort each group: favorites first, then by lastModified
const sortGroup = (projectList: Project[]) => {
return projectList.sort((a, b) => {
const aIsFavorite = favorites.includes(a.id);
const bIsFavorite = favorites.includes(b.id);
if (aIsFavorite && !bIsFavorite) return -1;
if (!aIsFavorite && bIsFavorite) return 1;
return b.lastModified.getTime() - a.lastModified.getTime();
});
};
for (const [labelId, projectList] of groups) {
groups.set(labelId, sortGroup(projectList));
}
return {
groups,
unlabeled: sortGroup(unlabeled),
};
}, [showGroupedView, labels, filteredProjects, getProjectLabels, favorites]);
// Get the first label color for a project (for colored icon display)
const getProjectLabelColor = (projectId: string): string | undefined => {
const projectLabelIds = getProjectLabels(projectId);
if (projectLabelIds.length === 0) return undefined;
const label = labels.find(l => l.id === projectLabelIds[0]);
return label?.color;
};
// Custom navigate function that closes sidebar on mobile
const navigateAndClose = (path: string) => {
navigate(path);
@@ -166,12 +342,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 +355,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>
@@ -191,10 +367,38 @@ export function ProjectSidebar({
<GitBranch className="h-4 w-4" />
{t('importRepository')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => navigateAndClose('/explore')}
className="flex items-center gap-2 w-full"
>
<Compass className="h-4 w-4" />
{t('exploreApps')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setLabelsDialogOpen(true)}
className="flex items-center gap-2 w-full"
>
<Tag className="h-4 w-4" />
{t('manageLabels')}
</DropdownMenuItem>
</DropdownMenuContent>
</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,15 +418,99 @@ 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>
) : showGroupedView && groupedProjects ? (
// Grouped view by labels
<div className="space-y-1">
{projects.map((project) => (
{/* Render each label group */}
{labels.map((label) => {
const groupProjects = groupedProjects.groups.get(label.id) || [];
if (groupProjects.length === 0) return null;
return (
<Collapsible
key={label.id}
open={!label.collapsed}
onOpenChange={() => toggleLabelCollapsed(label.id)}
>
<CollapsibleTrigger asChild>
<div>
<LabelGroupHeader
labelName={label.name}
labelColor={label.color}
isCollapsed={!!label.collapsed}
onToggle={() => toggleLabelCollapsed(label.id)}
projectCount={groupProjects.length}
/>
</div>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="space-y-0.5">
{groupProjects.map((project) => (
<ProjectItem
key={project.id}
project={project}
isSelected={selectedProject?.id === project.id}
onSelect={onSelectProject}
isFavorite={favorites.includes(project.id)}
labelColor={label.color}
/>
))}
</div>
</CollapsibleContent>
</Collapsible>
);
})}
{/* Other projects (unlabeled) */}
{groupedProjects.unlabeled.length > 0 && (
<div className="mt-2">
<Collapsible
open={!otherProjectsCollapsed}
onOpenChange={() => setOtherProjectsCollapsed(!otherProjectsCollapsed)}
>
<CollapsibleTrigger asChild>
<div>
<OtherProjectsGroupHeader
isCollapsed={otherProjectsCollapsed}
onToggle={() => setOtherProjectsCollapsed(!otherProjectsCollapsed)}
projectCount={groupedProjects.unlabeled.length}
/>
</div>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="space-y-0.5">
{groupedProjects.unlabeled.map((project) => (
<ProjectItem
key={project.id}
project={project}
isSelected={selectedProject?.id === project.id}
onSelect={onSelectProject}
isFavorite={favorites.includes(project.id)}
/>
))}
</div>
</CollapsibleContent>
</Collapsible>
</div>
)}
</div>
) : (
// Flat view (default)
<div className="space-y-1">
{filteredProjects.map((project) => (
<ProjectItem
key={project.id}
project={project}
isSelected={selectedProject?.id === project.id}
onSelect={onSelectProject}
isFavorite={favorites.includes(project.id)}
labelColor={getProjectLabelColor(project.id)}
/>
))}
</div>
@@ -253,6 +541,12 @@ export function ProjectSidebar({
</Button>
</div>
</div>
{/* Labels Management Dialog */}
<LabelsManageDialog
open={labelsDialogOpen}
onOpenChange={setLabelsDialogOpen}
/>
</div>
);
}
+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>
);
}
+141
View File
@@ -0,0 +1,141 @@
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
MessageSquarePlus,
History,
Folder,
Copy,
ChevronDown,
Trash2,
Star,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useQueryClient } from '@tanstack/react-query';
interface ProjectTitleMenuProps {
projectId: string;
projectName: string;
onNewChat: () => void;
onGitHistory: () => void;
onDuplicate: () => void;
onDelete: () => void;
onProjectDetails: () => void;
isAILoading: boolean;
isAnyLoading: boolean;
className?: string;
}
export function ProjectTitleMenu({
projectId,
projectName,
onNewChat,
onGitHistory,
onDuplicate,
onDelete,
onProjectDetails,
isAILoading,
isAnyLoading,
className = '',
}: ProjectTitleMenuProps) {
const { t } = useTranslation();
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
const queryClient = useQueryClient();
const isFavorite = favorites.includes(projectId);
const handleToggleFavorite = (e: React.MouseEvent) => {
e.preventDefault(); // Prevent menu from closing
e.stopPropagation();
const newFavorites = isFavorite
? favorites.filter(id => id !== projectId)
: [...favorites, projectId];
setFavorites(newFavorites);
// Invalidate the projects query to trigger a refetch with new sorting
queryClient.invalidateQueries({ queryKey: ['projects'] });
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className={cn("p-0 h-auto font-semibold truncate hover:bg-transparent hover:text-muted-foreground flex items-center gap-1", className)}
>
<span className="truncate">{projectName}</span>
<ChevronDown className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-48">
<DropdownMenuItem
onClick={handleToggleFavorite}
disabled={isAnyLoading}
className="gap-2"
onSelect={(e) => e.preventDefault()} // Prevent menu from closing
>
<Star
className={cn(
"h-4 w-4",
{ "text-yellow-500 fill-current": isFavorite },
)}
/>
{isFavorite ? 'Unfavorite' : 'Favorite'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
className="gap-2"
>
<Folder className="h-4 w-4" />
Project Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={onGitHistory}
disabled={isAnyLoading}
className="gap-2"
>
<History className="h-4 w-4" />
Rollback
</DropdownMenuItem>
<DropdownMenuItem
onClick={onNewChat}
disabled={isAILoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
New Chat
</DropdownMenuItem>
<DropdownMenuItem
onClick={onDuplicate}
disabled={isAnyLoading}
className="gap-2"
>
<Copy className="h-4 w-4" />
{t('duplicateProject')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={onDelete}
disabled={isAnyLoading}
className="gap-2 text-destructive focus:text-destructive"
>
<Trash2 className="h-4 w-4" />
Delete Project
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
+300
View File
@@ -0,0 +1,300 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Trash2, Rocket } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { PresetDeployProvider } from '@/lib/deploy/types';
import { ExternalFavicon } from '@/components/ExternalFavicon';
interface ProviderConfigDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
provider: DeployProvider;
preset?: PresetDeployProvider;
onUpdate: (provider: DeployProvider) => void;
onRemove: () => void;
}
/**
* Normalize a URL string to ensure it has a protocol
* @param url - The URL string to normalize
* @returns A fully-qualified URL string
*/
function normalizeUrl(url: string): string {
// If it already has a protocol, return as-is
if (/^https?:\/\//i.test(url)) {
return url;
}
// Add https:// prefix
return `https://${url}`;
}
export function ProviderConfigDialog({
open,
onOpenChange,
provider,
preset,
onUpdate,
onRemove,
}: ProviderConfigDialogProps) {
const { t } = useTranslation();
const [localProvider, setLocalProvider] = useState(provider);
// Reset local state when provider changes or dialog opens
useEffect(() => {
if (open) {
setLocalProvider(provider);
}
}, [provider, open]);
const handleSave = () => {
onUpdate(localProvider);
onOpenChange(false);
};
const handleDelete = () => {
onRemove();
onOpenChange(false);
};
// Use baseURL from configured provider, falling back to preset baseURL
const baseURL = ('baseURL' in localProvider && localProvider.baseURL) || preset?.baseURL;
// For Shakespeare, special handling for host field
const shakespeareUrl = localProvider.type === 'shakespeare' && 'host' in localProvider && localProvider.host
? normalizeUrl(localProvider.host)
: undefined;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<div className="flex items-center gap-2">
<ExternalFavicon
url={shakespeareUrl || baseURL}
size={20}
fallback={<Rocket size={20} />}
/>
<DialogTitle>{localProvider.name}</DialogTitle>
</div>
<DialogDescription>
{preset?.description || 'Configure your deployment provider'}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="grid gap-2">
<Label htmlFor="provider-name">
Name <span className="text-destructive">*</span>
</Label>
<Input
id="provider-name"
placeholder="Provider name"
value={localProvider.name}
onChange={(e) => setLocalProvider({ ...localProvider, name: e.target.value })}
/>
</div>
{localProvider.type === 'shakespeare' ? (
<>
<p className="text-sm text-muted-foreground">
{t('shakespeareDeployNostrAuth')}
</p>
<div className="grid gap-2">
<Label htmlFor="provider-host">
Host (Optional)
</Label>
<Input
id="provider-host"
placeholder="shakespeare.wtf"
value={localProvider.host || ''}
onChange={(e) => setLocalProvider({ ...localProvider, host: e.target.value })}
/>
</div>
</>
) : localProvider.type === 'nsite' ? (
<>
<div className="grid gap-2">
<Label htmlFor="provider-gateway">
Gateway <span className="text-destructive">*</span>
</Label>
<Input
id="provider-gateway"
placeholder="nsite.lol"
value={localProvider.gateway || ''}
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="provider-relays">
Relay URLs (comma-separated) <span className="text-destructive">*</span>
</Label>
<Input
id="provider-relays"
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
value={localProvider.relayUrls?.join(', ') || ''}
onChange={(e) => setLocalProvider({
...localProvider,
relayUrls: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
})}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="provider-blossom">
Blossom Servers (comma-separated) <span className="text-destructive">*</span>
</Label>
<Input
id="provider-blossom"
placeholder="https://blossom.primal.net/"
value={localProvider.blossomServers?.join(', ') || ''}
onChange={(e) => setLocalProvider({
...localProvider,
blossomServers: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
})}
/>
</div>
</>
) : (
<>
{localProvider.type === 'cloudflare' && (
<div className="grid gap-2">
<Label htmlFor="provider-accountId">
{preset?.accountIdLabel || 'Account ID'} <span className="text-destructive">*</span>
</Label>
<Input
id="provider-accountId"
placeholder="Enter Account ID"
value={localProvider.accountId}
onChange={(e) => setLocalProvider({ ...localProvider, accountId: e.target.value })}
/>
</div>
)}
{localProvider.type === 'deno' && (
<div className="grid gap-2">
<Label htmlFor="provider-organizationId">
{preset?.organizationIdLabel || 'Organization ID'} <span className="text-destructive">*</span>
</Label>
<Input
id="provider-organizationId"
placeholder="Enter Organization ID"
value={localProvider.organizationId}
onChange={(e) => setLocalProvider({ ...localProvider, organizationId: e.target.value })}
/>
</div>
)}
<div className="grid gap-2">
<Label htmlFor="provider-apiKey">
{preset?.apiKeyLabel || t('apiKey')} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="provider-apiKey"
placeholder={t('enterApiKey')}
value={localProvider.apiKey}
onChange={(e) => {
if (localProvider.type === 'netlify') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'vercel') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'cloudflare') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
}
}}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="provider-baseURL">
Base URL (Optional)
</Label>
<Input
id="provider-baseURL"
placeholder={
localProvider.type === 'netlify' ? 'https://api.netlify.com/api/v1' :
localProvider.type === 'vercel' ? 'https://api.vercel.com' :
localProvider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
localProvider.type === 'deno' ? 'https://api.deno.com/v1' :
'Base URL'
}
value={localProvider.baseURL || ''}
onChange={(e) => {
if (localProvider.type === 'netlify') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'vercel') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'cloudflare') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
}
}}
/>
</div>
{(localProvider.type === 'cloudflare' || localProvider.type === 'deno') && (
<div className="grid gap-2">
<Label htmlFor="provider-baseDomain">
Base Domain (Optional)
</Label>
<Input
id="provider-baseDomain"
placeholder={localProvider.type === 'cloudflare' ? 'workers.dev' : 'deno.dev'}
value={localProvider.baseDomain || ''}
onChange={(e) => setLocalProvider({ ...localProvider, baseDomain: e.target.value })}
/>
<p className="text-xs text-muted-foreground">
{localProvider.type === 'cloudflare'
? 'The domain suffix for deployed workers (e.g., workers.dev)'
: 'The domain suffix for deployed projects (e.g., deno.dev)'}
</p>
</div>
)}
<div className="flex items-center space-x-2">
<Checkbox
id="provider-proxy"
checked={localProvider.proxy || false}
onCheckedChange={(checked) => setLocalProvider({ ...localProvider, proxy: checked === true })}
/>
<Label
htmlFor="provider-proxy"
className="text-sm font-normal cursor-pointer"
>
Use CORS Proxy
</Label>
</div>
</>
)}
</div>
<DialogFooter className="gap-2">
<Button
variant="destructive"
onClick={handleDelete}
className="sm:mr-auto"
>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</Button>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
</Button>
<Button onClick={handleSave}>
{t('save')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { Bot } from 'lucide-react';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { ReactNode } from 'react';
interface ProviderTileProps {
icon?: ReactNode;
iconUrl?: string | null;
name: string;
onClick: () => void;
badge?: ReactNode;
}
export function ProviderTile({ icon, iconUrl, name, onClick, badge }: ProviderTileProps) {
return (
<button
onClick={onClick}
className="flex flex-col items-center justify-center gap-2 p-4 rounded-lg border bg-card hover:bg-muted transition-colors text-center h-[120px] relative"
>
{iconUrl ? (
<ExternalFavicon
url={iconUrl}
size={32}
fallback={icon || <Bot size={32} />}
/>
) : (
icon || <Bot size={32} />
)}
<span className="text-sm font-medium line-clamp-2 overflow-hidden max-w-full text-ellipsis">
{name}
</span>
{badge && (
<div className="absolute top-0 right-0">
{badge}
</div>
)}
</button>
);
}
+3 -3
View File
@@ -23,9 +23,9 @@ vi.mock('react-router-dom', () => ({
useNavigate: () => vi.fn()
}));
// Mock CreditsDialog to avoid NostrProvider dependency
vi.mock('./CreditsDialog', () => ({
CreditsDialog: () => null
// Mock AIProviderConfigDialog to avoid NostrProvider dependency
vi.mock('./AIProviderConfigDialog', () => ({
AIProviderConfigDialog: () => null
}));
describe('Quilly', () => {
+29 -10
View File
@@ -1,4 +1,4 @@
import { APIError } from 'openai';
import { APIConnectionError, APIError } from 'openai';
import { useNavigate } from 'react-router-dom';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -6,12 +6,13 @@ import { QuillySVG } from '@/components/ui/QuillySVG';
import { useAISettings } from '@/hooks/useAISettings';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { useAICredits } from '@/hooks/useAICredits';
import { CreditsDialog } from './CreditsDialog';
import { AIProviderConfigDialog } from './AIProviderConfigDialog';
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';
import { useOffline } from '@/hooks/useOffline';
export interface QuillyProps {
error: Error;
@@ -43,6 +44,7 @@ interface QuillyContentProps {
function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, provider }: QuillyContentProps) {
const navigate = useNavigate();
const { isOffline } = useOffline();
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
// Handle Project Preview Console Errors
@@ -183,21 +185,36 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
actions: [],
};
default:
return {
message: `AI service error: ${error.message}`,
actions: [],
};
}
}
if (error instanceof APIConnectionError) {
return {
message: isOffline
? 'It appears you are offline. Have you tried connecting to the internet?'
: 'There was a network problem between your device and the AI service.',
actions: onTryAgain ? [{
label: 'Try again',
onClick: () => {
onTryAgain();
onDismiss();
},
}] : [],
};
}
// Default fallback
return {
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();
},
}] : [],
};
};
@@ -262,10 +279,12 @@ function QuillyCreditsButton({ provider }: QuillyCreditsButtonProps) {
<button className="text-primary underline" onClick={() => setShowCreditsDialog(true)}>
{credits.data ? `Add credits (${credits.data.amount.toFixed(2)} remaining)` : 'Add credits'}
</button>
<CreditsDialog
<AIProviderConfigDialog
open={showCreditsDialog}
onOpenChange={setShowCreditsDialog}
provider={provider}
onUpdate={() => {}}
onRemove={() => {}}
/>
</>
);
+1 -1
View File
@@ -273,7 +273,7 @@ export function RelayListManager() {
className="h-10 shrink-0"
>
<Plus className="h-4 w-4 mr-2" />
{t('addRelay')}
{t('add')}
</Button>
</div>
+365
View File
@@ -0,0 +1,365 @@
import React, { useState, useRef, useEffect, memo } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitBranch, Loader2, EllipsisVertical, Edit, Code, ExternalLink } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
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 { NostrURI } from '@/lib/NostrURI';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import { useTranslation } from 'react-i18next';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useGitSettings } from '@/hooks/useGitSettings';
import { detectFork } from '@/lib/detectFork';
import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog';
import { useQueryClient } from '@tanstack/react-query';
import { useOGImage } from '@/hooks/useOGImage';
import { ZapDialog } from '@/components/ZapDialog';
import { Zap } from 'lucide-react';
import type { Event } from 'nostr-tools';
import type { NostrMetadata } from '@nostrify/nostrify';
import { formatRelativeTime } from '@/lib/utils';
interface RepositoryCardProps {
repo: Repository;
/** Pre-fetched author metadata to avoid individual fetches */
authorMetadata?: NostrMetadata;
/** Callback when a tag is clicked - receives the tag value */
onTagClick?: (tag: string) => void;
}
function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagClick }: RepositoryCardProps) {
// Only fetch author data if not preloaded
const { data: authorData } = useAuthor(preloadedMetadata ? undefined : repo.pubkey);
const metadata = preloadedMetadata ?? authorData?.metadata;
const { user } = useCurrentUser();
const { settings: gitSettings } = useGitSettings();
const navigate = useNavigate();
const projectsManager = useProjectsManager();
const { toast } = useToast();
const { t } = useTranslation();
const queryClient = useQueryClient();
const [isCloning, setIsCloning] = useState(false);
const [editRepoOpen, setEditRepoOpen] = useState(false);
const [imageError, setImageError] = useState(false);
const [eventViewerOpen, setEventViewerOpen] = useState(false);
const [isInViewport, setIsInViewport] = useState(false);
const cardRef = useRef<HTMLDivElement>(null);
// Lazy load OG images - only fetch when card is in viewport
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsInViewport(true);
observer.disconnect();
}
},
{ rootMargin: '100px' } // Start loading slightly before visible
);
if (cardRef.current) {
observer.observe(cardRef.current);
}
return () => observer.disconnect();
}, []);
const displayName = metadata?.name || genUserName(repo.pubkey);
const profileImage = metadata?.picture;
const isOwnRepo = user?.pubkey === repo.pubkey;
const hasLightning = !!(metadata?.lud16 || metadata?.lud06);
const canZap = user && !isOwnRepo && hasLightning;
// Get OG metadata from first web URL - only when in viewport
const firstWebUrl = repo.webUrls?.[0];
const { data: ogMetadata } = useOGImage(isInViewport ? firstWebUrl : undefined);
const ogImageUrl = ogMetadata?.image ?? null;
const ogDescription = ogMetadata?.description ?? null;
// Construct Nostr clone URL
const nostrURI = new NostrURI({
pubkey: repo.pubkey,
identifier: repo.repoId,
relay: repo.relays[0],
});
const handleClone = async (e: React.MouseEvent) => {
// Prevent card click from triggering
e.stopPropagation();
setIsCloning(true);
try {
await projectsManager.init();
// Determine if this is a fork
const repoUrl = nostrURI.toString();
const fork = await detectFork(repoUrl, user?.pubkey, gitSettings.credentials);
// Clone the repository using the Nostr URI
const project = await projectsManager.cloneProject({
name: repo.name,
repoUrl,
fork,
});
toast({
title: t('nostrRepositoryImportedSuccessfully'),
description: t('repositoryClonedFromNostr', { repoName: repo.name }),
});
// Navigate to the new project with build parameter
navigate(`/project/${project.id}?build`);
} catch (error) {
console.error('Failed to clone repository:', error);
let errorMessage = t('failedToImportRepository');
if (error instanceof Error) {
if (error.message.includes('Repository not found on Nostr network')) {
errorMessage = t('repositoryNotFoundOnNostr');
} else if (error.message.includes('No clone URLs found')) {
errorMessage = t('noCloneUrlsFound');
} else if (error.message.includes('All clone attempts failed')) {
errorMessage = t('allCloneAttemptsFailed');
} else {
errorMessage = error.message;
}
}
toast({
title: t('failedToImportRepository'),
description: errorMessage,
variant: "destructive",
});
} finally {
setIsCloning(false);
}
};
const handleRepoEditSuccess = () => {
// Refresh repositories list after successful edit
queryClient.invalidateQueries({ queryKey: ['nostr', 'user-repositories', user?.pubkey] });
};
// Check if we have a valid OG image to show
const hasValidImage = ogImageUrl && !imageError;
return (
<Card ref={cardRef} className="h-full flex flex-col hover:shadow-lg transition-shadow">
{/* Preview Image or Placeholder */}
{hasValidImage && firstWebUrl ? (
<a
href={firstWebUrl}
target="_blank"
rel="noopener noreferrer"
className="block aspect-video bg-muted overflow-hidden rounded-t-lg cursor-pointer hover:opacity-90 transition-opacity"
>
<img
src={ogImageUrl}
alt={`${repo.name} preview`}
className="w-full h-full object-cover"
onError={() => setImageError(true)}
/>
</a>
) : (
<div className="aspect-video bg-gradient-to-br from-primary to-accent rounded-t-lg flex items-center justify-center">
<Code className="h-12 w-12 text-white" />
</div>
)}
<CardContent className="p-6 flex flex-col flex-1">
{/* Header with name and menu */}
<div className="mb-4 flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-end gap-2 mb-2">
<h3 className="font-semibold text-lg leading-tight truncate">
{repo.name}
</h3>
<span className="text-sm text-muted-foreground shrink-0">
{formatRelativeTime(repo.created_at)}
</span>
</div>
</div>
<div className="flex items-center -mt-1 -mr-2 shrink-0">
{canZap && (
<ZapDialog target={repo as unknown as Event}>
<Button variant="ghost" size="icon" className="h-8 w-8 text-amber-500 hover:text-amber-600 hover:bg-amber-500/10">
<Zap className="h-4 w-4" />
</Button>
</ZapDialog>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{firstWebUrl && (
<DropdownMenuItem asChild className="gap-2">
<a href={firstWebUrl} target="_blank" rel="noopener noreferrer">
<ExternalLink className="h-4 w-4" />
Open Website
</a>
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => setEventViewerOpen(true)} className="gap-2">
<Code className="h-4 w-4" />
View Event
</DropdownMenuItem>
{isOwnRepo && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
<Edit className="h-4 w-4" />
Edit Repository
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Author */}
<div className="mb-4">
<div className="flex items-center gap-3 text-sm">
<Avatar className="h-10 w-10">
{profileImage && (
<AvatarImage src={profileImage} alt={displayName} />
)}
<AvatarFallback className="text-xs">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex items-center gap-2 min-w-0 flex-1">
<button
onClick={(e) => {
e.stopPropagation();
onTagClick?.(displayName);
}}
className="truncate font-medium text-base text-foreground hover:text-primary hover:underline transition-colors text-left"
>
{displayName}
</button>
{metadata?.nip05 && (
<span className="text-sm text-muted-foreground shrink-0">{metadata.nip05}</span>
)}
</div>
</div>
</div>
{/* Description */}
{(repo.description || ogDescription) && (
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
{repo.description || ogDescription}
</p>
)}
{/* Tags */}
{repo.repoTags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-4">
{repo.repoTags.slice(0, 3).map((tag, index) => (
<button
key={index}
onClick={(e) => {
e.stopPropagation();
onTagClick?.(tag);
}}
className="text-sm text-primary hover:text-primary/80 hover:underline transition-colors font-medium"
>
#{tag}
</button>
))}
{repo.repoTags.length > 3 && (
<span className="text-sm text-muted-foreground">
+{repo.repoTags.length - 3}
</span>
)}
</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}
disabled={isCloning}
>
{isCloning ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Cloning...
</>
) : (
<>
<GitBranch className="h-4 w-4 mr-2" />
Clone
</>
)}
</Button>
</div>
</CardContent>
<NostrRepoEditDialog
open={editRepoOpen}
onOpenChange={setEditRepoOpen}
repoIdentifier={repo.repoId}
onSuccess={handleRepoEditSuccess}
/>
{/* Event Viewer Dialog */}
<Dialog open={eventViewerOpen} onOpenChange={setEventViewerOpen}>
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle>Repository Event</DialogTitle>
</DialogHeader>
<div className="overflow-y-auto flex-1 min-h-0">
<pre className="text-xs p-4 rounded-lg overflow-x-auto">
{JSON.stringify({
id: repo.id,
pubkey: repo.pubkey,
created_at: repo.created_at,
kind: repo.kind,
tags: repo.tags,
content: repo.content,
sig: repo.sig,
}, null, 2)}
</pre>
</div>
</DialogContent>
</Dialog>
</Card>
);
}
// Memoize to prevent re-renders when parent re-renders with same props
export const RepositoryCard = memo(RepositoryCardInner);
+28 -8
View File
@@ -27,14 +27,19 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://test.git',
graspMetadata: {
relays: [],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://favicon.test/{href}',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
ngitServers: [],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -64,14 +69,19 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://test.git',
graspMetadata: {
relays: [],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://favicon.test/{href}',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
ngitServers: [],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -102,14 +112,19 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://test.git',
graspMetadata: {
relays: [],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://favicon.test/{href}',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
ngitServers: [],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -143,14 +158,19 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://test.git',
graspMetadata: {
relays: [],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://favicon.test/{href}',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
ngitServers: [],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
+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>
+79
View File
@@ -0,0 +1,79 @@
import { ArrowLeft, type LucideIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useNavigate } from 'react-router-dom';
import type { ReactNode } from 'react';
import { cn } from '@/lib/utils';
interface SettingsPageLayoutProps {
/** The icon component to display next to the title */
icon: LucideIcon;
/** Translation key for the page title */
titleKey: string;
/** Translation key for the page description */
descriptionKey: string;
/** The main content of the settings page */
children: ReactNode;
/** Optional className for the content container */
className?: string;
}
/**
* Shared layout component for all settings pages.
* Provides consistent header structure with mobile back button, icon, title, and description.
*/
export function SettingsPageLayout({
icon: Icon,
titleKey,
descriptionKey,
children,
className,
}: SettingsPageLayoutProps) {
const { t } = useTranslation();
const isMobile = useIsMobile();
const navigate = useNavigate();
return (
<div className="p-6 space-y-6 pb-16">
{isMobile && (
<div className="space-y-3">
<Button
variant="ghost"
size="sm"
onClick={() => navigate('/settings')}
className="h-8 w-auto px-2 -ml-2"
>
<ArrowLeft className="h-4 w-4 mr-2" />
{t('backToSettings')}
</Button>
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Icon className="h-6 w-6 text-primary" />
{t(titleKey)}
</h1>
<p className="text-muted-foreground">
{t(descriptionKey)}
</p>
</div>
</div>
)}
{!isMobile && (
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Icon className="h-6 w-6 text-primary" />
{t(titleKey)}
</h1>
<p className="text-muted-foreground">
{t(descriptionKey)}
</p>
</div>
)}
<div className={cn('space-y-6 max-w-xl', className)}>
{children}
</div>
</div>
);
}
+7 -34
View File
@@ -11,6 +11,7 @@ import { ModelSelector } from '@/components/ModelSelector';
interface ChatInputProps {
isLoading: boolean;
isConfigured: boolean;
isLoadingSettings: boolean;
providerModel: string;
onProviderModelChange: (model: string) => void;
onSend: (input: string, files: File[]) => void;
@@ -33,6 +34,7 @@ interface ChatInputProps {
export const ChatInput = memo(function ChatInput({
isLoading,
isConfigured,
isLoadingSettings,
providerModel,
onProviderModelChange,
onSend,
@@ -83,35 +85,6 @@ export const ChatInput = memo(function ChatInput({
}
}, [handleSend]);
const handlePaste = useCallback(async (e: React.ClipboardEvent) => {
const items = e.clipboardData?.items;
if (!items) return;
for (let i = 0; i < items.length; i++) {
const item = items[i];
// Check if the item is an image
if (item.type.startsWith('image/')) {
e.preventDefault(); // Prevent default paste behavior for images
const file = item.getAsFile();
if (file) {
// Generate a filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const extension = file.type.split('/')[1] || 'png';
const filename = `pasted-image-${timestamp}.${extension}`;
// Create a new File object with the generated name
const namedFile = new File([file], filename, { type: file.type });
// Add to attached files
setAttachedFiles(prev => [...prev, namedFile]);
}
break; // Only handle the first image found
}
}
}, []);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value);
}, []);
@@ -132,7 +105,7 @@ export const ChatInput = memo(function ChatInput({
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
@@ -142,7 +115,7 @@ export const ChatInput = memo(function ChatInput({
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || (isConfigured && !providerModel.trim())}
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
@@ -163,7 +136,7 @@ export const ChatInput = memo(function ChatInput({
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isLoading}
disabled={isLoadingSettings}
multiple={true}
/>
@@ -212,7 +185,7 @@ export const ChatInput = memo(function ChatInput({
<ModelSelector
value={providerModel}
onChange={onProviderModelChange}
disabled={isLoading}
disabled={isLoadingSettings}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={onModelSelectorOpenChange}
@@ -234,7 +207,7 @@ export const ChatInput = memo(function ChatInput({
<Button
onClick={handleSend}
onMouseDown={onFirstInteraction}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
disabled={isLoadingSettings || (!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
+287 -55
View File
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { Loader2, ChevronDown } from 'lucide-react';
import { ChevronDown, Play } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
@@ -15,7 +15,9 @@ import { useAIChat } from '@/hooks/useAIChat';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useMCPTools } from '@/hooks/useMCPTools';
import { useQueryClient } from '@tanstack/react-query';
import { AIMessageItem } from '@/components/AIMessageItem';
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
@@ -23,7 +25,6 @@ import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
import { BuildProjectTool } from '@/lib/tools/BuildProjectTool';
import { DeployProjectTool } from '@/lib/tools/DeployProjectTool';
import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool';
import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool';
import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool';
@@ -33,9 +34,11 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { NostrPublishEventsTool } from '@/lib/tools/NostrPublishEventsTool';
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 { GenerateImageTool } from '@/lib/tools/GenerateImageTool';
import { ViewAvailableModelsTool } from '@/lib/tools/ViewAvailableModelsTool';
import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerationTool';
import { createMCPTools } from '@/lib/tools/MCPTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
@@ -46,6 +49,9 @@ 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';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { AIMessage } from '@/lib/SessionManager';
// Clean interfaces now handled by proper hooks
@@ -82,20 +88,25 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const { models } = useProviderModels();
const { config } = useAppContext();
const { projectsPath, tmpPath, pluginsPath } = useFSPaths();
const queryClient = useQueryClient();
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
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;
// Determine which error to show - AI errors take priority over console errors
// since they are more immediately relevant to the user's current action
const displayError = aiError || consoleError;
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
const scrollAreaRef = useRef<HTMLDivElement>(null);
const { isConfigured, settings, addRecentlyUsedModel } = useAISettings();
const aiSettings = useAISettings();
const { isConfigured, settings, addRecentlyUsedModel, isLoading: isLoadingSettings } = aiSettings;
const [providerModel, setProviderModel] = useState(() => {
// Initialize with first recently used model if available, otherwise empty
return settings.recentlyUsedModels?.[0] || '';
@@ -150,20 +161,25 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
sessionManager.emit('fileChanged', projectId, filePath);
}, [sessionManager, projectId]);
// Callback to trigger sync after git commits
const handleCommit = useCallback(() => {
// Invalidate the git-sync query to trigger an immediate sync
queryClient.invalidateQueries({ queryKey: ['git-sync', cwd] });
}, [queryClient, cwd]);
// 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),
git_commit: new GitCommitTool(fs, cwd, git, { onCommit: handleCommit }),
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
npm_add_package: new NpmAddPackageTool(fs, cwd),
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
typecheck: new TypecheckTool(fs, cwd),
nostr_read_nip: new NostrReadNipTool(),
nostr_fetch_event: new NostrFetchEventTool(),
nostr_read_kind: new NostrReadKindTool(),
@@ -174,16 +190,59 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_publish_events: new NostrPublishEventsTool(),
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) {
tools.deploy_project = new DeployProjectTool(fs, cwd, user.signer, projectId);
// Add generate_image tool if imageModel is configured
if (settings.imageModel) {
try {
const { provider, model } = parseProviderModel(settings.imageModel, settings.providers);
// Find the model data to determine the generation mode
const providerModel = models.find(m => m.fullId === settings.imageModel);
// Determine mode: 'chat' if model supports image output modality, otherwise 'image'
let mode: 'chat' | 'image' = 'image';
if (providerModel?.type) {
switch (providerModel.type) {
case 'chat':
mode = 'chat';
break;
case 'image':
mode = 'image';
break;
}
} else if (providerModel?.modalities?.includes('image')) {
mode = 'chat';
}
tools.generate_image = new GenerateImageTool(
fs,
tmpPath,
provider,
model,
mode,
user,
config.corsProxy
);
} catch (error) {
console.warn('Failed to parse imageModel:', error);
}
} else {
// If imageModel is not configured, provide tools to help configure it
tools.view_available_models = new ViewAvailableModelsTool(
models,
settings.imageModel
);
tools.configure_image_generation = new ConfigureImageGenerationTool(
aiSettings,
models
);
}
return tools;
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]);
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
// MCP tools wrapped for execution
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
@@ -237,8 +296,10 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
messages,
streamingMessage,
isLoading: internalIsLoading,
isLoadingHistory,
totalCost,
lastInputTokens,
lastFinishReason,
addMessage,
sendMessage,
startGeneration,
@@ -252,6 +313,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();
@@ -272,9 +379,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
]
});
const result = await tool.execute({ filter: 'error' });
await addMessage({
role: 'tool',
content: await tool.execute({ filter: 'error' }),
content: result.content,
tool_call_id: toolCallId,
});
@@ -497,13 +606,158 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}), [internalStartNewSession]);
/** Render streaming message, loading skeleton, or tool loading state */
const renderStreamingMessage = () => {
if (streamingMessage) {
const streamingToolCall = streamingMessage.tool_calls?.[0];
return (
<>
{/* Show streaming message if text is streaming */}
{(streamingMessage.content || streamingMessage.reasoning_content) && (
<AIMessageItem
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
/>
)}
{/* Show tool call in "calling" state if streaming tool call is in progress */}
{(streamingToolCall?.type === 'function') ? (
<ToolCallDisplay
key="tool-calls-loading"
toolName={streamingToolCall.function.name}
toolArgs={(() => {
try {
return JSON.parse(streamingToolCall.function.arguments);
} catch {
return {};
}
})()}
state="calling"
/>
) : (
<>
{/* Show loading skeleton if AI appears stuck generating tools */}
{isStuck && (
<div key="stuck-loading-skeleton" className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm space-y-2">
<Skeleton className="h-4 w-3/4" />
</div>
</div>
</div>
)}
</>
)}
</>
)
}
const lastMessage = messages[messages.length - 1] as AIMessage | undefined;
const lastToolCall = lastMessage?.role === 'assistant' ? lastMessage?.tool_calls?.[0] : undefined;
// Show tool call in "waiting" state if last tool call is still executing
if (lastToolCall?.type === 'function') {
return (
<ToolCallDisplay
key="tool-running-loading"
toolName={lastToolCall.function.name}
toolArgs={(() => {
try {
return JSON.parse(lastToolCall.function.arguments);
} catch {
return {};
}
})()}
state="waiting"
/>
);
}
// Fallback skeleton if AI is loading
if (isLoading) {
return (
<div key="streaming-loading" className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm space-y-2">
<Skeleton className="h-4 w-3/4" />
</div>
</div>
</div>
);
}
};
return (
<div className="h-full flex flex-col relative">
<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>
)}
{/* Loading skeleton while loading history */}
{isLoadingHistory && (
<div className="space-y-6">
{/* User message skeleton */}
<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="space-y-2">
<Skeleton className="h-4 w-64" />
<Skeleton className="h-4 w-48" />
</div>
</div>
</div>
{/* Assistant message skeleton */}
<div className="flex py-6">
<div className="flex-1 min-w-0">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-5/6" />
<Skeleton className="h-4 w-4/5" />
</div>
</div>
</div>
{/* Another user message skeleton */}
<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="space-y-2">
<Skeleton className="h-4 w-56" />
</div>
</div>
</div>
{/* Another assistant message skeleton */}
<div className="flex py-6">
<div className="flex-1 min-w-0">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-11/12" />
</div>
</div>
</div>
</div>
)}
{/* Empty state when no messages and not loading */}
{messages.length === 0 && !streamingMessage && !isLoading && (
{!isLoadingHistory && messages.length === 0 && !streamingMessage && !isLoading && (
<div className="flex-1 flex items-center justify-center min-h-[400px]">
<div className="text-center space-y-4 max-w-md mx-auto">
<div className="mb-6">
@@ -527,7 +781,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
)}
{messages.map((message, index) => {
{!isLoadingHistory && messages.map((message, index) => {
// Find the corresponding tool call for tool messages
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
if (message.role === 'tool') {
@@ -549,45 +803,22 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
/>
);
})}
{streamingMessage && (
streamingMessage.content || streamingMessage.reasoning_content ? (
<>
<AIMessageItem
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
/>
{/* Show loading skeleton if AI appears stuck generating tools */}
{isStuck && (
<div key="stuck-loading-skeleton" className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm space-y-2">
<Skeleton className="h-4 w-3/4" />
</div>
</div>
</div>
)}
</>
) : (
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
<div key="streaming-loading" className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm space-y-2">
<Skeleton className="h-4 w-3/4" />
</div>
</div>
</div>
)
)
)}
{streamingMessage?.tool_calls?.[0]?.type === 'function' && (
<div key="tool-calls-loading" className="-mt-2">
<div className="flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin flex-shrink-0" />
<span className="font-medium">
{t('running')} {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
</span>
</div>
{!isLoadingHistory && renderStreamingMessage()}
{/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */}
{!isLoadingHistory && !isLoading && (!lastFinishReason || (lastFinishReason !== 'stop' && lastFinishReason !== 'length')) && messages.length > 0 && (
<div className="flex justify-center py-4">
<Button
onClick={() => startGeneration(providerModel)}
variant="outline"
size="sm"
disabled={!providerModel.trim() || !isConfigured}
className="gap-2"
>
<Play className="h-4 w-4" />
{t('resume')}
</Button>
</div>
)}
@@ -623,6 +854,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<ChatInput
isLoading={isLoading}
isConfigured={isConfigured}
isLoadingSettings={isLoadingSettings}
providerModel={providerModel}
onProviderModelChange={handleModelChange}
onSend={handleSend}
+142 -187
View File
@@ -10,16 +10,12 @@ import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BranchSwitcher } from '@/components/BranchSwitcher';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { type DeviceMode } from '@/components/ui/device-toggle';
import {
Popover,
PopoverContent,
@@ -28,7 +24,6 @@ import {
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
import { DeployDialog } from '@/components/DeployDialog';
import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
import { useAppContext } from '@/hooks/useAppContext';
@@ -38,8 +33,6 @@ interface PreviewPaneProps {
projectId: string;
activeTab: 'preview' | 'code';
onToggleView?: () => void;
projectName?: string;
onFirstInteraction?: () => void;
isPreviewable?: boolean;
}
@@ -73,7 +66,7 @@ interface JSONRPCResponse {
id: number;
}
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction: _onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable = true }: PreviewPaneProps) {
const { t } = useTranslation();
const { config } = useAppContext();
const { previewDomain } = config;
@@ -88,7 +81,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
const previewContainerRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const { projectsPath } = useFSPaths();
@@ -102,14 +97,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const [searchParams, setSearchParams] = useSearchParams();
const [shouldBuild, setShouldBuild] = useState(false);
const handleBuildProject = useCallback(() => {
buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
});
}, [buildProject]);
// Handle "build" URL parameter on initial load
useEffect(() => {
if (searchParams.has('build')) {
@@ -126,9 +113,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
useEffect(() => {
if (shouldBuild && isPreviewable && !isBuildLoading) {
setShouldBuild(false);
handleBuildProject();
buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
});
}
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
}, [isBuildLoading, isPreviewable, buildProject, shouldBuild]);
const loadFileContent = useCallback(async (filePath: string) => {
// Skip loading media files - they can't be edited as text
@@ -291,33 +282,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
sendNavigationCommand('refresh');
}, [sendNavigationCommand]);
const goBackIframe = useCallback(() => {
if (historyIndex > 0) {
// Move back in history
const newIndex = historyIndex - 1;
const targetPath = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(targetPath);
// Tell iframe to navigate to this path
sendNavigationCommand('navigate', { url: targetPath });
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
const goForwardIframe = useCallback(() => {
if (historyIndex < navigationHistory.length - 1) {
// Move forward in history
const newIndex = historyIndex + 1;
const targetPath = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(targetPath);
// Tell iframe to navigate to this path
sendNavigationCommand('navigate', { url: targetPath });
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
const toggleFullscreen = useCallback(() => {
setIsFullscreen(prev => !prev);
}, []);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
@@ -522,7 +489,11 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
// Automatically trigger a rebuild after saving a file
if (isPreviewable) {
console.log('File saved, triggering rebuild...');
handleBuildProject();
buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
});
}
} catch (error) {
console.error('Failed to save file:', error);
@@ -553,9 +524,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 relative"
className="h-8 gap-2 relative"
>
<Bug className="h-4 w-4" />
<span className="hidden lg:inline">Logs</span>
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
@@ -563,7 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
</PopoverTrigger>
<PopoverContent
align="end"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0 z-[9999]"
sideOffset={4}
>
@@ -628,117 +600,113 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
);
};
const Menu = () => {
const isAnyLoading = isBuildLoading;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
>
<MenuIcon className="h-4 w-4" />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48 sm:w-48">
<DropdownMenuItem
onClick={handleBuildProject}
disabled={isBuildLoading}
className="gap-2"
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
{isBuildLoading ? 'Building...' : 'Build'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
};
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
{isPreviewable && (
<TabsContent value="preview" className="h-full mt-0">
<div className="h-full w-full flex flex-col relative">
{/* Always show browser address bar */}
<div className="h-12 flex items-center w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined}
onBack={hasBuiltProject ? goBackIframe : undefined}
onForward={hasBuiltProject ? goForwardIframe : undefined}
canGoBack={hasBuiltProject && historyIndex > 0}
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
extraContent={(
<div className="flex items-center">
{(!isMobile && onToggleView && isPreviewable) && (
<Button
variant="ghost"
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
>
<Code className="h-4 w-4" />
</Button>
)}
<ConsoleDropdown />
<Menu />
</div>
<div
ref={previewContainerRef}
className={cn(
"h-full w-full flex flex-col relative",
isFullscreen && "fixed inset-0 z-[100] bg-background"
)}
>
{/* Top navigation bar */}
<div className="h-12 flex items-center gap-2 p-2 border-b bg-background w-full">
{/* Left side - fullscreen toggle */}
<Button
variant="ghost"
size="sm"
onClick={toggleFullscreen}
className="h-8 w-8 p-0"
title={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
>
{isFullscreen ? (
<Shrink className="h-4 w-4" />
) : (
<Expand className="h-4 w-4" />
)}
/>
</Button>
{/* Center - address bar with device toggle */}
<div className="flex-1 px-6">
<div className="relative max-w-64 mx-auto">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined}
navigationHistory={navigationHistory}
deviceMode={deviceMode}
onDeviceModeChange={setDeviceMode}
/>
</div>
</div>
{/* Right side - actions */}
<div className="flex items-center gap-1">
{/* Build button */}
<Button
variant="ghost"
size="sm"
onClick={() => buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
})}
disabled={isBuildLoading}
className="h-8 gap-2"
title="Build project"
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Hammer className="h-4 w-4" />
)}
<span className="hidden lg:inline">Build</span>
</Button>
{(!isMobile && onToggleView && isPreviewable) && (
<Button
variant="ghost"
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
>
<Code className="h-4 w-4" />
<span className="hidden lg:inline">Code</span>
</Button>
)}
<ConsoleDropdown />
</div>
</div>
{/* Content area */}
<div className="flex-1">
<div className="flex-1 flex items-center justify-center bg-muted/30">
{hasBuiltProject ? (
<iframe
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
/>
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
>
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
/>
</div>
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="h-full w-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground mb-4">
<p className="text-muted-foreground">
{t('buildProjectToSeePreview')}
</p>
<Button
onClick={handleBuildProject}
disabled={isBuildLoading}
variant="outline"
className="gap-2"
>
{isBuildLoading ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Building...
</>
) : (
<>
<Play className="h-5 w-5" />
Build Project
</>
)}
</Button>
</div>
</div>
)}
@@ -763,8 +731,24 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<TabsContent value="code" className="h-full mt-0">
{isMobile ? (
<div className="h-full flex flex-col min-h-0">
{/* Mobile Code view header */}
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background flex-shrink-0">
<BranchSwitcher projectId={projectId} />
<div className="flex-1" />
<Button
variant="ghost"
size="sm"
onClick={() => setMobileCodeView(mobileCodeView === 'terminal' ? 'explorer' : 'terminal')}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
<span className="hidden sm:inline">Terminal</span>
</Button>
<GitStatusIndicator projectId={projectId} />
</div>
{mobileCodeView === 'explorer' ? (
<div className="flex-1 relative min-h-0">
<div className="flex-1 min-h-0">
<ScrollArea className="h-full">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
@@ -775,35 +759,11 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
/>
</div>
</ScrollArea>
{/* Floating Terminal Button */}
<Button
variant="outline"
size="sm"
onClick={() => setMobileCodeView('terminal')}
className="fixed right-4 bottom-14 mb-safe z-20 size-12 p-0 rounded-full shadow-lg bg-background border-2"
>
<Terminal className="h-6 w-6" />
</Button>
</div>
) : mobileCodeView === 'terminal' ? (
<>
<div className="h-12 px-3 flex items-center gap-2 bg-black text-purple-400 flex-shrink-0">
<Button
variant="ghost"
size="sm"
onClick={() => setMobileCodeView('explorer')}
className="p-1 hover:bg-transparent hover:text-white"
>
<ArrowLeft className="h-4 w-4" />
</Button>
<h3 className="font-semibold">
Terminal
</h3>
</div>
<div className="flex-1 min-h-0">
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
</div>
</>
<div className="flex-1 min-h-0">
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
</div>
) : (
<>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
@@ -855,7 +815,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<div className="h-full flex flex-col">
{/* Code view header with back button */}
{!isMobile && onToggleView && isPreviewable && (
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background gap-3">
<Button
variant="ghost"
size="sm"
@@ -866,6 +826,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{t('backToPreview')}
</Button>
<div className="flex-1" />
<BranchSwitcher projectId={projectId} />
<Button
variant="ghost"
size="sm"
@@ -873,13 +834,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
<span className="hidden lg:inline">Terminal</span>
</Button>
<GitStatusIndicator projectId={projectId} />
</div>
)}
{/* Code view header without back button for non-previewable projects */}
{!isMobile && !isPreviewable && (
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
<div className="flex-1" />
<BranchSwitcher projectId={projectId} />
<Button
variant="ghost"
size="sm"
@@ -887,6 +851,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
<span className="hidden lg:inline">Terminal</span>
</Button>
<GitStatusIndicator projectId={projectId} />
</div>
@@ -938,16 +903,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
)}
</TabsContent>
</Tabs>
{/* Deploy Dialog */}
{projectName && (
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
)}
</div>
);
}
+1 -1
View File
@@ -61,7 +61,7 @@ export function StarButton({
>
<Star
className={cn(
"h-4 w-4",
"size-5",
isFavorite ? "text-yellow-500 fill-current" : "text-muted-foreground hover:text-yellow-500"
)}
/>
+18 -50
View File
@@ -8,7 +8,7 @@ import { useFS } from '@/hooks/useFS';
import { useGit } from '@/hooks/useGit';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
import { stripAnsiCodes } from '@/lib/ansiToHtml';
interface TerminalProps {
cwd: string;
@@ -104,50 +104,22 @@ export function Terminal({ cwd, className }: TerminalProps) {
return;
}
// Check if running in Electron - use real shell
if (window.electron?.shell) {
// Use the provided cwd (Electron will expand ~ if present)
const result = await window.electron.shell.exec(command, cwd);
// Use virtual shell
if (!shellToolRef.current) return;
// Format output
let output = '';
if (result.stdout) {
output += result.stdout;
}
if (result.stderr) {
if (output) output += '\n';
output += result.stderr;
}
// Add exit code info for non-zero exits
if (result.exitCode !== 0) {
if (output) output += '\n';
output += `Exit code: ${result.exitCode}`;
}
if (output) {
addLine('output', output);
}
// Handle special help command
if (command.trim() === 'help') {
const availableCommands = shellToolRef.current.getAvailableCommands();
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
`${cmd.name.padEnd(12)} - ${cmd.description}`
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
addLine('output', helpText);
} else {
// Use virtual shell (browser mode)
if (!shellToolRef.current) return;
const result = await shellToolRef.current.execute({ command });
// Handle special help command
if (command.trim() === 'help') {
const availableCommands = shellToolRef.current.getAvailableCommands();
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
`${cmd.name.padEnd(12)} - ${cmd.description}`
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
addLine('output', helpText);
} else {
const result = await shellToolRef.current.execute({ command });
// Add output
if (result && result.trim()) {
addLine('output', result);
}
// Add output
if (result.content && result.content.trim()) {
addLine('output', result.content);
}
}
} catch (error) {
@@ -155,7 +127,7 @@ export function Terminal({ cwd, className }: TerminalProps) {
} finally {
setIsExecuting(false);
}
}, [addLine, commandHistory, cwd]);
}, [addLine, commandHistory]);
const handleSubmit = useCallback((e: React.FormEvent) => {
e.preventDefault();
@@ -193,9 +165,7 @@ export function Terminal({ cwd, className }: TerminalProps) {
const copyToClipboard = useCallback(async (content: string) => {
try {
// Strip ANSI codes when copying to clipboard
const cleanContent = content.replace(/\u001b\[(?:\d+;)*\d+m/g, '');
await navigator.clipboard.writeText(cleanContent);
await navigator.clipboard.writeText(content);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
}
@@ -230,16 +200,14 @@ export function Terminal({ cwd, className }: TerminalProps) {
${' '}
</span>
) : null}
{containsAnsiCodes(line.content)
? <span dangerouslySetInnerHTML={{ __html: ansiToHtml(line.content) }} />
: line.content}
{stripAnsiCodes(line.content)}
</pre>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
copyToClipboard(line.content);
copyToClipboard(stripAnsiCodes(line.content));
}}
className="absolute right-0 top-0 h-4 w-4 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-gray-500 hover:text-white hover:bg-gray-700"
>
+496
View File
@@ -0,0 +1,496 @@
import { useState } from 'react';
import {
Wrench,
Eye,
FileText,
Edit,
Package,
PackageMinus,
GitCommit,
BookOpen,
Download,
Hash,
Tag,
Network,
List,
Plus,
Terminal,
Globe,
Loader2,
Logs,
Send,
Puzzle,
Image,
AlertCircle,
LucideIcon,
Settings,
TriangleAlert,
X,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { VFSImage } from '@/components/VFSImage';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ImageModelDialog } from '@/components/ImageModelDialog';
import { ImageLightbox } from '@/components/ImageLightbox';
interface ToolInfo {
icon: LucideIcon;
title: string;
callingTitle?: string; // Title to show while calling (e.g., "Editing {path}")
errorTitle?: string; // Title to show when error occurs (e.g., "Failed to edit {path}")
}
interface ToolCallDisplayProps {
toolName: string;
toolArgs: Record<string, unknown>;
state: 'calling' | 'waiting' | 'completed';
result?: string; // The tool result content (only for completed state)
}
// Component to show image generation errors inline
function ImageGenerationError() {
const [showImageModelDialog, setShowImageModelDialog] = useState(false);
return (
<>
<div className="mt-1 max-w-xs">
<Alert variant="default" className="border-primary/20 bg-primary/5">
<AlertCircle className="h-4 w-4 text-primary" />
<AlertDescription className="text-sm">
<span className="text-foreground">
Image generation failed. This could be due to an issue with the selected image model or the AI provider.{' '}
</span>
<button
className="text-primary underline hover:no-underline font-medium"
onClick={() => setShowImageModelDialog(true)}
>
Change image model
</button>
</AlertDescription>
</Alert>
</div>
<ImageModelDialog
open={showImageModelDialog}
onOpenChange={setShowImageModelDialog}
/>
</>
);
}
/**
* Get tool information including icon, title, and calling title
*/
function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo {
switch (toolName) {
case 'shell':
return {
icon: Terminal,
title: args.command ? String(args.command) : 'Shell Command',
callingTitle: args.command ? String(args.command) : 'Running Shell Command',
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell Command Failed',
};
case 'text_editor_view': {
const path = args.path ? String(args.path) : 'File';
const hasLineRange = args.start_line || args.end_line;
const lineInfo = hasLineRange
? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})`
: '';
return {
icon: Eye,
title: `Viewed ${path}${lineInfo}`,
callingTitle: `Viewing ${path}${lineInfo}`,
errorTitle: `Failed to view ${path}${lineInfo}`,
};
}
case 'text_editor_write':
return {
icon: FileText,
title: args.path ? `Wrote ${args.path}` : 'Wrote File',
callingTitle: args.path ? `Writing ${args.path}` : 'Writing File',
errorTitle: args.path ? `Failed to write ${args.path}` : 'Failed to Write File',
};
case 'text_editor_str_replace':
return {
icon: Edit,
title: args.path ? `Edited ${args.path}` : 'Edited File',
callingTitle: args.path ? `Editing ${args.path}` : 'Editing File',
errorTitle: args.path ? `Failed to edit ${args.path}` : 'Failed to Edit File',
};
case 'npm_add_package': {
const name = args.name ? String(args.name) : 'Package';
const devSuffix = args.dev ? ' (dev)' : '';
return {
icon: Package,
title: `Installed ${name}${devSuffix}`,
callingTitle: `Installing ${name}${devSuffix}`,
errorTitle: `Failed to install ${name}${devSuffix}`,
};
}
case 'npm_remove_package':
return {
icon: PackageMinus,
title: args.name ? `Removed ${args.name}` : 'Removed Package',
callingTitle: args.name ? `Removing ${args.name}` : 'Removing Package',
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to Remove Package',
};
case 'git_commit':
return {
icon: GitCommit,
title: args.message ? `Committed: ${args.message}` : 'Committed Changes',
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing Changes',
errorTitle: 'Failed to Commit Changes',
};
case 'build_project':
return {
icon: Package,
title: 'Built Project',
callingTitle: 'Building Project',
errorTitle: 'Failed to Build Project',
};
case 'nostr_read_nip':
return {
icon: BookOpen,
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP',
callingTitle: args.nip ? `Reading NIP-${args.nip}` : 'Reading NIP',
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to Read NIP',
};
case 'nostr_fetch_event':
return {
icon: Download,
title: args.identifier ? `Fetched ${String(args.identifier).slice(0, 16)}...` : 'Fetched Event',
callingTitle: args.identifier ? `Fetching ${String(args.identifier).slice(0, 16)}...` : 'Fetching Event',
errorTitle: args.identifier ? `Failed to fetch ${String(args.identifier).slice(0, 16)}...` : 'Failed to Fetch Event',
};
case 'nostr_read_kind':
return {
icon: Hash,
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind',
callingTitle: args.kind !== undefined ? `Reading Kind ${args.kind}` : 'Reading Kind',
errorTitle: args.kind !== undefined ? `Failed to read Kind ${args.kind}` : 'Failed to Read Kind',
};
case 'nostr_read_tag':
return {
icon: Tag,
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag',
callingTitle: args.tag ? `Reading Tag "${args.tag}"` : 'Reading Tag',
errorTitle: args.tag ? `Failed to read Tag "${args.tag}"` : 'Failed to Read Tag',
};
case 'nostr_read_protocol':
return {
icon: Network,
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol',
callingTitle: args.doc ? `Reading Protocol: ${args.doc}` : 'Reading Protocol',
errorTitle: args.doc ? `Failed to read Protocol: ${args.doc}` : 'Failed to Read Protocol',
};
case 'nostr_read_nips_index':
return {
icon: List,
title: 'Read NIPs Index',
callingTitle: 'Reading NIPs Index',
errorTitle: 'Failed to Read NIPs Index',
};
case 'nostr_generate_kind':
return {
icon: Plus,
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind',
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating Kind',
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to Generate Kind',
};
case 'nostr_publish_events': {
const eventCount = Array.isArray(args.events) ? args.events.length : 0;
return {
icon: Send,
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event',
callingTitle: eventCount > 1 ? `Publishing ${eventCount} Nostr events` : 'Publishing Nostr event',
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to Publish Nostr Event',
};
}
case 'deploy_project':
return {
icon: Globe,
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project',
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying Project',
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to Deploy Project',
};
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console',
callingTitle: 'Reading Console',
errorTitle: 'Failed to Read Console',
};
case 'skill':
return {
icon: Puzzle,
title: args.name ? `Skill: ${args.name}` : 'Skill',
callingTitle: args.name ? `Running Skill: ${args.name}` : 'Running Skill',
errorTitle: args.name ? `Skill Failed: ${args.name}` : 'Skill Failed',
};
case 'generate_image':
return {
icon: Image,
title: args.prompt ? String(args.prompt) : 'Generated Image',
callingTitle: args.prompt ? String(args.prompt) : 'Generating Image',
errorTitle: 'Failed to Generate Image',
};
case 'view_available_models':
return {
icon: Eye,
title: 'Viewed Available Models',
callingTitle: 'Viewing Available Models',
errorTitle: 'Failed to View Available Models',
};
case 'configure_image_generation':
return {
icon: Settings,
title: args.model ? `Configured image model: ${args.model}` : 'Configured Image Generation',
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring Image Generation',
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to Configure Image Generation',
};
default: {
const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
return {
icon: Wrench,
title: formattedName,
callingTitle: formattedName,
};
}
}
}
/**
* Parse tool error from result string
* Format: "Error with tool {toolName}: {errorMsg}"
* Returns null if not an error or if format doesn't match exactly
*/
function parseToolError(result: string | undefined, expectedToolName: string): string | null {
if (!result) return null;
// Strict parsing - exact format required
const prefix = `Error with tool ${expectedToolName}: `;
if (!result.startsWith(prefix)) return null;
// Extract error message after the prefix
return result.substring(prefix.length);
}
/**
* Unified component for displaying tool calls in all states
*/
export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallDisplayProps) {
const [isExpanded, setIsExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
const [imageLoadError, setImageLoadError] = useState(false);
const toolInfo = getToolInfo(toolName, toolArgs);
const IconComponent = toolInfo.icon;
// Check if this is an error result
const errorMessage = state === 'completed' ? parseToolError(result, toolName) : null;
const hasError = errorMessage !== null;
// Determine which title to show based on state
let displayTitle: string;
if (hasError && toolInfo.errorTitle) {
displayTitle = toolInfo.errorTitle;
} else if (state === 'completed') {
displayTitle = toolInfo.title;
} else {
displayTitle = toolInfo.callingTitle || toolInfo.title;
}
// Only allow clicking when completed
const isClickable = state === 'completed';
// Render special content for specific tools when expanded
const renderExpandedContent = () => {
if (!result || !isExpanded) return null;
// Show error message if present and expanded
if (hasError) {
return (
<div className="mt-1 p-3 bg-destructive/5 rounded border border-destructive/20 text-xs">
<div className="flex gap-2">
<TriangleAlert className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
<div className="whitespace-pre-wrap break-words text-foreground">
{errorMessage}
</div>
</div>
</div>
);
}
if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') {
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{toolArgs.file_text}
</div>
</div>
);
}
if (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string') {
const oldLines = String(toolArgs.old_str).split('\n');
const newLines = String(toolArgs.new_str).split('\n');
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
<div className="space-y-1">
{/* Old content (removed) */}
<div className="space-y-0">
{oldLines.map((line, index) => (
<div key={`old-${index}`} className="flex">
<span className="text-red-500 select-none mr-2">-</span>
<span className="bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-300 flex-1 whitespace-pre-wrap break-words">
{line}
</span>
</div>
))}
</div>
{/* New content (added) */}
<div className="space-y-0">
{newLines.map((line, index) => (
<div key={`new-${index}`} className="flex">
<span className="text-green-500 select-none mr-2">+</span>
<span className="bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-300 flex-1 whitespace-pre-wrap break-words">
{line}
</span>
</div>
))}
</div>
</div>
</div>
);
}
if (toolName === 'generate_image') {
// For generate_image, when expanded show the full prompt
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div>{typeof toolArgs.prompt === 'string' ? toolArgs.prompt : 'No prompt provided'}</div>
</div>
);
}
// Default rendering for other tools
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{result}
</div>
</div>
);
};
// Special rendering for generate_image - always show image below the tool
const renderImageBelowTool = () => {
if (hasError) return null;
if (toolName !== 'generate_image') return null;
// Show placeholder while generating (calling or waiting states)
if (state === 'calling' || state === 'waiting') {
return (
<div className="mt-1 p-3 bg-muted/30 rounded border max-w-xs">
<div className="relative w-full aspect-square">
<div className="w-full h-full rounded bg-muted/50" />
<div className="absolute inset-0 flex items-center justify-center">
<Loader2 className="h-12 w-12 text-muted-foreground/30 animate-spin" />
</div>
</div>
</div>
);
}
// For completed state, we need the result
if (!result) return null;
// Parse "Generated image: /tmp/filename.png" from result
const match = result.match(/Generated image:\s*(\/tmp\/[^\s\n]+)/);
if (match) {
const imagePath = match[1];
const filename = imagePath.split('/').pop() || imagePath;
// Hide the image section if there was a load error
if (imageLoadError) return null;
return (
<div className="mt-1 p-3 bg-muted/30 rounded border max-w-xs">
<div
className="cursor-pointer hover:opacity-90 transition-opacity"
onClick={() => setExpandedImageUrl(imagePath)}
>
<VFSImage
path={imagePath}
alt={filename}
className="max-w-full h-auto rounded"
onError={() => setImageLoadError(true)}
/>
</div>
</div>
);
} else {
// Image generation failed - show error in place
return <ImageGenerationError />;
}
};
return (
<>
<div className="-mt-2">
<button
onClick={() => isClickable && setIsExpanded(!isExpanded)}
disabled={!isClickable}
className={cn(
"w-full flex items-center gap-2 px-2 py-1 text-xs",
isClickable && "hover:bg-muted/30 rounded transition-colors duration-200",
!isClickable && "cursor-default"
)}
>
{state === 'calling' || state === 'waiting' ? (
<Loader2 className="h-3 w-3 text-muted-foreground flex-shrink-0 animate-spin" />
) : hasError ? (
<X className="h-3 w-3 text-muted-foreground flex-shrink-0" />
) : (
<IconComponent className="h-3 w-3 text-muted-foreground flex-shrink-0" />
)}
<span className="text-muted-foreground font-medium truncate flex-1 text-left">
{displayTitle}
</span>
</button>
{renderExpandedContent()}
{renderImageBelowTool()}
</div>
{/* Image expansion lightbox */}
<ImageLightbox
imageUrl={expandedImageUrl}
onClose={() => setExpandedImageUrl(null)}
/>
</>
);
}
+3 -3
View File
@@ -3,9 +3,9 @@ import { render, screen, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { URLFragmentHandler } from './URLFragmentHandler';
// Mock the AddProviderDialog component
vi.mock('./AddProviderDialog', () => ({
AddProviderDialog: ({ open, provider }: { open: boolean; provider: { id: string; baseURL: string; apiKey?: string; nostr?: boolean; proxy?: boolean } }) => {
// Mock the AddSharedProviderDialog component
vi.mock('./AddSharedProviderDialog', () => ({
AddSharedProviderDialog: ({ open, provider }: { open: boolean; provider: { id: string; baseURL: string; apiKey?: string; nostr?: boolean; proxy?: boolean } }) => {
if (!open) return null;
return (
<div data-testid="add-provider-dialog">
+9 -2
View File
@@ -1,7 +1,8 @@
import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { AddProviderDialog } from '@/components/AddProviderDialog';
import { AddSharedProviderDialog } from '@/components/AddSharedProviderDialog';
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,
};
@@ -71,7 +78,7 @@ export function URLFragmentHandler() {
}
return (
<AddProviderDialog
<AddSharedProviderDialog
open={dialogOpen}
onOpenChange={handleDialogClose}
provider={providerFromURL}
@@ -1,61 +0,0 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { UserMessage } from './UserMessage';
describe('UserMessage Integration', () => {
it('renders text parts with file attachments correctly', () => {
// Simulate the new text parts structure that ChatPane would create
const content = [
{ type: 'text' as const, text: 'Please analyze this file:' },
{ type: 'text' as const, text: 'Added file: /tmp/data.csv' },
{ type: 'text' as const, text: 'Let me know what you find!' }
];
render(<UserMessage content={content} />);
// Check that regular text is displayed
expect(screen.getByText('Please analyze this file:')).toBeInTheDocument();
expect(screen.getByText('Let me know what you find!')).toBeInTheDocument();
// Check that file attachment is rendered as a badge
expect(screen.getByText('data.csv')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/data.csv')).not.toBeInTheDocument();
});
it('handles single text part with file attachment', () => {
const content = [
{ type: 'text' as const, text: 'Added file: /tmp/script.js' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('script.js')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/script.js')).not.toBeInTheDocument();
});
it('handles multiple file attachments in separate parts', () => {
const content = [
{ type: 'text' as const, text: 'Here are my files:' },
{ type: 'text' as const, text: 'Added file: /tmp/config.json' },
{ type: 'text' as const, text: 'Added file: /tmp/styles.css' },
{ type: 'text' as const, text: 'Added file: /tmp/main.js' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Here are my files:')).toBeInTheDocument();
expect(screen.getByText('config.json')).toBeInTheDocument();
expect(screen.getByText('styles.css')).toBeInTheDocument();
expect(screen.getByText('main.js')).toBeInTheDocument();
});
it('handles empty content gracefully', () => {
const content: Array<{ type: 'text'; text: string }> = [];
const { container } = render(<UserMessage content={content} />);
expect(container.firstChild).toBeNull();
});
});
-113
View File
@@ -1,113 +0,0 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { UserMessage } from './UserMessage';
describe('UserMessage', () => {
it('renders regular text without file attachments', () => {
const content = 'This is a regular message without any file attachments.';
render(<UserMessage content={content} />);
expect(screen.getByText(content)).toBeInTheDocument();
});
it('handles backward compatibility with string content containing file attachments', () => {
const content = 'Here is my file: Added file: /tmp/test.txt';
render(<UserMessage content={content} />);
// 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', () => {
const content = [
{ type: 'text' as const, text: 'Here is my file:' },
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
];
render(<UserMessage content={content} />);
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 multiple file attachments with text parts', () => {
const content = [
{ type: 'text' as const, text: 'Files uploaded:' },
{ type: 'text' as const, text: 'Added file: /tmp/document.pdf' },
{ type: 'text' as const, text: 'Added file: /tmp/image.jpg' },
{ type: 'text' as const, text: 'All done!' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Files uploaded:')).toBeInTheDocument();
expect(screen.getByText('document.pdf')).toBeInTheDocument();
expect(screen.getByText('image.jpg')).toBeInTheDocument();
expect(screen.getByText('All done!')).toBeInTheDocument();
});
it('renders text files with FileText icon', () => {
const content = [{ type: 'text' as const, text: 'Added file: /tmp/script.js' }];
render(<UserMessage content={content} />);
expect(screen.getByText('script.js')).toBeInTheDocument();
// FileText icon should be rendered (we can't easily test the icon itself, but we can test the component renders)
});
it('handles files without extensions', () => {
const content = [{ type: 'text' as const, text: 'Added file: /tmp/README' }];
render(<UserMessage content={content} />);
expect(screen.getByText('README')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/README')).not.toBeInTheDocument();
});
it('handles complex filenames with underscores and numbers', () => {
const content = [{ type: 'text' as const, text: 'Added file: /tmp/my_file_1.txt' }];
render(<UserMessage content={content} />);
expect(screen.getByText('my_file_1.txt')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/my_file_1.txt')).not.toBeInTheDocument();
});
it('preserves whitespace in text content', () => {
const content = [
{ type: 'text' as const, text: 'Line 1\n\nLine 3 with spaces \n\nFinal line' },
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
];
const { container } = render(<UserMessage content={content} />);
// Check that the component renders and contains the expected text content
expect(container.textContent).toContain('Line 1');
expect(container.textContent).toContain('Line 3 with spaces');
expect(container.textContent).toContain('Final line');
expect(screen.getByText('test.txt')).toBeInTheDocument();
});
it('handles mixed content with file attachments in the middle', () => {
const content = [
{ type: 'text' as const, text: 'Starting text' },
{ type: 'text' as const, text: 'Added file: /tmp/middle.txt' },
{ type: 'text' as const, text: 'ending text' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Starting text')).toBeInTheDocument();
expect(screen.getByText('middle.txt')).toBeInTheDocument();
expect(screen.getByText('ending text')).toBeInTheDocument();
});
});
+32 -77
View File
@@ -3,7 +3,7 @@ import { Badge } from '@/components/ui/badge';
import type OpenAI from 'openai';
interface UserMessageProps {
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>;
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPart>;
}
/**
@@ -13,71 +13,12 @@ interface UserMessageProps {
*/
export function UserMessage({ content }: UserMessageProps) {
// Convert content to array format for uniform processing
const contentParts = typeof content === 'string'
const parts = typeof content === 'string'
? [{ type: 'text' as const, text: content }]
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
// Regular expression to match "Added file: /tmp/<filename>" patterns
// 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();
// 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 (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) {
// No file patterns found, treat as regular text
processedParts.push({ type: 'text', content: text });
}
});
: content.filter(part => part.type === 'text');
// If no content, return empty
if (processedParts.length === 0) {
if (parts.length === 0) {
return null;
}
@@ -87,28 +28,42 @@ export function UserMessage({ content }: UserMessageProps) {
return (
<div className="space-y-2">
{processedParts.map((part, index) => {
{parts.map((part, index) => {
if (part.type === 'text') {
// Only render text if it has content
if (!part.content.trim()) return null;
if (!part.text.trim()) return null;
// Detect "Added file: <filename>" pattern
const fileAddedMatch = /^Added file: (\/[^\s\n]+$)/g.exec(part.text);
console.log('fileAddedMatch', part, fileAddedMatch);
if (fileAddedMatch && fileAddedMatch[1]) {
const path = fileAddedMatch[1];
const filename = getFileName(path);
return (
<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>
);
}
// Regular text rendering
return (
<div key={index} className="whitespace-pre-wrap">
{part.content}
{part.text}
</div>
);
} else {
// Render file attachment badge (no "Added file:" text)
const filename = getFileName(part.filepath!);
// Unsupported content type
return (
<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 key={index} className="text-sm text-red-500">
[Unsupported content type]
</div>
);
}
+101
View File
@@ -0,0 +1,101 @@
import { useEffect, useState } from 'react';
import { useFS } from '@/hooks/useFS';
import { Skeleton } from '@/components/ui/skeleton';
import { AlertCircle } from 'lucide-react';
interface VFSImageProps {
path: string;
alt: string;
className?: string;
onClick?: () => void;
onError?: (error: string) => void;
}
export function VFSImage({ path, alt, className, onClick, onError }: VFSImageProps) {
const { fs } = useFS();
const [dataUri, setDataUri] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
let isMounted = true;
async function loadImage() {
try {
setIsLoading(true);
setError(null);
// Read the file from VFS
const imageData = await fs.readFile(path);
if (!isMounted) return;
// Determine MIME type from file extension
const extension = path.split('.').pop()?.toLowerCase() || '';
const mimeTypes: Record<string, string> = {
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'webp': 'image/webp',
'svg': 'image/svg+xml',
'bmp': 'image/bmp',
};
const mimeType = mimeTypes[extension] || 'image/png';
// Convert bytes to base64
const base64 = btoa(
Array.from(imageData)
.map(byte => String.fromCharCode(byte))
.join('')
);
// Create data URI
const uri = `data:${mimeType};base64,${base64}`;
if (isMounted) {
setDataUri(uri);
setIsLoading(false);
}
} catch (err) {
if (isMounted) {
const errorMessage = err instanceof Error ? err.message : 'Failed to load image';
setError(errorMessage);
setIsLoading(false);
onError?.(errorMessage);
}
}
}
loadImage();
return () => {
isMounted = false;
};
}, [fs, onError, path]);
if (isLoading) {
return <Skeleton className={className || 'w-full h-64'} />;
}
if (error || !dataUri) {
return (
<div className={className || 'w-full h-64 flex items-center justify-center bg-muted rounded'}>
<div className="text-center text-muted-foreground space-y-2">
<AlertCircle className="h-8 w-8 mx-auto" />
<p className="text-xs">{error || 'Failed to load image'}</p>
<p className="text-xs font-mono">{path}</p>
</div>
</div>
);
}
return (
<img
src={dataUri}
alt={alt}
className={className}
onClick={onClick}
/>
);
}
Loaded 100 of 299 files, more files were not shown because too many files have changed in this diff. Show more